Files
dndbeyond_src/ddb_main/node_modules/@dndbeyond/dice/dist/dice.js
T
2025-05-28 15:36:51 -07:00

2 lines
4.7 MiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*! For license information please see dice.js.LICENSE.txt */
var e,t,i,n,s={8401:e=>{e.exports=function e(t,i,n){function s(o,a){if(!i[o]){if(!t[o]){if(r)return r(o,!0);throw new Error("Cannot find module '"+o+"'")}var l=i[o]={exports:{}};t[o][0].call(l.exports,(function(e){return s(t[o][1][e]||e)}),l,l.exports,e,t,i,n)}return i[o].exports}for(var r=void 0,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(e,t,i){t.exports={name:"cannon",version:"0.6.2",description:"A lightweight 3D physics engine written in JavaScript.",homepage:"https://github.com/schteppe/cannon.js",author:"Stefan Hedman <schteppe@gmail.com> (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(e,t,i){t.exports={version:e("../package.json").version,AABB:e("./collision/AABB"),ArrayCollisionMatrix:e("./collision/ArrayCollisionMatrix"),Body:e("./objects/Body"),Box:e("./shapes/Box"),Broadphase:e("./collision/Broadphase"),Constraint:e("./constraints/Constraint"),ContactEquation:e("./equations/ContactEquation"),Narrowphase:e("./world/Narrowphase"),ConeTwistConstraint:e("./constraints/ConeTwistConstraint"),ContactMaterial:e("./material/ContactMaterial"),ConvexPolyhedron:e("./shapes/ConvexPolyhedron"),Cylinder:e("./shapes/Cylinder"),DistanceConstraint:e("./constraints/DistanceConstraint"),Equation:e("./equations/Equation"),EventTarget:e("./utils/EventTarget"),FrictionEquation:e("./equations/FrictionEquation"),GSSolver:e("./solver/GSSolver"),GridBroadphase:e("./collision/GridBroadphase"),Heightfield:e("./shapes/Heightfield"),HingeConstraint:e("./constraints/HingeConstraint"),LockConstraint:e("./constraints/LockConstraint"),Mat3:e("./math/Mat3"),Material:e("./material/Material"),NaiveBroadphase:e("./collision/NaiveBroadphase"),ObjectCollisionMatrix:e("./collision/ObjectCollisionMatrix"),Pool:e("./utils/Pool"),Particle:e("./shapes/Particle"),Plane:e("./shapes/Plane"),PointToPointConstraint:e("./constraints/PointToPointConstraint"),Quaternion:e("./math/Quaternion"),Ray:e("./collision/Ray"),RaycastVehicle:e("./objects/RaycastVehicle"),RaycastResult:e("./collision/RaycastResult"),RigidVehicle:e("./objects/RigidVehicle"),RotationalEquation:e("./equations/RotationalEquation"),RotationalMotorEquation:e("./equations/RotationalMotorEquation"),SAPBroadphase:e("./collision/SAPBroadphase"),SPHSystem:e("./objects/SPHSystem"),Shape:e("./shapes/Shape"),Solver:e("./solver/Solver"),Sphere:e("./shapes/Sphere"),SplitSolver:e("./solver/SplitSolver"),Spring:e("./objects/Spring"),Trimesh:e("./shapes/Trimesh"),Vec3:e("./math/Vec3"),Vec3Pool:e("./utils/Vec3Pool"),World:e("./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(e,t,i){var n=e("../math/Vec3");function s(e){e=e||{},this.lowerBound=new n,e.lowerBound&&this.lowerBound.copy(e.lowerBound),this.upperBound=new n,e.upperBound&&this.upperBound.copy(e.upperBound)}e("../utils/Utils"),t.exports=s;var r=new n;s.prototype.setFromPoints=function(e,t,i,n){var s=this.lowerBound,o=this.upperBound,a=i;s.copy(e[0]),a&&a.vmult(s,s),o.copy(s);for(var l=1;l<e.length;l++){var h=e[l];a&&(a.vmult(h,r),h=r),h.x>o.x&&(o.x=h.x),h.x<s.x&&(s.x=h.x),h.y>o.y&&(o.y=h.y),h.y<s.y&&(s.y=h.y),h.z>o.z&&(o.z=h.z),h.z<s.z&&(s.z=h.z)}return t&&(t.vadd(s,s),t.vadd(o,o)),n&&(s.x-=n,s.y-=n,s.z-=n,o.x+=n,o.y+=n,o.z+=n),this},s.prototype.copy=function(e){return this.lowerBound.copy(e.lowerBound),this.upperBound.copy(e.upperBound),this},s.prototype.clone=function(){return(new s).copy(this)},s.prototype.extend=function(e){var t=e.lowerBound.x;this.lowerBound.x>t&&(this.lowerBound.x=t);var i=e.upperBound.x;this.upperBound.x<i&&(this.upperBound.x=i),t=e.lowerBound.y,this.lowerBound.y>t&&(this.lowerBound.y=t),i=e.upperBound.y,this.upperBound.y<i&&(this.upperBound.y=i),t=e.lowerBound.z,this.lowerBound.z>t&&(this.lowerBound.z=t),i=e.upperBound.z,this.upperBound.z<i&&(this.upperBound.z=i)},s.prototype.overlaps=function(e){var t=this.lowerBound,i=this.upperBound,n=e.lowerBound,s=e.upperBound;return(n.x<=i.x&&i.x<=s.x||t.x<=s.x&&s.x<=i.x)&&(n.y<=i.y&&i.y<=s.y||t.y<=s.y&&s.y<=i.y)&&(n.z<=i.z&&i.z<=s.z||t.z<=s.z&&s.z<=i.z)},s.prototype.contains=function(e){var t=this.lowerBound,i=this.upperBound,n=e.lowerBound,s=e.upperBound;return t.x<=n.x&&i.x>=s.x&&t.y<=n.y&&i.y>=s.y&&t.z<=n.z&&i.z>=s.z},s.prototype.getCorners=function(e,t,i,n,s,r,o,a){var l=this.lowerBound,h=this.upperBound;e.copy(l),t.set(h.x,l.y,l.z),i.set(h.x,h.y,l.z),n.set(l.x,h.y,h.z),s.set(h.x,l.y,l.z),r.set(l.x,h.y,l.z),o.set(l.x,l.y,h.z),a.copy(h)};var o=[new n,new n,new n,new n,new n,new n,new n,new n];s.prototype.toLocalFrame=function(e,t){var i=o,n=i[0],s=i[1],r=i[2],a=i[3],l=i[4],h=i[5],c=i[6],u=i[7];this.getCorners(n,s,r,a,l,h,c,u);for(var d=0;8!==d;d++){var p=i[d];e.pointToLocal(p,p)}return t.setFromPoints(i)},s.prototype.toWorldFrame=function(e,t){var i=o,n=i[0],s=i[1],r=i[2],a=i[3],l=i[4],h=i[5],c=i[6],u=i[7];this.getCorners(n,s,r,a,l,h,c,u);for(var d=0;8!==d;d++){var p=i[d];e.pointToWorld(p,p)}return t.setFromPoints(i)}},{"../math/Vec3":30,"../utils/Utils":53}],4:[function(e,t,i){function n(){this.matrix=[]}t.exports=n,n.prototype.get=function(e,t){if(e=e.index,(t=t.index)>e){var i=t;t=e,e=i}return this.matrix[(e*(e+1)>>1)+t-1]},n.prototype.set=function(e,t,i){if(e=e.index,(t=t.index)>e){var n=t;t=e,e=n}this.matrix[(e*(e+1)>>1)+t-1]=i?1:0},n.prototype.reset=function(){for(var e=0,t=this.matrix.length;e!==t;e++)this.matrix[e]=0},n.prototype.setNumObjects=function(e){this.matrix.length=e*(e-1)>>1}},{}],5:[function(e,t,i){var n=e("../objects/Body"),s=e("../math/Vec3"),r=e("../math/Quaternion");function o(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}e("../shapes/Shape"),e("../shapes/Plane"),t.exports=o,o.prototype.collisionPairs=function(e,t,i){throw new Error("collisionPairs not implemented for this BroadPhase class!")};var a=n.STATIC|n.KINEMATIC;o.prototype.needBroadphaseCollision=function(e,t){return 0!=(e.collisionFilterGroup&t.collisionFilterMask)&&0!=(t.collisionFilterGroup&e.collisionFilterMask)&&(0==(e.type&a)&&e.sleepState!==n.SLEEPING||0==(t.type&a)&&t.sleepState!==n.SLEEPING)},o.prototype.intersectionTest=function(e,t,i,n){this.useBoundingBoxes?this.doBoundingBoxBroadphase(e,t,i,n):this.doBoundingSphereBroadphase(e,t,i,n)};var l=new s;new s,new r,new s,o.prototype.doBoundingSphereBroadphase=function(e,t,i,n){var s=l;t.position.vsub(e.position,s);var r=Math.pow(e.boundingRadius+t.boundingRadius,2);s.norm2()<r&&(i.push(e),n.push(t))},o.prototype.doBoundingBoxBroadphase=function(e,t,i,n){e.aabbNeedsUpdate&&e.computeAABB(),t.aabbNeedsUpdate&&t.computeAABB(),e.aabb.overlaps(t.aabb)&&(i.push(e),n.push(t))};var h={keys:[]},c=[],u=[];o.prototype.makePairsUnique=function(e,t){for(var i=h,n=c,s=u,r=e.length,o=0;o!==r;o++)n[o]=e[o],s[o]=t[o];for(e.length=0,t.length=0,o=0;o!==r;o++){var a=n[o].id,l=s[o].id;i[d=a<l?a+","+l:l+","+a]=o,i.keys.push(d)}for(o=0;o!==i.keys.length;o++){var d=i.keys.pop(),p=i[d];e.push(n[p]),t.push(s[p]),delete i[d]}},o.prototype.setWorld=function(e){};var d=new s;o.boundingSphereCheck=function(e,t){var i=d;return e.position.vsub(t.position,i),Math.pow(e.shape.boundingSphereRadius+t.shape.boundingSphereRadius,2)>i.norm2()},o.prototype.aabbQuery=function(e,t,i){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(e,t,i){t.exports=o;var n=e("./Broadphase"),s=e("../math/Vec3"),r=e("../shapes/Shape");function o(e,t,i,r,o){n.apply(this),this.nx=i||10,this.ny=r||10,this.nz=o||10,this.aabbMin=e||new s(100,100,100),this.aabbMax=t||new s(-100,-100,-100);var a=this.nx*this.ny*this.nz;if(a<=0)throw"GridBroadphase: Each dimension's n must be >0";this.bins=[],this.binLengths=[],this.bins.length=a,this.binLengths.length=a;for(var l=0;l<a;l++)this.bins[l]=[],this.binLengths[l]=0}o.prototype=new n,o.prototype.constructor=o;var a=new s;new s,o.prototype.collisionPairs=function(e,t,i){for(var n=e.numObjects(),s=e.bodies,o=this.aabbMax,l=this.aabbMin,h=this.nx,c=this.ny,u=this.nz,d=c*u,p=u,f=o.x,_=o.y,m=o.z,g=l.x,v=l.y,y=l.z,x=h/(f-g),b=c/(_-v),T=u/(m-y),S=(f-g)/h,E=(_-v)/c,C=(m-y)/u,A=.5*Math.sqrt(S*S+E*E+C*C),P=r.types,R=P.SPHERE,M=P.PLANE,I=(P.BOX,P.COMPOUND,P.CONVEXPOLYHEDRON,this.bins),D=this.binLengths,O=this.bins.length,w=0;w!==O;w++)D[w]=0;var N=Math.ceil;function F(e,t,i,n,s,r,o){var a=(e-g)*x|0,l=(t-v)*b|0,f=(i-y)*T|0,_=N((n-g)*x),m=N((s-v)*b),S=N((r-y)*T);a<0?a=0:a>=h&&(a=h-1),l<0?l=0:l>=c&&(l=c-1),f<0?f=0:f>=u&&(f=u-1),_<0?_=0:_>=h&&(_=h-1),m<0?m=0:m>=c&&(m=c-1),S<0?S=0:S>=u&&(S=u-1),l*=p,f*=1,_*=d,m*=p,S*=1;for(var E=a*=d;E<=_;E+=d)for(var C=l;C<=m;C+=p)for(var A=f;A<=S;A+=1){var P=E+C+A;I[P][D[P]++]=o}}for(l=Math.min,o=Math.max,w=0;w!==n;w++){var L=(te=s[w]).shape;switch(L.type){case R:var B=te.position.x,U=te.position.y,V=te.position.z,k=L.radius;F(B-k,U-k,V-k,B+k,U+k,V+k,te);break;case M:L.worldNormalNeedsUpdate&&L.computeWorldNormal(te.quaternion);var G=L.worldNormal,z=g+.5*S-te.position.x,W=v+.5*E-te.position.y,H=y+.5*C-te.position.z,X=a;X.set(z,W,H);for(var j=0,Y=0;j!==h;j++,Y+=d,X.y=W,X.x+=S)for(var q=0,K=0;q!==c;q++,K+=p,X.z=H,X.y+=E)for(var $=0,Q=0;$!==u;$++,Q+=1,X.z+=C)if(X.dot(G)<A){var Z=Y+K+Q;I[Z][D[Z]++]=te}break;default:te.aabbNeedsUpdate&&te.computeAABB(),F(te.aabb.lowerBound.x,te.aabb.lowerBound.y,te.aabb.lowerBound.z,te.aabb.upperBound.x,te.aabb.upperBound.y,te.aabb.upperBound.z,te)}}for(w=0;w!==O;w++){var J=D[w];if(J>1){var ee=I[w];for(j=0;j!==J;j++){var te=ee[j];for(q=0;q!==j;q++){var ie=ee[q];this.needBroadphaseCollision(te,ie)&&this.intersectionTest(te,ie,t,i)}}}}this.makePairsUnique(t,i)}},{"../math/Vec3":30,"../shapes/Shape":43,"./Broadphase":5}],7:[function(e,t,i){t.exports=r;var n=e("./Broadphase"),s=e("./AABB");function r(){n.apply(this)}r.prototype=new n,r.prototype.constructor=r,r.prototype.collisionPairs=function(e,t,i){var n,s,r,o,a=e.bodies,l=a.length;for(n=0;n!==l;n++)for(s=0;s!==n;s++)r=a[n],o=a[s],this.needBroadphaseCollision(r,o)&&this.intersectionTest(r,o,t,i)},new s,r.prototype.aabbQuery=function(e,t,i){i=i||[];for(var n=0;n<e.bodies.length;n++){var s=e.bodies[n];s.aabbNeedsUpdate&&s.computeAABB(),s.aabb.overlaps(t)&&i.push(s)}return i}},{"./AABB":3,"./Broadphase":5}],8:[function(e,t,i){function n(){this.matrix={}}t.exports=n,n.prototype.get=function(e,t){if(e=e.id,(t=t.id)>e){var i=t;t=e,e=i}return e+"-"+t in this.matrix},n.prototype.set=function(e,t,i){if(e=e.id,(t=t.id)>e){var n=t;t=e,e=n}i?this.matrix[e+"-"+t]=!0:delete this.matrix[e+"-"+t]},n.prototype.reset=function(){this.matrix={}},n.prototype.setNumObjects=function(e){}},{}],9:[function(e,t,i){t.exports=h;var n=e("../math/Vec3"),s=e("../math/Quaternion"),r=e("../math/Transform"),o=(e("../shapes/ConvexPolyhedron"),e("../shapes/Box"),e("../collision/RaycastResult")),a=e("../shapes/Shape"),l=e("../collision/AABB");function h(e,t){this.from=e?e.clone():new n,this.to=t?t.clone():new n,this._direction=new n,this.precision=1e-4,this.checkCollisionResponse=!0,this.skipBackfaces=!1,this.collisionFilterMask=-1,this.collisionFilterGroup=-1,this.mode=h.ANY,this.result=new o,this.hasHit=!1,this.callback=function(e){}}h.prototype.constructor=h,h.CLOSEST=1,h.ANY=2,h.ALL=4;var c=new l,u=[];h.prototype.intersectWorld=function(e,t){return this.mode=t.mode||h.ANY,this.result=t.result||new o,this.skipBackfaces=!!t.skipBackfaces,this.collisionFilterMask=void 0!==t.collisionFilterMask?t.collisionFilterMask:-1,this.collisionFilterGroup=void 0!==t.collisionFilterGroup?t.collisionFilterGroup:-1,t.from&&this.from.copy(t.from),t.to&&this.to.copy(t.to),this.callback=t.callback||function(){},this.hasHit=!1,this.result.reset(),this._updateDirection(),this.getAABB(c),u.length=0,e.broadphase.aabbQuery(e,c,u),this.intersectBodies(u),this.hasHit};var d=new n,p=new n;function f(e,t,i,n){n.vsub(t,N),i.vsub(t,d),e.vsub(t,p);var s,r,o=N.dot(N),a=N.dot(d),l=N.dot(p),h=d.dot(d),c=d.dot(p);return(s=h*l-a*c)>=0&&(r=o*c-a*l)>=0&&s+r<o*h-a*a}h.pointInTriangle=f;var _=new n,m=new s;h.prototype.intersectBody=function(e,t){t&&(this.result=t,this._updateDirection());var i=this.checkCollisionResponse;if((!i||e.collisionResponse)&&0!=(this.collisionFilterGroup&e.collisionFilterMask)&&0!=(e.collisionFilterGroup&this.collisionFilterMask))for(var n=_,s=m,r=0,o=e.shapes.length;r<o;r++){var a=e.shapes[r];if((!i||a.collisionResponse)&&(e.quaternion.mult(e.shapeOrientations[r],s),e.quaternion.vmult(e.shapeOffsets[r],n),n.vadd(e.position,n),this.intersectShape(a,s,n,e),this.result._shouldStop))break}},h.prototype.intersectBodies=function(e,t){t&&(this.result=t,this._updateDirection());for(var i=0,n=e.length;!this.result._shouldStop&&i<n;i++)this.intersectBody(e[i])},h.prototype._updateDirection=function(){this.to.vsub(this.from,this._direction),this._direction.normalize()},h.prototype.intersectShape=function(e,t,i,n){if(!(function(e,t,i){i.vsub(e,N);var n=N.dot(t);return t.mult(n,F),F.vadd(e,F),i.distanceTo(F)}(this.from,this._direction,i)>e.boundingSphereRadius)){var s=this[e.type];s&&s.call(this,e,t,i,n)}},new n,new n;var g=new n,v=new n,y=new n,x=new n;new n,new o,h.prototype.intersectBox=function(e,t,i,n){return this.intersectConvex(e.convexPolyhedronRepresentation,t,i,n)},h.prototype[a.types.BOX]=h.prototype.intersectBox,h.prototype.intersectPlane=function(e,t,i,s){var r=this.from,o=this.to,a=this._direction,l=new n(0,0,1);t.vmult(l,l);var h=new n;r.vsub(i,h);var c=h.dot(l);if(o.vsub(i,h),!(c*h.dot(l)>0||r.distanceTo(o)<c)){var u=l.dot(a);if(!(Math.abs(u)<this.precision)){var d=new n,p=new n,f=new n;r.vsub(i,d);var _=-l.dot(d)/u;a.scale(_,p),r.vadd(p,f),this.reportIntersection(l,f,e,s,-1)}}},h.prototype[a.types.PLANE]=h.prototype.intersectPlane,h.prototype.getAABB=function(e){var t=this.to,i=this.from;e.lowerBound.x=Math.min(t.x,i.x),e.lowerBound.y=Math.min(t.y,i.y),e.lowerBound.z=Math.min(t.z,i.z),e.upperBound.x=Math.max(t.x,i.x),e.upperBound.y=Math.max(t.y,i.y),e.upperBound.z=Math.max(t.z,i.z)};var b={faceList:[0]};h.prototype.intersectHeightfield=function(e,t,i,s){e.data,e.elementSize;var o=new n,a=new h(this.from,this.to);r.pointToLocalFrame(i,t,a.from,a.from),r.pointToLocalFrame(i,t,a.to,a.to);var l=[],c=null,u=null,d=null,p=null,f=e.getIndexOfPosition(a.from.x,a.from.y,l,!1);if(f&&(c=l[0],u=l[1],d=l[0],p=l[1]),(f=e.getIndexOfPosition(a.to.x,a.to.y,l,!1))&&((null===c||l[0]<c)&&(c=l[0]),(null===d||l[0]>d)&&(d=l[0]),(null===u||l[1]<u)&&(u=l[1]),(null===p||l[1]>p)&&(p=l[1])),null!==c){var _=[];e.getRectMinMax(c,u,d,p,_);for(var m=c;m<=d;m++)for(var g=u;g<=p;g++){if(this.result._shouldStop)return;if(e.getConvexTrianglePillar(m,g,!1),r.pointToWorldFrame(i,t,e.pillarOffset,o),this.intersectConvex(e.pillarConvex,t,o,s,b),this.result._shouldStop)return;e.getConvexTrianglePillar(m,g,!0),r.pointToWorldFrame(i,t,e.pillarOffset,o),this.intersectConvex(e.pillarConvex,t,o,s,b)}}},h.prototype[a.types.HEIGHTFIELD]=h.prototype.intersectHeightfield;var T=new n,S=new n;h.prototype.intersectSphere=function(e,t,i,n){var s=this.from,r=this.to,o=e.radius,a=Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2)+Math.pow(r.z-s.z,2),l=2*((r.x-s.x)*(s.x-i.x)+(r.y-s.y)*(s.y-i.y)+(r.z-s.z)*(s.z-i.z)),h=Math.pow(s.x-i.x,2)+Math.pow(s.y-i.y,2)+Math.pow(s.z-i.z,2)-Math.pow(o,2),c=Math.pow(l,2)-4*a*h,u=T,d=S;if(!(c<0))if(0===c)s.lerp(r,c,u),u.vsub(i,d),d.normalize(),this.reportIntersection(d,u,e,n,-1);else{var p=(-l-Math.sqrt(c))/(2*a),f=(-l+Math.sqrt(c))/(2*a);if(p>=0&&p<=1&&(s.lerp(r,p,u),u.vsub(i,d),d.normalize(),this.reportIntersection(d,u,e,n,-1)),this.result._shouldStop)return;f>=0&&f<=1&&(s.lerp(r,f,u),u.vsub(i,d),d.normalize(),this.reportIntersection(d,u,e,n,-1))}},h.prototype[a.types.SPHERE]=h.prototype.intersectSphere;var E=new n,C=(new n,new n,new n);h.prototype.intersectConvex=function(e,t,i,n,s){for(var r=E,o=C,a=s&&s.faceList||null,l=e.faces,h=e.vertices,c=e.faceNormals,u=this._direction,d=this.from,p=this.to,_=d.distanceTo(p),m=a?a.length:l.length,b=this.result,T=0;!b._shouldStop&&T<m;T++){var S=a?a[T]:T,A=l[S],P=c[S],R=t,M=i;o.copy(h[A[0]]),R.vmult(o,o),o.vadd(M,o),o.vsub(d,o),R.vmult(P,r);var I=u.dot(r);if(!(Math.abs(I)<this.precision)){var D=r.dot(o)/I;if(!(D<0)){u.mult(D,g),g.vadd(d,g),v.copy(h[A[0]]),R.vmult(v,v),M.vadd(v,v);for(var O=1;!b._shouldStop&&O<A.length-1;O++){y.copy(h[A[O]]),x.copy(h[A[O+1]]),R.vmult(y,y),R.vmult(x,x),M.vadd(y,y),M.vadd(x,x);var w=g.distanceTo(d);!f(g,v,y,x)&&!f(g,y,v,x)||w>_||this.reportIntersection(r,g,e,n,S)}}}}},h.prototype[a.types.CONVEXPOLYHEDRON]=h.prototype.intersectConvex;var A=new n,P=new n,R=new n,M=new n,I=new n,D=new n,O=(new l,[]),w=new r;h.prototype.intersectTrimesh=function(e,t,i,n,s){var o=A,a=O,l=w,h=C,c=P,u=R,d=M,p=D,_=I,m=(s&&s.faceList,e.indices),b=(e.vertices,e.faceNormals,this.from),T=this.to,S=this._direction;l.position.copy(i),l.quaternion.copy(t),r.vectorToLocalFrame(i,t,S,c),r.pointToLocalFrame(i,t,b,u),r.pointToLocalFrame(i,t,T,d);var E=u.distanceSquared(d);e.tree.rayQuery(this,l,a);for(var N=0,F=a.length;!this.result._shouldStop&&N!==F;N++){var L=a[N];e.getNormal(L,o),e.getVertex(m[3*L],v),v.vsub(u,h);var B=c.dot(o),U=o.dot(h)/B;if(!(U<0)){c.scale(U,g),g.vadd(u,g),e.getVertex(m[3*L+1],y),e.getVertex(m[3*L+2],x);var V=g.distanceSquared(u);!f(g,y,v,x)&&!f(g,v,y,x)||V>E||(r.vectorToWorldFrame(t,o,_),r.pointToWorldFrame(i,t,g,p),this.reportIntersection(_,p,e,n,L))}}a.length=0},h.prototype[a.types.TRIMESH]=h.prototype.intersectTrimesh,h.prototype.reportIntersection=function(e,t,i,n,s){var r=this.from,o=this.to,a=r.distanceTo(t),l=this.result;if(!(this.skipBackfaces&&e.dot(this._direction)>0))switch(l.hitFaceIndex=void 0!==s?s:-1,this.mode){case h.ALL:this.hasHit=!0,l.set(r,o,e,t,i,n,a),l.hasHit=!0,this.callback(l);break;case h.CLOSEST:(a<l.distance||!l.hasHit)&&(this.hasHit=!0,l.hasHit=!0,l.set(r,o,e,t,i,n,a));break;case h.ANY:this.hasHit=!0,l.hasHit=!0,l.set(r,o,e,t,i,n,a),l._shouldStop=!0}};var N=new n,F=new n},{"../collision/AABB":3,"../collision/RaycastResult":10,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../shapes/Box":37,"../shapes/ConvexPolyhedron":38,"../shapes/Shape":43}],10:[function(e,t,i){var n=e("../math/Vec3");function s(){this.rayFromWorld=new n,this.rayToWorld=new n,this.hitNormalWorld=new n,this.hitPointWorld=new n,this.hasHit=!1,this.shape=null,this.body=null,this.hitFaceIndex=-1,this.distance=-1,this._shouldStop=!1}t.exports=s,s.prototype.reset=function(){this.rayFromWorld.setZero(),this.rayToWorld.setZero(),this.hitNormalWorld.setZero(),this.hitPointWorld.setZero(),this.hasHit=!1,this.shape=null,this.body=null,this.hitFaceIndex=-1,this.distance=-1,this._shouldStop=!1},s.prototype.abort=function(){this._shouldStop=!0},s.prototype.set=function(e,t,i,n,s,r,o){this.rayFromWorld.copy(e),this.rayToWorld.copy(t),this.hitNormalWorld.copy(i),this.hitPointWorld.copy(n),this.shape=s,this.body=r,this.distance=o}},{"../math/Vec3":30}],11:[function(e,t,i){e("../shapes/Shape");var n=e("../collision/Broadphase");function s(e){n.apply(this),this.axisList=[],this.world=null,this.axisIndex=0;var t=this.axisList;this._addBodyHandler=function(e){t.push(e.body)},this._removeBodyHandler=function(e){var i=t.indexOf(e.body);-1!==i&&t.splice(i,1)},e&&this.setWorld(e)}t.exports=s,s.prototype=new n,s.prototype.setWorld=function(e){this.axisList.length=0;for(var t=0;t<e.bodies.length;t++)this.axisList.push(e.bodies[t]);e.removeEventListener("addBody",this._addBodyHandler),e.removeEventListener("removeBody",this._removeBodyHandler),e.addEventListener("addBody",this._addBodyHandler),e.addEventListener("removeBody",this._removeBodyHandler),this.world=e,this.dirty=!0},s.insertionSortX=function(e){for(var t=1,i=e.length;t<i;t++){for(var n=e[t],s=t-1;s>=0&&!(e[s].aabb.lowerBound.x<=n.aabb.lowerBound.x);s--)e[s+1]=e[s];e[s+1]=n}return e},s.insertionSortY=function(e){for(var t=1,i=e.length;t<i;t++){for(var n=e[t],s=t-1;s>=0&&!(e[s].aabb.lowerBound.y<=n.aabb.lowerBound.y);s--)e[s+1]=e[s];e[s+1]=n}return e},s.insertionSortZ=function(e){for(var t=1,i=e.length;t<i;t++){for(var n=e[t],s=t-1;s>=0&&!(e[s].aabb.lowerBound.z<=n.aabb.lowerBound.z);s--)e[s+1]=e[s];e[s+1]=n}return e},s.prototype.collisionPairs=function(e,t,i){var n,r,o=this.axisList,a=o.length,l=this.axisIndex;for(this.dirty&&(this.sortList(),this.dirty=!1),n=0;n!==a;n++){var h=o[n];for(r=n+1;r<a;r++){var c=o[r];if(this.needBroadphaseCollision(h,c)){if(!s.checkBounds(h,c,l))break;this.intersectionTest(h,c,t,i)}}}},s.prototype.sortList=function(){for(var e=this.axisList,t=this.axisIndex,i=e.length,n=0;n!==i;n++){var r=e[n];r.aabbNeedsUpdate&&r.computeAABB()}0===t?s.insertionSortX(e):1===t?s.insertionSortY(e):2===t&&s.insertionSortZ(e)},s.checkBounds=function(e,t,i){var n,s;0===i?(n=e.position.x,s=t.position.x):1===i?(n=e.position.y,s=t.position.y):2===i&&(n=e.position.z,s=t.position.z);var r=e.boundingRadius;return s-t.boundingRadius<n+r},s.prototype.autoDetectAxis=function(){for(var e=0,t=0,i=0,n=0,s=0,r=0,o=this.axisList,a=o.length,l=1/a,h=0;h!==a;h++){var c=o[h],u=c.position.x;e+=u,t+=u*u;var d=c.position.y;i+=d,n+=d*d;var p=c.position.z;s+=p,r+=p*p}var f=t-e*e*l,_=n-i*i*l,m=r-s*s*l;this.axisIndex=f>_?f>m?0:2:_>m?1:2},s.prototype.aabbQuery=function(e,t,i){i=i||[],this.dirty&&(this.sortList(),this.dirty=!1);var n=this.axisIndex,s="x";1===n&&(s="y"),2===n&&(s="z");for(var r=this.axisList,o=(t.lowerBound[s],t.upperBound[s],0);o<r.length;o++){var a=r[o];a.aabbNeedsUpdate&&a.computeAABB(),a.aabb.overlaps(t)&&i.push(a)}return i}},{"../collision/Broadphase":5,"../shapes/Shape":43}],12:[function(e,t,i){t.exports=a,e("./Constraint");var n=e("./PointToPointConstraint"),s=e("../equations/ConeEquation"),r=e("../equations/RotationalEquation"),o=(e("../equations/ContactEquation"),e("../math/Vec3"));function a(e,t,i){var a=void 0!==(i=i||{}).maxForce?i.maxForce:1e6,l=i.pivotA?i.pivotA.clone():new o,h=i.pivotB?i.pivotB.clone():new o;this.axisA=i.axisA?i.axisA.clone():new o,this.axisB=i.axisB?i.axisB.clone():new o,n.call(this,e,l,t,h,a),this.collideConnected=!!i.collideConnected,this.angle=void 0!==i.angle?i.angle:0;var c=this.coneEquation=new s(e,t,i),u=this.twistEquation=new r(e,t,i);this.twistAngle=void 0!==i.twistAngle?i.twistAngle:0,c.maxForce=0,c.minForce=-a,u.maxForce=0,u.minForce=-a,this.equations.push(c,u)}a.prototype=new n,a.constructor=a,new o,new o,a.prototype.update=function(){var e=this.bodyA,t=this.bodyB,i=this.coneEquation,s=this.twistEquation;n.prototype.update.call(this),e.vectorToWorldFrame(this.axisA,i.axisA),t.vectorToWorldFrame(this.axisB,i.axisB),this.axisA.tangents(s.axisA,s.axisA),e.vectorToWorldFrame(s.axisA,s.axisA),this.axisB.tangents(s.axisB,s.axisB),t.vectorToWorldFrame(s.axisB,s.axisB),i.angle=this.angle,s.maxAngle=this.twistAngle}},{"../equations/ConeEquation":18,"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],13:[function(e,t,i){t.exports=s;var n=e("../utils/Utils");function s(e,t,i){i=n.defaults(i,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=e,this.bodyB=t,this.id=s.idCounter++,this.collideConnected=i.collideConnected,i.wakeUpBodies&&(e&&e.wakeUp(),t&&t.wakeUp())}s.prototype.update=function(){throw new Error("method update() not implmemented in this Constraint subclass!")},s.prototype.enable=function(){for(var e=this.equations,t=0;t<e.length;t++)e[t].enabled=!0},s.prototype.disable=function(){for(var e=this.equations,t=0;t<e.length;t++)e[t].enabled=!1},s.idCounter=0},{"../utils/Utils":53}],14:[function(e,t,i){t.exports=r;var n=e("./Constraint"),s=e("../equations/ContactEquation");function r(e,t,i,r){n.call(this,e,t),void 0===i&&(i=e.position.distanceTo(t.position)),void 0===r&&(r=1e6),this.distance=i;var o=this.distanceEquation=new s(e,t);this.equations.push(o),o.minForce=-r,o.maxForce=r}r.prototype=new n,r.prototype.update=function(){var e=this.bodyA,t=this.bodyB,i=this.distanceEquation,n=.5*this.distance,s=i.ni;t.position.vsub(e.position,s),s.normalize(),s.mult(n,i.ri),s.mult(-n,i.rj)}},{"../equations/ContactEquation":19,"./Constraint":13}],15:[function(e,t,i){t.exports=a,e("./Constraint");var n=e("./PointToPointConstraint"),s=e("../equations/RotationalEquation"),r=e("../equations/RotationalMotorEquation"),o=(e("../equations/ContactEquation"),e("../math/Vec3"));function a(e,t,i){var a=void 0!==(i=i||{}).maxForce?i.maxForce:1e6,l=i.pivotA?i.pivotA.clone():new o,h=i.pivotB?i.pivotB.clone():new o;n.call(this,e,l,t,h,a),(this.axisA=i.axisA?i.axisA.clone():new o(1,0,0)).normalize(),(this.axisB=i.axisB?i.axisB.clone():new o(1,0,0)).normalize();var c=this.rotationalEquation1=new s(e,t,i),u=this.rotationalEquation2=new s(e,t,i),d=this.motorEquation=new r(e,t,a);d.enabled=!1,this.equations.push(c,u,d)}a.prototype=new n,a.constructor=a,a.prototype.enableMotor=function(){this.motorEquation.enabled=!0},a.prototype.disableMotor=function(){this.motorEquation.enabled=!1},a.prototype.setMotorSpeed=function(e){this.motorEquation.targetVelocity=e},a.prototype.setMotorMaxForce=function(e){this.motorEquation.maxForce=e,this.motorEquation.minForce=-e};var l=new o,h=new o;a.prototype.update=function(){var e=this.bodyA,t=this.bodyB,i=this.motorEquation,s=this.rotationalEquation1,r=this.rotationalEquation2,o=l,a=h,c=this.axisA,u=this.axisB;n.prototype.update.call(this),e.quaternion.vmult(c,o),t.quaternion.vmult(u,a),o.tangents(s.axisA,r.axisA),s.axisB.copy(a),r.axisB.copy(a),this.motorEquation.enabled&&(e.quaternion.vmult(this.axisA,i.axisA),t.quaternion.vmult(this.axisB,i.axisB))}},{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],16:[function(e,t,i){t.exports=o,e("./Constraint");var n=e("./PointToPointConstraint"),s=e("../equations/RotationalEquation"),r=(e("../equations/RotationalMotorEquation"),e("../equations/ContactEquation"),e("../math/Vec3"));function o(e,t,i){var o=void 0!==(i=i||{}).maxForce?i.maxForce:1e6,a=new r,l=new r,h=new r;e.position.vadd(t.position,h),h.scale(.5,h),t.pointToLocalFrame(h,l),e.pointToLocalFrame(h,a),n.call(this,e,a,t,l,o);var c=this.rotationalEquation1=new s(e,t,i),u=this.rotationalEquation2=new s(e,t,i),d=this.rotationalEquation3=new s(e,t,i);this.equations.push(c,u,d)}o.prototype=new n,o.constructor=o,new r,new r,o.prototype.update=function(){var e=this.bodyA,t=this.bodyB,i=(this.motorEquation,this.rotationalEquation1),s=this.rotationalEquation2,o=this.rotationalEquation3;n.prototype.update.call(this),e.vectorToWorldFrame(r.UNIT_X,i.axisA),t.vectorToWorldFrame(r.UNIT_Y,i.axisB),e.vectorToWorldFrame(r.UNIT_Y,s.axisA),t.vectorToWorldFrame(r.UNIT_Z,s.axisB),e.vectorToWorldFrame(r.UNIT_Z,o.axisA),t.vectorToWorldFrame(r.UNIT_X,o.axisB)}},{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],17:[function(e,t,i){t.exports=o;var n=e("./Constraint"),s=e("../equations/ContactEquation"),r=e("../math/Vec3");function o(e,t,i,o,a){n.call(this,e,i),a=void 0!==a?a:1e6,this.pivotA=t?t.clone():new r,this.pivotB=o?o.clone():new r;var l=this.equationX=new s(e,i),h=this.equationY=new s(e,i),c=this.equationZ=new s(e,i);this.equations.push(l,h,c),l.minForce=h.minForce=c.minForce=-a,l.maxForce=h.maxForce=c.maxForce=a,l.ni.set(1,0,0),h.ni.set(0,1,0),c.ni.set(0,0,1)}o.prototype=new n,o.prototype.update=function(){var e=this.bodyA,t=this.bodyB,i=this.equationX,n=this.equationY,s=this.equationZ;e.quaternion.vmult(this.pivotA,i.ri),t.quaternion.vmult(this.pivotB,i.rj),n.ri.copy(i.ri),n.rj.copy(i.rj),s.ri.copy(i.ri),s.rj.copy(i.rj)}},{"../equations/ContactEquation":19,"../math/Vec3":30,"./Constraint":13}],18:[function(e,t,i){t.exports=r;var n=e("../math/Vec3"),s=(e("../math/Mat3"),e("./Equation"));function r(e,t,i){var r=void 0!==(i=i||{}).maxForce?i.maxForce:1e6;s.call(this,e,t,-r,r),this.axisA=i.axisA?i.axisA.clone():new n(1,0,0),this.axisB=i.axisB?i.axisB.clone():new n(0,1,0),this.angle=void 0!==i.angle?i.angle:0}r.prototype=new s,r.prototype.constructor=r;var o=new n,a=new n;r.prototype.computeB=function(e){var t=this.a,i=this.b,n=this.axisA,s=this.axisB,r=o,l=a,h=this.jacobianElementA,c=this.jacobianElementB;return n.cross(s,r),s.cross(n,l),h.rotational.copy(l),c.rotational.copy(r),-(Math.cos(this.angle)-n.dot(s))*t-this.computeGW()*i-e*this.computeGiMf()}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],19:[function(e,t,i){t.exports=r;var n=e("./Equation"),s=e("../math/Vec3");function r(e,t,i){i=void 0!==i?i:1e6,n.call(this,e,t,0,i),this.restitution=0,this.ri=new s,this.rj=new s,this.ni=new s}e("../math/Mat3"),r.prototype=new n,r.prototype.constructor=r;var o=new s,a=new s,l=new s;r.prototype.computeB=function(e){var t=this.a,i=this.b,n=this.bi,s=this.bj,r=this.ri,h=this.rj,c=o,u=a,d=n.velocity,p=n.angularVelocity,f=(n.force,n.torque,s.velocity),_=s.angularVelocity,m=(s.force,s.torque,l),g=this.jacobianElementA,v=this.jacobianElementB,y=this.ni;r.cross(y,c),h.cross(y,u),y.negate(g.spatial),c.negate(g.rotational),v.spatial.copy(y),v.rotational.copy(u),m.copy(s.position),m.vadd(h,m),m.vsub(n.position,m),m.vsub(r,m);var x=y.dot(m),b=this.restitution+1;return-x*t-(b*f.dot(y)-b*d.dot(y)+_.dot(u)-p.dot(c))*i-e*this.computeGiMf()};var h=new s,c=new s,u=new s,d=new s,p=new s;r.prototype.getImpactVelocityAlongNormal=function(){var e=h,t=c,i=u,n=d,s=p;return this.bi.position.vadd(this.ri,i),this.bj.position.vadd(this.rj,n),this.bi.getVelocityAtWorldPoint(i,e),this.bj.getVelocityAtWorldPoint(n,t),e.vsub(t,s),this.ni.dot(s)}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],20:[function(e,t,i){t.exports=r;var n=e("../math/JacobianElement"),s=e("../math/Vec3");function r(e,t,i,s){this.id=r.id++,this.minForce=void 0===i?-1e6:i,this.maxForce=void 0===s?1e6:s,this.bi=e,this.bj=t,this.a=0,this.b=0,this.eps=0,this.jacobianElementA=new n,this.jacobianElementB=new n,this.enabled=!0,this.setSpookParams(1e7,4,1/60)}r.prototype.constructor=r,r.id=0,r.prototype.setSpookParams=function(e,t,i){var n=t,s=e,r=i;this.a=4/(r*(1+4*n)),this.b=4*n/(1+4*n),this.eps=4/(r*r*s*(1+4*n))},r.prototype.computeB=function(e,t,i){var n=this.computeGW();return-this.computeGq()*e-n*t-this.computeGiMf()*i},r.prototype.computeGq=function(){var e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,s=i.position,r=n.position;return e.spatial.dot(s)+t.spatial.dot(r)};var o=new s;r.prototype.computeGW=function(){var e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,s=i.velocity,r=n.velocity,a=i.angularVelocity||o,l=n.angularVelocity||o;return e.multiplyVectors(s,a)+t.multiplyVectors(r,l)},r.prototype.computeGWlambda=function(){var e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,s=i.vlambda,r=n.vlambda,a=i.wlambda||o,l=n.wlambda||o;return e.multiplyVectors(s,a)+t.multiplyVectors(r,l)};var a=new s,l=new s,h=new s,c=new s;r.prototype.computeGiMf=function(){var e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,s=i.force,r=i.torque,o=n.force,u=n.torque,d=i.invMassSolve,p=n.invMassSolve;return i.invInertiaWorldSolve?i.invInertiaWorldSolve.vmult(r,h):h.set(0,0,0),n.invInertiaWorldSolve?n.invInertiaWorldSolve.vmult(u,c):c.set(0,0,0),s.mult(d,a),o.mult(p,l),e.multiplyVectors(a,h)+t.multiplyVectors(l,c)};var u=new s;r.prototype.computeGiMGt=function(){var e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,s=i.invMassSolve,r=n.invMassSolve,o=i.invInertiaWorldSolve,a=n.invInertiaWorldSolve,l=s+r;return o&&(o.vmult(e.rotational,u),l+=u.dot(e.rotational)),a&&(a.vmult(t.rotational,u),l+=u.dot(t.rotational)),l};var d=new s;new s,new s,new s,new s,new s,r.prototype.addToWlambda=function(e){var t=this.jacobianElementA,i=this.jacobianElementB,n=this.bi,s=this.bj,r=d;t.spatial.mult(n.invMassSolve*e,r),n.vlambda.vadd(r,n.vlambda),i.spatial.mult(s.invMassSolve*e,r),s.vlambda.vadd(r,s.vlambda),n.invInertiaWorldSolve&&(n.invInertiaWorldSolve.vmult(t.rotational,r),r.mult(e,r),n.wlambda.vadd(r,n.wlambda)),s.invInertiaWorldSolve&&(s.invInertiaWorldSolve.vmult(i.rotational,r),r.mult(e,r),s.wlambda.vadd(r,s.wlambda))},r.prototype.computeC=function(){return this.computeGiMGt()+this.eps}},{"../math/JacobianElement":26,"../math/Vec3":30}],21:[function(e,t,i){t.exports=r;var n=e("./Equation"),s=e("../math/Vec3");function r(e,t,i){n.call(this,e,t,-i,i),this.ri=new s,this.rj=new s,this.t=new s}e("../math/Mat3"),r.prototype=new n,r.prototype.constructor=r;var o=new s,a=new s;r.prototype.computeB=function(e){this.a;var t=this.b,i=(this.bi,this.bj,this.ri),n=this.rj,s=o,r=a,l=this.t;i.cross(l,s),n.cross(l,r);var h=this.jacobianElementA,c=this.jacobianElementB;return l.negate(h.spatial),s.negate(h.rotational),c.spatial.copy(l),c.rotational.copy(r),-this.computeGW()*t-e*this.computeGiMf()}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],22:[function(e,t,i){t.exports=r;var n=e("../math/Vec3"),s=(e("../math/Mat3"),e("./Equation"));function r(e,t,i){var r=void 0!==(i=i||{}).maxForce?i.maxForce:1e6;s.call(this,e,t,-r,r),this.axisA=i.axisA?i.axisA.clone():new n(1,0,0),this.axisB=i.axisB?i.axisB.clone():new n(0,1,0),this.maxAngle=Math.PI/2}r.prototype=new s,r.prototype.constructor=r;var o=new n,a=new n;r.prototype.computeB=function(e){var t=this.a,i=this.b,n=this.axisA,s=this.axisB,r=o,l=a,h=this.jacobianElementA,c=this.jacobianElementB;return n.cross(s,r),s.cross(n,l),h.rotational.copy(l),c.rotational.copy(r),-(Math.cos(this.maxAngle)-n.dot(s))*t-this.computeGW()*i-e*this.computeGiMf()}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],23:[function(e,t,i){t.exports=r;var n=e("../math/Vec3"),s=(e("../math/Mat3"),e("./Equation"));function r(e,t,i){i=void 0!==i?i:1e6,s.call(this,e,t,-i,i),this.axisA=new n,this.axisB=new n,this.targetVelocity=0}r.prototype=new s,r.prototype.constructor=r,r.prototype.computeB=function(e){this.a;var t=this.b,i=(this.bi,this.bj,this.axisA),n=this.axisB,s=this.jacobianElementA,r=this.jacobianElementB;return s.rotational.copy(i),n.negate(r.rotational),-(this.computeGW()-this.targetVelocity)*t-e*this.computeGiMf()}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],24:[function(e,t,i){var n=e("../utils/Utils");function s(e,t,i){i=n.defaults(i,{friction:.3,restitution:.3,contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}),this.id=s.idCounter++,this.materials=[e,t],this.friction=i.friction,this.restitution=i.restitution,this.contactEquationStiffness=i.contactEquationStiffness,this.contactEquationRelaxation=i.contactEquationRelaxation,this.frictionEquationStiffness=i.frictionEquationStiffness,this.frictionEquationRelaxation=i.frictionEquationRelaxation}t.exports=s,s.idCounter=0},{"../utils/Utils":53}],25:[function(e,t,i){function n(e){var t="";"string"==typeof(e=e||{})?(t=e,e={}):"object"==typeof e&&(t=""),this.name=t,this.id=n.idCounter++,this.friction=void 0!==e.friction?e.friction:-1,this.restitution=void 0!==e.restitution?e.restitution:-1}t.exports=n,n.idCounter=0},{}],26:[function(e,t,i){t.exports=s;var n=e("./Vec3");function s(){this.spatial=new n,this.rotational=new n}s.prototype.multiplyElement=function(e){return e.spatial.dot(this.spatial)+e.rotational.dot(this.rotational)},s.prototype.multiplyVectors=function(e,t){return e.dot(this.spatial)+t.dot(this.rotational)}},{"./Vec3":30}],27:[function(e,t,i){t.exports=s;var n=e("./Vec3");function s(e){this.elements=e||[0,0,0,0,0,0,0,0,0]}s.prototype.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},s.prototype.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},s.prototype.setTrace=function(e){var t=this.elements;t[0]=e.x,t[4]=e.y,t[8]=e.z},s.prototype.getTrace=function(e){e=e||new n;var t=this.elements;e.x=t[0],e.y=t[4],e.z=t[8]},s.prototype.vmult=function(e,t){t=t||new n;var i=this.elements,s=e.x,r=e.y,o=e.z;return t.x=i[0]*s+i[1]*r+i[2]*o,t.y=i[3]*s+i[4]*r+i[5]*o,t.z=i[6]*s+i[7]*r+i[8]*o,t},s.prototype.smult=function(e){for(var t=0;t<this.elements.length;t++)this.elements[t]*=e},s.prototype.mmult=function(e,t){for(var i=t||new s,n=0;n<3;n++)for(var r=0;r<3;r++){for(var o=0,a=0;a<3;a++)o+=e.elements[n+3*a]*this.elements[a+3*r];i.elements[n+3*r]=o}return i},s.prototype.scale=function(e,t){t=t||new s;for(var i=this.elements,n=t.elements,r=0;3!==r;r++)n[3*r+0]=e.x*i[3*r+0],n[3*r+1]=e.y*i[3*r+1],n[3*r+2]=e.z*i[3*r+2];return t},s.prototype.solve=function(e,t){t=t||new n;for(var i,s=[],r=0;r<12;r++)s.push(0);for(r=0;r<3;r++)for(i=0;i<3;i++)s[r+4*i]=this.elements[r+3*i];s[3]=e.x,s[7]=e.y,s[11]=e.z;var o,a,l=3,h=l;do{if(0===s[(r=h-l)+4*r])for(i=r+1;i<h;i++)if(0!==s[r+4*i]){o=4;do{s[(a=4-o)+4*r]+=s[a+4*i]}while(--o);break}if(0!==s[r+4*r])for(i=r+1;i<h;i++){var c=s[r+4*i]/s[r+4*r];o=4;do{s[(a=4-o)+4*i]=a<=r?0:s[a+4*i]-s[a+4*r]*c}while(--o)}}while(--l);if(t.z=s[11]/s[10],t.y=(s[7]-s[6]*t.z)/s[5],t.x=(s[3]-s[2]*t.z-s[1]*t.y)/s[0],isNaN(t.x)||isNaN(t.y)||isNaN(t.z)||t.x===1/0||t.y===1/0||t.z===1/0)throw"Could not solve equation! Got x=["+t.toString()+"], b=["+e.toString()+"], A=["+this.toString()+"]";return t},s.prototype.e=function(e,t,i){if(void 0===i)return this.elements[t+3*e];this.elements[t+3*e]=i},s.prototype.copy=function(e){for(var t=0;t<e.elements.length;t++)this.elements[t]=e.elements[t];return this},s.prototype.toString=function(){for(var e="",t=0;t<9;t++)e+=this.elements[t]+",";return e},s.prototype.reverse=function(e){e=e||new s;for(var t,i=[],n=0;n<18;n++)i.push(0);for(n=0;n<3;n++)for(t=0;t<3;t++)i[n+6*t]=this.elements[n+3*t];i[3]=1,i[9]=0,i[15]=0,i[4]=0,i[10]=1,i[16]=0,i[5]=0,i[11]=0,i[17]=1;var r,o,a=3,l=a;do{if(0===i[(n=l-a)+6*n])for(t=n+1;t<l;t++)if(0!==i[n+6*t]){r=6;do{i[(o=6-r)+6*n]+=i[o+6*t]}while(--r);break}if(0!==i[n+6*n])for(t=n+1;t<l;t++){var h=i[n+6*t]/i[n+6*n];r=6;do{i[(o=6-r)+6*t]=o<=n?0:i[o+6*t]-i[o+6*n]*h}while(--r)}}while(--a);n=2;do{t=n-1;do{h=i[n+6*t]/i[n+6*n],r=6;do{i[(o=6-r)+6*t]=i[o+6*t]-i[o+6*n]*h}while(--r)}while(t--)}while(--n);n=2;do{h=1/i[n+6*n],r=6;do{i[(o=6-r)+6*n]=i[o+6*n]*h}while(--r)}while(n--);n=2;do{t=2;do{if(o=i[3+t+6*n],isNaN(o)||o===1/0)throw"Could not reverse! A=["+this.toString()+"]";e.e(n,t,o)}while(t--)}while(n--);return e},s.prototype.setRotationFromQuaternion=function(e){var t=e.x,i=e.y,n=e.z,s=e.w,r=t+t,o=i+i,a=n+n,l=t*r,h=t*o,c=t*a,u=i*o,d=i*a,p=n*a,f=s*r,_=s*o,m=s*a,g=this.elements;return g[0]=1-(u+p),g[1]=h-m,g[2]=c+_,g[3]=h+m,g[4]=1-(l+p),g[5]=d-f,g[6]=c-_,g[7]=d+f,g[8]=1-(l+u),this},s.prototype.transpose=function(e){for(var t=(e=e||new s).elements,i=this.elements,n=0;3!==n;n++)for(var r=0;3!==r;r++)t[3*n+r]=i[3*r+n];return e}},{"./Vec3":30}],28:[function(e,t,i){t.exports=s;var n=e("./Vec3");function s(e,t,i,n){this.x=void 0!==e?e:0,this.y=void 0!==t?t:0,this.z=void 0!==i?i:0,this.w=void 0!==n?n:1}s.prototype.set=function(e,t,i,n){this.x=e,this.y=t,this.z=i,this.w=n},s.prototype.toString=function(){return this.x+","+this.y+","+this.z+","+this.w},s.prototype.toArray=function(){return[this.x,this.y,this.z,this.w]},s.prototype.setFromAxisAngle=function(e,t){var i=Math.sin(.5*t);this.x=e.x*i,this.y=e.y*i,this.z=e.z*i,this.w=Math.cos(.5*t)},s.prototype.toAxisAngle=function(e){e=e||new n,this.normalize();var t=2*Math.acos(this.w),i=Math.sqrt(1-this.w*this.w);return i<.001?(e.x=this.x,e.y=this.y,e.z=this.z):(e.x=this.x/i,e.y=this.y/i,e.z=this.z/i),[e,t]};var r=new n,o=new n;s.prototype.setFromVectors=function(e,t){if(e.isAntiparallelTo(t)){var i=r,n=o;e.tangents(i,n),this.setFromAxisAngle(i,Math.PI)}else{var s=e.cross(t);this.x=s.x,this.y=s.y,this.z=s.z,this.w=Math.sqrt(Math.pow(e.norm(),2)*Math.pow(t.norm(),2))+e.dot(t),this.normalize()}};var a=new n,l=new n,h=new n;s.prototype.mult=function(e,t){t=t||new s;var i=this.w,n=a,r=l,o=h;return n.set(this.x,this.y,this.z),r.set(e.x,e.y,e.z),t.w=i*e.w-n.dot(r),n.cross(r,o),t.x=i*r.x+e.w*n.x+o.x,t.y=i*r.y+e.w*n.y+o.y,t.z=i*r.z+e.w*n.z+o.z,t},s.prototype.inverse=function(e){var t=this.x,i=this.y,n=this.z,r=this.w;e=e||new s,this.conjugate(e);var o=1/(t*t+i*i+n*n+r*r);return e.x*=o,e.y*=o,e.z*=o,e.w*=o,e},s.prototype.conjugate=function(e){return(e=e||new s).x=-this.x,e.y=-this.y,e.z=-this.z,e.w=this.w,e},s.prototype.normalize=function(){var e=Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);0===e?(this.x=0,this.y=0,this.z=0,this.w=0):(e=1/e,this.x*=e,this.y*=e,this.z*=e,this.w*=e)},s.prototype.normalizeFast=function(){var e=(3-(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w))/2;0===e?(this.x=0,this.y=0,this.z=0,this.w=0):(this.x*=e,this.y*=e,this.z*=e,this.w*=e)},s.prototype.vmult=function(e,t){t=t||new n;var i=e.x,s=e.y,r=e.z,o=this.x,a=this.y,l=this.z,h=this.w,c=h*i+a*r-l*s,u=h*s+l*i-o*r,d=h*r+o*s-a*i,p=-o*i-a*s-l*r;return t.x=c*h+p*-o+u*-l-d*-a,t.y=u*h+p*-a+d*-o-c*-l,t.z=d*h+p*-l+c*-a-u*-o,t},s.prototype.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},s.prototype.toEuler=function(e,t){var i,n,s;t=t||"YZX";var r=this.x,o=this.y,a=this.z,l=this.w;if("YZX"!==t)throw new Error("Euler order "+t+" not supported yet.");var h=r*o+a*l;if(h>.499&&(i=2*Math.atan2(r,l),n=Math.PI/2,s=0),h<-.499&&(i=-2*Math.atan2(r,l),n=-Math.PI/2,s=0),isNaN(i)){var c=r*r,u=o*o,d=a*a;i=Math.atan2(2*o*l-2*r*a,1-2*u-2*d),n=Math.asin(2*h),s=Math.atan2(2*r*l-2*o*a,1-2*c-2*d)}e.y=i,e.z=n,e.x=s},s.prototype.setFromEuler=function(e,t,i,n){n=n||"XYZ";var s=Math.cos(e/2),r=Math.cos(t/2),o=Math.cos(i/2),a=Math.sin(e/2),l=Math.sin(t/2),h=Math.sin(i/2);return"XYZ"===n?(this.x=a*r*o+s*l*h,this.y=s*l*o-a*r*h,this.z=s*r*h+a*l*o,this.w=s*r*o-a*l*h):"YXZ"===n?(this.x=a*r*o+s*l*h,this.y=s*l*o-a*r*h,this.z=s*r*h-a*l*o,this.w=s*r*o+a*l*h):"ZXY"===n?(this.x=a*r*o-s*l*h,this.y=s*l*o+a*r*h,this.z=s*r*h+a*l*o,this.w=s*r*o-a*l*h):"ZYX"===n?(this.x=a*r*o-s*l*h,this.y=s*l*o+a*r*h,this.z=s*r*h-a*l*o,this.w=s*r*o+a*l*h):"YZX"===n?(this.x=a*r*o+s*l*h,this.y=s*l*o+a*r*h,this.z=s*r*h-a*l*o,this.w=s*r*o-a*l*h):"XZY"===n&&(this.x=a*r*o-s*l*h,this.y=s*l*o-a*r*h,this.z=s*r*h+a*l*o,this.w=s*r*o+a*l*h),this},s.prototype.clone=function(){return new s(this.x,this.y,this.z,this.w)}},{"./Vec3":30}],29:[function(e,t,i){var n=e("./Vec3"),s=e("./Quaternion");function r(e){e=e||{},this.position=new n,e.position&&this.position.copy(e.position),this.quaternion=new s,e.quaternion&&this.quaternion.copy(e.quaternion)}t.exports=r;var o=new s;r.pointToLocalFrame=function(e,t,i,s){return s=s||new n,i.vsub(e,s),t.conjugate(o),o.vmult(s,s),s},r.prototype.pointToLocal=function(e,t){return r.pointToLocalFrame(this.position,this.quaternion,e,t)},r.pointToWorldFrame=function(e,t,i,s){return s=s||new n,t.vmult(i,s),s.vadd(e,s),s},r.prototype.pointToWorld=function(e,t){return r.pointToWorldFrame(this.position,this.quaternion,e,t)},r.prototype.vectorToWorldFrame=function(e,t){return t=t||new n,this.quaternion.vmult(e,t),t},r.vectorToWorldFrame=function(e,t,i){return e.vmult(t,i),i},r.vectorToLocalFrame=function(e,t,i,s){return s=s||new n,t.w*=-1,t.vmult(i,s),t.w*=-1,s}},{"./Quaternion":28,"./Vec3":30}],30:[function(e,t,i){t.exports=s;var n=e("./Mat3");function s(e,t,i){this.x=e||0,this.y=t||0,this.z=i||0}s.ZERO=new s(0,0,0),s.UNIT_X=new s(1,0,0),s.UNIT_Y=new s(0,1,0),s.UNIT_Z=new s(0,0,1),s.prototype.cross=function(e,t){var i=e.x,n=e.y,r=e.z,o=this.x,a=this.y,l=this.z;return(t=t||new s).x=a*r-l*n,t.y=l*i-o*r,t.z=o*n-a*i,t},s.prototype.set=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},s.prototype.setZero=function(){this.x=this.y=this.z=0},s.prototype.vadd=function(e,t){if(!t)return new s(this.x+e.x,this.y+e.y,this.z+e.z);t.x=e.x+this.x,t.y=e.y+this.y,t.z=e.z+this.z},s.prototype.vsub=function(e,t){if(!t)return new s(this.x-e.x,this.y-e.y,this.z-e.z);t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z},s.prototype.crossmat=function(){return new n([0,-this.z,this.y,this.z,0,-this.x,-this.y,this.x,0])},s.prototype.normalize=function(){var e=this.x,t=this.y,i=this.z,n=Math.sqrt(e*e+t*t+i*i);if(n>0){var s=1/n;this.x*=s,this.y*=s,this.z*=s}else this.x=0,this.y=0,this.z=0;return n},s.prototype.unit=function(e){e=e||new s;var t=this.x,i=this.y,n=this.z,r=Math.sqrt(t*t+i*i+n*n);return r>0?(r=1/r,e.x=t*r,e.y=i*r,e.z=n*r):(e.x=1,e.y=0,e.z=0),e},s.prototype.norm=function(){var e=this.x,t=this.y,i=this.z;return Math.sqrt(e*e+t*t+i*i)},s.prototype.length=s.prototype.norm,s.prototype.norm2=function(){return this.dot(this)},s.prototype.lengthSquared=s.prototype.norm2,s.prototype.distanceTo=function(e){var t=this.x,i=this.y,n=this.z,s=e.x,r=e.y,o=e.z;return Math.sqrt((s-t)*(s-t)+(r-i)*(r-i)+(o-n)*(o-n))},s.prototype.distanceSquared=function(e){var t=this.x,i=this.y,n=this.z,s=e.x,r=e.y,o=e.z;return(s-t)*(s-t)+(r-i)*(r-i)+(o-n)*(o-n)},s.prototype.mult=function(e,t){t=t||new s;var i=this.x,n=this.y,r=this.z;return t.x=e*i,t.y=e*n,t.z=e*r,t},s.prototype.scale=s.prototype.mult,s.prototype.dot=function(e){return this.x*e.x+this.y*e.y+this.z*e.z},s.prototype.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},s.prototype.negate=function(e){return(e=e||new s).x=-this.x,e.y=-this.y,e.z=-this.z,e};var r=new s,o=new s;s.prototype.tangents=function(e,t){var i=this.norm();if(i>0){var n=r,s=1/i;n.set(this.x*s,this.y*s,this.z*s);var a=o;Math.abs(n.x)<.9?(a.set(1,0,0),n.cross(a,e)):(a.set(0,1,0),n.cross(a,e)),n.cross(e,t)}else e.set(1,0,0),t.set(0,1,0)},s.prototype.toString=function(){return this.x+","+this.y+","+this.z},s.prototype.toArray=function(){return[this.x,this.y,this.z]},s.prototype.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this},s.prototype.lerp=function(e,t,i){var n=this.x,s=this.y,r=this.z;i.x=n+(e.x-n)*t,i.y=s+(e.y-s)*t,i.z=r+(e.z-r)*t},s.prototype.almostEquals=function(e,t){return void 0===t&&(t=1e-6),!(Math.abs(this.x-e.x)>t||Math.abs(this.y-e.y)>t||Math.abs(this.z-e.z)>t)},s.prototype.almostZero=function(e){return void 0===e&&(e=1e-6),!(Math.abs(this.x)>e||Math.abs(this.y)>e||Math.abs(this.z)>e)};var a=new s;s.prototype.isAntiparallelTo=function(e,t){return this.negate(a),a.almostEquals(e,t)},s.prototype.clone=function(){return new s(this.x,this.y,this.z)}},{"./Mat3":27}],31:[function(e,t,i){t.exports=h;var n=e("../utils/EventTarget"),s=(e("../shapes/Shape"),e("../math/Vec3")),r=e("../math/Mat3"),o=e("../math/Quaternion"),a=(e("../material/Material"),e("../collision/AABB")),l=e("../shapes/Box");function h(e){e=e||{},n.apply(this),this.id=h.idCounter++,this.world=null,this.preStep=null,this.postStep=null,this.vlambda=new s,this.collisionFilterGroup="number"==typeof e.collisionFilterGroup?e.collisionFilterGroup:1,this.collisionFilterMask="number"==typeof e.collisionFilterMask?e.collisionFilterMask:1,this.collisionResponse=!0,this.position=new s,e.position&&this.position.copy(e.position),this.previousPosition=new s,this.initPosition=new s,this.velocity=new s,e.velocity&&this.velocity.copy(e.velocity),this.initVelocity=new s,this.force=new s;var t="number"==typeof e.mass?e.mass:0;this.mass=t,this.invMass=t>0?1/t:0,this.material=e.material||null,this.linearDamping="number"==typeof e.linearDamping?e.linearDamping:.01,this.type=t<=0?h.STATIC:h.DYNAMIC,typeof e.type==typeof h.STATIC&&(this.type=e.type),this.allowSleep=void 0===e.allowSleep||e.allowSleep,this.sleepState=0,this.sleepSpeedLimit=void 0!==e.sleepSpeedLimit?e.sleepSpeedLimit:.1,this.sleepTimeLimit=void 0!==e.sleepTimeLimit?e.sleepTimeLimit:1,this.timeLastSleepy=0,this._wakeUpAfterNarrowphase=!1,this.torque=new s,this.quaternion=new o,e.quaternion&&this.quaternion.copy(e.quaternion),this.initQuaternion=new o,this.angularVelocity=new s,e.angularVelocity&&this.angularVelocity.copy(e.angularVelocity),this.initAngularVelocity=new s,this.interpolatedPosition=new s,this.interpolatedQuaternion=new o,this.shapes=[],this.shapeOffsets=[],this.shapeOrientations=[],this.inertia=new s,this.invInertia=new s,this.invInertiaWorld=new r,this.invMassSolve=0,this.invInertiaSolve=new s,this.invInertiaWorldSolve=new r,this.fixedRotation=void 0!==e.fixedRotation&&e.fixedRotation,this.angularDamping=void 0!==e.angularDamping?e.angularDamping:.01,this.aabb=new a,this.aabbNeedsUpdate=!0,this.wlambda=new s,e.shape&&this.addShape(e.shape),this.updateMassProperties()}h.prototype=new n,h.prototype.constructor=h,h.DYNAMIC=1,h.STATIC=2,h.KINEMATIC=4,h.AWAKE=0,h.SLEEPY=1,h.SLEEPING=2,h.idCounter=0,h.prototype.wakeUp=function(){var e=this.sleepState;this.sleepState=0,e===h.SLEEPING&&this.dispatchEvent({type:"wakeup"})},h.prototype.sleep=function(){this.sleepState=h.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0)},h.sleepyEvent={type:"sleepy"},h.sleepEvent={type:"sleep"},h.prototype.sleepTick=function(e){if(this.allowSleep){var t=this.sleepState,i=this.velocity.norm2()+this.angularVelocity.norm2(),n=Math.pow(this.sleepSpeedLimit,2);t===h.AWAKE&&i<n?(this.sleepState=h.SLEEPY,this.timeLastSleepy=e,this.dispatchEvent(h.sleepyEvent)):t===h.SLEEPY&&i>n?this.wakeUp():t===h.SLEEPY&&e-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(h.sleepEvent))}},h.prototype.updateSolveMassProperties=function(){this.sleepState===h.SLEEPING||this.type===h.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve.setZero(),this.invInertiaWorldSolve.setZero()):(this.invMassSolve=this.invMass,this.invInertiaSolve.copy(this.invInertia),this.invInertiaWorldSolve.copy(this.invInertiaWorld))},h.prototype.pointToLocalFrame=function(e,t){return t=t||new s,e.vsub(this.position,t),this.quaternion.conjugate().vmult(t,t),t},h.prototype.vectorToLocalFrame=function(e,t){return t=t||new s,this.quaternion.conjugate().vmult(e,t),t},h.prototype.pointToWorldFrame=function(e,t){return t=t||new s,this.quaternion.vmult(e,t),t.vadd(this.position,t),t},h.prototype.vectorToWorldFrame=function(e,t){return t=t||new s,this.quaternion.vmult(e,t),t};var c=new s,u=new o;h.prototype.addShape=function(e,t,i){var n=new s,r=new o;return t&&n.copy(t),i&&r.copy(i),this.shapes.push(e),this.shapeOffsets.push(n),this.shapeOrientations.push(r),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,this},h.prototype.updateBoundingRadius=function(){for(var e=this.shapes,t=this.shapeOffsets,i=e.length,n=0,s=0;s!==i;s++){var r=e[s];r.updateBoundingSphereRadius();var o=t[s].norm(),a=r.boundingSphereRadius;o+a>n&&(n=o+a)}this.boundingRadius=n};var d=new a;h.prototype.computeAABB=function(){for(var e=this.shapes,t=this.shapeOffsets,i=this.shapeOrientations,n=e.length,s=c,r=u,o=this.quaternion,a=this.aabb,l=d,h=0;h!==n;h++){var p=e[h];i[h].mult(o,r),r.vmult(t[h],s),s.vadd(this.position,s),p.calculateWorldAABB(s,r,l.lowerBound,l.upperBound),0===h?a.copy(l):a.extend(l)}this.aabbNeedsUpdate=!1};var p=new r,f=new r;new r,h.prototype.updateInertiaWorld=function(e){var t=this.invInertia;if(t.x!==t.y||t.y!==t.z||e){var i=p,n=f;i.setRotationFromQuaternion(this.quaternion),i.transpose(n),i.scale(t,i),i.mmult(n,this.invInertiaWorld)}};var _=new s,m=new s;h.prototype.applyForce=function(e,t){if(this.type===h.DYNAMIC){var i=_;t.vsub(this.position,i);var n=m;i.cross(e,n),this.force.vadd(e,this.force),this.torque.vadd(n,this.torque)}};var g=new s,v=new s;h.prototype.applyLocalForce=function(e,t){if(this.type===h.DYNAMIC){var i=g,n=v;this.vectorToWorldFrame(e,i),this.pointToWorldFrame(t,n),this.applyForce(i,n)}};var y=new s,x=new s,b=new s;h.prototype.applyImpulse=function(e,t){if(this.type===h.DYNAMIC){var i=y;t.vsub(this.position,i);var n=x;n.copy(e),n.mult(this.invMass,n),this.velocity.vadd(n,this.velocity);var s=b;i.cross(e,s),this.invInertiaWorld.vmult(s,s),this.angularVelocity.vadd(s,this.angularVelocity)}};var T=new s,S=new s;h.prototype.applyLocalImpulse=function(e,t){if(this.type===h.DYNAMIC){var i=T,n=S;this.vectorToWorldFrame(e,i),this.pointToWorldFrame(t,n),this.applyImpulse(i,n)}};var E=new s;h.prototype.updateMassProperties=function(){var e=E;this.invMass=this.mass>0?1/this.mass:0;var t=this.inertia,i=this.fixedRotation;this.computeAABB(),e.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),l.calculateInertia(e,this.mass,t),this.invInertia.set(t.x>0&&!i?1/t.x:0,t.y>0&&!i?1/t.y:0,t.z>0&&!i?1/t.z:0),this.updateInertiaWorld(!0)},h.prototype.getVelocityAtWorldPoint=function(e,t){var i=new s;return e.vsub(this.position,i),this.angularVelocity.cross(i,t),this.velocity.vadd(t,t),t}},{"../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(e,t,i){e("./Body");var n=e("../math/Vec3"),s=e("../math/Quaternion"),r=(e("../collision/RaycastResult"),e("../collision/Ray")),o=e("../objects/WheelInfo");function a(e){this.chassisBody=e.chassisBody,this.wheelInfos=[],this.sliding=!1,this.world=null,this.indexRightAxis=void 0!==e.indexRightAxis?e.indexRightAxis:1,this.indexForwardAxis=void 0!==e.indexForwardAxis?e.indexForwardAxis:0,this.indexUpAxis=void 0!==e.indexUpAxis?e.indexUpAxis:2}t.exports=a,new n,new n,new n;var l=new n,h=new n,c=new n;new r,a.prototype.addWheel=function(e){var t=new o(e=e||{}),i=this.wheelInfos.length;return this.wheelInfos.push(t),i},a.prototype.setSteeringValue=function(e,t){this.wheelInfos[t].steering=e},new n,a.prototype.applyEngineForce=function(e,t){this.wheelInfos[t].engineForce=e},a.prototype.setBrake=function(e,t){this.wheelInfos[t].brake=e},a.prototype.addToWorld=function(e){this.constraints,e.add(this.chassisBody);var t=this;this.preStepCallback=function(){t.updateVehicle(e.dt)},e.addEventListener("preStep",this.preStepCallback),this.world=e},a.prototype.getVehicleAxisWorld=function(e,t){t.set(0===e?1:0,1===e?1:0,2===e?1:0),this.chassisBody.vectorToWorldFrame(t,t)},a.prototype.updateVehicle=function(e){for(var t=this.wheelInfos,i=t.length,s=this.chassisBody,r=0;r<i;r++)this.updateWheelTransform(r);this.currentVehicleSpeedKmHour=3.6*s.velocity.norm();var o=new n;for(this.getVehicleAxisWorld(this.indexForwardAxis,o),o.dot(s.velocity)<0&&(this.currentVehicleSpeedKmHour*=-1),r=0;r<i;r++)this.castRay(t[r]);this.updateSuspension(e);var a=new n,l=new n;for(r=0;r<i;r++){var h=(p=t[r]).suspensionForce;h>p.maxSuspensionForce&&(h=p.maxSuspensionForce),p.raycastResult.hitNormalWorld.scale(h*e,a),p.raycastResult.hitPointWorld.vsub(s.position,l),s.applyImpulse(a,p.raycastResult.hitPointWorld)}this.updateFriction(e);var c=new n,u=new n,d=new n;for(r=0;r<i;r++){var p=t[r];s.getVelocityAtWorldPoint(p.chassisConnectionPointWorld,d);var f=1;if(1===this.indexUpAxis&&(f=-1),p.isInContact){this.getVehicleAxisWorld(this.indexForwardAxis,u);var _=u.dot(p.raycastResult.hitNormalWorld);p.raycastResult.hitNormalWorld.scale(_,c),u.vsub(c,u);var m=u.dot(d);p.deltaRotation=f*m*e/p.radius}!p.sliding&&p.isInContact||0===p.engineForce||!p.useCustomSlidingRotationalSpeed||(p.deltaRotation=(p.engineForce>0?1:-1)*p.customSlidingRotationalSpeed*e),Math.abs(p.brake)>Math.abs(p.engineForce)&&(p.deltaRotation=0),p.rotation+=p.deltaRotation,p.deltaRotation*=.99}},a.prototype.updateSuspension=function(e){for(var t=this.chassisBody.mass,i=this.wheelInfos,n=i.length,s=0;s<n;s++){var r=i[s];if(r.isInContact){var o,a=r.suspensionRestLength-r.suspensionLength;o=r.suspensionStiffness*a*r.clippedInvContactDotSuspension;var l=r.suspensionRelativeVelocity;o-=(l<0?r.dampingCompression:r.dampingRelaxation)*l,r.suspensionForce=o*t,r.suspensionForce<0&&(r.suspensionForce=0)}else r.suspensionForce=0}},a.prototype.removeFromWorld=function(e){this.constraints,e.remove(this.chassisBody),e.removeEventListener("preStep",this.preStepCallback),this.world=null};var u=new n,d=new n;a.prototype.castRay=function(e){var t=u,i=d;this.updateWheelTransformWorld(e);var s=this.chassisBody,r=-1,o=e.suspensionRestLength+e.radius;e.directionWorld.scale(o,t);var a=e.chassisConnectionPointWorld;a.vadd(t,i);var l=e.raycastResult;l.reset();var h=s.collisionResponse;s.collisionResponse=!1,this.world.rayTest(a,i,l),s.collisionResponse=h;var c=l.body;if(e.raycastResult.groundObject=0,c){r=l.distance,e.raycastResult.hitNormalWorld=l.hitNormalWorld,e.isInContact=!0;var p=l.distance;e.suspensionLength=p-e.radius;var f=e.suspensionRestLength-e.maxSuspensionTravel,_=e.suspensionRestLength+e.maxSuspensionTravel;e.suspensionLength<f&&(e.suspensionLength=f),e.suspensionLength>_&&(e.suspensionLength=_,e.raycastResult.reset());var m=e.raycastResult.hitNormalWorld.dot(e.directionWorld),g=new n;s.getVelocityAtWorldPoint(e.raycastResult.hitPointWorld,g);var v=e.raycastResult.hitNormalWorld.dot(g);if(m>=-.1)e.suspensionRelativeVelocity=0,e.clippedInvContactDotSuspension=10;else{var y=-1/m;e.suspensionRelativeVelocity=v*y,e.clippedInvContactDotSuspension=y}}else e.suspensionLength=e.suspensionRestLength+0*e.maxSuspensionTravel,e.suspensionRelativeVelocity=0,e.directionWorld.scale(-1,e.raycastResult.hitNormalWorld),e.clippedInvContactDotSuspension=1;return r},a.prototype.updateWheelTransformWorld=function(e){e.isInContact=!1;var t=this.chassisBody;t.pointToWorldFrame(e.chassisConnectionPointLocal,e.chassisConnectionPointWorld),t.vectorToWorldFrame(e.directionLocal,e.directionWorld),t.vectorToWorldFrame(e.axleLocal,e.axleWorld)},a.prototype.updateWheelTransform=function(e){var t=l,i=h,n=c,r=this.wheelInfos[e];this.updateWheelTransformWorld(r),r.directionLocal.scale(-1,t),i.copy(r.axleLocal),t.cross(i,n),n.normalize(),i.normalize();var o=r.steering,a=new s;a.setFromAxisAngle(t,o);var u=new s;u.setFromAxisAngle(i,r.rotation);var d=r.worldTransform.quaternion;this.chassisBody.quaternion.mult(a,d),d.mult(u,d),d.normalize();var p=r.worldTransform.position;p.copy(r.directionWorld),p.scale(r.suspensionLength,p),p.vadd(r.chassisConnectionPointWorld,p)};var p=[new n(1,0,0),new n(0,1,0),new n(0,0,1)];a.prototype.getWheelTransformWorld=function(e){return this.wheelInfos[e].worldTransform};var f=new n,_=[],m=[];a.prototype.updateFriction=function(e){for(var t=f,i=this.wheelInfos,s=i.length,r=this.chassisBody,o=m,a=_,l=0;l<s;l++)d=(A=i[l]).raycastResult.body,A.sideImpulse=0,A.forwardImpulse=0,o[l]||(o[l]=new n),a[l]||(a[l]=new n);for(l=0;l<s;l++)if(d=(A=i[l]).raycastResult.body){var h=a[l];this.getWheelTransformWorld(l).vectorToWorldFrame(p[this.indexRightAxis],h);var c=A.raycastResult.hitNormalWorld,u=h.dot(c);c.scale(u,t),h.vsub(t,h),h.normalize(),c.cross(h,o[l]),o[l].normalize(),A.sideImpulse=M(r,A.raycastResult.hitPointWorld,d,A.raycastResult.hitPointWorld,h),A.sideImpulse*=1}for(this.sliding=!1,l=0;l<s;l++){var d=(A=i[l]).raycastResult.body,g=0;if(A.slipInfo=1,d){var v=A.brake?A.brake:0;g=x(r,d,A.raycastResult.hitPointWorld,o[l],v);var y=v/(g+=A.engineForce*e);A.slipInfo*=y}if(A.forwardImpulse=0,A.skidInfo=1,d){A.skidInfo=1;var b=A.suspensionForce*e*A.frictionSlip,T=b*b;A.forwardImpulse=g;var S=.5*A.forwardImpulse,E=1*A.sideImpulse,C=S*S+E*E;A.sliding=!1,C>T&&(this.sliding=!0,A.sliding=!0,y=b/Math.sqrt(C),A.skidInfo*=y)}}if(this.sliding)for(l=0;l<s;l++)0!==(A=i[l]).sideImpulse&&A.skidInfo<1&&(A.forwardImpulse*=A.skidInfo,A.sideImpulse*=A.skidInfo);for(l=0;l<s;l++){var A=i[l],P=new n;if(P.copy(A.raycastResult.hitPointWorld),0!==A.forwardImpulse){var R=new n;o[l].scale(A.forwardImpulse,R),r.applyImpulse(R,P)}if(0!==A.sideImpulse){d=A.raycastResult.body;var I=new n;I.copy(A.raycastResult.hitPointWorld);var D=new n;a[l].scale(A.sideImpulse,D),r.pointToLocalFrame(P,P),P["xyz"[this.indexUpAxis]]*=A.rollInfluence,r.pointToWorldFrame(P,P),r.applyImpulse(D,P),D.scale(-1,D),d.applyImpulse(D,I)}}};var g=new n,v=new n,y=new n;function x(e,t,i,n,s){var r=0,o=i,a=g,l=v,h=y;return e.getVelocityAtWorldPoint(o,a),t.getVelocityAtWorldPoint(o,l),a.vsub(l,h),s<(r=-n.dot(h)*(1/(C(e,i,n)+C(t,i,n))))&&(r=s),r<-s&&(r=-s),r}var b=new n,T=new n,S=new n,E=new n;function C(e,t,i){var n=b,s=T,r=S,o=E;return t.vsub(e.position,n),n.cross(i,s),e.invInertiaWorld.vmult(s,o),o.cross(n,r),e.invMass+i.dot(r)}var A=new n,P=new n,R=new n;function M(e,t,i,n,s,r){if(s.norm2()>1.1)return 0;var o=A,a=P,l=R;return e.getVelocityAtWorldPoint(t,o),i.getVelocityAtWorldPoint(n,a),o.vsub(a,l),-.2*s.dot(l)*(1/(e.invMass+i.invMass))}},{"../collision/Ray":9,"../collision/RaycastResult":10,"../math/Quaternion":28,"../math/Vec3":30,"../objects/WheelInfo":36,"./Body":31}],33:[function(e,t,i){var n=e("./Body"),s=e("../shapes/Sphere"),r=e("../shapes/Box"),o=e("../math/Vec3"),a=e("../constraints/HingeConstraint");function l(e){if(this.wheelBodies=[],this.coordinateSystem=void 0===e.coordinateSystem?new o(1,2,3):e.coordinateSystem.clone(),this.chassisBody=e.chassisBody,!this.chassisBody){var t=new r(new o(5,2,.5));this.chassisBody=new n(1,t)}this.constraints=[],this.wheelAxes=[],this.wheelForces=[]}t.exports=l,l.prototype.addWheel=function(e){var t=(e=e||{}).body;t||(t=new n(1,new s(1.2))),this.wheelBodies.push(t),this.wheelForces.push(0),new o;var i=void 0!==e.position?e.position.clone():new o,r=new o;this.chassisBody.pointToWorldFrame(i,r),t.position.set(r.x,r.y,r.z);var l=void 0!==e.axis?e.axis.clone():new o(0,1,0);this.wheelAxes.push(l);var h=new a(this.chassisBody,t,{pivotA:i,axisA:l,pivotB:o.ZERO,axisB:l,collideConnected:!1});return this.constraints.push(h),this.wheelBodies.length-1},l.prototype.setSteeringValue=function(e,t){var i=this.wheelAxes[t],n=Math.cos(e),s=Math.sin(e),r=i.x,o=i.y;this.constraints[t].axisA.set(n*r-s*o,s*r+n*o,0)},l.prototype.setMotorSpeed=function(e,t){var i=this.constraints[t];i.enableMotor(),i.motorTargetVelocity=e},l.prototype.disableMotor=function(e){this.constraints[e].disableMotor()};var h=new o;l.prototype.setWheelForce=function(e,t){this.wheelForces[t]=e},l.prototype.applyWheelForce=function(e,t){var i=this.wheelAxes[t],n=this.wheelBodies[t],s=n.torque;i.scale(e,h),n.vectorToWorldFrame(h,h),s.vadd(h,s)},l.prototype.addToWorld=function(e){for(var t=this.constraints,i=this.wheelBodies.concat([this.chassisBody]),n=0;n<i.length;n++)e.add(i[n]);for(n=0;n<t.length;n++)e.addConstraint(t[n]);e.addEventListener("preStep",this._update.bind(this))},l.prototype._update=function(){for(var e=this.wheelForces,t=0;t<e.length;t++)this.applyWheelForce(e[t],t)},l.prototype.removeFromWorld=function(e){for(var t=this.constraints,i=this.wheelBodies.concat([this.chassisBody]),n=0;n<i.length;n++)e.remove(i[n]);for(n=0;n<t.length;n++)e.removeConstraint(t[n])};var c=new o;l.prototype.getWheelSpeed=function(e){var t=this.wheelAxes[e],i=this.wheelBodies[e].angularVelocity;return this.chassisBody.vectorToWorldFrame(t,c),i.dot(c)}},{"../constraints/HingeConstraint":15,"../math/Vec3":30,"../shapes/Box":37,"../shapes/Sphere":44,"./Body":31}],34:[function(e,t,i){t.exports=s,e("../shapes/Shape");var n=e("../math/Vec3");function s(){this.particles=[],this.density=1,this.smoothingRadius=1,this.speedOfSound=1,this.viscosity=.01,this.eps=1e-6,this.pressures=[],this.densities=[],this.neighbors=[]}e("../math/Quaternion"),e("../shapes/Particle"),e("../objects/Body"),e("../material/Material"),s.prototype.add=function(e){this.particles.push(e),this.neighbors.length<this.particles.length&&this.neighbors.push([])},s.prototype.remove=function(e){var t=this.particles.indexOf(e);-1!==t&&(this.particles.splice(t,1),this.neighbors.length>this.particles.length&&this.neighbors.pop())};var r=new n;s.prototype.getNeighbors=function(e,t){for(var i=this.particles.length,n=e.id,s=this.smoothingRadius*this.smoothingRadius,o=r,a=0;a!==i;a++){var l=this.particles[a];l.position.vsub(e.position,o),n!==l.id&&o.norm2()<s&&t.push(l)}};var o=new n,a=new n,l=new n,h=new n,c=new n,u=new n;s.prototype.update=function(){for(var e=this.particles.length,t=o,i=this.speedOfSound,n=this.eps,s=0;s!==e;s++){var r=this.particles[s];(E=this.neighbors[s]).length=0,this.getNeighbors(r,E),E.push(this.particles[s]);for(var d=E.length,p=0,f=0;f!==d;f++){r.position.vsub(E[f].position,t);var _=t.norm(),m=this.w(_);p+=E[f].mass*m}this.densities[s]=p,this.pressures[s]=i*i*(this.densities[s]-this.density)}var g=a,v=l,y=h,x=c,b=u;for(s=0;s!==e;s++){var T,S,E,C=this.particles[s];for(g.set(0,0,0),v.set(0,0,0),d=(E=this.neighbors[s]).length,f=0;f!==d;f++){var A=E[f];C.position.vsub(A.position,x);var P=x.norm();T=-A.mass*(this.pressures[s]/(this.densities[s]*this.densities[s]+n)+this.pressures[f]/(this.densities[f]*this.densities[f]+n)),this.gradw(x,y),y.mult(T,y),g.vadd(y,g),A.velocity.vsub(C.velocity,b),b.mult(1/(1e-4+this.densities[s]*this.densities[f])*this.viscosity*A.mass,b),S=this.nablaw(P),b.mult(S,b),v.vadd(b,v)}v.mult(C.mass,v),g.mult(C.mass,g),C.force.vadd(v,C.force),C.force.vadd(g,C.force)}},s.prototype.w=function(e){var t=this.smoothingRadius;return 315/(64*Math.PI*Math.pow(t,9))*Math.pow(t*t-e*e,3)},s.prototype.gradw=function(e,t){var i=e.norm(),n=this.smoothingRadius;e.mult(945/(32*Math.PI*Math.pow(n,9))*Math.pow(n*n-i*i,2),t)},s.prototype.nablaw=function(e){var t=this.smoothingRadius;return 945/(32*Math.PI*Math.pow(t,9))*(t*t-e*e)*(7*e*e-3*t*t)}},{"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Particle":41,"../shapes/Shape":43}],35:[function(e,t,i){var n=e("../math/Vec3");function s(e,t,i){i=i||{},this.restLength="number"==typeof i.restLength?i.restLength:1,this.stiffness=i.stiffness||100,this.damping=i.damping||1,this.bodyA=e,this.bodyB=t,this.localAnchorA=new n,this.localAnchorB=new n,i.localAnchorA&&this.localAnchorA.copy(i.localAnchorA),i.localAnchorB&&this.localAnchorB.copy(i.localAnchorB),i.worldAnchorA&&this.setWorldAnchorA(i.worldAnchorA),i.worldAnchorB&&this.setWorldAnchorB(i.worldAnchorB)}t.exports=s,s.prototype.setWorldAnchorA=function(e){this.bodyA.pointToLocalFrame(e,this.localAnchorA)},s.prototype.setWorldAnchorB=function(e){this.bodyB.pointToLocalFrame(e,this.localAnchorB)},s.prototype.getWorldAnchorA=function(e){this.bodyA.pointToWorldFrame(this.localAnchorA,e)},s.prototype.getWorldAnchorB=function(e){this.bodyB.pointToWorldFrame(this.localAnchorB,e)};var r=new n,o=new n,a=new n,l=new n,h=new n,c=new n,u=new n,d=new n,p=new n,f=new n,_=new n;s.prototype.applyForce=function(){var e=this.stiffness,t=this.damping,i=this.restLength,n=this.bodyA,s=this.bodyB,m=r,g=o,v=a,y=l,x=_,b=h,T=c,S=u,E=d,C=p,A=f;this.getWorldAnchorA(b),this.getWorldAnchorB(T),b.vsub(n.position,S),T.vsub(s.position,E),T.vsub(b,m);var P=m.norm();g.copy(m),g.normalize(),s.velocity.vsub(n.velocity,v),s.angularVelocity.cross(E,x),v.vadd(x,v),n.angularVelocity.cross(S,x),v.vsub(x,v),g.mult(-e*(P-i)-t*v.dot(g),y),n.force.vsub(y,n.force),s.force.vadd(y,s.force),S.cross(y,C),E.cross(y,A),n.torque.vsub(C,n.torque),s.torque.vadd(A,s.torque)}},{"../math/Vec3":30}],36:[function(e,t,i){var n=e("../math/Vec3"),s=e("../math/Transform"),r=e("../collision/RaycastResult"),o=e("../utils/Utils");function a(e){e=o.defaults(e,{chassisConnectionPointLocal:new n,chassisConnectionPointWorld:new n,directionLocal:new n,directionWorld:new n,axleLocal:new n,axleWorld:new n,suspensionRestLength:1,suspensionMaxLength:2,radius:1,suspensionStiffness:100,dampingCompression:10,dampingRelaxation:10,frictionSlip:1e4,steering:0,rotation:0,deltaRotation:0,rollInfluence:.01,maxSuspensionForce:Number.MAX_VALUE,isFrontWheel:!0,clippedInvContactDotSuspension:1,suspensionRelativeVelocity:0,suspensionForce:0,skidInfo:0,suspensionLength:0,maxSuspensionTravel:1,useCustomSlidingRotationalSpeed:!1,customSlidingRotationalSpeed:-.1}),this.maxSuspensionTravel=e.maxSuspensionTravel,this.customSlidingRotationalSpeed=e.customSlidingRotationalSpeed,this.useCustomSlidingRotationalSpeed=e.useCustomSlidingRotationalSpeed,this.sliding=!1,this.chassisConnectionPointLocal=e.chassisConnectionPointLocal.clone(),this.chassisConnectionPointWorld=e.chassisConnectionPointWorld.clone(),this.directionLocal=e.directionLocal.clone(),this.directionWorld=e.directionWorld.clone(),this.axleLocal=e.axleLocal.clone(),this.axleWorld=e.axleWorld.clone(),this.suspensionRestLength=e.suspensionRestLength,this.suspensionMaxLength=e.suspensionMaxLength,this.radius=e.radius,this.suspensionStiffness=e.suspensionStiffness,this.dampingCompression=e.dampingCompression,this.dampingRelaxation=e.dampingRelaxation,this.frictionSlip=e.frictionSlip,this.steering=0,this.rotation=0,this.deltaRotation=0,this.rollInfluence=e.rollInfluence,this.maxSuspensionForce=e.maxSuspensionForce,this.engineForce=0,this.brake=0,this.isFrontWheel=e.isFrontWheel,this.clippedInvContactDotSuspension=1,this.suspensionRelativeVelocity=0,this.suspensionForce=0,this.skidInfo=0,this.suspensionLength=0,this.sideImpulse=0,this.forwardImpulse=0,this.raycastResult=new r,this.worldTransform=new s,this.isInContact=!1}t.exports=a;var l=new n,h=new n;l=new n,a.prototype.updateWheel=function(e){var t=this.raycastResult;if(this.isInContact){var i=t.hitNormalWorld.dot(t.directionWorld);t.hitPointWorld.vsub(e.position,h),e.getVelocityAtWorldPoint(h,l);var n=t.hitNormalWorld.dot(l);if(i>=-.1)this.suspensionRelativeVelocity=0,this.clippedInvContactDotSuspension=10;else{var s=-1/i;this.suspensionRelativeVelocity=n*s,this.clippedInvContactDotSuspension=s}}else t.suspensionLength=this.suspensionRestLength,this.suspensionRelativeVelocity=0,t.directionWorld.scale(-1,t.hitNormalWorld),this.clippedInvContactDotSuspension=1}},{"../collision/RaycastResult":10,"../math/Transform":29,"../math/Vec3":30,"../utils/Utils":53}],37:[function(e,t,i){t.exports=o;var n=e("./Shape"),s=e("../math/Vec3"),r=e("./ConvexPolyhedron");function o(e){n.call(this),this.type=n.types.BOX,this.halfExtents=e,this.convexPolyhedronRepresentation=null,this.updateConvexPolyhedronRepresentation(),this.updateBoundingSphereRadius()}o.prototype=new n,o.prototype.constructor=o,o.prototype.updateConvexPolyhedronRepresentation=function(){var e=this.halfExtents.x,t=this.halfExtents.y,i=this.halfExtents.z,n=s,o=[new n(-e,-t,-i),new n(e,-t,-i),new n(e,t,-i),new n(-e,t,-i),new n(-e,-t,i),new n(e,-t,i),new n(e,t,i),new n(-e,t,i)],a=(new n(0,0,1),new n(0,1,0),new n(1,0,0),new r(o,[[3,2,1,0],[4,5,6,7],[5,4,0,1],[2,3,7,6],[0,4,7,3],[1,2,6,5]]));this.convexPolyhedronRepresentation=a,a.material=this.material},o.prototype.calculateLocalInertia=function(e,t){return t=t||new s,o.calculateInertia(this.halfExtents,e,t),t},o.calculateInertia=function(e,t,i){var n=e;i.x=1/12*t*(2*n.y*2*n.y+2*n.z*2*n.z),i.y=1/12*t*(2*n.x*2*n.x+2*n.z*2*n.z),i.z=1/12*t*(2*n.y*2*n.y+2*n.x*2*n.x)},o.prototype.getSideNormals=function(e,t){var i=e,n=this.halfExtents;if(i[0].set(n.x,0,0),i[1].set(0,n.y,0),i[2].set(0,0,n.z),i[3].set(-n.x,0,0),i[4].set(0,-n.y,0),i[5].set(0,0,-n.z),void 0!==t)for(var s=0;s!==i.length;s++)t.vmult(i[s],i[s]);return i},o.prototype.volume=function(){return 8*this.halfExtents.x*this.halfExtents.y*this.halfExtents.z},o.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.halfExtents.norm()};var a=new s;new s,o.prototype.forEachWorldCorner=function(e,t,i){for(var n=this.halfExtents,s=[[n.x,n.y,n.z],[-n.x,n.y,n.z],[-n.x,-n.y,n.z],[-n.x,-n.y,-n.z],[n.x,-n.y,-n.z],[n.x,n.y,-n.z],[-n.x,n.y,-n.z],[n.x,-n.y,n.z]],r=0;r<s.length;r++)a.set(s[r][0],s[r][1],s[r][2]),t.vmult(a,a),e.vadd(a,a),i(a.x,a.y,a.z)};var l=[new s,new s,new s,new s,new s,new s,new s,new s];o.prototype.calculateWorldAABB=function(e,t,i,n){var s=this.halfExtents;l[0].set(s.x,s.y,s.z),l[1].set(-s.x,s.y,s.z),l[2].set(-s.x,-s.y,s.z),l[3].set(-s.x,-s.y,-s.z),l[4].set(s.x,-s.y,-s.z),l[5].set(s.x,s.y,-s.z),l[6].set(-s.x,s.y,-s.z),l[7].set(s.x,-s.y,s.z);var r=l[0];t.vmult(r,r),e.vadd(r,r),n.copy(r),i.copy(r);for(var o=1;o<8;o++){r=l[o],t.vmult(r,r),e.vadd(r,r);var a=r.x,h=r.y,c=r.z;a>n.x&&(n.x=a),h>n.y&&(n.y=h),c>n.z&&(n.z=c),a<i.x&&(i.x=a),h<i.y&&(i.y=h),c<i.z&&(i.z=c)}}},{"../math/Vec3":30,"./ConvexPolyhedron":38,"./Shape":43}],38:[function(e,t,i){t.exports=o;var n=e("./Shape"),s=e("../math/Vec3"),r=(e("../math/Quaternion"),e("../math/Transform"));function o(e,t,i){n.call(this),this.type=n.types.CONVEXPOLYHEDRON,this.vertices=e||[],this.worldVertices=[],this.worldVerticesNeedsUpdate=!0,this.faces=t||[],this.faceNormals=[],this.computeNormals(),this.worldFaceNormalsNeedsUpdate=!0,this.worldFaceNormals=[],this.uniqueEdges=[],this.uniqueAxes=i?i.slice():null,this.computeEdges(),this.updateBoundingSphereRadius()}o.prototype=new n,o.prototype.constructor=o;var a=new s;o.prototype.computeEdges=function(){var e=this.faces,t=this.vertices,i=(t.length,this.uniqueEdges);i.length=0;for(var n=a,s=0;s!==e.length;s++)for(var r=e[s],o=r.length,l=0;l!==o;l++){var h=(l+1)%o;t[r[l]].vsub(t[r[h]],n),n.normalize();for(var c=!1,u=0;u!==i.length;u++)if(i[u].almostEquals(n)||i[u].almostEquals(n)){c=!0;break}c||i.push(n.clone())}},o.prototype.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var e=0;e<this.faces.length;e++){for(var t=0;t<this.faces[e].length;t++)if(!this.vertices[this.faces[e][t]])throw new Error("Vertex "+this.faces[e][t]+" not found!");var i=this.faceNormals[e]||new s;this.getFaceNormal(e,i),i.negate(i),this.faceNormals[e]=i;var n=this.vertices[this.faces[e][0]];if(i.dot(n)<0)for(console.error(".faceNormals["+e+"] = Vec3("+i.toString()+") looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule."),t=0;t<this.faces[e].length;t++)console.warn(".vertices["+this.faces[e][t]+"] = Vec3("+this.vertices[this.faces[e][t]].toString()+")")}};var l=new s,h=new s;o.computeNormal=function(e,t,i,n){t.vsub(e,h),i.vsub(t,l),l.cross(h,n),n.isZero()||n.normalize()},o.prototype.getFaceNormal=function(e,t){var i=this.faces[e],n=this.vertices[i[0]],s=this.vertices[i[1]],r=this.vertices[i[2]];return o.computeNormal(n,s,r,t)};var c=new s;o.prototype.clipAgainstHull=function(e,t,i,n,r,o,a,l,h){for(var u=c,d=-1,p=-Number.MAX_VALUE,f=0;f<i.faces.length;f++){u.copy(i.faceNormals[f]),r.vmult(u,u);var _=u.dot(o);_>p&&(p=_,d=f)}for(var m=[],g=i.faces[d],v=g.length,y=0;y<v;y++){var x=i.vertices[g[y]],b=new s;b.copy(x),r.vmult(b,b),n.vadd(b,b),m.push(b)}d>=0&&this.clipFaceAgainstHull(o,e,t,m,a,l,h)};var u=new s,d=new s,p=new s,f=new s,_=new s,m=new s;o.prototype.findSeparatingAxis=function(e,t,i,n,s,r,o,a){var l=u,h=d,c=p,g=f,v=_,y=m,x=Number.MAX_VALUE,b=this;if(b.uniqueAxes)for(S=0;S!==b.uniqueAxes.length;S++){if(i.vmult(b.uniqueAxes[S],l),!1===(A=b.testSepAxis(l,e,t,i,n,s)))return!1;A<x&&(x=A,r.copy(l))}else for(var T=o?o.length:b.faces.length,S=0;S<T;S++){var E=o?o[S]:S;if(l.copy(b.faceNormals[E]),i.vmult(l,l),!1===(A=b.testSepAxis(l,e,t,i,n,s)))return!1;A<x&&(x=A,r.copy(l))}if(e.uniqueAxes)for(S=0;S!==e.uniqueAxes.length;S++){if(s.vmult(e.uniqueAxes[S],h),!1===(A=b.testSepAxis(h,e,t,i,n,s)))return!1;A<x&&(x=A,r.copy(h))}else{var C=a?a.length:e.faces.length;for(S=0;S<C;S++){var A;if(E=a?a[S]:S,h.copy(e.faceNormals[E]),s.vmult(h,h),!1===(A=b.testSepAxis(h,e,t,i,n,s)))return!1;A<x&&(x=A,r.copy(h))}}for(var P=0;P!==b.uniqueEdges.length;P++){i.vmult(b.uniqueEdges[P],g);for(var R=0;R!==e.uniqueEdges.length;R++)if(s.vmult(e.uniqueEdges[R],v),g.cross(v,y),!y.almostZero()){y.normalize();var M=b.testSepAxis(y,e,t,i,n,s);if(!1===M)return!1;M<x&&(x=M,r.copy(y))}}return n.vsub(t,c),c.dot(r)>0&&r.negate(r),!0};var g=[],v=[];o.prototype.testSepAxis=function(e,t,i,n,s,r){o.project(this,e,i,n,g),o.project(t,e,s,r,v);var a=g[0],l=g[1],h=v[0],c=v[1];if(a<c||h<l)return!1;var u=a-c,d=h-l;return u<d?u:d};var y=new s,x=new s;o.prototype.calculateLocalInertia=function(e,t){this.computeLocalAABB(y,x);var i=x.x-y.x,n=x.y-y.y,s=x.z-y.z;t.x=1/12*e*(2*n*2*n+2*s*2*s),t.y=1/12*e*(2*i*2*i+2*s*2*s),t.z=1/12*e*(2*n*2*n+2*i*2*i)},o.prototype.getPlaneConstantOfFace=function(e){var t=this.faces[e],i=this.faceNormals[e],n=this.vertices[t[0]];return-i.dot(n)};var b=new s,T=new s,S=new s,E=new s,C=new s,A=new s,P=new s,R=new s;o.prototype.clipFaceAgainstHull=function(e,t,i,n,s,r,o){for(var a=b,l=T,h=S,c=E,u=C,d=A,p=P,f=R,_=this,m=n,g=[],v=-1,y=Number.MAX_VALUE,x=0;x<_.faces.length;x++){a.copy(_.faceNormals[x]),i.vmult(a,a);var M=a.dot(e);M<y&&(y=M,v=x)}if(!(v<0)){var I=_.faces[v];I.connectedFaces=[];for(var D=0;D<_.faces.length;D++)for(var O=0;O<_.faces[D].length;O++)-1!==I.indexOf(_.faces[D][O])&&D!==v&&-1===I.connectedFaces.indexOf(D)&&I.connectedFaces.push(D);m.length;for(var w=I.length,N=0;N<w;N++){var F=_.vertices[I[N]],L=_.vertices[I[(N+1)%w]];F.vsub(L,l),h.copy(l),i.vmult(h,h),t.vadd(h,h),c.copy(this.faceNormals[v]),i.vmult(c,c),t.vadd(c,c),h.cross(c,u),u.negate(u),d.copy(F),i.vmult(d,d),t.vadd(d,d),d.dot(u);var B=I.connectedFaces[N];p.copy(this.faceNormals[B]);var U=this.getPlaneConstantOfFace(B);f.copy(p),i.vmult(f,f);var V=U-f.dot(t);for(this.clipFaceAgainstPlane(m,g,f,V);m.length;)m.shift();for(;g.length;)m.push(g.shift())}for(p.copy(this.faceNormals[v]),U=this.getPlaneConstantOfFace(v),f.copy(p),i.vmult(f,f),V=U-f.dot(t),D=0;D<m.length;D++){var k=f.dot(m[D])+V;if(k<=s&&(console.log("clamped: depth="+k+" to minDist="+s),k=s),k<=r){var G=m[D];if(k<=0){var z={point:G,normal:f,depth:k};o.push(z)}}}}},o.prototype.clipFaceAgainstPlane=function(e,t,i,n){var r,o,a=e.length;if(a<2)return t;var l=e[e.length-1],h=e[0];r=i.dot(l)+n;for(var c=0;c<a;c++){if(h=e[c],o=i.dot(h)+n,r<0)if(o<0)(u=new s).copy(h),t.push(u);else{var u=new s;l.lerp(h,r/(r-o),u),t.push(u)}else o<0&&(u=new s,l.lerp(h,r/(r-o),u),t.push(u),t.push(h));l=h,r=o}return t},o.prototype.computeWorldVertices=function(e,t){for(var i=this.vertices.length;this.worldVertices.length<i;)this.worldVertices.push(new s);for(var n=this.vertices,r=this.worldVertices,o=0;o!==i;o++)t.vmult(n[o],r[o]),e.vadd(r[o],r[o]);this.worldVerticesNeedsUpdate=!1},new s,o.prototype.computeLocalAABB=function(e,t){var i=this.vertices.length,n=this.vertices;e.set(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),t.set(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(var s=0;s<i;s++){var r=n[s];r.x<e.x?e.x=r.x:r.x>t.x&&(t.x=r.x),r.y<e.y?e.y=r.y:r.y>t.y&&(t.y=r.y),r.z<e.z?e.z=r.z:r.z>t.z&&(t.z=r.z)}},o.prototype.computeWorldFaceNormals=function(e){for(var t=this.faceNormals.length;this.worldFaceNormals.length<t;)this.worldFaceNormals.push(new s);for(var i=this.faceNormals,n=this.worldFaceNormals,r=0;r!==t;r++)e.vmult(i[r],n[r]);this.worldFaceNormalsNeedsUpdate=!1},o.prototype.updateBoundingSphereRadius=function(){for(var e=0,t=this.vertices,i=0,n=t.length;i!==n;i++){var s=t[i].norm2();s>e&&(e=s)}this.boundingSphereRadius=Math.sqrt(e)};var M=new s;o.prototype.calculateWorldAABB=function(e,t,i,n){for(var s,r,o,a,l,h,c=this.vertices.length,u=this.vertices,d=0;d<c;d++){M.copy(u[d]),t.vmult(M,M),e.vadd(M,M);var p=M;p.x<s||void 0===s?s=p.x:(p.x>a||void 0===a)&&(a=p.x),p.y<r||void 0===r?r=p.y:(p.y>l||void 0===l)&&(l=p.y),p.z<o||void 0===o?o=p.z:(p.z>h||void 0===h)&&(h=p.z)}i.set(s,r,o),n.set(a,l,h)},o.prototype.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},o.prototype.getAveragePointLocal=function(e){e=e||new s;for(var t=this.vertices.length,i=this.vertices,n=0;n<t;n++)e.vadd(i[n],e);return e.mult(1/t,e),e},o.prototype.transformAllPoints=function(e,t){var i=this.vertices.length,n=this.vertices;if(t){for(var s=0;s<i;s++){var r=n[s];t.vmult(r,r)}for(s=0;s<this.faceNormals.length;s++)r=this.faceNormals[s],t.vmult(r,r)}if(e)for(s=0;s<i;s++)(r=n[s]).vadd(e,r)};var I=new s,D=new s,O=new s;o.prototype.pointIsInside=function(e){var t=this.vertices.length,i=this.vertices,n=this.faces,s=this.faceNormals,r=this.faces.length,o=I;this.getAveragePointLocal(o);for(var a=0;a<r;a++){this.faces[a].length,t=s[a];var l=i[n[a][0]],h=D;e.vsub(l,h);var c=t.dot(h),u=O;o.vsub(l,u);var d=t.dot(u);if(c<0&&d>0||c>0&&d<0)return!1}return-1},new s;var w=new s,N=new s;o.project=function(e,t,i,n,s){var o=e.vertices.length,a=w,l=0,h=0,c=N,u=e.vertices;c.setZero(),r.vectorToLocalFrame(i,n,t,a),r.pointToLocalFrame(i,n,c,c);var d=c.dot(a);h=l=u[0].dot(a);for(var p=1;p<o;p++){var f=u[p].dot(a);f>l&&(l=f),f<h&&(h=f)}if((h-=d)>(l-=d)){var _=h;h=l,l=_}s[0]=l,s[1]=h}},{"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"./Shape":43}],39:[function(e,t,i){t.exports=o;var n=e("./Shape"),s=e("../math/Vec3"),r=(e("../math/Quaternion"),e("./ConvexPolyhedron"));function o(e,t,i,o){var a=o,l=[],h=[],c=[],u=[],d=[],p=Math.cos,f=Math.sin;l.push(new s(t*p(0),t*f(0),.5*-i)),u.push(0),l.push(new s(e*p(0),e*f(0),.5*i)),d.push(1);for(var _=0;_<a;_++){var m=2*Math.PI/a*(_+1),g=2*Math.PI/a*(_+.5);_<a-1?(l.push(new s(t*p(m),t*f(m),.5*-i)),u.push(2*_+2),l.push(new s(e*p(m),e*f(m),.5*i)),d.push(2*_+3),c.push([2*_+2,2*_+3,2*_+1,2*_])):c.push([0,1,2*_+1,2*_]),(a%2==1||_<a/2)&&h.push(new s(p(g),f(g),0))}c.push(d),h.push(new s(0,0,1));var v=[];for(_=0;_<u.length;_++)v.push(u[u.length-_-1]);c.push(v),this.type=n.types.CONVEXPOLYHEDRON,r.call(this,l,c,h)}o.prototype=new r},{"../math/Quaternion":28,"../math/Vec3":30,"./ConvexPolyhedron":38,"./Shape":43}],40:[function(e,t,i){var n=e("./Shape"),s=e("./ConvexPolyhedron"),r=e("../math/Vec3"),o=e("../utils/Utils");function a(e,t){t=o.defaults(t,{maxValue:null,minValue:null,elementSize:1}),this.data=e,this.maxValue=t.maxValue,this.minValue=t.minValue,this.elementSize=t.elementSize,null===t.minValue&&this.updateMinValue(),null===t.maxValue&&this.updateMaxValue(),this.cacheEnabled=!0,n.call(this),this.pillarConvex=new s,this.pillarOffset=new r,this.type=n.types.HEIGHTFIELD,this.updateBoundingSphereRadius(),this._cachedPillars={}}t.exports=a,a.prototype=new n,a.prototype.update=function(){this._cachedPillars={}},a.prototype.updateMinValue=function(){for(var e=this.data,t=e[0][0],i=0;i!==e.length;i++)for(var n=0;n!==e[i].length;n++){var s=e[i][n];s<t&&(t=s)}this.minValue=t},a.prototype.updateMaxValue=function(){for(var e=this.data,t=e[0][0],i=0;i!==e.length;i++)for(var n=0;n!==e[i].length;n++){var s=e[i][n];s>t&&(t=s)}this.maxValue=t},a.prototype.setHeightValueAtIndex=function(e,t,i){this.data[e][t]=i,this.clearCachedConvexTrianglePillar(e,t,!1),e>0&&(this.clearCachedConvexTrianglePillar(e-1,t,!0),this.clearCachedConvexTrianglePillar(e-1,t,!1)),t>0&&(this.clearCachedConvexTrianglePillar(e,t-1,!0),this.clearCachedConvexTrianglePillar(e,t-1,!1)),t>0&&e>0&&this.clearCachedConvexTrianglePillar(e-1,t-1,!0)},a.prototype.getRectMinMax=function(e,t,i,n,s){s=s||[];for(var r=this.data,o=this.minValue,a=e;a<=i;a++)for(var l=t;l<=n;l++){var h=r[a][l];h>o&&(o=h)}s[0]=this.minValue,s[1]=o},a.prototype.getIndexOfPosition=function(e,t,i,n){var s=this.elementSize,r=this.data,o=Math.floor(e/s),a=Math.floor(t/s);return i[0]=o,i[1]=a,n&&(o<0&&(o=0),a<0&&(a=0),o>=r.length-1&&(o=r.length-1),a>=r[0].length-1&&(a=r[0].length-1)),!(o<0||a<0||o>=r.length-1||a>=r[0].length-1)},a.prototype.getHeightAt=function(e,t,i){var n=[];this.getIndexOfPosition(e,t,n,i);var s=[];return this.getRectMinMax(n[0],n[1]+1,n[0],n[1]+1,s),(s[0]+s[1])/2},a.prototype.getCacheConvexTrianglePillarKey=function(e,t,i){return e+"_"+t+"_"+(i?1:0)},a.prototype.getCachedConvexTrianglePillar=function(e,t,i){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(e,t,i)]},a.prototype.setCachedConvexTrianglePillar=function(e,t,i,n,s){this._cachedPillars[this.getCacheConvexTrianglePillarKey(e,t,i)]={convex:n,offset:s}},a.prototype.clearCachedConvexTrianglePillar=function(e,t,i){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(e,t,i)]},a.prototype.getConvexTrianglePillar=function(e,t,i){var n=this.pillarConvex,o=this.pillarOffset;if(this.cacheEnabled){if(a=this.getCachedConvexTrianglePillar(e,t,i))return this.pillarConvex=a.convex,void(this.pillarOffset=a.offset);n=new s,o=new r,this.pillarConvex=n,this.pillarOffset=o}var a=this.data,l=this.elementSize,h=n.faces;n.vertices.length=6;for(var c=0;c<6;c++)n.vertices[c]||(n.vertices[c]=new r);for(h.length=5,c=0;c<5;c++)h[c]||(h[c]=[]);var u=n.vertices,d=(Math.min(a[e][t],a[e+1][t],a[e][t+1],a[e+1][t+1])-this.minValue)/2+this.minValue;i?(o.set((e+.75)*l,(t+.75)*l,d),u[0].set(.25*l,.25*l,a[e+1][t+1]-d),u[1].set(-.75*l,.25*l,a[e][t+1]-d),u[2].set(.25*l,-.75*l,a[e+1][t]-d),u[3].set(.25*l,.25*l,-d-1),u[4].set(-.75*l,.25*l,-d-1),u[5].set(.25*l,-.75*l,-d-1),h[0][0]=0,h[0][1]=1,h[0][2]=2,h[1][0]=5,h[1][1]=4,h[1][2]=3,h[2][0]=2,h[2][1]=5,h[2][2]=3,h[2][3]=0,h[3][0]=3,h[3][1]=4,h[3][2]=1,h[3][3]=0,h[4][0]=1,h[4][1]=4,h[4][2]=5,h[4][3]=2):(o.set((e+.25)*l,(t+.25)*l,d),u[0].set(-.25*l,-.25*l,a[e][t]-d),u[1].set(.75*l,-.25*l,a[e+1][t]-d),u[2].set(-.25*l,.75*l,a[e][t+1]-d),u[3].set(-.25*l,-.25*l,-d-1),u[4].set(.75*l,-.25*l,-d-1),u[5].set(-.25*l,.75*l,-d-1),h[0][0]=0,h[0][1]=1,h[0][2]=2,h[1][0]=5,h[1][1]=4,h[1][2]=3,h[2][0]=0,h[2][1]=2,h[2][2]=5,h[2][3]=3,h[3][0]=1,h[3][1]=0,h[3][2]=3,h[3][3]=4,h[4][0]=4,h[4][1]=5,h[4][2]=2,h[4][3]=1),n.computeNormals(),n.computeEdges(),n.updateBoundingSphereRadius(),this.setCachedConvexTrianglePillar(e,t,i,n,o)},a.prototype.calculateLocalInertia=function(e,t){return(t=t||new r).set(0,0,0),t},a.prototype.volume=function(){return Number.MAX_VALUE},a.prototype.calculateWorldAABB=function(e,t,i,n){i.set(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),n.set(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},a.prototype.updateBoundingSphereRadius=function(){var e=this.data,t=this.elementSize;this.boundingSphereRadius=new r(e.length*t,e[0].length*t,Math.max(Math.abs(this.maxValue),Math.abs(this.minValue))).norm()}},{"../math/Vec3":30,"../utils/Utils":53,"./ConvexPolyhedron":38,"./Shape":43}],41:[function(e,t,i){t.exports=r;var n=e("./Shape"),s=e("../math/Vec3");function r(){n.call(this),this.type=n.types.PARTICLE}r.prototype=new n,r.prototype.constructor=r,r.prototype.calculateLocalInertia=function(e,t){return(t=t||new s).set(0,0,0),t},r.prototype.volume=function(){return 0},r.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=0},r.prototype.calculateWorldAABB=function(e,t,i,n){i.copy(e),n.copy(e)}},{"../math/Vec3":30,"./Shape":43}],42:[function(e,t,i){t.exports=r;var n=e("./Shape"),s=e("../math/Vec3");function r(){n.call(this),this.type=n.types.PLANE,this.worldNormal=new s,this.worldNormalNeedsUpdate=!0,this.boundingSphereRadius=Number.MAX_VALUE}r.prototype=new n,r.prototype.constructor=r,r.prototype.computeWorldNormal=function(e){var t=this.worldNormal;t.set(0,0,1),e.vmult(t,t),this.worldNormalNeedsUpdate=!1},r.prototype.calculateLocalInertia=function(e,t){return t||new s},r.prototype.volume=function(){return Number.MAX_VALUE};var o=new s;r.prototype.calculateWorldAABB=function(e,t,i,n){o.set(0,0,1),t.vmult(o,o);var s=Number.MAX_VALUE;i.set(-s,-s,-s),n.set(s,s,s),1===o.x&&(n.x=e.x),1===o.y&&(n.y=e.y),1===o.z&&(n.z=e.z),-1===o.x&&(i.x=e.x),-1===o.y&&(i.y=e.y),-1===o.z&&(i.z=e.z)},r.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=Number.MAX_VALUE}},{"../math/Vec3":30,"./Shape":43}],43:[function(e,t,i){t.exports=n;var n=e("./Shape");function n(){this.id=n.idCounter++,this.type=0,this.boundingSphereRadius=0,this.collisionResponse=!0,this.material=null}e("../math/Vec3"),e("../math/Quaternion"),e("../material/Material"),n.prototype.constructor=n,n.prototype.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},n.prototype.volume=function(){throw"volume() not implemented for shape type "+this.type},n.prototype.calculateLocalInertia=function(e,t){throw"calculateLocalInertia() not implemented for shape type "+this.type},n.idCounter=0,n.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(e,t,i){t.exports=r;var n=e("./Shape"),s=e("../math/Vec3");function r(e){if(n.call(this),this.radius=void 0!==e?Number(e):1,this.type=n.types.SPHERE,this.radius<0)throw new Error("The sphere radius cannot be negative.");this.updateBoundingSphereRadius()}r.prototype=new n,r.prototype.constructor=r,r.prototype.calculateLocalInertia=function(e,t){t=t||new s;var i=2*e*this.radius*this.radius/5;return t.x=i,t.y=i,t.z=i,t},r.prototype.volume=function(){return 4*Math.PI*this.radius/3},r.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},r.prototype.calculateWorldAABB=function(e,t,i,n){for(var s=this.radius,r=["x","y","z"],o=0;o<r.length;o++){var a=r[o];i[a]=e[a]-s,n[a]=e[a]+s}}},{"../math/Vec3":30,"./Shape":43}],45:[function(e,t,i){t.exports=l;var n=e("./Shape"),s=e("../math/Vec3"),r=(e("../math/Quaternion"),e("../math/Transform")),o=e("../collision/AABB"),a=e("../utils/Octree");function l(e,t){n.call(this),this.type=n.types.TRIMESH,this.vertices=new Float32Array(e),this.indices=new Int16Array(t),this.normals=new Float32Array(t.length),this.aabb=new o,this.edges=null,this.scale=new s(1,1,1),this.tree=new a,this.updateEdges(),this.updateNormals(),this.updateAABB(),this.updateBoundingSphereRadius(),this.updateTree()}l.prototype=new n,l.prototype.constructor=l;var h=new s;l.prototype.updateTree=function(){var e=this.tree;e.reset(),e.aabb.copy(this.aabb);var t=this.scale;e.aabb.lowerBound.x*=1/t.x,e.aabb.lowerBound.y*=1/t.y,e.aabb.lowerBound.z*=1/t.z,e.aabb.upperBound.x*=1/t.x,e.aabb.upperBound.y*=1/t.y,e.aabb.upperBound.z*=1/t.z;for(var i=new o,n=new s,r=new s,a=new s,l=[n,r,a],h=0;h<this.indices.length/3;h++){var c=3*h;this._getUnscaledVertex(this.indices[c],n),this._getUnscaledVertex(this.indices[c+1],r),this._getUnscaledVertex(this.indices[c+2],a),i.setFromPoints(l),e.insert(i,h)}e.removeEmptyNodes()};var c=new o;l.prototype.getTrianglesInAABB=function(e,t){c.copy(e);var i=this.scale,n=i.x,s=i.y,r=i.z,o=c.lowerBound,a=c.upperBound;return o.x/=n,o.y/=s,o.z/=r,a.x/=n,a.y/=s,a.z/=r,this.tree.aabbQuery(c,t)},l.prototype.setScale=function(e){var t=this.scale.x===this.scale.y===this.scale.z,i=e.x===e.y===e.z;t&&i||this.updateNormals(),this.scale.copy(e),this.updateAABB(),this.updateBoundingSphereRadius()},l.prototype.updateNormals=function(){for(var e=h,t=this.normals,i=0;i<this.indices.length/3;i++){var n=3*i,s=this.indices[n],r=this.indices[n+1],o=this.indices[n+2];this.getVertex(s,_),this.getVertex(r,m),this.getVertex(o,g),l.computeNormal(m,_,g,e),t[n]=e.x,t[n+1]=e.y,t[n+2]=e.z}},l.prototype.updateEdges=function(){for(var e={},t=function(t,i){e[s<r?s+"_"+r:r+"_"+s]=!0},i=0;i<this.indices.length/3;i++){var n=3*i,s=this.indices[n],r=this.indices[n+1];this.indices[n+2];t(),t(),t()}var o=Object.keys(e);for(this.edges=new Int16Array(2*o.length),i=0;i<o.length;i++){var a=o[i].split("_");this.edges[2*i]=parseInt(a[0],10),this.edges[2*i+1]=parseInt(a[1],10)}},l.prototype.getEdgeVertex=function(e,t,i){var n=this.edges[2*e+(t?1:0)];this.getVertex(n,i)};var u=new s,d=new s;l.prototype.getEdgeVector=function(e,t){var i=u,n=d;this.getEdgeVertex(e,0,i),this.getEdgeVertex(e,1,n),n.vsub(i,t)};var p=new s,f=new s;l.computeNormal=function(e,t,i,n){t.vsub(e,f),i.vsub(t,p),p.cross(f,n),n.isZero()||n.normalize()};var _=new s,m=new s,g=new s;l.prototype.getVertex=function(e,t){var i=this.scale;return this._getUnscaledVertex(e,t),t.x*=i.x,t.y*=i.y,t.z*=i.z,t},l.prototype._getUnscaledVertex=function(e,t){var i=3*e,n=this.vertices;return t.set(n[i],n[i+1],n[i+2])},l.prototype.getWorldVertex=function(e,t,i,n){return this.getVertex(e,n),r.pointToWorldFrame(t,i,n,n),n},l.prototype.getTriangleVertices=function(e,t,i,n){var s=3*e;this.getVertex(this.indices[s],t),this.getVertex(this.indices[s+1],i),this.getVertex(this.indices[s+2],n)},l.prototype.getNormal=function(e,t){var i=3*e;return t.set(this.normals[i],this.normals[i+1],this.normals[i+2])};var v=new o;l.prototype.calculateLocalInertia=function(e,t){this.computeLocalAABB(v);var i=v.upperBound.x-v.lowerBound.x,n=v.upperBound.y-v.lowerBound.y,s=v.upperBound.z-v.lowerBound.z;return t.set(1/12*e*(2*n*2*n+2*s*2*s),1/12*e*(2*i*2*i+2*s*2*s),1/12*e*(2*n*2*n+2*i*2*i))};var y=new s;l.prototype.computeLocalAABB=function(e){var t=e.lowerBound,i=e.upperBound,n=this.vertices.length,s=(this.vertices,y);this.getVertex(0,s),t.copy(s),i.copy(s);for(var r=0;r!==n;r++)this.getVertex(r,s),s.x<t.x?t.x=s.x:s.x>i.x&&(i.x=s.x),s.y<t.y?t.y=s.y:s.y>i.y&&(i.y=s.y),s.z<t.z?t.z=s.z:s.z>i.z&&(i.z=s.z)},l.prototype.updateAABB=function(){this.computeLocalAABB(this.aabb)},l.prototype.updateBoundingSphereRadius=function(){for(var e=0,t=this.vertices,i=new s,n=0,r=t.length/3;n!==r;n++){this.getVertex(n,i);var o=i.norm2();o>e&&(e=o)}this.boundingSphereRadius=Math.sqrt(e)},new s;var x=new r,b=new o;l.prototype.calculateWorldAABB=function(e,t,i,n){var s=x,r=b;s.position=e,s.quaternion=t,this.aabb.toWorldFrame(s,r),i.copy(r.lowerBound),n.copy(r.upperBound)},l.prototype.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},l.createTorus=function(e,t,i,n,s){e=e||1,t=t||.5,i=i||8,n=n||6,s=s||2*Math.PI;for(var r=[],o=[],a=0;a<=i;a++)for(var h=0;h<=n;h++){var c=h/n*s,u=a/i*Math.PI*2,d=(e+t*Math.cos(u))*Math.cos(c),p=(e+t*Math.cos(u))*Math.sin(c),f=t*Math.sin(u);r.push(d,p,f)}for(a=1;a<=i;a++)for(h=1;h<=n;h++){var _=(n+1)*a+h-1,m=(n+1)*(a-1)+h-1,g=(n+1)*(a-1)+h,v=(n+1)*a+h;o.push(_,m,v),o.push(m,g,v)}return new l(r,o)}},{"../collision/AABB":3,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../utils/Octree":50,"./Shape":43}],46:[function(e,t,i){t.exports=s,e("../math/Vec3"),e("../math/Quaternion");var n=e("./Solver");function s(){n.call(this),this.iterations=10,this.tolerance=1e-7}s.prototype=new n;var r=[],o=[],a=[];s.prototype.solve=function(e,t){var i,n,s,l,h,c=0,u=this.iterations,d=this.tolerance*this.tolerance,p=this.equations,f=p.length,_=t.bodies,m=_.length,g=e;if(0!==f)for(var v=0;v!==m;v++)_[v].updateSolveMassProperties();var y=o,x=a,b=r;for(y.length=f,x.length=f,b.length=f,v=0;v!==f;v++){var T=p[v];b[v]=0,x[v]=T.computeB(g),y[v]=1/T.computeC()}if(0!==f){for(v=0;v!==m;v++){var S=(A=_[v]).vlambda,E=A.wlambda;S.set(0,0,0),E&&E.set(0,0,0)}for(c=0;c!==u;c++){l=0;for(var C=0;C!==f;C++)T=p[C],i=x[C],n=y[C],(h=b[C])+(s=n*(i-T.computeGWlambda()-T.eps*h))<T.minForce?s=T.minForce-h:h+s>T.maxForce&&(s=T.maxForce-h),b[C]+=s,l+=s>0?s:-s,T.addToWlambda(s);if(l*l<d)break}for(v=0;v!==m;v++){var A,P=(A=_[v]).velocity,R=A.angularVelocity;P.vadd(A.vlambda,P),R&&R.vadd(A.wlambda,R)}}return c}},{"../math/Quaternion":28,"../math/Vec3":30,"./Solver":47}],47:[function(e,t,i){function n(){this.equations=[]}t.exports=n,n.prototype.solve=function(e,t){return 0},n.prototype.addEquation=function(e){e.enabled&&this.equations.push(e)},n.prototype.removeEquation=function(e){var t=this.equations,i=t.indexOf(e);-1!==i&&t.splice(i,1)},n.prototype.removeAllEquations=function(){this.equations.length=0}},{}],48:[function(e,t,i){t.exports=r,e("../math/Vec3"),e("../math/Quaternion");var n=e("./Solver"),s=e("../objects/Body");function r(e){for(n.call(this),this.iterations=10,this.tolerance=1e-7,this.subsolver=e,this.nodes=[],this.nodePool=[];this.nodePool.length<128;)this.nodePool.push(this.createNode())}r.prototype=new n;var o=[],a=[],l={bodies:[]},h=s.STATIC;function c(e){for(var t=e.length,i=0;i!==t;i++){var n=e[i];if(!(n.visited||n.body.type&h))return n}return!1}var u=[];function d(e,t,i,n){for(u.push(e),e.visited=!0,t(e,i,n);u.length;)for(var s,r=u.pop();s=c(r.children);)s.visited=!0,t(s,i,n),u.push(s)}function p(e,t,i){t.push(e.body);for(var n=e.eqs.length,s=0;s!==n;s++){var r=e.eqs[s];-1===i.indexOf(r)&&i.push(r)}}function f(e,t){return t.id-e.id}r.prototype.createNode=function(){return{body:null,children:[],eqs:[],visited:!1}},r.prototype.solve=function(e,t){for(var i=o,n=this.nodePool,s=t.bodies,r=this.equations,h=r.length,u=s.length,_=this.subsolver;n.length<u;)n.push(this.createNode());i.length=u;for(var m=0;m<u;m++)i[m]=n[m];for(m=0;m!==u;m++){var g=i[m];g.body=s[m],g.children.length=0,g.eqs.length=0,g.visited=!1}for(var v=0;v!==h;v++){var y=r[v],x=(m=s.indexOf(y.bi),s.indexOf(y.bj)),b=i[m],T=i[x];b.children.push(T),b.eqs.push(y),T.children.push(b),T.eqs.push(y)}var S,E=0,C=a;_.tolerance=this.tolerance,_.iterations=this.iterations;for(var A=l;S=c(i);){C.length=0,A.bodies.length=0,d(S,p,A.bodies,C);var P=C.length;for(C=C.sort(f),m=0;m!==P;m++)_.addEquation(C[m]);_.solve(e,A),_.removeAllEquations(),E++}return E}},{"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"./Solver":47}],49:[function(e,t,i){var n=function(){};t.exports=n,n.prototype={constructor:n,addEventListener:function(e,t){void 0===this._listeners&&(this._listeners={});var i=this._listeners;return void 0===i[e]&&(i[e]=[]),-1===i[e].indexOf(t)&&i[e].push(t),this},hasEventListener:function(e,t){if(void 0===this._listeners)return!1;var i=this._listeners;return void 0!==i[e]&&-1!==i[e].indexOf(t)},removeEventListener:function(e,t){if(void 0===this._listeners)return this;var i=this._listeners;if(void 0===i[e])return this;var n=i[e].indexOf(t);return-1!==n&&i[e].splice(n,1),this},dispatchEvent:function(e){if(void 0===this._listeners)return this;var t=this._listeners[e.type];if(void 0!==t){e.target=this;for(var i=0,n=t.length;i<n;i++)t[i].call(this,e)}return this}}},{}],50:[function(e,t,i){var n=e("../collision/AABB"),s=e("../math/Vec3");function r(e){e=e||{},this.root=e.root||null,this.aabb=e.aabb?e.aabb.clone():new n,this.data=[],this.children=[]}function o(e,t){(t=t||{}).root=null,t.aabb=e,r.call(this,t),this.maxDepth=void 0!==t.maxDepth?t.maxDepth:8}t.exports=o,o.prototype=new r,r.prototype.reset=function(e,t){this.children.length=this.data.length=0},r.prototype.insert=function(e,t,i){var n=this.data;if(i=i||0,!this.aabb.contains(e))return!1;var s=this.children;if(i<(this.maxDepth||this.root.maxDepth)){var r=!1;s.length||(this.subdivide(),r=!0);for(var o=0;8!==o;o++)if(s[o].insert(e,t,i+1))return!0;r&&(s.length=0)}return n.push(t),!0};var a=new s;r.prototype.subdivide=function(){var e=this.aabb,t=e.lowerBound,i=e.upperBound,o=this.children;o.push(new r({aabb:new n({lowerBound:new s(0,0,0)})}),new r({aabb:new n({lowerBound:new s(1,0,0)})}),new r({aabb:new n({lowerBound:new s(1,1,0)})}),new r({aabb:new n({lowerBound:new s(1,1,1)})}),new r({aabb:new n({lowerBound:new s(0,1,1)})}),new r({aabb:new n({lowerBound:new s(0,0,1)})}),new r({aabb:new n({lowerBound:new s(1,0,1)})}),new r({aabb:new n({lowerBound:new s(0,1,0)})})),i.vsub(t,a),a.scale(.5,a);for(var l=this.root||this,h=0;8!==h;h++){var c=o[h];c.root=l;var u=c.aabb.lowerBound;u.x*=a.x,u.y*=a.y,u.z*=a.z,u.vadd(t,u),u.vadd(a,c.aabb.upperBound)}},r.prototype.aabbQuery=function(e,t){this.data,this.children;for(var i=[this];i.length;){var n=i.pop();n.aabb.overlaps(e)&&Array.prototype.push.apply(t,n.data),Array.prototype.push.apply(i,n.children)}return t};var l=new n;r.prototype.rayQuery=function(e,t,i){return e.getAABB(l),l.toLocalFrame(t,l),this.aabbQuery(l,i),i},r.prototype.removeEmptyNodes=function(){for(var e=[this];e.length;){for(var t=e.pop(),i=t.children.length-1;i>=0;i--)t.children[i].data.length||t.children.splice(i,1);Array.prototype.push.apply(e,t.children)}}},{"../collision/AABB":3,"../math/Vec3":30}],51:[function(e,t,i){function n(){this.objects=[],this.type=Object}t.exports=n,n.prototype.release=function(){for(var e=arguments.length,t=0;t!==e;t++)this.objects.push(arguments[t])},n.prototype.get=function(){return 0===this.objects.length?this.constructObject():this.objects.pop()},n.prototype.constructObject=function(){throw new Error("constructObject() not implemented in this Pool subclass yet!")}},{}],52:[function(e,t,i){function n(){this.data={keys:[]}}t.exports=n,n.prototype.get=function(e,t){if(e>t){var i=t;t=e,e=i}return this.data[e+"-"+t]},n.prototype.set=function(e,t,i){if(e>t){var n=t;t=e,e=n}var s=e+"-"+t;this.get(e,t)||this.data.keys.push(s),this.data[s]=i},n.prototype.reset=function(){for(var e=this.data,t=e.keys;t.length>0;)delete e[t.pop()]}},{}],53:[function(e,t,i){function n(){}t.exports=n,n.defaults=function(e,t){for(var i in e=e||{},t)i in e||(e[i]=t[i]);return e}},{}],54:[function(e,t,i){t.exports=r;var n=e("../math/Vec3"),s=e("./Pool");function r(){s.call(this),this.type=n}r.prototype=new s,r.prototype.constructObject=function(){return new n}},{"../math/Vec3":30,"./Pool":51}],55:[function(e,t,i){t.exports=d;var n=e("../collision/AABB"),s=e("../shapes/Shape"),r=e("../collision/Ray"),o=e("../math/Vec3"),a=e("../math/Transform"),l=(e("../shapes/ConvexPolyhedron"),e("../math/Quaternion")),h=(e("../solver/Solver"),e("../utils/Vec3Pool")),c=e("../equations/ContactEquation"),u=e("../equations/FrictionEquation");function d(e){this.contactPointPool=[],this.frictionEquationPool=[],this.result=[],this.frictionResult=[],this.v3pool=new h,this.world=e,this.currentContactMaterial=null,this.enableFrictionReduction=!1}d.prototype.createContactEquation=function(e,t,i,n,s,r){var o;this.contactPointPool.length?((o=this.contactPointPool.pop()).bi=e,o.bj=t):o=new c(e,t),o.enabled=e.collisionResponse&&t.collisionResponse&&i.collisionResponse&&n.collisionResponse;var a=this.currentContactMaterial;o.restitution=a.restitution,o.setSpookParams(a.contactEquationStiffness,a.contactEquationRelaxation,this.world.dt);var l=i.material||e.material,h=n.material||t.material;return l&&h&&l.restitution>=0&&h.restitution>=0&&(o.restitution=l.restitution*h.restitution),o.si=s||i,o.sj=r||n,o},d.prototype.createFrictionEquationsFromContact=function(e,t){var i=e.bi,n=e.bj,s=e.si,r=e.sj,o=this.world,a=this.currentContactMaterial,l=a.friction,h=s.material||i.material,c=r.material||n.material;if(h&&c&&h.friction>=0&&c.friction>=0&&(l=h.friction*c.friction),l>0){var d=l*o.gravity.length(),p=i.invMass+n.invMass;p>0&&(p=1/p);var f=this.frictionEquationPool,_=f.length?f.pop():new u(i,n,d*p),m=f.length?f.pop():new u(i,n,d*p);return _.bi=m.bi=i,_.bj=m.bj=n,_.minForce=m.minForce=-d*p,_.maxForce=m.maxForce=d*p,_.ri.copy(e.ri),_.rj.copy(e.rj),m.ri.copy(e.ri),m.rj.copy(e.rj),e.ni.tangents(_.t,m.t),_.setSpookParams(a.frictionEquationStiffness,a.frictionEquationRelaxation,o.dt),m.setSpookParams(a.frictionEquationStiffness,a.frictionEquationRelaxation,o.dt),_.enabled=m.enabled=e.enabled,t.push(_,m),!0}return!1};var p=new o,f=new o,_=new o;d.prototype.createFrictionFromAverage=function(e){var t=this.result[this.result.length-1];if(this.createFrictionEquationsFromContact(t,this.frictionResult)&&1!==e){var i=this.frictionResult[this.frictionResult.length-2],n=this.frictionResult[this.frictionResult.length-1];p.setZero(),f.setZero(),_.setZero();for(var s=t.bi,r=(t.bj,0);r!==e;r++)(t=this.result[this.result.length-1-r]).bodyA!==s?(p.vadd(t.ni,p),f.vadd(t.ri,f),_.vadd(t.rj,_)):(p.vsub(t.ni,p),f.vadd(t.rj,f),_.vadd(t.ri,_));var o=1/e;f.scale(o,i.ri),_.scale(o,i.rj),n.ri.copy(i.ri),n.rj.copy(i.rj),p.normalize(),p.tangents(i.t,n.t)}};var m=new o,g=new o,v=new l,y=new l;d.prototype.getContacts=function(e,t,i,n,s,r,o){this.contactPointPool=s,this.frictionEquationPool=o,this.result=n,this.frictionResult=r;for(var a=v,l=y,h=m,c=g,u=0,d=e.length;u!==d;u++){var p=e[u],f=t[u],_=null;p.material&&f.material&&(_=i.getContactMaterial(p.material,f.material)||null);for(var x=0;x<p.shapes.length;x++){p.quaternion.mult(p.shapeOrientations[x],a),p.quaternion.vmult(p.shapeOffsets[x],h),h.vadd(p.position,h);for(var b=p.shapes[x],T=0;T<f.shapes.length;T++){f.quaternion.mult(f.shapeOrientations[T],l),f.quaternion.vmult(f.shapeOffsets[T],c),c.vadd(f.position,c);var S=f.shapes[T];if(!(h.distanceTo(c)>b.boundingSphereRadius+S.boundingSphereRadius)){var E=null;b.material&&S.material&&(E=i.getContactMaterial(b.material,S.material)||null),this.currentContactMaterial=E||_||i.defaultContactMaterial;var C=this[b.type|S.type];C&&(b.type<S.type?C.call(this,b,S,h,c,a,l,p,f,b,S):C.call(this,S,b,c,h,l,a,f,p,b,S))}}}}},d.prototype[s.types.BOX|s.types.BOX]=d.prototype.boxBox=function(e,t,i,n,s,r,o,a){e.convexPolyhedronRepresentation.material=e.material,t.convexPolyhedronRepresentation.material=t.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,t.convexPolyhedronRepresentation.collisionResponse=t.collisionResponse,this.convexConvex(e.convexPolyhedronRepresentation,t.convexPolyhedronRepresentation,i,n,s,r,o,a,e,t)},d.prototype[s.types.BOX|s.types.CONVEXPOLYHEDRON]=d.prototype.boxConvex=function(e,t,i,n,s,r,o,a){e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexConvex(e.convexPolyhedronRepresentation,t,i,n,s,r,o,a,e,t)},d.prototype[s.types.BOX|s.types.PARTICLE]=d.prototype.boxParticle=function(e,t,i,n,s,r,o,a){e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexParticle(e.convexPolyhedronRepresentation,t,i,n,s,r,o,a,e,t)},d.prototype[s.types.SPHERE]=d.prototype.sphereSphere=function(e,t,i,n,s,r,o,a){var l=this.createContactEquation(o,a,e,t);n.vsub(i,l.ni),l.ni.normalize(),l.ri.copy(l.ni),l.rj.copy(l.ni),l.ri.mult(e.radius,l.ri),l.rj.mult(-t.radius,l.rj),l.ri.vadd(i,l.ri),l.ri.vsub(o.position,l.ri),l.rj.vadd(n,l.rj),l.rj.vsub(a.position,l.rj),this.result.push(l),this.createFrictionEquationsFromContact(l,this.frictionResult)};var x=new o,b=new o,T=new o;d.prototype[s.types.PLANE|s.types.TRIMESH]=d.prototype.planeTrimesh=function(e,t,i,n,s,r,l,h){var c=new o,u=x;u.set(0,0,1),s.vmult(u,u);for(var d=0;d<t.vertices.length/3;d++){t.getVertex(d,c);var p=new o;p.copy(c),a.pointToWorldFrame(n,r,p,c);var f=b;if(c.vsub(i,f),u.dot(f)<=0){var _=this.createContactEquation(l,h,e,t);_.ni.copy(u);var m=T;u.scale(f.dot(u),m),c.vsub(m,m),_.ri.copy(m),_.ri.vsub(l.position,_.ri),_.rj.copy(c),_.rj.vsub(h.position,_.rj),this.result.push(_),this.createFrictionEquationsFromContact(_,this.frictionResult)}}};var S=new o,E=new o,C=(new o,new o),A=new o,P=new o,R=new o,M=new o,I=new o,D=new o,O=new o,w=new o,N=new o,F=new o,L=new n,B=[];d.prototype[s.types.SPHERE|s.types.TRIMESH]=d.prototype.sphereTrimesh=function(e,t,i,n,s,o,l,h){var c=P,u=R,d=M,p=I,f=D,_=O,m=L,g=A,v=E,y=B;a.pointToLocalFrame(n,o,i,f);var x=e.radius;m.lowerBound.set(f.x-x,f.y-x,f.z-x),m.upperBound.set(f.x+x,f.y+x,f.z+x),t.getTrianglesInAABB(m,y);for(var b=C,T=e.radius*e.radius,U=0;U<y.length;U++)for(var V=0;V<3;V++)t.getVertex(t.indices[3*y[U]+V],b),b.vsub(f,v),v.norm2()<=T&&(g.copy(b),a.pointToWorldFrame(n,o,g,b),b.vsub(i,v),(z=this.createContactEquation(l,h,e,t)).ni.copy(v),z.ni.normalize(),z.ri.copy(z.ni),z.ri.scale(e.radius,z.ri),z.ri.vadd(i,z.ri),z.ri.vsub(l.position,z.ri),z.rj.copy(b),z.rj.vsub(h.position,z.rj),this.result.push(z),this.createFrictionEquationsFromContact(z,this.frictionResult));for(U=0;U<y.length;U++)for(V=0;V<3;V++){t.getVertex(t.indices[3*y[U]+V],c),t.getVertex(t.indices[3*y[U]+(V+1)%3],u),u.vsub(c,d),f.vsub(u,_);var k=_.dot(d);f.vsub(c,_);var G=_.dot(d);if(G>0&&k<0&&(f.vsub(c,_),p.copy(d),p.normalize(),G=_.dot(p),p.scale(G,_),_.vadd(c,_),(q=_.distanceTo(f))<e.radius)){var z=this.createContactEquation(l,h,e,t);_.vsub(f,z.ni),z.ni.normalize(),z.ni.scale(e.radius,z.ri),a.pointToWorldFrame(n,o,_,_),_.vsub(h.position,z.rj),a.vectorToWorldFrame(o,z.ni,z.ni),a.vectorToWorldFrame(o,z.ri,z.ri),this.result.push(z),this.createFrictionEquationsFromContact(z,this.frictionResult)}}for(var W=w,H=N,X=F,j=S,Y=(U=0,y.length);U!==Y;U++){t.getTriangleVertices(y[U],W,H,X),t.getNormal(y[U],j),f.vsub(W,_);var q=_.dot(j);j.scale(q,_),f.vsub(_,_),q=_.distanceTo(f),r.pointInTriangle(_,W,H,X)&&q<e.radius&&(z=this.createContactEquation(l,h,e,t),_.vsub(f,z.ni),z.ni.normalize(),z.ni.scale(e.radius,z.ri),a.pointToWorldFrame(n,o,_,_),_.vsub(h.position,z.rj),a.vectorToWorldFrame(o,z.ni,z.ni),a.vectorToWorldFrame(o,z.ri,z.ri),this.result.push(z),this.createFrictionEquationsFromContact(z,this.frictionResult))}y.length=0};var U=new o,V=new o;d.prototype[s.types.SPHERE|s.types.PLANE]=d.prototype.spherePlane=function(e,t,i,n,s,r,o,a){var l=this.createContactEquation(o,a,e,t);if(l.ni.set(0,0,1),r.vmult(l.ni,l.ni),l.ni.negate(l.ni),l.ni.normalize(),l.ni.mult(e.radius,l.ri),i.vsub(n,U),l.ni.mult(l.ni.dot(U),V),U.vsub(V,l.rj),-U.dot(l.ni)<=e.radius){var h=l.ri,c=l.rj;h.vadd(i,h),h.vsub(o.position,h),c.vadd(n,c),c.vsub(a.position,c),this.result.push(l),this.createFrictionEquationsFromContact(l,this.frictionResult)}};var k=new o,G=new o,z=new o;function W(e,t,i){for(var n=null,s=e.length,r=0;r!==s;r++){var o=e[r],a=k;e[(r+1)%s].vsub(o,a);var l=G;a.cross(t,l);var h=z;i.vsub(o,h);var c=l.dot(h);if(!(null===n||c>0&&!0===n||c<=0&&!1===n))return!1;null===n&&(n=c>0)}return!0}var H=new o,X=new o,j=new o,Y=new o,q=[new o,new o,new o,new o,new o,new o],K=new o,$=new o,Q=new o,Z=new o;d.prototype[s.types.SPHERE|s.types.BOX]=d.prototype.sphereBox=function(e,t,i,n,s,r,o,a){var l=this.v3pool,h=q;i.vsub(n,H),t.getSideNormals(h,r);for(var c=e.radius,u=!1,d=$,p=Q,f=Z,_=null,m=0,g=0,v=0,y=null,x=0,b=h.length;x!==b&&!1===u;x++){var T=X;T.copy(h[x]);var S=T.norm();T.normalize();var E=H.dot(T);if(E<S+c&&E>0){var C=j,A=Y;C.copy(h[(x+1)%3]),A.copy(h[(x+2)%3]);var P=C.norm(),R=A.norm();C.normalize(),A.normalize();var M=H.dot(C),I=H.dot(A);if(M<P&&M>-P&&I<R&&I>-R){var D=Math.abs(E-S-c);(null===y||D<y)&&(y=D,g=M,v=I,_=S,d.copy(T),p.copy(C),f.copy(A),m++)}}}if(m){u=!0;var O=this.createContactEquation(o,a,e,t);d.mult(-c,O.ri),O.ni.copy(d),O.ni.negate(O.ni),d.mult(_,d),p.mult(g,p),d.vadd(p,d),f.mult(v,f),d.vadd(f,O.rj),O.ri.vadd(i,O.ri),O.ri.vsub(o.position,O.ri),O.rj.vadd(n,O.rj),O.rj.vsub(a.position,O.rj),this.result.push(O),this.createFrictionEquationsFromContact(O,this.frictionResult)}for(var w=l.get(),N=K,F=0;2!==F&&!u;F++)for(var L=0;2!==L&&!u;L++)for(var B=0;2!==B&&!u;B++)w.set(0,0,0),F?w.vadd(h[0],w):w.vsub(h[0],w),L?w.vadd(h[1],w):w.vsub(h[1],w),B?w.vadd(h[2],w):w.vsub(h[2],w),n.vadd(w,N),N.vsub(i,N),N.norm2()<c*c&&(u=!0,(O=this.createContactEquation(o,a,e,t)).ri.copy(N),O.ri.normalize(),O.ni.copy(O.ri),O.ri.mult(c,O.ri),O.rj.copy(w),O.ri.vadd(i,O.ri),O.ri.vsub(o.position,O.ri),O.rj.vadd(n,O.rj),O.rj.vsub(a.position,O.rj),this.result.push(O),this.createFrictionEquationsFromContact(O,this.frictionResult));l.release(w),w=null;var U=l.get(),V=l.get(),k=(O=l.get(),l.get()),G=(D=l.get(),h.length);for(F=0;F!==G&&!u;F++)for(L=0;L!==G&&!u;L++)if(F%3!=L%3){h[L].cross(h[F],U),U.normalize(),h[F].vadd(h[L],V),O.copy(i),O.vsub(V,O),O.vsub(n,O);var z=O.dot(U);for(U.mult(z,k),B=0;B===F%3||B===L%3;)B++;D.copy(i),D.vsub(k,D),D.vsub(V,D),D.vsub(n,D);var W=Math.abs(z),J=D.norm();if(W<h[B].norm()&&J<c){u=!0;var ee=this.createContactEquation(o,a,e,t);V.vadd(k,ee.rj),ee.rj.copy(ee.rj),D.negate(ee.ni),ee.ni.normalize(),ee.ri.copy(ee.rj),ee.ri.vadd(n,ee.ri),ee.ri.vsub(i,ee.ri),ee.ri.normalize(),ee.ri.mult(c,ee.ri),ee.ri.vadd(i,ee.ri),ee.ri.vsub(o.position,ee.ri),ee.rj.vadd(n,ee.rj),ee.rj.vsub(a.position,ee.rj),this.result.push(ee),this.createFrictionEquationsFromContact(ee,this.frictionResult)}}l.release(U,V,O,k,D)};var J=new o,ee=new o,te=new o,ie=new o,ne=new o,se=new o,re=new o,oe=new o,ae=new o,le=new o;d.prototype[s.types.SPHERE|s.types.CONVEXPOLYHEDRON]=d.prototype.sphereConvex=function(e,t,i,n,s,r,o,a){var l=this.v3pool;i.vsub(n,J);for(var h=t.faceNormals,c=t.faces,u=t.vertices,d=e.radius,p=0;p!==u.length;p++){var f=u[p],_=ne;r.vmult(f,_),n.vadd(_,_);var m=ie;if(_.vsub(i,m),m.norm2()<d*d)return g=!0,(D=this.createContactEquation(o,a,e,t)).ri.copy(m),D.ri.normalize(),D.ni.copy(D.ri),D.ri.mult(d,D.ri),_.vsub(n,D.rj),D.ri.vadd(i,D.ri),D.ri.vsub(o.position,D.ri),D.rj.vadd(n,D.rj),D.rj.vsub(a.position,D.rj),this.result.push(D),void this.createFrictionEquationsFromContact(D,this.frictionResult)}for(var g=!1,v=(p=0,c.length);p!==v&&!1===g;p++){var y=h[p],x=c[p],b=se;r.vmult(y,b);var T=re;r.vmult(u[x[0]],T),T.vadd(n,T);var S=oe;b.mult(-d,S),i.vadd(S,S);var E=ae;S.vsub(T,E);var C=E.dot(b),A=le;if(i.vsub(T,A),C<0&&A.dot(b)>0){for(var P=[],R=0,M=x.length;R!==M;R++){var I=l.get();r.vmult(u[x[R]],I),n.vadd(I,I),P.push(I)}if(W(P,b,i)){g=!0;var D=this.createContactEquation(o,a,e,t);b.mult(-d,D.ri),b.negate(D.ni);var O=l.get();b.mult(-C,O);var w=l.get();b.mult(-d,w),i.vsub(n,D.rj),D.rj.vadd(w,D.rj),D.rj.vadd(O,D.rj),D.rj.vadd(n,D.rj),D.rj.vsub(a.position,D.rj),D.ri.vadd(i,D.ri),D.ri.vsub(o.position,D.ri),l.release(O),l.release(w),this.result.push(D),this.createFrictionEquationsFromContact(D,this.frictionResult),R=0;for(var N=P.length;R!==N;R++)l.release(P[R]);return}for(R=0;R!==x.length;R++){var F=l.get(),L=l.get();r.vmult(u[x[(R+1)%x.length]],F),r.vmult(u[x[(R+2)%x.length]],L),n.vadd(F,F),n.vadd(L,L);var B=ee;L.vsub(F,B);var U=te;B.unit(U);var V=l.get(),k=l.get();i.vsub(F,k);var G=k.dot(U);U.mult(G,V),V.vadd(F,V);var z=l.get();if(V.vsub(i,z),G>0&&G*G<B.norm2()&&z.norm2()<d*d){for(D=this.createContactEquation(o,a,e,t),V.vsub(n,D.rj),V.vsub(i,D.ni),D.ni.normalize(),D.ni.mult(d,D.ri),D.rj.vadd(n,D.rj),D.rj.vsub(a.position,D.rj),D.ri.vadd(i,D.ri),D.ri.vsub(o.position,D.ri),this.result.push(D),this.createFrictionEquationsFromContact(D,this.frictionResult),R=0,N=P.length;R!==N;R++)l.release(P[R]);return l.release(F),l.release(L),l.release(V),l.release(z),void l.release(k)}l.release(F),l.release(L),l.release(V),l.release(z),l.release(k)}for(R=0,N=P.length;R!==N;R++)l.release(P[R])}}},new o,new o,d.prototype[s.types.PLANE|s.types.BOX]=d.prototype.planeBox=function(e,t,i,n,s,r,o,a){t.convexPolyhedronRepresentation.material=t.material,t.convexPolyhedronRepresentation.collisionResponse=t.collisionResponse,this.planeConvex(e,t.convexPolyhedronRepresentation,i,n,s,r,o,a)};var he=new o,ce=new o,ue=new o,de=new o;d.prototype[s.types.PLANE|s.types.CONVEXPOLYHEDRON]=d.prototype.planeConvex=function(e,t,i,n,s,r,o,a){var l=he,h=ce;h.set(0,0,1),s.vmult(h,h);for(var c=0,u=ue,d=0;d!==t.vertices.length;d++)if(l.copy(t.vertices[d]),r.vmult(l,l),n.vadd(l,l),l.vsub(i,u),h.dot(u)<=0){var p=this.createContactEquation(o,a,e,t),f=de;h.mult(h.dot(u),f),l.vsub(f,f),f.vsub(i,p.ri),p.ni.copy(h),l.vsub(n,p.rj),p.ri.vadd(i,p.ri),p.ri.vsub(o.position,p.ri),p.rj.vadd(n,p.rj),p.rj.vsub(a.position,p.rj),this.result.push(p),c++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(p,this.frictionResult)}this.enableFrictionReduction&&c&&this.createFrictionFromAverage(c)};var pe=new o,fe=new o;d.prototype[s.types.CONVEXPOLYHEDRON]=d.prototype.convexConvex=function(e,t,i,n,s,r,o,a,l,h,c,u){var d=pe;if(!(i.distanceTo(n)>e.boundingSphereRadius+t.boundingSphereRadius)&&e.findSeparatingAxis(t,i,s,n,r,d,c,u)){var p=[],f=fe;e.clipAgainstHull(i,s,t,n,r,d,-100,100,p);for(var _=0,m=0;m!==p.length;m++){var g=this.createContactEquation(o,a,e,t,l,h),v=g.ri,y=g.rj;d.negate(g.ni),p[m].normal.negate(f),f.mult(p[m].depth,f),p[m].point.vadd(f,v),y.copy(p[m].point),v.vsub(i,v),y.vsub(n,y),v.vadd(i,v),v.vsub(o.position,v),y.vadd(n,y),y.vsub(a.position,y),this.result.push(g),_++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(g,this.frictionResult)}this.enableFrictionReduction&&_&&this.createFrictionFromAverage(_)}};var _e=new o,me=new o,ge=new o;d.prototype[s.types.PLANE|s.types.PARTICLE]=d.prototype.planeParticle=function(e,t,i,n,s,r,o,a){var l=_e;l.set(0,0,1),o.quaternion.vmult(l,l);var h=me;if(n.vsub(o.position,h),l.dot(h)<=0){var c=this.createContactEquation(a,o,t,e);c.ni.copy(l),c.ni.negate(c.ni),c.ri.set(0,0,0);var u=ge;l.mult(l.dot(n),u),n.vsub(u,u),c.rj.copy(u),this.result.push(c),this.createFrictionEquationsFromContact(c,this.frictionResult)}};var ve=new o;d.prototype[s.types.PARTICLE|s.types.SPHERE]=d.prototype.sphereParticle=function(e,t,i,n,s,r,o,a){var l=ve;if(l.set(0,0,1),n.vsub(i,l),l.norm2()<=e.radius*e.radius){var h=this.createContactEquation(a,o,t,e);l.normalize(),h.rj.copy(l),h.rj.mult(e.radius,h.rj),h.ni.copy(l),h.ni.negate(h.ni),h.ri.set(0,0,0),this.result.push(h),this.createFrictionEquationsFromContact(h,this.frictionResult)}};var ye=new l,xe=new o,be=(new o,new o),Te=new o,Se=new o;d.prototype[s.types.PARTICLE|s.types.CONVEXPOLYHEDRON]=d.prototype.convexParticle=function(e,t,i,n,s,r,o,a){var l=-1,h=be,c=Se,u=null,d=xe;if(d.copy(n),d.vsub(i,d),s.conjugate(ye),ye.vmult(d,d),e.pointIsInside(d)){e.worldVerticesNeedsUpdate&&e.computeWorldVertices(i,s),e.worldFaceNormalsNeedsUpdate&&e.computeWorldFaceNormals(s);for(var p=0,f=e.faces.length;p!==f;p++){var _=[e.worldVertices[e.faces[p][0]]],m=e.worldFaceNormals[p];n.vsub(_[0],Te);var g=-m.dot(Te);(null===u||Math.abs(g)<Math.abs(u))&&(u=g,l=p,h.copy(m))}if(-1!==l){var v=this.createContactEquation(a,o,t,e);h.mult(u,c),c.vadd(n,c),c.vsub(i,c),v.rj.copy(c),h.negate(v.ni),v.ri.set(0,0,0);var y=v.ri,x=v.rj;y.vadd(n,y),y.vsub(a.position,y),x.vadd(i,x),x.vsub(o.position,x),this.result.push(v),this.createFrictionEquationsFromContact(v,this.frictionResult)}else console.warn("Point found inside convex, but did not find penetrating face!")}},d.prototype[s.types.BOX|s.types.HEIGHTFIELD]=d.prototype.boxHeightfield=function(e,t,i,n,s,r,o,a){e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexHeightfield(e.convexPolyhedronRepresentation,t,i,n,s,r,o,a)};var Ee=new o,Ce=new o,Ae=[0];d.prototype[s.types.CONVEXPOLYHEDRON|s.types.HEIGHTFIELD]=d.prototype.convexHeightfield=function(e,t,i,n,s,r,o,l){var h=t.data,c=t.elementSize,u=e.boundingSphereRadius,d=Ce,p=Ae,f=Ee;a.pointToLocalFrame(n,r,i,f);var _=Math.floor((f.x-u)/c)-1,m=Math.ceil((f.x+u)/c)+1,g=Math.floor((f.y-u)/c)-1,v=Math.ceil((f.y+u)/c)+1;if(!(m<0||v<0||_>h.length||g>h[0].length)){_<0&&(_=0),m<0&&(m=0),g<0&&(g=0),v<0&&(v=0),_>=h.length&&(_=h.length-1),m>=h.length&&(m=h.length-1),v>=h[0].length&&(v=h[0].length-1),g>=h[0].length&&(g=h[0].length-1);var y=[];t.getRectMinMax(_,g,m,v,y);var x=y[0],b=y[1];if(!(f.z-u>b||f.z+u<x))for(var T=_;T<m;T++)for(var S=g;S<v;S++)t.getConvexTrianglePillar(T,S,!1),a.pointToWorldFrame(n,r,t.pillarOffset,d),i.distanceTo(d)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&this.convexConvex(e,t.pillarConvex,i,d,s,r,o,l,null,null,p,null),t.getConvexTrianglePillar(T,S,!0),a.pointToWorldFrame(n,r,t.pillarOffset,d),i.distanceTo(d)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&this.convexConvex(e,t.pillarConvex,i,d,s,r,o,l,null,null,p,null)}};var Pe=new o,Re=new o;d.prototype[s.types.SPHERE|s.types.HEIGHTFIELD]=d.prototype.sphereHeightfield=function(e,t,i,n,s,r,o,l){var h=t.data,c=e.radius,u=t.elementSize,d=Re,p=Pe;a.pointToLocalFrame(n,r,i,p);var f=Math.floor((p.x-c)/u)-1,_=Math.ceil((p.x+c)/u)+1,m=Math.floor((p.y-c)/u)-1,g=Math.ceil((p.y+c)/u)+1;if(!(_<0||g<0||f>h.length||g>h[0].length)){f<0&&(f=0),_<0&&(_=0),m<0&&(m=0),g<0&&(g=0),f>=h.length&&(f=h.length-1),_>=h.length&&(_=h.length-1),g>=h[0].length&&(g=h[0].length-1),m>=h[0].length&&(m=h[0].length-1);var v=[];t.getRectMinMax(f,m,_,g,v);var y=v[0],x=v[1];if(!(p.z-c>x||p.z+c<y))for(var b=this.result,T=f;T<_;T++)for(var S=m;S<g;S++){var E=b.length;if(t.getConvexTrianglePillar(T,S,!1),a.pointToWorldFrame(n,r,t.pillarOffset,d),i.distanceTo(d)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&this.sphereConvex(e,t.pillarConvex,i,d,s,r,o,l),t.getConvexTrianglePillar(T,S,!0),a.pointToWorldFrame(n,r,t.pillarOffset,d),i.distanceTo(d)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&this.sphereConvex(e,t.pillarConvex,i,d,s,r,o,l),b.length-E>2)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(e,t,i){t.exports=v;var n=e("../shapes/Shape"),s=e("../math/Vec3"),r=e("../math/Quaternion"),o=e("../solver/GSSolver"),a=(e("../utils/Vec3Pool"),e("../equations/ContactEquation"),e("../equations/FrictionEquation"),e("./Narrowphase")),l=e("../utils/EventTarget"),h=e("../collision/ArrayCollisionMatrix"),c=e("../material/Material"),u=e("../material/ContactMaterial"),d=e("../objects/Body"),p=e("../utils/TupleDictionary"),f=e("../collision/RaycastResult"),_=e("../collision/AABB"),m=e("../collision/Ray"),g=e("../collision/NaiveBroadphase");function v(){l.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 s,this.broadphase=new g,this.bodies=[],this.solver=new o,this.constraints=[],this.narrowphase=new a(this),this.collisionMatrix=new h,this.collisionMatrixPrevious=new h,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new p,this.defaultMaterial=new c("default"),this.defaultContactMaterial=new u(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}}v.prototype=new l,new _;var y=new m;if(v.prototype.getContactMaterial=function(e,t){return this.contactMaterialTable.get(e.id,t.id)},v.prototype.numObjects=function(){return this.bodies.length},v.prototype.collisionMatrixTick=function(){var e=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=e,this.collisionMatrix.reset()},v.prototype.add=v.prototype.addBody=function(e){-1===this.bodies.indexOf(e)&&(e.index=this.bodies.length,this.bodies.push(e),e.world=this,e.initPosition.copy(e.position),e.initVelocity.copy(e.velocity),e.timeLastSleepy=this.time,e instanceof d&&(e.initAngularVelocity.copy(e.angularVelocity),e.initQuaternion.copy(e.quaternion)),this.collisionMatrix.setNumObjects(this.bodies.length),this.addBodyEvent.body=e,this.dispatchEvent(this.addBodyEvent))},v.prototype.addConstraint=function(e){this.constraints.push(e)},v.prototype.removeConstraint=function(e){var t=this.constraints.indexOf(e);-1!==t&&this.constraints.splice(t,1)},v.prototype.rayTest=function(e,t,i){i instanceof f?this.raycastClosest(e,t,{skipBackfaces:!0},i):this.raycastAll(e,t,{skipBackfaces:!0},i)},v.prototype.raycastAll=function(e,t,i,n){return i.mode=m.ALL,i.from=e,i.to=t,i.callback=n,y.intersectWorld(this,i)},v.prototype.raycastAny=function(e,t,i,n){return i.mode=m.ANY,i.from=e,i.to=t,i.result=n,y.intersectWorld(this,i)},v.prototype.raycastClosest=function(e,t,i,n){return i.mode=m.CLOSEST,i.from=e,i.to=t,i.result=n,y.intersectWorld(this,i)},v.prototype.remove=function(e){e.world=null;var t=this.bodies.length-1,i=this.bodies,n=i.indexOf(e);if(-1!==n){i.splice(n,1);for(var s=0;s!==i.length;s++)i[s].index=s;this.collisionMatrix.setNumObjects(t),this.removeBodyEvent.body=e,this.dispatchEvent(this.removeBodyEvent)}},v.prototype.removeBody=v.prototype.remove,v.prototype.addMaterial=function(e){this.materials.push(e)},v.prototype.addContactMaterial=function(e){this.contactmaterials.push(e),this.contactMaterialTable.set(e.materials[0].id,e.materials[1].id,e)},"undefined"==typeof performance&&(performance={}),!performance.now){var x=Date.now();performance.timing&&performance.timing.navigationStart&&(x=performance.timing.navigationStart),performance.now=function(){return Date.now()-x}}var b=new s;v.prototype.step=function(e,t,i){if(i=i||10,0===(t=t||0))this.internalStep(e),this.time+=e;else{var n=Math.floor((this.time+t)/e)-Math.floor(this.time/e);n=Math.min(n,i);for(var s=performance.now(),r=0;r!==n&&(this.internalStep(e),!(performance.now()-s>1e3*e));r++);this.time+=t;for(var o=this.time%e/e,a=b,l=this.bodies,h=0;h!==l.length;h++){var c=l[h];c.type!==d.STATIC&&c.sleepState!==d.SLEEPING?(c.position.vsub(c.previousPosition,a),a.scale(o,a),c.position.vadd(a,c.interpolatedPosition)):(c.interpolatedPosition.copy(c.position),c.interpolatedQuaternion.copy(c.quaternion))}}};var T={type:"postStep"},S={type:"preStep"},E={type:"collide",body:null,contact:null},C=[],A=[],P=[],R=[],M=(new s,new s,new s,new s,new s,new s,new s,new s,new s,new r,new r),I=new r,D=new s;v.prototype.internalStep=function(e){this.dt=e;var t,i=this.contacts,s=P,r=R,o=this.numObjects(),a=this.bodies,l=this.solver,h=this.gravity,c=this.doProfiling,u=this.profile,p=d.DYNAMIC,f=this.constraints,_=A,m=(h.norm(),h.x),g=h.y,v=h.z,y=0;for(c&&(t=performance.now()),y=0;y!==o;y++)if((k=a[y]).type&p){var x=k.force,b=k.mass;x.x+=b*m,x.y+=b*g,x.z+=b*v}y=0;for(var O=this.subsystems.length;y!==O;y++)this.subsystems[y].update();c&&(t=performance.now()),s.length=0,r.length=0,this.broadphase.collisionPairs(this,s,r),c&&(u.broadphase=performance.now()-t);var w=f.length;for(y=0;y!==w;y++)if(!(z=f[y]).collideConnected)for(var N=s.length-1;N>=0;N-=1)(z.bodyA===s[N]&&z.bodyB===r[N]||z.bodyB===s[N]&&z.bodyA===r[N])&&(s.splice(N,1),r.splice(N,1));this.collisionMatrixTick(),c&&(t=performance.now());var F=C,L=i.length;for(y=0;y!==L;y++)F.push(i[y]);i.length=0;var B=this.frictionEquations.length;for(y=0;y!==B;y++)_.push(this.frictionEquations[y]);for(this.frictionEquations.length=0,this.narrowphase.getContacts(s,r,this,i,F,this.frictionEquations,_),c&&(u.narrowphase=performance.now()-t),c&&(t=performance.now()),y=0;y<this.frictionEquations.length;y++)l.addEquation(this.frictionEquations[y]);for(var U=i.length,V=0;V!==U;V++){var k=(z=i[V]).bi,G=z.bj;z.si,z.sj,(k.material&&G.material&&this.getContactMaterial(k.material,G.material)||this.defaultContactMaterial).friction,k.material&&G.material&&(k.material.friction>=0&&G.material.friction>=0&&(k.material.friction,G.material.friction),k.material.restitution>=0&&G.material.restitution>=0&&(z.restitution=k.material.restitution*G.material.restitution)),l.addEquation(z),k.allowSleep&&k.type===d.DYNAMIC&&k.sleepState===d.SLEEPING&&G.sleepState===d.AWAKE&&G.type!==d.STATIC&&G.velocity.norm2()+G.angularVelocity.norm2()>=2*Math.pow(G.sleepSpeedLimit,2)&&(k._wakeUpAfterNarrowphase=!0),G.allowSleep&&G.type===d.DYNAMIC&&G.sleepState===d.SLEEPING&&k.sleepState===d.AWAKE&&k.type!==d.STATIC&&k.velocity.norm2()+k.angularVelocity.norm2()>=2*Math.pow(k.sleepSpeedLimit,2)&&(G._wakeUpAfterNarrowphase=!0),this.collisionMatrix.set(k,G,!0),this.collisionMatrixPrevious.get(k,G)||(E.body=G,E.contact=z,k.dispatchEvent(E),E.body=k,G.dispatchEvent(E))}for(c&&(u.makeContactConstraints=performance.now()-t,t=performance.now()),y=0;y!==o;y++)(k=a[y])._wakeUpAfterNarrowphase&&(k.wakeUp(),k._wakeUpAfterNarrowphase=!1);for(w=f.length,y=0;y!==w;y++){var z;(z=f[y]).update(),N=0;for(var W=z.equations.length;N!==W;N++){var H=z.equations[N];l.addEquation(H)}}l.solve(e,this),c&&(u.solve=performance.now()-t),l.removeAllEquations();var X=Math.pow;for(y=0;y!==o;y++)if((k=a[y]).type&p){var j=X(1-k.linearDamping,e),Y=k.velocity;Y.mult(j,Y);var q=k.angularVelocity;if(q){var K=X(1-k.angularDamping,e);q.mult(K,q)}}for(this.dispatchEvent(S),y=0;y!==o;y++)(k=a[y]).preStep&&k.preStep.call(k);c&&(t=performance.now());var $=M,Q=I,Z=this.stepnumber,J=d.DYNAMIC|d.KINEMATIC,ee=Z%(this.quatNormalizeSkip+1)==0,te=this.quatNormalizeFast,ie=.5*e;for(n.types.PLANE,n.types.CONVEXPOLYHEDRON,y=0;y!==o;y++){var ne=a[y],se=ne.force,re=ne.torque;if(ne.type&J&&ne.sleepState!==d.SLEEPING){var oe=ne.velocity,ae=ne.angularVelocity,le=ne.position,he=ne.quaternion,ce=ne.invMass,ue=ne.invInertiaWorld;oe.x+=se.x*ce*e,oe.y+=se.y*ce*e,oe.z+=se.z*ce*e,ne.angularVelocity&&(ue.vmult(re,D),D.mult(e,D),D.vadd(ae,ae)),le.x+=oe.x*e,le.y+=oe.y*e,le.z+=oe.z*e,ne.angularVelocity&&($.set(ae.x,ae.y,ae.z,0),$.mult(he,Q),he.x+=ie*Q.x,he.y+=ie*Q.y,he.z+=ie*Q.z,he.w+=ie*Q.w,ee&&(te?he.normalizeFast():he.normalize())),ne.aabb&&(ne.aabbNeedsUpdate=!0),ne.updateInertiaWorld&&ne.updateInertiaWorld()}}for(this.clearForces(),this.broadphase.dirty=!0,c&&(u.integrate=performance.now()-t),this.time+=e,this.stepnumber+=1,this.dispatchEvent(T),y=0;y!==o;y++){var de=(k=a[y]).postStep;de&&de.call(k)}if(this.allowSleep)for(y=0;y!==o;y++)a[y].sleepTick(this.time)},v.prototype.clearForces=function(){for(var e=this.bodies,t=e.length,i=0;i!==t;i++){var n=e[i];n.force,n.torque,n.force.set(0,0,0),n.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)},3706:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},n.apply(this,arguments)},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};t.__esModule=!0,t.Ctx=void 0;var r=i(3876),o=i(9589),a=i(2329),l=i(5016),h=i(343),c=i(4019),u=i(2896),d=i(8810),p=function(){function e(){this.lazyEvtAttach=new h.LazyEvt,this.lazyEvtDetach=new h.LazyEvt,this.lazyEvtDoneOrAborted=new h.LazyEvt,this.handlers=new r.Polyfill,this.evtByHandler=new o.Polyfill}return e.prototype.onDoneOrAborted=function(e){this.lazyEvtDoneOrAborted.post(e)},e.prototype.waitFor=function(e){var t=this;return this.evtDoneOrAborted.waitFor(e).then((function(e){if("ABORTED"===e.type)throw e.error;return e.result}),(function(e){throw t.abort(e),e}))},e.prototype.abort=function(e){return this.__done(e)},e.prototype.done=function(e){return this.__done(void 0,e)},e.prototype.__done=function(e,t){var i,r,o=[];try{for(var a=s(this.handlers.values()),l=a.next();!l.done;l=a.next()){var h=l.value,c=this.evtByHandler.get(h);h.detach()&&o.push({handler:h,evt:c})}}catch(e){i={error:e}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(i)throw i.error}}return this.onDoneOrAborted(n(n({},e?{type:"ABORTED",error:e}:{type:"DONE",result:t}),{handlers:o})),o},e.prototype.getHandlers=function(){var e=this;return Array.from(this.handlers.values()).map((function(t){return{handler:t,evt:e.evtByHandler.get(t)}}))},e.prototype.zz__addHandler=function(e,t){a.assert(e.ctx===this),a.assert(l.typeGuard(e)),this.handlers.add(e),this.evtByHandler.set(e,t),this.lazyEvtAttach.post({handler:e,evt:t})},e.prototype.zz__removeHandler=function(e){a.assert(e.ctx===this),a.assert(l.typeGuard(e)),this.lazyEvtDetach.post({handler:e,evt:this.evtByHandler.get(e)}),this.handlers.delete(e)},e.__1=(u.defineAccessors(e.prototype,"evtDoneOrAborted",{get:function(){return this.lazyEvtDoneOrAborted.evt}}),u.defineAccessors(e.prototype,"evtAttach",{get:function(){return this.lazyEvtAttach.evt}}),void u.defineAccessors(e.prototype,"evtDetach",{get:function(){return this.lazyEvtDetach.evt}})),e}();t.Ctx=p;try{d.overwriteReadonlyProp(t.Ctx,"name","Ctx")}catch(e){}c.importProxy.Ctx=t.Ctx},4888:(e,t)=>{t.__esModule=!0,t.asNonPostable=void 0,t.asNonPostable=function(e){return e}},6558:(e,t)=>{t.__esModule=!0,t.asPostable=void 0,t.asPostable=function(e){return e}},1462:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(s,r){function o(e){try{l(n.next(e))}catch(e){r(e)}}function a(e){try{l(n.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))},s=this&&this.__generator||function(e,t){var i,n,s,r,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(i)throw new TypeError("Generator is already executing.");for(;o;)try{if(i=1,n&&(s=2&r[0]?n.return:r[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,r[1])).done)return s;switch(n=0,s&&(r=[2&r[0],s.value]),r[0]){case 0:case 1:s=r;break;case 4:return o.label++,{value:r[1],done:!1};case 5:o.label++,n=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!s||r[1]>s[0]&&r[1]<s[3])){o.label=r[1];break}if(6===r[0]&&o.label<s[1]){o.label=s[1],s=r;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(r);break}s[2]&&o.ops.pop(),o.trys.pop();continue}r=t.call(e,o)}catch(e){r=[6,e],n=0}finally{i=s=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,a])}}};t.__esModule=!0,t.asyncPipe=void 0;var r=i(9068);t.asyncPipe=function(e,t){var i=this,o="state"in e?r.Evt.create(void 0):r.Evt.create(),a=0,l=function(r){return n(i,void 0,void 0,(function(){var i,n,l;return s(this,(function(s){switch(s.label){case 0:return a++,i=a,null!==(n=t(r))&&"then"in n?[4,n]:[3,2];case 1:return l=s.sent(),"state"in e&&i!==a?[2]:[3,3];case 2:l=n,s.label=3;case 3:return null===l||o.post(l[0]),[2]}}))}))};return e.attach(l),"state"in e&&l(e.state),o}},8408:(e,t,i)=>{t.__esModule=!0,t.create=void 0;var n=i(4019);t.create=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return 0===e.length?new n.importProxy.Evt:new n.importProxy.StatefulEvt(e[0])}},7528:(e,t)=>{t.__esModule=!0,t.factorize=void 0,t.factorize=function(e){return e}},8649:(e,t,i)=>{t.__esModule=!0,t.from=void 0;var n=i(5374),s=i(2329),r=i(5016),o=i(7058),a=i(4019),l=i(8197);function h(e,t,i,r){var c,u,d,p;if(d=t,!l.z_2.canBe(d)){if("then"in t){var f=new a.importProxy.Evt,_=(u=(c=function(){return null==e?void 0:e.evtDoneOrAborted.postCount})(),function(){return u!==c()});return t.then((function(e){_()||f.post(e)})),f}return o.mergeImpl(e,Array.from(t).map((function(t){return h(e,t,i,r)})))}if(l.z_2.NodeStyleEventEmitter_match(t))p={on:function(e,i){return t.addListener(i,e)},off:function(e,i){return t.removeListener(i,e)}};else if(l.z_2.JQueryStyleEventEmitter_match(t))p={on:function(e,i){return t.on(i,e)},off:function(e,i){return t.off(i,e)}};else if(l.z_2.HasEventTargetAddRemove_match(t))p={on:function(e,i,n){return t.addEventListener(i,e,n)},off:function(e,i,n){return t.removeEventListener(i,e,n)}};else if(l.z_2.RxJSSubject_match(t)){var m;p={on:function(e){return m=t.subscribe((function(t){return e(t)}))},off:function(){return m.unsubscribe()}}}else n.id(t),s.assert(!1);var g=new a.importProxy.Evt,v=function(e){return g.post(e)};return null==e||e.evtDoneOrAborted.attachOnce((function(){return p.off(v,i,r)})),p.on(v,i,r),g}t.from=function(e,t,i,n){return"evtDoneOrAborted"in e?(s.assert(r.typeGuard(t)&&r.typeGuard(i)&&r.typeGuard(n)),h(e,t,i,n)):(s.assert(r.typeGuard(t)&&r.typeGuard(i)),h(void 0,e,t,i))}},2878:(e,t,i)=>{t.__esModule=!0,t.getCtxFactory=void 0;var n=i(9589),s=i(4019);t.getCtxFactory=function(){var e=new n.Polyfill;return function(t){var i=e.get(t);return void 0===i&&(i=new s.importProxy.Ctx,e.set(t,i)),i}}},9068:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},n.apply(this,arguments)},s=this&&this.__read||function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o},r=this&&this.__spread||function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(s(arguments[t]));return e},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};t.__esModule=!0,t.Evt=t.doDetachIfNeeded=void 0,i(6184);var a=i(4019),l=i(8408),h=i(2878),c=i(7528),u=i(7058),d=i(8649),p=i(9752),f=i(6558),_=i(1462),m=i(4888),g=i(8136),v=i(7642),y=i(343),x=i(2896),b=i(808),T=i(6068),S=i(9589),E=i(14),C=i(8810),A=i(5016),P=i(176),R=i(2162),M=i(5614),I=i(4260),D=i(2753),O=i(1562),w=i(7219),N=i(6939),F=function(){function e(){this.lazyEvtAttach=new y.LazyEvt,this.lazyEvtDetach=new y.LazyEvt,this.__maxHandlers=void 0,this.postCount=0,this.traceId=null,this.handlers=[],this.handlerTriggers=new T.Polyfill,this.__currentChronologyMark=0,this.asyncHandlerCount=0}return e.setDefaultMaxHandlers=function(e){this.__defaultMaxHandlers=isFinite(e)?e:0},e.prototype.toStateful=function(e,t){var i=N.z_3.match(e),n=i?void 0:e,s=t||(i?e:void 0),r=new a.importProxy.StatefulEvt(n),o=function(e){return r.post(e)};return s?this.attach(s,o):this.attach(o),r},e.prototype.setMaxHandlers=function(e){return this.__maxHandlers=isFinite(e)?e:0,this},e.prototype.enableTrace=function(e){var t=e.id,i=e.formatter,n=e.log;this.traceId=t,this.traceFormatter=i||function(e){try{return JSON.stringify(e,null,2)}catch(t){return""+e}},this.log=void 0===n?function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return console.log.apply(console,r(e))}:!1===n?void 0:n},e.prototype.disableTrace=function(){return this.traceId=null,this},e.prototype.getChronologyMark=function(){return this.__currentChronologyMark++},e.prototype.detachHandler=function(e,t,i){var n=this.handlers.indexOf(e);return!(n<0||(A.typeGuard(e,!!e.ctx)&&e.ctx.zz__removeHandler(e),this.handlers.splice(n,1),e.async&&this.asyncHandlerCount--,this.handlerTriggers.delete(e),void 0!==t[0]&&(I.safeClearTimeout(t[0]),i(new w.EvtError.Detached)),this.lazyEvtDetach.post(e),0))},e.prototype.triggerHandler=function(e,t,i,n){var r=e.callback,o=e.once;void 0!==t[0]&&(I.safeClearTimeout(t[0]),t[0]=void 0),L(e,n,o);var a=s(n,1)[0],l=null==r?void 0:r.call(this,a);return null==i||i(a),D.isPromiseLike(l)?l:void 0},e.prototype.addHandler=function(e,t){var i=this;O.z_f1.fλ_Stateful_match(e.op)&&this.statelessByStatefulOp.set(e.op,P.encapsulateOpState(e.op));var s=new R.Deferred,r=[void 0],o=n(n(n({},e),t),{detach:function(){return i.detachHandler(o,r,s.reject)},promise:s.pr});if("number"==typeof o.timeout&&(r[0]=I.safeSetTimeout((function(){r[0]=void 0,o.detach(),s.reject(new w.EvtError.Timeout(o.timeout))}),o.timeout)),this.handlerTriggers.set(o,(function(e){return i.triggerHandler(o,r,s.isPending?s.resolve:void 0,e)})),o.async&&this.asyncHandlerChronologyMark.set(o,this.getChronologyMark()),o.prepend){var a=void 0;for(a=0;a<this.handlers.length&&this.handlers[a].extract;a++);this.handlers.splice(a,0,o)}else this.handlers.push(o);return o.async&&this.asyncHandlerCount++,this.checkForPotentialMemoryLeak(),A.typeGuard(o,!!o.ctx)&&o.ctx.zz__addHandler(o,this),this.lazyEvtAttach.post(o),o},e.prototype.checkForPotentialMemoryLeak=function(){var t=void 0!==this.__maxHandlers?this.__maxHandlers:e.__defaultMaxHandlers;if(0!==t&&this.handlers.length%(t+1)==0){var i=["MaxHandlersExceededWarning: Possible Evt memory leak detected.",this.handlers.length+" handlers attached"+(this.traceId?' to "'+this.traceId+'"':"")+".\n","Use Evt.prototype.setMaxHandlers(n) to increase limit on a specific Evt.\n","Use Evt.setDefaultMaxHandlers(n) to change the default limit currently set to "+e.__defaultMaxHandlers+".\n"].join(""),s=new T.Polyfill;this.getHandlers().map((function(e){var t=e.ctx,i=e.async,s=e.once,r=e.prepend,o=e.extract,a=e.op,l=e.callback;return n(n({hasCtx:!!t,once:s,prepend:r,extract:o,isWaitFor:i},a===g.matchAll?{}:{op:a.toString()}),l?{callback:l.toString()}:{})})).map((function(e){return"{\n"+Object.keys(e).map((function(t){return" "+t+": "+e[t]})).join(",\n")+"\n}"})).forEach((function(e){return s.set(e,(s.has(e)?s.get(e):0)+1)})),i+="\n"+Array.from(s.keys()).map((function(e){return s.get(e)+" handler"+(1===s.get(e)?"":"s")+" like:\n"+e})).join("\n")+"\n",null===this.traceId&&(i+="\n"+["To validate the identify of the Evt instance that is triggering this warning you can call",'Evt.prototype.enableTrace({ "id": "My evt id", "log": false }) on the Evt that you suspect.\n'].join(" "));try{console.warn(i)}catch(e){}}},e.prototype.getStatelessOp=function(e){return O.z_f1.fλ_Stateful_match(e)?this.statelessByStatefulOp.get(e):e},e.prototype.trace=function(e){var t,i=this;if(null!==this.traceId){var n="("+this.traceId+") ",s=!!this.handlers.find((function(t){var n=t.extract,s=t.op;return n&&!!i.getStatelessOp(s)(e)}));if(s)n+="extracted ";else{var r=this.handlers.filter((function(t){var n=t.extract,s=t.op;return!n&&!!i.getStatelessOp(s)(e)})).length;n+=r+" handler"+(r>1?"s":"")+", "}null===(t=this.log)||void 0===t||t.call(this,n+this.traceFormatter(e))}},e.prototype.postSync=function(e){var t,i,n=[],s=function(e){return[e,Promise.all(n).then((function(){}))]};try{for(var a=o(r(this.handlers)),l=a.next();!l.done;l=a.next()){var h=l.value,c=h.async,u=h.op,d=h.extract;if(!c){var p=b.invokeOperator(this.getStatelessOp(u),e,!0);if(O.z_f1.fλ_Result_NotMatched_match(p))L(h,p);else{var f=this.handlerTriggers.get(h);if(f){var _=f(p);if(void 0!==_&&n.push(_),d)return s(!0)}}}}}catch(e){t={error:e}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(t)throw t.error}}return s(!1)},e.prototype.postAsyncFactory=function(){var e=this;return E.buildMethodCb((function(t,i,n){var s,a;if(0!==e.asyncHandlerCount){var l,h=[];Promise.resolve().then((function(){return l=e.getChronologyMark()}));var c=function(n){if(!n.async)return"continue";var s=b.invokeOperator(e.getStatelessOp(n.op),t,!0);if(O.z_f1.fλ_Result_NotMatched_match(s))return L(n,s),"continue";var r=e.handlerTriggers.get(n);return r&&function(){var t=e.asyncHandlerChronologyMark.get(n);if(i>t)return!0;var s=e.asyncHandlerChronologyExceptionRange.get(n);return void 0!==s&&s.lowerMark<i&&i<s.upperMark&&t>s.upperMark}()?(h.push(new Promise((function(e){return n.promise.then((function(){return e()})).catch((function(){return e()}))}))),void r(s)):"continue"};try{for(var u=o(r(e.handlers)),d=u.next();!d.done;d=u.next())c(d.value)}catch(e){s={error:e}}finally{try{d&&!d.done&&(a=u.return)&&a.call(u)}finally{if(s)throw s.error}}if(0!==h.length){var p=r(e.handlers);Promise.all(h).then((function(){var t,s;try{for(var r=o(e.handlers),a=r.next();!a.done;a=r.next()){var h=a.value;h.async&&(p.indexOf(h)>=0||e.asyncHandlerChronologyExceptionRange.set(h,{lowerMark:i,upperMark:l}))}}catch(e){t={error:e}}finally{try{a&&!a.done&&(s=r.return)&&s.call(r)}finally{if(t)throw t.error}}n()}))}else n()}else n()}))},e.prototype.isHandled=function(e){var t=this;return!!this.getHandlers().find((function(i){var n=i.op;return!!t.getStatelessOp(n)(e)}))},e.prototype.getHandlers=function(){return r(this.handlers)},e.prototype.detach=function(e){var t,i,n=[];try{for(var s=o(this.getHandlers()),r=s.next();!r.done;r=s.next()){var a=r.value;void 0!==e&&a.ctx!==e||a.detach()&&n.push(a)}}catch(e){t={error:e}}finally{try{r&&!r.done&&(i=s.return)&&i.call(s)}finally{if(t)throw t.error}}return n},e.prototype.pipe=function(){for(var t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];var s=new e;return this.addHandler(n(n({},g.parsePropsFromArgs(t,"pipe")),{callback:function(e){return s.post(e)}}),e.propsFormMethodNames.attach),s},e.prototype.waitFor=function(){for(var t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];return this.addHandler(g.parsePropsFromArgs(t,"waitFor"),e.propsFormMethodNames.waitFor).promise},e.prototype.$attach=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.attach.apply(this,r(e))},e.prototype.attach=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.__attachX(e,"attach")},e.prototype.$attachOnce=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.attachOnce.apply(this,r(e))},e.prototype.attachOnce=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.__attachX(e,"attachOnce")},e.prototype.$attachExtract=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.attachExtract.apply(this,r(e))},e.prototype.attachExtract=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.__attachX(e,"attachExtract")},e.prototype.$attachPrepend=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.attachPrepend.apply(this,r(e))},e.prototype.attachPrepend=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.__attachX(e,"attachPrepend")},e.prototype.$attachOncePrepend=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.attachOncePrepend.apply(this,r(e))},e.prototype.attachOncePrepend=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.__attachX(e,"attachOncePrepend")},e.prototype.$attachOnceExtract=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.attachOnceExtract.apply(this,r(e))},e.prototype.attachOnceExtract=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.__attachX(e,"attachOnceExtract")},e.prototype.__attachX=function(t,i){var n=g.parsePropsFromArgs(t,"attach*"),s=this.addHandler(n,e.propsFormMethodNames[i]);return void 0===n.timeout?this:s.promise},e.prototype.postAsyncOnceHandled=function(e){var t=this;if(this.isHandled(e))return this.post(e);var i=new R.Deferred;return this.evtAttach.attachOnce((function(i){var n=i.op;return!!b.invokeOperator(t.getStatelessOp(n),e)}),(function(){return Promise.resolve().then((function(){return i.resolve(t.post(e))}))})),i.pr},e.prototype.postOrPostAndWait=function(e,t){var i=this;this.trace(e),C.overwriteReadonlyProp(this,"postCount",this.postCount+1);var n=this.getChronologyMark(),r=s(this.postSync(e),2),o=r[0],a=r[1],l=t?function(){return a}:function(){return i.postCount};if(o)return l();if(void 0===this.postAsync){if(0===this.asyncHandlerCount)return l();this.postAsync=this.postAsyncFactory()}return this.postAsync(e,n),l()},e.prototype.post=function(e){return this.postOrPostAndWait(e,!1)},e.prototype.postAndWait=function(e){return this.postOrPostAndWait(e,!0)},e.create=l.create,e.newCtx=v.newCtx,e.merge=u.merge,e.from=d.from,e.useEffect=p.useEffect,e.getCtx=h.getCtxFactory(),e.loosenType=M.loosenType,e.factorize=c.factorize,e.asPostable=f.asPostable,e.asyncPipe=_.asyncPipe,e.asNonPostable=m.asNonPostable,e.__defaultMaxHandlers=25,e.__1=(x.defineAccessors(e.prototype,"evtAttach",{get:function(){return this.lazyEvtAttach.evt}}),void x.defineAccessors(e.prototype,"evtDetach",{get:function(){return this.lazyEvtDetach.evt}})),e.__2=void Object.defineProperties(e.prototype,["__asyncHandlerChronologyMark","__asyncHandlerChronologyExceptionRange","__statelessByStatefulOp"].map((function(e){return[e.substr(2),{get:function(){return void 0===this[e]&&(this[e]=new S.Polyfill),this[e]}}]})).reduce((function(e,t){var i,r=s(t,2),o=r[0],a=r[1];return n(n({},e),((i={})[o]=a,i))}),{})),e.propsFormMethodNames={waitFor:{async:!0,extract:!1,once:!0,prepend:!1},attach:{async:!1,extract:!1,once:!1,prepend:!1},attachExtract:{async:!1,extract:!0,once:!1,prepend:!0},attachPrepend:{async:!1,extract:!1,once:!1,prepend:!0},attachOnce:{async:!1,extract:!1,once:!0,prepend:!1},attachOncePrepend:{async:!1,extract:!1,once:!0,prepend:!0},attachOnceExtract:{async:!1,extract:!0,once:!0,prepend:!0}},e}();function L(e,t,i){var n=O.z_f1.fλ_Result_getDetachArg(t);if("boolean"!=typeof n){var r=s(n,3),o=r[0],a=r[1],l=r[2];a?o.abort(a):o.done(l)}else(n||i)&&e.detach()}t.doDetachIfNeeded=L,t.Evt=F;try{C.overwriteReadonlyProp(t.Evt,"name","Evt")}catch(e){}a.importProxy.Evt=t.Evt},5614:(e,t)=>{t.__esModule=!0,t.loosenType=void 0,t.loosenType=function(e){return e}},7058:(e,t,i)=>{t.__esModule=!0,t.merge=t.mergeImpl=void 0;var n=i(4019);function s(e,t){var i=new n.importProxy.Evt,s=function(e){return i.post(e)};return t.forEach((function(t){void 0===e?t.attach(s):t.attach(e,s)})),i}t.mergeImpl=s,t.merge=function(e,t){return"length"in e?s(void 0,e):s(e,t)}},7642:(e,t,i)=>{t.__esModule=!0,t.newCtx=void 0;var n=i(4019);t.newCtx=function(){return new n.importProxy.Ctx}},8136:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},n.apply(this,arguments)},s=this&&this.__read||function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o},r=this&&this.__spread||function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(s(arguments[t]));return e};t.__esModule=!0,t.parsePropsFromArgs=t.matchAll=void 0;var o=i(5374),a=i(9291),l=i(5016);function h(){return!0}t.matchAll=h;var c=function(e){return void 0!==e&&l.typeGuard(e)&&("function"==typeof e||"function"==typeof e[0])},u={op:h,ctx:void 0,timeout:void 0,callback:void 0};t.parsePropsFromArgs=function e(t,i){switch(l.typeGuard(u),i){case"pipe":var h=function(e){return 0===e.length?{}:{op:1===e.length?e[0]:a.compose.apply(void 0,r(e))}};if(c(t[0]))return o.id(n(n({},u),h(t)));var d=s(t),p=d[0],f=d.slice(1);return o.id(n(n(n({},u),void 0!==p?{ctx:p}:{}),h(f)));case"waitFor":return e(r(t.filter((function(e,i){return!(i===t.length-1&&void 0===e)})),[u.callback]),"attach*");case"attach*":switch(t.length){case 4:var _=s(t,4),m=_[0],g=_[1],v=_[2],y=_[3];return o.id(n(n({},u),{op:m,ctx:g,timeout:v,callback:y}));case 3:var x=s(t,3);if(m=x[0],g=x[1],v=x[2],"number"==typeof g){var b=g,T=v;return c(m)?o.id(n(n({},u),{timeout:b,callback:T,op:m})):o.id(n(n({},u),{timeout:b,callback:T,ctx:m}))}return o.id(n(n({},u),{op:m,ctx:g,callback:v}));case 2:var S=s(t,2);return m=S[0],g=S[1],"number"==typeof m?o.id(n(n({},u),{timeout:m,callback:g})):(T=g,c(m)?o.id(n(n({},u),{callback:T,op:m})):o.id(n(n({},u),{callback:T,ctx:m})));case 1:var E=s(t,1)[0];return o.id(n(n({},u),{callback:E}));case 0:return o.id(n({},u))}}}},9752:(e,t)=>{t.__esModule=!0,t.useEffect=void 0,t.useEffect=function(e,t,i){var n=0;("state"in t?t.evtChange:t).attach((function(t){return e(t,{isFirst:!1,data:t},n++)})),e("state"in t?t.state:null==i?void 0:i[0],{isFirst:!0},n++)}},343:(e,t,i)=>{t.__esModule=!0,t.LazyEvt=void 0;var n=i(8810),s=i(4019),r=i(2896),o=function(){function e(){this.initialPostCount=0}return e.prototype.post=function(e){return void 0===this.__evt?++this.initialPostCount:this.__evt.post(e)},e.__1=void r.defineAccessors(e.prototype,"evt",{get:function(){return void 0===this.__evt&&(this.__evt=new s.importProxy.Evt,n.overwriteReadonlyProp(this.__evt,"postCount",this.initialPostCount)),this.__evt}}),e}();t.LazyEvt=o},8802:(e,t,i)=>{t.__esModule=!0,t.LazyStatefulEvt=void 0;var n=i(8810),s=i(4019),r=i(2896),o=function(){function e(e){this.initialPostCount=0,this.initialState=e}return e.prototype.post=function(e){return void 0===this.__evt?(this.initialState=e,++this.initialPostCount):this.__evt.post(e)},e.__1=void r.defineAccessors(e.prototype,"evt",{get:function(){return void 0===this.__evt&&(this.__evt=new s.importProxy.StatefulEvt(this.initialState),delete this.initialState,n.overwriteReadonlyProp(this.__evt,"postCount",this.initialPostCount)),this.__evt}}),e}();t.LazyStatefulEvt=o},8920:function(e,t,i){var n,s=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},n(e,t)},function(e,t){function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),r=this&&this.__read||function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o},o=this&&this.__spread||function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(r(arguments[t]));return e};t.__esModule=!0,t.StatefulEvt=void 0,i(7244);var a=i(2896),l=i(343),h=i(8802),c=i(4019),u=i(808),d=i(8136),p=i(9068),f=i(1562),_=function(e){function t(t){var i=e.call(this)||this;return i.lazyEvtDiff=new l.LazyEvt,i.lazyEvtChangeDiff=new l.LazyEvt,i.__state=t,i.lazyEvtChange=new h.LazyStatefulEvt(i.__state),i}return s(t,e),t.prototype.post=function(e){return this.__post(e,!1)},t.prototype.postForceChange=function(e){return this.__post(e?e[0]:this.state,!0)},t.prototype.__post=function(t,i){var n=this.state;this.__state=t;var s={prevState:n,newState:this.state};return this.lazyEvtDiff.post(s),!i&&Object.is(n,this.state)||(this.lazyEvtChange.post(this.state),this.lazyEvtChangeDiff.post(s)),e.prototype.post.call(this,t)},t.prototype.pipe=function(){for(var t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];var n=e.prototype.pipe.apply(this,o(t)),s=u.invokeOperator(this.getStatelessOp(d.parsePropsFromArgs(t,"pipe").op),this.state);if(f.z_f1.fλ_Result_NotMatched_match(s))throw new Error(["Cannot pipe StatefulEvt because the operator does not match","it's current state.","Use evt.toStateless([ctx]).pipe(op).toStatic(initialState)","to be sure the StatefulEvt is correctly initialized"].join(" "));return n.toStateful(s[0])},t.prototype.toStateless=function(t){return t?e.prototype.pipe.call(this,t):e.prototype.pipe.call(this)},t.__4=(a.defineAccessors(t.prototype,"state",{get:function(){return this.__state},set:function(e){this.post(e)}}),a.defineAccessors(t.prototype,"evtDiff",{get:function(){return this.lazyEvtDiff.evt}}),a.defineAccessors(t.prototype,"evtChange",{get:function(){return this.lazyEvtChange.evt}}),void a.defineAccessors(t.prototype,"evtChangeDiff",{get:function(){return this.lazyEvtChangeDiff.evt}})),t}(p.Evt);t.StatefulEvt=_,c.importProxy.StatefulEvt=t.StatefulEvt},4019:(e,t)=>{t.__esModule=!0,t.importProxy=void 0,t.importProxy={}},1932:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||t.hasOwnProperty(i)||n(t,e,i)};t.__esModule=!0,s(i(8862),t),s(i(8570),t);var r=i(3706);n(t,r,"Ctx");var o=i(9068);n(t,o,"Evt");var a=i(8920);n(t,a,"StatefulEvt");var l=i(1278);n(t,l,"matchVoid")},8197:(e,t,i)=>{t.__esModule=!0,t.EventTargetLike=t.z_2=void 0;var n,s=i(8630);t.z_2={RxJSSubject_match:function(e){return s.typeGuard(e)&&e instanceof Object&&"function"==typeof e.subscribe},NodeStyleEventEmitter_match:function(e){return s.typeGuard(e)&&e instanceof Object&&"function"==typeof e.addListener&&"function"==typeof e.removeListener},JQueryStyleEventEmitter_match:function(e){return s.typeGuard(e)&&e instanceof Object&&"function"==typeof e.on&&"function"==typeof e.off},HasEventTargetAddRemove_match:function(e){return s.typeGuard(e)&&e instanceof Object&&"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener},canBe:function(e){try{return t.z_2.HasEventTargetAddRemove_match(e)||t.z_2.NodeStyleEventEmitter_match(e)||t.z_2.JQueryStyleEventEmitter_match(e)||t.z_2.RxJSSubject_match(e)}catch(e){return!1}}},((n=t.EventTargetLike||(t.EventTargetLike={})).RxJSSubject||(n.RxJSSubject={})).match=t.z_2.RxJSSubject_match,(n.NodeStyleEventEmitter||(n.NodeStyleEventEmitter={})).match=t.z_2.NodeStyleEventEmitter_match,(n.JQueryStyleEventEmitter||(n.JQueryStyleEventEmitter={})).match=t.z_2.JQueryStyleEventEmitter_match,(n.HasEventTargetAddRemove||(n.HasEventTargetAddRemove={})).match=t.z_2.HasEventTargetAddRemove_match,n.canBe=t.z_2.canBe},380:function(e,t){var i,n=this&&this.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},i(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});t.__esModule=!0,t.Detached=void 0;var s=function(e){function t(){var t=this.constructor,i=e.call(this,"Evt handler detached")||this;return Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(Error);t.Detached=s},3883:function(e,t){var i,n=this&&this.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},i(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});t.__esModule=!0,t.Timeout=void 0;var s=function(e){function t(t){var i=this.constructor,n=e.call(this,"Evt timeout after "+t+"ms")||this;return n.timeout=t,Object.setPrototypeOf(n,i.prototype),n}return n(t,e),t}(Error);t.Timeout=s},7219:(e,t,i)=>{t.__esModule=!0,t.EvtError=void 0;var n,s=i(3883),r=i(380);(n=t.EvtError||(t.EvtError={})).Timeout=s.Timeout,n.Detached=r.Detached},5415:(e,t)=>{t.__esModule=!0},1562:(e,t,i)=>{t.__esModule=!0,t.Operator=t.z_f1=void 0;var n,s,r,o,a=i(8630);t.z_f1={fλ_Stateful_match:function(e){return"function"!=typeof e},fλ_Result_match:function(e){return t.z_f1.fλ_Result_Matched_match(e)||t.z_f1.fλ_Result_NotMatched_match(e)},fλ_Result_getDetachArg:function(e){var i=t.z_f1.fλ_Result_Matched_match(e)?e[1]:e;return!!t.z_f1.fλ_Result_Detach_FromEvt_match(i)||!!t.z_f1.fλ_Result_Detach_WithCtxArg_match(i)&&[i.DETACH,i.err,i.res]},fλ_Result_NotMatched_match:function(e){return null===e||t.z_f1.fλ_Result_Detach_match(e)},fλ_Result_Matched_match:function(e){return a.typeGuard(e)&&e instanceof Object&&!("input"in e)&&(1===e.length||2===e.length&&(null===e[1]||t.z_f1.fλ_Result_Detach_match(e[1])))},fλ_Result_Detach_FromEvt_match:function(e){return"DETACH"===e},fλ_Result_Detach_WithCtxArg_match:function(e){return a.typeGuard(e)&&e instanceof Object&&e.DETACH instanceof Object},fλ_Result_Detach_match:function(e){return t.z_f1.fλ_Result_Detach_FromEvt_match(e)||t.z_f1.fλ_Result_Detach_WithCtxArg_match(e)}},n=t.Operator||(t.Operator={}),((s=n.fλ||(n.fλ={})).Stateful||(s.Stateful={})).match=t.z_f1.fλ_Stateful_match,(r=s.Result||(s.Result={})).match=t.z_f1.fλ_Result_match,r.getDetachArg=t.z_f1.fλ_Result_getDetachArg,(r.NotMatched||(r.NotMatched={})).match=t.z_f1.fλ_Result_NotMatched_match,(r.Matched||(r.Matched={})).match=t.z_f1.fλ_Result_Matched_match,((o=r.Detach||(r.Detach={})).FromEvt||(o.FromEvt={})).match=t.z_f1.fλ_Result_Detach_FromEvt_match,(o.WithCtxArg||(o.WithCtxArg={})).match=t.z_f1.fλ_Result_Detach_WithCtxArg_match,o.match=t.z_f1.fλ_Result_Detach_match},8381:(e,t)=>{t.__esModule=!0},8862:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||t.hasOwnProperty(i)||n(t,e,i)};t.__esModule=!0,t.dom=void 0,s(i(8381),t),s(i(9730),t),s(i(8197),t),s(i(7219),t),s(i(5415),t);var r=i(7163);t.dom=r,s(i(1562),t)},3135:(e,t)=>{t.__esModule=!0},6939:(e,t,i)=>{t.__esModule=!0,t.CtxLike=t.z_3=void 0;var n=i(5016);t.z_3={match:function(e){return n.typeGuard(e)&&e instanceof Object&&"function"==typeof e.done&&"function"==typeof e.abort&&"function"==typeof e.zz__addHandler&&"function"==typeof e.zz__removeHandler}},(t.CtxLike||(t.CtxLike={})).match=t.z_3.match},4597:(e,t)=>{t.__esModule=!0},774:(e,t)=>{t.__esModule=!0},8456:(e,t)=>{t.__esModule=!0},2690:(e,t)=>{t.__esModule=!0},2751:(e,t)=>{t.__esModule=!0},1784:(e,t)=>{t.__esModule=!0},9730:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||t.hasOwnProperty(i)||n(t,e,i)};t.__esModule=!0,s(i(3135),t),s(i(6939),t),s(i(4597),t),s(i(774),t),s(i(8456),t),s(i(2690),t),s(i(2751),t),s(i(1784),t)},7163:(e,t)=>{t.__esModule=!0,t.__hack=void 0,t.__hack="NOT TYPE ONLY"},9291:function(e,t,i){var n=this&&this.__read||function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o},s=this&&this.__spread||function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(n(arguments[t]));return e};t.__esModule=!0,t.compose=void 0;var r=i(176),o=i(808),a=i(5374),l=i(2329),h=i(5016),c=i(1562);t.compose=function e(){for(var t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];if(1===t.length){var u=n(t,1)[0];return c.z_f1.fλ_Stateful_match(u)?r.encapsulateOpState(u):u}var d=n(t),p=d[0],f=d[1],_=d.slice(2),m=function(e,t){var i=c.z_f1.fλ_Stateful_match(e)?r.encapsulateOpState(e):a.id(e),s=c.z_f1.fλ_Stateful_match(t)?r.encapsulateOpState(t):a.id(t);return a.id((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=n(e,3),u=r[0],d=r[2],p=o.invokeOperator(i,u,d);if(c.z_f1.fλ_Result_NotMatched_match(p))return l.assert(h.typeGuard(p)),p;var f=p[1]?p[1]:null;l.assert(h.typeGuard(f));var _=n(p,1)[0],m=o.invokeOperator(s,_,d);return c.Operator.fλ.Result.NotMatched.match(m)?(l.assert(h.typeGuard(m)),null!==f?f:m):a.id([m[0],f||(m[1]?m[1]:null)])}))}(p,f);return 0===_.length?m:e.apply(void 0,s([m],_))}},176:function(e,t,i){var n=this&&this.__read||function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o};t.__esModule=!0,t.encapsulateOpState=void 0;var s=i(5374),r=i(1562);t.encapsulateOpState=function(e){var t=e[1];return s.id((function(){for(var i=[],s=0;s<arguments.length;s++)i[s]=arguments[s];var o=n(i,3),a=o[0],l=o[2],h=e[0](a,t,l);return l&&r.z_f1.fλ_Result_Matched_match(h)&&(t=h[0]),h}))}},5957:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]});t.__esModule=!0,n(t,i(7016),"throttleTime"),n(t,i(8055),"to"),n(t,i(4205),"nonNullable")},4205:(e,t)=>{t.__esModule=!0,t.nonNullable=void 0,t.nonNullable=function(e){return null==e?null:[e]}},7016:(e,t,i)=>{t.__esModule=!0,t.throttleTime=void 0;var n=i(9291);t.throttleTime=function(e){return n.compose([function(t,i){var n=i.lastClick,s=Date.now();return s-n<e?null:[{data:t,lastClick:s}]},{lastClick:0,data:null}],(function(e){return[e.data]}))}},8055:(e,t)=>{t.__esModule=!0,t.to=void 0;var i=new Map;t.to=function(e){var n;return null!==(n=i.get(e))&&void 0!==n?n:(i.set(e,(function(t){return t[0]!==e?null:[t[1]]})),t.to(e))}},8570:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||t.hasOwnProperty(i)||n(t,e,i)};t.__esModule=!0,s(i(5957),t);var r=i(9291);n(t,r,"compose");var o=i(808);n(t,o,"invokeOperator")},808:(e,t,i)=>{t.__esModule=!0,t.invokeOperator=void 0;var n=i(1562);t.invokeOperator=function(e,t,i){var s=e(t,void 0,i);return n.z_f1.fλ_Result_match(s)?s:s?[t]:null}},2162:function(e,t,i){var n,s=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},n(e,t)},function(e,t){function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});t.__esModule=!0,t.VoidDeferred=t.Deferred=void 0;var r=i(8810),o=function(){var e,t,i=this;this.isPending=!0,this.pr=new Promise((function(n,s){e=function(e){r.overwriteReadonlyProp(i,"isPending",!1),n(e)},t=function(e){r.overwriteReadonlyProp(i,"isPending",!1),s(e)}})),this.resolve=e,this.reject=t};t.Deferred=o;var a=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return s(t,e),t}(o);t.VoidDeferred=a},4260:(e,t)=>{t.__esModule=!0,t.safeClearTimeout=t.safeSetTimeout=void 0,t.safeSetTimeout=function(e,t){return setTimeout(e,t)},t.safeClearTimeout=function(e){return clearTimeout(e)}},2329:function(e,t,i){var n,s=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},n(e,t)},function(e,t){function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),r=this&&this.__read||function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o};t.__esModule=!0,t.assert=t.AssertionError=void 0;var o=i(8810),a=function(e){function t(t){var i=this.constructor,n=e.call(this,"Wrong assertion encountered"+(t?': "'+t+'"':""))||this;if(Object.setPrototypeOf(n,i.prototype),!n.stack)return n;try{o.overwriteReadonlyProp(n,"stack",n.stack.split("\n").filter((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=r(e,2)[1];return 1!==i&&2!==i})).join("\n"))}catch(e){}return n}return s(t,e),t}(Error);t.AssertionError=a,t.assert=function(e,t){if(!e)throw new a(t)}},2896:function(e,t){var i=this&&this.__assign||function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},i.apply(this,arguments)};t.__esModule=!0,t.defineAccessors=void 0,t.defineAccessors=function(e,t,n){var s=n.get,r=n.set;Object.defineProperty(e,t,i(i(i({},Object.getOwnPropertyDescriptor(e,t)||{enumerable:!0,configurable:!0}),void 0!==s?{get:function(){return s.call(this)}}:{}),void 0!==r?{set:function(e){r.call(this,e)}}:{}))}},5288:(e,t)=>{t.__esModule=!0,t.exclude=void 0,t.exclude=function(e){var t=e instanceof Object?function(t){return e.indexOf(t)<0}:function(t){return t!==e};return function(e){return t(e)}}},5374:(e,t)=>{t.__esModule=!0,t.id=void 0,t.id=function(e){return e}},8630:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]});t.__esModule=!0,n(t,i(2329),"assert"),n(t,i(5288),"exclude"),n(t,i(5374),"id"),n(t,i(1278),"matchVoid"),n(t,i(5192),"objectKeys"),n(t,i(5016),"typeGuard")},2753:(e,t)=>{t.__esModule=!0,t.isPromiseLike=void 0,t.isPromiseLike=function(e){return"function"==typeof(null==e?void 0:e.then)}},1278:(e,t)=>{t.__esModule=!0,t.matchVoid=void 0,t.matchVoid=function(e){return void 0===e}},5192:(e,t)=>{t.__esModule=!0,t.objectKeys=void 0,t.objectKeys=function(e){return Object.keys(e)}},8810:function(e,t){var i=this&&this.__assign||function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},i.apply(this,arguments)};t.__esModule=!0,t.overwriteReadonlyProp=void 0,t.overwriteReadonlyProp=function(e,t,n){try{e[t]=n}catch(e){}if(e[t]===n)return n;var s=void 0,r=Object.getOwnPropertyDescriptor(e,t)||{enumerable:!0,configurable:!0};if(r.get)throw new Error("Probably a wrong ides to overwrite "+t+" getter");try{Object.defineProperty(e,t,i(i({},r),{value:n}))}catch(e){s=e}if(e[t]!==n)throw s||new Error("Can't assign");return n}},5016:(e,t)=>{t.__esModule=!0,t.typeGuard=void 0,t.typeGuard=function(e,t){return void 0===t&&(t=!0),t}},1297:(e,t,i)=>{e.exports=function e(t,i,n){function s(o,a){if(!i[o]){if(!t[o]){if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var h=i[o]={exports:{}};t[o][0].call(h.exports,(function(e){return s(t[o][1][e]||e)}),h,h.exports,e,t,i,n)}return i[o].exports}for(var r=void 0,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(e,t,i){var n=e("./utils"),s=e("./support"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(e){for(var t,i,s,o,a,l,h,c=[],u=0,d=e.length,p=d,f="string"!==n.getTypeOf(e);u<e.length;)p=d-u,s=f?(t=e[u++],i=u<d?e[u++]:0,u<d?e[u++]:0):(t=e.charCodeAt(u++),i=u<d?e.charCodeAt(u++):0,u<d?e.charCodeAt(u++):0),o=t>>2,a=(3&t)<<4|i>>4,l=1<p?(15&i)<<2|s>>6:64,h=2<p?63&s:64,c.push(r.charAt(o)+r.charAt(a)+r.charAt(l)+r.charAt(h));return c.join("")},i.decode=function(e){var t,i,n,o,a,l,h=0,c=0,u="data:";if(e.substr(0,5)===u)throw new Error("Invalid base64 input, it looks like a data url.");var d,p=3*(e=e.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(e.charAt(e.length-1)===r.charAt(64)&&p--,e.charAt(e.length-2)===r.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=s.uint8array?new Uint8Array(0|p):new Array(0|p);h<e.length;)t=r.indexOf(e.charAt(h++))<<2|(o=r.indexOf(e.charAt(h++)))>>4,i=(15&o)<<4|(a=r.indexOf(e.charAt(h++)))>>2,n=(3&a)<<6|(l=r.indexOf(e.charAt(h++))),d[c++]=t,64!==a&&(d[c++]=i),64!==l&&(d[c++]=n);return d}},{"./support":30,"./utils":32}],2:[function(e,t,i){var n=e("./external"),s=e("./stream/DataWorker"),r=e("./stream/Crc32Probe"),o=e("./stream/DataLengthProbe");function a(e,t,i,n,s){this.compressedSize=e,this.uncompressedSize=t,this.crc32=i,this.compression=n,this.compressedContent=s}a.prototype={getContentWorker:function(){var e=new s(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),t=this;return e.on("end",(function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")})),e},getCompressedWorker:function(){return new s(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(e,t,i){return e.pipe(new r).pipe(new o("uncompressedSize")).pipe(t.compressWorker(i)).pipe(new o("compressedSize")).withStreamInfo("compression",t)},t.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,i){var n=e("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},i.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,i){var n=e("./utils"),s=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==n.getTypeOf(e)?function(e,t,i,n){var r=s,o=0+i;e^=-1;for(var a=0;a<o;a++)e=e>>>8^r[255&(e^t[a])];return-1^e}(0|t,e,e.length):function(e,t,i,n){var r=s,o=0+i;e^=-1;for(var a=0;a<o;a++)e=e>>>8^r[255&(e^t.charCodeAt(a))];return-1^e}(0|t,e,e.length):0}},{"./utils":32}],5:[function(e,t,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(e,t,i){var n;n="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:n}},{lie:37}],7:[function(e,t,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,s=e("pako"),r=e("./utils"),o=e("./stream/GenericWorker"),a=n?"uint8array":"array";function l(e,t){o.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}i.magic="\b\0",r.inherits(l,o),l.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(r.transformTo(a,e.data),!1)},l.prototype.flush=function(){o.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},i.compressWorker=function(e){return new l("Deflate",e)},i.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,i){function n(e,t){var i,n="";for(i=0;i<t;i++)n+=String.fromCharCode(255&e),e>>>=8;return n}function s(e,t,i,s,o,c){var u,d,p=e.file,f=e.compression,_=c!==a.utf8encode,m=r.transformTo("string",c(p.name)),g=r.transformTo("string",a.utf8encode(p.name)),v=p.comment,y=r.transformTo("string",c(v)),x=r.transformTo("string",a.utf8encode(v)),b=g.length!==p.name.length,T=x.length!==v.length,S="",E="",C="",A=p.dir,P=p.date,R={crc32:0,compressedSize:0,uncompressedSize:0};t&&!i||(R.crc32=e.crc32,R.compressedSize=e.compressedSize,R.uncompressedSize=e.uncompressedSize);var M=0;t&&(M|=8),_||!b&&!T||(M|=2048);var I=0,D=0;A&&(I|=16),"UNIX"===o?(D=798,I|=function(e,t){var i=e;return e||(i=t?16893:33204),(65535&i)<<16}(p.unixPermissions,A)):(D=20,I|=function(e){return 63&(e||0)}(p.dosPermissions)),u=P.getUTCHours(),u<<=6,u|=P.getUTCMinutes(),u<<=5,u|=P.getUTCSeconds()/2,d=P.getUTCFullYear()-1980,d<<=4,d|=P.getUTCMonth()+1,d<<=5,d|=P.getUTCDate(),b&&(E=n(1,1)+n(l(m),4)+g,S+="up"+n(E.length,2)+E),T&&(C=n(1,1)+n(l(y),4)+x,S+="uc"+n(C.length,2)+C);var O="";return O+="\n\0",O+=n(M,2),O+=f.magic,O+=n(u,2),O+=n(d,2),O+=n(R.crc32,4),O+=n(R.compressedSize,4),O+=n(R.uncompressedSize,4),O+=n(m.length,2),O+=n(S.length,2),{fileRecord:h.LOCAL_FILE_HEADER+O+m+S,dirRecord:h.CENTRAL_FILE_HEADER+n(D,2)+O+n(y.length,2)+"\0\0\0\0"+n(I,4)+n(s,4)+m+S+y}}var r=e("../utils"),o=e("../stream/GenericWorker"),a=e("../utf8"),l=e("../crc32"),h=e("../signature");function c(e,t,i,n){o.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=i,this.encodeFileName=n,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}r.inherits(c,o),c.prototype.push=function(e){var t=e.meta.percent||0,i=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,o.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:i?(t+100*(i-n-1))/i:100}}))},c.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var i=s(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0},c.prototype.closedSource=function(e){this.accumulate=!1;var t=this.streamFiles&&!e.file.dir,i=s(e,t,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(i.dirRecord),t)this.push({data:function(e){return h.DATA_DESCRIPTOR+n(e.crc32,4)+n(e.compressedSize,4)+n(e.uncompressedSize,4)}(e),meta:{percent:100}});else for(this.push({data:i.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},c.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var i=this.bytesWritten-e,s=function(e,t,i,s,o){var a=r.transformTo("string",o(s));return h.CENTRAL_DIRECTORY_END+"\0\0\0\0"+n(e,2)+n(e,2)+n(t,4)+n(i,4)+n(a.length,2)+a}(this.dirRecords.length,i,e,this.zipComment,this.encodeFileName);this.push({data:s,meta:{percent:100}})},c.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},c.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",(function(e){t.processChunk(e)})),e.on("end",(function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end()})),e.on("error",(function(e){t.error(e)})),this},c.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},c.prototype.error=function(e){var t=this._sources;if(!o.prototype.error.call(this,e))return!1;for(var i=0;i<t.length;i++)try{t[i].error(e)}catch(e){}return!0},c.prototype.lock=function(){o.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock()},t.exports=c},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(e,t,i){var n=e("../compressions"),s=e("./ZipFileWorker");i.generateWorker=function(e,t,i){var r=new s(t.streamFiles,i,t.platform,t.encodeFileName),o=0;try{e.forEach((function(e,i){o++;var s=function(e,t){var i=e||t,s=n[i];if(!s)throw new Error(i+" is not a valid compression method !");return s}(i.options.compression,t.compression),a=i.options.compressionOptions||t.compressionOptions||{},l=i.dir,h=i.date;i._compressWorker(s,a).withStreamInfo("file",{name:e,dir:l,date:h,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(r)})),r.entriesCount=o}catch(e){r.error(e)}return r}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(e,t,i){function n(){if(!(this instanceof n))return new n;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new n;for(var t in this)"function"!=typeof this[t]&&(e[t]=this[t]);return e}}(n.prototype=e("./object")).loadAsync=e("./load"),n.support=e("./support"),n.defaults=e("./defaults"),n.version="3.10.1",n.loadAsync=function(e,t){return(new n).loadAsync(e,t)},n.external=e("./external"),t.exports=n},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(e,t,i){var n=e("./utils"),s=e("./external"),r=e("./utf8"),o=e("./zipEntries"),a=e("./stream/Crc32Probe"),l=e("./nodejsUtils");function h(e){return new s.Promise((function(t,i){var n=e.decompressed.getContentWorker().pipe(new a);n.on("error",(function(e){i(e)})).on("end",(function(){n.streamInfo.crc32!==e.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):t()})).resume()}))}t.exports=function(e,t){var i=this;return t=n.extend(t||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:r.utf8decode}),l.isNode&&l.isStream(e)?s.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):n.prepareContent("the loaded zip file",e,!0,t.optimizedBinaryString,t.base64).then((function(e){var i=new o(t);return i.load(e),i})).then((function(e){var i=[s.Promise.resolve(e)],n=e.files;if(t.checkCRC32)for(var r=0;r<n.length;r++)i.push(h(n[r]));return s.Promise.all(i)})).then((function(e){for(var s=e.shift(),r=s.files,o=0;o<r.length;o++){var a=r[o],l=a.fileNameStr,h=n.resolve(a.fileNameStr);i.file(h,a.decompressed,{binary:!0,optimizedBinaryString:!0,date:a.date,dir:a.dir,comment:a.fileCommentStr.length?a.fileCommentStr:null,unixPermissions:a.unixPermissions,dosPermissions:a.dosPermissions,createFolders:t.createFolders}),a.dir||(i.file(h).unsafeOriginalName=l)}return s.zipComment.length&&(i.comment=s.zipComment),i}))}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(e,t,i){var n=e("../utils"),s=e("../stream/GenericWorker");function r(e,t){s.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}n.inherits(r,s),r.prototype._bindStream=function(e){var t=this;(this._stream=e).pause(),e.on("data",(function(e){t.push({data:e,meta:{percent:0}})})).on("error",(function(e){t.isPaused?this.generatedError=e:t.error(e)})).on("end",(function(){t.isPaused?t._upstreamEnded=!0:t.end()}))},r.prototype.pause=function(){return!!s.prototype.pause.call(this)&&(this._stream.pause(),!0)},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},t.exports=r},{"../stream/GenericWorker":28,"../utils":32}],13:[function(e,t,i){var n=e("readable-stream").Readable;function s(e,t,i){n.call(this,t),this._helper=e;var s=this;e.on("data",(function(e,t){s.push(e)||s._helper.pause(),i&&i(t)})).on("error",(function(e){s.emit("error",e)})).on("end",(function(){s.push(null)}))}e("../utils").inherits(s,n),s.prototype._read=function(){this._helper.resume()},t.exports=s},{"../utils":32,"readable-stream":16}],14:[function(e,t,i){t.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if("number"==typeof e)throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&"function"==typeof e.on&&"function"==typeof e.pause&&"function"==typeof e.resume}}},{}],15:[function(e,t,i){function n(e,t,i){var n,s=r.getTypeOf(t),a=r.extend(i||{},l);a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),"string"==typeof a.unixPermissions&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&16384&a.unixPermissions&&(a.dir=!0),a.dosPermissions&&16&a.dosPermissions&&(a.dir=!0),a.dir&&(e=_(e)),a.createFolders&&(n=f(e))&&m.call(this,n,!0);var u="string"===s&&!1===a.binary&&!1===a.base64;i&&void 0!==i.binary||(a.binary=!u),(t instanceof h&&0===t.uncompressedSize||a.dir||!t||0===t.length)&&(a.base64=!1,a.binary=!0,t="",a.compression="STORE",s="string");var g;g=t instanceof h||t instanceof o?t:d.isNode&&d.isStream(t)?new p(e,t):r.prepareContent(e,t,a.binary,a.optimizedBinaryString,a.base64);var v=new c(e,g,a);this.files[e]=v}var s=e("./utf8"),r=e("./utils"),o=e("./stream/GenericWorker"),a=e("./stream/StreamHelper"),l=e("./defaults"),h=e("./compressedObject"),c=e("./zipObject"),u=e("./generate"),d=e("./nodejsUtils"),p=e("./nodejs/NodejsStreamInputAdapter"),f=function(e){"/"===e.slice(-1)&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return 0<t?e.substring(0,t):""},_=function(e){return"/"!==e.slice(-1)&&(e+="/"),e},m=function(e,t){return t=void 0!==t?t:l.createFolders,e=_(e),this.files[e]||n.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function g(e){return"[object RegExp]"===Object.prototype.toString.call(e)}var v={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,i,n;for(t in this.files)n=this.files[t],(i=t.slice(this.root.length,t.length))&&t.slice(0,this.root.length)===this.root&&e(i,n)},filter:function(e){var t=[];return this.forEach((function(i,n){e(i,n)&&t.push(n)})),t},file:function(e,t,i){if(1!==arguments.length)return e=this.root+e,n.call(this,e,t,i),this;if(g(e)){var s=e;return this.filter((function(e,t){return!t.dir&&s.test(e)}))}var r=this.files[this.root+e];return r&&!r.dir?r:null},folder:function(e){if(!e)return this;if(g(e))return this.filter((function(t,i){return i.dir&&e.test(t)}));var t=this.root+e,i=m.call(this,t),n=this.clone();return n.root=i.name,n},remove:function(e){e=this.root+e;var t=this.files[e];if(t||("/"!==e.slice(-1)&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var i=this.filter((function(t,i){return i.name.slice(0,e.length)===e})),n=0;n<i.length;n++)delete this.files[i[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,i={};try{if((i=r.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:s.utf8encode})).type=i.type.toLowerCase(),i.compression=i.compression.toUpperCase(),"binarystring"===i.type&&(i.type="string"),!i.type)throw new Error("No output type specified.");r.checkSupport(i.type),"darwin"!==i.platform&&"freebsd"!==i.platform&&"linux"!==i.platform&&"sunos"!==i.platform||(i.platform="UNIX"),"win32"===i.platform&&(i.platform="DOS");var n=i.comment||this.comment||"";t=u.generateWorker(this,i,n)}catch(e){(t=new o("error")).error(e)}return new a(t,i.type||"string",i.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return(e=e||{}).type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};t.exports=v},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(e,t,i){t.exports=e("stream")},{stream:void 0}],17:[function(e,t,i){var n=e("./DataReader");function s(e){n.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=255&e[t]}e("../utils").inherits(s,n),s.prototype.byteAt=function(e){return this.data[this.zero+e]},s.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),s=e.charCodeAt(3),r=this.length-4;0<=r;--r)if(this.data[r]===t&&this.data[r+1]===i&&this.data[r+2]===n&&this.data[r+3]===s)return r-this.zero;return-1},s.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),s=e.charCodeAt(3),r=this.readData(4);return t===r[0]&&i===r[1]&&n===r[2]&&s===r[3]},s.prototype.readData=function(e){if(this.checkOffset(e),0===e)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./DataReader":18}],18:[function(e,t,i){var n=e("../utils");function s(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}s.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t,i=0;for(this.checkOffset(e),t=this.index+e-1;t>=this.index;t--)i=(i<<8)+this.byteAt(t);return this.index+=e,i},readString:function(e){return n.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=s},{"../utils":32}],19:[function(e,t,i){var n=e("./Uint8ArrayReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,i){var n=e("./DataReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},s.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},s.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},s.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./DataReader":18}],21:[function(e,t,i){var n=e("./ArrayReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,i){var n=e("../utils"),s=e("../support"),r=e("./ArrayReader"),o=e("./StringReader"),a=e("./NodeBufferReader"),l=e("./Uint8ArrayReader");t.exports=function(e){var t=n.getTypeOf(e);return n.checkSupport(t),"string"!==t||s.uint8array?"nodebuffer"===t?new a(e):s.uint8array?new l(n.transformTo("uint8array",e)):new r(n.transformTo("array",e)):new o(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\b"},{}],24:[function(e,t,i){var n=e("./GenericWorker"),s=e("../utils");function r(e){n.call(this,"ConvertWorker to "+e),this.destType=e}s.inherits(r,n),r.prototype.processChunk=function(e){this.push({data:s.transformTo(this.destType,e.data),meta:e.meta})},t.exports=r},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,i){var n=e("./GenericWorker"),s=e("../crc32");function r(){n.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(r,n),r.prototype.processChunk=function(e){this.streamInfo.crc32=s(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=r},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,i){var n=e("../utils"),s=e("./GenericWorker");function r(e){s.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}n.inherits(r,s),r.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}s.prototype.processChunk.call(this,e)},t.exports=r},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,i){var n=e("../utils"),s=e("./GenericWorker");function r(e){s.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then((function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=n.getTypeOf(e),t.isPaused||t._tickAndRepeat()}),(function(e){t.error(e)}))}n.inherits(r,s),r.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,n.delay(this._tickAndRepeat,[],this)),!0)},r.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(n.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},r.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=r},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,i){function n(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}n.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var i=0;i<this._listeners[e].length;i++)this._listeners[e][i].call(this,t)},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",(function(e){t.processChunk(e)})),e.on("end",(function(){t.end()})),e.on("error",(function(e){t.error(e)})),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var e=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e)},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}},t.exports=n},{}],29:[function(e,t,i){var n=e("../utils"),s=e("./ConvertWorker"),r=e("./GenericWorker"),o=e("../base64"),a=e("../support"),l=e("../external"),h=null;if(a.nodestream)try{h=e("../nodejs/NodejsStreamOutputAdapter")}catch(e){}function c(e,t,i){var o=t;switch(t){case"blob":case"arraybuffer":o="uint8array";break;case"base64":o="string"}try{this._internalType=o,this._outputType=t,this._mimeType=i,n.checkSupport(o),this._worker=e.pipe(new s(o)),e.lock()}catch(e){this._worker=new r("error"),this._worker.error(e)}}c.prototype={accumulate:function(e){return function(e,t){return new l.Promise((function(i,s){var r=[],a=e._internalType,l=e._outputType,h=e._mimeType;e.on("data",(function(e,i){r.push(e),t&&t(i)})).on("error",(function(e){r=[],s(e)})).on("end",(function(){try{var e=function(e,t,i){switch(e){case"blob":return n.newBlob(n.transformTo("arraybuffer",t),i);case"base64":return o.encode(t);default:return n.transformTo(e,t)}}(l,function(e,t){var i,n=0,s=null,r=0;for(i=0;i<t.length;i++)r+=t[i].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(s=new Uint8Array(r),i=0;i<t.length;i++)s.set(t[i],n),n+=t[i].length;return s;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}(a,r),h);i(e)}catch(e){s(e)}r=[]})).resume()}))}(this,e)},on:function(e,t){var i=this;return"data"===e?this._worker.on(e,(function(e){t.call(i,e.data,e.meta)})):this._worker.on(e,(function(){n.delay(t,arguments,i)})),this},resume:function(){return n.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(n.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new h(this,{objectMode:"nodebuffer"!==this._outputType},e)}},t.exports=c},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(e,t,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,i.nodebuffer="undefined"!=typeof Buffer,i.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)i.blob=!1;else{var n=new ArrayBuffer(0);try{i.blob=0===new Blob([n],{type:"application/zip"}).size}catch(e){try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(n),i.blob=0===s.getBlob("application/zip").size}catch(e){i.blob=!1}}}try{i.nodestream=!!e("readable-stream").Readable}catch(e){i.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,i){for(var n=e("./utils"),s=e("./support"),r=e("./nodejsUtils"),o=e("./stream/GenericWorker"),a=new Array(256),l=0;l<256;l++)a[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function h(){o.call(this,"utf-8 decode"),this.leftOver=null}function c(){o.call(this,"utf-8 encode")}a[254]=a[254]=1,i.utf8encode=function(e){return s.nodebuffer?r.newBufferFrom(e,"utf-8"):function(e){var t,i,n,r,o,a=e.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(t=s.uint8array?new Uint8Array(l):new Array(l),r=o=0;o<l;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),i<128?t[o++]=i:(i<2048?t[o++]=192|i>>>6:(i<65536?t[o++]=224|i>>>12:(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63),t[o++]=128|i>>>6&63),t[o++]=128|63&i);return t}(e)},i.utf8decode=function(e){return s.nodebuffer?n.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,i,s,r,o=e.length,l=new Array(2*o);for(t=i=0;t<o;)if((s=e[t++])<128)l[i++]=s;else if(4<(r=a[s]))l[i++]=65533,t+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&t<o;)s=s<<6|63&e[t++],r--;1<r?l[i++]=65533:s<65536?l[i++]=s:(s-=65536,l[i++]=55296|s>>10&1023,l[i++]=56320|1023&s)}return l.length!==i&&(l.subarray?l=l.subarray(0,i):l.length=i),n.applyFromCharCode(l)}(e=n.transformTo(s.uint8array?"uint8array":"array",e))},n.inherits(h,o),h.prototype.processChunk=function(e){var t=n.transformTo(s.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var r=t;(t=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),t.set(r,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var o=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+a[e[i]]>t?i:t}(t),l=t;o!==t.length&&(s.uint8array?(l=t.subarray(0,o),this.leftOver=t.subarray(o,t.length)):(l=t.slice(0,o),this.leftOver=t.slice(o,t.length))),this.push({data:i.utf8decode(l),meta:e.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=h,n.inherits(c,o),c.prototype.processChunk=function(e){this.push({data:i.utf8encode(e.data),meta:e.meta})},i.Utf8EncodeWorker=c},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,i){var n=e("./support"),s=e("./base64"),r=e("./nodejsUtils"),o=e("./external");function a(e){return e}function l(e,t){for(var i=0;i<e.length;++i)t[i]=255&e.charCodeAt(i);return t}e("setimmediate"),i.newBlob=function(e,t){i.checkSupport("blob");try{return new Blob([e],{type:t})}catch(i){try{var n=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return n.append(e),n.getBlob(t)}catch(e){throw new Error("Bug : can't construct the Blob.")}}};var h={stringifyByChunk:function(e,t,i){var n=[],s=0,r=e.length;if(r<=i)return String.fromCharCode.apply(null,e);for(;s<r;)"array"===t||"nodebuffer"===t?n.push(String.fromCharCode.apply(null,e.slice(s,Math.min(s+i,r)))):n.push(String.fromCharCode.apply(null,e.subarray(s,Math.min(s+i,r)))),s+=i;return n.join("")},stringifyByChar:function(e){for(var t="",i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t},applyCanBeUsed:{uint8array:function(){try{return n.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(e){return!1}}(),nodebuffer:function(){try{return n.nodebuffer&&1===String.fromCharCode.apply(null,r.allocBuffer(1)).length}catch(e){return!1}}()}};function c(e){var t=65536,n=i.getTypeOf(e),s=!0;if("uint8array"===n?s=h.applyCanBeUsed.uint8array:"nodebuffer"===n&&(s=h.applyCanBeUsed.nodebuffer),s)for(;1<t;)try{return h.stringifyByChunk(e,n,t)}catch(e){t=Math.floor(t/2)}return h.stringifyByChar(e)}function u(e,t){for(var i=0;i<e.length;i++)t[i]=e[i];return t}i.applyFromCharCode=c;var d={};d.string={string:a,array:function(e){return l(e,new Array(e.length))},arraybuffer:function(e){return d.string.uint8array(e).buffer},uint8array:function(e){return l(e,new Uint8Array(e.length))},nodebuffer:function(e){return l(e,r.allocBuffer(e.length))}},d.array={string:c,array:a,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return r.newBufferFrom(e)}},d.arraybuffer={string:function(e){return c(new Uint8Array(e))},array:function(e){return u(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:a,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return r.newBufferFrom(new Uint8Array(e))}},d.uint8array={string:c,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:a,nodebuffer:function(e){return r.newBufferFrom(e)}},d.nodebuffer={string:c,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return d.nodebuffer.uint8array(e).buffer},uint8array:function(e){return u(e,new Uint8Array(e.length))},nodebuffer:a},i.transformTo=function(e,t){if(t=t||"",!e)return t;i.checkSupport(e);var n=i.getTypeOf(t);return d[n][e](t)},i.resolve=function(e){for(var t=e.split("/"),i=[],n=0;n<t.length;n++){var s=t[n];"."===s||""===s&&0!==n&&n!==t.length-1||(".."===s?i.pop():i.push(s))}return i.join("/")},i.getTypeOf=function(e){return"string"==typeof e?"string":"[object Array]"===Object.prototype.toString.call(e)?"array":n.nodebuffer&&r.isBuffer(e)?"nodebuffer":n.uint8array&&e instanceof Uint8Array?"uint8array":n.arraybuffer&&e instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(e){if(!n[e.toLowerCase()])throw new Error(e+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(e){var t,i,n="";for(i=0;i<(e||"").length;i++)n+="\\x"+((t=e.charCodeAt(i))<16?"0":"")+t.toString(16).toUpperCase();return n},i.delay=function(e,t,i){setImmediate((function(){e.apply(i||null,t||[])}))},i.inherits=function(e,t){function i(){}i.prototype=t.prototype,e.prototype=new i},i.extend=function(){var e,t,i={};for(e=0;e<arguments.length;e++)for(t in arguments[e])Object.prototype.hasOwnProperty.call(arguments[e],t)&&void 0===i[t]&&(i[t]=arguments[e][t]);return i},i.prepareContent=function(e,t,r,a,h){return o.Promise.resolve(t).then((function(e){return n.blob&&(e instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(e)))&&"undefined"!=typeof FileReader?new o.Promise((function(t,i){var n=new FileReader;n.onload=function(e){t(e.target.result)},n.onerror=function(e){i(e.target.error)},n.readAsArrayBuffer(e)})):e})).then((function(t){var c=i.getTypeOf(t);return c?("arraybuffer"===c?t=i.transformTo("uint8array",t):"string"===c&&(h?t=s.decode(t):r&&!0!==a&&(t=function(e){return l(e,n.uint8array?new Uint8Array(e.length):new Array(e.length))}(t))),t):o.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))}))}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(e,t,i){var n=e("./reader/readerFor"),s=e("./utils"),r=e("./signature"),o=e("./zipEntry"),a=e("./support");function l(e){this.files=[],this.loadOptions=e}l.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+s.pretty(t)+", expected "+s.pretty(e)+")")}},isSignature:function(e,t){var i=this.reader.index;this.reader.setIndex(e);var n=this.reader.readString(4)===t;return this.reader.setIndex(i),n},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=a.uint8array?"uint8array":"array",i=s.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e,t,i,n=this.zip64EndOfCentralSize-44;0<n;)e=this.reader.readInt(2),t=this.reader.readInt(4),i=this.reader.readData(t),this.zip64ExtensibleData[e]={id:e,length:t,value:i}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(r.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(r.CENTRAL_FILE_HEADER);)(e=new o({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(r.CENTRAL_DIRECTORY_END);if(e<0)throw this.isSignature(0,r.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(e);var t=e;if(this.checkSignature(r.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===s.MAX_VALUE_16BITS||this.diskWithCentralDirStart===s.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===s.MAX_VALUE_16BITS||this.centralDirRecords===s.MAX_VALUE_16BITS||this.centralDirSize===s.MAX_VALUE_32BITS||this.centralDirOffset===s.MAX_VALUE_32BITS){if(this.zip64=!0,(e=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,r.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var i=this.centralDirOffset+this.centralDirSize;this.zip64&&(i+=20,i+=12+this.zip64EndOfCentralSize);var n=t-i;if(0<n)this.isSignature(t,r.CENTRAL_FILE_HEADER)||(this.reader.zero=n);else if(n<0)throw new Error("Corrupted zip: missing "+Math.abs(n)+" bytes.")},prepareReader:function(e){this.reader=n(e)},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},t.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(e,t,i){var n=e("./reader/readerFor"),s=e("./utils"),r=e("./compressedObject"),o=e("./crc32"),a=e("./utf8"),l=e("./compressions"),h=e("./support");function c(e,t){this.options=e,this.loadOptions=t}c.prototype={isEncrypted:function(){return 1==(1&this.bitFlag)},useUTF8:function(){return 2048==(2048&this.bitFlag)},readLocalPart:function(e){var t,i;if(e.skip(22),this.fileNameLength=e.readInt(2),i=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(i),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(t=function(e){for(var t in l)if(Object.prototype.hasOwnProperty.call(l,t)&&l[t].magic===e)return l[t];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new r(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=n(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,i,n,s=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4<s;)t=e.readInt(2),i=e.readInt(2),n=e.readData(i),this.extraFields[t]={id:t,length:i,value:n};e.setIndex(s)},handleUTF8:function(){var e=h.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var t=this.findExtraFieldUnicodePath();if(null!==t)this.fileNameStr=t;else{var i=s.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var n=this.findExtraFieldUnicodeComment();if(null!==n)this.fileCommentStr=n;else{var r=s.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=n(e.value);return 1!==t.readInt(1)||o(this.fileName)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=n(e.value);return 1!==t.readInt(1)||o(this.fileComment)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null}},t.exports=c},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(e,t,i){function n(e,t,i){this.name=e,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=t,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}}var s=e("./stream/StreamHelper"),r=e("./stream/DataWorker"),o=e("./utf8"),a=e("./compressedObject"),l=e("./stream/GenericWorker");n.prototype={internalStream:function(e){var t=null,i="string";try{if(!e)throw new Error("No output type specified.");var n="string"===(i=e.toLowerCase())||"text"===i;"binarystring"!==i&&"text"!==i||(i="string"),t=this._decompressWorker();var r=!this._dataBinary;r&&!n&&(t=t.pipe(new o.Utf8EncodeWorker)),!r&&n&&(t=t.pipe(new o.Utf8DecodeWorker))}catch(e){(t=new l("error")).error(e)}return new s(t,i,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof a&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new o.Utf8EncodeWorker)),a.createWorkerFrom(i,e,t)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof l?this._data:new r(this._data)}};for(var h=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],c=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},u=0;u<h.length;u++)n.prototype[h[u]]=c;t.exports=n},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(e,t,n){(function(e){var i,n,s=e.MutationObserver||e.WebKitMutationObserver;if(s){var r=0,o=new s(c),a=e.document.createTextNode("");o.observe(a,{characterData:!0}),i=function(){a.data=r=++r%2}}else if(e.setImmediate||void 0===e.MessageChannel)i="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var t=e.document.createElement("script");t.onreadystatechange=function(){c(),t.onreadystatechange=null,t.parentNode.removeChild(t),t=null},e.document.documentElement.appendChild(t)}:function(){setTimeout(c,0)};else{var l=new e.MessageChannel;l.port1.onmessage=c,i=function(){l.port2.postMessage(0)}}var h=[];function c(){var e,t;n=!0;for(var i=h.length;i;){for(t=h,h=[],e=-1;++e<i;)t[e]();i=h.length}n=!1}t.exports=function(e){1!==h.push(e)||n||i()}}).call(this,void 0!==i.g?i.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(e,t,i){var n=e("immediate");function s(){}var r={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function h(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,e!==s&&p(this,e)}function c(e,t,i){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function u(e,t,i){n((function(){var n;try{n=t(i)}catch(n){return r.reject(e,n)}n===e?r.reject(e,new TypeError("Cannot resolve promise with itself")):r.resolve(e,n)}))}function d(e){var t=e&&e.then;if(e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof t)return function(){t.apply(e,arguments)}}function p(e,t){var i=!1;function n(t){i||(i=!0,r.reject(e,t))}function s(t){i||(i=!0,r.resolve(e,t))}var o=f((function(){t(s,n)}));"error"===o.status&&n(o.value)}function f(e,t){var i={};try{i.value=e(t),i.status="success"}catch(e){i.status="error",i.value=e}return i}(t.exports=h).prototype.finally=function(e){if("function"!=typeof e)return this;var t=this.constructor;return this.then((function(i){return t.resolve(e()).then((function(){return i}))}),(function(i){return t.resolve(e()).then((function(){throw i}))}))},h.prototype.catch=function(e){return this.then(null,e)},h.prototype.then=function(e,t){if("function"!=typeof e&&this.state===a||"function"!=typeof t&&this.state===o)return this;var i=new this.constructor(s);return this.state!==l?u(i,this.state===a?e:t,this.outcome):this.queue.push(new c(i,e,t)),i},c.prototype.callFulfilled=function(e){r.resolve(this.promise,e)},c.prototype.otherCallFulfilled=function(e){u(this.promise,this.onFulfilled,e)},c.prototype.callRejected=function(e){r.reject(this.promise,e)},c.prototype.otherCallRejected=function(e){u(this.promise,this.onRejected,e)},r.resolve=function(e,t){var i=f(d,t);if("error"===i.status)return r.reject(e,i.value);var n=i.value;if(n)p(e,n);else{e.state=a,e.outcome=t;for(var s=-1,o=e.queue.length;++s<o;)e.queue[s].callFulfilled(t)}return e},r.reject=function(e,t){e.state=o,e.outcome=t;for(var i=-1,n=e.queue.length;++i<n;)e.queue[i].callRejected(t);return e},h.resolve=function(e){return e instanceof this?e:r.resolve(new this(s),e)},h.reject=function(e){var t=new this(s);return r.reject(t,e)},h.all=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var o=new Array(i),a=0,l=-1,h=new this(s);++l<i;)c(e[l],l);return h;function c(e,s){t.resolve(e).then((function(e){o[s]=e,++a!==i||n||(n=!0,r.resolve(h,o))}),(function(e){n||(n=!0,r.reject(h,e))}))}},h.race=function(e){if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var t=e.length,i=!1;if(!t)return this.resolve([]);for(var n,o=-1,a=new this(s);++o<t;)n=e[o],this.resolve(n).then((function(e){i||(i=!0,r.resolve(a,e))}),(function(e){i||(i=!0,r.reject(a,e))}));return a}},{immediate:36}],38:[function(e,t,i){var n={};(0,e("./lib/utils/common").assign)(n,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=n},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(e,t,i){var n=e("./zlib/deflate"),s=e("./utils/common"),r=e("./utils/strings"),o=e("./zlib/messages"),a=e("./zlib/zstream"),l=Object.prototype.toString,h=0,c=-1,u=0,d=8;function p(e){if(!(this instanceof p))return new p(e);this.options=s.assign({level:c,method:d,chunkSize:16384,windowBits:15,memLevel:8,strategy:u,to:""},e||{});var t=this.options;t.raw&&0<t.windowBits?t.windowBits=-t.windowBits:t.gzip&&0<t.windowBits&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=n.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==h)throw new Error(o[i]);if(t.header&&n.deflateSetHeader(this.strm,t.header),t.dictionary){var f;if(f="string"==typeof t.dictionary?r.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=n.deflateSetDictionary(this.strm,f))!==h)throw new Error(o[i]);this._dict_set=!0}}function f(e,t){var i=new p(t);if(i.push(e,!0),i.err)throw i.msg||o[i.err];return i.result}p.prototype.push=function(e,t){var i,o,a=this.strm,c=this.options.chunkSize;if(this.ended)return!1;o=t===~~t?t:!0===t?4:0,"string"==typeof e?a.input=r.string2buf(e):"[object ArrayBuffer]"===l.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new s.Buf8(c),a.next_out=0,a.avail_out=c),1!==(i=n.deflate(a,o))&&i!==h)return this.onEnd(i),!(this.ended=!0);0!==a.avail_out&&(0!==a.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(r.buf2binstring(s.shrinkBuf(a.output,a.next_out))):this.onData(s.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==i);return 4===o?(i=n.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===h):2!==o||(this.onEnd(h),!(a.avail_out=0))},p.prototype.onData=function(e){this.chunks.push(e)},p.prototype.onEnd=function(e){e===h&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Deflate=p,i.deflate=f,i.deflateRaw=function(e,t){return(t=t||{}).raw=!0,f(e,t)},i.gzip=function(e,t){return(t=t||{}).gzip=!0,f(e,t)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(e,t,i){var n=e("./zlib/inflate"),s=e("./utils/common"),r=e("./utils/strings"),o=e("./zlib/constants"),a=e("./zlib/messages"),l=e("./zlib/zstream"),h=e("./zlib/gzheader"),c=Object.prototype.toString;function u(e){if(!(this instanceof u))return new u(e);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=n.inflateInit2(this.strm,t.windowBits);if(i!==o.Z_OK)throw new Error(a[i]);this.header=new h,n.inflateGetHeader(this.strm,this.header)}function d(e,t){var i=new u(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}u.prototype.push=function(e,t){var i,a,l,h,u,d,p=this.strm,f=this.options.chunkSize,_=this.options.dictionary,m=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof e?p.input=r.binstring2buf(e):"[object ArrayBuffer]"===c.call(e)?p.input=new Uint8Array(e):p.input=e,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new s.Buf8(f),p.next_out=0,p.avail_out=f),(i=n.inflate(p,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&_&&(d="string"==typeof _?r.string2buf(_):"[object ArrayBuffer]"===c.call(_)?new Uint8Array(_):_,i=n.inflateSetDictionary(this.strm,d)),i===o.Z_BUF_ERROR&&!0===m&&(i=o.Z_OK,m=!1),i!==o.Z_STREAM_END&&i!==o.Z_OK)return this.onEnd(i),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&i!==o.Z_STREAM_END&&(0!==p.avail_in||a!==o.Z_FINISH&&a!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(l=r.utf8border(p.output,p.next_out),h=p.next_out-l,u=r.buf2string(p.output,l),p.next_out=h,p.avail_out=f-h,h&&s.arraySet(p.output,p.output,l,h,0),this.onData(u)):this.onData(s.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(m=!0)}while((0<p.avail_in||0===p.avail_out)&&i!==o.Z_STREAM_END);return i===o.Z_STREAM_END&&(a=o.Z_FINISH),a===o.Z_FINISH?(i=n.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},u.prototype.onData=function(e){this.chunks.push(e)},u.prototype.onEnd=function(e){e===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Inflate=u,i.inflate=d,i.inflateRaw=function(e,t){return(t=t||{}).raw=!0,d(e,t)},i.ungzip=d},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(e,t,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;i.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var n in i)i.hasOwnProperty(n)&&(e[n]=i[n])}}return e},i.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var s={arraySet:function(e,t,i,n,s){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+n),s);else for(var r=0;r<n;r++)e[s+r]=t[i+r]},flattenChunks:function(e){var t,i,n,s,r,o;for(t=n=0,i=e.length;t<i;t++)n+=e[t].length;for(o=new Uint8Array(n),t=s=0,i=e.length;t<i;t++)r=e[t],o.set(r,s),s+=r.length;return o}},r={arraySet:function(e,t,i,n,s){for(var r=0;r<n;r++)e[s+r]=t[i+r]},flattenChunks:function(e){return[].concat.apply([],e)}};i.setTyped=function(e){e?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,s)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,r))},i.setTyped(n)},{}],42:[function(e,t,i){var n=e("./common"),s=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch(e){s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){r=!1}for(var o=new n.Buf8(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function l(e,t){if(t<65537&&(e.subarray&&r||!e.subarray&&s))return String.fromCharCode.apply(null,n.shrinkBuf(e,t));for(var i="",o=0;o<t;o++)i+=String.fromCharCode(e[o]);return i}o[254]=o[254]=1,i.string2buf=function(e){var t,i,s,r,o,a=e.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(t=new n.Buf8(l),r=o=0;o<l;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),i<128?t[o++]=i:(i<2048?t[o++]=192|i>>>6:(i<65536?t[o++]=224|i>>>12:(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63),t[o++]=128|i>>>6&63),t[o++]=128|63&i);return t},i.buf2binstring=function(e){return l(e,e.length)},i.binstring2buf=function(e){for(var t=new n.Buf8(e.length),i=0,s=t.length;i<s;i++)t[i]=e.charCodeAt(i);return t},i.buf2string=function(e,t){var i,n,s,r,a=t||e.length,h=new Array(2*a);for(i=n=0;i<a;)if((s=e[i++])<128)h[n++]=s;else if(4<(r=o[s]))h[n++]=65533,i+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&i<a;)s=s<<6|63&e[i++],r--;1<r?h[n++]=65533:s<65536?h[n++]=s:(s-=65536,h[n++]=55296|s>>10&1023,h[n++]=56320|1023&s)}return l(h,n)},i.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+o[e[i]]>t?i:t}},{"./common":41}],43:[function(e,t,i){t.exports=function(e,t,i,n){for(var s=65535&e|0,r=e>>>16&65535|0,o=0;0!==i;){for(i-=o=2e3<i?2e3:i;r=r+(s=s+t[n++]|0)|0,--o;);s%=65521,r%=65521}return s|r<<16|0}},{}],44:[function(e,t,i){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(e,t,i){var n=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,i,s){var r=n,o=s+i;e^=-1;for(var a=s;a<o;a++)e=e>>>8^r[255&(e^t[a])];return-1^e}},{}],46:[function(e,t,i){var n,s=e("../utils/common"),r=e("./trees"),o=e("./adler32"),a=e("./crc32"),l=e("./messages"),h=0,c=0,u=-2,d=2,p=8,f=286,_=30,m=19,g=2*f+1,v=15,y=3,x=258,b=x+y+1,T=42,S=113;function E(e,t){return e.msg=l[t],t}function C(e){return(e<<1)-(4<e?9:0)}function A(e){for(var t=e.length;0<=--t;)e[t]=0}function P(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(s.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function R(e,t){r._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,P(e.strm)}function M(e,t){e.pending_buf[e.pending++]=t}function I(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function D(e,t){var i,n,s=e.max_chain_length,r=e.strstart,o=e.prev_length,a=e.nice_match,l=e.strstart>e.w_size-b?e.strstart-(e.w_size-b):0,h=e.window,c=e.w_mask,u=e.prev,d=e.strstart+x,p=h[r+o-1],f=h[r+o];e.prev_length>=e.good_match&&(s>>=2),a>e.lookahead&&(a=e.lookahead);do{if(h[(i=t)+o]===f&&h[i+o-1]===p&&h[i]===h[r]&&h[++i]===h[r+1]){r+=2,i++;do{}while(h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&r<d);if(n=x-(d-r),r=d-x,o<n){if(e.match_start=t,a<=(o=n))break;p=h[r+o-1],f=h[r+o]}}}while((t=u[t&c])>l&&0!=--s);return o<=e.lookahead?o:e.lookahead}function O(e){var t,i,n,r,l,h,c,u,d,p,f=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=f+(f-b)){for(s.arraySet(e.window,e.window,f,f,0),e.match_start-=f,e.strstart-=f,e.block_start-=f,t=i=e.hash_size;n=e.head[--t],e.head[t]=f<=n?n-f:0,--i;);for(t=i=f;n=e.prev[--t],e.prev[t]=f<=n?n-f:0,--i;);r+=f}if(0===e.strm.avail_in)break;if(h=e.strm,c=e.window,u=e.strstart+e.lookahead,p=void 0,(d=r)<(p=h.avail_in)&&(p=d),i=0===p?0:(h.avail_in-=p,s.arraySet(c,h.input,h.next_in,p,u),1===h.state.wrap?h.adler=o(h.adler,c,p,u):2===h.state.wrap&&(h.adler=a(h.adler,c,p,u)),h.next_in+=p,h.total_in+=p,p),e.lookahead+=i,e.lookahead+e.insert>=y)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+y-1])&e.hash_mask,e.prev[l&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=l,l++,e.insert--,!(e.lookahead+e.insert<y)););}while(e.lookahead<b&&0!==e.strm.avail_in)}function w(e,t){for(var i,n;;){if(e.lookahead<b){if(O(e),e.lookahead<b&&t===h)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=y&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+y-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-b&&(e.match_length=D(e,i)),e.match_length>=y)if(n=r._tr_tally(e,e.strstart-e.match_start,e.match_length-y),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=y){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+y-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart,0!=--e.match_length;);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(R(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<y-1?e.strstart:y-1,4===t?(R(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(R(e,!1),0===e.strm.avail_out)?1:2}function N(e,t){for(var i,n,s;;){if(e.lookahead<b){if(O(e),e.lookahead<b&&t===h)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=y&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+y-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=y-1,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-b&&(e.match_length=D(e,i),e.match_length<=5&&(1===e.strategy||e.match_length===y&&4096<e.strstart-e.match_start)&&(e.match_length=y-1)),e.prev_length>=y&&e.match_length<=e.prev_length){for(s=e.strstart+e.lookahead-y,n=r._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-y),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=s&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+y-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!=--e.prev_length;);if(e.match_available=0,e.match_length=y-1,e.strstart++,n&&(R(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((n=r._tr_tally(e,0,e.window[e.strstart-1]))&&R(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=r._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<y-1?e.strstart:y-1,4===t?(R(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(R(e,!1),0===e.strm.avail_out)?1:2}function F(e,t,i,n,s){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=s}function L(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=p,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new s.Buf16(2*g),this.dyn_dtree=new s.Buf16(2*(2*_+1)),this.bl_tree=new s.Buf16(2*(2*m+1)),A(this.dyn_ltree),A(this.dyn_dtree),A(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new s.Buf16(v+1),this.heap=new s.Buf16(2*f+1),A(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new s.Buf16(2*f+1),A(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function B(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=d,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?T:S,e.adler=2===t.wrap?0:1,t.last_flush=h,r._tr_init(t),c):E(e,u)}function U(e){var t=B(e);return t===c&&function(e){e.window_size=2*e.w_size,A(e.head),e.max_lazy_match=n[e.level].max_lazy,e.good_match=n[e.level].good_length,e.nice_match=n[e.level].nice_length,e.max_chain_length=n[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=y-1,e.match_available=0,e.ins_h=0}(e.state),t}function V(e,t,i,n,r,o){if(!e)return u;var a=1;if(-1===t&&(t=6),n<0?(a=0,n=-n):15<n&&(a=2,n-=16),r<1||9<r||i!==p||n<8||15<n||t<0||9<t||o<0||4<o)return E(e,u);8===n&&(n=9);var l=new L;return(e.state=l).strm=e,l.wrap=a,l.gzhead=null,l.w_bits=n,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=r+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+y-1)/y),l.window=new s.Buf8(2*l.w_size),l.head=new s.Buf16(l.hash_size),l.prev=new s.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new s.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=t,l.strategy=o,l.method=i,U(e)}n=[new F(0,0,0,0,(function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(O(e),0===e.lookahead&&t===h)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,R(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-b&&(R(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(R(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(R(e,!1),e.strm.avail_out),1)})),new F(4,4,8,4,w),new F(4,5,16,8,w),new F(4,6,32,32,w),new F(4,4,16,16,N),new F(8,16,32,32,N),new F(8,16,128,128,N),new F(8,32,128,256,N),new F(32,128,258,1024,N),new F(32,258,258,4096,N)],i.deflateInit=function(e,t){return V(e,t,p,15,8,0)},i.deflateInit2=V,i.deflateReset=U,i.deflateResetKeep=B,i.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?u:(e.state.gzhead=t,c):u},i.deflate=function(e,t){var i,s,o,l;if(!e||!e.state||5<t||t<0)return e?E(e,u):u;if(s=e.state,!e.output||!e.input&&0!==e.avail_in||666===s.status&&4!==t)return E(e,0===e.avail_out?-5:u);if(s.strm=e,i=s.last_flush,s.last_flush=t,s.status===T)if(2===s.wrap)e.adler=0,M(s,31),M(s,139),M(s,8),s.gzhead?(M(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),M(s,255&s.gzhead.time),M(s,s.gzhead.time>>8&255),M(s,s.gzhead.time>>16&255),M(s,s.gzhead.time>>24&255),M(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),M(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(M(s,255&s.gzhead.extra.length),M(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(e.adler=a(e.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(M(s,0),M(s,0),M(s,0),M(s,0),M(s,0),M(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),M(s,3),s.status=S);else{var d=p+(s.w_bits-8<<4)<<8;d|=(2<=s.strategy||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(d|=32),d+=31-d%31,s.status=S,I(s,d),0!==s.strstart&&(I(s,e.adler>>>16),I(s,65535&e.adler)),e.adler=1}if(69===s.status)if(s.gzhead.extra){for(o=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),P(e),o=s.pending,s.pending!==s.pending_buf_size));)M(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73;if(73===s.status)if(s.gzhead.name){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),P(e),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,M(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.gzindex=0,s.status=91)}else s.status=91;if(91===s.status)if(s.gzhead.comment){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),P(e),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,M(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.status=103)}else s.status=103;if(103===s.status&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&P(e),s.pending+2<=s.pending_buf_size&&(M(s,255&e.adler),M(s,e.adler>>8&255),e.adler=0,s.status=S)):s.status=S),0!==s.pending){if(P(e),0===e.avail_out)return s.last_flush=-1,c}else if(0===e.avail_in&&C(t)<=C(i)&&4!==t)return E(e,-5);if(666===s.status&&0!==e.avail_in)return E(e,-5);if(0!==e.avail_in||0!==s.lookahead||t!==h&&666!==s.status){var f=2===s.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(O(e),0===e.lookahead)){if(t===h)return 1;break}if(e.match_length=0,i=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(R(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(R(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(R(e,!1),0===e.strm.avail_out)?1:2}(s,t):3===s.strategy?function(e,t){for(var i,n,s,o,a=e.window;;){if(e.lookahead<=x){if(O(e),e.lookahead<=x&&t===h)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=y&&0<e.strstart&&(n=a[s=e.strstart-1])===a[++s]&&n===a[++s]&&n===a[++s]){o=e.strstart+x;do{}while(n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&s<o);e.match_length=x-(o-s),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=y?(i=r._tr_tally(e,1,e.match_length-y),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(R(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(R(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(R(e,!1),0===e.strm.avail_out)?1:2}(s,t):n[s.level].func(s,t);if(3!==f&&4!==f||(s.status=666),1===f||3===f)return 0===e.avail_out&&(s.last_flush=-1),c;if(2===f&&(1===t?r._tr_align(s):5!==t&&(r._tr_stored_block(s,0,0,!1),3===t&&(A(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),P(e),0===e.avail_out))return s.last_flush=-1,c}return 4!==t?c:s.wrap<=0?1:(2===s.wrap?(M(s,255&e.adler),M(s,e.adler>>8&255),M(s,e.adler>>16&255),M(s,e.adler>>24&255),M(s,255&e.total_in),M(s,e.total_in>>8&255),M(s,e.total_in>>16&255),M(s,e.total_in>>24&255)):(I(s,e.adler>>>16),I(s,65535&e.adler)),P(e),0<s.wrap&&(s.wrap=-s.wrap),0!==s.pending?c:1)},i.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==T&&69!==t&&73!==t&&91!==t&&103!==t&&t!==S&&666!==t?E(e,u):(e.state=null,t===S?E(e,-3):c):u},i.deflateSetDictionary=function(e,t){var i,n,r,a,l,h,d,p,f=t.length;if(!e||!e.state)return u;if(2===(a=(i=e.state).wrap)||1===a&&i.status!==T||i.lookahead)return u;for(1===a&&(e.adler=o(e.adler,t,f,0)),i.wrap=0,f>=i.w_size&&(0===a&&(A(i.head),i.strstart=0,i.block_start=0,i.insert=0),p=new s.Buf8(i.w_size),s.arraySet(p,t,f-i.w_size,i.w_size,0),t=p,f=i.w_size),l=e.avail_in,h=e.next_in,d=e.input,e.avail_in=f,e.next_in=0,e.input=t,O(i);i.lookahead>=y;){for(n=i.strstart,r=i.lookahead-(y-1);i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+y-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++,--r;);i.strstart=n,i.lookahead=y-1,O(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=y-1,i.match_available=0,e.next_in=h,e.input=d,e.avail_in=l,i.wrap=a,c},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(e,t,i){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(e,t,i){t.exports=function(e,t){var i,n,s,r,o,a,l,h,c,u,d,p,f,_,m,g,v,y,x,b,T,S,E,C,A;i=e.state,n=e.next_in,C=e.input,s=n+(e.avail_in-5),r=e.next_out,A=e.output,o=r-(t-e.avail_out),a=r+(e.avail_out-257),l=i.dmax,h=i.wsize,c=i.whave,u=i.wnext,d=i.window,p=i.hold,f=i.bits,_=i.lencode,m=i.distcode,g=(1<<i.lenbits)-1,v=(1<<i.distbits)-1;e:do{f<15&&(p+=C[n++]<<f,f+=8,p+=C[n++]<<f,f+=8),y=_[p&g];t:for(;;){if(p>>>=x=y>>>24,f-=x,0==(x=y>>>16&255))A[r++]=65535&y;else{if(!(16&x)){if(0==(64&x)){y=_[(65535&y)+(p&(1<<x)-1)];continue t}if(32&x){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}b=65535&y,(x&=15)&&(f<x&&(p+=C[n++]<<f,f+=8),b+=p&(1<<x)-1,p>>>=x,f-=x),f<15&&(p+=C[n++]<<f,f+=8,p+=C[n++]<<f,f+=8),y=m[p&v];i:for(;;){if(p>>>=x=y>>>24,f-=x,!(16&(x=y>>>16&255))){if(0==(64&x)){y=m[(65535&y)+(p&(1<<x)-1)];continue i}e.msg="invalid distance code",i.mode=30;break e}if(T=65535&y,f<(x&=15)&&(p+=C[n++]<<f,(f+=8)<x&&(p+=C[n++]<<f,f+=8)),l<(T+=p&(1<<x)-1)){e.msg="invalid distance too far back",i.mode=30;break e}if(p>>>=x,f-=x,(x=r-o)<T){if(c<(x=T-x)&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(E=d,(S=0)===u){if(S+=h-x,x<b){for(b-=x;A[r++]=d[S++],--x;);S=r-T,E=A}}else if(u<x){if(S+=h+u-x,(x-=u)<b){for(b-=x;A[r++]=d[S++],--x;);if(S=0,u<b){for(b-=x=u;A[r++]=d[S++],--x;);S=r-T,E=A}}}else if(S+=u-x,x<b){for(b-=x;A[r++]=d[S++],--x;);S=r-T,E=A}for(;2<b;)A[r++]=E[S++],A[r++]=E[S++],A[r++]=E[S++],b-=3;b&&(A[r++]=E[S++],1<b&&(A[r++]=E[S++]))}else{for(S=r-T;A[r++]=A[S++],A[r++]=A[S++],A[r++]=A[S++],2<(b-=3););b&&(A[r++]=A[S++],1<b&&(A[r++]=A[S++]))}break}}break}}while(n<s&&r<a);n-=b=f>>3,p&=(1<<(f-=b<<3))-1,e.next_in=n,e.next_out=r,e.avail_in=n<s?s-n+5:5-(n-s),e.avail_out=r<a?a-r+257:257-(r-a),i.hold=p,i.bits=f}},{}],49:[function(e,t,i){var n=e("../utils/common"),s=e("./adler32"),r=e("./crc32"),o=e("./inffast"),a=e("./inftrees"),l=0,h=-2,c=1,u=852,d=592;function p(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function f(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new n.Buf16(320),this.work=new n.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function _(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=c,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new n.Buf32(u),t.distcode=t.distdyn=new n.Buf32(d),t.sane=1,t.back=-1,l):h}function m(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,_(e)):h}function g(e,t){var i,n;return e&&e.state?(n=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?h:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,m(e))):h}function v(e,t){var i,n;return e?(n=new f,(e.state=n).window=null,(i=g(e,t))!==l&&(e.state=null),i):h}var y,x,b=!0;function T(e){if(b){var t;for(y=new n.Buf32(512),x=new n.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(1,e.lens,0,288,y,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(2,e.lens,0,32,x,0,e.work,{bits:5}),b=!1}e.lencode=y,e.lenbits=9,e.distcode=x,e.distbits=5}function S(e,t,i,s){var r,o=e.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new n.Buf8(o.wsize)),s>=o.wsize?(n.arraySet(o.window,t,i-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(s<(r=o.wsize-o.wnext)&&(r=s),n.arraySet(o.window,t,i-s,r,o.wnext),(s-=r)?(n.arraySet(o.window,t,i-s,s,0),o.wnext=s,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0}i.inflateReset=m,i.inflateReset2=g,i.inflateResetKeep=_,i.inflateInit=function(e){return v(e,15)},i.inflateInit2=v,i.inflate=function(e,t){var i,u,d,f,_,m,g,v,y,x,b,E,C,A,P,R,M,I,D,O,w,N,F,L,B=0,U=new n.Buf8(4),V=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return h;12===(i=e.state).mode&&(i.mode=13),_=e.next_out,d=e.output,g=e.avail_out,f=e.next_in,u=e.input,m=e.avail_in,v=i.hold,y=i.bits,x=m,b=g,N=l;e:for(;;)switch(i.mode){case c:if(0===i.wrap){i.mode=13;break}for(;y<16;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}if(2&i.wrap&&35615===v){U[i.check=0]=255&v,U[1]=v>>>8&255,i.check=r(i.check,U,2,0),y=v=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&v)<<8)+(v>>8))%31){e.msg="incorrect header check",i.mode=30;break}if(8!=(15&v)){e.msg="unknown compression method",i.mode=30;break}if(y-=4,w=8+(15&(v>>>=4)),0===i.wbits)i.wbits=w;else if(w>i.wbits){e.msg="invalid window size",i.mode=30;break}i.dmax=1<<w,e.adler=i.check=1,i.mode=512&v?10:12,y=v=0;break;case 2:for(;y<16;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}if(i.flags=v,8!=(255&i.flags)){e.msg="unknown compression method",i.mode=30;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=30;break}i.head&&(i.head.text=v>>8&1),512&i.flags&&(U[0]=255&v,U[1]=v>>>8&255,i.check=r(i.check,U,2,0)),y=v=0,i.mode=3;case 3:for(;y<32;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}i.head&&(i.head.time=v),512&i.flags&&(U[0]=255&v,U[1]=v>>>8&255,U[2]=v>>>16&255,U[3]=v>>>24&255,i.check=r(i.check,U,4,0)),y=v=0,i.mode=4;case 4:for(;y<16;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}i.head&&(i.head.xflags=255&v,i.head.os=v>>8),512&i.flags&&(U[0]=255&v,U[1]=v>>>8&255,i.check=r(i.check,U,2,0)),y=v=0,i.mode=5;case 5:if(1024&i.flags){for(;y<16;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}i.length=v,i.head&&(i.head.extra_len=v),512&i.flags&&(U[0]=255&v,U[1]=v>>>8&255,i.check=r(i.check,U,2,0)),y=v=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(m<(E=i.length)&&(E=m),E&&(i.head&&(w=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),n.arraySet(i.head.extra,u,f,E,w)),512&i.flags&&(i.check=r(i.check,u,E,f)),m-=E,f+=E,i.length-=E),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===m)break e;for(E=0;w=u[f+E++],i.head&&w&&i.length<65536&&(i.head.name+=String.fromCharCode(w)),w&&E<m;);if(512&i.flags&&(i.check=r(i.check,u,E,f)),m-=E,f+=E,w)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===m)break e;for(E=0;w=u[f+E++],i.head&&w&&i.length<65536&&(i.head.comment+=String.fromCharCode(w)),w&&E<m;);if(512&i.flags&&(i.check=r(i.check,u,E,f)),m-=E,f+=E,w)break e}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;y<16;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}if(v!==(65535&i.check)){e.msg="header crc mismatch",i.mode=30;break}y=v=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=12;break;case 10:for(;y<32;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}e.adler=i.check=p(v),y=v=0,i.mode=11;case 11:if(0===i.havedict)return e.next_out=_,e.avail_out=g,e.next_in=f,e.avail_in=m,i.hold=v,i.bits=y,2;e.adler=i.check=1,i.mode=12;case 12:if(5===t||6===t)break e;case 13:if(i.last){v>>>=7&y,y-=7&y,i.mode=27;break}for(;y<3;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}switch(i.last=1&v,y-=1,3&(v>>>=1)){case 0:i.mode=14;break;case 1:if(T(i),i.mode=20,6!==t)break;v>>>=2,y-=2;break e;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=30}v>>>=2,y-=2;break;case 14:for(v>>>=7&y,y-=7&y;y<32;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}if((65535&v)!=(v>>>16^65535)){e.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&v,y=v=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(E=i.length){if(m<E&&(E=m),g<E&&(E=g),0===E)break e;n.arraySet(d,u,f,E,_),m-=E,f+=E,g-=E,_+=E,i.length-=E;break}i.mode=12;break;case 17:for(;y<14;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}if(i.nlen=257+(31&v),v>>>=5,y-=5,i.ndist=1+(31&v),v>>>=5,y-=5,i.ncode=4+(15&v),v>>>=4,y-=4,286<i.nlen||30<i.ndist){e.msg="too many length or distance symbols",i.mode=30;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;y<3;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}i.lens[V[i.have++]]=7&v,v>>>=3,y-=3}for(;i.have<19;)i.lens[V[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,F={bits:i.lenbits},N=a(0,i.lens,0,19,i.lencode,0,i.work,F),i.lenbits=F.bits,N){e.msg="invalid code lengths set",i.mode=30;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;R=(B=i.lencode[v&(1<<i.lenbits)-1])>>>16&255,M=65535&B,!((P=B>>>24)<=y);){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}if(M<16)v>>>=P,y-=P,i.lens[i.have++]=M;else{if(16===M){for(L=P+2;y<L;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}if(v>>>=P,y-=P,0===i.have){e.msg="invalid bit length repeat",i.mode=30;break}w=i.lens[i.have-1],E=3+(3&v),v>>>=2,y-=2}else if(17===M){for(L=P+3;y<L;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}y-=P,w=0,E=3+(7&(v>>>=P)),v>>>=3,y-=3}else{for(L=P+7;y<L;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}y-=P,w=0,E=11+(127&(v>>>=P)),v>>>=7,y-=7}if(i.have+E>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=30;break}for(;E--;)i.lens[i.have++]=w}}if(30===i.mode)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=30;break}if(i.lenbits=9,F={bits:i.lenbits},N=a(1,i.lens,0,i.nlen,i.lencode,0,i.work,F),i.lenbits=F.bits,N){e.msg="invalid literal/lengths set",i.mode=30;break}if(i.distbits=6,i.distcode=i.distdyn,F={bits:i.distbits},N=a(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,F),i.distbits=F.bits,N){e.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(6<=m&&258<=g){e.next_out=_,e.avail_out=g,e.next_in=f,e.avail_in=m,i.hold=v,i.bits=y,o(e,b),_=e.next_out,d=e.output,g=e.avail_out,f=e.next_in,u=e.input,m=e.avail_in,v=i.hold,y=i.bits,12===i.mode&&(i.back=-1);break}for(i.back=0;R=(B=i.lencode[v&(1<<i.lenbits)-1])>>>16&255,M=65535&B,!((P=B>>>24)<=y);){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}if(R&&0==(240&R)){for(I=P,D=R,O=M;R=(B=i.lencode[O+((v&(1<<I+D)-1)>>I)])>>>16&255,M=65535&B,!(I+(P=B>>>24)<=y);){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}v>>>=I,y-=I,i.back+=I}if(v>>>=P,y-=P,i.back+=P,i.length=M,0===R){i.mode=26;break}if(32&R){i.back=-1,i.mode=12;break}if(64&R){e.msg="invalid literal/length code",i.mode=30;break}i.extra=15&R,i.mode=22;case 22:if(i.extra){for(L=i.extra;y<L;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}i.length+=v&(1<<i.extra)-1,v>>>=i.extra,y-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;R=(B=i.distcode[v&(1<<i.distbits)-1])>>>16&255,M=65535&B,!((P=B>>>24)<=y);){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}if(0==(240&R)){for(I=P,D=R,O=M;R=(B=i.distcode[O+((v&(1<<I+D)-1)>>I)])>>>16&255,M=65535&B,!(I+(P=B>>>24)<=y);){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}v>>>=I,y-=I,i.back+=I}if(v>>>=P,y-=P,i.back+=P,64&R){e.msg="invalid distance code",i.mode=30;break}i.offset=M,i.extra=15&R,i.mode=24;case 24:if(i.extra){for(L=i.extra;y<L;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}i.offset+=v&(1<<i.extra)-1,v>>>=i.extra,y-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===g)break e;if(E=b-g,i.offset>E){if((E=i.offset-E)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=30;break}C=E>i.wnext?(E-=i.wnext,i.wsize-E):i.wnext-E,E>i.length&&(E=i.length),A=i.window}else A=d,C=_-i.offset,E=i.length;for(g<E&&(E=g),g-=E,i.length-=E;d[_++]=A[C++],--E;);0===i.length&&(i.mode=21);break;case 26:if(0===g)break e;d[_++]=i.length,g--,i.mode=21;break;case 27:if(i.wrap){for(;y<32;){if(0===m)break e;m--,v|=u[f++]<<y,y+=8}if(b-=g,e.total_out+=b,i.total+=b,b&&(e.adler=i.check=i.flags?r(i.check,d,b,_-b):s(i.check,d,b,_-b)),b=g,(i.flags?v:p(v))!==i.check){e.msg="incorrect data check",i.mode=30;break}y=v=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;y<32;){if(0===m)break e;m--,v+=u[f++]<<y,y+=8}if(v!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=30;break}y=v=0}i.mode=29;case 29:N=1;break e;case 30:N=-3;break e;case 31:return-4;default:return h}return e.next_out=_,e.avail_out=g,e.next_in=f,e.avail_in=m,i.hold=v,i.bits=y,(i.wsize||b!==e.avail_out&&i.mode<30&&(i.mode<27||4!==t))&&S(e,e.output,e.next_out,b-e.avail_out)?(i.mode=31,-4):(x-=e.avail_in,b-=e.avail_out,e.total_in+=x,e.total_out+=b,i.total+=b,i.wrap&&b&&(e.adler=i.check=i.flags?r(i.check,d,b,e.next_out-b):s(i.check,d,b,e.next_out-b)),e.data_type=i.bits+(i.last?64:0)+(12===i.mode?128:0)+(20===i.mode||15===i.mode?256:0),(0==x&&0===b||4===t)&&N===l&&(N=-5),N)},i.inflateEnd=function(e){if(!e||!e.state)return h;var t=e.state;return t.window&&(t.window=null),e.state=null,l},i.inflateGetHeader=function(e,t){var i;return e&&e.state?0==(2&(i=e.state).wrap)?h:((i.head=t).done=!1,l):h},i.inflateSetDictionary=function(e,t){var i,n=t.length;return e&&e.state?0!==(i=e.state).wrap&&11!==i.mode?h:11===i.mode&&s(1,t,n,0)!==i.check?-3:S(e,t,n,n)?(i.mode=31,-4):(i.havedict=1,l):h},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(e,t,i){var n=e("../utils/common"),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],r=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,i,l,h,c,u,d){var p,f,_,m,g,v,y,x,b,T=d.bits,S=0,E=0,C=0,A=0,P=0,R=0,M=0,I=0,D=0,O=0,w=null,N=0,F=new n.Buf16(16),L=new n.Buf16(16),B=null,U=0;for(S=0;S<=15;S++)F[S]=0;for(E=0;E<l;E++)F[t[i+E]]++;for(P=T,A=15;1<=A&&0===F[A];A--);if(A<P&&(P=A),0===A)return h[c++]=20971520,h[c++]=20971520,d.bits=1,0;for(C=1;C<A&&0===F[C];C++);for(P<C&&(P=C),S=I=1;S<=15;S++)if(I<<=1,(I-=F[S])<0)return-1;if(0<I&&(0===e||1!==A))return-1;for(L[1]=0,S=1;S<15;S++)L[S+1]=L[S]+F[S];for(E=0;E<l;E++)0!==t[i+E]&&(u[L[t[i+E]]++]=E);if(v=0===e?(w=B=u,19):1===e?(w=s,N-=257,B=r,U-=257,256):(w=o,B=a,-1),S=C,g=c,M=E=O=0,_=-1,m=(D=1<<(R=P))-1,1===e&&852<D||2===e&&592<D)return 1;for(;;){for(y=S-M,b=u[E]<v?(x=0,u[E]):u[E]>v?(x=B[U+u[E]],w[N+u[E]]):(x=96,0),p=1<<S-M,C=f=1<<R;h[g+(O>>M)+(f-=p)]=y<<24|x<<16|b|0,0!==f;);for(p=1<<S-1;O&p;)p>>=1;if(0!==p?(O&=p-1,O+=p):O=0,E++,0==--F[S]){if(S===A)break;S=t[i+u[E]]}if(P<S&&(O&m)!==_){for(0===M&&(M=P),g+=C,I=1<<(R=S-M);R+M<A&&!((I-=F[R+M])<=0);)R++,I<<=1;if(D+=1<<R,1===e&&852<D||2===e&&592<D)return 1;h[_=O&m]=P<<24|R<<16|g-c|0}}return 0!==O&&(h[g+O]=S-M<<24|64<<16|0),d.bits=P,0}},{"../utils/common":41}],51:[function(e,t,i){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(e,t,i){var n=e("../utils/common");function s(e){for(var t=e.length;0<=--t;)e[t]=0}var r=256,o=286,a=30,l=15,h=16,c=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],u=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],d=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],p=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],f=new Array(576);s(f);var _=new Array(60);s(_);var m=new Array(512);s(m);var g=new Array(256);s(g);var v=new Array(29);s(v);var y,x,b,T=new Array(a);function S(e,t,i,n,s){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=s,this.has_stree=e&&e.length}function E(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function C(e){return e<256?m[e]:m[256+(e>>>7)]}function A(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function P(e,t,i){e.bi_valid>h-i?(e.bi_buf|=t<<e.bi_valid&65535,A(e,e.bi_buf),e.bi_buf=t>>h-e.bi_valid,e.bi_valid+=i-h):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function R(e,t,i){P(e,i[2*t],i[2*t+1])}function M(e,t){for(var i=0;i|=1&e,e>>>=1,i<<=1,0<--t;);return i>>>1}function I(e,t,i){var n,s,r=new Array(l+1),o=0;for(n=1;n<=l;n++)r[n]=o=o+i[n-1]<<1;for(s=0;s<=t;s++){var a=e[2*s+1];0!==a&&(e[2*s]=M(r[a]++,a))}}function D(e){var t;for(t=0;t<o;t++)e.dyn_ltree[2*t]=0;for(t=0;t<a;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function O(e){8<e.bi_valid?A(e,e.bi_buf):0<e.bi_valid&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function w(e,t,i,n){var s=2*t,r=2*i;return e[s]<e[r]||e[s]===e[r]&&n[t]<=n[i]}function N(e,t,i){for(var n=e.heap[i],s=i<<1;s<=e.heap_len&&(s<e.heap_len&&w(t,e.heap[s+1],e.heap[s],e.depth)&&s++,!w(t,n,e.heap[s],e.depth));)e.heap[i]=e.heap[s],i=s,s<<=1;e.heap[i]=n}function F(e,t,i){var n,s,o,a,l=0;if(0!==e.last_lit)for(;n=e.pending_buf[e.d_buf+2*l]<<8|e.pending_buf[e.d_buf+2*l+1],s=e.pending_buf[e.l_buf+l],l++,0===n?R(e,s,t):(R(e,(o=g[s])+r+1,t),0!==(a=c[o])&&P(e,s-=v[o],a),R(e,o=C(--n),i),0!==(a=u[o])&&P(e,n-=T[o],a)),l<e.last_lit;);R(e,256,t)}function L(e,t){var i,n,s,r=t.dyn_tree,o=t.stat_desc.static_tree,a=t.stat_desc.has_stree,h=t.stat_desc.elems,c=-1;for(e.heap_len=0,e.heap_max=573,i=0;i<h;i++)0!==r[2*i]?(e.heap[++e.heap_len]=c=i,e.depth[i]=0):r[2*i+1]=0;for(;e.heap_len<2;)r[2*(s=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[s]=0,e.opt_len--,a&&(e.static_len-=o[2*s+1]);for(t.max_code=c,i=e.heap_len>>1;1<=i;i--)N(e,r,i);for(s=h;i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],N(e,r,1),n=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=n,r[2*s]=r[2*i]+r[2*n],e.depth[s]=(e.depth[i]>=e.depth[n]?e.depth[i]:e.depth[n])+1,r[2*i+1]=r[2*n+1]=s,e.heap[1]=s++,N(e,r,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,n,s,r,o,a,h=t.dyn_tree,c=t.max_code,u=t.stat_desc.static_tree,d=t.stat_desc.has_stree,p=t.stat_desc.extra_bits,f=t.stat_desc.extra_base,_=t.stat_desc.max_length,m=0;for(r=0;r<=l;r++)e.bl_count[r]=0;for(h[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)_<(r=h[2*h[2*(n=e.heap[i])+1]+1]+1)&&(r=_,m++),h[2*n+1]=r,c<n||(e.bl_count[r]++,o=0,f<=n&&(o=p[n-f]),a=h[2*n],e.opt_len+=a*(r+o),d&&(e.static_len+=a*(u[2*n+1]+o)));if(0!==m){do{for(r=_-1;0===e.bl_count[r];)r--;e.bl_count[r]--,e.bl_count[r+1]+=2,e.bl_count[_]--,m-=2}while(0<m);for(r=_;0!==r;r--)for(n=e.bl_count[r];0!==n;)c<(s=e.heap[--i])||(h[2*s+1]!==r&&(e.opt_len+=(r-h[2*s+1])*h[2*s],h[2*s+1]=r),n--)}}(e,t),I(r,c,e.bl_count)}function B(e,t,i){var n,s,r=-1,o=t[1],a=0,l=7,h=4;for(0===o&&(l=138,h=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)s=o,o=t[2*(n+1)+1],++a<l&&s===o||(a<h?e.bl_tree[2*s]+=a:0!==s?(s!==r&&e.bl_tree[2*s]++,e.bl_tree[32]++):a<=10?e.bl_tree[34]++:e.bl_tree[36]++,r=s,h=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4))}function U(e,t,i){var n,s,r=-1,o=t[1],a=0,l=7,h=4;for(0===o&&(l=138,h=3),n=0;n<=i;n++)if(s=o,o=t[2*(n+1)+1],!(++a<l&&s===o)){if(a<h)for(;R(e,s,e.bl_tree),0!=--a;);else 0!==s?(s!==r&&(R(e,s,e.bl_tree),a--),R(e,16,e.bl_tree),P(e,a-3,2)):a<=10?(R(e,17,e.bl_tree),P(e,a-3,3)):(R(e,18,e.bl_tree),P(e,a-11,7));r=s,h=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4)}}s(T);var V=!1;function k(e,t,i,s){P(e,0+(s?1:0),3),function(e,t,i,s){O(e),A(e,i),A(e,~i),n.arraySet(e.pending_buf,e.window,t,i,e.pending),e.pending+=i}(e,t,i)}i._tr_init=function(e){V||(function(){var e,t,i,n,s,r=new Array(l+1);for(n=i=0;n<28;n++)for(v[n]=i,e=0;e<1<<c[n];e++)g[i++]=n;for(g[i-1]=n,n=s=0;n<16;n++)for(T[n]=s,e=0;e<1<<u[n];e++)m[s++]=n;for(s>>=7;n<a;n++)for(T[n]=s<<7,e=0;e<1<<u[n]-7;e++)m[256+s++]=n;for(t=0;t<=l;t++)r[t]=0;for(e=0;e<=143;)f[2*e+1]=8,e++,r[8]++;for(;e<=255;)f[2*e+1]=9,e++,r[9]++;for(;e<=279;)f[2*e+1]=7,e++,r[7]++;for(;e<=287;)f[2*e+1]=8,e++,r[8]++;for(I(f,287,r),e=0;e<a;e++)_[2*e+1]=5,_[2*e]=M(e,5);y=new S(f,c,257,o,l),x=new S(_,u,0,a,l),b=new S(new Array(0),d,0,19,7)}(),V=!0),e.l_desc=new E(e.dyn_ltree,y),e.d_desc=new E(e.dyn_dtree,x),e.bl_desc=new E(e.bl_tree,b),e.bi_buf=0,e.bi_valid=0,D(e)},i._tr_stored_block=k,i._tr_flush_block=function(e,t,i,n){var s,o,a=0;0<e.level?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<r;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),L(e,e.l_desc),L(e,e.d_desc),a=function(e){var t;for(B(e,e.dyn_ltree,e.l_desc.max_code),B(e,e.dyn_dtree,e.d_desc.max_code),L(e,e.bl_desc),t=18;3<=t&&0===e.bl_tree[2*p[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),s=e.opt_len+3+7>>>3,(o=e.static_len+3+7>>>3)<=s&&(s=o)):s=o=i+5,i+4<=s&&-1!==t?k(e,t,i,n):4===e.strategy||o===s?(P(e,2+(n?1:0),3),F(e,f,_)):(P(e,4+(n?1:0),3),function(e,t,i,n){var s;for(P(e,t-257,5),P(e,i-1,5),P(e,n-4,4),s=0;s<n;s++)P(e,e.bl_tree[2*p[s]+1],3);U(e,e.dyn_ltree,t-1),U(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),F(e,e.dyn_ltree,e.dyn_dtree)),D(e),n&&O(e)},i._tr_tally=function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(g[i]+r+1)]++,e.dyn_dtree[2*C(t)]++),e.last_lit===e.lit_bufsize-1},i._tr_align=function(e){P(e,2,3),R(e,256,f),function(e){16===e.bi_valid?(A(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},{"../utils/common":41}],53:[function(e,t,i){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,n){(function(e){!function(e,t){if(!e.setImmediate){var i,n,s,r,o=1,a={},l=!1,h=e.document,c=Object.getPrototypeOf&&Object.getPrototypeOf(e);c=c&&c.setTimeout?c:e,i="[object process]"==={}.toString.call(e.process)?function(e){process.nextTick((function(){d(e)}))}:function(){if(e.postMessage&&!e.importScripts){var t=!0,i=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=i,t}}()?(r="setImmediate$"+Math.random()+"$",e.addEventListener?e.addEventListener("message",p,!1):e.attachEvent("onmessage",p),function(t){e.postMessage(r+t,"*")}):e.MessageChannel?((s=new MessageChannel).port1.onmessage=function(e){d(e.data)},function(e){s.port2.postMessage(e)}):h&&"onreadystatechange"in h.createElement("script")?(n=h.documentElement,function(e){var t=h.createElement("script");t.onreadystatechange=function(){d(e),t.onreadystatechange=null,n.removeChild(t),t=null},n.appendChild(t)}):function(e){setTimeout(d,0,e)},c.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n<t.length;n++)t[n]=arguments[n+1];var s={callback:e,args:t};return a[o]=s,i(o),o++},c.clearImmediate=u}function u(e){delete a[e]}function d(e){if(l)setTimeout(d,0,e);else{var i=a[e];if(i){l=!0;try{!function(e){var i=e.callback,n=e.args;switch(n.length){case 0:i();break;case 1:i(n[0]);break;case 2:i(n[0],n[1]);break;case 3:i(n[0],n[1],n[2]);break;default:i.apply(t,n)}}(i)}finally{u(e),l=!1}}}}function p(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(r)&&d(+t.data.slice(r.length))}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,void 0!==i.g?i.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10)},6184:(e,t)=>{t.__esModule=!0,Array.prototype.find||Object.defineProperty(Array.prototype,"find",{value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');var t=Object(this),i=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var n=arguments[1],s=0;s<i;){var r=t[s];if(e.call(n,r,s,t))return r;s++}},configurable:!0,writable:!0})},6068:(e,t)=>{t.__esModule=!0,t.Polyfill=t.LightMapImpl=void 0;var i=function(){function e(){this.record=[]}return e.prototype.has=function(e){return this.record.map((function(e){return e[0]})).indexOf(e)>=0},e.prototype.get=function(e){var t=this.record.filter((function(t){return t[0]===e}))[0];if(void 0!==t)return t[1]},e.prototype.set=function(e,t){var i=this.record.filter((function(t){return t[0]===e}))[0];return void 0===i?this.record.push([e,t]):i[1]=t,this},e.prototype.delete=function(e){var t=this.record.map((function(e){return e[0]})).indexOf(e);return!(t<0||(this.record.splice(t,1),0))},e.prototype.keys=function(){return this.record.map((function(e){return e[0]}))},e}();t.LightMapImpl=i,t.Polyfill="undefined"!=typeof Map?Map:i},7244:(e,t)=>{t.__esModule=!0,Object.is||(Object.is=function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t})},3876:(e,t,i)=>{t.__esModule=!0,t.Polyfill=t.LightSetImpl=void 0;var n=i(6068),s=function(){function e(e){if(this.map=new n.Polyfill,void 0!==e)for(var t=0,i=e;t<i.length;t++){var s=i[t];this.add(s)}}return e.prototype.has=function(e){return this.map.has(e)},e.prototype.add=function(e){return this.map.set(e,!0),this},e.prototype.values=function(){return this.map.keys()},e.prototype.delete=function(e){return this.map.delete(e)},e}();t.LightSetImpl=s,t.Polyfill="undefined"!=typeof Set?Set:s},9589:(e,t,i)=>{t.__esModule=!0,t.Polyfill=void 0;var n=i(6068);t.Polyfill="undefined"!=typeof WeakMap?WeakMap:n.Polyfill},7126:function(e){var t;t=function(){return function(e){var t={};function i(n){if(t[n])return t[n].exports;var s=t[n]={i:n,l:!1,exports:{}};return e[n].call(s.exports,s,s.exports,i),s.l=!0,s.exports}return i.m=e,i.c=t,i.i=function(e){return e},i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:n})},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=6)}([function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.css=t.deepExtend=t.animationEndEvents=void 0;var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.inArray=function(e,t,i){var n=void 0;if(i){for(n in t)if(t.hasOwnProperty(n)&&t[n]===e)return!0}else for(n in t)if(t.hasOwnProperty(n)&&t[n]===e)return!0;return!1},t.stopPropagation=function(e){void 0!==(e=e||window.event).stopPropagation?e.stopPropagation():e.cancelBubble=!0},t.generateID=function(){return"noty_"+(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"")+"_"+"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))},t.outerHeight=function(e){var t=e.offsetHeight,i=window.getComputedStyle(e);return t+(parseInt(i.marginTop)+parseInt(i.marginBottom))},t.addListener=r,t.hasClass=o,t.addClass=function(e,t){var i=l(e),n=i+t;o(i,t)||(e.className=n.substring(1))},t.removeClass=function(e,t){var i=l(e),n=void 0;o(e,t)&&(n=i.replace(" "+t+" "," "),e.className=n.substring(1,n.length-1))},t.remove=a,t.classList=l,t.visibilityChangeFlow=function(){var e=void 0,t=void 0;function i(){s.PageHidden?setTimeout((function(){Object.keys(s.Store).forEach((function(e){s.Store.hasOwnProperty(e)&&s.Store[e].options.visibilityControl&&s.Store[e].stop()}))}),100):setTimeout((function(){Object.keys(s.Store).forEach((function(e){s.Store.hasOwnProperty(e)&&s.Store[e].options.visibilityControl&&s.Store[e].resume()})),s.queueRenderAll()}),100)}void 0!==document.hidden?(e="hidden",t="visibilitychange"):void 0!==document.msHidden?(e="msHidden",t="msvisibilitychange"):void 0!==document.webkitHidden&&(e="webkitHidden",t="webkitvisibilitychange"),t&&r(document,t,(function(){s.PageHidden=document[e],i()})),r(window,"blur",(function(){s.PageHidden=!0,i()})),r(window,"focus",(function(){s.PageHidden=!1,i()}))},t.createAudioElements=function(e){if(e.hasSound){var t=document.createElement("audio");e.options.sounds.sources.forEach((function(e){var i=document.createElement("source");i.src=e,i.type="audio/"+e.match(/\.([^.]+)$/)[1],t.appendChild(i)})),e.barDom?e.barDom.appendChild(t):document.querySelector("body").appendChild(t),t.volume=e.options.sounds.volume,e.soundPlayed||(t.play(),e.soundPlayed=!0),t.onended=function(){a(t)}}};var s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(i(1));function r(e,t,i){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];t=t.split(" ");for(var s=0;s<t.length;s++)document.addEventListener?e.addEventListener(t[s],i,n):document.attachEvent&&e.attachEvent("on"+t[s],i)}function o(e,t){return("string"==typeof e?e:l(e)).indexOf(" "+t+" ")>=0}function a(e){e.parentNode&&e.parentNode.removeChild(e)}function l(e){return(" "+(e&&e.className||"")+" ").replace(/\s+/gi," ")}t.animationEndEvents="webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend",t.deepExtend=function e(t){t=t||{};for(var i=1;i<arguments.length;i++){var s=arguments[i];if(s)for(var r in s)s.hasOwnProperty(r)&&(Array.isArray(s[r])?t[r]=s[r]:"object"===n(s[r])&&null!==s[r]?t[r]=e(t[r],s[r]):t[r]=s[r])}return t},t.css=function(){var e=["Webkit","O","Moz","ms"],t={};function i(i,n,s){n=function(i){return i=i.replace(/^-ms-/,"ms-").replace(/-([\da-z])/gi,(function(e,t){return t.toUpperCase()})),t[i]||(t[i]=function(t){var i=document.body.style;if(t in i)return t;for(var n=e.length,s=t.charAt(0).toUpperCase()+t.slice(1),r=void 0;n--;)if((r=e[n]+s)in i)return r;return t}(i))}(n),i.style[n]=s}return function(e,t){var n=arguments,s=void 0,r=void 0;if(2===n.length)for(s in t)t.hasOwnProperty(s)&&void 0!==(r=t[s])&&t.hasOwnProperty(s)&&i(e,s,r);else i(e,n[1],n[2])}}()},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.Defaults=t.Store=t.Queues=t.DefaultMaxVisible=t.docTitle=t.DocModalCount=t.PageHidden=void 0,t.getQueueCounts=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"global",t=0,i=a;return l.hasOwnProperty(e)&&(i=l[e].maxVisible,Object.keys(h).forEach((function(i){h[i].options.queue!==e||h[i].closed||t++}))),{current:t,maxVisible:i}},t.addToQueue=function(e){l.hasOwnProperty(e.options.queue)||(l[e.options.queue]={maxVisible:a,queue:[]}),l[e.options.queue].queue.push(e)},t.removeFromQueue=function(e){if(l.hasOwnProperty(e.options.queue)){var t=[];Object.keys(l[e.options.queue].queue).forEach((function(i){l[e.options.queue].queue[i].id!==e.id&&t.push(l[e.options.queue].queue[i])})),l[e.options.queue].queue=t}},t.queueRender=c,t.queueRenderAll=function(){Object.keys(l).forEach((function(e){c(e)}))},t.ghostFix=function(e){var t=n.generateID("ghost"),i=document.createElement("div");i.setAttribute("id",t),n.css(i,{height:n.outerHeight(e.barDom)+"px"}),e.barDom.insertAdjacentHTML("afterend",i.outerHTML),n.remove(e.barDom),i=document.getElementById(t),n.addClass(i,"noty_fix_effects_height"),n.addListener(i,n.animationEndEvents,(function(){n.remove(i)}))},t.build=function(e){!function(e){if(e.options.container)e.layoutDom=document.querySelector(e.options.container);else{var t="noty_layout__"+e.options.layout;e.layoutDom=document.querySelector("div#"+t),e.layoutDom||(e.layoutDom=document.createElement("div"),e.layoutDom.setAttribute("id",t),e.layoutDom.setAttribute("role","alert"),e.layoutDom.setAttribute("aria-live","polite"),n.addClass(e.layoutDom,"noty_layout"),document.querySelector("body").appendChild(e.layoutDom))}}(e);var t='<div class="noty_body">'+e.options.text+"</div>"+function(e){if(u(e)){var t=document.createElement("div");return n.addClass(t,"noty_buttons"),Object.keys(e.options.buttons).forEach((function(i){t.appendChild(e.options.buttons[i].dom)})),e.options.buttons.forEach((function(e){t.appendChild(e.dom)})),t.outerHTML}return""}(e)+'<div class="noty_progressbar"></div>';e.barDom=document.createElement("div"),e.barDom.setAttribute("id",e.id),n.addClass(e.barDom,"noty_bar noty_type__"+e.options.type+" noty_theme__"+e.options.theme),e.barDom.innerHTML=t,f(e,"onTemplate")},t.hasButtons=u,t.handleModal=function(e){var i,r;e.options.modal&&(0===s&&(i=document.querySelector("body"),r=document.createElement("div"),n.addClass(r,"noty_modal"),i.insertBefore(r,i.firstChild),n.addClass(r,"noty_modal_open"),n.addListener(r,n.animationEndEvents,(function(){n.removeClass(r,"noty_modal_open")}))),t.DocModalCount=s+=1)},t.handleModalClose=function(e){if(e.options.modal&&s>0&&(t.DocModalCount=s-=1,s<=0)){var i=document.querySelector(".noty_modal");i&&(n.removeClass(i,"noty_modal_open"),n.addClass(i,"noty_modal_close"),n.addListener(i,n.animationEndEvents,(function(){n.remove(i)})))}},t.queueClose=d,t.dequeueClose=p,t.fire=f,t.openFlow=function(e){f(e,"afterShow"),d(e),n.addListener(e.barDom,"mouseenter",(function(){p(e)})),n.addListener(e.barDom,"mouseleave",(function(){d(e)}))},t.closeFlow=function(e){delete h[e.id],e.closing=!1,f(e,"afterClose"),n.remove(e.barDom),0!==e.layoutDom.querySelectorAll(".noty_bar").length||e.options.container||n.remove(e.layoutDom),(n.inArray("docVisible",e.options.titleCount.conditions)||n.inArray("docHidden",e.options.titleCount.conditions))&&o.decrement(),c(e.options.queue)};var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(i(0));t.PageHidden=!1;var s=t.DocModalCount=0,r={originalTitle:null,count:0,changed:!1,timer:-1},o=t.docTitle={increment:function(){r.count++,o._update()},decrement:function(){r.count--,r.count<=0?o._clear():o._update()},_update:function(){var e=document.title;r.changed?document.title="("+r.count+") "+r.originalTitle:(r.originalTitle=e,document.title="("+r.count+") "+e,r.changed=!0)},_clear:function(){r.changed&&(r.count=0,document.title=r.originalTitle,r.changed=!1)}},a=t.DefaultMaxVisible=5,l=t.Queues={global:{maxVisible:a,queue:[]}},h=t.Store={};function c(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"global";if(l.hasOwnProperty(e)){var t=l[e].queue.shift();t&&t.show()}}function u(e){return!(!e.options.buttons||!Object.keys(e.options.buttons).length)}function d(e){e.options.timeout&&(e.options.progressBar&&e.progressDom&&n.css(e.progressDom,{transition:"width "+e.options.timeout+"ms linear",width:"0%"}),clearTimeout(e.closeTimer),e.closeTimer=setTimeout((function(){e.close()}),e.options.timeout))}function p(e){e.options.timeout&&e.closeTimer&&(clearTimeout(e.closeTimer),e.closeTimer=-1,e.options.progressBar&&e.progressDom&&n.css(e.progressDom,{transition:"width 0ms linear",width:"100%"}))}function f(e,t){e.listeners.hasOwnProperty(t)&&e.listeners[t].forEach((function(t){"function"==typeof t&&t.apply(e)}))}t.Defaults={type:"alert",layout:"topRight",theme:"mint",text:"",timeout:!1,progressBar:!0,closeWith:["click"],animation:{open:"noty_effects_open",close:"noty_effects_close"},id:!1,force:!1,killer:!1,queue:"global",container:!1,buttons:[],callbacks:{beforeShow:null,onShow:null,afterShow:null,onClose:null,afterClose:null,onClick:null,onHover:null,onTemplate:null},sounds:{sources:[],volume:1,conditions:[]},titleCount:{conditions:[]},modal:!1,visibilityControl:!1}},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.NotyButton=void 0;var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(i(0));t.NotyButton=function e(t,i,s){var r=this,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.dom=document.createElement("button"),this.dom.innerHTML=t,this.id=o.id=o.id||n.generateID("button"),this.cb=s,Object.keys(o).forEach((function(e){r.dom.setAttribute(e,o[e])})),n.addClass(this.dom,i||"noty_btn"),this}},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();t.Push=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/service-worker.js";return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.subData={},this.workerPath=t,this.listeners={onPermissionGranted:[],onPermissionDenied:[],onSubscriptionSuccess:[],onSubscriptionCancel:[],onWorkerError:[],onWorkerSuccess:[],onWorkerNotSupported:[]},this}return n(e,[{key:"on",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){};return"function"==typeof t&&this.listeners.hasOwnProperty(e)&&this.listeners[e].push(t),this}},{key:"fire",value:function(e){var t=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.listeners.hasOwnProperty(e)&&this.listeners[e].forEach((function(e){"function"==typeof e&&e.apply(t,i)}))}},{key:"create",value:function(){console.log("NOT IMPLEMENTED YET")}},{key:"isSupported",value:function(){var e=!1;try{e=window.Notification||window.webkitNotifications||navigator.mozNotification||window.external&&void 0!==window.external.msIsSiteMode()}catch(e){}return e}},{key:"getPermissionStatus",value:function(){var e="default";if(window.Notification&&window.Notification.permissionLevel)e=window.Notification.permissionLevel;else if(window.webkitNotifications&&window.webkitNotifications.checkPermission)switch(window.webkitNotifications.checkPermission()){case 1:e="default";break;case 0:e="granted";break;default:e="denied"}else window.Notification&&window.Notification.permission?e=window.Notification.permission:navigator.mozNotification?e="granted":window.external&&void 0!==window.external.msIsSiteMode()&&(e=window.external.msIsSiteMode()?"granted":"default");return e.toString().toLowerCase()}},{key:"getEndpoint",value:function(e){var t=e.endpoint,i=e.subscriptionId;return i&&-1===t.indexOf(i)&&(t+="/"+i),t}},{key:"isSWRegistered",value:function(){try{return"activated"===navigator.serviceWorker.controller.state}catch(e){return!1}}},{key:"unregisterWorker",value:function(){var e=this;"serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then((function(t){var i=!0,n=!1,s=void 0;try{for(var r,o=t[Symbol.iterator]();!(i=(r=o.next()).done);i=!0)r.value.unregister(),e.fire("onSubscriptionCancel")}catch(e){n=!0,s=e}finally{try{!i&&o.return&&o.return()}finally{if(n)throw s}}}))}},{key:"requestSubscription",value:function(){var e=this,t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=this,n=this.getPermissionStatus(),s=function(n){"granted"===n?(e.fire("onPermissionGranted"),"serviceWorker"in navigator?navigator.serviceWorker.register(e.workerPath).then((function(){navigator.serviceWorker.ready.then((function(e){i.fire("onWorkerSuccess"),e.pushManager.subscribe({userVisibleOnly:t}).then((function(e){var t=e.getKey("p256dh"),n=e.getKey("auth");i.subData={endpoint:i.getEndpoint(e),p256dh:t?window.btoa(String.fromCharCode.apply(null,new Uint8Array(t))):null,auth:n?window.btoa(String.fromCharCode.apply(null,new Uint8Array(n))):null},i.fire("onSubscriptionSuccess",[i.subData])})).catch((function(e){i.fire("onWorkerError",[e])}))}))})):i.fire("onWorkerNotSupported")):"denied"===n&&(e.fire("onPermissionDenied"),e.unregisterWorker())};"default"===n?window.Notification&&window.Notification.requestPermission?window.Notification.requestPermission(s):window.webkitNotifications&&window.webkitNotifications.checkPermission&&window.webkitNotifications.requestPermission(s):s(n)}}]),e}()},function(e,t,i){(function(t,n){var s;s=function(){function e(e){return"function"==typeof e}var s=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},r=0,o=void 0,a=void 0,l=function(e,t){_[r]=e,_[r+1]=t,2===(r+=2)&&(a?a(m):b())},h="undefined"!=typeof window?window:void 0,c=h||{},u=c.MutationObserver||c.WebKitMutationObserver,d="undefined"==typeof self&&void 0!==t&&"[object process]"==={}.toString.call(t),p="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function f(){var e=setTimeout;return function(){return e(m,1)}}var _=new Array(1e3);function m(){for(var e=0;e<r;e+=2)(0,_[e])(_[e+1]),_[e]=void 0,_[e+1]=void 0;r=0}var g,v,y,x,b=void 0;function T(e,t){var i=arguments,n=this,s=new this.constructor(C);void 0===s[E]&&z(s);var r,o=n._state;return o?(r=i[o-1],l((function(){return k(o,s,r,n._result)}))):L(n,s,e,t),s}function S(e){if(e&&"object"==typeof e&&e.constructor===this)return e;var t=new this(C);return O(t,e),t}d?b=function(){return t.nextTick(m)}:u?(v=0,y=new u(m),x=document.createTextNode(""),y.observe(x,{characterData:!0}),b=function(){x.data=v=++v%2}):p?((g=new MessageChannel).port1.onmessage=m,b=function(){return g.port2.postMessage(0)}):b=void 0===h?function(){try{var e=i(9);return void 0!==(o=e.runOnLoop||e.runOnContext)?function(){o(m)}:f()}catch(e){return f()}}():f();var E=Math.random().toString(36).substring(16);function C(){}var A=void 0,P=1,R=2,M=new U;function I(e){try{return e.then}catch(e){return M.error=e,M}}function D(t,i,n){i.constructor===t.constructor&&n===T&&i.constructor.resolve===S?function(e,t){t._state===P?N(e,t._result):t._state===R?F(e,t._result):L(t,void 0,(function(t){return O(e,t)}),(function(t){return F(e,t)}))}(t,i):n===M?(F(t,M.error),M.error=null):void 0===n?N(t,i):e(n)?function(e,t,i){l((function(e){var n=!1,s=function(i,s,r,o){try{i.call(s,(function(i){n||(n=!0,t!==i?O(e,i):N(e,i))}),(function(t){n||(n=!0,F(e,t))}))}catch(e){return e}}(i,t,0,0,e._label);!n&&s&&(n=!0,F(e,s))}),e)}(t,i,n):N(t,i)}function O(e,t){var i,n;e===t?F(e,new TypeError("You cannot resolve a promise with itself")):(n=typeof(i=t),null===i||"object"!==n&&"function"!==n?N(e,t):D(e,t,I(t)))}function w(e){e._onerror&&e._onerror(e._result),B(e)}function N(e,t){e._state===A&&(e._result=t,e._state=P,0!==e._subscribers.length&&l(B,e))}function F(e,t){e._state===A&&(e._state=R,e._result=t,l(w,e))}function L(e,t,i,n){var s=e._subscribers,r=s.length;e._onerror=null,s[r]=t,s[r+P]=i,s[r+R]=n,0===r&&e._state&&l(B,e)}function B(e){var t=e._subscribers,i=e._state;if(0!==t.length){for(var n=void 0,s=void 0,r=e._result,o=0;o<t.length;o+=3)n=t[o],s=t[o+i],n?k(i,n,s,r):s(r);e._subscribers.length=0}}function U(){this.error=null}var V=new U;function k(t,i,n,s){var r=e(n),o=void 0,a=void 0,l=void 0,h=void 0;if(r){if(o=function(e,t){try{return e(t)}catch(e){return V.error=e,V}}(n,s),o===V?(h=!0,a=o.error,o.error=null):l=!0,i===o)return void F(i,new TypeError("A promises callback cannot return that same promise."))}else o=s,l=!0;i._state!==A||(r&&l?O(i,o):h?F(i,a):t===P?N(i,o):t===R&&F(i,o))}var G=0;function z(e){e[E]=G++,e._state=void 0,e._result=void 0,e._subscribers=[]}function W(e,t){this._instanceConstructor=e,this.promise=new e(C),this.promise[E]||z(this.promise),s(t)?(this.length=t.length,this._remaining=t.length,this._result=new Array(this.length),0===this.length?N(this.promise,this._result):(this.length=this.length||0,this._enumerate(t),0===this._remaining&&N(this.promise,this._result))):F(this.promise,new Error("Array Methods must be provided an Array"))}function H(e){this[E]=G++,this._result=this._state=void 0,this._subscribers=[],C!==e&&("function"!=typeof e&&function(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}(),this instanceof H?function(e,t){try{t((function(t){O(e,t)}),(function(t){F(e,t)}))}catch(t){F(e,t)}}(this,e):function(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}())}return W.prototype._enumerate=function(e){for(var t=0;this._state===A&&t<e.length;t++)this._eachEntry(e[t],t)},W.prototype._eachEntry=function(e,t){var i=this._instanceConstructor,n=i.resolve;if(n===S){var s=I(e);if(s===T&&e._state!==A)this._settledAt(e._state,t,e._result);else if("function"!=typeof s)this._remaining--,this._result[t]=e;else if(i===H){var r=new i(C);D(r,e,s),this._willSettleAt(r,t)}else this._willSettleAt(new i((function(t){return t(e)})),t)}else this._willSettleAt(n(e),t)},W.prototype._settledAt=function(e,t,i){var n=this.promise;n._state===A&&(this._remaining--,e===R?F(n,i):this._result[t]=i),0===this._remaining&&N(n,this._result)},W.prototype._willSettleAt=function(e,t){var i=this;L(e,void 0,(function(e){return i._settledAt(P,t,e)}),(function(e){return i._settledAt(R,t,e)}))},H.all=function(e){return new W(this,e).promise},H.race=function(e){var t=this;return s(e)?new t((function(i,n){for(var s=e.length,r=0;r<s;r++)t.resolve(e[r]).then(i,n)})):new t((function(e,t){return t(new TypeError("You must pass an array to race."))}))},H.resolve=S,H.reject=function(e){var t=new this(C);return F(t,e),t},H._setScheduler=function(e){a=e},H._setAsap=function(e){l=e},H._asap=l,H.prototype={constructor:H,then:T,catch:function(e){return this.then(null,e)}},H.polyfill=function(){var e=void 0;if(void 0!==n)e=n;else if("undefined"!=typeof self)e=self;else try{e=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var t=e.Promise;if(t){var i=null;try{i=Object.prototype.toString.call(t.resolve())}catch(e){}if("[object Promise]"===i&&!t.cast)return}e.Promise=H},H.Promise=H,H},e.exports=s()}).call(t,i(7),i(8))},function(e,t){},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();i(5);var s,r=(s=i(4))&&s.__esModule?s:{default:s},o=c(i(0)),a=c(i(1)),l=i(2),h=i(3);function c(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}var u=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.options=o.deepExtend({},a.Defaults,t),a.Store[this.options.id]?a.Store[this.options.id]:(this.id=this.options.id||o.generateID("bar"),this.closeTimer=-1,this.barDom=null,this.layoutDom=null,this.progressDom=null,this.showing=!1,this.shown=!1,this.closed=!1,this.closing=!1,this.killable=this.options.timeout||this.options.closeWith.length>0,this.hasSound=this.options.sounds.sources.length>0,this.soundPlayed=!1,this.listeners={beforeShow:[],onShow:[],afterShow:[],onClose:[],afterClose:[],onClick:[],onHover:[],onTemplate:[]},this.promises={show:null,close:null},this.on("beforeShow",this.options.callbacks.beforeShow),this.on("onShow",this.options.callbacks.onShow),this.on("afterShow",this.options.callbacks.afterShow),this.on("onClose",this.options.callbacks.onClose),this.on("afterClose",this.options.callbacks.afterClose),this.on("onClick",this.options.callbacks.onClick),this.on("onHover",this.options.callbacks.onHover),this.on("onTemplate",this.options.callbacks.onTemplate),this)}return n(e,[{key:"on",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){};return"function"==typeof t&&this.listeners.hasOwnProperty(e)&&this.listeners[e].push(t),this}},{key:"show",value:function(){var t=this;if(this.showing||this.shown)return this;!0===this.options.killer?e.closeAll():"string"==typeof this.options.killer&&e.closeAll(this.options.killer);var i=a.getQueueCounts(this.options.queue);if(i.current>=i.maxVisible||a.PageHidden&&this.options.visibilityControl)return a.addToQueue(this),a.PageHidden&&this.hasSound&&o.inArray("docHidden",this.options.sounds.conditions)&&o.createAudioElements(this),a.PageHidden&&o.inArray("docHidden",this.options.titleCount.conditions)&&a.docTitle.increment(),this;if(a.Store[this.id]=this,a.fire(this,"beforeShow"),this.showing=!0,this.closing)return this.showing=!1,this;if(a.build(this),a.handleModal(this),this.options.force?this.layoutDom.insertBefore(this.barDom,this.layoutDom.firstChild):this.layoutDom.appendChild(this.barDom),this.hasSound&&!this.soundPlayed&&o.inArray("docVisible",this.options.sounds.conditions)&&o.createAudioElements(this),o.inArray("docVisible",this.options.titleCount.conditions)&&a.docTitle.increment(),this.shown=!0,this.closed=!1,a.hasButtons(this)&&Object.keys(this.options.buttons).forEach((function(e){var i=t.barDom.querySelector("#"+t.options.buttons[e].id);o.addListener(i,"click",(function(i){o.stopPropagation(i),t.options.buttons[e].cb(t)}))})),this.progressDom=this.barDom.querySelector(".noty_progressbar"),o.inArray("click",this.options.closeWith)&&(o.addClass(this.barDom,"noty_close_with_click"),o.addListener(this.barDom,"click",(function(e){o.stopPropagation(e),a.fire(t,"onClick"),t.close()}),!1)),o.addListener(this.barDom,"mouseenter",(function(){a.fire(t,"onHover")}),!1),this.options.timeout&&o.addClass(this.barDom,"noty_has_timeout"),this.options.progressBar&&o.addClass(this.barDom,"noty_has_progressbar"),o.inArray("button",this.options.closeWith)){o.addClass(this.barDom,"noty_close_with_button");var n=document.createElement("div");o.addClass(n,"noty_close_button"),n.innerHTML="×",this.barDom.appendChild(n),o.addListener(n,"click",(function(e){o.stopPropagation(e),t.close()}),!1)}return a.fire(this,"onShow"),null===this.options.animation.open?this.promises.show=new r.default((function(e){e()})):"function"==typeof this.options.animation.open?this.promises.show=new r.default(this.options.animation.open.bind(this)):(o.addClass(this.barDom,this.options.animation.open),this.promises.show=new r.default((function(e){o.addListener(t.barDom,o.animationEndEvents,(function(){o.removeClass(t.barDom,t.options.animation.open),e()}))}))),this.promises.show.then((function(){var e=t;setTimeout((function(){a.openFlow(e)}),100)})),this}},{key:"stop",value:function(){return a.dequeueClose(this),this}},{key:"resume",value:function(){return a.queueClose(this),this}},{key:"setTimeout",value:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){if(this.stop(),this.options.timeout=e,this.barDom){this.options.timeout?o.addClass(this.barDom,"noty_has_timeout"):o.removeClass(this.barDom,"noty_has_timeout");var t=this;setTimeout((function(){t.resume()}),100)}return this}))},{key:"setText",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.barDom&&(this.barDom.querySelector(".noty_body").innerHTML=e),t&&(this.options.text=e),this}},{key:"setType",value:function(e){var t=this,i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.barDom&&(o.classList(this.barDom).split(" ").forEach((function(e){"noty_type__"===e.substring(0,11)&&o.removeClass(t.barDom,e)})),o.addClass(this.barDom,"noty_type__"+e)),i&&(this.options.type=e),this}},{key:"setTheme",value:function(e){var t=this,i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.barDom&&(o.classList(this.barDom).split(" ").forEach((function(e){"noty_theme__"===e.substring(0,12)&&o.removeClass(t.barDom,e)})),o.addClass(this.barDom,"noty_theme__"+e)),i&&(this.options.theme=e),this}},{key:"close",value:function(){var e=this;return this.closed?this:this.shown?(a.fire(this,"onClose"),this.closing=!0,null===this.options.animation.close||!1===this.options.animation.close?this.promises.close=new r.default((function(e){e()})):"function"==typeof this.options.animation.close?this.promises.close=new r.default(this.options.animation.close.bind(this)):(o.addClass(this.barDom,this.options.animation.close),this.promises.close=new r.default((function(t){o.addListener(e.barDom,o.animationEndEvents,(function(){e.options.force?o.remove(e.barDom):a.ghostFix(e),t()}))}))),this.promises.close.then((function(){a.closeFlow(e),a.handleModalClose(e)})),this.closed=!0,this):(a.removeFromQueue(this),this)}}],[{key:"closeAll",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Object.keys(a.Store).forEach((function(t){e?a.Store[t].options.queue===e&&a.Store[t].killable&&a.Store[t].close():a.Store[t].killable&&a.Store[t].close()})),this}},{key:"clearQueue",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"global";return a.Queues.hasOwnProperty(e)&&(a.Queues[e].queue=[]),this}},{key:"overrideDefaults",value:function(e){return a.Defaults=o.deepExtend({},a.Defaults,e),this}},{key:"setMaxVisible",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:a.DefaultMaxVisible,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"global";return a.Queues.hasOwnProperty(t)||(a.Queues[t]={maxVisible:e,queue:[]}),a.Queues[t].maxVisible=e,this}},{key:"button",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return new l.NotyButton(e,t,i,n)}},{key:"version",value:function(){return"3.2.0-beta"}},{key:"Push",value:function(e){return new h.Push(e)}},{key:"Queues",get:function(){return a.Queues}},{key:"PageHidden",get:function(){return a.PageHidden}}]),e}();t.default=u,"undefined"!=typeof window&&o.visibilityChangeFlow(),e.exports=t.default},function(e,t){var i,n,s=e.exports={};function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function a(e){if(i===setTimeout)return setTimeout(e,0);if((i===r||!i)&&setTimeout)return i=setTimeout,setTimeout(e,0);try{return i(e,0)}catch(t){try{return i.call(null,e,0)}catch(t){return i.call(this,e,0)}}}!function(){try{i="function"==typeof setTimeout?setTimeout:r}catch(e){i=r}try{n="function"==typeof clearTimeout?clearTimeout:o}catch(e){n=o}}();var l,h=[],c=!1,u=-1;function d(){c&&l&&(c=!1,l.length?h=l.concat(h):u=-1,h.length&&p())}function p(){if(!c){var e=a(d);c=!0;for(var t=h.length;t;){for(l=h,h=[];++u<t;)l&&l[u].run();u=-1,t=h.length}l=null,c=!1,function(e){if(n===clearTimeout)return clearTimeout(e);if((n===o||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(e);try{return n(e)}catch(t){try{return n.call(null,e)}catch(t){return n.call(this,e)}}}(e)}}function f(e,t){this.fun=e,this.array=t}function _(){}s.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)t[i-1]=arguments[i];h.push(new f(e,t)),1!==h.length||c||a(p)},f.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=_,s.addListener=_,s.once=_,s.off=_,s.removeListener=_,s.removeAllListeners=_,s.emit=_,s.prependListener=_,s.prependOnceListener=_,s.listeners=function(e){return[]},s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},function(e,t){var i;i=function(){return this}();try{i=i||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(i=window)}e.exports=i},function(e,t){}])},e.exports=t()},14:function(e,t,i){var n=this&&this.__spreadArrays||function(){for(var e=0,t=0,i=arguments.length;t<i;t++)e+=arguments[t].length;var n=Array(e),s=0;for(t=0;t<i;t++)for(var r=arguments[t],o=0,a=r.length;o<a;o++,s++)n[s]=r[o];return n};t.__esModule=!0,t.buildMethodCb=t.buildCb=t.getPrComplete=t.isRunning=t.cancelAllQueuedCalls=t.getQueuedCallCount=t.buildMethod=t.build=t.createGroupRef=void 0;var s=i(9589),r=function(){function e(){this.queuedCalls=[],this.isRunning=!1,this.prComplete=Promise.resolve()}return e.prototype.cancelAllQueuedCalls=function(){var e;return this.queuedCalls.splice(0,e=this.queuedCalls.length),e},e}(),o={},a=new s.Polyfill;function l(e,t){var i=a.get(e);i||(i=new s.Polyfill,a.set(e,i));var n=i.get(t);return n||(n=new r,i.set(t,n)),n}function h(){return new Array(0)}t.createGroupRef=h,t.build=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];switch(e.length){case 1:return d(!0,h(),e[0]);case 2:return d(!0,e[0],e[1])}},t.buildMethod=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];switch(e.length){case 1:return d(!1,h(),e[0]);case 2:return d(!1,e[0],e[1])}},t.getQueuedCallCount=function(e,t){var i=u(e,t);return i?i.queuedCalls.length:0},t.cancelAllQueuedCalls=function(e,t){var i=u(e,t);return i?i.cancelAllQueuedCalls():0},t.isRunning=function(e,t){var i=u(e,t);return!!i&&i.isRunning},t.getPrComplete=function(e,t){var i=u(e,t);return i?i.prComplete:Promise.resolve()};var c=new s.Polyfill;function u(e,t){void 0===t&&(t=o);var i=c.get(e);if(!i)throw Error("Not a run exclusiveFunction");var n=a.get(t);if(n)return n.get(i)}function d(e,t,i){var n,s=function(){for(var s=this,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];if(!e){if(!(this instanceof Object))throw new Error("Run exclusive, <this> should be an object");n=l(this,t)}return new Promise((function(e,t){var o;n.prComplete=new Promise((function(e){return o=function(){return e()}}));var a=function(i){o(),n.isRunning=!1,n.queuedCalls.length&&n.queuedCalls.shift()(),"data"in i?e(i.data):t(i.reason)};(function e(){for(var t=this,s=[],r=0;r<arguments.length;r++)s[r]=arguments[r];if(n.isRunning)n.queuedCalls.push((function(){return e.apply(t,s)}));else{n.isRunning=!0;try{i.apply(this,s).then((function(e){return a({data:e})})).catch((function(e){return a({reason:e})}))}catch(e){a({reason:e})}}}).apply(s,r)}))};return e&&(n=l(o,t)),c.set(s,t),s}function p(e,t,i){var s,r=function(){for(var r=this,o=[],a=0;a<arguments.length;a++)o[a]=arguments[a];if(!e){if(!(this instanceof Object))throw new Error("Run exclusive, <this> should be an object");s=l(this,t)}var h,c=void 0;o.length&&"function"==typeof o[o.length-1]&&(c=o.pop()),s.prComplete=new Promise((function(e){return h=function(){return e()}}));var u=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];h(),s.isRunning=!1,s.queuedCalls.length&&s.queuedCalls.shift()(),c&&c.apply(r,e)};u.hasCallback=!!c,function e(){for(var t=this,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];if(s.isRunning)s.queuedCalls.push((function(){return e.apply(t,r)}));else{s.isRunning=!0;try{i.apply(this,n(r,[u]))}catch(e){throw e.message+=" ( This exception should not have been thrown, miss use of run-exclusive buildCb )",e}}}.apply(this,o)};return e&&(s=l(o,t)),c.set(r,t),r}t.buildCb=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];switch(e.length){case 1:return p(!0,h(),e[0]);case 2:return p(!0,e[0],e[1])}},t.buildMethodCb=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];switch(e.length){case 1:return p(!1,h(),e[0]);case 2:return p(!1,e[0],e[1])}}},7609:(e,t,i)=>{var n=i(7425).default;function s(){e.exports=s=function(){return t},e.exports.__esModule=!0,e.exports.default=e.exports;var t={},i=Object.prototype,r=i.hasOwnProperty,o=Object.defineProperty||function(e,t,i){e[t]=i.value},a="function"==typeof Symbol?Symbol:{},l=a.iterator||"@@iterator",h=a.asyncIterator||"@@asyncIterator",c=a.toStringTag||"@@toStringTag";function u(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{u({},"")}catch(e){u=function(e,t,i){return e[t]=i}}function d(e,t,i,n){var s=t&&t.prototype instanceof _?t:_,r=Object.create(s.prototype),a=new R(n||[]);return o(r,"_invoke",{value:E(e,i,a)}),r}function p(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}t.wrap=d;var f={};function _(){}function m(){}function g(){}var v={};u(v,l,(function(){return this}));var y=Object.getPrototypeOf,x=y&&y(y(M([])));x&&x!==i&&r.call(x,l)&&(v=x);var b=g.prototype=_.prototype=Object.create(v);function T(e){["next","throw","return"].forEach((function(t){u(e,t,(function(e){return this._invoke(t,e)}))}))}function S(e,t){function i(s,o,a,l){var h=p(e[s],e,o);if("throw"!==h.type){var c=h.arg,u=c.value;return u&&"object"==n(u)&&r.call(u,"__await")?t.resolve(u.__await).then((function(e){i("next",e,a,l)}),(function(e){i("throw",e,a,l)})):t.resolve(u).then((function(e){c.value=e,a(c)}),(function(e){return i("throw",e,a,l)}))}l(h.arg)}var s;o(this,"_invoke",{value:function(e,n){function r(){return new t((function(t,s){i(e,n,t,s)}))}return s=s?s.then(r,r):r()}})}function E(e,t,i){var n="suspendedStart";return function(s,r){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===s)throw r;return{value:void 0,done:!0}}for(i.method=s,i.arg=r;;){var o=i.delegate;if(o){var a=C(o,i);if(a){if(a===f)continue;return a}}if("next"===i.method)i.sent=i._sent=i.arg;else if("throw"===i.method){if("suspendedStart"===n)throw n="completed",i.arg;i.dispatchException(i.arg)}else"return"===i.method&&i.abrupt("return",i.arg);n="executing";var l=p(e,t,i);if("normal"===l.type){if(n=i.done?"completed":"suspendedYield",l.arg===f)continue;return{value:l.arg,done:i.done}}"throw"===l.type&&(n="completed",i.method="throw",i.arg=l.arg)}}}function C(e,t){var i=t.method,n=e.iterator[i];if(void 0===n)return t.delegate=null,"throw"===i&&e.iterator.return&&(t.method="return",t.arg=void 0,C(e,t),"throw"===t.method)||"return"!==i&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+i+"' method")),f;var s=p(n,e.iterator,t.arg);if("throw"===s.type)return t.method="throw",t.arg=s.arg,t.delegate=null,f;var r=s.arg;return r?r.done?(t[e.resultName]=r.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):r:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function M(e){if(e){var t=e[l];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var i=-1,n=function t(){for(;++i<e.length;)if(r.call(e,i))return t.value=e[i],t.done=!1,t;return t.value=void 0,t.done=!0,t};return n.next=n}}return{next:I}}function I(){return{value:void 0,done:!0}}return m.prototype=g,o(b,"constructor",{value:g,configurable:!0}),o(g,"constructor",{value:m,configurable:!0}),m.displayName=u(g,c,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===m||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,g):(e.__proto__=g,u(e,c,"GeneratorFunction")),e.prototype=Object.create(b),e},t.awrap=function(e){return{__await:e}},T(S.prototype),u(S.prototype,h,(function(){return this})),t.AsyncIterator=S,t.async=function(e,i,n,s,r){void 0===r&&(r=Promise);var o=new S(d(e,i,n,s),r);return t.isGeneratorFunction(i)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},T(b),u(b,c,"Generator"),u(b,l,(function(){return this})),u(b,"toString",(function(){return"[object Generator]"})),t.keys=function(e){var t=Object(e),i=[];for(var n in t)i.push(n);return i.reverse(),function e(){for(;i.length;){var n=i.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},t.values=M,R.prototype={constructor:R,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(P),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function i(i,n){return o.type="throw",o.arg=e,t.next=i,n&&(t.method="next",t.arg=void 0),!!n}for(var n=this.tryEntries.length-1;n>=0;--n){var s=this.tryEntries[n],o=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var a=r.call(s,"catchLoc"),l=r.call(s,"finallyLoc");if(a&&l){if(this.prev<s.catchLoc)return i(s.catchLoc,!0);if(this.prev<s.finallyLoc)return i(s.finallyLoc)}else if(a){if(this.prev<s.catchLoc)return i(s.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return i(s.finallyLoc)}}}},abrupt:function(e,t){for(var i=this.tryEntries.length-1;i>=0;--i){var n=this.tryEntries[i];if(n.tryLoc<=this.prev&&r.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var s=n;break}}s&&("break"===e||"continue"===e)&&s.tryLoc<=t&&t<=s.finallyLoc&&(s=null);var o=s?s.completion:{};return o.type=e,o.arg=t,s?(this.method="next",this.next=s.finallyLoc,f):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),P(i),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var n=i.completion;if("throw"===n.type){var s=n.arg;P(i)}return s}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:M(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),f}},t}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports},7425:e=>{function t(i){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(i)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},2841:(e,t,i)=>{var n=i(7609)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},1803:(e,t,i)=>{i.d(t,{O:()=>n});class n{constructor(){this.hoverCursor="",this.actions=new Array,this.isRecursive=!1}static get HasTriggers(){for(const e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,t)&&parseInt(t)===e)return!0;return!1}}n.Triggers={}},2633:(e,t,i)=>{i.d(t,{V:()=>n});class n{constructor(e,t,i,n,s,r){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=n,this.sourceEvent=s,this.additionalData=r}static CreateNew(e,t,i){const s=e.getScene();return new n(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new n(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new n(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new n(e,t.x,t.y,null,i,s)}}},4676:(e,t,i)=>{i.d(t,{f:()=>f,u:()=>p});var n=i(4141),s=i(4649),r=i(1128),o=i(3956),a=i(2208),l=i(4173),h=i(2695),c=i(9257),u=i(9697),d=i(6662);class p{}class f{static _PrepareAnimation(e,t,i,r,o,a,l,h){let c;if(!isNaN(parseFloat(o))&&isFinite(o)?c=f.ANIMATIONTYPE_FLOAT:o instanceof n._f?c=f.ANIMATIONTYPE_QUATERNION:o instanceof n.P?c=f.ANIMATIONTYPE_VECTOR3:o instanceof n.FM?c=f.ANIMATIONTYPE_VECTOR2:o instanceof s.Wo?c=f.ANIMATIONTYPE_COLOR3:o instanceof s.HE?c=f.ANIMATIONTYPE_COLOR4:o instanceof u.$&&(c=f.ANIMATIONTYPE_SIZE),null==c)return null;const d=new f(e,t,i,c,l),p=[{frame:0,value:o},{frame:r,value:a}];return d.setKeys(p),void 0!==h&&d.setEasingFunction(h),d}static CreateAnimation(e,t,i,n){const s=new f(e+"Animation",e,i,t,f.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(n),s}static CreateAndStartAnimation(e,t,i,n,s,r,o,a,l,h,c){const u=f._PrepareAnimation(e,i,n,s,r,o,a,l);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,s,1===u.loopMode,1,h):null):null}static CreateAndStartHierarchyAnimation(e,t,i,n,s,r,o,a,l,h,c){const u=f._PrepareAnimation(e,n,s,r,o,a,l,h);return u?t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,r,1===u.loopMode,1,c):null}static CreateMergeAndStartAnimation(e,t,i,n,s,r,o,a,l,h){const c=f._PrepareAnimation(e,i,n,s,r,o,a,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,s,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t=0,i,s=!1,r){let o=e;if(s&&(o=e.clone(),o.name=r||o.name),!o._keys.length)return o;t=t>=0?t:0;let a=0;const l=o._keys[0];let h=o._keys.length-1;const c=o._keys[h],u={referenceValue:l.value,referencePosition:n.jp.Vector3[0],referenceQuaternion:n.jp.Quaternion[0],referenceScaling:n.jp.Vector3[1],keyPosition:n.jp.Vector3[2],keyQuaternion:n.jp.Quaternion[1],keyScaling:n.jp.Vector3[3]};let d=!1,p=l.frame,_=c.frame;if(i){const e=o.getRange(i);e&&(p=e.from,_=e.to)}let m=l.frame===p,g=c.frame===_;if(1===o._keys.length){const e=o._getKeyValue(o._keys[0]);u.referenceValue=e.clone?e.clone():e,d=!0}else if(t<=l.frame){const e=o._getKeyValue(l.value);u.referenceValue=e.clone?e.clone():e,d=!0}else if(t>=c.frame){const e=o._getKeyValue(c.value);u.referenceValue=e.clone?e.clone():e,d=!0}let v=0;for(;!d||!m||!g&&v<o._keys.length-1;){const e=o._keys[v],i=o._keys[v+1];if(!d&&t>=e.frame&&t<=i.frame){let n;if(t===e.frame)n=o._getKeyValue(e.value);else if(t===i.frame)n=o._getKeyValue(i.value);else{const e={key:v,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT};n=o._interpolate(t,e)}u.referenceValue=n.clone?n.clone():n,d=!0}if(!m&&p>=e.frame&&p<=i.frame){if(p===e.frame)a=v;else if(p===i.frame)a=v+1;else{const e={key:v,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},t=o._interpolate(p,e),i={frame:p,value:t.clone?t.clone():t};o._keys.splice(v+1,0,i),a=v+1}m=!0}if(!g&&_>=e.frame&&_<=i.frame){if(_===e.frame)h=v;else if(_===i.frame)h=v+1;else{const e={key:v,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},t=o._interpolate(_,e),i={frame:_,value:t.clone?t.clone():t};o._keys.splice(v+1,0,i),h=v+1}g=!0}v++}for(o.dataType===f.ANIMATIONTYPE_QUATERNION?u.referenceValue.normalize().conjugateInPlace():o.dataType===f.ANIMATIONTYPE_MATRIX&&(u.referenceValue.decompose(u.referenceScaling,u.referenceQuaternion,u.referencePosition),u.referenceQuaternion.normalize().conjugateInPlace()),v=a;v<=h;v++){const e=o._keys[v];if(!v||o.dataType===f.ANIMATIONTYPE_FLOAT||e.value!==l.value)switch(o.dataType){case f.ANIMATIONTYPE_MATRIX:e.value.decompose(u.keyScaling,u.keyQuaternion,u.keyPosition),u.keyPosition.subtractInPlace(u.referencePosition),u.keyScaling.divideInPlace(u.referenceScaling),u.referenceQuaternion.multiplyToRef(u.keyQuaternion,u.keyQuaternion),n.y3.ComposeToRef(u.keyScaling,u.keyQuaternion,u.keyPosition,e.value);break;case f.ANIMATIONTYPE_QUATERNION:u.referenceValue.multiplyToRef(e.value,e.value);break;case f.ANIMATIONTYPE_VECTOR2:case f.ANIMATIONTYPE_VECTOR3:case f.ANIMATIONTYPE_COLOR3:case f.ANIMATIONTYPE_COLOR4:e.value.subtractToRef(u.referenceValue,e.value);break;case f.ANIMATIONTYPE_SIZE:e.value.width-=u.referenceValue.width,e.value.height-=u.referenceValue.height;break;default:e.value-=u.referenceValue}}return o}static TransitionTo(e,t,i,n,s,r,o,a=null){if(o<=0)return i[e]=t,a&&a(),null;const l=s*(o/1e3);r.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(r);const h=n.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,n,s,r){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=n,this.loopMode=s,this.enableBlending=r,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=n,this.loopMode=void 0===s?f.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=f._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 e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)}getEvents(){return this._events}createRange(e,t,i){this._ranges[e]||(this._ranges[e]=new h.X(e,t,i))}deleteRange(e,t=!0){const i=this._ranges[e];if(i){if(t){const e=i.from,t=i.to;for(let i=this._keys.length-1;i>=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e}getEasingFunction(){return this._easingFunction}setEasingFunction(e){this._easingFunction=e}floatInterpolateFunction(e,t,i){return r.R.Lerp(e,t,i)}floatInterpolateFunctionWithTangents(e,t,i,n,s){return r.R.Hermite(e,t,i,n,s)}quaternionInterpolateFunction(e,t,i){return n._f.Slerp(e,t,i)}quaternionInterpolateFunctionWithTangents(e,t,i,s,r){return n._f.Hermite(e,t,i,s,r).normalize()}vector3InterpolateFunction(e,t,i){return n.P.Lerp(e,t,i)}vector3InterpolateFunctionWithTangents(e,t,i,s,r){return n.P.Hermite(e,t,i,s,r)}vector2InterpolateFunction(e,t,i){return n.FM.Lerp(e,t,i)}vector2InterpolateFunctionWithTangents(e,t,i,s,r){return n.FM.Hermite(e,t,i,s,r)}sizeInterpolateFunction(e,t,i){return u.$.Lerp(e,t,i)}color3InterpolateFunction(e,t,i){return s.Wo.Lerp(e,t,i)}color3InterpolateFunctionWithTangents(e,t,i,n,r){return s.Wo.Hermite(e,t,i,n,r)}color4InterpolateFunction(e,t,i){return s.HE.Lerp(e,t,i)}color4InterpolateFunctionWithTangents(e,t,i,n,r){return s.HE.Hermite(e,t,i,n,r)}_getKeyValue(e){return"function"==typeof e?e():e}evaluate(e){return this._interpolate(e,{key:0,repeatCount:0,loopMode:f.ANIMATIONLOOPMODE_CONSTANT})}_interpolate(e,t){if(t.loopMode===f.ANIMATIONLOOPMODE_CONSTANT&&t.repeatCount>0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const i=this._keys,n=i.length;let s=t.key;for(;s>=0&&e<i[s].frame;)--s;for(;s+1<=n-1&&e>=i[s+1].frame;)++s;if(t.key=s,s<0)return this._getKeyValue(i[0].value);if(s+1>n-1)return this._getKeyValue(i[n-1].value);const r=i[s],o=i[s+1],a=this._getKeyValue(r.value),h=this._getKeyValue(o.value);if(r.interpolation===l.N.STEP)return o.frame>e?a:h;const c=void 0!==r.outTangent&&void 0!==o.inTangent,u=o.frame-r.frame;let d=(e-r.frame)/u;const p=this.getEasingFunction();switch(null!==p&&(d=p.ease(d)),this.dataType){case f.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(a,r.outTangent*u,h,o.inTangent*u,d):this.floatInterpolateFunction(a,h,d);switch(t.loopMode){case f.ANIMATIONLOOPMODE_CYCLE:case f.ANIMATIONLOOPMODE_CONSTANT:return e;case f.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+e}break}case f.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(a,r.outTangent.scale(u),h,o.inTangent.scale(u),d):this.quaternionInterpolateFunction(a,h,d);switch(t.loopMode){case f.ANIMATIONLOOPMODE_CYCLE:case f.ANIMATIONLOOPMODE_CONSTANT:return e;case f.ANIMATIONLOOPMODE_RELATIVE:return e.addInPlace(t.offsetValue.scale(t.repeatCount))}return e}case f.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(a,r.outTangent.scale(u),h,o.inTangent.scale(u),d):this.vector3InterpolateFunction(a,h,d);switch(t.loopMode){case f.ANIMATIONLOOPMODE_CYCLE:case f.ANIMATIONLOOPMODE_CONSTANT:return e;case f.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case f.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(a,r.outTangent.scale(u),h,o.inTangent.scale(u),d):this.vector2InterpolateFunction(a,h,d);switch(t.loopMode){case f.ANIMATIONLOOPMODE_CYCLE:case f.ANIMATIONLOOPMODE_CONSTANT:return e;case f.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case f.ANIMATIONTYPE_SIZE:switch(t.loopMode){case f.ANIMATIONLOOPMODE_CYCLE:case f.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(a,h,d);case f.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(a,h,d).add(t.offsetValue.scale(t.repeatCount))}break;case f.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(a,r.outTangent.scale(u),h,o.inTangent.scale(u),d):this.color3InterpolateFunction(a,h,d);switch(t.loopMode){case f.ANIMATIONLOOPMODE_CYCLE:case f.ANIMATIONLOOPMODE_CONSTANT:return e;case f.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case f.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(a,r.outTangent.scale(u),h,o.inTangent.scale(u),d):this.color4InterpolateFunction(a,h,d);switch(t.loopMode){case f.ANIMATIONLOOPMODE_CYCLE:case f.ANIMATIONLOOPMODE_CONSTANT:return e;case f.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case f.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case f.ANIMATIONLOOPMODE_CYCLE:case f.ANIMATIONLOOPMODE_CONSTANT:return f.AllowMatricesInterpolation?this.matrixInterpolateFunction(a,h,d,t.workValue):a;case f.ANIMATIONLOOPMODE_RELATIVE:return a}}return 0}matrixInterpolateFunction(e,t,i,s){return f.AllowMatrixDecomposeForInterpolation?s?(n.y3.DecomposeLerpToRef(e,t,i,s),s):n.y3.DecomposeLerp(e,t,i):s?(n.y3.LerpToRef(e,t,i,s),s):n.y3.Lerp(e,t,i)}clone(){const e=new f(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e){this._keys=e.slice(0)}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let n=0;n<i.length;n++){const s=i[n],r={};switch(r.frame=s.frame,t){case f.ANIMATIONTYPE_FLOAT:r.values=[s.value],void 0!==s.inTangent&&r.values.push(s.inTangent),void 0!==s.outTangent&&(void 0===s.inTangent&&r.values.push(void 0),r.values.push(s.outTangent)),void 0!==s.interpolation&&(void 0===s.inTangent&&r.values.push(void 0),void 0===s.outTangent&&r.values.push(void 0),r.values.push(s.interpolation));break;case f.ANIMATIONTYPE_QUATERNION:case f.ANIMATIONTYPE_MATRIX:case f.ANIMATIONTYPE_VECTOR3:case f.ANIMATIONTYPE_COLOR3:case f.ANIMATIONTYPE_COLOR4:r.values=s.value.asArray(),null!=s.inTangent&&r.values.push(s.inTangent.asArray()),null!=s.outTangent&&(void 0===s.inTangent&&r.values.push(void 0),r.values.push(s.outTangent.asArray())),void 0!==s.interpolation&&(void 0===s.inTangent&&r.values.push(void 0),void 0===s.outTangent&&r.values.push(void 0),r.values.push(s.interpolation))}e.keys.push(r)}e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const n={};n.name=t,n.from=i.from,n.to=i.to,e.ranges.push(n)}return e}static _UniversalLerp(e,t,i){const n=e.constructor;return n.Lerp?n.Lerp(e,t,i):n.Slerp?n.Slerp(e,t,i):e.toFixed?e*(1-i)+i*t:t}static Parse(e){const t=new f(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior),i=e.dataType,r=[];let o,a;for(e.enableBlending&&(t.enableBlending=e.enableBlending),e.blendingSpeed&&(t.blendingSpeed=e.blendingSpeed),a=0;a<e.keys.length;a++){const t=e.keys[a];let l,h,c;switch(i){case f.ANIMATIONTYPE_FLOAT:o=t.values[0],t.values.length>=2&&(l=t.values[1]),t.values.length>=3&&(h=t.values[2]),t.values.length>=4&&(c=t.values[3]);break;case f.ANIMATIONTYPE_QUATERNION:if(o=n._f.FromArray(t.values),t.values.length>=8){const e=n._f.FromArray(t.values.slice(4,8));e.equals(n._f.Zero())||(l=e)}if(t.values.length>=12){const e=n._f.FromArray(t.values.slice(8,12));e.equals(n._f.Zero())||(h=e)}t.values.length>=13&&(c=t.values[12]);break;case f.ANIMATIONTYPE_MATRIX:o=n.y3.FromArray(t.values),t.values.length>=17&&(c=t.values[16]);break;case f.ANIMATIONTYPE_COLOR3:o=s.Wo.FromArray(t.values),t.values[3]&&(l=s.Wo.FromArray(t.values[3])),t.values[4]&&(h=s.Wo.FromArray(t.values[4])),t.values[5]&&(c=t.values[5]);break;case f.ANIMATIONTYPE_COLOR4:o=s.HE.FromArray(t.values),t.values[4]&&(l=s.HE.FromArray(t.values[4])),t.values[5]&&(h=s.HE.FromArray(t.values[5])),t.values[6]&&(c=s.HE.FromArray(t.values[6]));break;case f.ANIMATIONTYPE_VECTOR3:default:o=n.P.FromArray(t.values),t.values[3]&&(l=n.P.FromArray(t.values[3])),t.values[4]&&(h=n.P.FromArray(t.values[4])),t.values[5]&&(c=t.values[5])}const u={};u.frame=t.frame,u.value=o,null!=l&&(u.inTangent=l),null!=h&&(u.outTangent=h),null!=c&&(u.interpolation=c),r.push(u)}if(t.setKeys(r),e.ranges)for(a=0;a<e.ranges.length;a++)o=e.ranges[a],t.createRange(o.name,o.from,o.to);return t}static AppendSerializedAnimations(e,t){o.p4.AppendSerializedAnimations(e,t)}static ParseFromFileAsync(e,t){return new Promise(((i,n)=>{const s=new d.g;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){let t=JSON.parse(s.responseText);if(t.animations&&(t=t.animations),t.length){const e=new Array;for(const i of t)e.push(this.Parse(i));i(e)}else{const n=this.Parse(t);e&&(n.name=e),i(n)}}else n("Unable to load the animation")})),s.open("GET",t),s.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const n=new d.g;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const i=JSON.parse(JSON.parse(n.responseText).jsonPayload);if(i.animations){const n=JSON.parse(i.animations),s=new Array;for(const t of n.animations){const i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{const n=JSON.parse(i.animation),s=this.Parse(n);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}f._UniqueIdGenerator=0,f.AllowMatricesInterpolation=!1,f.AllowMatrixDecomposeForInterpolation=!0,f.SnippetUrl="https://snippet.babylonjs.com",f.ANIMATIONTYPE_FLOAT=0,f.ANIMATIONTYPE_VECTOR3=1,f.ANIMATIONTYPE_QUATERNION=2,f.ANIMATIONTYPE_MATRIX=3,f.ANIMATIONTYPE_COLOR3=4,f.ANIMATIONTYPE_COLOR4=7,f.ANIMATIONTYPE_VECTOR2=5,f.ANIMATIONTYPE_SIZE=6,f.ANIMATIONLOOPMODE_RELATIVE=0,f.ANIMATIONLOOPMODE_CYCLE=1,f.ANIMATIONLOOPMODE_CONSTANT=2,f.CreateFromSnippetAsync=f.ParseFromSnippetAsync,(0,a.H)("BABYLON.Animation",f),c.N._AnimationRangeFactory=(e,t,i)=>new h.X(e,t,i)},8117:(e,t,i)=>{i.d(t,{O:()=>n});class n{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new n(this.frame,this.action,this.onlyOnce)}}},2323:(e,t,i)=>{i.d(t,{O:()=>l,U:()=>a});var n=i(4676),s=i(5757),r=i(1431),o=i(4875);class a{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class l{get from(){return this._from}get to(){return this._to}get isStarted(){return this._isStarted}get isPlaying(){return this._isStarted&&!this._isPaused}get speedRatio(){return this._speedRatio}set speedRatio(e){if(this._speedRatio!==e){this._speedRatio=e;for(let e=0;e<this._animatables.length;e++)this._animatables[e].speedRatio=this._speedRatio}}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(let e=0;e<this._animatables.length;e++)this._animatables[e].loopAnimation=this._loopAnimation}}get isAdditive(){return this._isAdditive}set isAdditive(e){if(this._isAdditive!==e){this._isAdditive=e;for(let e=0;e<this._animatables.length;e++)this._animatables[e].isAdditive=this._isAdditive}}get targetedAnimations(){return this._targetedAnimations}get animatables(){return this._animatables}get children(){return this._targetedAnimations}constructor(e,t=null){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._parentContainer=null,this.onAnimationEndObservable=new s.y$,this.onAnimationLoopObservable=new s.y$,this.onAnimationGroupLoopObservable=new s.y$,this.onAnimationGroupEndObservable=new s.y$,this.onAnimationGroupPauseObservable=new s.y$,this.onAnimationGroupPlayObservable=new s.y$,this.metadata=null,this._animationLoopFlags=[],this._scene=t||r.l.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new a;i.animation=e,i.target=t;const n=e.getKeys();return this._from>n[0].frame&&(this._from=n[0].frame),this._to<n[n.length-1].frame&&(this._to=n[n.length-1].frame),this._targetedAnimations.push(i),i}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;i<this._targetedAnimations.length;i++){const n=this._targetedAnimations[i].animation.getKeys(),s=n[0],r=n[n.length-1];if(s.frame>e){const t={frame:e,value:s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation};n.splice(0,0,t)}if(r.frame<t){const e={frame:t,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};n.push(e)}}return this._from=e,this._to=t,this}_processLoop(e,t,i){e.onAnimationLoop=()=>{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._targetedAnimations.length&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,n,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let r=0;r<this._targetedAnimations.length;r++){const o=this._targetedAnimations[r],a=this._scene.beginDirectAnimation(o.target,[o.animation],void 0!==i?i:this._from,void 0!==n?n:this._to,e,t,void 0,void 0,void 0!==s?s:this._isAdditive);a.onAnimationEnd=()=>{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(a)},this._processLoop(a,o,r),this._animatables.push(a)}return this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e<this._animatables.length;e++)this._animatables[e].pause();return this.onAnimationGroupPauseObservable.notifyObservers(this),this}play(e){return this.isStarted&&this._animatables.length===this._targetedAnimations.length?(void 0!==e&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this._isPaused=!1,this}reset(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(),this;for(let e=0;e<this._animatables.length;e++)this._animatables[e].reset();return this}restart(){if(!this._isStarted)return this;for(let e=0;e<this._animatables.length;e++)this._animatables[e].restart();return this.onAnimationGroupPlayObservable.notifyObservers(this),this}stop(){if(!this._isStarted)return this;const e=this._animatables.slice();for(let t=0;t<e.length;t++)e[t].stop(void 0,void 0,!0);let t=0;for(let e=0;e<this._scene._activeAnimatables.length;e++){const i=this._scene._activeAnimatables[e];i._runtimeAnimations.length>0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t<this._animatables.length;t++)this._animatables[t].weight=e;return this}syncAllAnimationsWith(e){for(let t=0;t<this._animatables.length;t++)this._animatables[t].syncWith(e);return this}goToFrame(e){if(!this._isStarted)return this;for(let t=0;t<this._animatables.length;t++)this._animatables[t].goToFrame(e);return this}dispose(){this._targetedAnimations.length=0,this._animatables.length=0;const e=this._scene.animationGroups.indexOf(this);if(e>-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,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),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const n=new l(e||this.name,this._scene);for(const e of this._targetedAnimations)n.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return n}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.targetedAnimations=[];for(let t=0;t<this.targetedAnimations.length;t++){const i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return o.$&&o.$.HasTags(this)&&(e.tags=o.$.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e}static Parse(e,t){const i=new l(e.name,t);for(let s=0;s<e.targetedAnimations.length;s++){const r=e.targetedAnimations[s],o=n.f.Parse(r.animation),a=r.targetId;if("influence"===r.animation.property){const e=t.getMorphTargetById(a);e&&i.addTargetedAnimation(o,e)}else{const e=t.getNodeById(a);null!=e&&i.addTargetedAnimation(o,e)}}return null!==e.from&&null!==e.to&&i.normalize(e.from,e.to),o.$&&o.$.AddTagsTo(i,e.tags),void 0!==e.metadata&&(i.metadata=e.metadata),i}static MakeAnimationAdditive(e,t=0,i,s=!1,r){let o=e;s&&(o=e.clone(r||o.name));const a=o.targetedAnimations;for(let e=0;e<a.length;e++){const s=a[e];n.f.MakeAnimationAdditive(s.animation,t,i)}return o.isAdditive=!0,o}getClassName(){return"AnimationGroup"}toString(e){let t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from,t+=", to: "+this._to,t+=", isStarted: "+this._isStarted,t+=", speedRatio: "+this._speedRatio,t+=", targetedAnimations length: "+this._targetedAnimations.length,t+=", animatables length: "+this._animatables),t}}},4173:(e,t,i)=>{var n;i.d(t,{N:()=>n}),function(e){e[e.NONE=0]="NONE",e[e.STEP=1]="STEP"}(n||(n={}))},2695:(e,t,i)=>{i.d(t,{X:()=>n});class n{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new n(this.name,this.from,this.to)}}},3642:(e,t,i)=>{i.d(t,{$:()=>c});var n=i(7257),s=i(5757),r=i(4141),o=i(7814),a=i(2722),l=i(4934),h=i(1431);class c{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((null===(e=o.D.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:o.D.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){var t;this._spatialSound=e,this._spatialSound&&(null===(t=o.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&o.D.audioEngine.audioContext&&this._createSpatialParameters()}constructor(e,t,i,l=null,u){var d,p,f,_,m;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 s.y$,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=r.P.Zero(),this._localDirection=new r.P(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||h.l.LastCreatedScene)if(this._scene=i,c._SceneComponentInitialization(i),this._readyToPlayCallback=l,this._customAttenuationFunction=(e,t,i,n,s)=>t<i?e*(1-t/i):0,u&&(this.autoplay=u.autoplay||!1,this._loop=u.loop||!1,void 0!==u.volume&&(this._volume=u.volume),this._spatialSound=null!==(d=u.spatialSound)&&void 0!==d&&d,this.maxDistance=null!==(p=u.maxDistance)&&void 0!==p?p:100,this.useCustomAttenuation=null!==(f=u.useCustomAttenuation)&&void 0!==f&&f,this.rolloffFactor=u.rolloffFactor||1,this.refDistance=u.refDistance||1,this.distanceModel=u.distanceModel||"linear",this._playbackRate=u.playbackRate||1,this._streaming=null!==(_=u.streaming)&&void 0!==_&&_,this._length=u.length,this._offset=u.offset),(null===(m=o.D.audioEngine)||void 0===m?void 0:m.canUseWebAudio)&&o.D.audioEngine.audioContext){this._soundGain=o.D.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._outputAudioNode=this._soundGain,this._spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.addSound(this);let e=!0;if(t)try{"string"==typeof t?this._urlType="String":t instanceof ArrayBuffer?this._urlType="ArrayBuffer":t instanceof HTMLMediaElement?this._urlType="MediaElement":t instanceof MediaStream?this._urlType="MediaStream":t instanceof AudioBuffer?this._urlType="AudioBuffer":Array.isArray(t)&&(this._urlType="Array");let i=[],s=!1;switch(this._urlType){case"MediaElement":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=o.D.audioEngine.audioContext.createMediaElementSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"MediaStream":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=o.D.audioEngine.audioContext.createMediaStreamSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"ArrayBuffer":t.byteLength>0&&(s=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e<i.length;e++){const t=i[e];if(s=u&&u.skipCodecCheck||-1!==t.indexOf(".mp3",t.length-4)&&o.D.audioEngine.isMP3supported||-1!==t.indexOf(".ogg",t.length-4)&&o.D.audioEngine.isOGGsupported||-1!==t.indexOf(".wav",t.length-4)||-1!==t.indexOf(".m4a",t.length-4)||-1!==t.indexOf(".mp4",t.length-4)||-1!==t.indexOf("blob:"),s){this._streaming?(this._htmlAudioElement=new Audio(t),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,n.w1.SetCorsBehavior(t,this._htmlAudioElement),this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",(()=>{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&a.Y.Error("XHR "+e.status+" error on: "+t+"."),a.Y.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?s||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):a.Y.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){a.Y.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),o.D.audioEngine&&!o.D.audioEngine.WarnedWebAudioUnsupported&&(a.Y.Error("Web Audio is not supported by your browser."),o.D.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){var e;(null===(e=o.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?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))}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){var t;(null===(t=o.D.audioEngine)||void 0===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;(null===(t=o.D.audioEngine)||void 0===t?void 0:t.audioContext)&&o.D.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{a.Y.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){var t;(null===(t=o.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,n,s,r,o,a,l,h,c;e&&(this.loop=null!==(t=e.loop)&&void 0!==t?t:this.loop,this.maxDistance=null!==(i=e.maxDistance)&&void 0!==i?i:this.maxDistance,this.useCustomAttenuation=null!==(n=e.useCustomAttenuation)&&void 0!==n?n:this.useCustomAttenuation,this.rolloffFactor=null!==(s=e.rolloffFactor)&&void 0!==s?s:this.rolloffFactor,this.refDistance=null!==(r=e.refDistance)&&void 0!==r?r:this.refDistance,this.distanceModel=null!==(o=e.distanceModel)&&void 0!==o?o:this.distanceModel,this._playbackRate=null!==(a=e.playbackRate)&&void 0!==a?a:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this._setOffset(null!==(h=e.offset)&&void 0!==h?h:void 0),this.setVolume(null!==(c=e.volume)&&void 0!==c?c: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),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))}_createSpatialParameters(){var e,t;(null===(e=o.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&o.D.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:o.D.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_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))}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){var e;(null===(e=o.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(null===(t=o.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t<e?a.Y.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."):(this._coneInnerAngle=e,this._coneOuterAngle=t,this._coneOuterGain=i,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length)))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){var t;if(e!=this._coneInnerAngle){if(this._coneOuterAngle<e)return void a.Y.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e,(null===(t=o.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle)}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){var t;if(e!=this._coneOuterAngle){if(e<this._coneInnerAngle)return void a.Y.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e,(null===(t=o.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneOuterAngle=this._coneOuterAngle)}}setPosition(e){var t;e.equals(this._position)||(this._position.copyFrom(e),(null===(t=o.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z))}setLocalDirectionToMesh(e){var t;this._localDirection=e,(null===(t=o.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._connectedTransformNode&&this.isPlaying&&this._updateDirection()}_updateDirection(){if(!this._connectedTransformNode||!this._soundPanner)return;const e=this._connectedTransformNode.getWorldMatrix(),t=r.P.TransformNormal(this._localDirection,e);t.normalize(),this._soundPanner.orientationX.value=t.x,this._soundPanner.orientationY.value=t.y,this._soundPanner.orientationZ.value=t.z}updateDistanceFromListener(){var e;if((null===(e=o.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._connectedTransformNode&&this.useCustomAttenuation&&this._soundGain&&this._scene.activeCamera){const e=this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,e,this.maxDistance,this.refDistance,this.rolloffFactor)}}setAttenuationFunction(e){this._customAttenuationFunction=e}play(e,t,i){var n,s,r,l;if(this._isReadyToPlay&&this._scene.audioEnabled&&(null===(n=o.D.audioEngine)||void 0===n?void 0:n.audioContext))try{let n=e?(null===(s=o.D.audioEngine)||void 0===s?void 0:s.audioContext.currentTime)+e:null===(r=o.D.audioEngine)||void 0===r?void 0:r.audioContext.currentTime;if(this._soundSource&&this._streamingSource||this._spatialSound&&this._soundPanner&&(isNaN(this._position.x)||isNaN(this._position.y)||isNaN(this._position.z)||(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedTransformNode?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming){if(this._streamingSource||(this._streamingSource=o.D.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=()=>{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{var t,i;if(null===(t=o.D.audioEngine)||void 0===t?void 0:t.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{var t,i;null===(t=o.D.audioEngine)||void 0===t||t.lock(),(this.loop||this.autoplay)&&(null===(i=o.D.audioEngine)||void 0===i||i.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(null===(i=o.D.audioEngine)||void 0===i||i.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const s=()=>{var s,r,a,l;if(null===(s=o.D.audioEngine)||void 0===s?void 0:s.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){const e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=null===(r=o.D.audioEngine)||void 0===r?void 0:r.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},n=e?(null===(a=o.D.audioEngine)||void 0===a?void 0:a.audioContext.currentTime)+e:o.D.audioEngine.audioContext.currentTime;const s=((this.isPaused?this.currentTime:0)+(null!==(l=this._offset)&&void 0!==l?l:0))%this._soundSource.buffer.duration;this._soundSource.start(n,s,this.loop?void 0:i)}}};"suspended"===(null===(l=o.D.audioEngine)||void 0===l?void 0:l.audioContext.state)?setTimeout((()=>{var e;"suspended"===(null===(e=o.D.audioEngine)||void 0===e?void 0:e.audioContext.state)?(o.D.audioEngine.lock(),(this.loop||this.autoplay)&&o.D.audioEngine.onAudioUnlockedObservable.addOnce((()=>{s()}))):s()}),500):s()}this._startTime=n,this.isPlaying=!0,this.isPaused=!1}catch(e){a.Y.Error("Error while trying to play audio: "+this.name+", "+e.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._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if((null===(t=o.D.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){const t=e?o.D.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(t)}}else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=o.D.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=o.D.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(null===(i=o.D.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&o.D.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(o.D.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,o.D.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,o.D.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=e=>this._onRegisterAfterWorldMatrixUpdate(e),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){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=o.D.audioEngine)||void 0===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 c(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.name,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,n){const s=e.name;let o;o=e.url?i+e.url:i+s;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(n){const e=()=>{n._isReadyToPlay?(l._audioBuffer=n.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play(0,l._offset,l._length)):setTimeout(e,300)};l=new c(s,new ArrayBuffer(0),t,null,a),e()}else l=new c(s,o,t,(()=>{t.removePendingData(l)}),a),t.addPendingData(l);if(e.position){const t=r.P.FromArray(e.position);l.setPosition(t)}if(e.isDirectional&&(l.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=r.P.FromArray(e.localDirectionToMesh);l.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&l.attachToMesh(i)}return e.metadata&&(l.metadata=e.metadata),l}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}}c._SceneComponentInitialization=e=>{throw(0,l.S)("AudioSceneComponent")}},710:(e,t,i)=>{i.d(t,{s:()=>s});var n=i(2722);class s{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let n=0;for(const e of i)n+=e;const s=n>0?1/n:0;for(let e=0;e<this._weights.length;e++)this._weights[e]*=s;this._sounds=t;for(const e of this._sounds)e.onEndedObservable.add((()=>{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAngle<e)return void n.Y.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e;for(const t of this._sounds)t.directionalConeInnerAngle=e}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){if(e!==this._coneOuterAngle){if(e<this._coneInnerAngle)return void n.Y.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e;for(const t of this._sounds)t.directionalConeOuterAngle=e}}get volume(){return this._volume}set volume(e){if(e!==this._volume)for(const t of this._sounds)t.setVolume(e)}_onended(){void 0!==this._currentIndex&&(this._sounds[this._currentIndex].autoplay=!1),this.loop&&this.isPlaying?this.play():this.isPlaying=!1}pause(){this.isPaused=!0,void 0!==this._currentIndex&&this._sounds[this._currentIndex].pause()}stop(){this.isPlaying=!1,void 0!==this._currentIndex&&this._sounds[this._currentIndex].stop()}play(e){if(!this.isPaused){this.stop();const e=Math.random();let t=0;for(let i=0;i<this._weights.length;i++)if(t+=this._weights[i],e<=t){this._currentIndex=i;break}}const t=this._sounds[this._currentIndex];t.isReady()?t.play(0,this.isPaused?void 0:e):t.autoplay=!0,this.isPlaying=!0,this.isPaused=!1}}},6981:(e,t,i)=>{i.d(t,{N:()=>h});var n=i(1795),s=i(1057),r=i(1903),o=i(4141),a=i(5757),l=i(2704);class h{constructor(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new o.P,this._tmpQuaternion=new o._f,this._dragType={NONE:0,DRAG:1,DRAG_WITH_CONTROLLER:2,NEAR_DRAG:3},this._moving=!1,this._dragging=this._dragType.NONE,this.draggableMeshes=null,this.zDragFactor=3,this.currentDraggingPointerIds=[],this.detachCameraControls=!0,this.onDragStartObservable=new a.y$,this.onDragObservable=new a.y$,this.onDragEndObservable=new a.y$,this.allowMultiPointer=!0}get currentDraggingPointerId(){return void 0!==this.currentDraggingPointerIds[0]?this.currentDraggingPointerIds[0]:-1}set currentDraggingPointerId(e){this.currentDraggingPointerIds[0]=e}get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}get name(){return"BaseSixDofDrag"}get isMoving(){return this._moving}init(){}get _pointerCamera(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera}_createVirtualMeshInfo(){const e=new n.x("",h._virtualScene);e.rotationQuaternion=new o._f;const t=new n.x("",h._virtualScene);t.rotationQuaternion=new o._f;const i=new n.x("",h._virtualScene);return i.rotationQuaternion=new o._f,{dragging:!1,moving:!1,dragMesh:e,originMesh:t,pivotMesh:i,startingPivotPosition:new o.P,startingPivotOrientation:new o._f,startingPosition:new o.P,startingOrientation:new o._f,lastOriginPosition:new o.P,lastDragPosition:new o.P}}_resetVirtualMeshesPosition(){for(let e=0;e<this.currentDraggingPointerIds.length;e++)this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.rotationQuaternion),this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingPivotPosition.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.position),this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingPivotOrientation.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.rotationQuaternion),this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingPosition.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].dragMesh.position),this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingOrientation.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].dragMesh.rotationQuaternion)}_pointerUpdate2D(e,t,i){!this._pointerCamera||this._pointerCamera.cameraRigMode!=l.V.RIG_MODE_NONE||this._pointerCamera._isLeftCamera||this._pointerCamera._isRightCamera||(e.origin.copyFrom(this._pointerCamera.globalPosition),i=0);const n=this._virtualMeshesInfo[t],s=o.jp.Vector3[0];e.origin.subtractToRef(n.lastOriginPosition,s),n.lastOriginPosition.copyFrom(e.origin);const r=-o.P.Dot(s,e.direction);n.originMesh.addChild(n.dragMesh),n.originMesh.addChild(n.pivotMesh),this._applyZOffset(n.dragMesh,r,i),this._applyZOffset(n.pivotMesh,r,i),n.originMesh.position.copyFrom(e.origin);const a=o.jp.Vector3[0];e.origin.addToRef(e.direction,a),n.originMesh.lookAt(a),n.originMesh.removeChild(n.dragMesh),n.originMesh.removeChild(n.pivotMesh)}_pointerUpdateXR(e,t,i,n){const s=this._virtualMeshesInfo[i];if(s.originMesh.position.copyFrom(e.position),this._dragging===this._dragType.NEAR_DRAG&&t?s.originMesh.rotationQuaternion.copyFrom(t.rotationQuaternion):s.originMesh.rotationQuaternion.copyFrom(e.rotationQuaternion),s.pivotMesh.computeWorldMatrix(!0),s.dragMesh.computeWorldMatrix(!0),0!==n){const e=o.jp.Vector3[0],t=o.jp.Vector3[1];e.copyFrom(this._pointerCamera.getForwardRay().direction),s.originMesh.position.subtractToRef(s.lastOriginPosition,t),s.lastOriginPosition.copyFrom(s.originMesh.position);const i=t.length();t.normalize();const r=o.jp.Vector3[2],a=o.jp.Vector3[3];s.dragMesh.absolutePosition.subtractToRef(this._pointerCamera.globalPosition,r),s.dragMesh.absolutePosition.subtractToRef(s.originMesh.position,a);const l=a.length();r.normalize(),a.normalize();let h=Math.abs(o.P.Dot(t,a))*o.P.Dot(t,e)*n*i*l;const c=.01;h<0&&c-l>h&&(h=Math.min(c-l,0)),a.scaleInPlace(h),a.addToRef(s.pivotMesh.absolutePosition,this._tmpVector),s.pivotMesh.setAbsolutePosition(this._tmpVector),a.addToRef(s.dragMesh.absolutePosition,this._tmpVector),s.dragMesh.setAbsolutePosition(this._tmpVector)}}attach(e){this._ownerNode=e,this._scene=this._ownerNode.getScene(),h._virtualScene||(h._virtualScene=new s.x(this._scene.getEngine(),{virtual:!0}),h._virtualScene.detachControl());const t=e=>this._ownerNode===e||e.isDescendantOf(this._ownerNode)&&(!this.draggableMeshes||-1!==this.draggableMeshes.indexOf(e));this._pointerObserver=this._scene.onPointerObservable.add((e=>{const i=e.event.pointerId;this._virtualMeshesInfo[i]||(this._virtualMeshesInfo[i]=this._createVirtualMeshInfo());const n=this._virtualMeshesInfo[i],s="xr-near"===e.event.pointerType;if(e.type==r.kD.POINTERDOWN){if(!n.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&(!s||e.pickInfo.aimTransform)&&t(e.pickInfo.pickedMesh)){if(!this.allowMultiPointer&&this.currentDraggingPointerIds.length>0)return;!this._pointerCamera||this._pointerCamera.cameraRigMode!==l.V.RIG_MODE_NONE||this._pointerCamera._isLeftCamera||this._pointerCamera._isRightCamera||e.pickInfo.ray.origin.copyFrom(this._pointerCamera.globalPosition),this._ownerNode.computeWorldMatrix(!0);const t=this._virtualMeshesInfo[i];s?(this._dragging=e.pickInfo.originMesh?this._dragType.NEAR_DRAG:this._dragType.DRAG_WITH_CONTROLLER,t.originMesh.position.copyFrom(e.pickInfo.aimTransform.position),this._dragging===this._dragType.NEAR_DRAG&&e.pickInfo.gripTransform?t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.gripTransform.rotationQuaternion):t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.aimTransform.rotationQuaternion)):(this._dragging=this._dragType.DRAG,t.originMesh.position.copyFrom(e.pickInfo.ray.origin)),t.lastOriginPosition.copyFrom(t.originMesh.position),t.dragMesh.position.copyFrom(e.pickInfo.pickedPoint),t.lastDragPosition.copyFrom(e.pickInfo.pickedPoint),t.pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),t.pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),t.startingPosition.copyFrom(t.dragMesh.position),t.startingPivotPosition.copyFrom(t.pivotMesh.position),t.startingOrientation.copyFrom(t.dragMesh.rotationQuaternion),t.startingPivotOrientation.copyFrom(t.pivotMesh.rotationQuaternion),s?(t.originMesh.addChild(t.dragMesh),t.originMesh.addChild(t.pivotMesh)):t.originMesh.lookAt(t.dragMesh.position),t.dragging=!0,-1===this.currentDraggingPointerIds.indexOf(i)&&this.currentDraggingPointerIds.push(i),this.detachCameraControls&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.inputs&&this._pointerCamera.inputs.attachedToElement?(this._pointerCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1),this._targetDragStart(t.pivotMesh.position,t.pivotMesh.rotationQuaternion,i),this.onDragStartObservable.notifyObservers({position:t.pivotMesh.position})}}else if(e.type==r.kD.POINTERUP||e.type==r.kD.POINTERDOUBLETAP){const e=this.currentDraggingPointerIds.indexOf(i);n.dragging=!1,-1!==e&&(this.currentDraggingPointerIds.splice(e,1),0===this.currentDraggingPointerIds.length&&(this._moving=!1,this._dragging=this._dragType.NONE,this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1)),n.originMesh.removeChild(n.dragMesh),n.originMesh.removeChild(n.pivotMesh),this._targetDragEnd(i),this.onDragEndObservable.notifyObservers({}))}else if(e.type==r.kD.POINTERMOVE&&-1!==this.currentDraggingPointerIds.indexOf(i)&&n.dragging&&e.pickInfo&&(e.pickInfo.ray||e.pickInfo.aimTransform)){let t=this.zDragFactor;(this.currentDraggingPointerIds.length>1||e.pickInfo.originMesh)&&(t=0),this._ownerNode.computeWorldMatrix(!0),s?this._pointerUpdateXR(e.pickInfo.aimTransform,e.pickInfo.gripTransform,i,t):this._pointerUpdate2D(e.pickInfo.ray,i,t),this._tmpQuaternion.copyFrom(n.startingPivotOrientation),this._tmpQuaternion.x=-this._tmpQuaternion.x,this._tmpQuaternion.y=-this._tmpQuaternion.y,this._tmpQuaternion.z=-this._tmpQuaternion.z,n.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion,this._tmpQuaternion),n.pivotMesh.absolutePosition.subtractToRef(n.startingPivotPosition,this._tmpVector),this.onDragObservable.notifyObservers({delta:this._tmpVector,position:n.pivotMesh.position,pickInfo:e.pickInfo}),this._targetDrag(this._tmpVector,this._tmpQuaternion,i),n.lastDragPosition.copyFrom(n.dragMesh.absolutePosition),this._moving=!0}}))}_applyZOffset(e,t,i){e.position.z-=e.position.z<1?t*i:t*i*e.position.z,e.position.z<0&&(e.position.z=0)}_targetDragStart(e,t,i){}_targetDrag(e,t,i){}_targetDragEnd(e){}_reattachCameraControls(){if(this._pointerCamera)if("ArcRotateCamera"===this._pointerCamera.getClassName()){const e=this._pointerCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._pointerCamera.attachControl(!this._pointerCamera.inputs||this._pointerCamera.inputs.noPreventDefault)}detach(){this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver));for(const e in this._virtualMeshesInfo)this._virtualMeshesInfo[e].originMesh.dispose(),this._virtualMeshesInfo[e].dragMesh.dispose();this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()}}},1809:(e,t,i)=>{i.d(t,{Y:()=>n});class n{get delay(){return this.fadeInDelay}set delay(e){this.fadeInDelay=e,this.fadeOutDelay=e}constructor(){this.fadeInDelay=0,this.fadeOutDelay=0,this.fadeInTime=300,this.fadeOutTime=300,this._millisecondsPerFrame=1e3/60,this._hovered=!1,this._hoverValue=0,this._ownerNode=null,this._delay=0,this._time=300,this._update=()=>{if(this._ownerNode){if(this._hoverValue+=this._hovered?this._millisecondsPerFrame:-this._millisecondsPerFrame,this._setAllVisibility(this._ownerNode,(this._hoverValue-this._delay)/this._time),this._ownerNode.visibility>1){if(this._setAllVisibility(this._ownerNode,1),this._hoverValue>this._time)return this._hoverValue=this._time,void this._detachObserver()}else if(this._ownerNode.visibility<0&&(this._setAllVisibility(this._ownerNode,0),this._hoverValue<0))return this._hoverValue=0,void this._detachObserver();this._attachObserver()}}}get name(){return"FadeInOut"}init(){}attach(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)}detach(){this._ownerNode=null}fadeIn(e=!0){this._delay=e?this.fadeInDelay:this.fadeOutDelay,this._time=e?this.fadeInTime:this.fadeOutTime,this._detachObserver(),this._ownerNode&&(e&&this._ownerNode.visibility>=1||!e&&this._ownerNode.visibility<=0)||(this._hovered=e,this._hovered||(this._delay*=-1),this._ownerNode.visibility>=1?this._hoverValue=this._time:this._ownerNode.visibility<=0&&(this._hoverValue=0),this._update())}fadeOut(){this.fadeIn(!1)}_setAllVisibility(e,t){e.visibility=t,e.getChildMeshes().forEach((e=>{this._setAllVisibility(e,t)}))}_attachObserver(){var e;this._onBeforeRenderObserver||(this._onBeforeRenderObserver=null===(e=this._ownerNode)||void 0===e?void 0:e.getScene().onBeforeRenderObservable.add(this._update))}_detachObserver(){var e;this._onBeforeRenderObserver&&(null===(e=this._ownerNode)||void 0===e||e.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)}}},4095:(e,t,i)=>{i.d(t,{j:()=>o});var n=i(4141),s=i(1128),r=i(1341);class o{constructor(){this._tmpQuaternion=new n._f,this._tmpVectors=[new n.P,new n.P,new n.P,new n.P,new n.P,new n.P,new n.P],this._tmpMatrix=new n.y3,this._tmpInvertView=new n.y3,this._tmpForward=new n.P,this._tmpNodeForward=new n.P,this._tmpPosition=new n.P,this._workingPosition=new n.P,this._workingQuaternion=new n._f,this._lastTick=-1,this._recenterNextUpdate=!0,this.interpolatePose=!0,this.lerpTime=500,this.ignoreCameraPitchAndRoll=!1,this.pitchOffset=15,this.maxViewVerticalDegrees=30,this.maxViewHorizontalDegrees=30,this.orientToCameraDeadzoneDegrees=60,this.ignoreDistanceClamp=!1,this.ignoreAngleClamp=!1,this.verticalMaxDistance=0,this.defaultDistance=.8,this.maximumDistance=2,this.minimumDistance=.3,this.useFixedVerticalOffset=!1,this.fixedVerticalOffset=0,this._enabled=!0}get followedCamera(){return this._followedCamera||this._scene.activeCamera}set followedCamera(e){this._followedCamera=e}get name(){return"Follow"}init(){}attach(e,t){this._scene=e.getScene(),this.attachedNode=e,t&&(this.followedCamera=t),this._addObservables()}detach(){this.attachedNode=null,this._removeObservables()}recenter(){this._recenterNextUpdate=!0}_angleBetweenVectorAndPlane(e,t){return this._tmpVectors[0].copyFrom(e),e=this._tmpVectors[0],this._tmpVectors[1].copyFrom(t),t=this._tmpVectors[1],e.normalize(),t.normalize(),Math.PI/2-Math.acos(n.P.Dot(e,t))}_length2D(e){return Math.sqrt(e.x*e.x+e.z*e.z)}_distanceClamp(e,t=!1){let i=this.minimumDistance,n=this.maximumDistance;const r=this.defaultDistance,o=this._tmpVectors[0];o.copyFrom(e);let a=o.length();if(o.normalizeFromLength(a),this.ignoreCameraPitchAndRoll){i=this._length2D(o)*i,n=this._length2D(o)*n;const t=this._length2D(e);o.scaleInPlace(a/t),a=t}let l=a;return l=t?r:s.R.Clamp(a,i,n),e.copyFrom(o).scaleInPlace(l),a!==l}_applyVerticalClamp(e){0!==this.verticalMaxDistance&&(e.y=s.R.Clamp(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))}_toOrientationQuatToRef(e,t){n._f.RotationYawPitchRollToRef(Math.atan2(e.x,e.z),Math.atan2(e.y,Math.sqrt(e.z*e.z+e.x*e.x)),0,t)}_applyPitchOffset(e){const t=this._tmpVectors[0],i=this._tmpVectors[1];t.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),i.copyFromFloats(1,0,0),n.P.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),n.P.TransformNormalToRef(i,e,i),n._f.RotationAxisToRef(i,this.pitchOffset*Math.PI/180,this._tmpQuaternion),t.rotateByQuaternionToRef(this._tmpQuaternion,t),this._toOrientationQuatToRef(t,this._tmpQuaternion),this._tmpQuaternion.toRotationMatrix(this._tmpMatrix),e.copyFrom(this._tmpMatrix)}_angularClamp(e,t){const i=this._tmpVectors[5];i.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1);const s=this._tmpVectors[6];s.copyFromFloats(1,0,0),n.P.TransformNormalToRef(i,e,i),n.P.TransformNormalToRef(s,e,s);const o=n.P.UpReadOnly;if(t.length()<r.kn)return!1;let a=!1;const l=this._tmpQuaternion;if(this.ignoreCameraPitchAndRoll){const e=n.P.GetAngleBetweenVectorsOnPlane(t,i,s);n._f.RotationAxisToRef(s,e,l),t.rotateByQuaternionToRef(l,t)}else{const e=-n.P.GetAngleBetweenVectorsOnPlane(t,i,s),r=this.maxViewVerticalDegrees*Math.PI/180*.5;e<-r?(n._f.RotationAxisToRef(s,-e-r,l),t.rotateByQuaternionToRef(l,t),a=!0):e>r&&(n._f.RotationAxisToRef(s,-e+r,l),t.rotateByQuaternionToRef(l,t),a=!0)}const h=this._angleBetweenVectorAndPlane(t,s)*(this._scene.useRightHandedSystem?-1:1),c=this.maxViewHorizontalDegrees*Math.PI/180*.5;return h<-c?(n._f.RotationAxisToRef(o,-h-c,l),t.rotateByQuaternionToRef(l,t),a=!0):h>c&&(n._f.RotationAxisToRef(o,-h+c,l),t.rotateByQuaternionToRef(l,t),a=!0),a}_orientationClamp(e,t){var i;const s=this._tmpVectors[0];s.copyFrom(e).scaleInPlace(-1).normalize();const o=this._tmpVectors[1],a=this._tmpVectors[2];o.copyFromFloats(0,1,0),n.P.CrossToRef(s,o,a);const l=a.length();l<r.kn||(a.normalizeFromLength(l),n.P.CrossToRef(a,s,o),(null===(i=this.attachedNode)||void 0===i?void 0:i.getScene().useRightHandedSystem)?n._f.FromLookDirectionRHToRef(s,o,t):n._f.FromLookDirectionLHToRef(s,o,t))}_passedOrientationDeadzone(e,t){const i=this._tmpVectors[5];return i.copyFrom(e),i.normalize(),180*Math.abs(n.P.GetAngleBetweenVectorsOnPlane(t,i,n.P.UpReadOnly))/Math.PI>this.orientToCameraDeadzoneDegrees}_updateLeashing(e){if(this.attachedNode&&this._enabled){const t=this.attachedNode.parent;this.attachedNode.setParent(null);const i=this.attachedNode.getWorldMatrix(),s=this._workingPosition,r=this._workingQuaternion,o=this.attachedNode.getPivotPoint(),a=this._tmpInvertView;a.copyFrom(e.getViewMatrix()),a.invert(),n.P.TransformCoordinatesToRef(o,i,s);const l=this._tmpPosition;l.copyFromFloats(0,0,0),n.P.TransformCoordinatesToRef(l,i,l),l.scaleInPlace(-1).subtractInPlace(o),s.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(a);let h=!1;const c=this._tmpForward;c.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),n.P.TransformNormalToRef(c,a,c);const u=this._tmpNodeForward;if(u.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),n.P.TransformNormalToRef(u,i,u),this._recenterNextUpdate)s.copyFrom(c).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){const e=s.length();s.copyFrom(c).scaleInPlace(e)}else h=this._angularClamp(a,s);let d=!1;this.ignoreDistanceClamp||(d=this._distanceClamp(s,h),this._applyVerticalClamp(s)),this.useFixedVerticalOffset&&(s.y=l.y-e.globalPosition.y+this.fixedVerticalOffset),(h||d||this._passedOrientationDeadzone(s,u)||this._recenterNextUpdate)&&this._orientationClamp(s,r),this._workingPosition.subtractInPlace(o),this._recenterNextUpdate=!1,this.attachedNode.setParent(t)}}_updateTransformToGoal(e){if(!this.attachedNode||!this.followedCamera||!this._enabled)return;this.attachedNode.rotationQuaternion||(this.attachedNode.rotationQuaternion=n._f.Identity());const t=this.attachedNode.parent;if(this.attachedNode.setParent(null),!this.interpolatePose)return this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition),void this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion);const i=new n.P;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),n.P.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);const s=new n._f;s.copyFrom(this.attachedNode.rotationQuaternion),n._f.SmoothToRef(s,this._workingQuaternion,e,this.lerpTime,this.attachedNode.rotationQuaternion),this.attachedNode.setParent(t)}_addObservables(){this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{if(!this.followedCamera)return;const e=Date.now();this._updateLeashing(this.followedCamera),this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._onBeforeRender&&this._scene.onBeforeRenderObservable.remove(this._onBeforeRender)}}},4184:(e,t,i)=>{i.d(t,{$6:()=>n,bH:()=>r,q_:()=>c,rX:()=>s});var n,s,r,o=i(4370),a=i(9596),l=i(4141),h=i(7257);!function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(n||(n={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(s||(s={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(r||(r={}));class c{constructor(){this._sceneRenderObserver=null,this._zoneAxis={},this.handConstraintVisibility=r.PALM_AND_GAZE,this.palmUpStrictness=.95,this.gazeProximityRadius=.15,this.targetOffset=.1,this.targetZone=n.ULNAR_SIDE,this.zoneOrientationMode=s.HAND_ROTATION,this.nodeOrientationMode=s.HAND_ROTATION,this.handedness="none",this.lerpTime=100,this._zoneAxis[n.ABOVE_FINGER_TIPS]=new l.P(0,1,0),this._zoneAxis[n.RADIAL_SIDE]=new l.P(-1,0,0),this._zoneAxis[n.ULNAR_SIDE]=new l.P(1,0,0),this._zoneAxis[n.BELOW_WRIST]=new l.P(0,-1,0)}get name(){return"HandConstraint"}enable(){this._node.setEnabled(!0)}disable(){this._node.setEnabled(!1)}_getHandPose(){if(!this._handTracking)return null;let e;if(e="none"===this.handedness?this._handTracking.getHandByHandedness("left")||this._handTracking.getHandByHandedness("right"):this._handTracking.getHandByHandedness(this.handedness),e){const t=e.getJointMesh(a.fL.PINKY_FINGER_METACARPAL),i=e.getJointMesh(a.fL.MIDDLE_FINGER_METACARPAL),n=e.getJointMesh(a.fL.WRIST);if(n&&i&&t){const s={position:i.absolutePosition,quaternion:new l._f,id:e.xrController.uniqueId},r=l.jp.Vector3[0],o=l.jp.Vector3[1],a=l.jp.Vector3[2];return r.copyFrom(i.absolutePosition).subtractInPlace(n.absolutePosition).normalize(),o.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),l.P.CrossToRef(r,o,o),l.P.CrossToRef(o,r,a),l._f.FromLookDirectionLHToRef(o,r,s.quaternion),s}}return null}init(){}attach(e){this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=l._f.RotationYawPitchRoll(this._node.rotation.y,this._node.rotation.x,this._node.rotation.z));let t=Date.now();this._sceneRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{const e=this._getHandPose();if(this._node.reservedDataStore=this._node.reservedDataStore||{},this._node.reservedDataStore.nearInteraction=this._node.reservedDataStore.nearInteraction||{},this._node.reservedDataStore.nearInteraction.excludedControllerId=null,e){const i=l.jp.Vector3[0],n=this._scene.activeCamera;i.copyFrom(this._zoneAxis[this.targetZone]);const r=l.jp.Quaternion[0];if(n&&(this.zoneOrientationMode===s.LOOK_AT_CAMERA||this.nodeOrientationMode===s.LOOK_AT_CAMERA)){const t=l.jp.Vector3[1];t.copyFrom(n.position).subtractInPlace(e.position).normalize(),this._scene.useRightHandedSystem?l._f.FromLookDirectionRHToRef(t,l.P.UpReadOnly,r):l._f.FromLookDirectionLHToRef(t,l.P.UpReadOnly,r)}this.zoneOrientationMode===s.HAND_ROTATION?e.quaternion.toRotationMatrix(l.jp.Matrix[0]):r.toRotationMatrix(l.jp.Matrix[0]),l.P.TransformNormalToRef(i,l.jp.Matrix[0],i),i.scaleInPlace(this.targetOffset);const o=l.jp.Vector3[2],a=l.jp.Quaternion[1];o.copyFrom(e.position).addInPlace(i),this.nodeOrientationMode===s.HAND_ROTATION?a.copyFrom(e.quaternion):a.copyFrom(r);const h=Date.now()-t;l.P.SmoothToRef(this._node.position,o,h,this.lerpTime,this._node.position),l._f.SmoothToRef(this._node.rotationQuaternion,a,h,this.lerpTime,this._node.rotationQuaternion),this._node.reservedDataStore.nearInteraction.excludedControllerId=e.id}this._setVisibility(e),t=Date.now()}))}_setVisibility(e){let t=!0,i=!0;const n=this._scene.activeCamera;if(n){const s=n.getForwardRay();if(this.handConstraintVisibility===r.GAZE_FOCUS||this.handConstraintVisibility===r.PALM_AND_GAZE){let t;i=!1,this._eyeTracking&&(t=this._eyeTracking.getEyeGaze()),t=t||s;const n=l.jp.Vector3[0];e?e.position.subtractToRef(t.origin,n):this._node.getAbsolutePosition().subtractToRef(t.origin,n);const r=l.P.Dot(n,t.direction),o=r*r;r>0&&n.lengthSquared()-o<this.gazeProximityRadius*this.gazeProximityRadius&&(i=!0)}if((this.handConstraintVisibility===r.PALM_UP||this.handConstraintVisibility===r.PALM_AND_GAZE)&&(t=!1,e)){const i=l.jp.Vector3[0];l.P.LeftHandedForwardReadOnly.rotateByQuaternionToRef(e.quaternion,i),l.P.Dot(i,s.direction)>2*this.palmUpStrictness-1&&(t=!0)}}this._node.setEnabled(t&&i)}detach(){this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver)}linkToXRExperience(e){const t=e.featuresManager?e.featuresManager:e;if(t){try{this._eyeTracking=t.getEnabledFeature(o.b.EYE_TRACKING)}catch(e){}try{this._handTracking=t.getEnabledFeature(o.b.HAND_TRACKING)}catch(e){h.w1.Error("Hand tracking must be enabled for the Hand Menu to work")}}else h.w1.Error("XR features manager must be available or provided directly for the Hand Menu to work")}}},9778:(e,t,i)=>{i.d(t,{M:()=>u});var n=i(4496),s=i(1057),r=i(5757),o=i(4141),a=i(1903),l=i(450),h=i(6746),c=i(3615);class u{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new r.y$,this.onDragStartObservable=new r.y$,this.onDragEndObservable=new r.y$,this.onEnabledObservable=new r.y$,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new o.P(0,0,0),this._alternatePickedPoint=new o.P(0,0,0),this._worldDragAxis=new o.P(0,0,0),this._targetPosition=new o.P(0,0,0),this._attachedToElement=!1,this._startDragRay=new l.z(new o.P,new o.P),this._lastPointerRay={},this._dragDelta=new o.P,this._pointA=new o.P(0,0,0),this._pointC=new o.P(0,0,0),this._localAxis=new o.P(0,0,0),this._lookAt=new o.P(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,u._PlaneScene||(this._debugMode?u._PlaneScene=this._scene:(u._PlaneScene=new s.x(this._scene.getEngine(),{virtual:!0}),u._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((()=>{u._PlaneScene.dispose(),u._PlaneScene=null})))),this._dragPlane=(0,c.pT)("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:n.Kj.DOUBLESIDE},u._PlaneScene),this.lastDragPosition=new o.P(0,0,0);const i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add((e=>{if(this.enabled){if(e.type==a.kD.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==a.kD.POINTERUP)!this.startAndReleaseDragOnPointerEvents||this.currentDraggingPointerId!=e.event.pointerId||this._activeDragButton!==e.event.button&&-1!==this._activeDragButton||this.releaseDrag();else if(e.type==a.kD.POINTERMOVE){const t=e.event.pointerId;if(this.currentDraggingPointerId===u._AnyMouseId&&t!==u._AnyMouseId){const i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new l.z(new o.P,new o.P)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}else this._attachedToElement&&this.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(this._moving&&this.moveAttached){let e=!1;h.m._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),h.m._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}}))}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){const e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=u._AnyMouseId,t,i){this._startDrag(e,t,i);let n=this._lastPointerRay[e];e===u._AnyMouseId&&(n=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),n&&this._moveDrag(n)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;h.m._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const n=this._pickWithRayOnDragPlane(this._startDragRay);n?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(n),this.onDragStartObservable.notifyObservers({dragPlanePoint:n,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),h.m._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){h.m._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?o.P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=o.P.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),h.m._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(o.P.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*o.P.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const t=o.P.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}const i=u._PlaneScene.pickWithRay(e,(e=>e==this._dragPlane));return i&&i.hit&&i.pickedMesh&&i.pickedPoint?i.pickedPoint:null}_updateDragPlanePosition(e,t){this._pointA.copyFrom(t),this._options.dragAxis?(this.useObjectOrientationForDragging?o.P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),e.origin.subtractToRef(this._pointA,this._pointC),this._pointC.normalize(),Math.abs(o.P.Dot(this._localAxis,this._pointC))>.999?Math.abs(o.P.Dot(o.P.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(o.P.Right()):this._lookAt.copyFrom(o.P.UpReadOnly):(o.P.CrossToRef(this._localAxis,this._pointC,this._lookAt),o.P.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?o.P.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}u._AnyMouseId=-2},498:(e,t,i)=>{i.d(t,{K:()=>l});var n=i(4141),s=i(5757),r=i(6981),o=i(4674),a=i(5203);class l extends r.N{constructor(){super(...arguments),this._sceneRenderObserver=null,this._targetPosition=new n.P(0,0,0),this._targetOrientation=new n._f,this._targetScaling=new n.P(1,1,1),this._startingPosition=new n.P(0,0,0),this._startingOrientation=new n._f,this._startingScaling=new n.P(1,1,1),this.onPositionChangedObservable=new s.y$,this.dragDeltaRatio=.2,this.rotateDraggedObject=!0,this.rotateAroundYOnly=!1,this.rotateWithMotionController=!0,this.disableMovement=!1,this.faceCameraOnDragStart=!1}get name(){return"SixDofDrag"}attach(e){super.attach(e),e.isNearGrabbable=!0,this._virtualTransformNode=new o.Y("virtual_sixDof",r.N._virtualScene),this._virtualTransformNode.rotationQuaternion=n._f.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(1===this.currentDraggingPointerIds.length&&this._moving&&!this.disableMovement){const t=e.parent;e.setParent(null),e.position.addInPlace(this._targetPosition.subtract(e.position).scale(this.dragDeltaRatio)),this.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),(!t||t.scaling&&!t.scaling.isNonUniformWithinEpsilon(.001))&&n._f.SlerpToRef(e.rotationQuaternion,this._targetOrientation,this.dragDeltaRatio,e.rotationQuaternion),e.setParent(t)}}))}_getPositionOffsetAround(e,t,i){const s=n.jp.Matrix[0],r=n.jp.Matrix[1],o=n.jp.Matrix[2],a=n.jp.Matrix[3],l=n.jp.Matrix[4];return n.y3.TranslationToRef(e.x,e.y,e.z,s),n.y3.TranslationToRef(-e.x,-e.y,-e.z,r),n.y3.FromQuaternionToRef(i,o),n.y3.ScalingToRef(t,t,t,a),r.multiplyToRef(o,l),l.multiplyToRef(a,l),l.multiplyToRef(s,l),l.getTranslation()}_onePointerPositionUpdated(e,t){n.jp.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?n._f.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,n.jp.Quaternion[0]):n.jp.Quaternion[0].copyFrom(t),n.jp.Quaternion[0].multiplyToRef(this._startingOrientation,this._targetOrientation)):(this._dragging===this._dragType.NEAR_DRAG||this._dragging===this._dragType.DRAG_WITH_CONTROLLER&&this.rotateWithMotionController)&&t.multiplyToRef(this._startingOrientation,this._targetOrientation),this._targetPosition.copyFrom(this._startingPosition).addInPlace(e)}_twoPointersPositionUpdated(){const e=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition,t=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition,i=n.jp.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);const s=n.jp.Vector3[1];t.subtractToRef(e,s);const r=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,o=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,a=n.jp.Vector3[2];r.addToRef(o,a),a.scaleInPlace(.5);const l=n.jp.Vector3[3];o.subtractToRef(r,l);const h=l.length()/s.length(),c=a.subtract(i),u=n._f.FromEulerAngles(0,n.P.GetAngleBetweenVectorsOnPlane(s.normalize(),l.normalize(),n.P.UpReadOnly),0),d=this._ownerNode.parent;this._ownerNode.setParent(null);const p=this._getPositionOffsetAround(i.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),h,u);this._virtualTransformNode.rotationQuaternion.multiplyToRef(u,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(h,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef(c.addInPlace(p),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(d)}_targetDragStart(){const e=this.currentDraggingPointerIds.length,t=this._ownerNode.parent;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=n._f.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));const i=this._ownerNode.getAbsolutePivotPoint();if(this._ownerNode.setParent(null),1===e){if(this._targetPosition.copyFrom(this._ownerNode.position),this._targetOrientation.copyFrom(this._ownerNode.rotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.scaling),this.faceCameraOnDragStart&&this._scene.activeCamera){const e=n.jp.Vector3[0];this._scene.activeCamera.position.subtractToRef(i,e),e.normalize();const t=n.jp.Quaternion[0];this._scene.useRightHandedSystem?n._f.FromLookDirectionRHToRef(e,new n.P(0,1,0),t):n._f.FromLookDirectionLHToRef(e,new n.P(0,1,0),t),t.normalize(),n._f.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,n.jp.Quaternion[0]),this._targetOrientation.copyFrom(n.jp.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else 2===e&&(this._virtualTransformNode.setPivotPoint(new n.P(0,0,0),a.T.LOCAL),this._virtualTransformNode.position.copyFrom(this._ownerNode.position),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.scaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.rotationQuaternion),this._virtualTransformNode.setPivotPoint(i,a.T.WORLD),this._resetVirtualMeshesPosition());this._ownerNode.setParent(t)}_targetDrag(e,t){1===this.currentDraggingPointerIds.length?this._onePointerPositionUpdated(e,t):2===this.currentDraggingPointerIds.length&&this._twoPointersPositionUpdated()}_targetDragEnd(){if(1===this.currentDraggingPointerIds.length){this._resetVirtualMeshesPosition();const e=this.faceCameraOnDragStart;this.faceCameraOnDragStart=!1,this._targetDragStart(),this.faceCameraOnDragStart=e}}detach(){super.detach(),this._ownerNode&&(this._ownerNode.isNearGrabbable=!1,this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver)),this._virtualTransformNode&&this._virtualTransformNode.dispose()}}},120:(e,t,i)=>{i.d(t,{p:()=>r});var n=i(1903),s=i(4141);class r{constructor(){this._attachPointLocalOffset=new s.P,this._workingPosition=new s.P,this._workingQuaternion=new s._f,this._lastTick=-1,this._hit=!1,this.hitNormalOffset=.05,this.meshes=[],this.interpolatePose=!0,this.lerpTime=250,this.keepOrientationVertical=!0,this.enabled=!0,this.maxStickingDistance=.8}get name(){return"SurfaceMagnetism"}init(){}attach(e,t){this._attachedMesh=e,this._scene=t||e.getScene(),this._attachedMesh.rotationQuaternion||(this._attachedMesh.rotationQuaternion=s._f.RotationYawPitchRoll(this._attachedMesh.rotation.y,this._attachedMesh.rotation.x,this._attachedMesh.rotation.z)),this.updateAttachPoint(),this._workingPosition.copyFrom(this._attachedMesh.position),this._workingQuaternion.copyFrom(this._attachedMesh.rotationQuaternion),this._addObservables()}detach(){this._attachedMesh=null,this._removeObservables()}_getTargetPose(e){if(!this._attachedMesh)return null;if(e&&e.hit){const t=e.getNormal(!0,!0),i=e.pickedPoint;if(!t||!i)return null;t.normalize();const n=s.jp.Vector3[0];return n.copyFrom(t),n.scaleInPlace(this.hitNormalOffset),n.addInPlace(i),this._attachedMesh.parent&&(s.jp.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),s.P.TransformNormalToRef(n,s.jp.Matrix[0],n)),{position:n,quaternion:s._f.RotationYawPitchRoll(-Math.atan2(t.x,-t.z),this.keepOrientationVertical?0:Math.atan2(t.y,Math.sqrt(t.z*t.z+t.x*t.x)),0)}}return null}updateAttachPoint(){this._getAttachPointOffsetToRef(this._attachPointLocalOffset)}findAndUpdateTarget(e){if(this._hit=!1,!e.ray)return!1;const t=e.ray.intersectsMeshes(this.meshes)[0];if(this._attachedMesh&&t&&t.hit&&t.pickedMesh){const e=this._getTargetPose(t);e&&s.P.Distance(this._attachedMesh.position,e.position)<this.maxStickingDistance&&(this._workingPosition.copyFrom(e.position),this._workingQuaternion.copyFrom(e.quaternion),this._hit=!0)}return this._hit}_getAttachPointOffsetToRef(e){if(!this._attachedMesh)return void e.setAll(0);const t=s.jp.Quaternion[0];t.copyFrom(this._attachedMesh.rotationQuaternion),this._attachedMesh.rotationQuaternion.copyFromFloats(0,0,0,1),this._attachedMesh.computeWorldMatrix();const i=this._attachedMesh.getHierarchyBoundingVectors(),n=s.jp.Vector3[0];i.max.addToRef(i.min,n),n.scaleInPlace(.5),n.z=i.max.z;const r=s.jp.Matrix[0];this._attachedMesh.getWorldMatrix().invertToRef(r),s.P.TransformCoordinatesToRef(n,r,e),this._attachedMesh.rotationQuaternion.copyFrom(t)}_updateTransformToGoal(e){if(!this._attachedMesh||!this._hit)return;const t=this._attachedMesh.parent;this._attachedMesh.setParent(null);const i=s.jp.Vector3[0];if(s.P.TransformNormalToRef(this._attachPointLocalOffset,this._attachedMesh.getWorldMatrix(),i),!this.interpolatePose)return this._attachedMesh.position.copyFrom(this._workingPosition).subtractInPlace(i),void this._attachedMesh.rotationQuaternion.copyFrom(this._workingQuaternion);const n=new s.P;s.P.SmoothToRef(this._attachedMesh.position,this._workingPosition,e,this.lerpTime,n),this._attachedMesh.position.copyFrom(n);const r=new s._f;r.copyFrom(this._attachedMesh.rotationQuaternion),s._f.SmoothToRef(r,this._workingQuaternion,e,this.lerpTime,this._attachedMesh.rotationQuaternion),this._attachedMesh.setParent(t)}_addObservables(){this._pointerObserver=this._scene.onPointerObservable.add((e=>{this.enabled&&e.type==n.kD.POINTERMOVE&&e.pickInfo&&this.findAndUpdateTarget(e.pickInfo)})),this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{const e=Date.now();this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._scene.onPointerObservable.remove(this._pointerObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRender),this._pointerObserver=null,this._onBeforeRender=null}}},4026:(e,t,i)=>{i.d(t,{N:()=>a});var n=i(4141),s=i(5860),r=i(9257),o=i(5203);class a extends r.N{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){this._needToCompose=!1,e.updateFlag!==this._localMatrix.updateFlag&&(this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,s=null,r=null,o=null,a=null){super(e,t.getScene()),this.name=e,this.children=new Array,this.animations=new Array,this._index=null,this._absoluteTransform=new n.y3,this._invertedAbsoluteTransform=new n.y3,this._scalingDeterminant=1,this._worldTransform=new n.y3,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?s.clone():n.y3.Identity(),this._restPose=r||this._localMatrix.clone(),this._baseMatrix=o||this._localMatrix.clone(),this._index=a,t.bones.push(this),this.setParent(i,!1),(o||s)&&this._updateDifferenceMatrix()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateDifferenceMatrix(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBaseMatrix(){return this._baseMatrix}getRestPose(){return this._restPose}setRestPose(e){this._restPose.copyFrom(e)}getBindPose(){return this._baseMatrix}setBindPose(e){this.updateMatrix(e)}getWorldMatrix(){return this._worldTransform}returnToRest(){var e;if(this._linkedTransformNode){const t=n.jp.Vector3[0],i=n.jp.Quaternion[0],s=n.jp.Vector3[1];this.getRestPose().decompose(t,i,s),this._linkedTransformNode.position.copyFrom(s),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:n._f.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}else this._matrix=this._restPose}getInvertedAbsoluteTransform(){return this._invertedAbsoluteTransform}getAbsoluteTransform(){return this._absoluteTransform}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=n.P.Zero(),this._localRotation=n._f.Zero(),this._localPosition=n.P.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,n.y3.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,i=!0){this._baseMatrix.copyFrom(e),t&&this._updateDifferenceMatrix(),i?this._matrix=e:this.markAsDirty()}_updateDifferenceMatrix(e,t=!0){if(e||(e=this._baseMatrix),this.parent?e.multiplyToRef(this.parent._absoluteTransform,this._absoluteTransform):this._absoluteTransform.copyFrom(e),this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform),t)for(let e=0;e<this.children.length;e++)this.children[e]._updateDifferenceMatrix();this._scalingDeterminant=this._absoluteTransform.determinant()<0?-1:1}markAsDirty(){return this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty(),this}_markAsDirtyAndCompose(){this.markAsDirty(),this._needToCompose=!0}_markAsDirtyAndDecompose(){this.markAsDirty(),this._needToDecompose=!0}translate(e,t=o.T.LOCAL,i){const s=this.getLocalMatrix();if(t==o.T.LOCAL)s.addAtIndex(12,e.x),s.addAtIndex(13,e.y),s.addAtIndex(14,e.z);else{let t=null;i&&(t=i.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();const r=a._TmpMats[0],o=a._TmpVecs[0];this.parent?i&&t?(r.copyFrom(this.parent.getAbsoluteTransform()),r.multiplyToRef(t,r)):r.copyFrom(this.parent.getAbsoluteTransform()):n.y3.IdentityToRef(r),r.setTranslationFromFloats(0,0,0),r.invert(),n.P.TransformCoordinatesToRef(e,r,o),s.addAtIndex(12,o.x),s.addAtIndex(13,o.y),s.addAtIndex(14,o.z)}this._markAsDirtyAndDecompose()}setPosition(e,t=o.T.LOCAL,i){const s=this.getLocalMatrix();if(t==o.T.LOCAL)s.setTranslationFromFloats(e.x,e.y,e.z);else{let t=null;i&&(t=i.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();const r=a._TmpMats[0],o=a._TmpVecs[0];this.parent?(i&&t?(r.copyFrom(this.parent.getAbsoluteTransform()),r.multiplyToRef(t,r)):r.copyFrom(this.parent.getAbsoluteTransform()),r.invert()):n.y3.IdentityToRef(r),n.P.TransformCoordinatesToRef(e,r,o),s.setTranslationFromFloats(o.x,o.y,o.z)}this._markAsDirtyAndDecompose()}setAbsolutePosition(e,t){this.setPosition(e,o.T.WORLD,t)}scale(e,t,i,s=!1){const r=this.getLocalMatrix(),o=a._TmpMats[0];n.y3.ScalingToRef(e,t,i,o),o.multiplyToRef(r,r),o.invert();for(const n of this.children){const s=n.getLocalMatrix();s.multiplyToRef(o,s),s.multiplyAtIndex(12,e),s.multiplyAtIndex(13,t),s.multiplyAtIndex(14,i),n._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),s)for(const n of this.children)n.scale(e,t,i,s)}setScale(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()}getScale(){return this._decompose(),this._localScaling}getScaleToRef(e){this._decompose(),e.copyFrom(this._localScaling)}setYawPitchRoll(e,t,i,s=o.T.LOCAL,r){if(s===o.T.LOCAL){const o=a._TmpQuat;return n._f.RotationYawPitchRollToRef(e,t,i,o),void this.setRotationQuaternion(o,s,r)}const l=a._TmpMats[0];if(!this._getNegativeRotationToRef(l,r))return;const h=a._TmpMats[1];n.y3.RotationYawPitchRollToRef(e,t,i,h),l.multiplyToRef(h,h),this._rotateWithMatrix(h,s,r)}rotate(e,t,i=o.T.LOCAL,s){const r=a._TmpMats[0];r.setTranslationFromFloats(0,0,0),n.y3.RotationAxisToRef(e,t,r),this._rotateWithMatrix(r,i,s)}setAxisAngle(e,t,i=o.T.LOCAL,s){if(i===o.T.LOCAL){const r=a._TmpQuat;return n._f.RotationAxisToRef(e,t,r),void this.setRotationQuaternion(r,i,s)}const r=a._TmpMats[0];if(!this._getNegativeRotationToRef(r,s))return;const l=a._TmpMats[1];n.y3.RotationAxisToRef(e,t,l),r.multiplyToRef(l,l),this._rotateWithMatrix(l,i,s)}setRotation(e,t=o.T.LOCAL,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=o.T.LOCAL,i){if(t===o.T.LOCAL)return this._decompose(),this._localRotation.copyFrom(e),void this._markAsDirtyAndCompose();const s=a._TmpMats[0];if(!this._getNegativeRotationToRef(s,i))return;const r=a._TmpMats[1];n.y3.FromQuaternionToRef(e,r),s.multiplyToRef(r,r),this._rotateWithMatrix(r,t,i)}setRotationMatrix(e,t=o.T.LOCAL,i){if(t===o.T.LOCAL){const s=a._TmpQuat;return n._f.FromRotationMatrixToRef(e,s),void this.setRotationQuaternion(s,t,i)}const s=a._TmpMats[0];if(!this._getNegativeRotationToRef(s,i))return;const r=a._TmpMats[1];r.copyFrom(e),s.multiplyToRef(e,r),this._rotateWithMatrix(r,t,i)}_rotateWithMatrix(e,t=o.T.LOCAL,i){const n=this.getLocalMatrix(),s=n.m[12],r=n.m[13],l=n.m[14],h=this.getParent(),c=a._TmpMats[3],u=a._TmpMats[4];h&&t==o.T.WORLD?(i?(c.copyFrom(i.getWorldMatrix()),h.getAbsoluteTransform().multiplyToRef(c,c)):c.copyFrom(h.getAbsoluteTransform()),u.copyFrom(c),u.invert(),n.multiplyToRef(c,n),n.multiplyToRef(e,n),n.multiplyToRef(u,n)):t==o.T.WORLD&&i?(c.copyFrom(i.getWorldMatrix()),u.copyFrom(c),u.invert(),n.multiplyToRef(c,n),n.multiplyToRef(e,n),n.multiplyToRef(u,n)):n.multiplyToRef(e,n),n.setTranslationFromFloats(s,r,l),this.computeAbsoluteTransforms(),this._markAsDirtyAndDecompose()}_getNegativeRotationToRef(e,t){const i=a._TmpMats[2];return e.copyFrom(this.getAbsoluteTransform()),t?(e.multiplyToRef(t.getWorldMatrix(),e),n.y3.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):n.y3.IdentityToRef(i),e.invert(),!isNaN(e.m[0])&&(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=o.T.LOCAL,t=null){const i=n.P.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=o.T.LOCAL,t,i){if(e==o.T.LOCAL){const e=this.getLocalMatrix();i.x=e.m[12],i.y=e.m[13],i.z=e.m[14]}else{let e=null;t&&(e=t.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();let n=a._TmpMats[0];t&&e?(n.copyFrom(this.getAbsoluteTransform()),n.multiplyToRef(e,n)):n=this.getAbsoluteTransform(),i.x=n.m[12],i.y=n.m[13],i.z=n.m[14]}}getAbsolutePosition(e=null){const t=n.P.Zero();return this.getPositionToRef(o.T.WORLD,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(o.T.WORLD,e,t)}computeAbsoluteTransforms(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteTransform,this._absoluteTransform);else{this._absoluteTransform.copyFrom(this._localMatrix);const e=this._skeleton.getPoseMatrix();e&&this._absoluteTransform.multiplyToRef(e,this._absoluteTransform)}const e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].computeAbsoluteTransforms()}getDirection(e,t=null){const i=n.P.Zero();return this.getDirectionToRef(e,t,i),i}getDirectionToRef(e,t=null,i){let s=null;t&&(s=t.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();const r=a._TmpMats[0];r.copyFrom(this.getAbsoluteTransform()),t&&s&&r.multiplyToRef(s,r),n.P.TransformNormalToRef(e,r,i),i.normalize()}getRotation(e=o.T.LOCAL,t=null){const i=n.P.Zero();return this.getRotationToRef(e,t,i),i}getRotationToRef(e=o.T.LOCAL,t=null,i){const n=a._TmpQuat;this.getRotationQuaternionToRef(e,t,n),n.toEulerAnglesToRef(i)}getRotationQuaternion(e=o.T.LOCAL,t=null){const i=n._f.Identity();return this.getRotationQuaternionToRef(e,t,i),i}getRotationQuaternionToRef(e=o.T.LOCAL,t=null,i){if(e==o.T.LOCAL)this._decompose(),i.copyFrom(this._localRotation);else{const e=a._TmpMats[0],n=this.getAbsoluteTransform();t?n.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(n),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.decompose(void 0,i,void 0)}}getRotationMatrix(e=o.T.LOCAL,t){const i=n.y3.Identity();return this.getRotationMatrixToRef(e,t,i),i}getRotationMatrixToRef(e=o.T.LOCAL,t,i){if(e==o.T.LOCAL)this.getLocalMatrix().getRotationMatrixToRef(i);else{const e=a._TmpMats[0],n=this.getAbsoluteTransform();t?n.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(n),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.getRotationMatrixToRef(i)}}getAbsolutePositionFromLocal(e,t=null){const i=n.P.Zero();return this.getAbsolutePositionFromLocalToRef(e,t,i),i}getAbsolutePositionFromLocalToRef(e,t=null,i){let s=null;t&&(s=t.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();let r=a._TmpMats[0];t&&s?(r.copyFrom(this.getAbsoluteTransform()),r.multiplyToRef(s,r)):r=this.getAbsoluteTransform(),n.P.TransformCoordinatesToRef(e,r,i)}getLocalPositionFromAbsolute(e,t=null){const i=n.P.Zero();return this.getLocalPositionFromAbsoluteToRef(e,t,i),i}getLocalPositionFromAbsoluteToRef(e,t=null,i){let s=null;t&&(s=t.getWorldMatrix()),this._skeleton.computeAbsoluteTransforms();const r=a._TmpMats[0];r.copyFrom(this.getAbsoluteTransform()),t&&s&&r.multiplyToRef(s,r),r.invert(),n.P.TransformCoordinatesToRef(e,r,i)}setCurrentPoseAsRest(){this.setRestPose(this.getLocalMatrix())}}a._TmpVecs=s.B.BuildArray(2,n.P.Zero),a._TmpQuat=n._f.Identity(),a._TmpMats=s.B.BuildArray(5,n.y3.Identity)},5047:(e,t,i)=>{i.d(t,{O:()=>d});var n=i(4026),s=i(5757),r=i(4141),o=i(7647),a=i(4676),l=i(2695),h=i(1431),c=i(2722),u=i(6387);class d{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=new Array,this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=r.y3.Identity(),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 s.y$,this.bones=[],this._scene=i||h.l.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const n=this._scene.getEngine().getCaps();this._canUseTextureForBones=n.textureFloat&&n.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 e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return-1}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=new l.X(e,t,i);for(let n=0,s=this.bones.length;n<s;n++)this.bones[n].animations[0]&&this.bones[n].animations[0].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,n=this.bones.length;i<n;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}copyAnimationRange(e,t,i=!1){if(this._ranges[t]||!e.getAnimationRange(t))return!1;let n=!0;const s=this._getHighestAnimationFrame()+1,r={},o=e.bones;let a,h;for(h=0,a=o.length;h<a;h++)r[o[h].name]=o[h];this.bones.length!==o.length&&(c.Y.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${o.length}`),n=!1);const u=i&&this.dimensionsAtRest&&e.dimensionsAtRest?this.dimensionsAtRest.divide(e.dimensionsAtRest):null;for(h=0,a=this.bones.length;h<a;h++){const e=this.bones[h].name,o=r[e];o?n=n&&this.bones[h].copyAnimationRange(o,t,s,i,u):(c.Y.Warn("copyAnimationRange: not same rig, missing source bone "+e),n=!1)}const d=e.getAnimationRange(t);return d&&(this._ranges[t]=new l.X(t,d.from+s,d.to+s)),n}returnToRest(){for(const e of this.bones)-1!==e._index&&e.returnToRest()}_getHighestAnimationFrame(){let e=0;for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){const i=this.bones[t].animations[0].getHighestFrame();e<i&&(e=i)}return e}beginAnimation(e,t,i,n){const s=this.getAnimationRange(e);return s?this._scene.beginAnimation(this,s.from,s.to,t,i,n):null}static MakeAnimationAdditive(e,t=0,i){const n=e.getAnimationRange(i);if(!n)return null;const s=e._scene.getAllAnimatablesByTarget(e);let r=null;for(let e=0;e<s.length;e++){const t=s[e];if(t.fromFrame===(null==n?void 0:n.from)&&t.toFrame===(null==n?void 0:n.to)){r=t;break}}const o=e.getAnimatables();for(let e=0;e<o.length;e++){const n=o[e].animations;if(n)for(let e=0;e<n.length;e++)a.f.MakeAnimationAdditive(n[e],t,i)}return r&&(r.isAdditive=!0),e}_markAsDirty(){this._isDirty=!0,this._absoluteTransformIsDirty=!0}_registerMeshWithPoseMatrix(e){this._meshesWithPoseMatrix.push(e)}_unregisterMeshWithPoseMatrix(e){const t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i<this.bones.length;i++){const n=this.bones[i];n._childUpdateId++;const s=n.getParent();if(s?n.getLocalMatrix().multiplyToRef(s.getWorldMatrix(),n.getWorldMatrix()):t?n.getLocalMatrix().multiplyToRef(t,n.getWorldMatrix()):n.getWorldMatrix().copyFrom(n.getLocalMatrix()),-1!==n._index){const t=null===n._index?i:n._index;n.getInvertedAbsoluteTransform().multiplyToArray(n.getWorldMatrix(),e,16*t)}}this._identity.copyToArray(e,16*this.bones.length)}prepare(){if(this._numBonesWithLinkedTransformNode>0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)e.getParent()||(e.getBaseMatrix().multiplyToRef(t,r.jp.Matrix[1]),e._updateDifferenceMatrix(r.jp.Matrix[1]));if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=o.l.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._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=o.l.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables}clone(e,t){const i=new d(e,t||e,this._scene);i.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let e=0;e<this.bones.length;e++){const t=this.bones[e];let s=null;const r=t.getParent();if(r){const e=this.bones.indexOf(r);s=i.bones[e]}const o=new n.N(t.name,i,s,t.getBaseMatrix().clone(),t.getRestPose().clone());o._index=t._index,t._linkedTransformNode&&o.linkTransformNode(t._linkedTransformNode),u.j.DeepCopy(t.animations,o.animations)}if(this._ranges){i._ranges={};for(const e in this._ranges){const t=this._ranges[e];t&&(i._ranges[e]=t.clone())}}return this._isDirty=!0,i}enableBlending(e=.01){this.bones.forEach((t=>{t.animations.forEach((t=>{t.enableBlending=!0,t.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;i<this.bones.length;i++){const n=this.bones[i],s=n.getParent(),r={parentBoneIndex:s?this.bones.indexOf(s):-1,index:n.getIndex(),name:n.name,id:n.id,matrix:n.getBaseMatrix().toArray(),rest:n.getRestPose().toArray(),linkedTransformNodeId:null===(e=n.getTransformNode())||void 0===e?void 0:e.id};t.bones.push(r),n.length&&(r.length=n.length),n.metadata&&(r.metadata=n.metadata),n.animations&&n.animations.length>0&&(r.animation=n.animations[0].serialize()),t.ranges=[];for(const e in this._ranges){const i=this._ranges[e];if(!i)continue;const n={};n.name=e,n.from=i.from,n.to=i.to,t.ranges.push(n)}}return t}static Parse(e,t){const i=new d(e.name,e.id,t);let s;for(e.dimensionsAtRest&&(i.dimensionsAtRest=r.P.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,s=0;s<e.bones.length;s++){const t=e.bones[s],o=e.bones[s].index;let l=null;t.parentBoneIndex>-1&&(l=i.bones[t.parentBoneIndex]);const h=t.rest?r.y3.FromArray(t.rest):null,c=new n.N(t.name,i,l,r.y3.FromArray(t.matrix),h,null,o);void 0!==t.id&&null!==t.id&&(c.id=t.id),t.length&&(c.length=t.length),t.metadata&&(c.metadata=t.metadata),t.animation&&c.animations.push(a.f.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,c._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(s=0;s<e.ranges.length;s++){const t=e.ranges[s];i.createAnimationRange(t.name,t.from,t.to)}return i}computeAbsoluteTransforms(e=!1){(this._absoluteTransformIsDirty||e)&&(this.bones[0].computeAbsoluteTransforms(),this._absoluteTransformIsDirty=!1)}getPoseMatrix(){let e=null;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=new Array,t=new Array(this.bones.length);for(let i=0;i<this.bones.length;i++)this._sortBones(i,e,t);this.bones=e}_sortBones(e,t,i){if(i[e])return;i[e]=!0;const n=this.bones[e];if(!n)return;void 0===n._index&&(n._index=e);const s=n.getParent();s&&this._sortBones(this.bones.indexOf(s),t,i),t.push(n)}setCurrentPoseAsRest(){this.bones.forEach((e=>{e.setCurrentPoseAsRest()}))}}},708:(e,t,i)=>{i.d(t,{l:()=>s,o:()=>r});var n=i(7698);class s{constructor(e,t,i,s=0,r=!1,o=!1,a=!1,l){this._isAlreadyOwned=!1,e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=o,this._divisor=l||1,t instanceof n.h?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?s:s*Float32Array.BYTES_PER_ELEMENT,r||this.create()}createVertexBuffer(e,t,i,n,s,o=!1,a){const l=o?t:t*Float32Array.BYTES_PER_ELEMENT,h=n?o?n:n*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new r(this._engine,this,e,this._updatable,!0,h,void 0===s?this._instanced:s,l,i,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e),this._data=e):this._buffer=this._engine.createVertexBuffer(e))}_rebuild(){this._buffer=null,this.create(this._data)}update(e){this.create(e)}updateDirectly(e,t,i,n=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,n?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=0===t&&void 0===i?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null,this._data=null)}}class r{get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}constructor(e,t,i,n,o,a,l,h,c,u,d=!1,p=!1,f=1,_=!1){if(t instanceof s?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new s(e,t,n,a,o,l,p),this._ownsBuffer=!0),this.uniqueId=r._Counter++,this._kind=i,null==u){const e=this.getData();this.type=r.FLOAT,e instanceof Int8Array?this.type=r.BYTE:e instanceof Uint8Array?this.type=r.UNSIGNED_BYTE:e instanceof Int16Array?this.type=r.SHORT:e instanceof Uint16Array?this.type=r.UNSIGNED_SHORT:e instanceof Int32Array?this.type=r.INT:e instanceof Uint32Array&&(this.type=r.UNSIGNED_INT)}else this.type=u;const m=r.GetTypeByteLength(this.type);p?(this._size=c||(a?a/m:r.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*m,this.byteOffset=h||0):(this._size=c||a||r.DeduceStride(i),this.byteStride=a?a*m:this._buffer.byteStride||this._size*m,this.byteOffset=(h||0)*m),this.normalized=d,this._instanced=void 0!==l&&l,this._instanceDivisor=l?f:0,this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer&&this._buffer._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();if(!i)return null;const n=this.getSize()*r.GetTypeByteLength(this.type),s=e*this.getSize();if(this.type!==r.FLOAT||this.byteStride!==n){const e=new Float32Array(s);return this.forEach(s,((t,i)=>e[i]=t)),e}if(!(i instanceof Array||i instanceof Float32Array)||0!==this.byteOffset||i.length!==s){if(i instanceof Array){const e=this.byteOffset/4;return i.slice(e,e+s)}if(i instanceof ArrayBuffer)return new Float32Array(i,this.byteOffset,s);{let e=i.byteOffset+this.byteOffset;if(t){const t=new Float32Array(s),n=new Float32Array(i.buffer,e,s);return t.set(n),t}const n=e%4;return n&&(e=Math.max(0,e-n)),new Float32Array(i.buffer,e,s)}}return t?i.slice():i}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/r.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/r.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*r.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e)}update(e){this._buffer.update(e)}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i)}dispose(){this._ownsBuffer&&this._buffer.dispose()}forEach(e,t){r.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}static DeduceStride(e){switch(e){case r.UVKind:case r.UV2Kind:case r.UV3Kind:case r.UV4Kind:case r.UV5Kind:case r.UV6Kind:return 2;case r.NormalKind:case r.PositionKind:return 3;case r.ColorKind:case r.MatricesIndicesKind:case r.MatricesIndicesExtraKind:case r.MatricesWeightsKind:case r.MatricesWeightsExtraKind:case r.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetTypeByteLength(e){switch(e){case r.BYTE:case r.UNSIGNED_BYTE:return 1;case r.SHORT:case r.UNSIGNED_SHORT:return 2;case r.INT:case r.UNSIGNED_INT:case r.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,n,s,o,a,l){if(e instanceof Array){let s=t/4;const r=i/4;for(let t=0;t<o;t+=n){for(let i=0;i<n;i++)l(e[s+i],t+i);s+=r}}else{const h=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),c=r.GetTypeByteLength(s);for(let e=0;e<o;e+=n){let o=t;for(let t=0;t<n;t++)l(r._GetFloatValue(h,s,o,a),e+t),o+=c;t+=i}}}static _GetFloatValue(e,t,i,n){switch(t){case r.BYTE:{let t=e.getInt8(i);return n&&(t=Math.max(t/127,-1)),t}case r.UNSIGNED_BYTE:{let t=e.getUint8(i);return n&&(t/=255),t}case r.SHORT:{let t=e.getInt16(i,!0);return n&&(t=Math.max(t/32767,-1)),t}case r.UNSIGNED_SHORT:{let t=e.getUint16(i,!0);return n&&(t/=65535),t}case r.INT:return e.getInt32(i,!0);case r.UNSIGNED_INT:return e.getUint32(i,!0);case r.FLOAT:return e.getFloat32(i,!0);default:throw new Error(`Invalid component type ${t}`)}}}r._Counter=0,r.BYTE=5120,r.UNSIGNED_BYTE=5121,r.SHORT=5122,r.UNSIGNED_SHORT=5123,r.INT=5124,r.UNSIGNED_INT=5125,r.FLOAT=5126,r.PositionKind="position",r.NormalKind="normal",r.TangentKind="tangent",r.UVKind="uv",r.UV2Kind="uv2",r.UV3Kind="uv3",r.UV4Kind="uv4",r.UV5Kind="uv5",r.UV6Kind="uv6",r.ColorKind="color",r.ColorInstanceKind="instanceColor",r.MatricesIndicesKind="matricesIndices",r.MatricesWeightsKind="matricesWeights",r.MatricesIndicesExtraKind="matricesIndicesExtra",r.MatricesWeightsExtraKind="matricesWeightsExtra"},7698:(e,t,i)=>{i.d(t,{h:()=>n});class n{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=n._Counter++}}n._Counter=0},9563:(e,t,i)=>{i.d(t,{Y:()=>h});var n=i(9472),s=i(3956),r=i(5757),o=i(1903),a=i(2272),l=i(7257);class h{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new r.y$,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=l.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==o.kD.POINTERWHEEL)return;const i=t.event,n=i.deltaMode===a.G.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*n*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*n*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*n*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,o.kD.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"}}(0,n.gn)([(0,s.qC)()],h.prototype,"wheelPrecisionX",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"wheelPrecisionY",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"wheelPrecisionZ",void 0)},1399:(e,t,i)=>{i.d(t,{Y:()=>h});var n=i(9472),s=i(3956),r=i(1181),o=i(2925),a=i(4141),l=i(7257);class h{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=l.w1.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===o.OG.KEYDOWN)-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)&&-1===this.keysUpward.indexOf(i.keyCode)&&-1===this.keysDownward.indexOf(i.keyCode)&&-1===this.keysRotateLeft.indexOf(i.keyCode)&&-1===this.keysRotateRight.indexOf(i.keyCode)&&-1===this.keysRotateUp.indexOf(i.keyCode)&&-1===this.keysRotateDown.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t<this._keys.length;t++){const i=this._keys[t],n=e._computeLocalCameraSpeed();-1!==this.keysLeft.indexOf(i)?e._localDirection.copyFromFloats(-n,0,0):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,0,n):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(n,0,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,0,-n):-1!==this.keysUpward.indexOf(i)?e._localDirection.copyFromFloats(0,n,0):-1!==this.keysDownward.indexOf(i)?e._localDirection.copyFromFloats(0,-n,0):-1!==this.keysRotateLeft.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y-=this._getLocalRotation()):-1!==this.keysRotateRight.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y+=this._getLocalRotation()):-1!==this.keysRotateUp.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x-=this._getLocalRotation()):-1!==this.keysRotateDown.indexOf(i)&&(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x+=this._getLocalRotation()),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),a.P.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}getClassName(){return"FreeCameraKeyboardMoveInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}_getLocalRotation(){let e=this.rotationSpeed*this._engine.getDeltaTime()/1e3;return this.camera.getScene().useRightHandedSystem&&(e*=-1),this.camera.parent&&this.camera.parent._getWorldMatrixDeterminant()<0&&(e*=-1),e}}(0,n.gn)([(0,s.qC)()],h.prototype,"keysUp",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"keysUpward",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"keysDown",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"keysDownward",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"keysLeft",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"keysRight",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"rotationSpeed",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"keysRotateLeft",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"keysRotateRight",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"keysRotateUp",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"keysRotateDown",void 0),r.u.FreeCameraKeyboardMoveInput=h},3516:(e,t,i)=>{i.d(t,{A:()=>h});var n=i(9472),s=i(5757),r=i(3956),o=i(1181),a=i(1903),l=i(7257);class h{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new s.y$,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=l.w1.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();this._pointerInput||(this._pointerInput=n=>{const s=n.event,r="touch"===s.pointerType;if(t.isInVRExclusivePointerMode)return;if(!this.touchEnabled&&r)return;if(n.type!==a.kD.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;const o=s.target;if(n.type===a.kD.POINTERDOWN){if(r&&-1!==this._activePointerId||!r&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{null==o||o.setPointerCapture(s.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},e||(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(n.event)}else if(n.type===a.kD.POINTERUP){if(r&&this._activePointerId!==s.pointerId||!r&&this._currentActiveButton!==s.button)return;try{null==o||o.releasePointerCapture(s.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(n.type===a.kD.POINTERMOVE&&(this._activePointerId===s.pointerId||!r))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(n.event);else if(this._previousPosition){let t=s.clientX-this._previousPosition.x;const i=s.clientY-this._previousPosition.y;this.camera.getScene().useRightHandedSystem&&(t*=-1),this.camera.parent&&this.camera.parent._getWorldMatrixDeterminant()<0&&(t*=-1),this._allowCameraRotation&&(this.camera.cameraRotation.y+=t/this.angularSensibility,this.camera.cameraRotation.x+=i/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:t,offsetY:i}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;if(t.isInVRExclusivePointerMode)return;let n=i.movementX;this.camera.getScene().useRightHandedSystem&&(n*=-1),this.camera.parent&&this.camera.parent._getWorldMatrixDeterminant()<0&&(n*=-1),this.camera.cameraRotation.y+=n/this.angularSensibility;const s=i.movementY;this.camera.cameraRotation.x+=s/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,a.kD.POINTERDOWN|a.kD.POINTERUP|a.kD.POINTERMOVE),i&&(this._contextMenuBind=this.onContextMenu.bind(this),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}(0,n.gn)([(0,r.qC)()],h.prototype,"buttons",void 0),(0,n.gn)([(0,r.qC)()],h.prototype,"angularSensibility",void 0),o.u.FreeCameraMouseInput=h},9891:(e,t,i)=>{i.d(t,{A:()=>c});var n,s=i(9472),r=i(3956),o=i(1181),a=i(9563),l=i(4141),h=i(5203);!function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(n||(n={}));class c extends a.Y{constructor(){super(...arguments),this._moveRelative=l.P.Zero(),this._rotateRelative=l.P.Zero(),this._moveScene=l.P.Zero(),this._wheelXAction=n.MoveRelative,this._wheelXActionCoordinate=h.c7.X,this._wheelYAction=n.MoveRelative,this._wheelYActionCoordinate=h.c7.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==n.MoveRelative||(this._wheelXAction=n.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==n.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==n.MoveRelative||(this._wheelYAction=n.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==n.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==n.MoveRelative||(this._wheelZAction=n.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==n.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==n.RotateRelative||(this._wheelXAction=n.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==n.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==n.RotateRelative||(this._wheelYAction=n.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==n.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==n.RotateRelative||(this._wheelZAction=n.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==n.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==n.MoveScene||(this._wheelXAction=n.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==n.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==n.MoveScene||(this._wheelYAction=n.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==n.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==n.MoveScene||(this._wheelZAction=n.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==n.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(0===this._wheelDeltaX&&0===this._wheelDeltaY&&0==this._wheelDeltaZ)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=l.y3.Zero();this.camera.getViewMatrix().invertToRef(e);const t=l.P.Zero();l.P.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(0===e)return;if(null===t||null===i)return;let s=null;switch(t){case n.MoveRelative:s=this._moveRelative;break;case n.RotateRelative:s=this._rotateRelative;break;case n.MoveScene:s=this._moveScene}switch(i){case h.c7.X:s.set(e,0,0);break;case h.c7.Y:s.set(0,e,0);break;case h.c7.Z:s.set(0,0,e)}}}(0,s.gn)([(0,r.qC)()],c.prototype,"wheelXMoveRelative",null),(0,s.gn)([(0,r.qC)()],c.prototype,"wheelYMoveRelative",null),(0,s.gn)([(0,r.qC)()],c.prototype,"wheelZMoveRelative",null),(0,s.gn)([(0,r.qC)()],c.prototype,"wheelXRotateRelative",null),(0,s.gn)([(0,r.qC)()],c.prototype,"wheelYRotateRelative",null),(0,s.gn)([(0,r.qC)()],c.prototype,"wheelZRotateRelative",null),(0,s.gn)([(0,r.qC)()],c.prototype,"wheelXMoveScene",null),(0,s.gn)([(0,r.qC)()],c.prototype,"wheelYMoveScene",null),(0,s.gn)([(0,r.qC)()],c.prototype,"wheelZMoveScene",null),o.u.FreeCameraMouseWheelInput=c},7932:(e,t,i)=>{i.d(t,{y:()=>h});var n=i(9472),s=i(3956),r=i(1181),o=i(1903),a=i(4141),l=i(7257);class h{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=l.w1.IsSafari()}attachControl(e){e=l.w1.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const n=i.event,s="mouse"===n.pointerType||this._isSafari&&void 0===n.pointerType;if(this.allowMouse||!s)if(i.type===o.kD.POINTERDOWN){if(e||n.preventDefault(),this._pointerPressed.push(n.pointerId),1!==this._pointerPressed.length)return;t={x:n.clientX,y:n.clientY}}else if(i.type===o.kD.POINTERUP){e||n.preventDefault();const i=this._pointerPressed.indexOf(n.pointerId);if(-1===i)return;if(this._pointerPressed.splice(i,1),0!=i)return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===o.kD.POINTERMOVE){if(e||n.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(n.pointerId))return;this._offsetX=n.clientX-t.x,this._offsetY=-(n.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,o.kD.POINTERDOWN|o.kD.POINTERUP|o.kD.POINTERMOVE),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(null===this._offsetX||null===this._offsetY)return;if(0===this._offsetX&&0===this._offsetY)return;const e=this.camera;if(e.cameraRotation.y=this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const t=e._computeLocalCameraSpeed(),i=new a.P(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);a.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(a.P.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}(0,n.gn)([(0,s.qC)()],h.prototype,"touchAngularSensibility",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"touchMoveSensibility",void 0),r.u.FreeCameraTouchInput=h},2704:(e,t,i)=>{i.d(t,{V:()=>_});var n=i(9472),s=i(3956),r=i(5363),o=i(7257),a=i(5757),l=i(4141),h=i(9257),c=i(2722),u=i(2208),d=i(4934),p=i(4538),f=i(1560);class _ extends h.N{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,n;let s=0,r=0;if(this.mode===_.PERSPECTIVE_CAMERA)this.fovMode===_.FOVMODE_VERTICAL_FIXED?(r=2*this.minZ*Math.tan(this.fov/2),s=this.getEngine().getAspectRatio(this)*r):(s=2*this.minZ*Math.tan(this.fov/2),r=s/this.getEngine().getAspectRatio(this));else{const o=this.getEngine().getRenderWidth()/2,a=this.getEngine().getRenderHeight()/2;s=(null!==(e=this.orthoRight)&&void 0!==e?e:o)-(null!==(t=this.orthoLeft)&&void 0!==t?t:-o),r=(null!==(i=this.orthoTop)&&void 0!==i?i:a)-(null!==(n=this.orthoBottom)&&void 0!==n?n:-a)}return s*r}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,n=!0){super(e,i),this._position=l.P.Zero(),this._upVector=l.P.Up(),this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=_.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new p.l(0,0,1,1),this.layerMask=268435455,this.fovMode=_.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=_.RIG_MODE_NONE,this.customRenderTargets=new Array,this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new a.y$,this.onProjectionMatrixChangedObservable=new a.y$,this.onAfterCheckInputsObservable=new a.y$,this.onRestoreStateObservable=new a.y$,this.isRigCamera=!1,this._rigCameras=new Array,this._webvrViewMatrix=l.y3.Identity(),this._skipRendering=!1,this._projectionMatrix=new l.y3,this._postProcesses=new Array,this._activeMeshes=new r.t(256),this._globalPosition=l.P.Zero(),this._computedViewMatrix=l.y3.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=l.y3.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=l._f.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),n&&!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)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}applyVerticalCorrection(){const e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x}get globalPosition(){return this._globalPosition}getActiveMeshes(){return this._activeMeshes}isActiveMesh(e){return-1!==this._activeMeshes.indexOf(e)}isReady(e=!1){if(e)for(const e of this._postProcesses)if(e&&!e.isReady())return!1;return super.isReady(e)}_initCache(){super._initCache(),this._cache.position=new l.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new l.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return!!super._isSynchronized()&&this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent()}_isSynchronizedProjectionMatrix(){let e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;const t=this.getEngine();return e=this.mode===_.PERSPECTIVE_CAMERA?this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight(),e}attachControl(e,t){}detachControl(e){}update(){this._checkInputs(),this.cameraRigMode!==_.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()}_checkInputs(){this.onAfterCheckInputsObservable.notifyObservers(this)}get rigCameras(){return this._rigCameras}get rigPostProcess(){return this._rigPostProcess}_getFirstPostProcess(){for(let e=0;e<this._postProcesses.length;e++)if(null!==this._postProcesses[e])return this._postProcesses[e];return null}_cascadePostProcessesToRigCams(){const e=this._getFirstPostProcess();e&&e.markTextureDirty();for(let e=0,t=this._rigCameras.length;e<t;e++){const t=this._rigCameras[e],i=t._rigPostProcess;i?("pass"===i.getEffectName()&&(t.isIntermediate=0===this._postProcesses.length),t._postProcesses=this._postProcesses.slice(0).concat(i),i.markTextureDirty()):t._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(c.Y.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return l.y3.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix)),this._computedViewMatrix}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){var t,i,n,s,r,o,a,h;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const c=this.getEngine(),u=this.getScene(),d=c.useReverseDepthBuffer;if(this.mode===_.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=c.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=u.useRightHandedSystem?l.y3.PerspectiveFovRHToRef:l.y3.PerspectiveFovLHToRef,e(this.fov,c.getAspectRatio(this),d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===_.FOVMODE_VERTICAL_FIXED,c.isNDCHalfZRange,this.projectionPlaneTilt,d)}else{const e=c.getRenderWidth()/2,p=c.getRenderHeight()/2;u.useRightHandedSystem?l.y3.OrthoOffCenterRHToRef(null!==(t=this.orthoLeft)&&void 0!==t?t:-e,null!==(i=this.orthoRight)&&void 0!==i?i:e,null!==(n=this.orthoBottom)&&void 0!==n?n:-p,null!==(s=this.orthoTop)&&void 0!==s?s:p,d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange):l.y3.OrthoOffCenterLHToRef(null!==(r=this.orthoLeft)&&void 0!==r?r:-e,null!==(o=this.orthoRight)&&void 0!==o?o:e,null!==(a=this.orthoBottom)&&void 0!==a?a:-p,null!==(h=this.orthoTop)&&void 0!==h?h:p,d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=c.getRenderWidth(),this._cache.renderHeight=c.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?f.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=f.i.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw(0,d.S)("Ray")}getForwardRayToRef(e,t=100,i,n){throw(0,d.S)("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==_.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=o.w1.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==_.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return l.y3.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}_updateCameraRotationMatrix(){}_updateWebVRCameraRotationMatrix(){}_getWebVRProjectionMatrix(){return l.y3.Identity()}_getWebVRViewMatrix(){return l.y3.Identity()}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=o.w1.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===_.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){const e=s.p4.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),s.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){const i=s.p4.Clone(_.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return i.name=e,i.parent=t,this.onClonedObservable.notifyObservers(i),i}getDirection(e){const t=l.P.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){l.P.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,i,n=0,s=!0){return h.N.Construct(e,t,i,{interaxial_distance:n,isStereoscopicSideBySide:s})||(()=>_._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,n=_.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=s.p4.Parse(n,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=l.P.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(l.P.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(l.P.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],n=(0,u.q)("BABYLON.Animation");n&&r.animations.push(n.Parse(i))}h.N.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&r.setEnabled(e.isEnabled),r}}_._CreateDefaultParsedCamera=(e,t)=>{throw(0,d.S)("UniversalCamera")},_.PERSPECTIVE_CAMERA=0,_.ORTHOGRAPHIC_CAMERA=1,_.FOVMODE_VERTICAL_FIXED=0,_.FOVMODE_HORIZONTAL_FIXED=1,_.RIG_MODE_NONE=0,_.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,_.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,_.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,_.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,_.RIG_MODE_STEREOSCOPIC_INTERLACED=14,_.RIG_MODE_VR=20,_.RIG_MODE_WEBVR=21,_.RIG_MODE_CUSTOM=22,_.ForceAttachControlToAlwaysPreventDefault=!1,(0,n.gn)([(0,s.hd)("position")],_.prototype,"_position",void 0),(0,n.gn)([(0,s.hd)("upVector")],_.prototype,"_upVector",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoLeft",null),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoRight",null),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoBottom",null),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoTop",null),(0,n.gn)([(0,s.qC)()],_.prototype,"fov",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"projectionPlaneTilt",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"minZ",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"maxZ",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"inertia",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"mode",null),(0,n.gn)([(0,s.qC)()],_.prototype,"layerMask",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"fovMode",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"cameraRigMode",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"interaxialDistance",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"isStereoscopicSideBySide",void 0)},1181:(e,t,i)=>{i.d(t,{p:()=>a,u:()=>o});var n=i(2722),s=i(3956),r=i(2704),o={};class a{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?n.Y.Warn("camera input of type "+t+" already exists on camera"):(this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault))}remove(e){for(const t in this.attached){const i=this.attached[t];if(i===e)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=!r.V.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const e in this.attached){const i=this.attached[e],n=s.p4.Serialize(i);t[i.getClassName()]=n}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=o[e];if(i){const n=t[e],r=s.p4.Parse((()=>new i),n,null);this.add(r)}}}else for(const t in this.attached){const i=o[this.attached[t].getClassName()];if(i){const n=s.p4.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(n)}}}}},8482:(e,t,i)=>{i.d(t,{c:()=>c});var n=i(9472),s=i(3956),r=i(4141),o=i(7814),a=i(3835),l=i(189),h=i(7257);class c extends a.C{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){const e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){const t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){const e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){const t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){const e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){const e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){const e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){const e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,n=!0){super(e,t,i,n),this.ellipsoid=new r.P(.5,1,.5),this.ellipsoidOffset=new r.P(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=r.P.Zero(),this._diffPosition=r.P.Zero(),this._newPosition=r.P.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>o.D.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new l.a(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=h.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new r.P(0,0,0),this.cameraRotation=new r.FM(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?r.P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let n=e;this.applyGravity&&(n=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,n,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=r.P.Zero(),this._transformedDirection=r.P.Zero()),this.inputs.checkInputs(),super._checkInputs()}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}(0,n.gn)([(0,s.hd)()],c.prototype,"ellipsoid",void 0),(0,n.gn)([(0,s.hd)()],c.prototype,"ellipsoidOffset",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"checkCollisions",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"applyGravity",void 0)},189:(e,t,i)=>{i.d(t,{a:()=>l});var n=i(1181),s=i(1399),r=i(3516),o=i(9891),a=i(7932);class l extends n.p{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new s.Y),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new r.A(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new o.A,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new a.y),this}clear(){super.clear(),this._mouseInput=null}}},3835:(e,t,i)=>{i.d(t,{C:()=>h});var n=i(9472),s=i(3956),r=i(2704),o=i(4141),a=i(1341),l=i(5203);class h extends r.V{constructor(e,t,i,n=!0){super(e,t,i,n),this._tmpUpVector=o.P.Zero(),this._tmpTargetVector=o.P.Zero(),this.cameraDirection=new o.P(0,0,0),this.cameraRotation=new o.FM(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new o._f,this.rotation=new o.P(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=o.P.Zero(),this._initialFocalDistance=1,this._viewMatrix=o.y3.Zero(),this._camMatrix=o.y3.Zero(),this._cameraTransformMatrix=o.y3.Zero(),this._cameraRotationMatrix=o.y3.Zero(),this._referencePoint=new o.P(0,0,1),this._transformedReferencePoint=o.P.Zero(),this._defaultUp=o.P.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)}_initCache(){super._initCache(),this._cache.lockedTarget=new o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new o._f(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=a.kn),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),o.y3.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&&o._f.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(o.jp.Matrix[0]),o.P.TransformNormalToRef(this.cameraDirection,o.jp.Matrix[0],o.jp.Vector3[0]),void this.position.addInPlace(o.jp.Vector3[0]);this.position.addInPlace(this.cameraDirection)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this.rotation),this.rotation.x+=this.cameraRotation.x*e,this.rotation.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this.rotation.x>e&&(this.rotation.x=e),this.rotation.x<-e&&(this.rotation.x=-e)}this.rotationQuaternion&&this.rotation.lengthSquared()&&o._f.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}t&&(Math.abs(this.cameraDirection.x)<this.speed*a.kn&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<this.speed*a.kn&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<this.speed*a.kn&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<this.speed*a.kn&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<this.speed*a.kn&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):o.y3.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return o.P.TransformNormalToRef(this._defaultUp,this._cameraRotationMatrix,this.upVector),this}_getViewMatrix(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),o.P.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?l.RD.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(o._f.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),l.RD.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,i){if(this.ignoreParentScaling){if(this.parent){const n=this.parent.getWorldMatrix();o.P.TransformCoordinatesToRef(e,n,this._globalPosition),o.P.TransformCoordinatesToRef(t,n,this._tmpTargetVector),o.P.TransformNormalToRef(i,n,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(t),this._tmpUpVector.copyFrom(i);this.getScene().useRightHandedSystem?o.y3.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):o.y3.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix)}else if(this.getScene().useRightHandedSystem?o.y3.LookAtRHToRef(e,t,i,this._viewMatrix):o.y3.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent){const e=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(e,this._viewMatrix),this._viewMatrix.getTranslationToRef(this._globalPosition),this._viewMatrix.invert(),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e)}createRigCamera(e,t){if(this.cameraRigMode!==r.V.RIG_MODE_NONE){const t=new h(e,this.position.clone(),this.getScene());return t.isRigCamera=!0,t.rigParent=this,this.cameraRigMode!==r.V.RIG_MODE_VR&&this.cameraRigMode!==r.V.RIG_MODE_WEBVR||(this.rotationQuaternion||(this.rotationQuaternion=new o._f),t._cameraRigParams={},t.rotationQuaternion=new o._f),t.mode=this.mode,t.orthoLeft=this.orthoLeft,t.orthoRight=this.orthoRight,t.orthoTop=this.orthoTop,t.orthoBottom=this.orthoBottom,t}return null}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case r.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case r.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case r.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case r.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case r.V.RIG_MODE_STEREOSCOPIC_INTERLACED:{const i=this.cameraRigMode===r.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,n=this.cameraRigMode===r.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*n,t);break}case r.V.RIG_MODE_VR:e.rotationQuaternion?(e.rotationQuaternion.copyFrom(this.rotationQuaternion),t.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.rotation.copyFrom(this.rotation),t.rotation.copyFrom(this.rotation)),e.position.copyFrom(this.position),t.position.copyFrom(this.position)}super._updateRigCameras()}_getRigCamPositionAndTarget(e,t){this.getTarget().subtractToRef(this.position,h._TargetFocalPoint),h._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);const i=h._TargetFocalPoint.addInPlace(this.position);o.y3.TranslationToRef(-i.x,-i.y,-i.z,h._TargetTransformMatrix),h._TargetTransformMatrix.multiplyToRef(o.y3.RotationAxis(t.upVector,e),h._RigCamTransformMatrix),o.y3.TranslationToRef(i.x,i.y,i.z,h._TargetTransformMatrix),h._RigCamTransformMatrix.multiplyToRef(h._TargetTransformMatrix,h._RigCamTransformMatrix),o.P.TransformCoordinatesToRef(this.position,h._RigCamTransformMatrix,t.position),t.setTarget(i)}getClassName(){return"TargetCamera"}}h._RigCamTransformMatrix=new o.y3,h._TargetTransformMatrix=new o.y3,h._TargetFocalPoint=new o.P,(0,n.gn)([(0,s.hd)()],h.prototype,"rotation",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"speed",void 0),(0,n.gn)([(0,s.RR)("lockedTargetId")],h.prototype,"lockedTarget",void 0)},2312:(e,t,i)=>{i.d(t,{c:()=>n});class n{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}},9356:(e,t,i)=>{i.d(t,{a:()=>s});var n=i(4141);class s{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new n.P(0,0,0),this._diffPositionForCollisions=new n.P(0,0,0),this._collisionResponse=!0}}},5670:(e,t,i)=>{i.d(t,{p:()=>r});var n=i(4141),s=i(708);class r{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(s.o.NormalKind))return null;let i,r=this.pickedMesh.getIndices();0===(null==r?void 0:r.length)&&(r=null);const o=n.jp.Vector3[0],a=n.jp.Vector3[1],l=n.jp.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(s.o.NormalKind);let t=r?n.P.FromArrayToRef(e,3*r[3*this.faceId],o):o.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),h=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+1],a):a.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),c=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+2],l):l.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),h=h.scale(this.bv),c=c.scale(1-this.bu-this.bv),i=new n.P(t.x+h.x+c.x,t.y+h.y+c.y,t.z+h.z+c.z)}else{const e=this.pickedMesh.getVerticesData(s.o.PositionKind),t=r?n.P.FromArrayToRef(e,3*r[3*this.faceId],o):o.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),h=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+1],a):a.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),c=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+2],l):l.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),u=t.subtract(h),d=c.subtract(h);i=n.P.Cross(u,d)}const h=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(n.jp.Matrix[0].copyFrom(i),i=n.jp.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(n.jp.Matrix[1]),i=n.jp.Matrix[1]),n.P.TransformNormalToRef(t,i,t)};if(e&&h(this.pickedMesh,i),this.ray){const t=n.jp.Vector3[0].copyFrom(i);e||h(this.pickedMesh,t),n.P.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=s.o.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 r=n.FM.FromArray(i,2*t[3*this.faceId]),o=n.FM.FromArray(i,2*t[3*this.faceId+1]),a=n.FM.FromArray(i,2*t[3*this.faceId+2]);return r=r.scale(this.bu),o=o.scale(this.bv),a=a.scale(1-this.bu-this.bv),new n.FM(r.x+o.x+a.x,r.y+o.y+a.y)}}},4892:(e,t,i)=>{i.d(t,{e:()=>n});class n{}n.UseOpenGLOrientationForUV=!1},5237:(e,t,i)=>{i.d(t,{k:()=>o});var n=i(5860),s=i(4141),r=i(1341);class o{constructor(e,t,i){this.vectors=n.B.BuildArray(8,s.P.Zero),this.center=s.P.Zero(),this.centerWorld=s.P.Zero(),this.extendSize=s.P.Zero(),this.extendSizeWorld=s.P.Zero(),this.directions=n.B.BuildArray(3,s.P.Zero),this.vectorsWorld=n.B.BuildArray(8,s.P.Zero),this.minimumWorld=s.P.Zero(),this.maximumWorld=s.P.Zero(),this.minimum=s.P.Zero(),this.maximum=s.P.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const n=e.x,r=e.y,o=e.z,a=t.x,l=t.y,h=t.z,c=this.vectors;this.minimum.copyFromFloats(n,r,o),this.maximum.copyFromFloats(a,l,h),c[0].copyFromFloats(n,r,o),c[1].copyFromFloats(a,l,h),c[2].copyFromFloats(a,r,o),c[3].copyFromFloats(n,l,o),c[4].copyFromFloats(n,r,h),c[5].copyFromFloats(a,l,o),c[6].copyFromFloats(n,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||s.y3.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=o._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),n=i.length();i.normalizeFromLength(n);const s=n*e,r=i.scaleInPlace(.5*s),a=this.center.subtractToRef(r,t[1]),l=this.center.addToRef(r,t[2]);return this.reConstruct(a,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,n=this.directions,r=this.vectorsWorld,o=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(o[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let n=0;n<8;++n){const a=r[n];s.P.TransformCoordinatesToRef(o[n],e,a),t.minimizeInPlace(a),i.maximizeInPlace(a)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}s.P.FromArrayToRef(e.m,0,n[0]),s.P.FromArrayToRef(e.m,4,n[1]),s.P.FromArrayToRef(e.m,8,n[2]),this._worldMatrix=e}isInFrustum(e){return o.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return o.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,n=t.x,s=t.y,o=t.z,a=i.x,l=i.y,h=i.z,c=e.x,u=e.y,d=e.z,p=-r.kn;return!(a-c<p||p>c-n||l-u<p||p>u-s||h-d<p||p>d-o)}intersectsSphere(e){return o.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,n=this.maximumWorld,s=i.x,r=i.y,o=i.z,a=n.x,l=n.y,h=n.z,c=e.x,u=e.y,d=e.z,p=t.x,f=t.y,_=t.z;return!(a<c||s>p||l<u||r>f||h<d||o>_)}dispose(){var e,t;null===(e=this._drawWrapperFront)||void 0===e||e.dispose(),null===(t=this._drawWrapperBack)||void 0===t||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,n){const r=o._TmpVector3[0];return s.P.ClampToRef(i,e,t,r),s.P.DistanceSquared(i,r)<=n*n}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const n=t[i];for(let t=0;t<8;++t)if(n.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let n=!0;const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){n=!1;break}if(n)return!1}return!0}}o._TmpVector3=n.B.BuildArray(3,s.P.Zero)},3722:(e,t,i)=>{i.d(t,{j:()=>u});var n=i(5860),s=i(4141),r=i(5237),o=i(6667);const a={min:0,max:0},l={min:0,max:0},h=(e,t,i)=>{const n=s.P.Dot(t.centerWorld,e),r=Math.abs(s.P.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(s.P.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(s.P.Dot(t.directions[2],e))*t.extendSize.z;i.min=n-r,i.max=n+r},c=(e,t,i)=>(h(e,t,a),h(e,i,l),!(a.min>l.max||l.min>a.max));class u{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new r.k(e,t,i),this.boundingSphere=new o.K(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=u._TmpVector3[0].copyFrom(e).subtractInPlace(t),n=u._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,n,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,n,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=s.P.Minimize(this.minimum,e),i=s.P.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=s.jp.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=s.jp.Vector3[0];return s.P.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),s.P.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!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,u._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(!o.K.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!r.k.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,n=e.boundingBox;return!!(c(i.directions[0],i,n)&&c(i.directions[1],i,n)&&c(i.directions[2],i,n)&&c(n.directions[0],i,n)&&c(n.directions[1],i,n)&&c(n.directions[2],i,n)&&c(s.P.Cross(i.directions[0],n.directions[0]),i,n)&&c(s.P.Cross(i.directions[0],n.directions[1]),i,n)&&c(s.P.Cross(i.directions[0],n.directions[2]),i,n)&&c(s.P.Cross(i.directions[1],n.directions[0]),i,n)&&c(s.P.Cross(i.directions[1],n.directions[1]),i,n)&&c(s.P.Cross(i.directions[1],n.directions[2]),i,n)&&c(s.P.Cross(i.directions[2],n.directions[0]),i,n)&&c(s.P.Cross(i.directions[2],n.directions[1]),i,n)&&c(s.P.Cross(i.directions[2],n.directions[2]),i,n))}}u._TmpVector3=n.B.BuildArray(2,s.P.Zero)},6667:(e,t,i)=>{i.d(t,{K:()=>r});var n=i(5860),s=i(4141);class r{constructor(e,t,i){this.center=s.P.Zero(),this.centerWorld=s.P.Zero(),this.minimum=s.P.Zero(),this.maximum=s.P.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const n=s.P.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*n,this._update(i||s.y3.IdentityReadOnly)}scale(e){const t=this.radius*e,i=r._TmpVector3,n=i[0].setAll(t),s=this.center.subtractToRef(n,i[1]),o=this.center.addToRef(n,i[2]);return this.reConstruct(s,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{s.P.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=r._TmpVector3[0];s.P.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let n=0;n<6;n++)if(e[n].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=s.P.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){const i=s.P.DistanceSquared(e.centerWorld,t.centerWorld),n=e.radiusWorld+t.radiusWorld;return!(n*n<i)}static CreateFromCenterAndRadius(e,t,i){this._TmpVector3[0].copyFrom(e),this._TmpVector3[1].copyFromFloats(0,0,t),this._TmpVector3[2].copyFrom(e),this._TmpVector3[0].addInPlace(this._TmpVector3[1]),this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);const n=new r(this._TmpVector3[0],this._TmpVector3[2]);return n._worldMatrix=i||s.y3.Identity(),n}}r._TmpVector3=n.B.BuildArray(3,s.P.Zero)},450:(e,t,i)=>{i.d(t,{z:()=>c});var n=i(5860),s=i(4141),r=i(5670),o=i(2312),a=i(1057),l=i(2704),h=i(1431);class c{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new c(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const n=c._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),s=c._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let r,o,a,l,h=0,u=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<n.x||this.origin.x>s.x)return!1}else if(r=1/this.direction.x,o=(n.x-this.origin.x)*r,a=(s.x-this.origin.x)*r,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),u=Math.min(a,u),h>u)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<n.y||this.origin.y>s.y)return!1}else if(r=1/this.direction.y,o=(n.y-this.origin.y)*r,a=(s.y-this.origin.y)*r,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),u=Math.min(a,u),h>u)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<n.z||this.origin.z>s.z)return!1}else if(r=1/this.direction.z,o=(n.z-this.origin.z)*r,a=(s.z-this.origin.z)*r,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),u=Math.min(a,u),h>u)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,n=e.center.y-this.origin.y,s=e.center.z-this.origin.z,r=i*i+n*n+s*s,o=e.radius+t,a=o*o;if(r<=a)return!0;const l=i*this.direction.x+n*this.direction.y+s*this.direction.z;return!(l<0)&&r-l*l<=a}intersectsTriangle(e,t,i){const n=c._TmpVector3[0],r=c._TmpVector3[1],a=c._TmpVector3[2],l=c._TmpVector3[3],h=c._TmpVector3[4];t.subtractToRef(e,n),i.subtractToRef(e,r),s.P.CrossToRef(this.direction,r,a);const u=s.P.Dot(n,a);if(0===u)return null;const d=1/u;this.origin.subtractToRef(e,l);const p=s.P.Dot(l,a)*d;if(p<0||p>1)return null;s.P.CrossToRef(l,n,h);const f=s.P.Dot(this.direction,h)*d;if(f<0||p+f>1)return null;const _=s.P.Dot(r,h)*d;return _>this.length?null:new o.c(1-p-f,p,_)}intersectsPlane(e){let t;const i=s.P.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const n=s.P.Dot(e.normal,this.origin);return t=(-e.d-n)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new s.P(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new s.P(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new s.P(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t){const i=s.jp.Matrix[0];return e.getWorldMatrix().invertToRef(i),this._tmpRay?c.TransformToRef(this,i,this._tmpRay):this._tmpRay=c.Transform(this,i),e.intersects(this._tmpRay,t)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let n=0;n<e.length;n++){const s=this.intersectsMesh(e[n],t);s.hit&&i.push(s)}return i.sort(this._comparePickingInfo),i}_comparePickingInfo(e,t){return e.distance<t.distance?-1:e.distance>t.distance?1:0}intersectionSegment(e,t,i){const n=this.origin,r=s.jp.Vector3[0],o=s.jp.Vector3[1],a=s.jp.Vector3[2],l=s.jp.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(c._Rayl,a),n.addToRef(a,o),e.subtractToRef(n,l);const h=s.P.Dot(r,r),u=s.P.Dot(r,a),d=s.P.Dot(a,a),p=s.P.Dot(r,l),f=s.P.Dot(a,l),_=h*d-u*u;let m,g,v=_,y=_;_<c._Smallnum?(m=0,v=1,g=f,y=d):(m=u*f-d*p,g=h*f-u*p,m<0?(m=0,g=f,y=d):m>v&&(m=v,g=f+u,y=d)),g<0?(g=0,-p<0?m=0:-p>h?m=v:(m=-p,v=h)):g>y&&(g=y,-p+u<0?m=0:-p+u>h?m=v:(m=-p+u,v=h));const x=Math.abs(m)<c._Smallnum?0:m/v,b=Math.abs(g)<c._Smallnum?0:g/y,T=s.jp.Vector3[4];a.scaleToRef(b,T);const S=s.jp.Vector3[5];r.scaleToRef(x,S),S.addInPlace(l);const E=s.jp.Vector3[6];return S.subtractToRef(T,E),b>0&&b<=this.length&&E.lengthSquared()<i*i?S.length():-1}update(e,t,i,n,r,o,a,l=!1){if(l){c._RayDistant||(c._RayDistant=c.Zero()),c._RayDistant.unprojectRayToRef(e,t,i,n,s.y3.IdentityReadOnly,o,a);const l=s.jp.Matrix[0];r.invertToRef(l),c.TransformToRef(c._RayDistant,l,this)}else this.unprojectRayToRef(e,t,i,n,r,o,a);return this}static Zero(){return new c(s.P.Zero(),s.P.Zero())}static CreateNew(e,t,i,n,s,r,o){return c.Zero().update(e,t,i,n,s,r,o)}static CreateNewFromTo(e,t,i=s.y3.IdentityReadOnly){const n=t.subtract(e),r=Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z);return n.normalize(),c.Transform(new c(e,n,r),i)}static Transform(e,t){const i=new c(new s.P(0,0,0),new s.P(0,0,0));return c.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){s.P.TransformCoordinatesToRef(e.origin,t,i.origin),s.P.TransformNormalToRef(e.direction,t,i.direction),i.length=e.length;const n=i.direction,r=n.length();if(0!==r&&1!==r){const e=1/r;n.x*=e,n.y*=e,n.z*=e,i.length*=r}}unprojectRayToRef(e,t,i,n,r,o,a){var l;const c=s.jp.Matrix[0];r.multiplyToRef(o,c),c.multiplyToRef(a,c),c.invert();const u=s.jp.Vector3[0];u.x=e/i*2-1,u.y=-(t/n*2-1),u.z=(null===(l=h.l.LastCreatedEngine)||void 0===l?void 0:l.isNDCHalfZRange)?0:-1;const d=s.jp.Vector3[1].copyFromFloats(u.x,u.y,1-1e-8),p=s.jp.Vector3[2],f=s.jp.Vector3[3];s.P._UnprojectFromInvertedMatrixToRef(u,c,p),s.P._UnprojectFromInvertedMatrixToRef(d,c,f),this.origin.copyFrom(p),f.subtractToRef(p,this.direction),this.direction.normalize()}}c._TmpVector3=n.B.BuildArray(6,s.P.Zero),c._RayDistant=c.Zero(),c._Smallnum=1e-8,c._Rayl=1e9,a.x.prototype.createPickingRay=function(e,t,i,n,s=!1){const r=c.Zero();return this.createPickingRayToRef(e,t,i,r,n,s),r},a.x.prototype.createPickingRayToRef=function(e,t,i,n,r,o=!1,a=!1){const l=this.getEngine();if(!r){if(!this.activeCamera)return this;r=this.activeCamera}const h=r.viewport.toGlobal(l.getRenderWidth(),l.getRenderHeight());return e=e/l.getHardwareScalingLevel()-h.x,t=t/l.getHardwareScalingLevel()-(l.getRenderHeight()-h.y-h.height),n.update(e,t,h.width,h.height,i||s.y3.IdentityReadOnly,o?s.y3.IdentityReadOnly:r.getViewMatrix(),r.getProjectionMatrix(),a),this},a.x.prototype.createPickingRayInCameraSpace=function(e,t,i){const n=c.Zero();return this.createPickingRayInCameraSpaceToRef(e,t,n,i),n},a.x.prototype.createPickingRayInCameraSpaceToRef=function(e,t,i,n){if(!r.p)return this;const o=this.getEngine();if(!n){if(!this.activeCamera)throw new Error("Active camera not set");n=this.activeCamera}const a=n.viewport.toGlobal(o.getRenderWidth(),o.getRenderHeight()),l=s.y3.Identity();return e=e/o.getHardwareScalingLevel()-a.x,t=t/o.getHardwareScalingLevel()-(o.getRenderHeight()-a.y-a.height),i.update(e,t,a.width,a.height,l,l,n.getProjectionMatrix()),this},a.x.prototype._internalPickForMesh=function(e,t,i,n,s,r,o,a){const l=t(n,i.enableDistantPicking),h=i.intersects(l,s,o,r,n,a);return h&&h.hit?!s&&null!=e&&h.distance>=e.distance?null:h:null},a.x.prototype._internalPick=function(e,t,i,n,o){let a=null;const l=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),h=this.cameraToUseForPointers||this.activeCamera;for(let r=0;r<this.meshes.length;r++){const c=this.meshes[r];if(t){if(!t(c))continue}else if(!c.isEnabled()||!c.isVisible||!c.isPickable)continue;const u=l&&c.isWorldMatrixCameraDependent(),d=c.computeWorldMatrix(u,h);if(c.hasThinInstances&&c.thinInstanceEnablePicking){const t=this._internalPickForMesh(a,e,c,d,!0,!0,o);if(t){if(n)return t;const r=s.jp.Matrix[1],l=c.thinInstanceGetWorldMatrices();for(let t=0;t<l.length;t++){l[t].multiplyToRef(d,r);const s=this._internalPickForMesh(a,e,c,r,i,n,o,!0);if(s&&(a=s,a.thinInstanceIndex=t,i))return a}}}else{const t=this._internalPickForMesh(a,e,c,d,i,n,o);if(t&&(a=t,i))return a}}return a||new r.p},a.x.prototype._internalMultiPick=function(e,t,i){if(!r.p)return null;const n=new Array,o=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),a=this.cameraToUseForPointers||this.activeCamera;for(let r=0;r<this.meshes.length;r++){const l=this.meshes[r];if(t){if(!t(l))continue}else if(!l.isEnabled()||!l.isVisible||!l.isPickable)continue;const h=o&&l.isWorldMatrixCameraDependent(),c=l.computeWorldMatrix(h,a);if(l.hasThinInstances&&l.thinInstanceEnablePicking){if(this._internalPickForMesh(null,e,l,c,!0,!0,i)){const t=s.jp.Matrix[1],r=l.thinInstanceGetWorldMatrices();for(let s=0;s<r.length;s++){r[s].multiplyToRef(c,t);const o=this._internalPickForMesh(null,e,l,t,!1,!1,i,!0);o&&(o.thinInstanceIndex=s,n.push(o))}}}else{const t=this._internalPickForMesh(null,e,l,c,!1,!1,i);t&&n.push(t)}}return n},a.x.prototype.pickWithBoundingInfo=function(e,t,i,n,o){if(!r.p)return null;const a=this._internalPick((i=>(this._tempPickingRay||(this._tempPickingRay=c.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,o||null),this._tempPickingRay)),i,n,!0);return a&&(a.ray=this.createPickingRay(e,t,s.y3.Identity(),o||null)),a},Object.defineProperty(a.x.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),a.x.prototype.pick=function(e,t,i,n,r,o,a=!1){const l=this._internalPick(((i,n)=>(this._tempPickingRay||(this._tempPickingRay=c.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null,!1,n),this._tempPickingRay)),i,n,!1,o);return l&&(l.ray=this.createPickingRay(e,t,s.y3.Identity(),r||null)),l},a.x.prototype.pickWithRay=function(e,t,i,n){const r=this._internalPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=s.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=c.Zero()),c.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i,!1,n);return r&&(r.ray=e),r},a.x.prototype.multiPick=function(e,t,i,n,s){return this._internalMultiPick((i=>this.createPickingRay(e,t,i,n||null)),i,s)},a.x.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=s.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=c.Zero()),c.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i)},l.V.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new c(s.P.Zero(),s.P.Zero(),e),e,t,i)},l.V.prototype.getForwardRayToRef=function(e,t=100,i,n){return i||(i=this.getWorldMatrix()),e.length=t,n?e.origin.copyFrom(n):e.origin.copyFrom(this.position),s.jp.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),s.P.TransformNormalToRef(s.jp.Vector3[2],i,s.jp.Vector3[3]),s.P.NormalizeToRef(s.jp.Vector3[3],e.direction),e}},3255:(e,t,i)=>{var n,s,r,o,a,l,h;i.d(t,{$i:()=>l,D_:()=>h,FP:()=>r,Fz:()=>s,V7:()=>o,Yi:()=>n,s2:()=>a}),function(e){e[e.Generic=0]="Generic",e[e.Keyboard=1]="Keyboard",e[e.Mouse=2]="Mouse",e[e.Touch=3]="Touch",e[e.DualShock=4]="DualShock",e[e.Xbox=5]="Xbox",e[e.Switch=6]="Switch",e[e.DualSense=7]="DualSense"}(n||(n={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.Move=12]="Move"}(s||(s={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.DeltaHorizontal=10]="DeltaHorizontal",e[e.DeltaVertical=11]="DeltaVertical"}(r||(r={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(o||(o={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Create=8]="Create",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(a||(a={})),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.LT=6]="LT",e[e.RT=7]="RT",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.LStickXAxis=17]="LStickXAxis",e[e.LStickYAxis=18]="LStickYAxis",e[e.RStickXAxis=19]="RStickXAxis",e[e.RStickYAxis=20]="RStickYAxis"}(l||(l={})),function(e){e[e.B=0]="B",e[e.A=1]="A",e[e.Y=2]="Y",e[e.X=3]="X",e[e.L=4]="L",e[e.R=5]="R",e[e.ZL=6]="ZL",e[e.ZR=7]="ZR",e[e.Minus=8]="Minus",e[e.Plus=9]="Plus",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.Capture=17]="Capture",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(h||(h={}))},7967:(e,t,i)=>{i.d(t,{p:()=>s});var n=i(5757);class s{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new n.y$,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}},3739:(e,t,i)=>{i.d(t,{U:()=>f});var n=i(3255),s=i(5757),r=i(2272);class o{static CreateDeviceEvent(e,t,i,s,r,o,a){switch(e){case n.Yi.Keyboard:return this._CreateKeyboardEvent(i,s,r,o);case n.Yi.Mouse:if(i===n.Fz.MouseWheelX||i===n.Fz.MouseWheelY||i===n.Fz.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,r,o);case n.Yi.Touch:return this._CreatePointerEvent(e,t,i,s,r,o,a);default:throw`Unable to generate event for device ${n.Yi[e]}`}}static _CreatePointerEvent(e,t,i,s,r,o,a){const l=this._CreateMouseEvent(e,t,i,s,r,o);return e===n.Yi.Mouse?(l.deviceType=n.Yi.Mouse,l.pointerId=1,l.pointerType="mouse"):(l.deviceType=n.Yi.Touch,l.pointerId=null!=a?a:t,l.pointerType="touch"),i===n.Fz.Move?l.type="pointermove":i>=n.Fz.LeftClick&&i<=n.Fz.RightClick&&(l.type=1===s?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,o,a){const l=this._CreateMouseEvent(e,t,i,s,o,a);switch(l.pointerId=1,l.type="wheel",l.deltaMode=r.G.DOM_DELTA_PIXEL,l.deltaX=0,l.deltaY=0,l.deltaZ=0,i){case n.Fz.MouseWheelX:l.deltaX=s;break;case n.Fz.MouseWheelY:l.deltaY=s;break;case n.Fz.MouseWheelZ:l.deltaZ=s}return l}static _CreateMouseEvent(e,t,i,s,r,o){const a=this._CreateEvent(o),l=r.pollInput(e,t,n.Fz.Horizontal),h=r.pollInput(e,t,n.Fz.Vertical);return o?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-o.getBoundingClientRect().x,a.offsetY=a.movementY-o.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,n.FP.DeltaHorizontal),a.movementY=r.pollInput(e,t,n.FP.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=n.Yi.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(n.Yi.Keyboard),s=i&&1===t.pollInput(n.Yi.Keyboard,0,18),r=i&&1===t.pollInput(n.Yi.Keyboard,0,17),o=i&&(1===t.pollInput(n.Yi.Keyboard,0,91)||1===t.pollInput(n.Yi.Keyboard,0,92)||1===t.pollInput(n.Yi.Keyboard,0,93)),a=i&&1===t.pollInput(n.Yi.Keyboard,0,16);e.altKey=s,e.ctrlKey=r,e.metaKey=o,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class a{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,n,s)=>{const r=o.CreateDeviceEvent(e,t,n,s,this);i(e,t,r)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===n.Yi.Mouse||e===n.Yi.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}var l=i(6797),h=i(7257);const c=Object.keys(n.Fz).length/2;class u{constructor(e,t,i,n){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=h.w1.IsSafari(),this._usingMacOS=(0,l.up)()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=l.MZ.IsNavigatorAvailable()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=h.w1.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=n,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 ${n.Yi[e]}`;e>=n.Yi.DualShock&&e<=n.Yi.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(void 0===r)throw`Unable to find input ${i} for device ${n.Yi[e]} in slot ${t}`;return i===n.Fz.Move&&h.w1.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=null==this?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e<i.length;e++)i[e]=0}this._elementToAttachTo=e,this._elementToAttachTo.tabIndex=-1!==this._elementToAttachTo.tabIndex?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._eventsAttached=!0,this._checkForConnectedDevices()}}_disableEvents(){this._elementToAttachTo&&(this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1}_checkForConnectedDevices(){if(navigator.getGamepads){const e=navigator.getGamepads();for(const t of e)t&&this._addGamePad(t)}"function"==typeof matchMedia&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(n.Yi.Mouse,0,0,0)}_addGamePad(e){const t=this._getGamepadDeviceType(e.id),i=e.index;this._gamepads=this._gamepads||new Array(e.index+1),this._registerDevice(t,i,e.buttons.length+e.axes.length),this._gamepads[i]=t}_addPointerDevice(e,t,i,n){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,c);const s=this._inputs[e][t];s[0]=i,s[1]=n}_registerDevice(e,t,i){if(void 0===t)throw`Unable to register device ${n.Yi[e]} to undefined slot.`;if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){const n=new Array(i);n.fill(0),this._inputs[e][t]=n,this._onDeviceConnected(e,t)}}_unregisterDevice(e,t){this._inputs[e][t]&&(delete this._inputs[e][t],this._onDeviceDisconnected(e,t))}_handleKeyActions(){this._keyboardDownEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(n.Yi.Keyboard,0,255));const t=this._inputs[n.Yi.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(n.Yi.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(n.Yi.Keyboard,0,255));const t=this._inputs[n.Yi.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=o.CreateDeviceEvent(n.Yi.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(n.Yi.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(n.Yi.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[n.Yi.Keyboard][0];for(let t=0;t<e.length;t++)if(0!==e[t]){e[t]=0;const i=o.CreateDeviceEvent(n.Yi.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(n.Yi.Keyboard,0,i)}this._usingMacOS&&this._metaKeys.splice(0,this._metaKeys.length)}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)}_handlePointerActions(){this._maxTouchPoints=l.MZ.IsNavigatorAvailable()&&navigator.maxTouchPoints||2,this._activeTouchIds||(this._activeTouchIds=new Array(this._maxTouchPoints));for(let e=0;e<this._maxTouchPoints;e++)this._activeTouchIds[e]=-1;this._pointerMoveEvent=e=>{const t=this._getPointerType(e),i=t===n.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=e;r.inputIndex=n.Fz.Move,s[n.Fz.Horizontal]=e.clientX,s[n.Fz.Vertical]=e.clientY,void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===n.Yi.Mouse?0:e.pointerId;if(t===n.Yi.Touch){const t=this._activeTouchIds.indexOf(-1);if(!(t>=0))return void h.w1.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===n.Yi.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=s[n.Fz.Horizontal],o=s[n.Fz.Vertical];if(t===n.Yi.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[n.Fz.Horizontal]=e.clientX,s[n.Fz.Vertical]=e.clientY,s[e.button+2]=1;const a=e;a.inputIndex=e.button+2,this._onInputChanged(t,i,a),r===e.clientX&&o===e.clientY||(a.inputIndex=n.Fz.Move,this._onInputChanged(t,i,a))}},this._pointerUpEvent=e=>{var t,i,s,r,o;const a=this._getPointerType(e),l=a===n.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(a===n.Yi.Touch){if(-1===l)return;this._activeTouchIds[l]=-1}const h=null===(t=this._inputs[a])||void 0===t?void 0:t[l];if(h&&0!==h[e.button+2]){const t=h[n.Fz.Horizontal],c=h[n.Fz.Vertical];h[n.Fz.Horizontal]=e.clientX,h[n.Fz.Vertical]=e.clientY,h[e.button+2]=0;const u=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),t===e.clientX&&c===e.clientY||(u.inputIndex=n.Fz.Move,this._onInputChanged(a,l,u)),u.inputIndex=e.button+2,a===n.Yi.Mouse&&this._mouseId>=0&&(null===(s=(i=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(i,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&(null===(o=(r=this._elementToAttachTo).hasPointerCapture)||void 0===o?void 0:o.call(r,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(a,l,u),a===n.Yi.Touch&&this._onDeviceDisconnected(a,l)}},this._pointerCancelEvent=e=>{var t,i,s,r;if("mouse"===e.pointerType){const e=this._inputs[n.Yi.Mouse][0];this._mouseId>=0&&(null===(i=(t=this._elementToAttachTo).hasPointerCapture)||void 0===i?void 0:i.call(t,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=n.Fz.LeftClick;t<=n.Fz.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=o.CreateDeviceEvent(n.Yi.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(n.Yi.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);(null===(r=(s=this._elementToAttachTo).hasPointerCapture)||void 0===r?void 0:r.call(s,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[n.Yi.Touch][t][n.Fz.LeftClick]=0;const i=o.CreateDeviceEvent(n.Yi.Touch,t,n.Fz.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(n.Yi.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(n.Yi.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(e){}this._pointerBlurEvent=()=>{var e,t,i,s,r;if(this.isDeviceAvailable(n.Yi.Mouse)){const i=this._inputs[n.Yi.Mouse][0];this._mouseId>=0&&(null===(t=(e=this._elementToAttachTo).hasPointerCapture)||void 0===t?void 0:t.call(e,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let e=n.Fz.LeftClick;e<=n.Fz.BrowserForward;e++)if(1===i[e]){i[e]=0;const t=o.CreateDeviceEvent(n.Yi.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(n.Yi.Mouse,0,t)}}if(this.isDeviceAvailable(n.Yi.Touch)){const e=this._inputs[n.Yi.Touch];for(let t=0;t<this._activeTouchIds.length;t++){const a=this._activeTouchIds[t];if((null===(s=(i=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(i,a))&&this._elementToAttachTo.releasePointerCapture(a),-1!==a&&1===(null===(r=e[t])||void 0===r?void 0:r[n.Fz.LeftClick])){e[t][n.Fz.LeftClick]=0;const i=o.CreateDeviceEvent(n.Yi.Touch,t,n.Fz.LeftClick,0,this,this._elementToAttachTo,a);this._onInputChanged(n.Yi.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(n.Yi.Touch,t)}}}},this._pointerWheelEvent=e=>{const t=n.Yi.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,c));const i=this._inputs[t][0];if(i){i[n.Fz.MouseWheelX]=e.deltaX||0,i[n.Fz.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[n.Fz.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[n.Fz.MouseWheelX]&&(s.inputIndex=n.Fz.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[n.Fz.MouseWheelY]&&(s.inputIndex=n.Fz.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[n.Fz.MouseWheelZ]&&(s.inputIndex=n.Fz.MouseWheelZ,this._onInputChanged(t,0,s))}},this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(n.Yi.Mouse)){const e=this._inputs[n.Yi.Mouse][0];e[n.Fz.MouseWheelX]=0,e[n.Fz.MouseWheelY]=0,e[n.Fz.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const n=navigator.getGamepads()[t];if(n&&e===this._gamepads[t]){const s=this._inputs[e][t];i>=n.buttons.length?s[i]=n.axes[i-n.buttons.length].valueOf():s[i]=n.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?n.Yi.DualSense:n.Yi.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?n.Yi.Xbox:-1!==e.indexOf("057e")?n.Yi.Switch:n.Yi.Generic}_getPointerType(e){let t=n.Yi.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=n.Yi.Touch),t}}var d=i(7967);class p{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t<this._devices.length;t++){const i=this._devices[t];for(const n in i){const i=+n;e._addDevice(new d.p(this._deviceInputSystem,t,i))}}this._registeredManagers.push(e)},this.unregisterManager=e=>{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(n.Yi).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const n=new d.p(this._deviceInputSystem,e,t);i._addDevice(n)}},s=(e,t)=>{var i;(null===(i=this._devices[e])||void 0===i?void 0:i[t])&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},r=(e,t,i)=>{if(i)for(const n of this._registeredManagers)n._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new a(i,s,r):this._deviceInputSystem=new u(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class f{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(n.Yi).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new p(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new s.y$((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new s.y$,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,n;const s=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(s),(null===(n=this._devices[e])||void 0===n?void 0:n[t])&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var n,s;null===(s=null===(n=this._devices[e])||void 0===n?void 0:n[t])||void 0===s||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case n.Yi.Keyboard:case n.Yi.Mouse:this._firstDevice[e]=0;break;case n.Yi.Touch:case n.Yi.DualSense:case n.Yi.DualShock:case n.Yi.Xbox:case n.Yi.Switch:case n.Yi.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i<t.length;i++)if(t[i]){this._firstDevice[e]=i;break}break}}}}},9347:(e,t,i)=>{var n=i(3230);n.B.prototype.setAlphaConstants=function(e,t,i,n){this._alphaState.setAlphaBlendConstants(e,t,i,n)},n.B.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},n.B.prototype.getAlphaMode=function(){return this._alphaMode},n.B.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},n.B.prototype.getAlphaEquation=function(){return this._alphaEquation}},2477:(e,t,i)=>{var n=i(3230),s=i(6202),r=i(2722),o=i(5661),a=i(1983);n.B.prototype._createDepthStencilCubeTexture=function(e,t,i){const n=new s.l(this,s.S.DepthStencil);if(n.isCube=!0,1===this.webGLVersion)return r.Y.Error("Depth cube texture is not supported by WebGL 1."),n;const o={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},a=this._gl;this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,n,!0),this._setupDepthStencilTexture(n,e,o.generateStencil,o.bilinearFiltering,o.comparisonFunction),i._depthStencilTexture=n,i._depthStencilTextureWithStencil=o.generateStencil;for(let t=0;t<6;t++)o.generateStencil?a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,a.DEPTH24_STENCIL8,e,e,0,a.DEPTH_STENCIL,a.UNSIGNED_INT_24_8,null):a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,a.DEPTH_COMPONENT24,e,e,0,a.DEPTH_COMPONENT,a.UNSIGNED_INT,null);return this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(n),n},n.B.prototype._partialLoadFile=function(e,t,i,n,s=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&n(i)}),void 0,void 0,!0,((e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)}))},n.B.prototype._cascadeLoadFiles=function(e,t,i,n=null){const s=[];s._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,s,t,n)},n.B.prototype._cascadeLoadImgs=function(e,t,i,n,s=null,r){const o=[];o._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(n[a],a,o,e,t,i,s,r)},n.B.prototype._partialLoadImg=function(e,t,i,n,s,r,l=null,h){const c=(0,a.f)();(0,o.r6)(e,(e=>{i[t]=e,i._internalCount++,n&&n.removePendingData(c),6===i._internalCount&&r&&r(s,i)}),((e,t)=>{n&&n.removePendingData(c),l&&l(e,t)}),n?n.offlineProvider:null,h),n&&n.addPendingData(c)},n.B.prototype._setCubeMapTextureParams=function(e,t,i){const n=this._gl;n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MIN_FILTER,t?n.LINEAR_MIPMAP_LINEAR:n.LINEAR),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null)},n.B.prototype.createCubeTextureBase=function(e,t,i,o,a=null,l=null,h,c=null,u=!1,d=0,p=0,f=null,_=null,m=null,g=!1){const v=f||new s.l(this,s.S.Cube);v.isCube=!0,v.url=e,v.generateMipMaps=!o,v._lodGenerationScale=d,v._lodGenerationOffset=p,v._useSRGBBuffer=!!g&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!o),v!==f&&(v.label=e.substring(0,60)),this._doNotHandleContextLost||(v._extension=c,v._files=i);const y=e;this._transformTextureUrl&&!f&&(e=this._transformTextureUrl(e));const x=e.split("?")[0],b=x.lastIndexOf("."),T=c||(b>-1?x.substring(b).toLowerCase():"");let S=null;for(const e of n.B._TextureLoaders)if(e.canLoad(T)){S=e;break}const E=(n,s)=>{e===y?l&&n&&l(n.status+" "+n.statusText,s):(r.Y.Warn(`Failed to load ${e}, falling back to the ${y}`),this.createCubeTextureBase(y,t,i,!!o,a,l,h,c,u,d,p,v,_,m,g))};if(S){const n=e=>{_&&_(v,e),S.loadCubeData(e,v,u,a,l)};i&&6===i.length?S.supportCascades?this._cascadeLoadFiles(t,(e=>n(e.map((e=>new Uint8Array(e))))),i,l):l?l("Textures type does not support cascades."):r.Y.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,E)}else{if(!i)throw new Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(t,v,((e,t)=>{m&&m(e,t)}),i,l)}return this._internalTexturesCache.push(v),v},n.B.prototype.createCubeTexture=function(e,t,i,s,o=null,a=null,l,h=null,c=!1,u=0,d=0,p=null,f,_=!1){const m=this._gl;return this.createCubeTextureBase(e,t,i,!!s,o,a,l,h,c,u,d,p,(e=>this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?n.B.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,a=i,h=[m.TEXTURE_CUBE_MAP_POSITIVE_X,m.TEXTURE_CUBE_MAP_POSITIVE_Y,m.TEXTURE_CUBE_MAP_POSITIVE_Z,m.TEXTURE_CUBE_MAP_NEGATIVE_X,m.TEXTURE_CUBE_MAP_NEGATIVE_Y,m.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const c=l?this._getInternalFormat(l,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:m.RGBA;let u=l?this._getInternalFormat(l):m.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(u=c);for(let e=0;e<h.length;e++)if(t[e].width!==i||t[e].height!==a){if(this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext)return void r.Y.Warn("Cannot create canvas to resize texture.");this._workingCanvas.width=i,this._workingCanvas.height=a,this._workingContext.drawImage(t[e],0,0,t[e].width,t[e].height,0,0,i,a),m.texImage2D(h[e],0,c,u,m.UNSIGNED_BYTE,this._workingCanvas)}else m.texImage2D(h[e],0,c,u,m.UNSIGNED_BYTE,t[e]);s||m.generateMipmap(m.TEXTURE_CUBE_MAP),this._setCubeMapTextureParams(e,!s),e.width=i,e.height=a,e.isReady=!0,l&&(e.format=l),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),o&&o()}),!!_)}},3742:(e,t,i)=>{var n=i(3230);n.B.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let n;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),n=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,n,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},n.B.prototype.updateDynamicVertexBuffer=function(e,t,i,n){this.bindArrayBuffer(e),void 0===i&&(i=0);const s=t.byteLength||t.length;void 0===n||n>=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+n)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,n):new Uint8Array(t.buffer,t.byteOffset+i,n),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()}},6914:(e,t,i)=>{var n=i(3230),s=i(6202);n.B.prototype.createDynamicTexture=function(e,t,i,r){const o=new s.l(this,s.S.Dynamic);return o.baseWidth=e,o.baseHeight=t,i&&(e=this.needPOTTextures?n.B.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?n.B.GetExponentOfTwo(t,this._caps.maxTextureSize):t),o.width=e,o.height=t,o.isReady=!1,o.generateMipMaps=i,o.samplingMode=r,this.updateTextureSamplingMode(r,o),this._internalTexturesCache.push(o),o},n.B.prototype.updateDynamicTexture=function(e,t,i,n=!1,s,r=!1,o=!1){if(!e)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,r);this._unpackFlipY(void 0===i?e.invertY:i),n&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(s||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);a.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),n&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0}},6599:(e,t,i)=>{var n=i(6202),s=i(2722),r=i(7257),o=i(3230);function a(e,t,i,n){let s,r=1;1===n?s=new Float32Array(t*i*4):2===n?(s=new Uint16Array(t*i*4),r=15360):s=7===n?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let n=0;n<t;n++)for(let o=0;o<i;o++){const i=3*(o*t+n),a=4*(o*t+n);s[a+0]=e[i+0],s[a+1]=e[i+1],s[a+2]=e[i+2],s[a+3]=r}return s}function l(e){return function(t,i,s,r,o,a,l,h,c=null,u=0){const d=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,p=e?n.S.Raw3D:n.S.Raw2DArray,f=new n.l(this,p);f.baseWidth=i,f.baseHeight=s,f.baseDepth=r,f.width=i,f.height=s,f.depth=r,f.format=o,f.type=u,f.generateMipMaps=a,f.samplingMode=h,e?f.is3D=!0:f.is2DArray=!0,this._doNotHandleContextLost||(f._bufferView=t),e?this.updateRawTexture3D(f,t,o,l,c,u):this.updateRawTexture2DArray(f,t,o,l,c,u),this._bindTextureDirectly(d,f,!0);const _=this._getSamplingParameters(h,a);return this._gl.texParameteri(d,this._gl.TEXTURE_MAG_FILTER,_.mag),this._gl.texParameteri(d,this._gl.TEXTURE_MIN_FILTER,_.min),a&&this._gl.generateMipmap(d),this._bindTextureDirectly(d,null),this._internalTexturesCache.push(f),f}}function h(e){return function(t,i,n,s,r=null,o=0){const a=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,l=this._getWebGLTextureType(o),h=this._getInternalFormat(n),c=this._getRGBABufferInternalSizedFormat(o,n);this._bindTextureDirectly(a,t,!0),this._unpackFlipY(void 0===s||!!s),this._doNotHandleContextLost||(t._bufferView=i,t.format=n,t.invertY=s,t._compression=r),t.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&i?this._gl.compressedTexImage3D(a,0,this.getCaps().s3tc[r],t.width,t.height,t.depth,0,i):this._gl.texImage3D(a,0,c,t.width,t.height,t.depth,0,h,l,i),t.generateMipMaps&&this._gl.generateMipmap(a),this._bindTextureDirectly(a,null),t.isReady=!0}}o.B.prototype.updateRawTexture=function(e,t,i,n,s=null,r=0,o=!1){if(!e)return;const a=this._getRGBABufferInternalSizedFormat(r,i,o),l=this._getInternalFormat(i),h=this._getWebGLTextureType(r);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=r,e.invertY=n,e._compression=s),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},o.B.prototype.createRawTexture=function(e,t,i,s,r,o,a,l=null,h=0,c=0,u=!1){const d=new n.l(this,n.S.Raw);d.baseWidth=t,d.baseHeight=i,d.width=t,d.height=i,d.format=s,d.generateMipMaps=r,d.samplingMode=a,d.invertY=o,d._compression=l,d.type=h,d._useSRGBBuffer=this._getUseSRGBBuffer(u,!r),this._doNotHandleContextLost||(d._bufferView=e),this.updateRawTexture(d,e,s,o,l,h,d._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,d,!0);const p=this._getSamplingParameters(a,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,p.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,p.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(d),d},o.B.prototype.createRawCubeTexture=function(e,t,i,o,a,l,h,c=null){const u=this._gl,d=new n.l(this,n.S.CubeRaw);d.isCube=!0,d.format=i,d.type=o,this._doNotHandleContextLost||(d._bufferViewArray=e);const p=this._getWebGLTextureType(o);let f=this._getInternalFormat(i);f===u.RGB&&(f=u.RGBA),p!==u.FLOAT||this._caps.textureFloatLinearFiltering?p!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?p!==u.FLOAT||this._caps.textureFloatRender?p!==u.HALF_FLOAT||this._caps.colorBufferFloat||(a=!1,s.Y.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(a=!1,s.Y.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(a=!1,h=1,s.Y.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(a=!1,h=1,s.Y.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));const _=t,m=_;if(d.width=_,d.height=m,d.invertY=l,d._compression=c,!this.needPOTTextures||r.w1.IsExponentOfTwo(d.width)&&r.w1.IsExponentOfTwo(d.height)||(a=!1),e)this.updateRawCubeTexture(d,e,i,o,l,c);else{const e=this._getRGBABufferInternalSizedFormat(o),t=0;this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,d,!0);for(let i=0;i<6;i++)c?u.compressedTexImage2D(u.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,this.getCaps().s3tc[c],d.width,d.height,0,void 0):u.texImage2D(u.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,e,d.width,d.height,0,f,p,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,d,!0),e&&a&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const g=this._getSamplingParameters(h,a);return u.texParameteri(u.TEXTURE_CUBE_MAP,u.TEXTURE_MAG_FILTER,g.mag),u.texParameteri(u.TEXTURE_CUBE_MAP,u.TEXTURE_MIN_FILTER,g.min),u.texParameteri(u.TEXTURE_CUBE_MAP,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(u.TEXTURE_CUBE_MAP,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,null),d.generateMipMaps=a,d.samplingMode=h,d.isReady=!0,d},o.B.prototype.updateRawCubeTexture=function(e,t,i,n,s,o=null,l=0){e._bufferViewArray=t,e.format=i,e.type=n,e.invertY=s,e._compression=o;const h=this._gl,c=this._getWebGLTextureType(n);let u=this._getInternalFormat(i);const d=this._getRGBABufferInternalSizedFormat(n);let p=!1;u===h.RGB&&(u=h.RGBA,p=!0),this._bindTextureDirectly(h.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===s||!!s),e.width%4!=0&&h.pixelStorei(h.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let s=t[i];o?h.compressedTexImage2D(h.TEXTURE_CUBE_MAP_POSITIVE_X+i,l,this.getCaps().s3tc[o],e.width,e.height,0,s):(p&&(s=a(s,e.width,e.height,n)),h.texImage2D(h.TEXTURE_CUBE_MAP_POSITIVE_X+i,l,d,e.width,e.height,0,u,c,s))}(!this.needPOTTextures||r.w1.IsExponentOfTwo(e.width)&&r.w1.IsExponentOfTwo(e.height))&&e.generateMipMaps&&0===l&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},o.B.prototype.createRawCubeTextureFromUrl=function(e,t,i,n,s,r,o,l,h=null,c=null,u=3,d=!1){const p=this._gl,f=this.createRawCubeTexture(null,i,n,s,!r,d,u,null);null==t||t.addPendingData(f),f.url=e,f.isReady=!1,this._internalTexturesCache.push(f);const _=e=>{const i=f.width,r=o(e);if(r){if(l){const e=this._getWebGLTextureType(s);let t=this._getInternalFormat(n);const o=this._getRGBABufferInternalSizedFormat(s);let h=!1;t===p.RGB&&(t=p.RGBA,h=!0),this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const c=l(r);for(let n=0;n<c.length;n++){const r=i>>n;for(let i=0;i<6;i++){let l=c[n][i];h&&(l=a(l,r,r,s)),p.texImage2D(i,n,o,r,r,0,t,e,l)}}this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,r,n,s,d);f.isReady=!0,null==t||t.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),h&&h()}};return this._loadFile(e,(e=>{_(e)}),void 0,null==t?void 0:t.offlineProvider,!0,((e,i)=>{null==t||t.removePendingData(f),c&&e&&c(e.status+" "+e.statusText,i)})),f},o.B.prototype.createRawTexture2DArray=l(!1),o.B.prototype.createRawTexture3D=l(!0),o.B.prototype.updateRawTexture2DArray=h(!1),o.B.prototype.updateRawTexture3D=h(!0)},9075:(e,t,i)=>{i.d(t,{A:()=>s});var n=i(3230);function s(e,t,i=!1,n){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return n&&e.set(new Int8Array(n)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return n&&e.set(new Uint8Array(n)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return n&&e.set(new Int16Array(n)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return n&&e.set(new Uint16Array(n)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return n&&e.set(new Int32Array(n)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return n&&e.set(new Uint32Array(n)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return n&&e.set(new Float32Array(n)),e}}const s=(ArrayBuffer,new Uint8Array(t));return n&&s.set(new Uint8Array(n)),s}n.B.prototype._readTexturePixelsSync=function(e,t,i,n=-1,r=0,o=null,a=!0,l=!1,h=0,c=0){var u,d;const p=this._gl;if(!p)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=p.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}p.bindFramebuffer(p.FRAMEBUFFER,this._dummyFramebuffer),n>-1?p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_CUBE_MAP_POSITIVE_X+n,null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,r):p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,null===(d=e._hardwareTexture)||void 0===d?void 0:d.underlyingResource,r);let f=void 0!==e.type?this._getWebGLTextureType(e.type):p.UNSIGNED_BYTE;return l?o||(o=s(e.type,4*t*i)):f===p.UNSIGNED_BYTE?(o||(o=new Uint8Array(4*t*i)),f=p.UNSIGNED_BYTE):(o||(o=new Float32Array(4*t*i)),f=p.FLOAT),a&&this.flushFramebuffer(),p.readPixels(h,c,t,i,p.RGBA,f,o),p.bindFramebuffer(p.FRAMEBUFFER,this._currentFramebuffer),o},n.B.prototype._readTexturePixels=function(e,t,i,n=-1,s=0,r=null,o=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,n,s,r,o,a,l,h))}},7246:(e,t,i)=>{var n=i(6202),s=i(2722),r=i(3230),o=i(7374);class a extends o.r{constructor(e,t,i,n,s){super(e,t,i,n),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._context=s}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}_shareDepth(e){super._shareDepth(e);const t=this._context,i=this._depthStencilBuffer,n=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=this._depthStencilBuffer,this._engine._bindUnboundFramebuffer(n),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,n=0){var s,r,o,a;if(!e._hardwareTexture)return;const l=this._framebuffer,h=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(l),this._engine.webGLVersion>1){const l=this._context,h=l["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=null!==(r=null!=i?i:null===(s=this.layerIndices)||void 0===s?void 0:s[t])&&void 0!==r?r:0,l.framebufferTextureLayer(l.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,n,i)):e.isCube?(i=null!==(a=null!=i?i:null===(o=this.faceIndices)||void 0===o?void 0:o[t])&&void 0!==a?a:0,l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,n)):l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_2D,e._hardwareTexture.underlyingResource,n)}else{const s=this._context,r=s["COLOR_ATTACHMENT"+t+"_WEBGL"],o=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,r,o,e._hardwareTexture.underlyingResource,n)}this._engine._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,n;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const s=null!==(n=null===(i=this._attachments)||void 0===i?void 0:i.length)&&void 0!==n?n:this.textures.length;for(let e=0;e<s;e++){const t=this.textures[e];t&&(t.is2DArray||t.is3D?this._bindTextureRenderTarget(t,e,this.layerIndices[e]):t.isCube?this._bindTextureRenderTarget(t,e,this.faceIndices[e]):this._bindTextureRenderTarget(t,e))}}setLayerAndFaceIndex(e=0,t,i){if(super.setLayerAndFaceIndex(e,t,i),!this.textures||!this.layerIndices||!this.faceIndices)return;const n=this.textures[e];n.is2DArray||n.is3D?this._bindTextureRenderTarget(this.textures[e],e,this.layerIndices[e]):n.isCube&&this._bindTextureRenderTarget(this.textures[e],e,this.faceIndices[e])}dispose(e=!1){const t=this._context;e||(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(t.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(t.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(t.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),super.dispose(e)}}r.B.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const n=new a(e,t,i,this,this._gl);return this._renderTargetWrapperCache.push(n),n},r.B.prototype.createRenderTargetTexture=function(e,t){var i,s;const r=this._createHardwareRenderTargetWrapper(!1,!1,e);let o,a=!0,l=!1,h=!1,c=1;void 0!==t&&"object"==typeof t&&(a=null===(i=t.generateDepthBuffer)||void 0===i||i,l=!!t.generateStencilBuffer,h=!!t.noColorAttachment,o=t.colorAttachment,c=null!==(s=t.samples)&&void 0!==s?s:1);const u=o||(h?null:this._createInternalTexture(e,t,!0,n.S.RenderTarget)),d=e.width||e,p=e.height||e,f=this._currentFramebuffer,_=this._gl,m=_.createFramebuffer();return this._bindUnboundFramebuffer(m),r._depthStencilBuffer=this._setupFramebufferDepthAttachments(l,a,d,p),u&&!u.is2DArray&&_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_2D,u._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(f),r._framebuffer=m,r._generateDepthBuffer=a,r._generateStencilBuffer=l,r.setTextures(u),this.updateRenderTargetTextureSampleCount(r,c),r},r.B.prototype.createDepthStencilTexture=function(e,t,i){if(t.isCube){const n=e.width||e;return this._createDepthStencilCubeTexture(n,t,i)}return this._createDepthStencilTexture(e,t,i)},r.B.prototype._createDepthStencilTexture=function(e,t,i){const r=this._gl,o=e.layers||0,a=0!==o?r.TEXTURE_2D_ARRAY:r.TEXTURE_2D,l=new n.l(this,n.S.DepthStencil);if(!this._caps.depthTextureExtension)return s.Y.Error("Depth texture is not supported by your browser or hardware."),l;const h={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t};if(this._bindTextureDirectly(a,l,!0),this._setupDepthStencilTexture(l,e,h.generateStencil,0!==h.comparisonFunction&&h.bilinearFiltering,h.comparisonFunction,h.samples),void 0!==h.depthTextureFormat){if(15!==h.depthTextureFormat&&16!==h.depthTextureFormat&&17!==h.depthTextureFormat&&13!==h.depthTextureFormat&&14!==h.depthTextureFormat&&18!==h.depthTextureFormat)return s.Y.Error("Depth texture format is not supported."),l;l.format=h.depthTextureFormat}else l.format=h.generateStencil?13:16;const c=17===l.format||13===l.format||18===l.format;i._depthStencilTexture=l,i._depthStencilTextureWithStencil=c;let u=r.UNSIGNED_INT;15===l.format?u=r.UNSIGNED_SHORT:17===l.format||13===l.format?u=r.UNSIGNED_INT_24_8:14===l.format?u=r.FLOAT:18===l.format&&(u=r.FLOAT_32_UNSIGNED_INT_24_8_REV);const d=c?r.DEPTH_STENCIL:r.DEPTH_COMPONENT;let p=d;this.webGLVersion>1&&(15===l.format?p=r.DEPTH_COMPONENT16:16===l.format?p=r.DEPTH_COMPONENT24:17===l.format||13===l.format?p=r.DEPTH24_STENCIL8:14===l.format?p=r.DEPTH_COMPONENT32F:18===l.format&&(p=r.DEPTH32F_STENCIL8)),l.is2DArray?r.texImage3D(a,0,p,l.width,l.height,o,0,d,u,null):r.texImage2D(a,0,p,l.width,l.height,0,d,u,null),this._bindTextureDirectly(a,null),this._internalTexturesCache.push(l);const f=i;if(f._depthStencilBuffer){const e=this._currentFramebuffer;this._bindUnboundFramebuffer(f._framebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.STENCIL_ATTACHMENT,r.RENDERBUFFER,null),this._bindUnboundFramebuffer(e),r.deleteRenderbuffer(f._depthStencilBuffer),f._depthStencilBuffer=null}return l},r.B.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const n=e.texture._hardwareTexture;if(n.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){const s=i.createFramebuffer();if(!s)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const r=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBAMultiSampleBufferFormat(e.texture.type),i.COLOR_ATTACHMENT0,!1);if(!r)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(r)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t}},6697:(e,t,i)=>{var n=i(6202),s=i(2722);i(3230).B.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),r={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1);const o=this._gl,a=new n.l(this,n.S.RenderTarget);this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,a,!0);const l=this._getSamplingParameters(r.samplingMode,r.generateMipMaps);1!==r.type||this._caps.textureFloat||(r.type=0,s.Y.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,l.mag),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,l.min),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE);for(let t=0;t<6;t++)o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(r.type,r.format),e,e,0,this._getInternalFormat(r.format),this._getWebGLTextureType(r.type),null);const h=o.createFramebuffer();return this._bindUnboundFramebuffer(h),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(r.generateStencilBuffer,r.generateDepthBuffer,e,e),r.generateMipMaps&&o.generateMipmap(o.TEXTURE_CUBE_MAP),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=h,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer,a.width=e,a.height=e,a.isReady=!0,a.isCube=!0,a.samples=1,a.generateMipMaps=r.generateMipMaps,a.samplingMode=r.samplingMode,a.type=r.type,a.format=r.format,this._internalTexturesCache.push(a),i.setTextures(a),i}},4901:(e,t,i)=>{var n=i(3230),s=i(8261);n.B.prototype.createUniformBuffer=function(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new s.M(t);return this.bindUniformBuffer(i),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i},n.B.prototype.createDynamicUniformBuffer=function(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new s.M(t);return this.bindUniformBuffer(i),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i},n.B.prototype.updateUniformBuffer=function(e,t,i,n){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===n?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+n)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+n)),this.bindUniformBuffer(null)},n.B.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},n.B.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},n.B.prototype.bindUniformBlock=function(e,t,i){const n=e.program,s=this._gl.getUniformBlockIndex(n,t);4294967295!==s&&this._gl.uniformBlockBinding(n,s,i)}},6430:(e,t,i)=>{i.d(t,{Z:()=>s});var n=i(8985);class s{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&&console.log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&console.log("End of inlining process.")}_collectFunctions(){let e=0;for(;e<this._sourceCode.length;){const t=this._sourceCode.indexOf(this.inlineToken,e);if(t<0)break;const i=this._sourceCode.indexOf("(",t+this.inlineToken.length);if(i<0){this.debug&&console.warn(`Could not find the opening parenthesis after the token. startIndex=${e}`),e=t+this.inlineToken.length;continue}const r=s._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(t+this.inlineToken.length,i));if(!r){this.debug&&console.warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(t+this.inlineToken.length,i)}`),e=t+this.inlineToken.length;continue}const[o,a]=[r[3],r[4]],l=(0,n.vt)("(",")",this._sourceCode,i);if(l<0){this.debug&&console.warn(`Could not extract the parameters the function '${a}' (type=${o}). funcParamsStartIndex=${i}`),e=t+this.inlineToken.length;continue}const h=this._sourceCode.substring(i+1,l),c=(0,n.Pm)(this._sourceCode,l+1);if(c===this._sourceCode.length){this.debug&&console.warn(`Could not extract the body of the function '${a}' (type=${o}). funcParamsEndIndex=${l}`),e=t+this.inlineToken.length;continue}const u=(0,n.vt)("{","}",this._sourceCode,c);if(u<0){this.debug&&console.warn(`Could not extract the body of the function '${a}' (type=${o}). funcBodyStartIndex=${c}`),e=t+this.inlineToken.length;continue}const d=this._sourceCode.substring(c,u+1),p=(0,n.Kt)(h).split(","),f=[];for(let e=0;e<p.length;++e){const t=p[e].trim(),i=t.lastIndexOf(" ");i>=0&&f.push(t.substring(i+1))}"void"!==o&&f.push("return"),this._functionDescr.push({name:a,type:o,parameters:f,body:d,callIndex:0}),e=u+1;const _=t>0?this._sourceCode.substring(0,t):"",m=u+1<this._sourceCode.length-1?this._sourceCode.substring(u+1):"";this._sourceCode=_+m,e-=u+1-t}this.debug&&console.log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=`,this._functionDescr)}_processInlining(e=20){for(;e-- >=0&&this._replaceFunctionCallsByCode(););return this.debug&&console.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:o}=t;let a=0;for(;a<this._sourceCode.length;){const l=this._sourceCode.indexOf(i,a);if(l<0)break;if(0===l||(0,n.uA)(this._sourceCode.charAt(l-1))){a=l+i.length;continue}const h=(0,n.Pm)(this._sourceCode,l+i.length);if(h===this._sourceCode.length||"("!==this._sourceCode.charAt(h)){a=l+i.length;continue}const c=(0,n.vt)("(",")",this._sourceCode,h);if(c<0){this.debug&&console.warn(`Could not extract the parameters of the function call. Function '${i}' (type=${s}). callParamsStartIndex=${h}`),a=l+i.length;continue}const u=this._sourceCode.substring(h+1,c),d=e=>{const t=[];let i=0,s=0;for(;i<e.length;){if("("===e.charAt(i)){const t=(0,n.vt)("(",")",e,i);if(t<0)return null;i=t}else","===e.charAt(i)&&(t.push(e.substring(s,i)),s=i+1);i++}return s<i&&t.push(e.substring(s,i)),t},p=d((0,n.Kt)(u));if(null===p){this.debug&&console.warn(`Invalid function call: can't extract the parameters of the function call. Function '${i}' (type=${s}). callParamsStartIndex=${h}, callParams=`+u),a=l+i.length;continue}const f=[];for(let e=0;e<p.length;++e){const t=p[e].trim();f.push(t)}const _="void"!==s?i+"_"+t.callIndex++:null;if(_&&f.push(_+" ="),f.length!==r.length){this.debug&&console.warn(`Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '${i}' (type=${s}). function parameters=${r}, call parameters=${f}`),a=l+i.length;continue}a=c+1;const m=this._replaceNames(o,r,f);let g=l>0?this._sourceCode.substring(0,l):"";const v=c+1<this._sourceCode.length-1?this._sourceCode.substring(c+1):"";if(_){const e=(0,n.wm)(this._sourceCode,l-1,"\n");g=this._sourceCode.substring(0,e+1);const t=this._sourceCode.substring(e+1,l);this._sourceCode=g+s+" "+_+";\n"+m+"\n"+t+_+v,this.debug&&console.log(`Replace function call by code. Function '${i}' (type=${s}). injectDeclarationIndex=${e}, call parameters=${f}`)}else this._sourceCode=g+m+v,a+=m.length-(c+1-l),this.debug&&console.log(`Replace function call by code. Function '${i}' (type=${s}). functionCallIndex=${l}, call parameters=${f}`);e=!0}}return e}_replaceNames(e,t,i){for(let s=0;s<t.length;++s){const r=new RegExp((0,n.AW)(t[s]),"g"),o=t[s].length,a=i[s];e=e.replace(r,((i,...r)=>{const l=r[0];return(0,n.uA)(e.charAt(l-1))||(0,n.uA)(e.charAt(l+o))?t[s]:a}))}return e}}s._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/},8198:(e,t,i)=>{i.d(t,{L:()=>g});class n{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var i,n,s,r,o,a;let l="";if(this.line){let h=this.line;const c=t.processor;if(c){c.lineProcessor&&(h=c.lineProcessor(h,t.isFragment,t.processingContext));const l=null!==(n=null===(i=t.processor)||void 0===i?void 0:i.attributeKeywordName)&&void 0!==n?n:"attribute",u=t.isFragment&&(null===(s=t.processor)||void 0===s?void 0:s.varyingFragmentKeywordName)?null===(r=t.processor)||void 0===r?void 0:r.varyingFragmentKeywordName:!t.isFragment&&(null===(o=t.processor)||void 0===o?void 0:o.varyingVertexKeywordName)?null===(a=t.processor)||void 0===a?void 0:a.varyingVertexKeywordName:"varying";!t.isFragment&&c.attributeProcessor&&this.line.startsWith(l)?h=c.attributeProcessor(this.line,e,t.processingContext):c.varyingProcessor&&this.line.startsWith(u)?h=c.varyingProcessor(this.line,t.isFragment,e,t.processingContext):c.uniformProcessor&&c.uniformRegexp&&c.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(h=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&c.uniformBufferRegexp&&c.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(h=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):c.textureProcessor&&c.textureRegexp&&c.textureRegexp.test(this.line)?h=c.textureProcessor(this.line,t.isFragment,e,t.processingContext):(c.uniformProcessor||c.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?c.uniformProcessor&&(h=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&(h=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,c.endOfUniformBufferProcessor&&(h=c.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}l+=h+"\r\n"}return this.children.forEach((i=>{l+=i.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),l}}class s{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex<this._lines.length-1}set lines(e){this._lines.length=0;for(const t of e){if("#"===t[0]){this._lines.push(t);continue}if(t.trim().startsWith("//")){this._lines.push(t);continue}const e=t.split(";");for(let t=0;t<e.length;t++){let i=e[t];i=i.trim(),i&&this._lines.push(i+(t!==e.length-1?";":""))}}}}class r extends n{process(e,t){for(let i=0;i<this.children.length;i++){const n=this.children[i];if(n.isValid(e))return n.process(e,t)}return""}}class o extends n{isValid(e){return this.testExpression.isTrue(e)}}class a{isTrue(e){return!0}static postfixToInfix(e){const t=[];for(const i of e)if(void 0===a._OperatorPriority[i])t.push(i);else{const e=t[t.length-1],n=t[t.length-2];t.length-=2,t.push(`(${n}${i}${e})`)}return t[t.length-1]}static infixToPostfix(e){const t=[];let i=-1;const n=()=>{h=h.trim(),""!==h&&(t.push(h),h="")},s=e=>{i<a._Stack.length-1&&(a._Stack[++i]=e)},r=()=>a._Stack[i],o=()=>-1===i?"!!INVALID EXPRESSION!!":a._Stack[i--];let l=0,h="";for(;l<e.length;){const c=e.charAt(l),u=l<e.length-1?e.substr(l,2):"";if("("===c)h="",s(c);else if(")"===c){for(n();-1!==i&&"("!==r();)t.push(o());o()}else if(a._OperatorPriority[u]>1){for(n();-1!==i&&a._OperatorPriority[r()]>=a._OperatorPriority[u];)t.push(o());s(u),l++}else h+=c;l++}for(n();-1!==i;)"("===r()?o():t.push(o());return t}}a._OperatorPriority={")":0,"(":1,"||":2,"&&":3},a._Stack=["","","","","","","","","","","","","","","","","","","",""];class l extends a{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=void 0!==e[this.define];return this.not&&(t=!t),t}}class h extends a{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}class c extends a{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}class u extends a{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}isTrue(e){let t=e[this.define];void 0===t&&(t=this.define);let i=!1;const n=parseInt(t),s=parseInt(this.testValue);switch(this.operand){case">":i=n>s;break;case"<":i=n<s;break;case"<=":i=n<=s;break;case">=":i=n>=s;break;case"==":i=n===s}return i}}var d=i(4934),p=i(9131);const f=/defined\s*?\((.+?)\)/g,_=/defined\s*?\[(.+?)\]/g,m=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g;class g{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,n){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const s=this._ProcessShaderConversion(e,t,n);i(s,e)}))}static PreProcess(e,t,i,n){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const s=this._ApplyPreProcessing(e,t,n);i(s,e)}))}static Finalize(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}static _ProcessPrecision(e,t){var i;if(null===(i=t.processor)||void 0===i?void 0:i.noPrecision)return e;const n=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=n?"precision highp float;\n"+e:"precision mediump float;\n"+e:n||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new l(t[1].trim(),"!"===e[0]);const i=["==",">=","<=","<",">"];let n="",s=0;for(n of i)if(s=e.indexOf(n),s>-1)break;if(-1===s)return new l(e);const r=e.substring(0,s).trim(),o=e.substring(s+n.length).trim();return new u(r,n,o)}static _BuildSubExpression(e){e=e.replace(f,"defined[$1]");const t=a.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],n=i[i.length-2];i.length-=2;const s="&&"==e?new c:new h;"string"==typeof t&&(t=t.replace(_,"defined($1)")),"string"==typeof n&&(n=n.replace(_,"defined($1)")),s.leftOperand="string"==typeof n?this._ExtractOperation(n):n,s.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(s)}let n=i[i.length-1];return"string"==typeof n&&(n=n.replace(_,"defined($1)")),"string"==typeof n?this._ExtractOperation(n):n}static _BuildExpression(e,t){const i=new o,n=e.substring(0,t);let s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),i.testExpression="#ifdef"===n?new l(s):"#ifndef"===n?new l(s,!0):this._BuildSubExpression(s),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("#else"===r){const i=new n;return t.children.push(i),void this._MoveCursor(e,i)}if("#elif"===r){const e=this._BuildExpression(s,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine,s=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/.exec(i);if(s&&s.length)switch(s[0]){case"#ifdef":{const n=new r;t.children.push(n);const s=this._BuildExpression(i,6);n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const n=new r;t.children.push(n);const s=this._BuildExpression(i,7);n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}case"#if":{const n=new r,s=this._BuildExpression(i,3);t.children.push(n),n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}}else{const e=new n;if(e.line=i,t.children.push(e),"#"===i[0]&&"d"===i[1]){const t=i.replace(";","").split(" ");e.additionalDefineKey=t[1],3===t.length&&(e.additionalDefineValue=t[2])}}}return!1}static _EvaluatePreProcessors(e,t,i){const r=new n,o=new s;return o.lineIndex=-1,o.lines=e.split("\n"),this._MoveCursor(o,r),r.process(t,i)}static _PreparePreProcessors(e,t){var i;const n=e.defines,s={};for(const e of n){const t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===p.x.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",t._getGlobalDefines(s),s}static _ProcessShaderConversion(e,t,i){let n=this._ProcessPrecision(e,t);if(!t.processor)return n;if(t.processor.shaderLanguage===p.x.GLSL&&-1!==n.indexOf("#version 3")&&(n=n.replace("#version 300 es",""),!t.processor.parseGLES3))return n;const s=t.defines,r=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(n=t.processor.preProcessor(n,s,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,r,t),t.processor.postProcessor&&(n=t.processor.postProcessor(n,s,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ApplyPreProcessing(e,t,i){var n,s;let r=e;const o=t.defines,a=this._PreparePreProcessors(t,i);return(null===(n=t.processor)||void 0===n?void 0:n.preProcessor)&&(r=t.processor.preProcessor(r,o,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,a,t),(null===(s=t.processor)||void 0===s?void 0:s.postProcessor)&&(r=t.processor.postProcessor(r,o,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ProcessIncludes(e,t,i){let n=m.exec(e),s=new String(e),r=!1;for(;null!=n;){let o=n[1];if(-1!==o.indexOf("__decl__")&&(o=o.replace(/__decl__/,""),t.supportsUniformBuffers&&(o=o.replace(/Vertex/,"Ubo"),o=o.replace(/Fragment/,"Ubo")),o+="Declaration"),!t.includesShadersStore[o]){const e=t.shadersRepository+"ShadersInclude/"+o+".fx";return void g._FileToolsLoadFile(e,(e=>{t.includesShadersStore[o]=e,this._ProcessIncludes(s,t,i)}))}{let e=t.includesShadersStore[o];if(n[2]){const t=n[3].split(",");for(let i=0;i<t.length;i+=2){const n=new RegExp(t[i],"g"),s=t[i+1];e=e.replace(n,s)}}if(n[4]){const i=n[5];if(-1!==i.indexOf("..")){const n=i.split(".."),s=parseInt(n[0]);let r=parseInt(n[1]),o=e.slice(0);e="",isNaN(r)&&(r=t.indexParameters[n[1]]);for(let i=s;i<r;i++)t.supportsUniformBuffers||(o=o.replace(/light\{X\}.(\w*)/g,((e,t)=>t+"{X}"))),e+=o.replace(/\{X\}/g,i.toString())+"\n"}else t.supportsUniformBuffers||(e=e.replace(/light\{X\}.(\w*)/g,((e,t)=>t+"{X}"))),e=e.replace(/\{X\}/g,i)}s=s.replace(n[0],e),r=r||e.indexOf("#include<")>=0||e.indexOf("#include <")>=0}n=m.exec(e)}r?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,n,s,r){throw(0,d.S)("FileTools")}}},4001:(e,t,i)=>{i.d(t,{C:()=>s});var n=i(9131);class s{constructor(){this.shaderLanguage=n.x.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const n=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i)e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(n?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}},2200:(e,t,i)=>{i.d(t,{B:()=>n});class n{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))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}}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}},4238:(e,t,i)=>{i.d(t,{y:()=>n});class n{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}_fillEffectInformation(e,t,i,n,s,r,o,a){const l=this.engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{n[i[t]]=e})),this._uniforms=n,h=0;h<s.length;h++)null==e.getUniform(s[h])&&(s.splice(h,1),h--);s.forEach(((e,t)=>{r[e]=t}));for(const e of l.getAttributes(this,o))a.push(e)}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],n=t.updateFlag;return(void 0===i||i!==n)&&(this._valueCache[e]=n,!0)}_cacheFloat2(e,t,i){let n=this._valueCache[e];if(!n||2!==n.length)return n=[t,i],this._valueCache[e]=n,!0;let s=!1;return n[0]!==t&&(n[0]=t,s=!0),n[1]!==i&&(n[1]=i,s=!0),s}_cacheFloat3(e,t,i,n){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,n],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),s[2]!==n&&(s[2]=n,r=!0),r}_cacheFloat4(e,t,i,n,s){let r=this._valueCache[e];if(!r||4!==r.length)return r=[t,i,n,s],this._valueCache[e]=r,!0;let o=!1;return r[0]!==t&&(r[0]=t,o=!0),r[1]!==i&&(r[1]=i,o=!0),r[2]!==n&&(r[2]=n,o=!0),r[3]!==s&&(r[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&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,n){this._cacheFloat3(e,t,i,n)&&(this.engine.setInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setInt4(this._uniforms[e],t,i,n,s)||(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];void 0!==i&&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,n){this._cacheFloat3(e,t,i,n)&&(this.engine.setUInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setUInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setUInt4(this._uniforms[e],t,i,n,s)||(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];void 0!==i&&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,n){this._cacheFloat3(e,t,i,n)&&(this.engine.setFloat3(this._uniforms[e],t,i,n)||(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,n,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setFloat4(this._uniforms[e],t,i,n,s)||(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}}},7458:(e,t,i)=>{i.d(t,{g:()=>n});class n{}n.ALPHA_DISABLE=0,n.ALPHA_ADD=1,n.ALPHA_COMBINE=2,n.ALPHA_SUBTRACT=3,n.ALPHA_MULTIPLY=4,n.ALPHA_MAXIMIZED=5,n.ALPHA_ONEONE=6,n.ALPHA_PREMULTIPLIED=7,n.ALPHA_PREMULTIPLIED_PORTERDUFF=8,n.ALPHA_INTERPOLATE=9,n.ALPHA_SCREENMODE=10,n.ALPHA_ONEONE_ONEONE=11,n.ALPHA_ALPHATOCOLOR=12,n.ALPHA_REVERSEONEMINUS=13,n.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,n.ALPHA_ONEONE_ONEZERO=15,n.ALPHA_EXCLUSION=16,n.ALPHA_LAYER_ACCUMULATE=17,n.ALPHA_EQUATION_ADD=0,n.ALPHA_EQUATION_SUBSTRACT=1,n.ALPHA_EQUATION_REVERSE_SUBTRACT=2,n.ALPHA_EQUATION_MAX=3,n.ALPHA_EQUATION_MIN=4,n.ALPHA_EQUATION_DARKEN=5,n.DELAYLOADSTATE_NONE=0,n.DELAYLOADSTATE_LOADED=1,n.DELAYLOADSTATE_LOADING=2,n.DELAYLOADSTATE_NOTLOADED=4,n.NEVER=512,n.ALWAYS=519,n.LESS=513,n.EQUAL=514,n.LEQUAL=515,n.GREATER=516,n.GEQUAL=518,n.NOTEQUAL=517,n.KEEP=7680,n.ZERO=0,n.REPLACE=7681,n.INCR=7682,n.DECR=7683,n.INVERT=5386,n.INCR_WRAP=34055,n.DECR_WRAP=34056,n.TEXTURE_CLAMP_ADDRESSMODE=0,n.TEXTURE_WRAP_ADDRESSMODE=1,n.TEXTURE_MIRROR_ADDRESSMODE=2,n.TEXTURE_CREATIONFLAG_STORAGE=1,n.TEXTUREFORMAT_ALPHA=0,n.TEXTUREFORMAT_LUMINANCE=1,n.TEXTUREFORMAT_LUMINANCE_ALPHA=2,n.TEXTUREFORMAT_RGB=4,n.TEXTUREFORMAT_RGBA=5,n.TEXTUREFORMAT_RED=6,n.TEXTUREFORMAT_R=6,n.TEXTUREFORMAT_RG=7,n.TEXTUREFORMAT_RED_INTEGER=8,n.TEXTUREFORMAT_R_INTEGER=8,n.TEXTUREFORMAT_RG_INTEGER=9,n.TEXTUREFORMAT_RGB_INTEGER=10,n.TEXTUREFORMAT_RGBA_INTEGER=11,n.TEXTUREFORMAT_BGRA=12,n.TEXTUREFORMAT_DEPTH24_STENCIL8=13,n.TEXTUREFORMAT_DEPTH32_FLOAT=14,n.TEXTUREFORMAT_DEPTH16=15,n.TEXTUREFORMAT_DEPTH24=16,n.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,n.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,n.TEXTUREFORMAT_STENCIL8=19,n.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,n.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,n.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,n.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,n.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,n.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,n.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,n.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,n.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,n.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,n.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,n.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,n.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,n.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,n.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,n.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,n.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,n.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,n.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,n.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,n.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,n.TEXTURETYPE_UNSIGNED_BYTE=0,n.TEXTURETYPE_UNSIGNED_INT=0,n.TEXTURETYPE_FLOAT=1,n.TEXTURETYPE_HALF_FLOAT=2,n.TEXTURETYPE_BYTE=3,n.TEXTURETYPE_SHORT=4,n.TEXTURETYPE_UNSIGNED_SHORT=5,n.TEXTURETYPE_INT=6,n.TEXTURETYPE_UNSIGNED_INTEGER=7,n.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,n.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,n.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,n.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,n.TEXTURETYPE_UNSIGNED_INT_24_8=12,n.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,n.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,n.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,n.TEXTURETYPE_UNDEFINED=16,n.TEXTURE_2D=3553,n.TEXTURE_2D_ARRAY=35866,n.TEXTURE_CUBE_MAP=34067,n.TEXTURE_CUBE_MAP_ARRAY=3735928559,n.TEXTURE_3D=32879,n.TEXTURE_NEAREST_SAMPLINGMODE=1,n.TEXTURE_NEAREST_NEAREST=1,n.TEXTURE_BILINEAR_SAMPLINGMODE=2,n.TEXTURE_LINEAR_LINEAR=2,n.TEXTURE_TRILINEAR_SAMPLINGMODE=3,n.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,n.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,n.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,n.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,n.TEXTURE_NEAREST_LINEAR=7,n.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,n.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,n.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,n.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,n.TEXTURE_LINEAR_NEAREST=12,n.TEXTURE_EXPLICIT_MODE=0,n.TEXTURE_SPHERICAL_MODE=1,n.TEXTURE_PLANAR_MODE=2,n.TEXTURE_CUBIC_MODE=3,n.TEXTURE_PROJECTION_MODE=4,n.TEXTURE_SKYBOX_MODE=5,n.TEXTURE_INVCUBIC_MODE=6,n.TEXTURE_EQUIRECTANGULAR_MODE=7,n.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,n.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,n.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,n.TEXTURE_FILTERING_QUALITY_HIGH=64,n.TEXTURE_FILTERING_QUALITY_MEDIUM=16,n.TEXTURE_FILTERING_QUALITY_LOW=8,n.SCALEMODE_FLOOR=1,n.SCALEMODE_NEAREST=2,n.SCALEMODE_CEILING=3,n.MATERIAL_TextureDirtyFlag=1,n.MATERIAL_LightDirtyFlag=2,n.MATERIAL_FresnelDirtyFlag=4,n.MATERIAL_AttributesDirtyFlag=8,n.MATERIAL_MiscDirtyFlag=16,n.MATERIAL_PrePassDirtyFlag=32,n.MATERIAL_AllDirtyFlag=63,n.MATERIAL_TriangleFillMode=0,n.MATERIAL_WireFrameFillMode=1,n.MATERIAL_PointFillMode=2,n.MATERIAL_PointListDrawMode=3,n.MATERIAL_LineListDrawMode=4,n.MATERIAL_LineLoopDrawMode=5,n.MATERIAL_LineStripDrawMode=6,n.MATERIAL_TriangleStripDrawMode=7,n.MATERIAL_TriangleFanDrawMode=8,n.MATERIAL_ClockWiseSideOrientation=0,n.MATERIAL_CounterClockWiseSideOrientation=1,n.ACTION_NothingTrigger=0,n.ACTION_OnPickTrigger=1,n.ACTION_OnLeftPickTrigger=2,n.ACTION_OnRightPickTrigger=3,n.ACTION_OnCenterPickTrigger=4,n.ACTION_OnPickDownTrigger=5,n.ACTION_OnDoublePickTrigger=6,n.ACTION_OnPickUpTrigger=7,n.ACTION_OnPickOutTrigger=16,n.ACTION_OnLongPressTrigger=8,n.ACTION_OnPointerOverTrigger=9,n.ACTION_OnPointerOutTrigger=10,n.ACTION_OnEveryFrameTrigger=11,n.ACTION_OnIntersectionEnterTrigger=12,n.ACTION_OnIntersectionExitTrigger=13,n.ACTION_OnKeyDownTrigger=14,n.ACTION_OnKeyUpTrigger=15,n.PARTICLES_BILLBOARDMODE_Y=2,n.PARTICLES_BILLBOARDMODE_ALL=7,n.PARTICLES_BILLBOARDMODE_STRETCHED=8,n.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,n.MESHES_CULLINGSTRATEGY_STANDARD=0,n.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,n.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,n.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,n.SCENELOADER_NO_LOGGING=0,n.SCENELOADER_MINIMAL_LOGGING=1,n.SCENELOADER_SUMMARY_LOGGING=2,n.SCENELOADER_DETAILED_LOGGING=3,n.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,n.PREPASS_POSITION_TEXTURE_TYPE=1,n.PREPASS_VELOCITY_TEXTURE_TYPE=2,n.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,n.PREPASS_COLOR_TEXTURE_TYPE=4,n.PREPASS_DEPTH_TEXTURE_TYPE=5,n.PREPASS_NORMAL_TEXTURE_TYPE=6,n.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,n.BUFFER_CREATIONFLAG_READ=1,n.BUFFER_CREATIONFLAG_WRITE=2,n.BUFFER_CREATIONFLAG_READWRITE=3,n.BUFFER_CREATIONFLAG_UNIFORM=4,n.BUFFER_CREATIONFLAG_VERTEX=8,n.BUFFER_CREATIONFLAG_INDEX=16,n.BUFFER_CREATIONFLAG_STORAGE=32,n.RENDERPASS_MAIN=0,n.INPUT_ALT_KEY=18,n.INPUT_CTRL_KEY=17,n.INPUT_META_KEY1=91,n.INPUT_META_KEY2=92,n.INPUT_META_KEY3=93,n.INPUT_SHIFT_KEY=16,n.SNAPSHOTRENDERING_STANDARD=0,n.SNAPSHOTRENDERING_FAST=1,n.PERSPECTIVE_CAMERA=0,n.ORTHOGRAPHIC_CAMERA=1,n.FOVMODE_VERTICAL_FIXED=0,n.FOVMODE_HORIZONTAL_FIXED=1,n.RIG_MODE_NONE=0,n.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,n.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,n.RIG_MODE_STEREOSCOPIC_INTERLACED=14,n.RIG_MODE_VR=20,n.RIG_MODE_WEBVR=21,n.RIG_MODE_CUSTOM=22,n.MAX_SUPPORTED_UV_SETS=6,n.GL_ALPHA_EQUATION_ADD=32774,n.GL_ALPHA_EQUATION_MIN=32775,n.GL_ALPHA_EQUATION_MAX=32776,n.GL_ALPHA_EQUATION_SUBTRACT=32778,n.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,n.GL_ALPHA_FUNCTION_SRC=768,n.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,n.GL_ALPHA_FUNCTION_SRC_ALPHA=770,n.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,n.GL_ALPHA_FUNCTION_DST_ALPHA=772,n.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,n.GL_ALPHA_FUNCTION_DST_COLOR=774,n.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,n.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,n.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,n.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,n.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,n.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,n.SnippetUrl="https://snippet.babylonjs.com"},7814:(e,t,i)=>{i.d(t,{D:()=>f});var n=i(5757),s=i(6202),r=i(6797),o=i(1431),a=i(4934),l=i(3230),h=i(4757),c=i(8215),u=i(8261),d=i(2722),p=i(2200);i(9347),i(9075),i(3742);class f extends l.B{static get NpmPackage(){return l.B.NpmPackage}static get Version(){return l.B.Version}static get Instances(){return o.l.Instances}static get LastCreatedEngine(){return o.l.LastCreatedEngine}static get LastCreatedScene(){return o.l.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise(((i,n)=>{const s=new Image;s.onload=()=>{s.decode().then((()=>{this.createImageBitmap(s,t).then((e=>{i(e)}))}))},s.onerror=()=>{n(`Error loading image ${s.src}`)},s.src=e}))}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const n=this.createCanvas(t,i).getContext("2d");if(!n)throw new Error("Unable to get 2d context for resizeImageBitmap");return n.drawImage(e,0,0),n.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i<f.Instances.length;i++){const n=f.Instances[i];for(let i=0;i<n.scenes.length;i++)n.scenes[i].markAllMaterialsAsDirty(e,t)}}static DefaultLoadingScreenFactory(e){throw(0,a.S)("LoadingScreen")}get _supportsHardwareTextureRescaling(){return!!f._RescalePostProcessFactory}get performanceMonitor(){return this._performanceMonitor}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=!0}getInputElement(){return this._renderingCanvas}constructor(e,t,i,s=!1){if(super(e,t,i,s),this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.scenes=new Array,this._virtualScenes=new Array,this.onNewSceneAddedObservable=new n.y$,this.postProcesses=new Array,this.isPointerLock=!1,this.onResizeObservable=new n.y$,this.onCanvasBlurObservable=new n.y$,this.onCanvasFocusObservable=new n.y$,this.onCanvasPointerOutObservable=new n.y$,this.onBeginFrameObservable=new n.y$,this.customAnimationFrameRequester=null,this.onEndFrameObservable=new n.y$,this.onBeforeShaderCompilationObservable=new n.y$,this.onAfterShaderCompilationObservable=new n.y$,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this._fps=60,this._deltaTime=0,this._drawCalls=new c.z,this.canvasTabIndex=1,this.disablePerformanceMonitorInBackground=!1,this._performanceMonitor=new h.A,this._compatibilityMode=!0,this.currentRenderPassId=0,this._renderPassNames=["main"],f.Instances.push(this),e){if(this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext){const t=e;this._sharedInit(t),this._connectVREvents()}this._prepareVRComponent(),i.autoEnableWebVR&&this.initWebVR()}}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),this._onCanvasFocus=()=>{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=e=>{this.disableContextMenu&&e.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=t=>{document.elementFromPoint(t.clientX,t.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(t)};const t=this.getHostWindow();t&&"function"==typeof t.addEventListener&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!f.audioEngine&&this._creationOptions.audioEngine&&f.AudioEngineFactory&&(f.audioEngine=f.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),(0,r.n5)()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&f._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=void 0!==f.OfflineProviderFactory,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){var e;null===(e=this._onPointerLockChange)||void 0===e||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 1e3*this._timeStep}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){const i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()}restoreStencilState(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)}setDirectViewport(e,t,i,n){const s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,n),s}scissorClear(e,t,i,n,s){this.enableScissor(e,t,i,n),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,n){const s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,n)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}initWebVR(){throw(0,a.S)("WebVRCamera")}_prepareVRComponent(){}_connectVREvents(e,t){}_submitVRFrame(){}disableVR(){}isVRPresenting(){return!1}_requestVRFrame(){}_loadFileAsync(e,t,i){return new Promise(((n,s)=>{this._loadFile(e,(e=>{n(e)}),void 0,t,i,((e,t)=>{s(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,n){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,n):this._setTexture(e,null,void 0,void 0,n))}setTextureFromPostProcess(e,t,i){var n;let s=null;t&&(t._textures.data[t._currentRenderTextureInd]?s=t._textures.data[t._currentRenderTextureInd]:t._forcedOutputTexture&&(s=t._forcedOutputTexture)),this._bindTexture(e,null!==(n=null==s?void 0:s.texture)&&void 0!==n?n:null,i)}setTextureFromPostProcessOutput(e,t,i){var n,s;this._bindTexture(e,null!==(s=null===(n=null==t?void 0:t._outputTexture)||void 0===n?void 0:n.texture)&&void 0!==s?s:null,i)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e<this._activeRenderLoops.length;e++)(0,this._activeRenderLoops[e])()}_renderLoop(){if(!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0?this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this.isVRPresenting()?this._requestVRFrame():this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&f._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&f._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&f._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){f._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this._submitVRFrame(),this.onEndFrameObservable.notifyObservers(this)}resize(e=!1){this.isVRPresenting()||super.resize(e)}setSize(e,t,i=!1){if(!this._renderingCanvas)return!1;if(!super.setSize(e,t,i))return!1;if(this.scenes){for(let e=0;e<this.scenes.length;e++){const t=this.scenes[e];for(let e=0;e<t.cameras.length;e++)t.cameras[e]._currentRenderId=0}this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,n,s,r=null){s=s||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const o=super.createShaderProgram(e,t,i,n,s,r);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,n,s=null){const r=n.createProgram();if(e.program=r,!r)throw new Error("Unable to create program");if(n.attachShader(r,t),n.attachShader(r,i),this.webGLVersion>1&&s){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(r,s),e.transformFeedback=t}return n.linkProgram(r),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),r}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach((t=>{t.postProcesses.forEach((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){const t=++f._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t<this.scenes.length;++t){const i=this.scenes[t];for(let t=0;t<i.meshes.length;++t){const n=i.meshes[t];if(n.subMeshes)for(let t=0;t<n.subMeshes.length;++t)n.subMeshes[t]._removeDrawWrapper(e)}}}_rescaleTexture(e,t,i,n,s){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const r=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&f._RescalePostProcessFactory&&(this._rescalePostProcess=f._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled((()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],r,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,n,0,0,t.width,t.height,0),this.unBindFramebuffer(r),r.dispose(),s&&s()})))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3){const n=new p.B(e,this._gl),r=new s.l(this,s.S.Unknown,!0);return r._hardwareTexture=n,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}_uploadImageToTexture(e,t,i=0,n=0){const s=this._gl,r=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,n,a,o,r,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void d.Y.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new u.M(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const n=this._gl;return new Promise(((s,r)=>{const o=()=>{const a=n.clientWaitSync(e,t,0);a!=n.WAIT_FAILED?a!=n.TIMEOUT_EXPIRED?s():setTimeout(o,i):r()};o()}))}_readPixelsAsync(e,t,i,n,s,r,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const a=this._gl,l=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.bufferData(a.PIXEL_PACK_BUFFER,o.byteLength,a.STREAM_READ),a.readPixels(e,t,i,n,s,r,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const h=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(a.flush(),this._clientWaitAsync(h,0,10).then((()=>(a.deleteSync(h),a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,o),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(l),o)))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();1===o.l.Instances.length&&f.audioEngine&&(f.audioEngine.dispose(),f.audioEngine=null),this.disableVR();const e=this.getHostWindow();e&&"function"==typeof e.removeEventListener&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),(0,r.n5)()&&(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=o.l.Instances.indexOf(this);t>=0&&o.l.Instances.splice(t,1),f.Instances.length||(o.l.OnEnginesDisposedObservable.notifyObservers(this),o.l.OnEnginesDisposedObservable.clear()),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(!(0,r.CG)())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!(0,r.CG)())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=f.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 n=document.createElement("div");n.style.whiteSpace="nowrap",n.appendChild(t),n.appendChild(i),document.body.appendChild(n);let s=0,r=0;try{r=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(n)}return{ascent:s,height:r,descent:r-s}}}f.ALPHA_DISABLE=0,f.ALPHA_ADD=1,f.ALPHA_COMBINE=2,f.ALPHA_SUBTRACT=3,f.ALPHA_MULTIPLY=4,f.ALPHA_MAXIMIZED=5,f.ALPHA_ONEONE=6,f.ALPHA_PREMULTIPLIED=7,f.ALPHA_PREMULTIPLIED_PORTERDUFF=8,f.ALPHA_INTERPOLATE=9,f.ALPHA_SCREENMODE=10,f.DELAYLOADSTATE_NONE=0,f.DELAYLOADSTATE_LOADED=1,f.DELAYLOADSTATE_LOADING=2,f.DELAYLOADSTATE_NOTLOADED=4,f.NEVER=512,f.ALWAYS=519,f.LESS=513,f.EQUAL=514,f.LEQUAL=515,f.GREATER=516,f.GEQUAL=518,f.NOTEQUAL=517,f.KEEP=7680,f.REPLACE=7681,f.INCR=7682,f.DECR=7683,f.INVERT=5386,f.INCR_WRAP=34055,f.DECR_WRAP=34056,f.TEXTURE_CLAMP_ADDRESSMODE=0,f.TEXTURE_WRAP_ADDRESSMODE=1,f.TEXTURE_MIRROR_ADDRESSMODE=2,f.TEXTUREFORMAT_ALPHA=0,f.TEXTUREFORMAT_LUMINANCE=1,f.TEXTUREFORMAT_LUMINANCE_ALPHA=2,f.TEXTUREFORMAT_RGB=4,f.TEXTUREFORMAT_RGBA=5,f.TEXTUREFORMAT_RED=6,f.TEXTUREFORMAT_R=6,f.TEXTUREFORMAT_RG=7,f.TEXTUREFORMAT_RED_INTEGER=8,f.TEXTUREFORMAT_R_INTEGER=8,f.TEXTUREFORMAT_RG_INTEGER=9,f.TEXTUREFORMAT_RGB_INTEGER=10,f.TEXTUREFORMAT_RGBA_INTEGER=11,f.TEXTURETYPE_UNSIGNED_BYTE=0,f.TEXTURETYPE_UNSIGNED_INT=0,f.TEXTURETYPE_FLOAT=1,f.TEXTURETYPE_HALF_FLOAT=2,f.TEXTURETYPE_BYTE=3,f.TEXTURETYPE_SHORT=4,f.TEXTURETYPE_UNSIGNED_SHORT=5,f.TEXTURETYPE_INT=6,f.TEXTURETYPE_UNSIGNED_INTEGER=7,f.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,f.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,f.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,f.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,f.TEXTURETYPE_UNSIGNED_INT_24_8=12,f.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,f.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,f.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,f.TEXTURE_NEAREST_SAMPLINGMODE=1,f.TEXTURE_BILINEAR_SAMPLINGMODE=2,f.TEXTURE_TRILINEAR_SAMPLINGMODE=3,f.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,f.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,f.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,f.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,f.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,f.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,f.TEXTURE_NEAREST_LINEAR=7,f.TEXTURE_NEAREST_NEAREST=1,f.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,f.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,f.TEXTURE_LINEAR_LINEAR=2,f.TEXTURE_LINEAR_NEAREST=12,f.TEXTURE_EXPLICIT_MODE=0,f.TEXTURE_SPHERICAL_MODE=1,f.TEXTURE_PLANAR_MODE=2,f.TEXTURE_CUBIC_MODE=3,f.TEXTURE_PROJECTION_MODE=4,f.TEXTURE_SKYBOX_MODE=5,f.TEXTURE_INVCUBIC_MODE=6,f.TEXTURE_EQUIRECTANGULAR_MODE=7,f.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,f.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,f.SCALEMODE_FLOOR=1,f.SCALEMODE_NEAREST=2,f.SCALEMODE_CEILING=3,f._RescalePostProcessFactory=null,f._RenderPassIdCounter=0},1431:(e,t,i)=>{i.d(t,{l:()=>s});var n=i(5757);class s{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}s.Instances=new Array,s.OnEnginesDisposedObservable=new n.y$,s._LastCreatedScene=null,s.UseFallbackTexture=!0,s.FallbackTexture=""},771:(e,t,i)=>{i.d(t,{Z:()=>n});class n{static SetMatrixPrecision(e){if(n.MatrixTrackPrecisionChange=!1,e&&!n.MatrixUse64Bits&&n.MatrixTrackedMatrices)for(let e=0;e<n.MatrixTrackedMatrices.length;++e){const t=n.MatrixTrackedMatrices[e],i=t._m;t._m=new Array(16);for(let e=0;e<16;++e)t._m[e]=i[e]}n.MatrixUse64Bits=e,n.MatrixCurrentType=n.MatrixUse64Bits?Array:Float32Array,n.MatrixTrackedMatrices=null}}n.MatrixUse64Bits=!1,n.MatrixTrackPrecisionChange=!0,n.MatrixCurrentType=Float32Array,n.MatrixTrackedMatrices=[]},7374:(e,t,i)=>{i.d(t,{r:()=>s});var n=i(6202);class s{get depthStencilTexture(){return this._depthStencilTexture}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get texture(){var e,t;return null!==(t=null===(e=this._textures)||void 0===e?void 0:e[0])&&void 0!==t?t:null}get textures(){return this._textures}get 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 n=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,n}constructor(e,t,i,n){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=n,this._depthStencilTexture=null}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]:null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,n=1,s=14,r){var o;return null===(o=this._depthStencilTexture)||void 0===o||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:n,depthTextureFormat:s,label:r},this),this._depthStencilTexture}_shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var e,t,i,s,r,o,a,l;let h=null;if(this._isMulti){const i=this.textures;if(i&&i.length>0){let s=!1,r=i.length;const o=i[i.length-1]._source;o!==n.S.Depth&&o!==n.S.DepthStencil||(s=!0,r--);const a=[],l=[],c=[],u=[],d=[],p=[],f=[],_={};for(let n=0;n<r;++n){const s=i[n];a.push(s.samplingMode),l.push(s.type),c.push(s.format),void 0!==_[s.uniqueId]?(u.push(-1),f.push(0)):(_[s.uniqueId]=n,s.is2DArray?(u.push(35866),f.push(s.depth)):s.isCube?(u.push(34067),f.push(0)):s.is3D?(u.push(32879),f.push(s.depth)):(u.push(3553),f.push(0))),this._faceIndices&&d.push(null!==(e=this._faceIndices[n])&&void 0!==e?e:0),this._layerIndices&&p.push(null!==(t=this._layerIndices[n])&&void 0!==t?t:0)}const m={samplingModes:a,generateMipMaps:i[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:s,types:l,formats:c,textureCount:r,targetTypes:u,faceIndex:d,layerIndex:p,layerCounts:f},g={width:this.width,height:this.height};h=this._engine.createMultipleRenderTarget(g,m);for(let e=0;e<r;++e){if(-1!==u[e])continue;const t=_[i[e].uniqueId];h.setTexture(h.textures[t],e)}}}else{const e={};if(e.generateDepthBuffer=this._generateDepthBuffer,e.generateMipMaps=null!==(s=null===(i=this.texture)||void 0===i?void 0:i.generateMipMaps)&&void 0!==s&&s,e.generateStencilBuffer=this._generateStencilBuffer,e.samplingMode=null===(r=this.texture)||void 0===r?void 0:r.samplingMode,e.type=null===(o=this.texture)||void 0===o?void 0:o.type,e.format=null===(a=this.texture)||void 0===a?void 0:a.format,this.isCube)h=this._engine.createRenderTargetCubeTexture(this.width,e);else{const t={width:this.width,height:this.height,layers:this.is2DArray?null===(l=this.texture)||void 0===l?void 0:l.depth:void 0};h=this._engine.createRenderTargetTexture(t,e)}h.texture.isReady=!0}return h}_swapRenderTargetWrapper(e){if(this._textures&&e._textures)for(let t=0;t<this._textures.length;++t)this._textures[t]._swapAndDie(e._textures[t],!1),e._textures[t].isReady=!0;this._depthStencilTexture&&e._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(e._depthStencilTexture),e._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null}_rebuild(){const e=this._cloneRenderTargetWrapper();if(e){if(this._depthStencilTexture){const t=this._depthStencilTexture.samplingMode,i=2===t||3===t||11===t;e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,i,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples)}this.samples>1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let i=0;null!==(t=i<(null===(e=this._textures)||void 0===e?void 0:e.length))&&void 0!==t&&t;++i)this._textures[i].dispose();this._textures=null}dispose(e=!1){var t;e||(null===(t=this._depthStencilTexture)||void 0===t||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}},8104:(e,t,i)=>{i.d(t,{v:()=>s});var n=i(9131);class s{static GetShadersRepository(e=n.x.GLSL){return e===n.x.GLSL?s.ShadersRepository:s.ShadersRepositoryWGSL}static GetShadersStore(e=n.x.GLSL){return e===n.x.GLSL?s.ShadersStore:s.ShadersStoreWGSL}static GetIncludesShadersStore(e=n.x.GLSL){return e===n.x.GLSL?s.IncludesShadersStore:s.IncludesShadersStoreWGSL}}s.ShadersRepository="src/Shaders/",s.ShadersStore={},s.IncludesShadersStore={},s.ShadersRepositoryWGSL="src/ShadersWGSL/",s.ShadersStoreWGSL={},s.IncludesShadersStoreWGSL={}},3230:(e,t,i)=>{i.d(t,{B:()=>E});var n=i(1431),s=i(1979),r=i(4934),o=i(5757),a=i(6533),l=i(8657),h=i(4710),c=i(6202),u=i(2722),d=i(6797),p=i(9131);class f{constructor(){this.shaderLanguage=p.x.GLSL}postProcessor(e,t,i,n,s){if(!s.getCaps().drawBuffersExtension){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}var _=i(4001),m=i(8261),g=i(4238),v=i(771),y=i(2200),x=i(1345),b=i(9468),T=i(8108);class S{}class E{static get NpmPackage(){return"babylonjs@6.3.0"}static get Version(){return"6.3.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 s.Q.ShadersRepository}static set ShadersRepository(e){s.Q.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,this._depthCullingState.depthFunc=e?518:515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return E._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,n){var s,r,c,p,m,g,y,x,C,A,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 o.y$,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 o.y$,this.onContextRestoredObservable=new o.y$,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new a.k,this._stencilStateComposer=new b.C,this._stencilState=new l.s,this._alphaState=new h.Q,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._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 o.y$,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=T.F.Now;let R=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=null!=n&&n,this._stencilStateComposer.stencilGlobal=this._stencilState,v.Z.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=null!=t?t:i.antialias,i.deterministicLockstep=null!==(s=i.deterministicLockstep)&&void 0!==s&&s,i.lockstepMaxSteps=null!==(r=i.lockstepMaxSteps)&&void 0!==r?r:4,i.timeStep=null!==(c=i.timeStep)&&void 0!==c?c:1/60,i.audioEngine=null===(p=i.audioEngine)||void 0===p||p,i.stencil=null===(m=i.stencil)||void 0===m||m,this._audioContext=null!==(y=null===(g=i.audioEngineOptions)||void 0===g?void 0:g.audioContext)&&void 0!==y?y:null,this._audioDestination=null!==(C=null===(x=i.audioEngineOptions)||void 0===x?void 0:x.audioDestination)&&void 0!==C?C:null,this.premultipliedAlpha=null===(A=i.premultipliedAlpha)||void 0===A||A,this.useExactSrgbConversions=null!==(P=i.useExactSrgbConversions)&&void 0!==P&&P,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,n=n||i.adaptToDeviceRatio||!1;const M=(0,d.CG)()&&window.devicePixelRatio||1,I=i.limitDeviceRatio||M;if(this._hardwareScalingLevel=n?1/Math.min(I,M):1,this._lastDevicePixelRatio=M,!e)return;if(e.getContext){if(R=e,this._renderingCanvas=R,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of E.ExceptionList){const n=t.key,s=t.targets;if(new RegExp(n).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,n=t.captureConstraint,s=new RegExp(i).exec(e);if(s&&s.length>0&&parseInt(s[s.length-1])>=n)continue}for(const e of s)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,u.Y.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(this._initGLContext.bind(this))},R.addEventListener("webglcontextlost",this._onContextLost,!1),R.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=R.getContext("webgl2",i)||R.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!R)throw new Error("The provided canvas is null or undefined.");try{this._gl=R.getContext("webgl",i)||R.getContext("experimental-webgl",i)}catch(e){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e<this._caps.maxVertexAttribs;e++)this._currentBufferPointers[e]=new S;this._shaderProcessor=this.webGLVersion>1?new _.C:new f,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);const D=`Babylon.js v${E.Version}`;console.log(D+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",D)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&(0,d.n5)()&&"ontouchend"in document},this._checkForMobile(),(0,d.CG)()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout((async()=>{var t;this._dummyFramebuffer=null;const i=this._depthCullingState.depthTest,n=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),null===(t=this._rebuildComputeEffects)||void 0===t||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=i,this._depthCullingState.depthFunc=n,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,u.Y.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()}s.Q.ResetCache()}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuild();for(const e of this._storageBuffers)e._rebuild()}_initGLContext(){var e;this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,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._glVersion=this._gl.getParameter(this._gl.VERSION);const t=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=t&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(null!==(e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))&&void 0!==e?e:0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e<this._maxSimultaneousTextures;e++)this._nextFreeTextureSlots.push(e);"Mali-G72"===this._glRenderer&&(this._caps.disableMorphTargetTexture=!0)}_initFeatures(){this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:1!==this._webGLVersion,supportDepthStencilTexture:1!==this._webGLVersion,supportShadowSamplers:1!==this._webGLVersion,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:1!==this._webGLVersion,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:1!==this._webGLVersion,basisNeedsPOT:1===this._webGLVersion,support3DTextures:1!==this._webGLVersion,needTypeSuffixInShaderConstants:1!==this._webGLVersion,supportMSAA:1!==this._webGLVersion,supportSSAO2:1!==this._webGLVersion,supportExtendedTextureFormats:1!==this._webGLVersion,supportSwitchCaseInShader:1!==this._webGLVersion,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,_collectUbosUpdatedInFrame:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}get isStencilEnable(){return this._isStencilEnable}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);const e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}getLoadedTexturesCache(){return this._internalTexturesCache}getCaps(){return this._caps}stopRenderLoop(e){if(!e)return void(this._activeRenderLoops.length=0);const t=this._activeRenderLoops.indexOf(e);t>=0&&this._activeRenderLoops.splice(t,1)}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e<this._activeRenderLoops.length;e++)(0,this._activeRenderLoops[e])();this.endFrame()}}this._activeRenderLoops.length>0?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(0,d.CG)()?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 E.QueueNewFrame(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=this._renderLoop.bind(this),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,i,n=!1){const s=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=s;let r=0;t&&e&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),r|=this._gl.COLOR_BUFFER_BIT),i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),r|=this._gl.DEPTH_BUFFER_BIT),n&&(this._gl.clearStencil(0),r|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(r)}_viewport(e,t,i,n){e===this._viewportCached.x&&t===this._viewportCached.y&&i===this._viewportCached.z&&n===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=n,this._gl.viewport(e,t,i,n))}setViewport(e,t,i){const n=t||this.getRenderWidth(),s=i||this.getRenderHeight(),r=e.x||0,o=e.y||0;this._cachedViewport=e,this._viewport(r*n,o*s,n*e.width,s*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=(0,d.CG)()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if((0,d.CG)())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width,i=this._renderingCanvas.clientHeight||e.height}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|=0,t|=0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t||(this._renderingCanvas.width=e,this._renderingCanvas.height=t,0)))}bindFramebuffer(e,t=0,i,n,s,r=0,o=0){var a,l,h,c,u;const d=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(d._MSAAFramebuffer?d._MSAAFramebuffer:d._framebuffer);const p=this._gl;e.isMulti||(e.is2DArray?p.framebufferTextureLayer(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,null===(a=e.texture._hardwareTexture)||void 0===a?void 0:a.underlyingResource,r,o):e.isCube&&p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(l=e.texture._hardwareTexture)||void 0===l?void 0:l.underlyingResource,r));const f=e._depthStencilTexture;if(f){const i=e._depthStencilTextureWithStencil?p.DEPTH_STENCIL_ATTACHMENT:p.DEPTH_ATTACHMENT;e.is2DArray?p.framebufferTextureLayer(p.FRAMEBUFFER,i,null===(h=f._hardwareTexture)||void 0===h?void 0:h.underlyingResource,r,o):e.isCube?p.framebufferTexture2D(p.FRAMEBUFFER,i,p.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(c=f._hardwareTexture)||void 0===c?void 0:c.underlyingResource,r):p.framebufferTexture2D(p.FRAMEBUFFER,i,p.TEXTURE_2D,null===(u=f._hardwareTexture)||void 0===u?void 0:u.underlyingResource,r)}this._cachedViewport&&!s?this.setViewport(this._cachedViewport,i,n):(i||(i=e.width,r&&(i/=Math.pow(2,r))),n||(n=e.height,r&&(n/=Math.pow(2,r))),this._viewport(0,0,i,n)),this.wipeCaches()}setState(e,t=0,i,n=!1,s,r,o=0){var a,l;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const h=null===(l=null!==(a=this.cullBackFaces)&&void 0!==a?a:s)||void 0===l||l?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==h||i)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(o);const c=n?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==c||i)&&(this._depthCullingState.frontFace=c),this._stencilStateComposer.stencilMaterial=r}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){const e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){const e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)}unBindFramebuffer(e,t=!1,i){var n;const s=e;this._currentRenderTarget=null;const r=this._gl;if(s._MSAAFramebuffer){if(e.isMulti)return void this.unBindMultiColorAttachmentFramebuffer(e,t,i);r.bindFramebuffer(r.READ_FRAMEBUFFER,s._MSAAFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,s._framebuffer),r.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,r.COLOR_BUFFER_BIT,r.NEAREST)}!(null===(n=e.texture)||void 0===n?void 0:n.generateMipMaps)||t||e.isCube||this.generateMipmaps(e.texture),i&&(s._MSAAFramebuffer&&this._bindUnboundFramebuffer(s._framebuffer),i()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create vertex buffer");const n=new m.M(i);return this.bindArrayBuffer(n),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),this._resetVertexBufferBinding(),n.references=1,n}createDynamicVertexBuffer(e){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t){const i=this._gl.createBuffer(),n=new m.M(i);if(!i)throw new Error("Unable to create index buffer");this.bindIndexBuffer(n);const s=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),n.references=1,n.is32Bits=4===s.BYTES_PER_ELEMENT,n}_normalizeIndexData(e){if(2===e.BYTES_PER_ELEMENT)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let t=0;t<e.length;t++)if(e[t]>=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const n=e.program,s=this._gl.getUniformBlockIndex(n,t);this._gl.uniformBlockBinding(n,s,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,n,s,r,o){const a=this._currentBufferPointers[t];if(!a)return;let l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==n&&(a.type=n,l=!0),a.normalized!==s&&(a.normalized=s,l=!0),a.stride!==r&&(a.stride=r,l=!0),a.offset!==o&&(a.offset=o,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=n,a.normalized=s,a.stride=r,a.offset=o,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),n===this._gl.UNSIGNED_INT||n===this._gl.INT?this._gl.vertexAttribIPointer(t,i,n,r,o):this._gl.vertexAttribPointer(t,i,n,s,r,o))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const n=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s<n.length;s++){const r=t.getAttributeLocation(s);if(r>=0){const t=n[s];let o=null;if(i&&(o=i[t]),o||(o=e[t]),!o)continue;this._gl.enableVertexAttribArray(r),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[r]=!0);const a=o.getBuffer();a&&(this._vertexAttribPointer(a,r,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(r,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(r),this._currentInstanceBuffers.push(a))))}}}recordVertexArrayObject(e,t,i,n){const s=this._gl.createVertexArray();if(!s)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,n),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,n,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;const t=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let r=0;for(let o=0;o<t;o++)if(o<i.length){const t=s.getAttributeLocation(o);t>=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[o],this._gl.FLOAT,!1,n,r)),r+=4*i[o]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,n){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,n)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t<i;t++){const i=this._currentInstanceBuffers[t];e!=i&&i.references&&(e=i,this.bindArrayBuffer(i));const n=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(n,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0}releaseVertexArrayObject(e){this._gl.deleteVertexArray(e)}_releaseBuffer(e){return e.references--,0===e.references&&(this._deleteBuffer(e),!0)}_deleteBuffer(e){this._gl.deleteBuffer(e.underlyingResource)}updateAndBindInstancesBuffer(e,t,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==i[0].index)this.bindInstancesBuffer(e,i,!0);else for(let t=0;t<4;t++){const n=i[t];this._vertexAttribArraysEnabled[n]||(this._gl.enableVertexAttribArray(n),this._vertexAttribArraysEnabled[n]=!0),this._vertexAttribPointer(e,n,4,this._gl.FLOAT,!1,64,16*t),this._gl.vertexAttribDivisor(n,1),this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(e)}}bindInstancesBuffer(e,t,i=!0){this.bindArrayBuffer(e);let n=0;if(i)for(let e=0;e<t.length;e++)n+=4*t[e].attributeSize;for(let i=0;i<t.length;i++){const s=t[i];void 0===s.index&&(s.index=this._currentEffect.getAttributeLocationByName(s.attributeName)),s.index<0||(this._vertexAttribArraysEnabled[s.index]||(this._gl.enableVertexAttribArray(s.index),this._vertexAttribArraysEnabled[s.index]=!0),this._vertexAttribPointer(e,s.index,s.attributeSize,s.attributeType||this._gl.FLOAT,s.normalized||!1,n,s.offset),this._gl.vertexAttribDivisor(s.index,void 0===s.divisor?1:s.divisor),this._currentInstanceLocations.push(s.index),this._currentInstanceBuffers.push(e))}}disableInstanceAttributeByName(e){if(!this._currentEffect)return;const t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}disableInstanceAttribute(e){let t,i=!1;for(;-1!==(t=this._currentInstanceLocations.indexOf(e));)this._currentInstanceLocations.splice(t,1),this._currentInstanceBuffers.splice(t,1),i=!0,t=this._currentInstanceLocations.indexOf(e);i&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))}disableAttributeByIndex(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1}draw(e,t,i,n){this.drawElementsType(e?0:1,t,i,n)}drawPointClouds(e,t,i){this.drawArraysType(2,e,t,i)}drawUnIndexed(e,t,i,n){this.drawArraysType(e?0:1,t,i,n)}drawElementsType(e,t,i,n){this.applyStates(),this._reportDrawCall();const s=this._drawMode(e),r=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,o=this._uintIndicesCurrentlySet?4:2;n?this._gl.drawElementsInstanced(s,i,r,t*o,n):this._gl.drawElements(s,i,r,t*o)}drawArraysType(e,t,i,n){this.applyStates(),this._reportDrawCall();const s=this._drawMode(e);n?this._gl.drawArraysInstanced(s,t,i,n):this._gl.drawArrays(s,t,i)}_drawMode(e){switch(e){case 0:default:return this._gl.TRIANGLES;case 2:case 3:return this._gl.POINTS;case 1:case 4:return this._gl.LINES;case 5:return this._gl.LINE_LOOP;case 6:return this._gl.LINE_STRIP;case 7:return this._gl.TRIANGLE_STRIP;case 8:return this._gl.TRIANGLE_FAN}}_reportDrawCall(){}_releaseEffect(e){this._compiledEffects[e._key]&&delete this._compiledEffects[e._key];const t=e.getPipelineContext();t&&this._deletePipelineContext(t)}_deletePipelineContext(e){const t=e;t&&t.program&&(t.program.__SPECTOR_rebuildProgram=null,this._gl.deleteProgram(t.program))}_getGlobalDefines(e){if(e)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}createEffect(e,t,i,n,r,o,a,l,h,c=p.x.GLSL){var u;const d=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,f=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,_=this._getGlobalDefines();let m=null!==(u=null!=r?r:t.defines)&&void 0!==u?u:"";_&&(m+=_);const g=d+"+"+f+"@"+m;if(this._compiledEffects[g]){const e=this._compiledEffects[g];return a&&e.isReady()&&a(e),e}const v=new s.Q(e,t,i,n,this,r,o,a,l,h,g,c);return this._compiledEffects[g]=v,v}static _ConcatenateShader(e,t,i=""){return i+(t?t+"\n":"")+e}_compileShader(e,t,i,n){return this._compileRawShader(E._ConcatenateShader(e,i,n),t)}_compileRawShader(e,t){const i=this._gl,n=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!n){let e=i.NO_ERROR,n=i.NO_ERROR;for(;(n=i.getError())!==i.NO_ERROR;)e=n;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${this._contextWasLost}`)}return i.shaderSource(n,e),i.compileShader(n),n}_getShaderSource(e){return this._gl.getShaderSource(e)}createRawShaderProgram(e,t,i,n,s=null){n=n||this._gl;const r=this._compileRawShader(t,"vertex"),o=this._compileRawShader(i,"fragment");return this._createShaderProgram(e,r,o,n,s)}createShaderProgram(e,t,i,n,s,r=null){s=s||this._gl;const o=this._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"",a=this._compileShader(t,"vertex",n,o),l=this._compileShader(i,"fragment",n,o);return this._createShaderProgram(e,a,l,s,r)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new g.y;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,n,s=null){const r=n.createProgram();if(e.program=r,!r)throw new Error("Unable to create program");return n.attachShader(r,t),n.attachShader(r,i),n.linkProgram(r),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),r}_finalizePipelineContext(e){const t=e.context,i=e.vertexShader,n=e.fragmentShader,s=e.program;if(!t.getProgramParameter(s,t.LINK_STATUS)){if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){const t=this._gl.getShaderInfoLog(i);if(t)throw e.vertexCompilationError=t,new Error("VERTEX SHADER "+t)}if(!this._gl.getShaderParameter(n,this._gl.COMPILE_STATUS)){const t=this._gl.getShaderInfoLog(n);if(t)throw e.fragmentCompilationError=t,new Error("FRAGMENT SHADER "+t)}const r=t.getProgramInfoLog(s);if(r)throw e.programLinkError=r,new Error(r)}if(this.validateShaderPrograms&&(t.validateProgram(s),!t.getProgramParameter(s,t.VALIDATE_STATUS))){const i=t.getProgramInfoLog(s);if(i)throw e.programValidationError=i,new Error(i)}t.deleteShader(i),t.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,i,n,s,r,o,a,l,h){const c=e;c.program=n?this.createRawShaderProgram(c,t,i,void 0,l):this.createShaderProgram(c,t,i,a,void 0,l),c.program.__SPECTOR_rebuildProgram=o}_isRenderingStateCompiled(e){const t=e;return!!this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(t),!0)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!i.isParallelCompiled)return void t();const n=i.onCompiled;i.onCompiled=n?()=>{n(),t()}:t}getUniforms(e,t){const i=new Array,n=e;for(let e=0;e<t.length;e++)i.push(this._gl.getUniformLocation(n.program,t[e]));return i}getAttributes(e,t){const i=[],n=e;for(let e=0;e<t.length;e++)try{i.push(this._gl.getAttribLocation(n.program,t[e]))}catch(e){i.push(-1)}return i}enableEffect(e){(e=null!==e&&x.q.IsWrapper(e)?e.effect:e)&&e!==this._currentEffect&&(this._stencilStateComposer.stencilMaterial=void 0,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setInt(e,t){return!!e&&(this._gl.uniform1i(e,t),!0)}setInt2(e,t,i){return!!e&&(this._gl.uniform2i(e,t,i),!0)}setInt3(e,t,i,n){return!!e&&(this._gl.uniform3i(e,t,i,n),!0)}setInt4(e,t,i,n,s){return!!e&&(this._gl.uniform4i(e,t,i,n,s),!0)}setIntArray(e,t){return!!e&&(this._gl.uniform1iv(e,t),!0)}setIntArray2(e,t){return!(!e||t.length%2!=0||(this._gl.uniform2iv(e,t),0))}setIntArray3(e,t){return!(!e||t.length%3!=0||(this._gl.uniform3iv(e,t),0))}setIntArray4(e,t){return!(!e||t.length%4!=0||(this._gl.uniform4iv(e,t),0))}setUInt(e,t){return!!e&&(this._gl.uniform1ui(e,t),!0)}setUInt2(e,t,i){return!!e&&(this._gl.uniform2ui(e,t,i),!0)}setUInt3(e,t,i,n){return!!e&&(this._gl.uniform3ui(e,t,i,n),!0)}setUInt4(e,t,i,n,s){return!!e&&(this._gl.uniform4ui(e,t,i,n,s),!0)}setUIntArray(e,t){return!!e&&(this._gl.uniform1uiv(e,t),!0)}setUIntArray2(e,t){return!(!e||t.length%2!=0||(this._gl.uniform2uiv(e,t),0))}setUIntArray3(e,t){return!(!e||t.length%3!=0||(this._gl.uniform3uiv(e,t),0))}setUIntArray4(e,t){return!(!e||t.length%4!=0||(this._gl.uniform4uiv(e,t),0))}setArray(e,t){return!(!e||t.length<1||(this._gl.uniform1fv(e,t),0))}setArray2(e,t){return!(!e||t.length%2!=0||(this._gl.uniform2fv(e,t),0))}setArray3(e,t){return!(!e||t.length%3!=0||(this._gl.uniform3fv(e,t),0))}setArray4(e,t){return!(!e||t.length%4!=0||(this._gl.uniform4fv(e,t),0))}setMatrices(e,t){return!!e&&(this._gl.uniformMatrix4fv(e,!1,t),!0)}setMatrix3x3(e,t){return!!e&&(this._gl.uniformMatrix3fv(e,!1,t),!0)}setMatrix2x2(e,t){return!!e&&(this._gl.uniformMatrix2fv(e,!1,t),!0)}setFloat(e,t){return!!e&&(this._gl.uniform1f(e,t),!0)}setFloat2(e,t,i){return!!e&&(this._gl.uniform2f(e,t,i),!0)}setFloat3(e,t,i,n){return!!e&&(this._gl.uniform3f(e,t,i,n),!0)}setFloat4(e,t,i,n,s){return!!e&&(this._gl.uniform4f(e,t,i,n,s),!0)}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl),this._colorWriteChanged){this._colorWriteChanged=!1;const e=this._colorWrite;this._gl.colorMask(e,e,e,e)}}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}clearInternalTexturesCache(){this._internalTexturesCache.length=0}wipeCaches(e){this.preventCacheWipeBetweenFrames&&!e||(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))}_getSamplingParameters(e,t){const i=this._gl;let n=i.NEAREST,s=i.NEAREST;switch(e){case 11:n=i.LINEAR,s=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case 3:n=i.LINEAR,s=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case 8:n=i.NEAREST,s=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case 4:n=i.NEAREST,s=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case 5:n=i.NEAREST,s=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case 6:n=i.NEAREST,s=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case 7:n=i.NEAREST,s=i.LINEAR;break;case 1:n=i.NEAREST,s=i.NEAREST;break;case 9:n=i.LINEAR,s=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case 10:n=i.LINEAR,s=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case 2:n=i.LINEAR,s=i.LINEAR;break;case 12:n=i.LINEAR,s=i.NEAREST}return{min:s,mag:n}}_createTexture(){const e=this._gl.createTexture();if(!e)throw new Error("Unable to create texture");return e}_createHardwareTexture(){return new y.B(this._createTexture(),this._gl)}_createInternalTexture(e,t,i=!0,n=c.S.Unknown){var s;let r,o=!1,a=0,l=3,h=5,d=!1,p=1;void 0!==t&&"object"==typeof t?(o=!!t.generateMipMaps,a=void 0===t.type?0:t.type,l=void 0===t.samplingMode?3:t.samplingMode,h=void 0===t.format?5:t.format,d=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,p=null!==(s=t.samples)&&void 0!==s?s:1,r=t.label):o=!!t,d&&(d=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(1!==a||this._caps.textureFloatLinearFiltering)&&(2!==a||this._caps.textureHalfFloatLinearFiltering)||(l=1),1!==a||this._caps.textureFloat||(a=0,u.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const f=this._gl,_=new c.l(this,n),m=e.width||e,g=e.height||e,v=e.layers||0,y=this._getSamplingParameters(l,o),x=0!==v?f.TEXTURE_2D_ARRAY:f.TEXTURE_2D,b=this._getRGBABufferInternalSizedFormat(a,h,d),T=this._getInternalFormat(h),S=this._getWebGLTextureType(a);return this._bindTextureDirectly(x,_),0!==v?(_.is2DArray=!0,f.texImage3D(x,0,b,m,g,v,0,T,S,null)):f.texImage2D(x,0,b,m,g,0,T,S,null),f.texParameteri(x,f.TEXTURE_MAG_FILTER,y.mag),f.texParameteri(x,f.TEXTURE_MIN_FILTER,y.min),f.texParameteri(x,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(x,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),o&&this._gl.generateMipmap(x),this._bindTextureDirectly(x,null),_._useSRGBBuffer=d,_.baseWidth=m,_.baseHeight=g,_.width=m,_.height=g,_.depth=v,_.isReady=!0,_.samples=p,_.generateMipMaps=o,_.samplingMode=l,_.type=a,_.format=h,_.label=r,this._internalTexturesCache.push(_),_}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,s,r=3,o=null,a=null,l,h,d=null,p=null,f=null,_=null,m,g,v){const y="data:"===(e=e||"").substr(0,5),x="blob:"===e.substr(0,5),b=y&&-1!==e.indexOf(";base64,"),T=p||new c.l(this,c.S.Url);T!==p&&(T.label=e.substring(0,60));const S=e;!this._transformTextureUrl||b||p||d||(e=this._transformTextureUrl(e)),S!==e&&(T._originalUrl=S);const C=e.lastIndexOf(".");let A=_||(C>-1?e.substring(C).toLowerCase():""),P=null;A.indexOf("?")>-1&&(A=A.split("?")[0]);for(const e of E._TextureLoaders)if(e.canLoad(A,m)){P=e;break}s&&s.addPendingData(T),T.url=e,T.generateMipMaps=!t,T.samplingMode=r,T.invertY=i,T._useSRGBBuffer=this._getUseSRGBBuffer(!!v,t),this._doNotHandleContextLost||(T._buffer=d);let R=null;o&&!p&&(R=T.onLoadedObservable.add(o)),p||this._internalTexturesCache.push(T);const M=(i,c)=>{s&&s.removePendingData(T),e===S?(R&&T.onLoadedObservable.remove(R),n.l.UseFallbackTexture&&this._createTextureBase(n.l.FallbackTexture,t,T.invertY,s,r,null,a,l,h,d,T),i=(i||"Unknown error")+(n.l.UseFallbackTexture?" - Fallback texture was used":""),T.onErrorObservable.notifyObservers({message:i,exception:c}),a&&a(i,c)):(u.Y.Warn(`Failed to load ${e}, falling back to ${S}`),this._createTextureBase(S,t,T.invertY,s,r,o,a,l,h,d,T,f,_,m,g,v))};if(P){const t=e=>{P.loadData(e,T,((e,t,i,n,o,a)=>{a?M("TextureLoader failed to load data"):l(T,A,s,{width:e,height:t},T.invertY,!i,n,(()=>(o(),!1)),r)}),g)};d?d instanceof ArrayBuffer?t(new Uint8Array(d)):ArrayBuffer.isView(d)?t(d):a&&a("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,s?s.offlineProvider:void 0,!0,((e,t)=>{M("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{x&&!this._doNotHandleContextLost&&(T._buffer=e),l(T,A,s,e,T.invertY,t,!1,h,r)};!y||b?d&&("string"==typeof d.decoding||d.close)?i(d):E._FileToolsLoadImage(e,i,M,s?s.offlineProvider:null,m,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof d||d instanceof ArrayBuffer||ArrayBuffer.isView(d)||d instanceof Blob?E._FileToolsLoadImage(d,i,M,s?s.offlineProvider:null,m,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):d&&i(d)}return T}createTexture(e,t,i,n,s=3,r=null,o=null,a=null,l=null,h=null,u=null,d,p,f,_){return this._createTextureBase(e,t,i,n,s,r,o,this._prepareWebGLTexture.bind(this),((e,t,i,s,r,o)=>{const a=this._gl,l=i.width===e&&i.height===t,u=h?this._getInternalFormat(h,r._useSRGBBuffer):".jpg"!==s||r._useSRGBBuffer?r._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:a.RGBA:a.RGB;let d=h?this._getInternalFormat(h):".jpg"!==s||r._useSRGBBuffer?a.RGBA:a.RGB;if(r._useSRGBBuffer&&1===this.webGLVersion&&(d=u),l)return a.texImage2D(a.TEXTURE_2D,0,u,d,a.UNSIGNED_BYTE,i),!1;const p=this._caps.maxTextureSize;if(i.width>p||i.height>p||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),a.texImage2D(a.TEXTURE_2D,0,u,d,a.UNSIGNED_BYTE,this._workingCanvas),r.width=e,r.height=t,1));{const e=new c.l(this,c.S.Temp);this._bindTextureDirectly(a.TEXTURE_2D,e,!0),a.texImage2D(a.TEXTURE_2D,0,u,d,a.UNSIGNED_BYTE,i),this._rescaleTexture(e,r,n,u,(()=>{this._releaseTexture(e),this._bindTextureDirectly(a.TEXTURE_2D,r,!0),o()}))}return!0}),a,l,h,u,d,p,_)}static _FileToolsLoadImage(e,t,i,n,s,o){throw(0,r.S)("FileTools")}_rescaleTexture(e,t,i,n,s){}createRawTexture(e,t,i,n,s,o,a,l=null,h=0,c=0,u=!1){throw(0,r.S)("Engine.RawTexture")}createRawCubeTexture(e,t,i,n,s,o,a,l=null){throw(0,r.S)("Engine.RawTexture")}createRawTexture3D(e,t,i,n,s,o,a,l,h=null,c=0){throw(0,r.S)("Engine.RawTexture")}createRawTexture2DArray(e,t,i,n,s,o,a,l,h=null,c=0){throw(0,r.S)("Engine.RawTexture")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const n=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(n,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(n,this._gl.TEXTURE_MIN_FILTER,s.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(n)),this._bindTextureDirectly(n,null),t.samplingMode=e}updateTextureDimensions(e,t,i,n=1){}updateTextureWrappingMode(e,t,i=null,n=null){const s=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==n&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(n),e),e._cachedWrapR=n),this._bindTextureDirectly(s,null)}_setupDepthStencilTexture(e,t,i,n,s,r=1){const o=t.width||t,a=t.height||t,l=t.layers||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=r,e.generateMipMaps=!1,e.samplingMode=n?2:1,e.type=0,e._comparisonFunction=s;const h=this._gl,c=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(c,h.TEXTURE_MAG_FILTER,u.mag),h.texParameteri(c,h.TEXTURE_MIN_FILTER,u.min),h.texParameteri(c,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(c,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===s?(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,s),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,n,s,r=0,o=0){const a=this._gl;let l=a.TEXTURE_2D;if(e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+r),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=a.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,o,t,i,n,0,s)}_uploadDataToTextureDirectly(e,t,i=0,n=0,s,r=!1){const o=this._gl,a=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===s?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=o.TEXTURE_2D;e.isCube&&(c=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),p=r?e.width:Math.pow(2,Math.max(u-n,0)),f=r?e.height:Math.pow(2,Math.max(d-n,0));o.texImage2D(c,n,h,p,f,0,l,a,t)}updateTextureData(e,t,i,n,s,r,o=0,a=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,p=h.TEXTURE_2D;e.isCube&&(p=h.TEXTURE_CUBE_MAP_POSITIVE_X+o,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(p,a,i,n,s,r,u,c,t),l&&this._gl.generateMipmap(p),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){const s=this._gl,r=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(r,e,!0),this._uploadDataToTextureDirectly(e,t,i,n),this._bindTextureDirectly(r,null,!0)}_prepareWebGLTextureContinuation(e,t,i,n,s){const r=this._gl;if(!r)return;const o=this._getSamplingParameters(s,!i);r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,o.mag),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,o.min),i||n||r.generateMipmap(r.TEXTURE_2D),this._bindTextureDirectly(r.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,n,s,r,o,a,l=3){const h=this.getCaps().maxTextureSize,c=Math.min(h,this.needPOTTextures?E.GetExponentOfTwo(n.width,h):n.width),u=Math.min(h,this.needPOTTextures?E.GetExponentOfTwo(n.height,h):n.height),d=this._gl;d&&(e._hardwareTexture?(this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),e.baseWidth=n.width,e.baseHeight=n.height,e.width=c,e.height=u,e.isReady=!0,a(c,u,n,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,r,o,l)}))||this._prepareWebGLTextureContinuation(e,i,r,o,l)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,n,s=1){const r=this._gl;if(e&&t)return this._createRenderBuffer(i,n,s,r.DEPTH_STENCIL,r.DEPTH24_STENCIL8,r.DEPTH_STENCIL_ATTACHMENT);if(t){let e=r.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=r.DEPTH_COMPONENT32F),this._createRenderBuffer(i,n,s,e,e,r.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,n,s,r.STENCIL_INDEX8,r.STENCIL_INDEX8,r.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,n,s,r,o=!0){const a=this._gl.createRenderbuffer();return this._updateRenderBuffer(a,e,t,i,n,s,r,o)}_updateRenderBuffer(e,t,i,n,s,r,o,a=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),n>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,n,r,t,i):l.renderbufferStorage(l.RENDERBUFFER,s,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e),a&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource),this.unbindAllTextures();const i=this._internalTexturesCache.indexOf(e);-1!==i&&this._internalTexturesCache.splice(i,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t<i.length;t++){const n=e.getUniform(i[t]);n&&(this._boundUniforms[t]=n)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,i=!1,n=!1){var s,r;let o=!1;const a=t&&t._associatedChannel>-1;if(i&&a&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||n){if(this._activateCurrentTexture(),t&&t.isMultiview)throw console.error(e,t),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,null!==(r=null===(s=null==t?void 0:t._hardwareTexture)||void 0===s?void 0:s.underlyingResource)&&void 0!==r?r:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(o=!0,this._activateCurrentTexture());return a&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),o}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const n=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(n,t)}unbindAllTextures(){for(let e=0;e<this._maxSimultaneousTextures;e++)this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,n){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,n=!1,s=""){if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;let r;r=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&r&&(r._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===r&&(i||this._bindSamplerUniformToChannel(r._associatedChannel,e),o=!1),this._activeChannel=e;const a=this._getTextureTarget(r);if(o&&this._bindTextureDirectly(a,r,i),r&&!r.isMultiview){if(r.isCube&&r._cachedCoordinatesMode!==t.coordinatesMode){r._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}r._cachedWrapU!==t.wrapU&&(r._cachedWrapU=t.wrapU,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),r)),r._cachedWrapV!==t.wrapV&&(r._cachedWrapV=t.wrapV,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),r)),r.is3D&&r._cachedWrapR!==t.wrapR&&(r._cachedWrapR=t.wrapR,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),r)),this._setAnisotropicLevel(a,r,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,n){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t<i.length;t++){const n=i[t].getInternalTexture();n?(this._textureUnits[t]=e+t,n._associatedChannel=e+t):this._textureUnits[t]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let e=0;e<i.length;e++)this._setTexture(this._textureUnits[e],i[e],!0)}}_setAnisotropicLevel(e,t,i){const n=this._caps.textureAnisotropicFilterExtension;11!==t.samplingMode&&3!==t.samplingMode&&2!==t.samplingMode&&(i=1),n&&t._cachedAnisotropicFilteringLevel!==i&&(this._setTextureParameterFloat(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=i)}_setTextureParameterFloat(e,t,i,n){this._bindTextureDirectly(e,n,!0,!0),this._gl.texParameterf(e,t,i)}_setTextureParameterInteger(e,t,i,n){n&&this._bindTextureDirectly(e,n,!0,!0),this._gl.texParameteri(e,t,i)}unbindAllAttributes(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(let e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e)}else for(let e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e;this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),null===(e=this.releaseComputeEffects)||void 0===e||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},(0,d.CG)()&&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,s.Q.ResetCache();for(const e of this._activeRequests)e.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);const r=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&r===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,n=t.UNSIGNED_BYTE,s=new Uint8Array(4);t.readPixels(0,0,1,1,e,n,s),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(n),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._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}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._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;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}_getRGBAMultiSampleBufferFormat(e,t=5){switch(e){case 1:return 6===t?this._gl.R32F:this._gl.RGBA32F;case 2:return 6===t?this._gl.R16F:this._gl.RGBA16F}return this._gl.RGBA8}_loadFile(e,t,i,n,s,r){const o=E._FileToolsLoadFile(e,t,i,n,s,r);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}static _FileToolsLoadFile(e,t,i,n,s,o){throw(0,r.S)("FileTools")}readPixels(e,t,i,n,s=!0,r=!0){const o=s?4:3,a=s?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(n*i*o);return r&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,n,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=this._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=this._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}static FloorPOT(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}static NearestPOT(e){const t=E.CeilingPOT(e),i=E.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let n;switch(i){case 1:n=E.FloorPOT(e);break;case 2:n=E.NearestPOT(e);break;default:n=E.CeilingPOT(e)}return Math.min(n,t)}static QueueNewFrame(e,t){if((0,d.CG)()){const{requestPostAnimationFrame:i,requestAnimationFrame:n}=t||window;if("function"==typeof i)return i(e);if("function"==typeof n)return n(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:(0,d.n5)()?document:null}}E.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],E._TextureLoaders=[],E.CollisionsEpsilon=.001,E._IsSupported=null,E._HasMajorPerformanceCaveat=null},9884:(e,t,i)=>{i.d(t,{o:()=>s,p:()=>n});class n{}n.COPY=1,n.CUT=2,n.PASTE=3;class s{constructor(e,t){this.type=e,this.event=t}static GetTypeFromCharacter(e){switch(e){case 67:return n.COPY;case 86:return n.PASTE;case 88:return n.CUT;default:return-1}}}},2272:(e,t,i)=>{var n;i.d(t,{G:()=>s,g:()=>n}),function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(n||(n={}));class s{}s.DOM_DELTA_PIXEL=0,s.DOM_DELTA_LINE=1,s.DOM_DELTA_PAGE=2},2925:(e,t,i)=>{i.d(t,{NG:()=>s,OG:()=>n,WZ:()=>r});class n{}n.KEYDOWN=1,n.KEYUP=2;class s{constructor(e,t){this.type=e,this.event=t}}class r extends s{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}},1903:(e,t,i)=>{i.d(t,{CU:()=>r,FV:()=>o,R5:()=>a,kD:()=>s});var n=i(4141);class s{}s.POINTERDOWN=1,s.POINTERUP=2,s.POINTERMOVE=4,s.POINTERWHEEL=8,s.POINTERPICK=16,s.POINTERTAP=32,s.POINTERDOUBLETAP=64;class r{constructor(e,t){this.type=e,this.event=t}}class o extends r{constructor(e,t,i,s){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new n.FM(i,s)}}class a extends r{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,n=null){super(e,t),this._pickInfo=i,this._inputManager=n}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}},3322:(e,t,i)=>{i.d(t,{t:()=>h});var n=i(4141),s=i(4496),r=i(2704),o=i(9803),a=i(1903),l=i(9311);class h{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((e=>{e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=o.x.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._updateScale=!0,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=n.y3.RotationY(Math.PI),this._rootMesh=new s.Kj("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=n._f.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((()=>{this._update()}))}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh){const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new n.P(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,h.PreserveScaling?t:void 0)}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera;let i=t.globalPosition;t.devicePosition&&(i=t.devicePosition),this._rootMesh.position.subtractToRef(i,n.jp.Vector3[0]);let s=this.scaleRatio;if(t.mode==r.V.ORTHOGRAPHIC_CAMERA)t.orthoTop&&t.orthoBottom&&(s*=t.orthoTop-t.orthoBottom);else{const e=t.getScene().useRightHandedSystem?n.P.RightHandedForwardReadOnly:n.P.LeftHandedForwardReadOnly,i=t.getDirection(e);s*=n.P.Dot(n.jp.Vector3[0],i)}this._rootMesh.scaling.setAll(s),e._getWorldMatrixDeterminant()<0&&!h.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}}_handlePivot(){const e=this._attachedNode;e.isUsingPivotMatrix&&e.isUsingPivotMatrix()&&e.position&&e.getWorldMatrix().setTranslation(e.position)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const i=n.jp.Matrix[1];e.parent._worldMatrix.invertToRef(i),this._attachedNode._worldMatrix.multiplyToRef(i,n.jp.Matrix[0]),t=n.jp.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,n.jp.Matrix[1]),i=n.jp.Matrix[1]):i=t,i.decompose(n.jp.Vector3[1],n.jp.Quaternion[0],n.jp.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){const e=this._attachedNode;e.rotation=n.jp.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(n.jp.Quaternion[0]),e.rotationQuaternion.normalize())}e.position.copyFrom(n.jp.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){const e=this._attachedNode;if(e.parent){const t=n.jp.Matrix[0],i=n.jp.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i),i.decompose(n.jp.Vector3[0],n.jp.Quaternion[0],e.position,h.PreserveScaling?e:void 0)}else this._attachedNode._worldMatrix.decompose(n.jp.Vector3[0],n.jp.Quaternion[0],e.position,h.PreserveScaling?e:void 0);n.jp.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(n.jp.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(n.jp.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=n.jp.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){const e=this._attachedNode,t=e.getParent();if(t){const i=n.jp.Matrix[0],s=n.jp.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,s),e.getLocalMatrix().copyFrom(s)}else e.getLocalMatrix().copyFrom(e.getWorldMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===l._.LIGHTTYPEID_DIRECTIONALLIGHT||t===l._.LIGHTTYPEID_SPOTLIGHT||t===l._.LIGHTTYPEID_POINTLIGHT){const t=e.parent;if(t){const i=n.jp.Matrix[0],s=n.jp.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,s),s.decompose(void 0,n.jp.Quaternion[0],n.jp.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,n.jp.Quaternion[0],n.jp.Vector3[0]);e.position=new n.P(n.jp.Vector3[0].x,n.jp.Vector3[0].y,n.jp.Vector3[0].z),e.direction&&(e.direction=new n.P(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach((e=>{e.material=t,e.color&&(e.color=t.diffuseColor)}))}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add((e=>{var n,s;if(e.pickInfo){if(e.type===a.kD.POINTERMOVE){if(i)return;t.forEach((t=>{var i,n;if(t.colliderMeshes&&t.gizmoMeshes){const s=-1!=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(n=null==e?void 0:e.pickInfo)||void 0===n?void 0:n.pickedMesh)),r=t.dragBehavior.enabled?s||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=r,e.color&&(e.color=r.diffuseColor)}))}}))}e.type===a.kD.POINTERDOWN&&t.has(null===(n=e.pickInfo.pickedMesh)||void 0===n?void 0:n.parent)&&(i=!0,t.get(null===(s=e.pickInfo.pickedMesh)||void 0===s?void 0:s.parent).active=!0,t.forEach((t=>{var i,n;const s=(-1!=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(n=null==e?void 0:e.pickInfo)||void 0===n?void 0:n.pickedMesh))||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=s,e.color&&(e.color=s.diffuseColor)}))}))),e.type===a.kD.POINTERUP&&t.forEach((e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach((t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}))}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}h.PreserveScaling=!1},4380:(e,t,i)=>{i.d(t,{m:()=>f});var n=i(5757),s=i(4141),r=i(4649),o=i(1431),a=i(708),l=i(7104),h=i(2262),c=i(2333),u=i(8513),d=i(1345),p=i(8104);i(1423);p.v.ShadersStore.layerPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec4 color;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef LINEAR\nbaseColor.rgb=toGammaSpace(baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";p.v.ShadersStore.layerVertexShader="attribute vec2 position;\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class f{set applyPostProcess(e){this._applyPostProcess=e}get applyPostProcess(){return this.isBackground||this._applyPostProcess}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.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)}constructor(e,t,i,l,p){this.name=e,this._applyPostProcess=!0,this.scale=new s.FM(1,1),this.offset=new s.FM(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new n.y$,this.onBeforeRenderObservable=new n.y$,this.onAfterRenderObservable=new n.y$,this.texture=t?new h.x(t,i,!0):null,this.isBackground=void 0===l||l,this.color=void 0===p?new r.HE(1,1,1,1):p,this._scene=i||o.l.LastCreatedScene;let f=this._scene._getComponent(c.l.NAME_LAYER);f||(f=new u.N(this._scene),this._scene._addComponent(f)),this._scene.layers.push(this);const _=this._scene.getEngine();this._drawWrapper=new d.q(_);const m=[];m.push(1,1),m.push(-1,1),m.push(-1,-1),m.push(1,-1);const g=new a.o(_,m,a.o.PositionKind,!1,!1,2);this._vertexBuffers[a.o.PositionKind]=g,this._createIndexBuffer()}_createIndexBuffer(){const e=this._scene.getEngine(),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[a.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}render(){if(!this.isEnabled)return;const e=this._scene.getEngine();let t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(t+="\r\n#define LINEAR"),this._previousDefines!==t&&(this._previousDefines=t,this._drawWrapper.effect=e.createEffect("layer",[a.o.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t));const i=this._drawWrapper.effect;i&&i.isReady()&&this.texture&&this.texture.isReady()&&(this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),i.setTexture("textureSampler",this.texture),i.setMatrix("textureMatrix",this.texture.getTextureMatrix()),i.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),i.setVector2("offset",this.offset),i.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,i),this.alphaTest?e.drawElementsType(l.F.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(l.F.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this))}dispose(){const e=this._vertexBuffers[a.o.PositionKind];e&&(e.dispose(),this._vertexBuffers[a.o.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];const t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()}}},8513:(e,t,i)=>{i.d(t,{N:()=>r});var n=i(2333),s=i(1431);class r{constructor(e){this.name=n.l.NAME_LAYER,this.scene=e||s.l.LastCreatedScene,this.scene&&(this._engine=this.scene.getEngine(),this.scene.layers=new Array)}register(){this.scene._beforeCameraDrawStage.registerStep(n.l.STEP_BEFORECAMERADRAW_LAYER,this,this._drawCameraBackground),this.scene._afterCameraDrawStage.registerStep(n.l.STEP_AFTERCAMERADRAW_LAYER,this,this._drawCameraForegroundWithPostProcessing),this.scene._afterCameraPostProcessStage.registerStep(n.l.STEP_AFTERCAMERAPOSTPROCESS_LAYER,this,this._drawCameraForegroundWithoutPostProcessing),this.scene._beforeRenderTargetDrawStage.registerStep(n.l.STEP_BEFORERENDERTARGETDRAW_LAYER,this,this._drawRenderTargetBackground),this.scene._afterRenderTargetDrawStage.registerStep(n.l.STEP_AFTERRENDERTARGETDRAW_LAYER,this,this._drawRenderTargetForegroundWithPostProcessing),this.scene._afterRenderTargetPostProcessStage.registerStep(n.l.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER,this,this._drawRenderTargetForegroundWithoutPostProcessing)}rebuild(){const e=this.scene.layers;for(const t of e)t._rebuild()}dispose(){const e=this.scene.layers;for(;e.length;)e[0].dispose()}_draw(e){const t=this.scene.layers;if(t.length){this._engine.setDepthBuffer(!1);for(const i of t)e(i)&&i.render();this._engine.setDepthBuffer(!0)}}_drawCameraPredicate(e,t,i,n){return!e.renderOnlyInRenderTargetTextures&&e.isBackground===t&&e.applyPostProcess===i&&0!=(e.layerMask&n)}_drawCameraBackground(e){this._draw((t=>this._drawCameraPredicate(t,!0,!0,e.layerMask)))}_drawCameraForegroundWithPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!0,e.layerMask)))}_drawCameraForegroundWithoutPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!1,e.layerMask)))}_drawRenderTargetPredicate(e,t,i,n,s){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(s)>-1&&0!=(e.layerMask&n)}_drawRenderTargetBackground(e){this._draw((t=>this._drawRenderTargetPredicate(t,!0,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithoutPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!1,this.scene.activeCamera.layerMask,e)))}addFromContainer(e){e.layers&&e.layers.forEach((e=>{this.scene.layers.push(e)}))}removeFromContainer(e,t=!1){e.layers&&e.layers.forEach((e=>{const i=this.scene.layers.indexOf(e);-1!==i&&this.scene.layers.splice(i,1),t&&e.dispose()}))}}},7951:(e,t,i)=>{i.d(t,{O:()=>h});var n=i(9472),s=i(3956),r=i(4141),o=i(9257),a=i(9311),l=i(6792);o.N.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new h(e,r.P.Zero(),t)));class h extends l.O{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 a._.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&&r.y3.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=r.P.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;let n=Number.MAX_VALUE,s=Number.MIN_VALUE;for(let o=0;o<i.length;o++){const a=i[o];if(!a)continue;const l=a.getBoundingInfo().boundingBox;for(let i=0;i<l.vectorsWorld.length;i++)r.P.TransformCoordinatesToRef(l.vectorsWorld[i],t,e),e.x<this._orthoLeft&&(this._orthoLeft=e.x),e.y<this._orthoBottom&&(this._orthoBottom=e.y),e.x>this._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.z<n&&(n=e.z),e.z>s&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=n,this._shadowMaxZ=s)}const s=this._orthoRight-this._orthoLeft,o=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,l=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,h=this.getScene().getEngine().useReverseDepthBuffer;r.y3.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-o*this.shadowOrthoScale,this._orthoTop+o*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}}(0,n.gn)([(0,s.qC)()],h.prototype,"shadowFrustumSize",null),(0,n.gn)([(0,s.qC)()],h.prototype,"shadowOrthoScale",null),(0,n.gn)([(0,s.qC)()],h.prototype,"autoUpdateExtends",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"autoCalcShadowZBounds",void 0),(0,n.gn)([(0,s.qC)("orthoLeft")],h.prototype,"_orthoLeft",void 0),(0,n.gn)([(0,s.qC)("orthoRight")],h.prototype,"_orthoRight",void 0),(0,n.gn)([(0,s.qC)("orthoTop")],h.prototype,"_orthoTop",void 0),(0,n.gn)([(0,s.qC)("orthoBottom")],h.prototype,"_orthoBottom",void 0)},7616:(e,t,i)=>{i.d(t,{e:()=>h});var n=i(9472),s=i(3956),r=i(4141),o=i(4649),a=i(9257),l=i(9311);a.N.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new h(e,r.P.Zero(),t)));class h extends l._{constructor(e,t,i){super(e,i),this.groundColor=new o.Wo(0,0,0),this.direction=t||r.P.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=r.P.Normalize(e.subtract(r.P.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=r.P.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=r.P.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=r.y3.Identity()),this._worldMatrix}getTypeID(){return l._.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}(0,n.gn)([(0,s.n9)()],h.prototype,"groundColor",void 0),(0,n.gn)([(0,s.hd)()],h.prototype,"direction",void 0)},9311:(e,t,i)=>{i.d(t,{_:()=>u});var n=i(9472),s=i(3956),r=i(4141),o=i(4649),a=i(9257),l=i(3743),h=i(2208),c=i(4185);class u extends a.N{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}constructor(e,t){super(e,t),this.diffuse=new o.Wo(1,1,1),this.specular=new o.Wo(1,1,1),this.falloffType=u.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=u.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,this._isLight=!0,this.getScene().addLight(this),this._uniformBuffer=new l.M(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=new Array,this.excludedMeshes=new Array,this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,n,s=!0){var r;const a=e.toString();let l=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+a),this._renderId!==t.getRenderId()||this._lastUseSpecular!==n||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=n;const e=this.getScaledIntensity();this.transferToEffect(i,a),this.diffuse.scaleToRef(e,o.zZ.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",o.zZ.Color3[0],this.range,a),n&&(this.specular.scaleToRef(e,o.zZ.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",o.zZ.Color3[1],this.radius,a)),l=!0}if(this.transferTexturesToEffect(i,a),t.shadowsEnabled&&this.shadowEnabled&&s){const e=null!==(r=this.getShadowGenerator(t.activeCamera))&&void 0!==r?r:this.getShadowGenerator();e&&(e.bindShadowLight(a,i),l=!0)}l?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}_syncParentEnabledState(){super._syncParentEnabledState(),this.isDisposed()||this._resyncMeshes()}setEnabled(e){super.setEnabled(e),this._resyncMeshes()}getShadowGenerator(e=null){var t;return null===this._shadowGenerators?null:null!==(t=this._shadowGenerators.get(e))&&void 0!==t?t:null}getShadowGenerators(){return this._shadowGenerators}getAbsolutePosition(){return r.P.Zero()}canAffectMesh(e){return!(e&&(this.includedOnlyMeshes&&this.includedOnlyMeshes.length>0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||0!==this.includeOnlyWithLayerMask&&0==(this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=u.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const n=s.p4.Clone(i,this);return e&&(n.name=e),t&&(n.parent=t),n.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(n),n}serialize(){const e=s.p4.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)}))),s.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return a.N.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=u.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const n=s.p4.Parse(i,e,t);if(e.excludedMeshesIds&&(n._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(n._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(n.falloffType=e.falloffType),void 0!==e.lightmapMode&&(n.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],s=(0,h.q)("BABYLON.Animation");s&&n.animations.push(s.Parse(i))}a.N.ParseAnimationRanges(n,e,t)}return e.autoAnimate&&t.beginAnimation(n,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&n.setEnabled(e.isEnabled),n}_hookArrayForExcluded(e){const t=e.push;e.push=(...i)=>{const n=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return n};const i=e.splice;e.splice=(t,n)=>{const s=i.apply(e,[t,n]);for(const e of s)e._resyncLightSource(this);return s};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const n=t.apply(e,i);return this._resyncMeshes(),n};const i=e.splice;e.splice=(t,n)=>{const s=i.apply(e,[t,n]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===u.INTENSITYMODE_AUTOMATIC&&(i=t===u.LIGHTTYPEID_DIRECTIONALLIGHT?u.INTENSITYMODE_ILLUMINANCE:u.INTENSITYMODE_LUMINOUSINTENSITY),t){case u.LIGHTTYPEID_POINTLIGHT:case u.LIGHTTYPEID_SPOTLIGHT:switch(i){case u.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case u.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case u.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case u.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case u.INTENSITYMODE_ILLUMINANCE:e=1;break;case u.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case u.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}u.FALLOFF_DEFAULT=c.m.FALLOFF_DEFAULT,u.FALLOFF_PHYSICAL=c.m.FALLOFF_PHYSICAL,u.FALLOFF_GLTF=c.m.FALLOFF_GLTF,u.FALLOFF_STANDARD=c.m.FALLOFF_STANDARD,u.LIGHTMAP_DEFAULT=c.m.LIGHTMAP_DEFAULT,u.LIGHTMAP_SPECULAR=c.m.LIGHTMAP_SPECULAR,u.LIGHTMAP_SHADOWSONLY=c.m.LIGHTMAP_SHADOWSONLY,u.INTENSITYMODE_AUTOMATIC=c.m.INTENSITYMODE_AUTOMATIC,u.INTENSITYMODE_LUMINOUSPOWER=c.m.INTENSITYMODE_LUMINOUSPOWER,u.INTENSITYMODE_LUMINOUSINTENSITY=c.m.INTENSITYMODE_LUMINOUSINTENSITY,u.INTENSITYMODE_ILLUMINANCE=c.m.INTENSITYMODE_ILLUMINANCE,u.INTENSITYMODE_LUMINANCE=c.m.INTENSITYMODE_LUMINANCE,u.LIGHTTYPEID_POINTLIGHT=c.m.LIGHTTYPEID_POINTLIGHT,u.LIGHTTYPEID_DIRECTIONALLIGHT=c.m.LIGHTTYPEID_DIRECTIONALLIGHT,u.LIGHTTYPEID_SPOTLIGHT=c.m.LIGHTTYPEID_SPOTLIGHT,u.LIGHTTYPEID_HEMISPHERICLIGHT=c.m.LIGHTTYPEID_HEMISPHERICLIGHT,(0,n.gn)([(0,s.n9)()],u.prototype,"diffuse",void 0),(0,n.gn)([(0,s.n9)()],u.prototype,"specular",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"falloffType",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"intensity",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"range",null),(0,n.gn)([(0,s.qC)()],u.prototype,"intensityMode",null),(0,n.gn)([(0,s.qC)()],u.prototype,"radius",null),(0,n.gn)([(0,s.qC)()],u.prototype,"_renderPriority",void 0),(0,n.gn)([(0,s.wz)("_reorderLightsInScene")],u.prototype,"renderPriority",void 0),(0,n.gn)([(0,s.qC)("shadowEnabled")],u.prototype,"_shadowEnabled",void 0),(0,n.gn)([(0,s.qC)("excludeWithLayerMask")],u.prototype,"_excludeWithLayerMask",void 0),(0,n.gn)([(0,s.qC)("includeOnlyWithLayerMask")],u.prototype,"_includeOnlyWithLayerMask",void 0),(0,n.gn)([(0,s.qC)("lightmapMode")],u.prototype,"_lightmapMode",void 0)},4185:(e,t,i)=>{i.d(t,{m:()=>n});class n{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}n.FALLOFF_DEFAULT=0,n.FALLOFF_PHYSICAL=1,n.FALLOFF_GLTF=2,n.FALLOFF_STANDARD=3,n.LIGHTMAP_DEFAULT=0,n.LIGHTMAP_SPECULAR=1,n.LIGHTMAP_SHADOWSONLY=2,n.INTENSITYMODE_AUTOMATIC=0,n.INTENSITYMODE_LUMINOUSPOWER=1,n.INTENSITYMODE_LUMINOUSINTENSITY=2,n.INTENSITYMODE_ILLUMINANCE=3,n.INTENSITYMODE_LUMINANCE=4,n.LIGHTTYPEID_POINTLIGHT=0,n.LIGHTTYPEID_DIRECTIONALLIGHT=1,n.LIGHTTYPEID_SPOTLIGHT=2,n.LIGHTTYPEID_HEMISPHERICLIGHT=3},5520:(e,t,i)=>{i.d(t,{c:()=>h});var n=i(9472),s=i(3956),r=i(4141),o=i(9257),a=i(9311),l=i(6792);o.N.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new h(e,r.P.Zero(),t)));class h extends l.O{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 e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return a._.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new r.P(1,0,0);case 1:return new r.P(-1,0,0);case 2:return new r.P(0,-1,0);case 3:return new r.P(0,1,0);case 4:return new r.P(0,0,1);case 5:return new r.P(0,0,-1)}return r.P.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;const s=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;r.y3.PerspectiveFovLHToRef(this.shadowAngle,1,a?o:s,a?s:o,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}}(0,n.gn)([(0,s.qC)()],h.prototype,"shadowAngle",null)},6792:(e,t,i)=>{i.d(t,{O:()=>l});var n=i(9472),s=i(3956),r=i(4141),o=i(9311),a=i(5203);class l extends o._{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return!(!this.parent||!this.parent.getWorldMatrix||(this.transformedPosition||(this.transformedPosition=r.P.Zero()),r.P.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=r.P.Zero()),r.P.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))}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=r.P.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=r.P.Cross(this.direction,a.RD.Y),t=r.P.Cross(e,this.direction);return r.P.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=r.P.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=r.y3.Identity()),r.y3.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 void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?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)}}(0,n.gn)([(0,s.hd)()],l.prototype,"position",null),(0,n.gn)([(0,s.hd)()],l.prototype,"direction",null),(0,n.gn)([(0,s.qC)()],l.prototype,"shadowMinZ",null),(0,n.gn)([(0,s.qC)()],l.prototype,"shadowMaxZ",null)},6317:(e,t,i)=>{i.d(t,{P:()=>c});var n=i(9472),s=i(3956),r=i(4141),o=i(9257),a=i(9311),l=i(6792),h=i(2262);o.N.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new c(e,r.P.Zero(),r.P.Zero(),0,0,t)));class c extends l.O{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),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()&&(c._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):c._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((()=>{this._markMeshesAsLightDirty()}))))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,n,s,o){super(e,o),this._innerAngle=0,this._projectionTextureMatrix=r.y3.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=r.P.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=r.P.Zero(),this._projectionTextureViewLightMatrix=r.y3.Zero(),this._projectionTextureProjectionLightMatrix=r.y3.Zero(),this._projectionTextureScalingMatrix=r.y3.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=n,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return a._.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;this._shadowAngleScale=this._shadowAngleScale||1;const s=this._shadowAngleScale*this._angle,o=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;r.y3.PerspectiveFovLHToRef(s,1,l?a:o,l?o:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),r.y3.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),n=-i*t,s=1/Math.tan(this._angle/2);r.y3.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof h.x){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;r.y3.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(.5*this._innerAngle)-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=r.P.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=r.P.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 i=this.computeTransformedInformation()?r.P.Normalize(this.transformedDirection):r.P.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=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?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())}}(0,n.gn)([(0,s.qC)()],c.prototype,"angle",null),(0,n.gn)([(0,s.qC)()],c.prototype,"innerAngle",null),(0,n.gn)([(0,s.qC)()],c.prototype,"shadowAngleScale",null),(0,n.gn)([(0,s.qC)()],c.prototype,"exponent",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"projectionTextureLightNear",null),(0,n.gn)([(0,s.qC)()],c.prototype,"projectionTextureLightFar",null),(0,n.gn)([(0,s.qC)()],c.prototype,"projectionTextureUpDirection",null),(0,n.gn)([(0,s.oU)("projectedLightTexture")],c.prototype,"_projectionTexture",void 0)},9953:(e,t,i)=>{i.d(t,{O:()=>n,n:()=>p});var n,s=i(7257),r=i(5757),o=i(1057),a=i(7814),l=i(1431),h=i(2722),c=i(1376),u=i(5661),d=i(1722);!function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(n||(n={}));class p{static get ForceFullSceneLoadingForIncremental(){return c.Z.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){c.Z.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return c.Z.ShowLoadingScreen}static set ShowLoadingScreen(e){c.Z.ShowLoadingScreen=e}static get loggingLevel(){return c.Z.loggingLevel}static set loggingLevel(e){c.Z.loggingLevel=e}static get CleanBoneMatrixWeights(){return c.Z.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){c.Z.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return p._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return p._RegisteredPlugins[e]||(h.Y.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"),p.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in p._RegisteredPlugins){const i=p._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return p._RegisteredPlugins[t]}return p.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),n=e.substring(i,e.length).toLowerCase();return p._GetPluginForExtension(n)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let n="Unable to load from "+e.url;return t?n+=`: ${t}`:i&&(n+=`: ${i}`),n}static _LoadData(e,t,i,n,s,r,o){const l=p._GetDirectLoad(e.url),h=o?p._GetPluginForExtension(o):l?p._GetPluginForDirectLoad(e.url):p._GetPluginForFilename(e.url);let c;if(c=void 0!==h.plugin.createPlugin?h.plugin.createPlugin():h.plugin,!c)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(p.OnPluginActivatedObservable.notifyObservers(c),l&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!(0,u.VL)(e.url))){if(c.directLoad){const e=c.directLoad(t,l);e.then?e.then((e=>{i(c,e)})).catch((e=>{s("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,l);return c}const d=h.isBinary,f=(e,n)=>{t.isDisposed?s("Scene has been disposed"):i(c,e,n)};let _=null,m=!1;const g=c.onDisposeObservable;g&&g.add((()=>{m=!0,_&&(_.abort(),_=null),r()}));const v=()=>{if(m)return;const i=(e,t)=>{s(null==e?void 0:e.statusText,t)},r=e.file||e.url;_=c.loadFile?c.loadFile(t,r,f,n,d,i):t._loadFile(r,f,n,!0,d,i)},y=t.getEngine();let x=y.enableOfflineSupport;if(x){let i=!1;for(const n of t.disableOfflineSupportExceptionRules)if(n.test(e.url)){i=!0;break}x=!i}return x&&a.D.OfflineProviderFactory?t.offlineProvider=a.D.OfflineProviderFactory(e.url,v,y.disableManifestCheck):v(),c}static _GetFileInfo(e,t){let i,n,r=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,n=e.name,r=e}else if("string"==typeof t&&t.startsWith("data:"))i=t,n="";else{const r=t;if("/"===r.substr(0,1))return s.w1.Error("Wrong sceneFilename parameter"),null;i=e+r,n=r}else i=e,n=s.w1.GetFilename(e),e=s.w1.GetFolderPath(e);return{url:i,rootUrl:e,name:n,file:r}}static GetPluginForExtension(e){return p._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!p._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;p._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{p._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",n=l.l.LastCreatedScene,s=null,r=null,o=null,a=null){if(!n)return h.Y.Error("No scene available to import mesh to"),null;const c=p._GetFileInfo(t,i);if(!c)return null;const u={};n.addPendingData(u);const f=()=>{n.removePendingData(u)},_=(e,t)=>{const i=p._FormatErrorMessage(c,e,t);o?o(n,i,new d.LH(i,d.SM.SceneLoaderError,t)):h.Y.Error(i),f()},m=r?e=>{try{r(e)}catch(e){_("Error in onProgress callback: "+e,e)}}:void 0,g=(e,t,i,r,o,a,l)=>{if(n.importedMeshesFiles.push(c.url),s)try{s(e,t,i,r,o,a,l)}catch(e){_("Error in onSuccess callback: "+e,e)}n.removePendingData(u)};return p._LoadData(c,n,((t,i,s)=>{if(t.rewriteRootURL&&(c.rootUrl=t.rewriteRootURL(c.rootUrl,s)),t.importMesh){const s=t,r=new Array,o=new Array,a=new Array;if(!s.importMesh(e,n,i,c.rootUrl,r,o,a,_))return;n.loadingPluginName=t.name,g(r,o,a,[],[],[],[])}else t.importMeshAsync(e,n,i,c.rootUrl,m,c.name).then((e=>{n.loadingPluginName=t.name,g(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights)})).catch((e=>{_(e.message,e)}))}),m,_,f,a)}static ImportMeshAsync(e,t,i="",n=l.l.LastCreatedScene,s=null,r=null){return new Promise(((o,a)=>{p.ImportMesh(e,t,i,n,((e,t,i,n,s,r,a)=>{o({meshes:e,particleSystems:t,skeletons:i,animationGroups:n,transformNodes:s,geometries:r,lights:a})}),s,((e,t,i)=>{a(i||new Error(t))}),r)}))}static Load(e,t="",i=l.l.LastCreatedEngine,n=null,r=null,a=null,h=null){return i?p.Append(e,t,new o.x(i),n,r,a,h):(s.w1.Error("No engine available"),null)}static LoadAsync(e,t="",i=l.l.LastCreatedEngine,n=null,s=null){return new Promise(((r,o)=>{p.Load(e,t,i,(e=>{r(e)}),n,((e,t,i)=>{o(i||new Error(t))}),s)}))}static Append(e,t="",i=l.l.LastCreatedScene,n=null,s=null,r=null,o=null){if(!i)return h.Y.Error("No scene available to append to"),null;const a=p._GetFileInfo(e,t);if(!a)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)};p.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const f=(e,t)=>{const n=p._FormatErrorMessage(a,e,t);r?r(i,n,new d.LH(n,d.SM.SceneLoaderError,t)):h.Y.Error(n),u()},_=s?e=>{try{s(e)}catch(e){f("Error in onProgress callback",e)}}:void 0,m=()=>{if(n)try{n(i)}catch(e){f("Error in onSuccess callback",e)}i.removePendingData(c)};return p._LoadData(a,i,((e,t)=>{if(e.load){if(!e.load(i,t,a.rootUrl,f))return;i.loadingPluginName=e.name,m()}else e.loadAsync(i,t,a.rootUrl,_,a.name).then((()=>{i.loadingPluginName=e.name,m()})).catch((e=>{f(e.message,e)}))}),_,f,u,o)}static AppendAsync(e,t="",i=l.l.LastCreatedScene,n=null,s=null){return new Promise(((r,o)=>{p.Append(e,t,i,(e=>{r(e)}),n,((e,t,i)=>{o(i||new Error(t))}),s)}))}static LoadAssetContainer(e,t="",i=l.l.LastCreatedScene,n=null,s=null,r=null,o=null){if(!i)return h.Y.Error("No scene available to load asset container to"),null;const a=p._GetFileInfo(e,t);if(!a)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)},f=(e,t)=>{const n=p._FormatErrorMessage(a,e,t);r?r(i,n,new d.LH(n,d.SM.SceneLoaderError,t)):h.Y.Error(n),u()},_=s?e=>{try{s(e)}catch(e){f("Error in onProgress callback",e)}}:void 0,m=e=>{if(n)try{n(e)}catch(e){f("Error in onSuccess callback",e)}i.removePendingData(c)};return p._LoadData(a,i,((e,t)=>{if(e.loadAssetContainer){const n=e.loadAssetContainer(i,t,a.rootUrl,f);if(!n)return;i.loadingPluginName=e.name,m(n)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,a.rootUrl,_,a.name).then((t=>{i.loadingPluginName=e.name,m(t)})).catch((e=>{f(e.message,e)})):f("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),_,f,u,o)}static LoadAssetContainerAsync(e,t="",i=l.l.LastCreatedScene,n=null,s=null){return new Promise(((r,o)=>{p.LoadAssetContainer(e,t,i,(e=>{r(e)}),n,((e,t,i)=>{o(i||new Error(t))}),s)}))}static ImportAnimations(e,t="",i=l.l.LastCreatedScene,s=!0,r=n.Clean,o=null,a=null,c=null,u=null,d=null){if(!i)return void h.Y.Error("No scene available to load animations to");if(s){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()})),i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(r){case n.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case n.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case n.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case n.NoSync:break;default:return void h.Y.Error("Unknown animation group loading mode value '"+r+"'")}const p=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(p),o),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)}),c,u,d)}static ImportAnimationsAsync(e,t="",i=l.l.LastCreatedScene,s=!0,r=n.Clean,o=null,a=null,h=null,c=null,u=null){return new Promise(((n,a)=>{p.ImportAnimations(e,t,i,s,r,o,(e=>{n(e)}),h,((e,t,i)=>{a(i||new Error(t))}),u)}))}}p.NO_LOGGING=0,p.MINIMAL_LOGGING=1,p.SUMMARY_LOGGING=2,p.DETAILED_LOGGING=3,p.OnPluginActivatedObservable=new r.y$,p._RegisteredPlugins={},p._ShowingLoadingScreen=!1},1376:(e,t,i)=>{i.d(t,{Z:()=>n});class n{static get ForceFullSceneLoadingForIncremental(){return n._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){n._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return n._ShowLoadingScreen}static set ShowLoadingScreen(e){n._ShowLoadingScreen=e}static get loggingLevel(){return n._LoggingLevel}static set loggingLevel(e){n._LoggingLevel=e}static get CleanBoneMatrixWeights(){return n._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){n._CleanBoneMatrixWeights=e}}n._ForceFullSceneLoadingForIncremental=!1,n._ShowLoadingScreen=!0,n._CleanBoneMatrixWeights=!1,n._LoggingLevel=0},6653:(e,t,i)=>{i.d(t,{K:()=>l});var n=i(468),s=i(3837),r=i(4767),o=i(2208),a=i(2262);class l extends n.k{constructor(e){super(e,r.u.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",s.E.AutoDetect,!1,r.u.VertexAndFragment),this.registerOutput("rgba",s.E.Color4,r.u.Neutral),this.registerOutput("rgb",s.E.Color3,r.u.Neutral),this.registerOutput("r",s.E.Float,r.u.Neutral),this.registerOutput("g",s.E.Float,r.u.Neutral),this.registerOutput("b",s.E.Float,r.u.Neutral),this.registerOutput("a",s.E.Float,r.u.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(s.E.Vector2|s.E.Vector3|s.E.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?r.u.VertexAndFragment:r.u.Fragment:r.u.VertexAndFragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\r\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===r.u.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\r\n`}else this.uv.ownerBlock.target!==r.u.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\r\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\r\n`}_writeOutput(e,t,i,n=!1){if(n){if(e.target===r.u.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}else this.uv.ownerBlock.target!==r.u.Fragment?(e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n"):e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==r.u.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=a.x.Parse(e.texture,t,i))}}(0,o.H)("BABYLON.CurrentScreenBlock",l)},9709:(e,t,i)=>{i.d(t,{g:()=>c});var n=i(9472),s=i(468),r=i(3837),o=i(4767),a=i(2208),l=i(9749),h=i(5346);class c extends s.k{constructor(e){super(e,o.u.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",r.E.Color4,!0),this.registerInput("rgb",r.E.AutoDetect,!0),this.registerInput("a",r.E.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(r.E.Color3|r.E.Vector3|r.E.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){this.useLogarithmicDepth&&i&&h.G.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,n=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||n.isConnected,e.sharedData.blocksWithDefines.push(this),this.useLogarithmicDepth&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const s=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",s),t.connectedPoint)n.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${n.associatedVariableName});\r\n`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName};\r\n`;else if(i.connectedPoint){let t="1.0";n.connectedPoint&&(t=n.associatedVariableName),i.connectedPoint.type===r.E.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\r\n`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t});\r\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+="gl_FragColor = toLinearSpace(gl_FragColor);\r\n",e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+="gl_FragColor = toGammaSpace(gl_FragColor);\r\n",e.compilationString+="#endif\r\n",this.useLogarithmicDepth&&(e.compilationString+="gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n"),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\r\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\r\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\r\n`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var n;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=null!==(n=e.useLogarithmicDepth)&&void 0!==n&&n}}(0,n.gn)([(0,l.p)("Convert to gamma space",l.U.Boolean,"PROPERTIES",{notifiers:{update:!0}})],c.prototype,"convertToGammaSpace",void 0),(0,n.gn)([(0,l.p)("Convert to linear space",l.U.Boolean,"PROPERTIES",{notifiers:{update:!0}})],c.prototype,"convertToLinearSpace",void 0),(0,n.gn)([(0,l.p)("Use logarithmic depth",l.U.Boolean,"PROPERTIES")],c.prototype,"useLogarithmicDepth",void 0),(0,a.H)("BABYLON.FragmentOutputBlock",c)},3426:(e,t,i)=>{var n;i.d(t,{c:()=>n}),function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime"}(n||(n={}))},363:(e,t,i)=>{i.d(t,{S:()=>g});var n=i(468),s=i(3837),r=i(8832),o=i(9135),a=i(4141),l=i(4767),h=i(2208),c=i(6913),u=i(3426),d=i(5757),p=i(8108);const f={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},_={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},m={particle_texturemask:!0};class g extends n.k{get type(){if(this._type===s.E.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=s.E.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=s.E.Vector2,this._type;case"Vector3":return this._type=s.E.Vector3,this._type;case"Vector4":return this._type=s.E.Vector4,this._type;case"Color3":return this._type=s.E.Color3,this._type;case"Color4":return this._type=s.E.Color4,this._type;case"Matrix":return this._type=s.E.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=s.E.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=s.E.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=s.E.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=s.E.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case o.$.World:case o.$.WorldView:case o.$.WorldViewProjection:case o.$.View:case o.$.ViewProjection:case o.$.Projection:return this._type=s.E.Matrix,this._type;case o.$.CameraPosition:return this._type=s.E.Vector3,this._type;case o.$.FogColor:return this._type=s.E.Color3,this._type;case o.$.DeltaTime:case o.$.MaterialAlpha:return this._type=s.E.Float,this._type;case o.$.CameraParameters:return this._type=s.E.Vector4,this._type}}return this._type}constructor(e,t=l.u.Vertex,i=s.E.AutoDetect){super(e,t,!1,!0),this._mode=r.M.Undefined,this._animationType=u.c.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new d.y$,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=r.M.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===s.E.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.M.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=r.M.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.M.Undefined}get isUniform(){return this._mode===r.M.Uniform}set isUniform(e){this._mode=e?r.M.Uniform:r.M.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===r.M.Attribute}set isAttribute(e){this._mode=e?r.M.Attribute:r.M.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===r.M.Varying}set isVarying(e){this._mode=e?r.M.Varying:r.M.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=r.M.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case u.c.Time:this.type===s.E.Float&&(this.value+=.01*e.getAnimationRatio());break;case u.c.RealTime:this.type===s.E.Float&&(this.value=(p.F.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\r\n`:`#ifdef ${e}\r\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case s.E.Float:this.value=0;break;case s.E.Vector2:this.value=a.FM.Zero();break;case s.E.Vector3:this.value=a.P.Zero();break;case s.E.Vector4:this.value=a.Lt.Zero();break;case s.E.Color3:this.value=c.Wo.White();break;case s.E.Color4:this.value=new c.HE(1,1,1,1);break;case s.E.Matrix:this.value=a.y3.Identity()}}_emitConstant(e){switch(this.type){case s.E.Float:return`${e._emitFloat(this.value)}`;case s.E.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case s.E.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case s.E.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case s.E.Color3:return c.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&c.zZ.Color3[0].toGammaSpaceToRef(c.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&c.zZ.Color3[0].toLinearSpaceToRef(c.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${c.zZ.Color3[0].r}, ${c.zZ.Color3[0].g}, ${c.zZ.Color3[0].b})`;case s.E.Color4:return c.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&c.zZ.Color4[0].toGammaSpaceToRef(c.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&c.zZ.Color4[0].toLinearSpaceToRef(c.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${c.zZ.Color4[0].r}, ${c.zZ.Color4[0].g}, ${c.zZ.Color4[0].b}, ${c.zZ.Color4[0].a})`}return""}get _noContextSwitch(){return _[this.name]}_emit(e,t){var i;if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)};\r\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName};\r\n`,t&&(e._uniformDeclaration+="#endif\r\n");const i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case o.$.WorldView:i.needWorldViewMatrix=!0;break;case o.$.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==u.c.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=null!==(i=f[this.name])&&void 0!==i?i:this.name,this.target===l.u.Vertex&&e._vertexState)return void(_[this.name]?m[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t));if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),_[this.name]?m[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName};\r\n`,t&&(e._attributeDeclaration+="#endif\r\n"))}}_transmitWorld(e,t,i,n){if(!this._systemValue)return;const s=this.associatedVariableName;switch(this._systemValue){case o.$.World:e.setMatrix(s,t);break;case o.$.WorldView:e.setMatrix(s,i);break;case o.$.WorldViewProjection:e.setMatrix(s,n)}}_transmit(e,t,i){if(this.isAttribute)return;const n=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case o.$.World:case o.$.WorldView:case o.$.WorldViewProjection:return;case o.$.View:e.setMatrix(n,t.getViewMatrix());break;case o.$.Projection:e.setMatrix(n,t.getProjectionMatrix());break;case o.$.ViewProjection:e.setMatrix(n,t.getTransformMatrix());break;case o.$.CameraPosition:t.bindEyePosition(e,n,!0);break;case o.$.FogColor:e.setColor3(n,t.fogColor);break;case o.$.DeltaTime:e.setFloat(n,t.deltaTime/1e3);break;case o.$.CameraParameters:t.activeCamera&&e.setFloat4(n,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case o.$.MaterialAlpha:e.setFloat(n,i.alpha)}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(null!==r)switch(this.type){case s.E.Float:e.setFloat(n,r);break;case s.E.Int:e.setInt(n,r);break;case s.E.Color3:c.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&c.zZ.Color3[0].toGammaSpaceToRef(c.zZ.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&c.zZ.Color3[0].toLinearSpaceToRef(c.zZ.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(n,c.zZ.Color3[0]);break;case s.E.Color4:c.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&c.zZ.Color4[0].toGammaSpaceToRef(c.zZ.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&c.zZ.Color4[0].toLinearSpaceToRef(c.zZ.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(n,c.zZ.Color4[0]);break;case s.E.Vector2:e.setVector2(n,r);break;case s.E.Vector3:e.setVector3(n,r);break;case s.E.Vector4:e.setVector4(n,r);break;case s.E.Matrix:e.setMatrix(n,r)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}");\r\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${o.$[this._systemValue]});\r\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case s.E.Float:i=`${this.value}`;break;case s.E.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case s.E.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case s.E.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case s.E.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case s.E.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 s.E.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===s.E.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${u.c[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\r\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===r.M.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===r.M.Attribute&&e.type===s.E.Vector3&&(this._type=s.E.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=(0,h.q)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}(0,h.H)("BABYLON.InputBlock",g)},1320:(e,t,i)=>{i.d(t,{D:()=>a});var n=i(468),s=i(3837),r=i(4767),o=i(2208);class a extends n.k{constructor(e){super(e,r.u.Fragment),this._isUnique=!0,this.registerInput("color",s.E.Color4,!1,r.u.Fragment),this.registerInput("alphaTexture",s.E.Float,!1,r.u.Fragment),this.registerInput("alphaColor",s.E.Float,!1,r.u.Fragment),this.registerOutput("blendColor",s.E.Color4,r.u.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!==r.u.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${this._declareOutput(this.blendColor,e)};\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\n #else\n ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}(0,o.H)("BABYLON.ParticleBlendMultiplyBlock",a)},8560:(e,t,i)=>{i.d(t,{p:()=>a});var n=i(468),s=i(3837),r=i(4767),o=i(2208);class a extends n.k{constructor(e){super(e,r.u.Fragment),this._isUnique=!0,this.registerInput("color",s.E.Color4,!1,r.u.Fragment),this.registerOutput("rampColor",s.E.Color4,r.u.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!==r.u.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n vec4 baseColor = ${this.color.associatedVariableName};\n float alpha = ${this.color.associatedVariableName}.a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n ${this._declareOutput(this.rampColor,e)} = baseColor;\n #else\n ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}(0,o.H)("BABYLON.ParticleRampGradientBlock",a)},7010:(e,t,i)=>{i.d(t,{P:()=>h});var n=i(468),s=i(3837),r=i(4767),o=i(363),a=i(2208),l=i(2262);class h extends n.k{constructor(e){super(e,r.u.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",s.E.AutoDetect,!1,r.u.VertexAndFragment),this.registerOutput("rgba",s.E.Color4,r.u.Neutral),this.registerOutput("rgb",s.E.Color3,r.u.Neutral),this.registerOutput("r",s.E.Float,r.u.Neutral),this.registerOutput("g",s.E.Float,r.u.Neutral),this.registerOutput("b",s.E.Float,r.u.Neutral),this.registerOutput("a",s.E.Float,r.u.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(s.E.Vector2|s.E.Vector3|s.E.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e){if(!this.uv.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"particle_uv"===e.name));t||(t=new o.S("uv"),t.setAsAttribute("particle_uv")),t.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n"}_buildBlock(e){if(super._buildBlock(e),e.target===r.u.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\r\n`;for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=l.x.Parse(e.texture,t,i))}}(0,a.H)("BABYLON.ParticleTextureBlock",h)},7123:(e,t,i)=>{i.d(t,{t:()=>a});var n=i(468),s=i(3837),r=i(4767),o=i(2208);class a extends n.k{constructor(e){super(e,r.u.Vertex,!0),this.registerInput("vector",s.E.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e){for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName};\r\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+="vFragmentDepth = 1.0 + gl_Position.w;\r\n",e.compilationString+="gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n"),this}}(0,o.H)("BABYLON.VertexOutputBlock",a)},8022:(e,t,i)=>{i.d(t,{v:()=>a});var n=i(468),s=i(3837),r=i(4767),o=i(2208);class a extends n.k{constructor(e){super(e,r.u.Neutral),this.registerInput("rgba",s.E.Color4,!0),this.registerInput("rgb ",s.E.Color3,!0),this.registerOutput("rgb",s.E.Color3),this.registerOutput("r",s.E.Float),this.registerOutput("g",s.E.Float),this.registerOutput("b",s.E.Float),this.registerOutput("a",s.E.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],n=this._outputs[1],s=this._outputs[2],r=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb;\r\n`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.r;\r\n`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.g;\r\n`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.b;\r\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.a;\r\n`),this}}(0,o.H)("BABYLON.ColorSplitterBlock",a)},3841:(e,t,i)=>{i.d(t,{U:()=>a});var n=i(468),s=i(3837),r=i(4767),o=i(2208);class a extends n.k{constructor(e){super(e,r.u.Neutral),this.registerInput("left",s.E.AutoDetect),this.registerInput("right",s.E.AutoDetect),this.registerOutput("output",s.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MultiplyBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\r\n`,this}}(0,o.H)("BABYLON.MultiplyBlock",a)},2864:(e,t,i)=>{i.d(t,{w:()=>c});var n=i(9472),s=i(468),r=i(3837),o=i(4767),a=i(2208),l=i(4141),h=i(9749);class c extends s.k{constructor(e){super(e,o.u.Neutral),this.sourceRange=new l.FM(-1,1),this.targetRange=new l.FM(0,1),this.registerInput("input",r.E.AutoDetect),this.registerInput("sourceMin",r.E.Float,!0),this.registerInput("sourceMax",r.E.Float,!0),this.registerInput("targetMin",r.E.Float,!0),this.registerInput("targetMax",r.E.Float,!0),this.registerOutput("output",r.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),n=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),r=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${r} - ${s}) / (${n} - ${i});\r\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\r\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\r\n`,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=l.FM.FromArray(e.sourceRange),this.targetRange=l.FM.FromArray(e.targetRange)}}(0,n.gn)([(0,h.p)("From",h.U.Vector2)],c.prototype,"sourceRange",void 0),(0,n.gn)([(0,h.p)("To",h.U.Vector2)],c.prototype,"targetRange",void 0),(0,a.H)("BABYLON.RemapBlock",c)},7238:(e,t,i)=>{i.d(t,{m:()=>a});var n=i(468),s=i(3837),r=i(4767),o=i(2208);class a extends n.k{constructor(e){super(e,r.u.Neutral),this.complementW=1,this.complementZ=0,this.target=r.u.Vertex,this.registerInput("vector",s.E.AutoDetect),this.registerInput("transform",s.E.Matrix),this.registerOutput("output",s.E.Vector4),this.registerOutput("xyz",s.E.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),e.sharedData.blocksWithDefines.push(this);const r=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${r} = mat3(${i.associatedVariableName});\r\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\r\n",e.compilationString+=`${r} = transposeMat3(inverseMat3(${r}));\r\n`,e.compilationString+="#endif\r\n",t.connectedPoint.type){case s.E.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\r\n`;break;case s.E.Vector3:case s.E.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\r\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\r\n`}}else{const n=i.associatedVariableName;switch(t.connectedPoint.type){case s.E.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\r\n`;break;case s.E.Vector3:case s.E.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\r\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * ${t.associatedVariableName};\r\n`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;\r\n`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\r\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\r\n`,e}}(0,o.H)("BABYLON.TransformBlock",a)},3069:(e,t,i)=>{i.d(t,{S:()=>l,p:()=>n});var n,s=i(468),r=i(3837),o=i(4767),a=i(2208);!function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees"}(n||(n={}));class l extends s.k{constructor(e){super(e,o.u.Neutral),this.operation=n.Cos,this.registerInput("input",r.E.AutoDetect),this.registerOutput("output",r.E.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 n.Cos:i="cos";break;case n.Sin:i="sin";break;case n.Abs:i="abs";break;case n.Exp:i="exp";break;case n.Exp2:i="exp2";break;case n.Round:i="round";break;case n.Floor:i="floor";break;case n.Ceiling:i="ceil";break;case n.Sqrt:i="sqrt";break;case n.Log:i="log";break;case n.Tan:i="tan";break;case n.ArcTan:i="atan";break;case n.ArcCos:i="acos";break;case n.ArcSin:i="asin";break;case n.Fract:i="fract";break;case n.Sign:i="sign";break;case n.Radians:i="radians";break;case n.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName});\r\n`,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${n[this.operation]};\r\n`}}(0,a.H)("BABYLON.TrigonometryBlock",l)},8982:(e,t,i)=>{i.d(t,{t:()=>a});var n=i(468),s=i(3837),r=i(4767),o=i(2208);class a extends n.k{constructor(e){super(e,r.u.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",s.E.Vector4,!0),this.registerInput("xyz ",s.E.Vector3,!0),this.registerInput("xy ",s.E.Vector2,!0),this.registerInput("zw ",s.E.Vector2,!0),this.registerInput("x",s.E.Float,!0),this.registerInput("y",s.E.Float,!0),this.registerInput("z",s.E.Float,!0),this.registerInput("w",s.E.Float,!0),this.registerOutput("xyzw",s.E.Vector4),this.registerOutput("xyz",s.E.Vector3),this.registerOutput("xy",s.E.Vector2),this.registerOutput("zw",s.E.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,n=this.z,s=this.w,r=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\r\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\r\n`)):a.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${a.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${a.associatedVariableName}${this._buildSwizzle(3)};\r\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\r\n`)):r.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${r.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};\r\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${r.associatedVariableName}, ${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${r.associatedVariableName}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(3)};\r\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${r.associatedVariableName}${this._buildSwizzle(2)};\r\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\r\n`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)};\r\n`)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};\r\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(3)};\r\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\r\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\r\n`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)};\r\n`)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){var n,s,r,o;super._deserialize(e,t,i),this.xSwizzle=null!==(n=e.xSwizzle)&&void 0!==n?n:"x",this.ySwizzle=null!==(s=e.ySwizzle)&&void 0!==s?s:"y",this.zSwizzle=null!==(r=e.zSwizzle)&&void 0!==r?r:"z",this.wSwizzle=null!==(o=e.wSwizzle)&&void 0!==o?o:"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\r\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\r\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\r\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\r\n`,e}}(0,o.H)("BABYLON.VectorMergerBlock",a)},8832:(e,t,i)=>{var n;i.d(t,{M:()=>n}),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(n||(n={}))},3837:(e,t,i)=>{var n;i.d(t,{E:()=>n}),function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(n||(n={}))},4767:(e,t,i)=>{var n;i.d(t,{u:()=>n}),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(n||(n={}))},2904:(e,t,i)=>{var n;i.d(t,{a:()=>n}),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(n||(n={}))},9135:(e,t,i)=>{var n;i.d(t,{$:()=>n}),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(n||(n={}))},4834:(e,t,i)=>{i.d(t,{O:()=>Y,n:()=>j});var n=i(9472),s=i(580),r=i(1795),o=i(4141),a=i(4649),l=i(7814),h=i(3837),c=i(4767),u=i(1979);class d{constructor(){this.supportUniformBuffers=!1,this.attributes=new Array,this.uniforms=new Array,this.constants=new Array,this.samplers=new Array,this.functions={},this.extensions={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){const t=e.sharedData.emitComments,i=this.target===c.u.Fragment;this.compilationString=`\r\n${t?"//Entry point\r\n":""}void main(void) {\r\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\r\n${t?"//Constants\r\n":""}${this._constantDeclaration}\r\n${this.compilationString}`);let n="";for(const e in this.functions)n+=this.functions[e]+"\r\n";this.compilationString=`\r\n${n}\r\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\r\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\r\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\r\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\r\n${t?"//Varyings\r\n":""}${this.sharedData.varyingDeclaration}\r\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\r\n${t?"//Samplers\r\n":""}${this._samplerDeclaration}\r\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\r\n${t?"//Uniforms\r\n":""}${this._uniformDeclaration}\r\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\r\n${t?"//Attributes\r\n":""}${this._attributeDeclaration}\r\n${this.compilationString}`),this.compilationString="precision highp float;\r\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\r\nprecision highp sampler2DArray;\r\n#endif\r\n"+this.compilationString;for(const e in this.extensions){const t=this.extensions[e];this.compilationString=`\r\n${t}\r\n${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2D ${e};\r\n`,this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};\r\n`,this.samplers.push(e))}_getGLType(e){switch(e){case h.E.Float:return"float";case h.E.Int:return"int";case h.E.Vector2:return"vec2";case h.E.Color3:case h.E.Vector3:return"vec3";case h.E.Color4:case h.E.Vector4:return"vec4";case h.E.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\r\n${t}\r\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\r\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\r\n`;let n=u.Q.IncludesShadersStore[e]+"\r\n";if(this.sharedData.emitComments&&(n=t+"\r\n"+n),!i)return n;if(i.replaceStrings)for(let e=0;e<i.replaceStrings.length;e++){const t=i.replaceStrings[e];n=n.replace(t.search,t.replace)}return n}_emitFunctionFromInclude(e,t,i,n=""){const s=e+n;if(!this.functions[s]){if(!i||!(i.removeAttributes||i.removeUniforms||i.removeVaryings||i.removeIfDef||i.replaceStrings))return i&&i.repeatKey?this.functions[s]=`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\r\n`:this.functions[s]=`#include<${e}>${(null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":""}\r\n`,void(this.sharedData.emitComments&&(this.functions[s]=t+"\r\n"+this.functions[s]));if(this.functions[s]=u.Q.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[s]=t+"\r\n"+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/^\s*?attribute.+$/gm,"")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/^\s*?uniform.+$/gm,"")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/^\s*?varying.+$/gm,"")),i.replaceStrings)for(let e=0;e<i.replaceStrings.length;e++){const t=i.replaceStrings[e];this.functions[s]=this.functions[s].replace(t.search,t.replace)}}}_registerTempVariable(e){return-1===this.sharedData.temps.indexOf(e)&&(this.sharedData.temps.push(e),!0)}_emitVaryingFromString(e,t,i="",n=!1){return-1===this.sharedData.varyings.indexOf(e)&&(this.sharedData.varyings.push(e),i&&(i.startsWith("defined(")?this.sharedData.varyingDeclaration+=`#if ${i}\r\n`:this.sharedData.varyingDeclaration+=`${n?"#ifndef":"#ifdef"} ${i}\r\n`),this.sharedData.varyingDeclaration+=`varying ${t} ${e};\r\n`,i&&(this.sharedData.varyingDeclaration+="#endif\r\n"),!0)}_emitUniformFromString(e,t,i="",n=!1){-1===this.uniforms.indexOf(e)&&(this.uniforms.push(e),i&&(i.startsWith("defined(")?this._uniformDeclaration+=`#if ${i}\r\n`:this._uniformDeclaration+=`${n?"#ifndef":"#ifdef"} ${i}\r\n`),this._uniformDeclaration+=`uniform ${t} ${e};\r\n`,i&&(this._uniformDeclaration+="#endif\r\n"))}_emitFloat(e){return e.toString()===e.toFixed(0)?`${e}.0`:e.toString()}}var p=i(5757);class f{constructor(){this.temps=new Array,this.varyings=new Array,this.varyingDeclaration="",this.inputBlocks=new Array,this.textureBlocks=new Array,this.bindableBlocks=new Array,this.forcedBindableBlocks=new Array,this.blocksWithFallbacks=new Array,this.blocksWithDefines=new Array,this.repeatableContentBlocks=new Array,this.dynamicUniformBlocks=new Array,this.blockingBlocks=new Array,this.animatedInputs=new Array,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.\r\n"),this.checks.emitFragment||(e+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\r\n");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.\r\n`;if(e)throw"Build of NodeMaterial failed:\r\n"+e}}var _=i(1917),m=i(708),g=i(7257),v=i(7238),y=i(7123),x=i(9709),b=i(363),T=i(2208),S=i(3956),E=i(6653),C=i(7010),A=i(8560),P=i(1320),R=i(1434),M=i(6662),I=i(392),D=i(8982),O=i(2864),w=i(3841),N=i(2904),F=i(2262),L=i(5753),B=i(8022),U=i(6290),V=i(7902),k=i(3426),G=i(3069),z=i(9135),W=i(1431),H=i(5346);const X={effect:null,subMesh:null};class j extends _.H{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.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class Y extends s.a{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){super(e,t||W.l.LastCreatedScene),this._buildId=Y._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new o.y3,this._cachedWorldViewProjectionMatrix=new o.y3,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new p.y$,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=new Array,this._mode=N.a.Material,this.forceAlphaBlending=!1,this._options={emitComments:!1,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return g.w1.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return 0!=(e.target&c.u.Vertex)&&this._addVertexOutputNode(e),0!=(e.target&c.u.Fragment)&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(0!=(e.target&c.u.Vertex)&&this._removeVertexOutputNode(e),0!=(e.target&c.u.Fragment)&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=c.u.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=c.u.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_initializeBlock(e,t,i,n=!0){if(e.initialize(t),n&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const s of e.inputs){s.associatedVariableName="";const r=s.connectedPoint;if(r){const s=r.ownerBlock;s!==e&&((s.target===c.u.VertexAndFragment||t.target===c.u.Fragment&&s.target===c.u.Vertex&&s._preparationId!==this._buildId)&&i.push(s),this._initializeBlock(s,t,i,n))}}for(const t of e.outputs)t.associatedVariableName=""}_resetDualBlocks(e,t){e.target===c.u.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const n=i.connectedPoint;if(n){const i=n.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!0){this._buildWasSuccessful=!1;const n=this.getScene().getEngine(),s=this._mode===N.a.Particle;if(0===this._vertexOutputNodes.length&&!s)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new d,this._vertexCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._vertexCompilationState.target=c.u.Vertex,this._fragmentCompilationState=new d,this._fragmentCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._fragmentCompilationState.target=c.u.Fragment,this._sharedData=new f,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=s;const r=[],o=[];for(const e of this._vertexOutputNodes)r.push(e),this._initializeBlock(e,this._vertexCompilationState,o,i);for(const e of this._fragmentOutputNodes)o.push(e),this._initializeBlock(e,this._fragmentCompilationState,r,i);this.optimize();for(const e of r)e.build(this._vertexCompilationState,r);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const e of o)this._resetDualBlocks(e,this._buildId-1);for(const e of o)e.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=Y._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(console.log("Vertex shader:"),console.log(this._vertexCompilationState.compilationString),console.log("Fragment shader:"),console.log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const a=this.getScene().meshes;for(const e of a)if(e.subMeshes)for(const t of e.subMeshes){if(t.getMaterial()!==this)continue;if(!t.materialDefines)continue;const e=t.materialDefines;e.markAllAsDirty(),e.reset()}}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,n=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(m.o.NormalKind),t.TANGENT=e.isVerticesDataPresent(m.o.TangentKind);const r=e.useVertexColors&&e.isVerticesDataPresent(m.o.ColorKind);t.VERTEXCOLOR_NME=r;let o=!1;for(let i=1;i<=6;++i){const n=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),o=o||t["UV"+i]!==n}(i!==t.NORMAL||n!==t.TANGENT||s!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}createPostProcess(e,t=1,i=1,n,s,r=0,o=5){return this.mode!==N.a.PostProcess?(console.log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,n,s,r,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,n=1,s,o,a=0,l=5){let h=this.name+this._buildId;const c=new j,d=new r.x(h+"PostProcess",this.getScene());let p=this._buildId;return this._processDefines(d,c),u.Q.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 I.D(this.name+"PostProcess",h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,n,s,o,c.toString(),a,h,{maxSimultaneousLights:this.maxSimultaneousLights},!1,l),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{p!==this._buildId&&(delete u.Q.ShadersStore[h+"VertexShader"],delete u.Q.ShadersStore[h+"PixelShader"],h=this.name+this._buildId,c.markAllAsDirty(),p=this._buildId),this._processDefines(d,c)&&(u.Q.RegisterShader(h,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),U.Q.SetImmediate((()=>e.updateEffect(c.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,h,h)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==N.a.ProceduralTexture)return console.log("Incompatible material mode"),null;let i=this.name+this._buildId;const n=new V.g(i,e,null,t),s=new r.x(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};const o=new j,a=this._processDefines(s,o);u.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[m.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,o.toString(),null==a?void 0:a.fallbacks,void 0);n.nodeMaterialSource=this,n._setEffect(l);let h=this._buildId;return n.onBeforeGenerationObservable.add((()=>{h!==this._buildId&&(delete u.Q.ShadersStore[i+"VertexShader"],delete u.Q.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,o.markAllAsDirty(),h=this._buildId);const e=this._processDefines(s,o);e&&(u.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),U.Q.SetImmediate((()=>{l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[m.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,o.toString(),null==e?void 0:e.fallbacks,void 0),n._setEffect(l)}))),this._checkInternals(l)})),n}_createEffectForParticles(e,t,i,n,s,o,a,l=""){let h=this.name+this._buildId+"_"+t;o||(o=new j),a||(a=this.getScene().getMeshByName(this.name+"Particle"))||((a=new r.x(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let c=this._buildId;const d=[];let p=l;if(!s){const r=this._processDefines(a,o);u.Q.RegisterShader(h,this._fragmentCompilationState._builtCompilationString),e.fillDefines(d,t),p=d.join("\n"),s=this.getScene().getEngine().createEffectForParticles(h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,o.toString()+"\n"+p,null==r?void 0:r.fallbacks,i,n,e),e.setCustomEffect(s,t)}s.onBindObservable.add((s=>{c!==this._buildId&&(delete u.Q.ShadersStore[h+"PixelShader"],h=this.name+this._buildId+"_"+t,o.markAllAsDirty(),c=this._buildId),d.length=0,e.fillDefines(d,t);const r=d.join("\n");r!==p&&(o.markAllAsDirty(),p=r);const f=this._processDefines(a,o);if(f)return u.Q.RegisterShader(h,this._fragmentCompilationState._builtCompilationString),s=this.getScene().getEngine().createEffectForParticles(h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,o.toString()+"\n"+p,null==f?void 0:f.fallbacks,i,n,e),e.setCustomEffect(s,t),void this._createEffectForParticles(e,t,i,n,s,o,a,l);this._checkInternals(s)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){this.mode===N.a.Particle?(this._createEffectForParticles(e,L.U.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,L.U.BLENDMODE_MULTIPLY,t,i)):console.log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===N.a.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):console.log("Incompatible material mode")}_processDefines(e,t,i=!1,n){let s=null;const r=this.getScene();if(H.G.PrepareDefinesForCamera(r,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((n=>{n.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((s=>{s.prepareDefines(e,this,t,i,n)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const n=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,n)}));const r=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===r.indexOf(e)&&r.push(e)}));const o=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===o.indexOf(e)&&o.push(e)}));const a=new R.L;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,a)})),s={lightDisposed:i,uniformBuffers:n,mergedUniforms:r,mergedSamplers:o,fallbacks:a}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const n=this.getScene();if(this._sharedData.animatedInputs){const e=n.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(n);this._animationFrame=e}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new j);const s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=n.getEngine();if(this._prepareDefinesForAttributes(e,s),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,s,i))))return!1;const o=this._processDefines(e,s,i,t);if(o){const e=t.effect,i=s.toString();let a=r.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:o.mergedUniforms,uniformBuffersNames:o.uniformBuffers,samplers:o.mergedSamplers,defines:i,fallbacks:o.fallbacks,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},r);if(a)if(this._onEffectCreatedObservable&&(X.effect=a,X.subMesh=t,this._onEffectCreatedObservable.notifyObservers(X)),this.allowShaderHotSwapping&&e&&!a.isReady()){if(a=e,s.markAsUnprocessed(),o.lightDisposed)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(a,s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}get compiledShaders(){return`// Vertex shader\r\n${this._vertexCompilationState.compilationString}\r\n\r\n// Fragment shader\r\n${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const t of this._sharedData.inputBlocks)t._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);const r=this._mustRebind(n,s,t.visibility),o=this._sharedData;if(r){for(const e of o.bindableBlocks)e.bind(s,this,t,i);for(const e of o.forcedBindableBlocks)e.bind(s,this,t,i);for(const e of o.inputBlocks)e._transmit(s,n,this)}else if(!this.isFrozen)for(const e of o.forcedBindableBlocks)e.bind(s,this,t,i);this._afterBind(t,this._activeEffect)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)Y._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const e of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))e.dispose();for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(){this.BJSNODEMATERIALEDITOR.NodeEditor.Show({nodeMaterial:this})}edit(e){return new Promise((t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:Y.EditorURL;g.w1.LoadScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(),t()}))}else this._createNodeEditor(),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new b.S("Position");e.setAsAttribute("position");const t=new b.S("World");t.setAsSystemValue(z.$.World);const i=new v.m("WorldPos");e.connectTo(i),t.connectTo(i);const n=new b.S("ViewProjection");n.setAsSystemValue(z.$.ViewProjection);const s=new v.m("WorldPos * ViewProjectionTransform");i.connectTo(s),n.connectTo(s);const r=new y.t("VertexOutput");s.connectTo(r);const o=new b.S("color");o.value=new a.HE(.8,.8,.8,1);const l=new x.g("FragmentOutput");o.connectTo(l),this.addOutputNode(r),this.addOutputNode(l),this._mode=N.a.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new b.S("Position");e.setAsAttribute("position2d");const t=new b.S("Constant1");t.isConstant=!0,t.value=1;const i=new D.t("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const n=new y.t("VertexOutput");i.connectTo(n);const s=new b.S("Scale");s.visibleInInspector=!0,s.value=new o.FM(1,1);const r=new O.w("uv0");e.connectTo(r);const a=new w.U("UV scale");r.connectTo(a),s.connectTo(a);const l=new E.K("CurrentScreen");a.connectTo(l),l.texture=new F.x("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const h=new x.g("FragmentOutput");l.connectTo(h,{output:"rgba"}),this.addOutputNode(n),this.addOutputNode(h),this._mode=N.a.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new b.S("Position");e.setAsAttribute("position2d");const t=new b.S("Constant1");t.isConstant=!0,t.value=1;const i=new D.t("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const n=new y.t("VertexOutput");i.connectTo(n);const s=new b.S("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=k.c.Time,s.isConstant=!1;const r=new b.S("Color3");r.value=new a.Wo(1,1,1),r.isConstant=!1;const o=new x.g("FragmentOutput"),l=new D.t("VectorMerger");l.visibleInInspector=!1;const h=new G.S("Cos");h.operation=G.p.Cos,e.connectTo(l),s.output.connectTo(h.input),h.output.connectTo(l.z),l.xyzOut.connectTo(o.rgb),this.addOutputNode(n),this.addOutputNode(o),this._mode=N.a.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new b.S("uv");e.setAsAttribute("particle_uv");const t=new C.P("ParticleTexture");e.connectTo(t);const i=new b.S("Color");i.setAsAttribute("particle_color");const n=new w.U("Texture * Color");t.connectTo(n),i.connectTo(n);const s=new A.p("ParticleRampGradient");n.connectTo(s);const r=new B.v("ColorSplitter");i.connectTo(r);const o=new P.D("ParticleBlendMultiply");s.connectTo(o),t.connectTo(o,{output:"a"}),r.connectTo(o,{output:"a"});const a=new x.g("FragmentOutput");o.connectTo(a),this.addOutputNode(a),this._mode=N.a.Particle}async loadAsync(e,t=""){return Y.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const n=i.connectedPoint;if(n){const i=n.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,t);const n=[];for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,n);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\r\n`;for(const n of t)n.isInput&&-1===e.indexOf(n)&&(s+=n._dumpCode(i,e));for(const t of n)t.isInput&&-1===e.indexOf(t)&&(s+=t._dumpCode(i,e));e=[],s+="\r\n// Connections\r\n";for(const t of this._vertexOutputNodes)s+=t._dumpCodeForOutputConnections(e);for(const t of this._fragmentOutputNodes)s+=t._dumpCodeForOutputConnections(e);s+="\r\n// Output nodes\r\n";for(const e of this._vertexOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName});\r\n`;for(const e of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName});\r\n`;return s+="nodeMaterial.build();\r\n",s}serialize(e){const t=e?{}:S.p4.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(const n of e.outputs)for(const s of t.blocks){const r=i[s.id];if(r)for(const o of s.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==n.name);else{const e=r.getInputByName(o.inputName);if(!e||e.isConnected)continue;n.connectTo(e,!0),this._restoreConnections(r,t,i)}}}parseSerializedObject(e,t="",i=!1){var n;i||this.clear();const s={};for(const i of e.blocks){const e=(0,T.q)(i.customType);if(e){const n=new e;n._deserialize(i,this.getScene(),t),s[i.id]=n,this.attachedBlocks.push(n)}}for(let t=0;t<e.blocks.length;t++){const n=s[e.blocks[t].id];n&&(n.inputs.length&&!i||this._restoreConnections(n,e,s))}if(e.outputNodes)for(const t of e.outputNodes)this.addOutputNode(s[t]);if(e.locations||e.editorData&&e.editorData.locations){const t=e.locations||e.editorData.locations;for(const e of t)s[e.blockId]&&(e.blockId=s[e.blockId].uniqueId);i&&this.editorData&&this.editorData.locations&&t.concat(this.editorData.locations),e.locations?this.editorData={locations:t}:(this.editorData=e.editorData,this.editorData.locations=t);const n=[];for(const e in s)n[e]=s[e].uniqueId;this.editorData.map=n}this.comment=e.comment,void 0!==e.forceAlphaBlending&&(this.forceAlphaBlending=e.forceAlphaBlending),i||(this._mode=null!==(n=e.mode)&&void 0!==n?n:N.a.Material)}loadFromSerialization(e,t="",i=!1){this.parseSerializedObject(e,t,i)}clone(e,t=!1){const i=this.serialize(),n=S.p4.Clone((()=>new Y(e,this.getScene(),this.options)),this);return n.id=e,n.name=e,n.parseSerializedObject(i),n._buildId=this._buildId,n.build(!1,!t),n}static Parse(e,t,i=""){const n=S.p4.Parse((()=>new Y(e.name,t)),e,t,i);return n.parseSerializedObject(e,i),n.build(),n}static async ParseFromFileAsync(e,t,i,n="",s=!1,r){const o=null!=r?r:new Y(e,i),a=await i._loadFileAsync(t),l=JSON.parse(a);return o.parseSerializedObject(l,n),s||o.build(),o}static ParseFromSnippetAsync(e,t=W.l.LastCreatedScene,i="",n,s=!1){return"_BLANK"===e?Promise.resolve(Y.CreateDefault("blank",t)):new Promise(((r,o)=>{const a=new M.g;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const l=JSON.parse(JSON.parse(a.responseText).jsonPayload),h=JSON.parse(l.nodeMaterial);n||((n=S.p4.Parse((()=>new Y(e,t)),h,t,i)).uniqueId=t.getUniqueId()),n.parseSerializedObject(h),n.snippetId=e;try{s||n.build(),r(n)}catch(e){o(e)}}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}static CreateDefault(e,t){const i=new Y(e,t);return i.setToDefault(),i.build(),i}}Y._BuildIdGenerator=0,Y.EditorURL=`https://unpkg.com/babylonjs-node-editor@${l.D.Version}/babylon.nodeEditor.js`,Y.SnippetUrl="https://snippet.babylonjs.com",Y.IgnoreTexturesAtLoadTime=!1,(0,n.gn)([(0,S.qC)()],Y.prototype,"ignoreAlpha",void 0),(0,n.gn)([(0,S.qC)()],Y.prototype,"maxSimultaneousLights",void 0),(0,n.gn)([(0,S.qC)("mode")],Y.prototype,"_mode",void 0),(0,n.gn)([(0,S.qC)("comment")],Y.prototype,"comment",void 0),(0,n.gn)([(0,S.qC)()],Y.prototype,"forceAlphaBlending",void 0),(0,T.H)("BABYLON.NodeMaterial",Y)},468:(e,t,i)=>{i.d(t,{k:()=>l});var n=i(3837),s=i(8660),r=i(4767),o=i(8718),a=i(2208);class l{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){0==(this._target&e)&&(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}constructor(e,t=r.u.Vertex,i=!1,n=!1){this._isFinalMerger=!1,this._isInput=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===r.u.Neutral,this._isFinalMerger=i,this._isInput=n,this._name=e,this.uniqueId=o.K.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===r.u.Neutral}initialize(e){}bind(e,t,i,n){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}registerInput(e,t,i=!1,n,r){return(r=null!=r?r:new s.VT(e,this,s.Ab.Input)).type=t,r.isOptional=i,n&&(r.target=n),this._inputs.push(r),this}registerOutput(e,t,i,n){return(n=null!=n?n:new s.VT(e,this,s.Ab.Output)).type=t,i&&(n.target=i),this._outputs.push(n),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==n.E.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===r.u.Neutral||0!=(e.target&t.target))return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),n=!0;for(;n;){const s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),n=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,n){}provideFallbacks(e,t){}initializeDefines(e,t,i,n=!1){}prepareDefines(e,t,i,n=!1,s){}autoConfigure(e){}replaceRepeatableContent(e,t,i,n){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))||this.target===r.u.Vertex||this.target!==r.u.VertexAndFragment&&this.target!==r.u.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))}isReady(e,t,i,n=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,n){e.build(t,n);const s=null!=t._vertexState,o=e._buildTarget===r.u.Vertex&&e.target!==r.u.VertexAndFragment;if(s&&(0==(e.target&e._buildTarget)||0==(e.target&i.target)||this.target!==r.u.VertexAndFragment&&o)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName};\r\n`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==r.u.Neutral){if(0==(i.target&this.target))continue;if(0==(i.target&e.target))continue}const n=i.connectedPoint.ownerBlock;n&&n!==this&&this._processBuild(n,e,i,t)}if(this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&console.log(`${e.target===r.u.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case r.u.Vertex:e.sharedData.checks.emitVertex=!0;break;case r.u.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\r\n//${this.name}\r\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(0!=(i.target&e.target))for(const n of i.endpoints){const i=n.ownerBlock;i&&0!=(i.target&e.target)&&-1!==t.indexOf(i)&&this._processBuild(i,e,n,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\r\n${e}.visibleOnFrame = ${this.visibleOnFrame};\r\n${e}.target = ${this.target};\r\n`}_dumpCode(e,t){let i;t.push(this);const n=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=n||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=n+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName),i=`\r\n// ${this.getClassName()}\r\n`,this.comments&&(i+=`// ${this.comments}\r\n`),i+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\r\n`,i+=this._dumpPropertiesCode();for(const n of this.inputs){if(!n.isConnected)continue;const s=n.connectedPoint.ownerBlock;-1===t.indexOf(s)&&(i+=s._dumpCode(e,t))}for(const n of this.outputs)if(n.hasEndpoints)for(const s of n.endpoints){const n=s.ownerBlock;n&&-1===t.indexOf(n)&&(i+=n._dumpCode(e,t))}return i}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const n=i.connectedPoint,s=n.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(n.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\r\n`}return t}clone(e,t=""){const i=this.serialize(),n=(0,a.q)(i.customType);if(n){const s=new n;return s._deserialize(i,e,t),s}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){var n;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(n=e.target)&&void 0!==n?n:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}},8660:(e,t,i)=>{i.d(t,{Ab:()=>s,VT:()=>l,WS:()=>n});var n,s,r=i(3837),o=i(4767),a=i(5757);!function(e){e[e.Compatible=0]="Compatible",e[e.TypeIncompatible=1]="TypeIncompatible",e[e.TargetIncompatible=2]="TargetIncompatible",e[e.HierarchyIssue=3]="HierarchyIssue"}(n||(n={})),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(s||(s={}));class l{static AreEquivalentTypes(e,t){switch(e){case r.E.Vector3:if(t===r.E.Color3)return!0;break;case r.E.Vector4:if(t===r.E.Color4)return!0;break;case r.E.Color3:if(t===r.E.Vector3)return!0;break;case r.E.Color4:if(t===r.E.Vector4)return!0}return!1}get direction(){return this._direction}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===r.E.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===r.E.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._type=e}get target(){return this._prioritizeVertex&&this._ownerBlock?this._target!==o.u.VertexAndFragment?this._target:this._ownerBlock.target===o.u.Fragment?o.u.Fragment:o.u.Vertex:this._target}set target(e){this._target=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get isConnectedToInputBlock(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map((e=>e.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===o.u.Vertex)return!0;if((e.ownerBlock.target===o.u.Neutral||e.ownerBlock.target===o.u.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===o.u.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===o.u.Vertex)return!0;if(e.target===o.u.Vertex)return!0;if((e.ownerBlock.target===o.u.Neutral||e.ownerBlock.target===o.u.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===o.u.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===o.u.Fragment)return!0;if((e.ownerBlock.target===o.u.Neutral||e.ownerBlock.target===o.u.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInFragmentShader)))return!0}return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=new Array,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=r.E.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=new Array,this.excludedConnectionPointTypes=new Array,this.onConnectionObservable=new a.y$,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=o.u.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===n.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===o.u.Fragment){if(i.target===o.u.Vertex)return n.TargetIncompatible;for(const e of i.outputs)if(e.ownerBlock.target!=o.u.Neutral&&e.isConnectedInVertexShader)return n.TargetIncompatible}if(this.type!==e.type&&e.innerType!==r.E.AutoDetect)return l.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&l.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?n.Compatible:n.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return n.TypeIncompatible;let a=i,h=t;return this.direction===s.Input&&(a=t,h=i),a.isAnAncestorOf(h)?n.HierarchyIssue:n.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t<r.E.All;)e&t||this.excludedConnectionPointTypes.push(t),t<<=1}serialize(e=!0){const t={};return t.name=this.name,t.displayName=this.displayName,e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name,t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),(this.isExposedOnFrame||this.exposedPortPosition>=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}}},9749:(e,t,i)=>{var n;function s(e,t=n.Boolean,i="PROPERTIES",s){return(n,r)=>{let o=n._propStore;o||(o=[],n._propStore=o),o.push({propertyName:r,displayName:e,type:t,groupName:i,options:null!=s?s:{}})}}i.d(t,{U:()=>n,p:()=>s}),function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(n||(n={}))},9482:(e,t,i)=>{i.d(t,{i:()=>u,u:()=>d});var n=i(9472),s=i(3956),r=i(708),o=i(4141),a=i(85),l=i(5346),h=i(8449),c=i(1917);class u extends c.H{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.MAINUV1=!1}}class d extends h.n{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new u,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new o.FM(1,0),this._texture=null,this.texture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&a.k.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(r.o.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&a.k.AnisotropicTextureEnabled?l.G.PrepareDefinesForMergedUV(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&a.k.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),l.G.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&a.k.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"}]}}}(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],d.prototype,"isEnabled",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"intensity",void 0),(0,n.gn)([(0,s.QC)()],d.prototype,"direction",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],d.prototype,"texture",void 0)},1444:(e,t,i)=>{i.d(t,{d:()=>l});var n=i(9472),s=i(3956),r=i(1917),o=i(8449);class a extends r.H{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 l extends o.n{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new a,t),this._useEnergyConservation=l.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=l.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=l.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=l.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=l.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=l.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=l.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=l.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"}}l.DEFAULT_USE_ENERGY_CONSERVATION=!0,l.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,l.DEFAULT_USE_SPHERICAL_HARMONICS=!0,l.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsMiscDirty")],l.prototype,"useEnergyConservation",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsMiscDirty")],l.prototype,"useSmithVisibilityHeightCorrelated",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsMiscDirty")],l.prototype,"useSphericalHarmonics",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsMiscDirty")],l.prototype,"useSpecularGlossinessInputEnergyConservation",void 0)},5843:(e,t,i)=>{i.d(t,{m:()=>N,r:()=>w});var n=i(9472),s=i(3956),r=i(2722),o=i(5363),a=i(6344),l=i(1057),h=i(4141),c=i(708),u=i(1444),d=i(178),p=i(4649),f=i(1128),_=i(4475),m=i(7104),g=i(1698),v=i(1917),y=i(580),x=i(5346),b=i(2262),T=i(85),S=(i(452),i(8104));i(8190),i(1868),i(3055);S.v.IncludesShadersStore.pbrFragmentDeclaration="uniform vec4 vEyePosition;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec4 vMetallicReflectanceFactors;\nuniform vec3 vEmissiveColor;\nuniform float visibility;\nuniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;\nuniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;\nuniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;\nuniform vec2 vClearCoatTangentSpaceParams;\nuniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;\nuniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\nuniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;\nuniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\nuniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;\nuniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;\nuniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;\nuniform vec3 vDiffusionDistance;\nuniform vec4 vTintColor;\nuniform vec3 vSubSurfaceIntensity;\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include<decalFragmentDeclaration>\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;\nuniform vec3 vSphericalL1_1;\nuniform vec3 vSphericalL10;\nuniform vec3 vSphericalL11;\nuniform vec3 vSphericalL2_2;\nuniform vec3 vSphericalL2_1;\nuniform vec3 vSphericalL20;\nuniform vec3 vSphericalL21;\nuniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n",i(2963),i(4804);S.v.IncludesShadersStore.pbrUboDeclaration="layout(std140,column_major) uniform;\nuniform Material {\nvec2 vAlbedoInfos;\nvec4 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec3 vReflectivityInfos;\nvec2 vMicroSurfaceSamplerInfos;\nvec2 vReflectionInfos;\nvec2 vReflectionFilteringInfo;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec3 vBumpInfos;\nmat4 albedoMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 reflectivityMatrix;\nmat4 microSurfaceSamplerMatrix;\nmat4 bumpMatrix;\nvec2 vTangentSpaceParams;\nmat4 reflectionMatrix;\nvec3 vReflectionColor;\nvec4 vAlbedoColor;\nvec4 vLightingIntensity;\nvec3 vReflectionMicrosurfaceInfos;\nfloat pointSize;\nvec4 vReflectivityColor;\nvec3 vEmissiveColor;\nvec3 vAmbientColor;\nvec2 vDebugMode;\nvec4 vMetallicReflectanceFactors;\nvec2 vMetallicReflectanceInfos;\nmat4 metallicReflectanceMatrix;\nvec2 vReflectanceInfos;\nmat4 reflectanceMatrix;\nvec3 vSphericalL00;\nvec3 vSphericalL1_1;\nvec3 vSphericalL10;\nvec3 vSphericalL11;\nvec3 vSphericalL2_2;\nvec3 vSphericalL2_1;\nvec3 vSphericalL20;\nvec3 vSphericalL21;\nvec3 vSphericalL22;\nvec3 vSphericalX;\nvec3 vSphericalY;\nvec3 vSphericalZ;\nvec3 vSphericalXX_ZZ;\nvec3 vSphericalYY_ZZ;\nvec3 vSphericalZZ;\nvec3 vSphericalXY;\nvec3 vSphericalYZ;\nvec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include<sceneUboDeclaration>\n#include<meshUboDeclaration>\n",i(6637);S.v.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include<mainUVVaryingDeclaration>[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n",i(2557),i(3756),i(1015);S.v.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";S.v.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;\nuniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;\nuniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#endif\n",i(5141),i(6390),i(1030),i(9519),i(1423),i(4022),i(3897);S.v.IncludesShadersStore.pbrHelperFunctions="#define RECIPROCAL_PI2 0.15915494\n#define RECIPROCAL_PI 0.31830988618\n#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{\nreturn square(roughness)+MINIMUMVARIANCE;\n}\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=saturate(reflectance0*25.0);\nreturn reflectance90;\n}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);\nvec3 nDfdy=dFdy(normalVector.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\nfloat geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\ngeometricAlphaGFactor*=0.75;\nreturn vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\nfloat alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);\nfloat alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);\nreturn vec2(alphaT,alphaB);\n}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy) {\nvec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;\nvec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);\nvec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);\nvec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));\nreturn anisotropicNormal;\n}\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {\nreturn exp(-alpha*distance);\n}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {\nreturn cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));\n}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {\nreturn -log(color)/distance;\n}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\nvec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);\nreturn clearCoatAbsorption;\n}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n#endif\n",i(3660),i(3996);S.v.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {\nreturn vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));\n}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz *Nz+C1;\nvec3 t2=a2 *Ny+t1;\nvec3 t3=b3 *Nx+t2;\nreturn t3;\n}\n#endif\n#endif\n";S.v.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat lightDistance;\nfloat attenuation;\nvec3 L;\nvec3 H;\nfloat NdotV;\nfloat NdotLUnclamped;\nfloat NdotL;\nfloat VdotH;\nfloat roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};\npreLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nresult.lightDistance=sqrt(result.lightDistanceSquared);\nresult.L=normalize(result.lightOffset);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.lightDistance=length(-lightData.xyz);\nresult.L=normalize(-lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.NdotL=dot(N,lightData.xyz)*0.5+0.5;\nresult.NdotL=saturateEps(result.NdotL);\nresult.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;\n}";S.v.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/maxEps(lightDistanceSquared);\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nfloat lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=saturate(1.0-factor*factor);\nattenuation*=attenuation;\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=saturate(cd*lightAngleScale+lightAngleOffset);\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}",i(3154),i(4115);S.v.IncludesShadersStore.pbrDirectLightingFunctions="#define CLEARCOATREFLECTANCE90 1.0\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef CLEARCOAT\nvec4 clearCoat;\n#endif\n#ifdef SHEEN\nvec3 sheen;\n#endif\n};\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\nfloat lightRoughness=lightRadius/lightDistance;\nfloat totalRoughness=saturate(lightRoughness+roughness);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nvec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {\nreturn mix(groundColor,lightColor,info.NdotL);\n}\nvec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {\nfloat diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);\nreturn diffuseTerm*info.attenuation*info.NdotL*lightColor;\n}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}\n#ifdef SS_TRANSLUCENCY\nvec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {\nfloat NdotL=absEps(info.NdotLUnclamped);\nfloat wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);\nfloat trAdapt=step(0.,info.NdotLUnclamped);\nvec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);\nfloat diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);\nreturn diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;\n}\n#endif\n#ifdef SPECULARTERM\nvec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\nfloat NdotH=saturateEps(dot(N,info.H));\nfloat roughness=max(info.roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nvec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);\n#else\nfloat smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);\n#endif\nvec3 specTerm=fresnel*distribution*smithVisibility;\nreturn specTerm*info.attenuation*info.NdotL*lightColor;\n}\n#endif\n#ifdef ANISOTROPIC\nvec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\nfloat NdotH=saturateEps(dot(N,info.H));\nfloat TdotH=dot(T,info.H);\nfloat BdotH=dot(B,info.H);\nfloat TdotV=dot(T,V);\nfloat BdotV=dot(B,V);\nfloat TdotL=dot(T,info.L);\nfloat BdotL=dot(B,info.L);\nfloat alphaG=convertRoughnessToAverageSlope(info.roughness);\nvec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);\nalphaTB=max(alphaTB,square(geometricRoughnessFactor));\nvec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nfloat distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);\nfloat smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);\nvec3 specTerm=fresnel*distribution*smithVisibility;\nreturn specTerm*info.attenuation*info.NdotL*lightColor;\n}\n#endif\n#ifdef CLEARCOAT\nvec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {\nfloat NccdotL=saturateEps(dot(Ncc,info.L));\nfloat NccdotH=saturateEps(dot(Ncc,info.H));\nfloat clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\nfloat fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);\nfresnel*=clearCoatIntensity;\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);\nfloat kelemenVisibility=visibility_Kelemen(info.VdotH);\nfloat clearCoatTerm=fresnel*distribution*kelemenVisibility;\nreturn vec4(\nclearCoatTerm*info.attenuation*NccdotL*lightColor,\n1.0-fresnel\n);\n}\nvec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\nvec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);\nfloat NdotLRefract=saturateEps(dot(Ncc,LRefract));\nvec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);\nreturn absorption;\n}\n#endif\n#ifdef SHEEN\nvec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\nfloat NdotH=saturateEps(dot(N,info.H));\nfloat roughness=max(info.roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat fresnel=1.;\nfloat distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);\n/*#ifdef SHEEN_SOFTER\nfloat visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);\n#else */\nfloat visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);\n/* #endif */\nfloat sheenTerm=fresnel*distribution*visibility;\nreturn sheenTerm*info.attenuation*info.NdotL*lightColor;\n}\n#endif\n";S.v.IncludesShadersStore.pbrIBLFunctions="#if defined(REFLECTION) || defined(SS_REFRACTION)\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {\nfloat microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {\nfloat lod=log2(cubeMapDimensionPixels)*roughness;\nreturn lod;\n}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn saturate(square(temp)-1.0+ambientOcclusion);\n}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {\nvec3 reflection=reflect(view,normal);\nfloat temp=saturate(1.0+1.1*dot(reflection,geometricNormal));\nreturn square(temp);\n}\n#endif\n#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nreturn getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);\n}\n#endif\n",i(8882),i(7441),i(2132),i(8074);S.v.IncludesShadersStore.pbrBlockAlbedoOpacity="struct albedoOpacityOutParams\n{\nvec3 surfaceAlbedo;\nfloat alpha;\n};\n#define pbr_inline\nvoid albedoOpacityBlock(\nin vec4 vAlbedoColor,\n#ifdef ALBEDO\nin vec4 albedoTexture,\nin vec2 albedoInfos,\n#endif\n#ifdef OPACITY\nin vec4 opacityMap,\nin vec2 vOpacityInfos,\n#endif\n#ifdef DETAIL\nin vec4 detailColor,\nin vec4 vDetailInfos,\n#endif\n#ifdef DECAL\nin vec4 decalColor,\nin vec4 vDecalInfos,\n#endif\nout albedoOpacityOutParams outParams\n)\n{\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\n#ifdef GAMMAALBEDO\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\n#else\nsurfaceAlbedo*=albedoTexture.rgb;\n#endif\nsurfaceAlbedo*=albedoInfos.y;\n#endif\n#include<decalFragment>\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nsurfaceAlbedo*=vColor.rgb;\n#endif\n#ifdef DETAIL\nfloat detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);\nsurfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; \n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALBEDO\n#ifdef OPACITY\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\nalpha=1.0;\n#endif\n#endif\n#endif\noutParams.surfaceAlbedo=surfaceAlbedo;\noutParams.alpha=alpha;\n}\n";S.v.IncludesShadersStore.pbrBlockReflectivity="struct reflectivityOutParams\n{\nfloat microSurface;\nfloat roughness;\nvec3 surfaceReflectivityColor;\n#ifdef METALLICWORKFLOW\nvec3 surfaceAlbedo;\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\nvec3 ambientOcclusionColor;\n#endif\n#if DEBUGMODE>0\nvec4 surfaceMetallicColorMap;\nvec4 surfaceReflectivityColorMap;\nvec2 metallicRoughness;\nvec3 metallicF0;\n#endif\n};\n#define pbr_inline\nvoid reflectivityBlock(\nin vec4 vReflectivityColor,\n#ifdef METALLICWORKFLOW\nin vec3 surfaceAlbedo,\nin vec4 metallicReflectanceFactors,\n#endif\n#ifdef REFLECTIVITY\nin vec3 reflectivityInfos,\nin vec4 surfaceMetallicOrReflectivityColorMap,\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\nin vec3 ambientOcclusionColorIn,\n#endif\n#ifdef MICROSURFACEMAP\nin vec4 microSurfaceTexel,\n#endif\n#ifdef DETAIL\nin vec4 detailColor,\nin vec4 vDetailInfos,\n#endif\nout reflectivityOutParams outParams\n)\n{\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\n#if DEBUGMODE>0\noutParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;\n#endif\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);\noutParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;\n#endif\n#endif\n#endif\n#ifdef DETAIL\nfloat detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);\nfloat loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);\nfloat hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);\nmetallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));\n#endif\n#ifdef MICROSURFACEMAP\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n#if DEBUGMODE>0\noutParams.metallicRoughness=metallicRoughness;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS\nmicroSurface=1.0-metallicRoughness.g;\nvec3 baseColor=surfaceAlbedo;\n#ifdef FROSTBITE_REFLECTANCE\noutParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);\nsurfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);\n#else\nvec3 metallicF0=metallicReflectanceFactors.rgb;\n#if DEBUGMODE>0\noutParams.metallicF0=metallicF0;\n#endif\noutParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);\nsurfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);\n#endif\n#else\n#ifdef REFLECTIVITY\nsurfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;\n#if DEBUGMODE>0\noutParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceMetallicOrReflectivityColorMap.a;\nmicroSurface*=reflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE\n#endif\n#endif\n#endif\nmicroSurface=saturate(microSurface);\nfloat roughness=1.-microSurface;\noutParams.microSurface=microSurface;\noutParams.roughness=roughness;\noutParams.surfaceReflectivityColor=surfaceReflectivityColor;\n}\n";S.v.IncludesShadersStore.pbrBlockAmbientOcclusion="struct ambientOcclusionOutParams\n{\nvec3 ambientOcclusionColor;\n#if DEBUGMODE>0\nvec3 ambientOcclusionColorMap;\n#endif\n};\n#define pbr_inline\nvoid ambientOcclusionBlock(\n#ifdef AMBIENT\nin vec3 ambientOcclusionColorMap_,\nin vec4 vAmbientInfos,\n#endif\nout ambientOcclusionOutParams outParams\n)\n{\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#if DEBUGMODE>0\noutParams.ambientOcclusionColorMap=ambientOcclusionColorMap;\n#endif\n#endif\noutParams.ambientOcclusionColor=ambientOcclusionColor;\n}\n";S.v.IncludesShadersStore.pbrBlockAlphaFresnel="#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nstruct alphaFresnelOutParams\n{\nfloat alpha;\n};\n#define pbr_inline\nvoid alphaFresnelBlock(\nin vec3 normalW,\nin vec3 viewDirectionW,\nin float alpha,\nin float microSurface,\nout alphaFresnelOutParams outParams\n)\n{\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\noutParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (outParams.alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\noutParams.alpha=1.0;\n#endif\n#endif\n}\n#endif\n#endif\n";S.v.IncludesShadersStore.pbrBlockAnisotropic="#ifdef ANISOTROPIC\nstruct anisotropicOutParams\n{\nfloat anisotropy;\nvec3 anisotropicTangent;\nvec3 anisotropicBitangent;\nvec3 anisotropicNormal;\n#if DEBUGMODE>0\nvec3 anisotropyMapData;\n#endif\n};\n#define pbr_inline\nvoid anisotropicBlock(\nin vec3 vAnisotropy,\n#ifdef ANISOTROPIC_TEXTURE\nin vec3 anisotropyMapData,\n#endif\nin mat3 TBN,\nin vec3 normalW,\nin vec3 viewDirectionW,\nout anisotropicOutParams outParams\n)\n{\nfloat anisotropy=vAnisotropy.b;\nvec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);\n#ifdef ANISOTROPIC_TEXTURE\nanisotropy*=anisotropyMapData.b;\nanisotropyDirection.rg*=anisotropyMapData.rg*2.0-1.0;\n#if DEBUGMODE>0\noutParams.anisotropyMapData=anisotropyMapData;\n#endif\n#endif\nmat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));\nvec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);\nvec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));\noutParams.anisotropy=anisotropy;\noutParams.anisotropicTangent=anisotropicTangent;\noutParams.anisotropicBitangent=anisotropicBitangent;\noutParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy);\n}\n#endif\n";S.v.IncludesShadersStore.pbrBlockReflection="#ifdef REFLECTION\nstruct reflectionOutParams\n{\nvec4 environmentRadiance;\nvec3 environmentIrradiance;\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords;\n#else\nvec2 reflectionCoords;\n#endif\n#ifdef SS_TRANSLUCENCY\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nvec3 irradianceVector;\n#endif\n#endif\n#endif\n};\n#define pbr_inline\nvoid createReflectionCoords(\nin vec3 vPositionW,\nin vec3 normalW,\n#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\n#endif\n#ifdef REFLECTIONMAP_3D\nout vec3 reflectionCoords\n#else\nout vec2 reflectionCoords\n#endif\n)\n{\n#ifdef ANISOTROPIC\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal);\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nreflectionCoords=reflectionVector;\n#else\nreflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n}\n#define pbr_inline\n#define inline\nvoid sampleReflectionTexture(\nin float alphaG,\nin vec3 vReflectionMicrosurfaceInfos,\nin vec2 vReflectionInfos,\nin vec3 vReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nin float NdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nin float roughness,\n#endif\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\nconst vec3 reflectionCoords,\n#else\nin sampler2D reflectionSampler,\nconst vec2 reflectionCoords,\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\nin samplerCube reflectionSamplerHigh,\n#else\nin sampler2D reflectionSamplerLow,\nin sampler2D reflectionSamplerHigh,\n#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\n#endif\nout vec4 environmentRadiance\n)\n{\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#elif defined(LINEARSPECULARREFLECTION)\nfloat reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);\n#endif\n#ifdef LODBASEDMICROSFURACE\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\n#ifdef REALTIME_FILTERING\nenvironmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);\n#else\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#endif\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);\nif (lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nenvironmentRadiance=mix(\nenvironmentMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\n}\n#define pbr_inline\n#define inline\nvoid reflectionBlock(\nin vec3 vPositionW,\nin vec3 normalW,\nin float alphaG,\nin vec3 vReflectionMicrosurfaceInfos,\nin vec2 vReflectionInfos,\nin vec3 vReflectionColor,\n#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nin float NdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nin float roughness,\n#endif\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\n#else\nin sampler2D reflectionSampler,\n#endif\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nin vec3 vEnvironmentIrradiance,\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nin mat4 reflectionMatrix,\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\nin samplerCube irradianceSampler,\n#else\nin sampler2D irradianceSampler,\n#endif\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\nin samplerCube reflectionSamplerHigh,\n#else\nin sampler2D reflectionSamplerLow,\nin sampler2D reflectionSamplerHigh,\n#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\n#endif\nout reflectionOutParams outParams\n)\n{\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=vec3(0.);\n#else\nvec2 reflectionCoords=vec2(0.);\n#endif\ncreateReflectionCoords(\nvPositionW,\nnormalW,\n#ifdef ANISOTROPIC\nanisotropicOut,\n#endif\nreflectionCoords\n);\nsampleReflectionTexture(\nalphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nroughness,\n#endif\n#ifdef REFLECTIONMAP_3D\nreflectionSampler,\nreflectionCoords,\n#else\nreflectionSampler,\nreflectionCoords,\n#endif\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentRadiance\n);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\n#ifdef ANISOTROPIC\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\n#endif\n#if defined(REALTIME_FILTERING)\nenvironmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo);\n#else\nenvironmentIrradiance=computeEnvironmentIrradiance(irradianceVector);\n#endif\n#ifdef SS_TRANSLUCENCY\noutParams.irradianceVector=irradianceVector;\n#endif\n#endif\n#elif defined(USEIRRADIANCEMAP)\nvec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);\nenvironmentIrradiance=environmentIrradiance4.rgb;\n#ifdef RGBDREFLECTION\nenvironmentIrradiance.rgb=fromRGBD(environmentIrradiance4);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\nenvironmentIrradiance*=vReflectionColor.rgb;\noutParams.environmentRadiance=environmentRadiance;\noutParams.environmentIrradiance=environmentIrradiance;\noutParams.reflectionCoords=reflectionCoords;\n}\n#endif\n";S.v.IncludesShadersStore.pbrBlockSheen="#ifdef SHEEN\nstruct sheenOutParams\n{\nfloat sheenIntensity;\nvec3 sheenColor;\nfloat sheenRoughness;\n#ifdef SHEEN_LINKWITHALBEDO\nvec3 surfaceAlbedo;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfloat sheenAlbedoScaling;\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nvec3 finalSheenRadianceScaled;\n#endif\n#if DEBUGMODE>0\nvec4 sheenMapData;\nvec3 sheenEnvironmentReflectance;\n#endif\n};\n#define pbr_inline\n#define inline\nvoid sheenBlock(\nin vec4 vSheenColor,\n#ifdef SHEEN_ROUGHNESS\nin float vSheenRoughness,\n#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nin vec4 sheenMapRoughnessData,\n#endif\n#endif\nin float roughness,\n#ifdef SHEEN_TEXTURE\nin vec4 sheenMapData,\nin float sheenMapLevel,\n#endif\nin float reflectance,\n#ifdef SHEEN_LINKWITHALBEDO\nin vec3 baseColor,\nin vec3 surfaceAlbedo,\n#endif\n#ifdef ENVIRONMENTBRDF\nin float NdotV,\nin vec3 environmentBrdf,\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nin vec2 AARoughnessFactors,\nin vec3 vReflectionMicrosurfaceInfos,\nin vec2 vReflectionInfos,\nin vec3 vReflectionColor,\nin vec4 vLightingIntensity,\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\nin vec3 reflectionCoords,\n#else\nin sampler2D reflectionSampler,\nin vec2 reflectionCoords,\n#endif\nin float NdotVUnclamped,\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\nin samplerCube reflectionSamplerHigh,\n#else\nin sampler2D reflectionSamplerLow,\nin sampler2D reflectionSamplerHigh,\n#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nin float seo,\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\nin float eho,\n#endif\n#endif\nout sheenOutParams outParams\n)\n{\nfloat sheenIntensity=vSheenColor.a;\n#ifdef SHEEN_TEXTURE\n#if DEBUGMODE>0\noutParams.sheenMapData=sheenMapData;\n#endif\n#endif\n#ifdef SHEEN_LINKWITHALBEDO\nfloat sheenFactor=pow5(1.0-sheenIntensity);\nvec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);\nfloat sheenRoughness=sheenIntensity;\noutParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;\n#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\n#endif\n#else\nvec3 sheenColor=vSheenColor.rgb;\n#ifdef SHEEN_TEXTURE\n#ifdef SHEEN_GAMMATEXTURE\nsheenColor.rgb*=toLinearSpace(sheenMapData.rgb);\n#else\nsheenColor.rgb*=sheenMapData.rgb;\n#endif\nsheenColor.rgb*=sheenMapLevel;\n#endif\n#ifdef SHEEN_ROUGHNESS\nfloat sheenRoughness=vSheenRoughness;\n#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE\n#if defined(SHEEN_TEXTURE)\nsheenRoughness*=sheenMapData.a;\n#endif\n#elif defined(SHEEN_TEXTURE_ROUGHNESS)\n#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL\nsheenRoughness*=sheenMapData.a;\n#else\nsheenRoughness*=sheenMapRoughnessData.a;\n#endif\n#endif\n#else\nfloat sheenRoughness=roughness;\n#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\n#endif\n#endif\n#if !defined(SHEEN_ALBEDOSCALING)\nsheenIntensity*=(1.-reflectance);\n#endif\nsheenColor*=sheenIntensity;\n#endif\n#ifdef ENVIRONMENTBRDF\n/*#ifdef SHEEN_SOFTER\nvec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));\n#else*/\n#ifdef SHEEN_ROUGHNESS\nvec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness);\n#else\nvec3 environmentSheenBrdf=environmentBrdf;\n#endif\n/*#endif*/\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nfloat sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);\n#ifdef SPECULARAA\nsheenAlphaG+=AARoughnessFactors.y;\n#endif\nvec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);\nsampleReflectionTexture(\nsheenAlphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nsheenRoughness,\n#endif\nreflectionSampler,\nreflectionCoords,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentSheenRadiance\n);\nvec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nsheenEnvironmentReflectance*=seo;\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\nsheenEnvironmentReflectance*=eho;\n#endif\n#if DEBUGMODE>0\noutParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;\n#endif\noutParams.finalSheenRadianceScaled=\nenvironmentSheenRadiance.rgb *\nsheenEnvironmentReflectance *\nvLightingIntensity.z;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\noutParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;\n#endif\noutParams.sheenIntensity=sheenIntensity;\noutParams.sheenColor=sheenColor;\noutParams.sheenRoughness=sheenRoughness;\n}\n#endif\n";S.v.IncludesShadersStore.pbrBlockClearcoat="struct clearcoatOutParams\n{\nvec3 specularEnvironmentR0;\nfloat conservationFactor;\nvec3 clearCoatNormalW;\nvec2 clearCoatAARoughnessFactors;\nfloat clearCoatIntensity;\nfloat clearCoatRoughness;\n#ifdef REFLECTION\nvec3 finalClearCoatRadianceScaled;\n#endif\n#ifdef CLEARCOAT_TINT\nvec3 absorption;\nfloat clearCoatNdotVRefract;\nvec3 clearCoatColor;\nfloat clearCoatThickness;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nvec3 energyConservationFactorClearCoat;\n#endif\n#if DEBUGMODE>0\nmat3 TBNClearCoat;\nvec2 clearCoatMapData;\nvec4 clearCoatTintMapData;\nvec4 environmentClearCoatRadiance;\nfloat clearCoatNdotV;\nvec3 clearCoatEnvironmentReflectance;\n#endif\n};\n#ifdef CLEARCOAT\n#define pbr_inline\n#define inline\nvoid clearcoatBlock(\nin vec3 vPositionW,\nin vec3 geometricNormalW,\nin vec3 viewDirectionW,\nin vec2 vClearCoatParams,\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nin vec4 clearCoatMapRoughnessData,\n#endif\nin vec3 specularEnvironmentR0,\n#ifdef CLEARCOAT_TEXTURE\nin vec2 clearCoatMapData,\n#endif\n#ifdef CLEARCOAT_TINT\nin vec4 vClearCoatTintParams,\nin float clearCoatColorAtDistance,\nin vec4 vClearCoatRefractionParams,\n#ifdef CLEARCOAT_TINT_TEXTURE\nin vec4 clearCoatTintMapData,\n#endif\n#endif\n#ifdef CLEARCOAT_BUMP\nin vec2 vClearCoatBumpInfos,\nin vec4 clearCoatBumpMapData,\nin vec2 vClearCoatBumpUV,\n#if defined(TANGENT) && defined(NORMAL)\nin mat3 vTBN,\n#else\nin vec2 vClearCoatTangentSpaceParams,\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nin mat4 normalMatrix,\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nin vec3 faceNormal,\n#endif\n#ifdef REFLECTION\nin vec3 vReflectionMicrosurfaceInfos,\nin vec2 vReflectionInfos,\nin vec3 vReflectionColor,\nin vec4 vLightingIntensity,\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\n#else\nin sampler2D reflectionSampler,\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\nin samplerCube reflectionSamplerHigh,\n#else\nin sampler2D reflectionSamplerLow,\nin sampler2D reflectionSamplerHigh,\n#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\n#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\nin float ambientMonochrome,\n#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\nin float frontFacingMultiplier,\n#endif\nout clearcoatOutParams outParams\n)\n{\nfloat clearCoatIntensity=vClearCoatParams.x;\nfloat clearCoatRoughness=vClearCoatParams.y;\n#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\n#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE\nclearCoatRoughness*=clearCoatMapData.y;\n#endif\n#if DEBUGMODE>0\noutParams.clearCoatMapData=clearCoatMapData;\n#endif\n#endif\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL\nclearCoatRoughness*=clearCoatMapData.y;\n#else\nclearCoatRoughness*=clearCoatMapRoughnessData.y;\n#endif\n#endif\noutParams.clearCoatIntensity=clearCoatIntensity;\noutParams.clearCoatRoughness=clearCoatRoughness;\n#ifdef CLEARCOAT_TINT\nvec3 clearCoatColor=vClearCoatTintParams.rgb;\nfloat clearCoatThickness=vClearCoatTintParams.a;\n#ifdef CLEARCOAT_TINT_TEXTURE\n#ifdef CLEARCOAT_TINT_GAMMATEXTURE\nclearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);\n#else\nclearCoatColor*=clearCoatTintMapData.rgb;\n#endif\nclearCoatThickness*=clearCoatTintMapData.a;\n#if DEBUGMODE>0\noutParams.clearCoatTintMapData=clearCoatTintMapData;\n#endif\n#endif\noutParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);\noutParams.clearCoatThickness=clearCoatThickness;\n#endif\n#ifdef CLEARCOAT_REMAP_F0\nvec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);\n#else\nvec3 specularEnvironmentR0Updated=specularEnvironmentR0;\n#endif\noutParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);\nvec3 clearCoatNormalW=geometricNormalW;\n#ifdef CLEARCOAT_BUMP\n#ifdef NORMALXYSCALE\nfloat clearCoatNormalScale=1.0;\n#else\nfloat clearCoatNormalScale=vClearCoatBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBNClearCoat=vTBN;\n#else\nvec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;\nmat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);\n#endif\n#if DEBUGMODE>0\noutParams.TBNClearCoat=TBNClearCoat;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nclearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);\nclearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);\n#else\nclearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nclearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nclearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;\n#endif\noutParams.clearCoatNormalW=clearCoatNormalW;\noutParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);\nfloat clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);\nfloat clearCoatNdotV=absEps(clearCoatNdotVUnclamped);\n#if DEBUGMODE>0\noutParams.clearCoatNdotV=clearCoatNdotV;\n#endif\n#ifdef CLEARCOAT_TINT\nvec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);\noutParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));\n#endif\n#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))\nvec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);\n#endif\n#if defined(REFLECTION)\nfloat clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\n#ifdef SPECULARAA\nclearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;\n#endif\nvec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);\nvec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nclearCoatReflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 clearCoatReflectionCoords=clearCoatReflectionVector;\n#else\nvec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nclearCoatReflectionCoords/=clearCoatReflectionVector.z;\n#endif\nclearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;\n#endif\nsampleReflectionTexture(\nclearCoatAlphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nclearCoatNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nclearCoatRoughness,\n#endif\nreflectionSampler,\nclearCoatReflectionCoords,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentClearCoatRadiance\n);\n#if DEBUGMODE>0\noutParams.environmentClearCoatRadiance=environmentClearCoatRadiance;\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);\nclearCoatEnvironmentReflectance*=clearCoatEho;\n#endif\n#endif\n#endif\n#else\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));\n#endif\nclearCoatEnvironmentReflectance*=clearCoatIntensity;\n#if DEBUGMODE>0\noutParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;\n#endif\noutParams.finalClearCoatRadianceScaled=\nenvironmentClearCoatRadiance.rgb *\nclearCoatEnvironmentReflectance *\nvLightingIntensity.z;\n#endif\n#if defined(CLEARCOAT_TINT)\noutParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);\n#endif\nfloat fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);\nfresnelIBLClearCoat*=clearCoatIntensity;\noutParams.conservationFactor=(1.-fresnelIBLClearCoat);\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\noutParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);\n#endif\n}\n#endif\n";S.v.IncludesShadersStore.pbrBlockIridescence="struct iridescenceOutParams\n{\nfloat iridescenceIntensity;\nfloat iridescenceIOR;\nfloat iridescenceThickness;\nvec3 specularEnvironmentR0;\n};\n#ifdef IRIDESCENCE\n#define pbr_inline\n#define inline\nvoid iridescenceBlock(\nin vec4 vIridescenceParams,\nin float viewAngle,\nin vec3 specularEnvironmentR0,\n#ifdef IRIDESCENCE_TEXTURE\nin vec2 iridescenceMapData,\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nin vec2 iridescenceThicknessMapData,\n#endif\n#ifdef CLEARCOAT\nin float NdotVUnclamped,\n#ifdef CLEARCOAT_TEXTURE\nin vec2 clearCoatMapData,\n#endif\n#endif\nout iridescenceOutParams outParams\n)\n{\nfloat iridescenceIntensity=vIridescenceParams.x;\nfloat iridescenceIOR=vIridescenceParams.y;\nfloat iridescenceThicknessMin=vIridescenceParams.z;\nfloat iridescenceThicknessMax=vIridescenceParams.w;\nfloat iridescenceThicknessWeight=1.;\n#ifdef IRIDESCENCE_TEXTURE\niridescenceIntensity*=iridescenceMapData.x;\n#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE\niridescenceThicknessWeight=iridescenceMapData.g;\n#endif\n#endif\n#if defined(IRIDESCENCE_THICKNESS_TEXTURE)\niridescenceThicknessWeight=iridescenceThicknessMapData.g;\n#endif\nfloat iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);\nfloat topIor=1.; \n#ifdef CLEARCOAT\nfloat clearCoatIntensity=vClearCoatParams.x;\n#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\n#endif\ntopIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);\nviewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0));\n#endif\nvec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);\noutParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);\noutParams.iridescenceIntensity=iridescenceIntensity;\noutParams.iridescenceThickness=iridescenceThickness;\noutParams.iridescenceIOR=iridescenceIOR;\n}\n#endif\n";S.v.IncludesShadersStore.pbrBlockSubSurface="struct subSurfaceOutParams\n{\nvec3 specularEnvironmentReflectance;\n#ifdef SS_REFRACTION\nvec3 finalRefraction;\nvec3 surfaceAlbedo;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nfloat alpha;\n#endif\n#ifdef REFLECTION\nfloat refractionFactorForIrradiance;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nvec3 transmittance;\nfloat translucencyIntensity;\n#ifdef REFLECTION\nvec3 refractionIrradiance;\n#endif\n#endif\n#if DEBUGMODE>0\nvec4 thicknessMap;\nvec4 environmentRefraction;\nvec3 refractionTransmittance;\n#endif\n};\n#ifdef SUBSURFACE\n#define pbr_inline\n#define inline\nvoid subSurfaceBlock(\nin vec3 vSubSurfaceIntensity,\nin vec2 vThicknessParam,\nin vec4 vTintColor,\nin vec3 normalW,\nin vec3 specularEnvironmentReflectance,\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nin vec4 thicknessMap,\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nin vec4 refractionIntensityMap,\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nin vec4 translucencyIntensityMap,\n#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\nin mat4 reflectionMatrix,\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nin vec3 irradianceVector_,\n#endif\n#if defined(REALTIME_FILTERING)\nin samplerCube reflectionSampler,\nin vec2 vReflectionFilteringInfo,\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\nin samplerCube irradianceSampler,\n#else\nin sampler2D irradianceSampler,\n#endif\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\nin vec3 surfaceAlbedo,\n#endif\n#ifdef SS_REFRACTION\nin vec3 vPositionW,\nin vec3 viewDirectionW,\nin mat4 view,\nin vec4 vRefractionInfos,\nin mat4 refractionMatrix,\nin vec4 vRefractionMicrosurfaceInfos,\nin vec4 vLightingIntensity,\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nin float alpha,\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\nin float NdotVUnclamped,\n#endif\n#ifdef SS_LINEARSPECULARREFRACTION\nin float roughness,\n#endif\nin float alphaG,\n#ifdef SS_REFRACTIONMAP_3D\nin samplerCube refractionSampler,\n#ifndef LODBASEDMICROSFURACE\nin samplerCube refractionSamplerLow,\nin samplerCube refractionSamplerHigh,\n#endif\n#else\nin sampler2D refractionSampler,\n#ifndef LODBASEDMICROSFURACE\nin sampler2D refractionSamplerLow,\nin sampler2D refractionSamplerHigh,\n#endif\n#endif\n#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vRefractionFilteringInfo,\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nin vec3 refractionPosition,\nin vec3 refractionSize,\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nin vec3 vDiffusionDistance,\n#endif\nout subSurfaceOutParams outParams\n)\n{\noutParams.specularEnvironmentReflectance=specularEnvironmentReflectance;\n#ifdef SS_REFRACTION\nfloat refractionIntensity=vSubSurfaceIntensity.x;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nrefractionIntensity*=(1.0-alpha);\noutParams.alpha=1.0;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nfloat translucencyIntensity=vSubSurfaceIntensity.y;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n#if defined(SS_USE_GLTF_TEXTURES)\nfloat thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;\n#else\nfloat thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;\n#endif\n#if DEBUGMODE>0\noutParams.thicknessMap=thicknessMap;\n#endif\n#ifdef SS_MASK_FROM_THICKNESS_TEXTURE\n#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE)\n#if defined(SS_USE_GLTF_TEXTURES)\nrefractionIntensity*=thicknessMap.r;\n#else\nrefractionIntensity*=thicknessMap.g;\n#endif\n#endif\n#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE)\ntranslucencyIntensity*=thicknessMap.b;\n#endif\n#endif\n#else\nfloat thickness=vThicknessParam.y;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\n#ifdef SS_USE_GLTF_TEXTURES\nrefractionIntensity*=refractionIntensityMap.r;\n#else\nrefractionIntensity*=refractionIntensityMap.g;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\ntranslucencyIntensity*=translucencyIntensityMap.b;\n#endif\n#ifdef SS_TRANSLUCENCY\nthickness=maxEps(thickness);\nvec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);\ntransmittance*=translucencyIntensity;\noutParams.transmittance=transmittance;\noutParams.translucencyIntensity=translucencyIntensity;\n#endif\n#ifdef SS_REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\n#ifdef ANISOTROPIC\nvec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y);\n#else\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#endif\n#ifdef SS_REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n#ifdef SS_REFRACTIONMAP_3D\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\n#ifdef SS_USE_THICKNESS_AS_DEPTH\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0)));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\n#endif\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef SS_HAS_THICKNESS\nfloat ior=vRefractionInfos.y;\n#else\nfloat ior=vRefractionMicrosurfaceInfos.w;\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\nfloat refractionAlphaG=alphaG;\nrefractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);\n#elif defined(SS_LINEARSPECULARREFRACTION)\nfloat refractionRoughness=alphaG;\nrefractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));\nfloat refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);\n#else\nfloat refractionAlphaG=alphaG;\nrefractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);\n#endif\n#ifdef LODBASEDMICROSFURACE\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef SS_LODINREFRACTIONALPHA\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\n#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)\nenvironmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0);\n#else\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#endif\n#else\nfloat lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif (lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n} else {\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef SS_RGBDREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef SS_GAMMAREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n#ifdef SS_REFRACTION\nvec3 refractionTransmittance=vec3(refractionIntensity);\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);\nrefractionTransmittance*=cocaLambert(volumeAlbedo,thickness);\n#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)\nfloat maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);\nvec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);\nenvironmentRefraction.rgb*=volumeAlbedo;\n#else\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);\nrefractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);\n#endif\n#ifdef SS_ALBEDOFORREFRACTIONTINT\nenvironmentRefraction.rgb*=surfaceAlbedo.rgb;\n#endif\noutParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);\n#ifdef REFLECTION\noutParams.refractionFactorForIrradiance=(1.-refractionIntensity);\n#endif\n#ifdef UNUSED_MULTIPLEBOUNCES\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\noutParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);\n#endif\nrefractionTransmittance*=1.0-outParams.specularEnvironmentReflectance;\n#if DEBUGMODE>0\noutParams.refractionTransmittance=refractionTransmittance;\n#endif\noutParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;\n#if DEBUGMODE>0\noutParams.environmentRefraction=environmentRefraction;\n#endif\n#endif\n#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\n#endif\n#else\nvec3 irradianceVector=irradianceVector_;\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP)\n#if defined(REALTIME_FILTERING)\nvec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo);\n#else\nvec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);\n#endif\n#elif defined(USEIRRADIANCEMAP)\n#ifdef REFLECTIONMAP_3D\nvec3 irradianceCoords=irradianceVector;\n#else\nvec2 irradianceCoords=irradianceVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nirradianceCoords/=irradianceVector.z;\n#endif\nirradianceCoords.y=1.0-irradianceCoords.y;\n#endif\nvec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords);\n#ifdef RGBDREFLECTION\nrefractionIrradiance.rgb=fromRGBD(refractionIrradiance);\n#endif\n#ifdef GAMMAREFLECTION\nrefractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);\n#endif\n#else\nvec4 refractionIrradiance=vec4(0.);\n#endif\nrefractionIrradiance.rgb*=transmittance;\n#ifdef SS_ALBEDOFORTRANSLUCENCYTINT\nrefractionIrradiance.rgb*=surfaceAlbedo.rgb;\n#endif\noutParams.refractionIrradiance=refractionIrradiance.rgb;\n#endif\n}\n#endif\n",i(5791);S.v.IncludesShadersStore.pbrBlockNormalGeometric="vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\nvec3 geometricNormalW=normalW;\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\ngeometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW;\n#endif\n",i(2321);S.v.IncludesShadersStore.pbrBlockNormalFinal="#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n",i(783);S.v.IncludesShadersStore.pbrBlockLightmapInit="#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\n#endif\n#ifdef GAMMALIGHTMAP\nlightmapColor.rgb=toLinearSpace(lightmapColor.rgb);\n#endif\nlightmapColor.rgb*=vLightmapInfos.y;\n#endif\n";S.v.IncludesShadersStore.pbrBlockGeometryInfo="float NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=absEps(NdotVUnclamped);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nvec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);\n#ifdef SPECULARAA\nalphaG+=AARoughnessFactors.y;\n#endif\n#if defined(ENVIRONMENTBRDF)\nvec3 environmentBrdf=getBRDFLookup(NdotV,roughness);\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=aoOut.ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);\n#endif\n#endif\n#endif\n#endif\n";S.v.IncludesShadersStore.pbrBlockReflectance0="float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);\nvec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a);\n#else \nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\n#endif\n#ifdef ALPHAFRESNEL\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nspecularEnvironmentR90=specularEnvironmentR90*reflectance90;\n#endif\n";S.v.IncludesShadersStore.pbrBlockReflectance="#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);\n#ifdef RADIANCEOCCLUSION\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\nvec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n#ifdef CLEARCOAT\nspecularEnvironmentReflectance*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nspecularEnvironmentReflectance*=clearcoatOut.absorption;\n#endif\n#endif\n";S.v.IncludesShadersStore.pbrBlockDirectLighting="vec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef CLEARCOAT\nvec3 clearCoatBase=vec3(0.,0.,0.);\n#endif\n#ifdef SHEEN\nvec3 sheenBase=vec3(0.,0.,0.);\n#endif\npreLightingInfo preInfo;\nlightingInfo info;\nfloat shadow=1.; \n#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\nvec3 absorption=vec3(0.);\n#endif\n",i(9490);S.v.IncludesShadersStore.pbrBlockFinalLitComponents="#if defined(ENVIRONMENTBRDF)\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);\n#endif\n#endif\n#ifndef METALLICWORKFLOW\n#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n#endif\n#endif\n#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)\nsurfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;\n#endif\n#ifdef REFLECTION\nvec3 finalIrradiance=reflectionOut.environmentIrradiance;\n#if defined(CLEARCOAT)\nfinalIrradiance*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nfinalIrradiance*=clearcoatOut.absorption;\n#endif\n#endif\n#if defined(SS_REFRACTION)\nfinalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;\n#endif\n#if defined(SS_TRANSLUCENCY)\nfinalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);\nfinalIrradiance+=subSurfaceOut.refractionIrradiance;\n#endif\nfinalIrradiance*=surfaceAlbedo.rgb;\nfinalIrradiance*=vLightingIntensity.z;\nfinalIrradiance*=aoOut.ambientOcclusionColor;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalSpecularScaled*=energyConservationFactor;\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalSpecularScaled*=sheenOut.sheenAlbedoScaling;\n#endif\n#endif\n#ifdef REFLECTION\nvec3 finalRadiance=reflectionOut.environmentRadiance.rgb;\nfinalRadiance*=subSurfaceOut.specularEnvironmentReflectance;\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalRadianceScaled*=energyConservationFactor;\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalRadianceScaled*=sheenOut.sheenAlbedoScaling;\n#endif\n#endif\n#ifdef SHEEN\nvec3 finalSheen=sheenBase*sheenOut.sheenColor;\nfinalSheen=max(finalSheen,0.0);\nvec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;\n#endif\n#endif\n#endif\n#ifdef CLEARCOAT\nvec3 finalClearCoat=clearCoatBase;\nfinalClearCoat=max(finalClearCoat,0.0);\nvec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;\n#ifdef CLEARCOAT_TINT\nsubSurfaceOut.finalRefraction*=clearcoatOut.absorption;\n#endif\n#endif\n#endif\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#if defined(CLEARCOAT)\nluminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);\n#endif\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalClearCoatScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)\nalpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);\n#endif\n#endif\n";S.v.IncludesShadersStore.pbrBlockFinalUnlitComponents="vec3 finalDiffuse=diffuseBase;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\nfinalDiffuse*=vLightingIntensity.x;\nvec3 finalAmbient=vAmbientColor;\nfinalAmbient*=surfaceAlbedo.rgb;\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\n#ifdef GAMMAEMISSIVE\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\n#else\nfinalEmissive*=emissiveColorTex.rgb;\n#endif\nfinalEmissive*= vEmissiveInfos.y;\n#endif\nfinalEmissive*=vLightingIntensity.y;\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor;\n#endif\nfinalAmbient*=aoOut.ambientOcclusionColor;\nfinalDiffuse*=ambientOcclusionForDirectDiffuse;\n";S.v.IncludesShadersStore.pbrBlockFinalColorComposition="vec4 finalColor=vec4(\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance +\n#endif\n#ifdef SPECULARTERM\nfinalSpecularScaled +\n#endif\n#ifdef SHEEN\nfinalSheenScaled +\n#endif\n#ifdef CLEARCOAT\nfinalClearCoatScaled +\n#endif\n#ifdef REFLECTION\nfinalRadianceScaled +\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled +\n#endif\n#ifdef CLEARCOAT\nclearcoatOut.finalClearCoatRadianceScaled +\n#endif\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction +\n#endif\n#endif\nfinalAmbient +\nfinalDiffuse,\nalpha);\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor.rgb;\n#else\nfinalColor.rgb+=lightmapColor.rgb;\n#endif\n#endif\n#endif\nfinalColor.rgb+=finalEmissive;\n#define CUSTOM_FRAGMENT_BEFORE_FOG\nfinalColor=max(finalColor,0.0);\n",i(8773),i(6043);S.v.IncludesShadersStore.pbrBlockImageProcessing="#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)\n#if !defined(SKIPFINALCOLORCLAMP)\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#endif\n#else\nfinalColor=applyImageProcessing(finalColor);\n#endif\nfinalColor.a*=visibility;\n#ifdef PREMULTIPLYALPHA\nfinalColor.rgb*=finalColor.a;\n#endif\n",i(4643);S.v.IncludesShadersStore.pbrDebug="#if DEBUGMODE>0\nif (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) {\n#if DEBUGMODE==1\ngl_FragColor.rgb=vPositionW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==2 && defined(NORMAL)\ngl_FragColor.rgb=vNormalW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==5\ngl_FragColor.rgb=normalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==6 && defined(MAINUV1)\ngl_FragColor.rgb=vec3(vMainUV1,0.0);\n#elif DEBUGMODE==7 && defined(MAINUV2)\ngl_FragColor.rgb=vec3(vMainUV2,0.0);\n#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==10 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearcoatOut.clearCoatNormalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==11 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicNormal;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==12 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicTangent;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==13 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicBitangent;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==20 && defined(ALBEDO)\ngl_FragColor.rgb=albedoTexture.rgb;\n#elif DEBUGMODE==21 && defined(AMBIENT)\ngl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb;\n#elif DEBUGMODE==22 && defined(OPACITY)\ngl_FragColor.rgb=opacityMap.rgb;\n#elif DEBUGMODE==23 && defined(EMISSIVE)\ngl_FragColor.rgb=emissiveColorTex.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==24 && defined(LIGHTMAP)\ngl_FragColor.rgb=lightmapColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb;\n#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0);\n#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\ngl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb;\n#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)\ngl_FragColor.rgb=sheenOut.sheenMapData.rgb;\n#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)\ngl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb;\n#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)\ngl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb;\n#elif DEBUGMODE==40 && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==41 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentRadiance.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)\ngl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==50\ngl_FragColor.rgb=diffuseBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==51 && defined(SPECULARTERM)\ngl_FragColor.rgb=specularBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==52 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearCoatBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==53 && defined(SHEEN)\ngl_FragColor.rgb=sheenBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==54 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==60\ngl_FragColor.rgb=surfaceAlbedo.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==61\ngl_FragColor.rgb=clearcoatOut.specularEnvironmentR0;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r);\n#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.metallicF0;\n#elif DEBUGMODE==63\ngl_FragColor.rgb=vec3(roughness);\n#elif DEBUGMODE==64\ngl_FragColor.rgb=vec3(alphaG);\n#elif DEBUGMODE==65\ngl_FragColor.rgb=vec3(NdotV);\n#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\ngl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==67 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness);\n#elif DEBUGMODE==68 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV);\n#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)\ngl_FragColor.rgb=subSurfaceOut.transmittance;\n#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.refractionTransmittance;\n#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)\ngl_FragColor.rgb=vec3(seo);\n#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION)\ngl_FragColor.rgb=vec3(eho);\n#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)\ngl_FragColor.rgb=vec3(energyConservationFactor);\n#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=specularEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)\ngl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==86 && defined(ALPHABLEND)\ngl_FragColor.rgb=vec3(luminanceOverAlpha);\n#elif DEBUGMODE==87\ngl_FragColor.rgb=vec3(alpha);\n#endif\ngl_FragColor.rgb*=vDebugMode.y;\n#ifdef DEBUGMODE_NORMALIZE\ngl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;\n#endif\n#ifdef DEBUGMODE_GAMMA\ngl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);\n#endif\ngl_FragColor.a=1.0;\n#ifdef PREPASS\ngl_FragData[0]=toLinearSpace(gl_FragColor); \ngl_FragData[1]=vec4(0.,0.,0.,0.); \n#endif\nreturn;\n}\n#endif\n";S.v.ShadersStore.pbrPixelShader="#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include<prePassDeclaration>[SCENE_MRT_COUNT]\nprecision highp float;\n#include<oitDeclaration>\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE\n#endif\n#include<__decl__pbrFragment>\n#include<pbrFragmentExtraDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<pbrFragmentSamplersDeclaration>\n#include<imageProcessingDeclaration>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#include<helperFunctions>\n#include<subSurfaceScatteringFunctions>\n#include<importanceSampling>\n#include<pbrHelperFunctions>\n#include<imageProcessingFunctions>\n#include<shadowsFragmentFunctions>\n#include<harmonicsFunctions>\n#include<pbrDirectLightingSetupFunctions>\n#include<pbrDirectLightingFalloffFunctions>\n#include<pbrBRDFFunctions>\n#include<hdrFilteringFunctions>\n#include<pbrDirectLightingFunctions>\n#include<pbrIBLFunctions>\n#include<bumpFragmentMainFunctions>\n#include<bumpFragmentFunctions>\n#ifdef REFLECTION\n#include<reflectionFunction>\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#include<pbrBlockAlbedoOpacity>\n#include<pbrBlockReflectivity>\n#include<pbrBlockAmbientOcclusion>\n#include<pbrBlockAlphaFresnel>\n#include<pbrBlockAnisotropic>\n#include<pbrBlockReflection>\n#include<pbrBlockSheen>\n#include<pbrBlockClearcoat>\n#include<pbrBlockIridescence>\n#include<pbrBlockSubSurface>\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\n#include<pbrBlockNormalGeometric>\n#include<bumpFragment>\n#include<pbrBlockNormalFinal>\nalbedoOpacityOutParams albedoOpacityOut;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#endif\n#ifdef DECAL\nvec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);\n#endif\nalbedoOpacityBlock(\nvAlbedoColor,\n#ifdef ALBEDO\nalbedoTexture,\nvAlbedoInfos,\n#endif\n#ifdef OPACITY\nopacityMap,\nvOpacityInfos,\n#endif\n#ifdef DETAIL\ndetailColor,\nvDetailInfos,\n#endif\n#ifdef DECAL\ndecalColor,\nvDecalInfos,\n#endif\nalbedoOpacityOut\n);\nvec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;\nfloat alpha=albedoOpacityOut.alpha;\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\n#include<depthPrePass>\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\nambientOcclusionOutParams aoOut;\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb;\n#endif\nambientOcclusionBlock(\n#ifdef AMBIENT\nambientOcclusionColorMap,\nvAmbientInfos,\n#endif\naoOut\n);\n#include<pbrBlockLightmapInit>\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\nvec3 baseColor=surfaceAlbedo;\nreflectivityOutParams reflectivityOut;\n#if defined(REFLECTIVITY)\nvec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nvec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap;\n#ifndef METALLICWORKFLOW\n#ifdef REFLECTIVITY_GAMMA\nsurfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap);\n#endif\nsurfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y;\n#endif\n#endif\n#if defined(MICROSURFACEMAP)\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\n#endif\n#ifdef METALLICWORKFLOW\nvec4 metallicReflectanceFactors=vMetallicReflectanceFactors;\n#ifdef REFLECTANCE\nvec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset);\n#ifdef REFLECTANCE_GAMMA\nreflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap);\n#endif\nmetallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb;\n#endif\n#ifdef METALLIC_REFLECTANCE\nvec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset);\n#ifdef METALLIC_REFLECTANCE_GAMMA\nmetallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap);\n#endif\n#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY\nmetallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb;\n#endif\nmetallicReflectanceFactors*=metallicReflectanceFactorsMap.a;\n#endif\n#endif\nreflectivityBlock(\nvReflectivityColor,\n#ifdef METALLICWORKFLOW\nsurfaceAlbedo,\nmetallicReflectanceFactors,\n#endif\n#ifdef REFLECTIVITY\nvReflectivityInfos,\nsurfaceMetallicOrReflectivityColorMap,\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\naoOut.ambientOcclusionColor,\n#endif\n#ifdef MICROSURFACEMAP\nmicroSurfaceTexel,\n#endif\n#ifdef DETAIL\ndetailColor,\nvDetailInfos,\n#endif\nreflectivityOut\n);\nfloat microSurface=reflectivityOut.microSurface;\nfloat roughness=reflectivityOut.roughness;\n#ifdef METALLICWORKFLOW\nsurfaceAlbedo=reflectivityOut.surfaceAlbedo;\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\naoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;\n#endif\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nalphaFresnelOutParams alphaFresnelOut;\nalphaFresnelBlock(\nnormalW,\nviewDirectionW,\nalpha,\nmicroSurface,\nalphaFresnelOut\n);\nalpha=alphaFresnelOut.alpha;\n#endif\n#endif\n#include<pbrBlockGeometryInfo>\n#ifdef ANISOTROPIC\nanisotropicOutParams anisotropicOut;\n#ifdef ANISOTROPIC_TEXTURE\nvec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;\n#endif\nanisotropicBlock(\nvAnisotropy,\n#ifdef ANISOTROPIC_TEXTURE\nanisotropyMapData,\n#endif\nTBN,\nnormalW,\nviewDirectionW,\nanisotropicOut\n);\n#endif\n#ifdef REFLECTION\nreflectionOutParams reflectionOut;\n#ifndef USE_CUSTOM_REFLECTION\nreflectionBlock(\nvPositionW,\nnormalW,\nalphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#ifdef ANISOTROPIC\nanisotropicOut,\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nroughness,\n#endif\nreflectionSampler,\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nvEnvironmentIrradiance,\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nreflectionMatrix,\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\nirradianceSampler,\n#endif\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nreflectionOut\n);\n#else\n#define CUSTOM_REFLECTION\n#endif\n#endif\n#include<pbrBlockReflectance0>\n#ifdef SHEEN\nsheenOutParams sheenOut;\n#ifdef SHEEN_TEXTURE\nvec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset);\n#endif\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w;\n#endif\nsheenBlock(\nvSheenColor,\n#ifdef SHEEN_ROUGHNESS\nvSheenRoughness,\n#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nsheenMapRoughnessData,\n#endif\n#endif\nroughness,\n#ifdef SHEEN_TEXTURE\nsheenMapData,\nvSheenInfos.y,\n#endif\nreflectance,\n#ifdef SHEEN_LINKWITHALBEDO\nbaseColor,\nsurfaceAlbedo,\n#endif\n#ifdef ENVIRONMENTBRDF\nNdotV,\nenvironmentBrdf,\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nAARoughnessFactors,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\nvLightingIntensity,\nreflectionSampler,\nreflectionOut.reflectionCoords,\nNdotVUnclamped,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nseo,\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\neho,\n#endif\n#endif\nsheenOut\n);\n#ifdef SHEEN_LINKWITHALBEDO\nsurfaceAlbedo=sheenOut.surfaceAlbedo;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifdef CLEARCOAT_TEXTURE\nvec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;\n#endif\n#endif\n#ifdef IRIDESCENCE\niridescenceOutParams iridescenceOut;\n#ifdef IRIDESCENCE_TEXTURE\nvec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nvec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w;\n#endif\niridescenceBlock(\nvIridescenceParams,\nNdotV,\nspecularEnvironmentR0,\n#ifdef IRIDESCENCE_TEXTURE\niridescenceMapData,\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\niridescenceThicknessMapData,\n#endif\n#ifdef CLEARCOAT\nNdotVUnclamped,\n#ifdef CLEARCOAT_TEXTURE\nclearCoatMapData,\n#endif\n#endif\niridescenceOut\n);\nfloat iridescenceIntensity=iridescenceOut.iridescenceIntensity;\nspecularEnvironmentR0=iridescenceOut.specularEnvironmentR0;\n#endif\nclearcoatOutParams clearcoatOut;\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w;\n#endif\n#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\nvec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);\n#endif\n#ifdef CLEARCOAT_BUMP\nvec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset);\n#endif\nclearcoatBlock(\nvPositionW,\ngeometricNormalW,\nviewDirectionW,\nvClearCoatParams,\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nclearCoatMapRoughnessData,\n#endif\nspecularEnvironmentR0,\n#ifdef CLEARCOAT_TEXTURE\nclearCoatMapData,\n#endif\n#ifdef CLEARCOAT_TINT\nvClearCoatTintParams,\nclearCoatColorAtDistance,\nvClearCoatRefractionParams,\n#ifdef CLEARCOAT_TINT_TEXTURE\nclearCoatTintMapData,\n#endif\n#endif\n#ifdef CLEARCOAT_BUMP\nvClearCoatBumpInfos,\nclearCoatBumpMapData,\nvClearCoatBumpUV,\n#if defined(TANGENT) && defined(NORMAL)\nvTBN,\n#else\nvClearCoatTangentSpaceParams,\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nnormalMatrix,\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nfaceNormal,\n#endif\n#ifdef REFLECTION\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\nvLightingIntensity,\nreflectionSampler,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\nambientMonochrome,\n#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n(gl_FrontFacing ? 1. : -1.),\n#endif\nclearcoatOut\n);\n#else\nclearcoatOut.specularEnvironmentR0=specularEnvironmentR0;\n#endif\n#include<pbrBlockReflectance>\nsubSurfaceOutParams subSurfaceOut;\n#ifdef SUBSURFACE\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nvec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset);\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nvec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset);\n#endif\nsubSurfaceBlock(\nvSubSurfaceIntensity,\nvThicknessParam,\nvTintColor,\nnormalW,\nspecularEnvironmentReflectance,\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nthicknessMap,\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nrefractionIntensityMap,\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\ntranslucencyIntensityMap,\n#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\nreflectionMatrix,\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nreflectionOut.irradianceVector,\n#endif\n#if defined(REALTIME_FILTERING)\nreflectionSampler,\nvReflectionFilteringInfo,\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\nirradianceSampler,\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\nsurfaceAlbedo,\n#endif\n#ifdef SS_REFRACTION\nvPositionW,\nviewDirectionW,\nview,\nvRefractionInfos,\nrefractionMatrix,\nvRefractionMicrosurfaceInfos,\nvLightingIntensity,\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha,\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\nNdotVUnclamped,\n#endif\n#ifdef SS_LINEARSPECULARREFRACTION\nroughness,\n#endif\nalphaG,\nrefractionSampler,\n#ifndef LODBASEDMICROSFURACE\nrefractionSamplerLow,\nrefractionSamplerHigh,\n#endif\n#ifdef ANISOTROPIC\nanisotropicOut,\n#endif\n#ifdef REALTIME_FILTERING\nvRefractionFilteringInfo,\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nvRefractionPosition,\nvRefractionSize,\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nvDiffusionDistance,\n#endif\nsubSurfaceOut\n);\n#ifdef SS_REFRACTION\nsurfaceAlbedo=subSurfaceOut.surfaceAlbedo;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha=subSurfaceOut.alpha;\n#endif\n#endif\n#else\nsubSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;\n#endif\n#include<pbrBlockDirectLighting>\n#include<lightFragment>[0..maxSimultaneousLights]\n#include<pbrBlockFinalLitComponents>\n#endif \n#include<pbrBlockFinalUnlitComponents>\n#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\n#include<pbrBlockFinalColorComposition>\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#include<pbrBlockImageProcessing>\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nfloat writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0;\n#ifdef PREPASS_POSITION\ngl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);\n#endif\n#ifdef PREPASS_VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=abs(a-b);\nvelocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;\ngl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_ALBEDO_SQRT\nvec3 sqAlbedo=sqrt(surfaceAlbedo); \n#endif\n#ifdef PREPASS_IRRADIANCE\nvec3 irradiance=finalDiffuse;\n#ifndef UNLIT\n#ifdef REFLECTION\nirradiance+=finalIrradiance;\n#endif\n#endif\n#ifdef SS_SCATTERING\ngl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); \nirradiance/=sqAlbedo;\n#else\ngl_FragData[0]=finalColor; \nfloat scatteringDiffusionProfile=255.;\n#endif\ngl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); \n#else\ngl_FragData[0]=vec4(finalColor.rgb,finalColor.a);\n#endif\n#ifdef PREPASS_DEPTH\ngl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); \n#endif\n#ifdef PREPASS_ALBEDO_SQRT\ngl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); \n#endif\n#ifdef PREPASS_REFLECTIVITY\n#ifndef UNLIT\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo;\n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo;\n#endif\n#endif\n#endif\n#if !defined(PREPASS) || defined(WEBGL2)\ngl_FragColor=finalColor;\n#endif\n#include<oitFragment>\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {\nfrontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;\nfrontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);\n} else {\nbackColor+=finalColor;\n}\n#endif\n#include<pbrDebug>\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n",i(5613);S.v.IncludesShadersStore.pbrVertexDeclaration="uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef METALLIC_REFLECTANCE\nuniform vec2 vMetallicReflectanceInfos;\nuniform mat4 metallicReflectanceMatrix;\n#endif\n#ifdef REFLECTANCE\nuniform vec2 vReflectanceInfos;\nuniform mat4 reflectanceMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;\nuniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\nuniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#ifdef IRIDESCENCE\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;\nuniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\nuniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;\nuniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;\nuniform mat4 translucencyIntensityMatrix;\n#endif\n#endif\n#ifdef NORMAL\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;\nuniform vec3 vSphericalL1_1;\nuniform vec3 vSphericalL10;\nuniform vec3 vSphericalL11;\nuniform vec3 vSphericalL2_2;\nuniform vec3 vSphericalL2_1;\nuniform vec3 vSphericalL20;\nuniform vec3 vSphericalL21;\nuniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\n#endif\n#endif\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\nuniform mat4 detailMatrix;\n#endif\n#include<decalVertexDeclaration>\n#define ADDITIONAL_VERTEX_DECLARATION\n",i(6467),i(7520),i(493),i(1063),i(7019),i(9478),i(2838),i(6343),i(9042),i(1542),i(9935),i(9901),i(8073),i(6757),i(9085),i(6883),i(6655),i(3206),i(8741),i(3088),i(2508),i(6255),i(5215),i(962),i(1101),i(9025),i(5501);S.v.ShadersStore.pbrVertexShader="precision highp float;\n#include<__decl__pbrVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#include<uvAttributeDeclaration>[2..7]\n#include<mainUVVaryingDeclaration>[1..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\n#include<prePassVertexDeclaration>\n#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)\n#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)\n#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)\n#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\n#ifdef CLEARCOAT\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)\n#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)\n#endif\n#ifdef SHEEN\n#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#endif\n#ifdef ANISOTROPIC\n#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)\n#endif\n#ifdef SUBSURFACE\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)\n#endif\nvarying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#include<prePassVertex>\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));\nvNormalW=normalize(normalWorld*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#if DEBUGMODE>0\nvClipSpacePosition=gl_Position;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#include<uvVariableDeclaration>[2..7]\n#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#ifdef CLEARCOAT\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)\n#endif\n#ifdef SHEEN\n#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z)\n#endif\n#ifdef ANISOTROPIC\n#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)\n#endif\n#ifdef SUBSURFACE\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}";var E=i(1434),C=i(3077),A=i(3949),P=i(9482),R=i(4783),M=i(3808),I=i(6150),D=i(99);const O={effect:null,subMesh:null};class w extends v.H{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class N extends y.a{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new h.Lt(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=N.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=p.Wo.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new p.Wo(0,0,0),this._albedoColor=new p.Wo(1,1,1),this._reflectivityColor=new p.Wo(1,1,1),this._reflectionColor=new p.Wo(1,1,1),this._emissiveColor=new p.Wo(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=N.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 o.t(16),this._globalAmbientColor=new p.Wo(0,0,0),this._useLogarithmicDepth=!1,this._unlit=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new u.d(this),this.clearCoat=new C.Y(this),this.iridescence=new A.B(this),this.anisotropy=new P.u(this),this.sheen=new R.B(this),this.subSurface=new M.u(this),this.detailMap=new I.p(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),T.k.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=(0,a.$)(this.getScene()),this.prePassConfiguration=new d.o}get hasRenderTargetTextures(){return!!(T.k.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}get _disableAlphaBlending(){var e;return this._transparencyMode===N.PBRMATERIAL_OPAQUE||this._transparencyMode===N.PBRMATERIAL_ALPHATEST||(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){var e;return!!this._forceAlphaTest||!(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===N.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==N.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(g.S.GetDefineNames,this._eventInfo),t.materialDefines=new w(this._eventInfo.defineNames));const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const s=this.getScene(),o=s.getEngine();if(n._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,s.texturesEnabled)){if(this._albedoTexture&&T.k.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&T.k.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&T.k.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&T.k.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture&&!e.irradianceTexture.isReadyOrNotBlocking())return!1}if(this._lightmapTexture&&T.k.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&T.k.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(T.k.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&T.k.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&T.k.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(c.o.NormalKind)||(e.createNormals(!0),r.Y.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,l=n._areLightsDisposed;let h=this._prepareEffect(e,n,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),u=!1;if(h)if(this._onEffectCreatedObservable&&(O.effect=h,O.subMesh=t,this._onEffectCreatedObservable.notifyObservers(O)),this.allowShaderHotSwapping&&a&&!h.isReady()){if(h=a,n.markAsUnprocessed(),u=this.isFrozen,l)return n._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(h,n,this._materialContext);return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!u,t.effect._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),0))}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,n=null,s=null,r=null,o){if(this._prepareDefines(e,t,s,r,o),!t.isDirty)return null;t.markAsProcessed();const a=this.getScene().getEngine(),l=new E.L;let h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=x.G.HandleFallbacksForShadows(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");const u=[c.o.PositionKind];t.NORMAL&&u.push(c.o.NormalKind),t.TANGENT&&u.push(c.o.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&u.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&u.push(c.o.ColorKind),t.INSTANCESCOLOR&&u.push(c.o.ColorInstanceKind),x.G.PrepareAttributesForBones(u,e,t,l),x.G.PrepareAttributesForInstances(u,t),x.G.PrepareAttributesForMorphTargets(u,e,t),x.G.PrepareAttributesForBakedVertexAnimation(u,e,t);let p="pbr";const f=["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"],m=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],v=["Material","Scene","Mesh"];this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=f,this._eventInfo.attributes=u,this._eventInfo.samplers=m,this._eventInfo.uniformBuffersNames=v,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(g.S.PrepareEffect,this._eventInfo),d.o.AddUniforms(f),d.o.AddSamplers(m),(0,D.qx)(f),_.$&&(_.$.PrepareUniforms(f,t),_.$.PrepareSamplers(m,t)),x.G.PrepareUniformsAndSamplersList({uniformsNames:f,uniformBuffersNames:v,samplers:m,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const y={};this.customShaderNameResolve&&(p=this.customShaderNameResolve(p,f,v,m,t,u,y));const b=t.toString(),T=a.createEffect(p,{attributes:u,uniformsNames:f,uniformBuffersNames:v,samplers:m,defines:b,fallbacks:l,onCompiled:i,onError:n,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS},processFinalCode:y.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},a);return this._eventInfo.customCode=void 0,T}_prepareDefines(e,t,i=null,n=null,s=!1){var r;const o=this.getScene(),a=o.getEngine();x.G.PrepareDefinesForLights(o,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,x.G.PrepareDefinesForMultiview(o,t);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(x.G.PrepareDefinesForPrePass(o,t,this.canRenderToMRT&&!l),x.G.PrepareDefinesForOIT(o,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(o.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,a.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&T.k.DiffuseTextureEnabled?(x.G.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&T.k.AmbientTextureEnabled?(x.G.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&T.k.OpacityTextureEnabled?(x.G.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&T.k.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,a._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===b.x.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case b.x.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case b.x.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case b.x.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case b.x.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case b.x.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case b.x.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case b.x.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case b.x.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case b.x.CUBIC_MODE:case b.x.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==b.x.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||a.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&&T.k.LightmapTextureEnabled?(x.G.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&T.k.EmissiveTextureEnabled?(x.G.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,T.k.SpecularTextureEnabled){if(this._metallicTexture?(x.G.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?(x.G.PrepareDefinesForMergedUV(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture){const e=null!==this._metallicReflectanceTexture&&this._metallicReflectanceTexture._texture===(null===(r=this._reflectanceTexture)||void 0===r?void 0:r._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(x.G.PrepareDefinesForMergedUV(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&!e&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(x.G.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?x.G.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;a.getCaps().standardDerivatives&&this._bumpTexture&&T.k.BumpTextureEnabled&&!this._disableBumpMap?(x.G.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&T.k.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&T.k.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===N.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===N.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=a.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(x.G.PrepareDefinesForMisc(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(c.o.NormalKind),t.DEBUGMODE=this._debugMode),x.G.PrepareDefinesForFrameBoundValues(o,a,this,t,!!i,n,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),x.G.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==N.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const n={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(g.S.GetDefineNames,this._eventInfo);const s=new w(this._eventInfo.defineNames),r=this._prepareEffect(e,s,void 0,void 0,n.useInstances,n.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(O.effect=r,O.subMesh=null,this._onEffectCreatedObservable.notifyObservers(O)),r.isReady()?t&&t(this):r.onCompileObservable.add((()=>{t&&t(this)}))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var n,s,r,o;const a=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=a.getEngine();this._uniformBuffer.bindToEffect(c,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,a,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(a,c,t.visibility);x.G.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let _=null;const m=this._uniformBuffer;if(d){if(this.bindViewProjection(c),_=this._getReflectionTexture(),!m.useUbo||!this.isFrozen||!m.isSync||c._forceRebindOnNextCall){if(a.texturesEnabled){if(this._albedoTexture&&T.k.DiffuseTextureEnabled&&(m.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),x.G.BindTextureMatrix(this._albedoTexture,m,"albedo")),this._ambientTexture&&T.k.AmbientTextureEnabled&&(m.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),x.G.BindTextureMatrix(this._ambientTexture,m,"ambient")),this._opacityTexture&&T.k.OpacityTextureEnabled&&(m.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),x.G.BindTextureMatrix(this._opacityTexture,m,"opacity")),_&&T.k.ReflectionTextureEnabled){if(m.updateMatrix("reflectionMatrix",_.getReflectionTextureMatrix()),m.updateFloat2("vReflectionInfos",_.level,0),_.boundingBoxSize){const e=_;m.updateVector3("vReflectionPosition",e.boundingBoxPosition),m.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=_.getSize().width;m.updateFloat2("vReflectionFilteringInfo",e,f.R.Log2(e))}if(!h.USEIRRADIANCEMAP){const e=_.sphericalPolynomial;if(h.USESPHERICALFROMREFLECTIONMAP&&e)if(h.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;m.updateVector3("vSphericalL00",t.l00),m.updateVector3("vSphericalL1_1",t.l1_1),m.updateVector3("vSphericalL10",t.l10),m.updateVector3("vSphericalL11",t.l11),m.updateVector3("vSphericalL2_2",t.l2_2),m.updateVector3("vSphericalL2_1",t.l2_1),m.updateVector3("vSphericalL20",t.l20),m.updateVector3("vSphericalL21",t.l21),m.updateVector3("vSphericalL22",t.l22)}else m.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),m.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),m.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),m.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),m.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),m.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),m.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),m.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),m.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}m.updateFloat3("vReflectionMicrosurfaceInfos",_.getSize().width,_.lodGenerationScale,_.lodGenerationOffset)}this._emissiveTexture&&T.k.EmissiveTextureEnabled&&(m.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),x.G.BindTextureMatrix(this._emissiveTexture,m,"emissive")),this._lightmapTexture&&T.k.LightmapTextureEnabled&&(m.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),x.G.BindTextureMatrix(this._lightmapTexture,m,"lightmap")),T.k.SpecularTextureEnabled&&(this._metallicTexture?(m.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),x.G.BindTextureMatrix(this._metallicTexture,m,"reflectivity")):this._reflectivityTexture&&(m.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),x.G.BindTextureMatrix(this._reflectivityTexture,m,"reflectivity")),this._metallicReflectanceTexture&&(m.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),x.G.BindTextureMatrix(this._metallicReflectanceTexture,m,"metallicReflectance")),this._reflectanceTexture&&h.REFLECTANCE&&(m.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),x.G.BindTextureMatrix(this._reflectanceTexture,m,"reflectance")),this._microSurfaceTexture&&(m.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),x.G.BindTextureMatrix(this._microSurfaceTexture,m,"microSurfaceSampler"))),this._bumpTexture&&u.getCaps().standardDerivatives&&T.k.BumpTextureEnabled&&!this._disableBumpMap&&(m.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),x.G.BindTextureMatrix(this._bumpTexture,m,"bump"),a._mirroredCameraPosition?m.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):m.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&m.updateFloat("pointSize",this.pointSize),h.METALLICWORKFLOW){p.zZ.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,p.zZ.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,m.updateColor4("vReflectivityColor",p.zZ.Color3[0],1);const e=null!==(s=null===(n=this.subSurface)||void 0===n?void 0:n._indexOfRefraction)&&void 0!==s?s:1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,p.zZ.Color3[0]);const r=this._metallicF0Factor;m.updateColor4("vMetallicReflectanceFactors",p.zZ.Color3[0],r)}else m.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);m.updateColor3("vEmissiveColor",T.k.EmissiveTextureEnabled?this._emissiveColor:p.Wo.BlackReadOnly),m.updateColor3("vReflectionColor",this._reflectionColor),!h.SS_REFRACTION&&(null===(r=this.subSurface)||void 0===r?void 0:r._linkRefractionWithTransparency)?m.updateColor4("vAlbedoColor",this._albedoColor,1):m.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*a.environmentIntensity,this._lightingInfos.w=this._specularIntensity,m.updateVector4("vLightingIntensity",this._lightingInfos),a.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),m.updateColor3("vAmbientColor",this._globalAmbientColor),m.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}a.texturesEnabled&&(this._albedoTexture&&T.k.DiffuseTextureEnabled&&m.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&T.k.AmbientTextureEnabled&&m.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&T.k.OpacityTextureEnabled&&m.setTexture("opacitySampler",this._opacityTexture),_&&T.k.ReflectionTextureEnabled&&(h.LODBASEDMICROSFURACE?m.setTexture("reflectionSampler",_):(m.setTexture("reflectionSampler",_._lodTextureMid||_),m.setTexture("reflectionSamplerLow",_._lodTextureLow||_),m.setTexture("reflectionSamplerHigh",_._lodTextureHigh||_)),h.USEIRRADIANCEMAP&&m.setTexture("irradianceSampler",_.irradianceTexture)),h.ENVIRONMENTBRDF&&m.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&T.k.EmissiveTextureEnabled&&m.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&T.k.LightmapTextureEnabled&&m.setTexture("lightmapSampler",this._lightmapTexture),T.k.SpecularTextureEnabled&&(this._metallicTexture?m.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&m.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&m.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&h.REFLECTANCE&&m.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&m.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&u.getCaps().standardDerivatives&&T.k.BumpTextureEnabled&&!this._disableBumpMap&&m.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(c),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,D.an)(this._activeEffect,this,a),this.bindEyePosition(c)}else a.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!d&&this.isFrozen||(a.lightsEnabled&&!this._disableLighting&&x.G.BindLights(a,t,this._activeEffect,h,this._maxSimultaneousLights),(a.fogEnabled&&t.applyFog&&a.fogMode!==l.x.FOGMODE_NONE||_||t.receiveShadows||h.PREPASS)&&this.bindView(c),x.G.BindFogParameters(a,t,this._activeEffect,!0),h.NUM_MORPH_INFLUENCERS&&x.G.BindMorphTargetParameters(t,this._activeEffect),h.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(o=t.bakedVertexAnimationManager)||void 0===o||o.bind(c,h.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),x.G.BindLogDepth(h,this._activeEffect,a)),this._afterBind(t,this._activeEffect),m.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e}setPrePassRenderer(){var e;if(!(null===(e=this.subSurface)||void 0===e?void 0:e.isScatteringEnabled))return!1;const t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,n,s,r,o,a,l,h,c,u,d,p;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(i=this._albedoTexture)||void 0===i||i.dispose(),null===(n=this._ambientTexture)||void 0===n||n.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(r=this._reflectionTexture)||void 0===r||r.dispose(),null===(o=this._emissiveTexture)||void 0===o||o.dispose(),null===(a=this._metallicTexture)||void 0===a||a.dispose(),null===(l=this._reflectivityTexture)||void 0===l||l.dispose(),null===(h=this._bumpTexture)||void 0===h||h.dispose(),null===(c=this._lightmapTexture)||void 0===c||c.dispose(),null===(u=this._metallicReflectanceTexture)||void 0===u||u.dispose(),null===(d=this._reflectanceTexture)||void 0===d||d.dispose(),null===(p=this._microSurfaceTexture)||void 0===p||p.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}N.PBRMATERIAL_OPAQUE=m.F.MATERIAL_OPAQUE,N.PBRMATERIAL_ALPHATEST=m.F.MATERIAL_ALPHATEST,N.PBRMATERIAL_ALPHABLEND=m.F.MATERIAL_ALPHABLEND,N.PBRMATERIAL_ALPHATESTANDBLEND=m.F.MATERIAL_ALPHATESTANDBLEND,N.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,N.LIGHTFALLOFF_PHYSICAL=0,N.LIGHTFALLOFF_GLTF=1,N.LIGHTFALLOFF_STANDARD=2,(0,n.gn)([(0,s.rX)()],N.prototype,"_imageProcessingConfiguration",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsMiscDirty")],N.prototype,"debugMode",void 0),(0,n.gn)([(0,s.qC)()],N.prototype,"useLogarithmicDepth",null)},3077:(e,t,i)=>{i.d(t,{Y:()=>u,d:()=>c});var n=i(9472),s=i(3956),r=i(4649),o=i(85),a=i(5346),l=i(8449),h=i(1917);class c extends h.H{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 u extends l.n{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new c,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=u._DefaultIndexOfRefraction,this.indexOfRefraction=u._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=r.Wo.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 n=this._material._disableBumpMap;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&o.k.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&o.k.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1;if(i.getCaps().standardDerivatives&&this._bumpTexture&&o.k.ClearCoatBumpTextureEnabled&&!n&&!this._bumpTexture.isReady())return!1;if(this._isTintEnabled&&this._tintTexture&&o.k.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&o.k.ClearCoatTextureEnabled?a.G.PrepareDefinesForMergedUV(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&o.k.ClearCoatTextureEnabled?a.G.PrepareDefinesForMergedUV(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&o.k.ClearCoatBumpTextureEnabled?a.G.PrepareDefinesForMergedUV(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===u._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&o.k.ClearCoatTintTextureEnabled?(a.G.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,n){var s,r,l,h,c,u,d,p;if(!this._isEnabled)return;const f=n.materialDefines,_=this._material.isFrozen,m=this._material._disableBumpMap,g=this._material._invertNormalMapX,v=this._material._invertNormalMapY,y=f.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!_||!e.isSync){y&&o.k.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),a.G.BindTextureMatrix(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&o.k.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",null!==(r=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==r?r:0,null!==(h=null===(l=this._texture)||void 0===l?void 0:l.level)&&void 0!==h?h:0,null!==(u=null===(c=this._textureRoughness)||void 0===c?void 0:c.coordinatesIndex)&&void 0!==u?u:0,null!==(p=null===(d=this._textureRoughness)||void 0===d?void 0:d.level)&&void 0!==p?p:0),this._texture&&a.G.BindTextureMatrix(this._texture,e,"clearCoat"),!this._textureRoughness||y||f.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE||a.G.BindTextureMatrix(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&o.k.ClearCoatTextureEnabled&&!m&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),a.G.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&&o.k.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),a.G.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const n=1-this._indexOfRefraction,_=1+this._indexOfRefraction,x=Math.pow(-n/_,2),b=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",x,b,n,_),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&&o.k.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!y&&!f.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&o.k.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&o.k.ClearCoatBumpTextureEnabled&&!m&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&o.k.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,n,s;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(n=this._bumpTexture)||void 0===n||n.dispose(),null===(s=this._tintTexture)||void 0===s||s.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"}]}}}u._DefaultIndexOfRefraction=1.5,(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"isEnabled",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"intensity",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"roughness",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"indexOfRefraction",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"texture",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"useRoughnessFromMainTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"textureRoughness",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"remapF0OnInterfaceChange",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"bumpTexture",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"isTintEnabled",void 0),(0,n.gn)([(0,s.n9)()],u.prototype,"tintColor",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"tintColorAtDistance",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"tintThickness",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"tintTexture",void 0)},3949:(e,t,i)=>{i.d(t,{B:()=>c,f:()=>h});var n=i(9472),s=i(3956),r=i(85),o=i(5346),a=i(8449),l=i(1917);class h extends l.H{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 c extends a.n{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new h,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=c._DefaultMinimumThickness,this.maximumThickness=c._DefaultMaximumThickness,this.indexOfRefraction=c._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&r.k.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&r.k.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.IRIDESCENCE=!0,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=null!==this._texture&&this._texture._texture===(null===(i=this._thicknessTexture)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&r.k.IridescenceTextureEnabled?o.G.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&r.k.IridescenceTextureEnabled?o.G.PrepareDefinesForMergedUV(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,n){var s,a,l,h,c,u,d,p;if(!this._isEnabled)return;const f=n.materialDefines,_=this._material.isFrozen,m=f.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&_&&e.isSync||(m&&r.k.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),o.G.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&r.k.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(a=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==a?a:0,null!==(h=null===(l=this._texture)||void 0===l?void 0:l.level)&&void 0!==h?h:0,null!==(u=null===(c=this._thicknessTexture)||void 0===c?void 0:c.coordinatesIndex)&&void 0!==u?u:0,null!==(p=null===(d=this._thicknessTexture)||void 0===d?void 0:d.level)&&void 0!==p?p:0),this._texture&&o.G.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||m||f.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||o.G.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&r.k.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!m&&!f.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&r.k.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._thicknessTexture)||void 0===i||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}c._DefaultMinimumThickness=100,c._DefaultMaximumThickness=400,c._DefaultIndexOfRefraction=1.3,(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],c.prototype,"isEnabled",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"intensity",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"minimumThickness",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"maximumThickness",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"indexOfRefraction",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],c.prototype,"texture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],c.prototype,"thicknessTexture",void 0)},9500:(e,t,i)=>{i.d(t,{Y:()=>h});var n=i(9472),s=i(3956),r=i(6344),o=i(4649),a=i(5843),l=i(2208);class h extends a.m{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===a.m.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?a.m.LIGHTFALLOFF_PHYSICAL:a.m.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===a.m.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?a.m.LIGHTFALLOFF_GLTF:a.m.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=h.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=o.Wo.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new o.Wo(0,0,0),this.albedoColor=new o.Wo(1,1,1),this.reflectivityColor=new o.Wo(1,1,1),this.reflectionColor=new o.Wo(1,1,1),this.emissiveColor=new o.Wo(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this._environmentBRDFTexture=(0,r.$)(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0){const i=s.p4.Clone((()=>new h(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return i.id=e,i.name=e,this.stencil.copyTo(i.stencil),this.clearCoat.copyTo(i.clearCoat),this.anisotropy.copyTo(i.anisotropy),this.brdf.copyTo(i.brdf),this.sheen.copyTo(i.sheen),this.subSurface.copyTo(i.subSurface),this.iridescence.copyTo(i.iridescence),i}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const n=s.p4.Parse((()=>new h(e.name,t)),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}h.PBRMATERIAL_OPAQUE=a.m.PBRMATERIAL_OPAQUE,h.PBRMATERIAL_ALPHATEST=a.m.PBRMATERIAL_ALPHATEST,h.PBRMATERIAL_ALPHABLEND=a.m.PBRMATERIAL_ALPHABLEND,h.PBRMATERIAL_ALPHATESTANDBLEND=a.m.PBRMATERIAL_ALPHATESTANDBLEND,h.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=a.m.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"directIntensity",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"emissiveIntensity",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"environmentIntensity",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"specularIntensity",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"disableBumpMap",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"albedoTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"ambientTexture",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"ambientTextureStrength",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],h.prototype,"opacityTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"reflectionTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"emissiveTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"reflectivityTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"metallicTexture",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"metallic",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"roughness",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"metallicF0Factor",void 0),(0,n.gn)([(0,s.n9)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"metallicReflectanceColor",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"metallicReflectanceTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"reflectanceTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"microSurfaceTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"bumpTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty",null)],h.prototype,"lightmapTexture",void 0),(0,n.gn)([(0,s.n9)("ambient"),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"ambientColor",void 0),(0,n.gn)([(0,s.n9)("albedo"),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"albedoColor",void 0),(0,n.gn)([(0,s.n9)("reflectivity"),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"reflectivityColor",void 0),(0,n.gn)([(0,s.n9)("reflection"),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"reflectionColor",void 0),(0,n.gn)([(0,s.n9)("emissive"),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"emissiveColor",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"microSurface",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useLightmapAsShadowmap",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],h.prototype,"useAlphaFromAlbedoTexture",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],h.prototype,"forceAlphaTest",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],h.prototype,"alphaCutOff",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useSpecularOverAlpha",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useRoughnessFromMetallicTextureGreen",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useMetallnessFromMetallicTextureBlue",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useAmbientInGrayScale",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"usePhysicalLightFalloff",null),(0,n.gn)([(0,s.qC)()],h.prototype,"useGLTFLightFalloff",null),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useRadianceOverAlpha",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useObjectSpaceNormalMap",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useParallax",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useParallaxOcclusion",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"parallaxScaleBias",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsLightsDirty")],h.prototype,"disableLighting",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"forceIrradianceInFragment",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsLightsDirty")],h.prototype,"maxSimultaneousLights",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"invertNormalMapX",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"invertNormalMapY",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"twoSidedLighting",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useAlphaFresnel",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useLinearAlphaFresnel",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"environmentBRDFTexture",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"forceNormalForward",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"enableSpecularAntiAliasing",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useHorizonOcclusion",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],h.prototype,"useRadianceOcclusion",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsMiscDirty")],h.prototype,"unlit",void 0),(0,l.H)("BABYLON.PBRMaterial",h)},4783:(e,t,i)=>{i.d(t,{A:()=>c,B:()=>u});var n=i(9472),s=i(3956),r=i(4649),o=i(85),a=i(5346),l=i(8449),h=i(1917);class c extends h.H{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 u extends l.n{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new c,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=r.Wo.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){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&o.k.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&o.k.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&o.k.SheenTextureEnabled?(a.G.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&o.k.SheenTextureEnabled?a.G.PrepareDefinesForMergedUV(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,n){var s,r,l,h,c,u,d,p;if(!this._isEnabled)return;const f=n.materialDefines,_=this._material.isFrozen,m=f.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&_&&e.isSync||(m&&o.k.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),a.G.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&o.k.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(r=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==r?r:0,null!==(h=null===(l=this._texture)||void 0===l?void 0:l.level)&&void 0!==h?h:0,null!==(u=null===(c=this._textureRoughness)||void 0===c?void 0:c.coordinatesIndex)&&void 0!==u?u:0,null!==(p=null===(d=this._textureRoughness)||void 0===d?void 0:d.level)&&void 0!==p?p:0),this._texture&&a.G.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||m||f.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||a.G.BindTextureMatrix(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&o.k.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!m&&!f.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&o.k.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"isEnabled",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"linkSheenWithAlbedo",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"intensity",void 0),(0,n.gn)([(0,s.n9)()],u.prototype,"color",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"texture",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"useRoughnessFromMainTexture",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"roughness",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"textureRoughness",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"albedoScaling",void 0)},3808:(e,t,i)=>{i.d(t,{H:()=>d,u:()=>p});var n=i(9472),s=i(3956),r=i(4649),o=i(85),a=i(5346),l=i(1128),h=i(4141),c=i(8449),u=i(1917);class d extends u.H{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_SCATTERING=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}}class p extends c.n{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){this._volumeIndexOfRefraction=e>=1?e:-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new d,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=r.Wo.White(),this.tintColorAtDistance=1,this.diffusionDistance=r.Wo.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&&o.k.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&o.k.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,void(e.SS_USE_GLTF_TEXTURES=!1);if(e._areTexturesDirty){e.SUBSURFACE=!0,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1;const i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,n=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(n||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&o.k.ThicknessTextureEnabled&&a.G.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&o.k.RefractionIntensityTextureEnabled&&!s&&a.G.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&o.k.TranslucencyIntensityTextureEnabled&&!s&&a.G.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)&&s,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&s,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&s,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&o.k.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,n){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;n.getRenderingMesh().getWorldMatrix().decompose(h.jp.Vector3[0]);const s=Math.max(Math.abs(h.jp.Vector3[0].x),Math.abs(h.jp.Vector3[0].y),Math.abs(h.jp.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,n){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const s=n.materialDefines,r=this._material.isFrozen,h=this._material.realTimeFiltering,c=s.LODBASEDMICROSFURACE,u=this._getRefractionTexture(t);if(!e.useUbo||!r||!e.isSync){if(this._thicknessTexture&&o.k.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),a.G.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&o.k.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),a.G.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&o.k.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),a.G.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),u&&o.k.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",u.getRefractionTextureMatrix());let t=1;u.isCube||u.depth&&(t=u.depth);const i=u.getSize().width,n=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",u.level,1/n,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,u.lodGenerationScale,u.lodGenerationOffset,1/this.indexOfRefraction),h&&e.updateFloat2("vRefractionFilteringInfo",i,l.R.Log2(i)),u.boundingBoxSize){const t=u;e.updateVector3("vRefractionPosition",t.boundingBoxPosition),e.updateVector3("vRefractionSize",t.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0)}t.texturesEnabled&&(this._thicknessTexture&&o.k.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&o.k.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&o.k.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),u&&o.k.RefractionTextureEnabled&&(c?e.setTexture("refractionSampler",u):(e.setTexture("refractionSampler",u._lodTextureMid||u),e.setTexture("refractionSamplerLow",u._lodTextureLow||u),e.setTexture("refractionSamplerHigh",u._lodTextureHigh||u))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){o.k.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!(o.k.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"}]}}}(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"isRefractionEnabled",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"isTranslucencyEnabled",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markScenePrePassDirty")],p.prototype,"isScatteringEnabled",void 0),(0,n.gn)([(0,s.qC)()],p.prototype,"_scatteringDiffusionProfileIndex",void 0),(0,n.gn)([(0,s.qC)()],p.prototype,"refractionIntensity",void 0),(0,n.gn)([(0,s.qC)()],p.prototype,"translucencyIntensity",void 0),(0,n.gn)([(0,s.qC)()],p.prototype,"useAlbedoToTintRefraction",void 0),(0,n.gn)([(0,s.qC)()],p.prototype,"useAlbedoToTintTranslucency",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"thicknessTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"refractionTexture",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"indexOfRefraction",void 0),(0,n.gn)([(0,s.qC)()],p.prototype,"_volumeIndexOfRefraction",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"volumeIndexOfRefraction",null),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"invertRefractionY",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"linkRefractionWithTransparency",void 0),(0,n.gn)([(0,s.qC)()],p.prototype,"minimumThickness",void 0),(0,n.gn)([(0,s.qC)()],p.prototype,"maximumThickness",void 0),(0,n.gn)([(0,s.qC)()],p.prototype,"useThicknessAsDepth",void 0),(0,n.gn)([(0,s.n9)()],p.prototype,"tintColor",void 0),(0,n.gn)([(0,s.qC)()],p.prototype,"tintColorAtDistance",void 0),(0,n.gn)([(0,s.n9)()],p.prototype,"diffusionDistance",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"useMaskFromThicknessTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"refractionIntensityTexture",void 0),(0,n.gn)([(0,s.oU)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"translucencyIntensityTexture",void 0),(0,n.gn)([(0,s.qC)(),(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],p.prototype,"useGltfStyleTextures",void 0)},7902:(e,t,i)=>{i.d(t,{g:()=>_});var n=i(9472),s=i(3956),r=i(5757),o=i(708),a=i(2333),l=i(7104),h=i(2262),c=i(4246),u=i(8517);i(7246),i(6697);i(8104).v.ShadersStore.proceduralVertexShader="attribute vec2 position;\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";var d=i(2208),p=i(1431),f=i(1345);class _ extends h.x{constructor(e,t,i,n,s=null,l=!0,h=!1,c=0){super(null,n,!l),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new r.y$,this.onBeforeGenerationObservable=new r.y$,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null;let d=(n=this.getScene()||p.l.LastCreatedScene)._getComponent(a.l.NAME_PROCEDURALTEXTURE);d||(d=new u.O(n),n._addComponent(d)),n.proceduralTextures.push(this),this._fullEngine=n.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=c,this._generateMipMaps=l,this._drawWrapper=new f.q(this._fullEngine),this.setFragment(i),this._fallbackTexture=s;const _=this._createRtWrapper(h,t,l,c);this._texture=_.texture;const m=[];m.push(1,1),m.push(-1,1),m.push(-1,-1),m.push(1,-1),this._vertexBuffers[o.o.PositionKind]=new o.o(this._fullEngine,m,o.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,n){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:n}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:n}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then((e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId})):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[o.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===c._.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=c._.REFRESHRATE_RENDER_ONCE)}reset(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose()}_getDefines(){return""}isReady(){const e=this._fullEngine;let t;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const i=this._getDefines();return!(!this._drawWrapper.effect||i!==this._cachedDefines||!this._drawWrapper.effect.isReady())||(t=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._cachedDefines!==i&&(this._cachedDefines=i,this._drawWrapper.effect=e.createEffect(t,[o.o.PositionKind],this._uniforms,this._samplers,i,void 0,void 0,(()=>{var e;null===(e=this._rtWrapper)||void 0===e||e.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}))),this._drawWrapper.effect.isReady())}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const n=this._createRtWrapper(i,e,t,this._textureType);this._texture=n.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var t,i;const n=this.getScene();if(!n)return;const s=this._fullEngine;if(s.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),s.setState(!1),!this.nodeMaterialSource){for(const e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;null===(t=s._debugPushGroup)||void 0===t||t.call(s,`procedural texture generation for ${this.name}`,1);const r=s.currentViewport;if(this.isCube)for(let e=0;e<6;e++)s.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&s.clear(n.clearColor,!0,!1,!1),s.drawElementsType(l.F.TriangleFillMode,0,6);else s.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&s.clear(n.clearColor,!0,!1,!1),s.drawElementsType(l.F.TriangleFillMode,0,6);s.unBindFramebuffer(this._rtWrapper,this.isCube),r&&s.setViewport(r),this.isCube&&s.generateMipMapsForCubemap(this._texture),null===(i=s._debugPopGroup)||void 0===i||i.call(s,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new _(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[o.o.PositionKind];i&&(i.dispose(),this._vertexBuffers[o.o.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}(0,n.gn)([(0,s.qC)()],_.prototype,"isEnabled",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"autoClear",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"_generateMipMaps",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"_size",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"refreshRate",null),(0,d.H)("BABYLON.ProceduralTexture",_)},8517:(e,t,i)=>{i.d(t,{O:()=>r});var n=i(7257),s=i(2333);class r{constructor(e){this.name=s.l.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=new Array}register(){this.scene._beforeClearStage.registerStep(s.l.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){n.w1.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e<this.scene.proceduralTextures.length;e++){const t=this.scene.proceduralTextures[e];t._shouldRender()&&t.render()}n.w1.EndPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0)}}}},6702:(e,t,i)=>{i.d(t,{V:()=>c});var n=i(9472),s=i(3956),r=i(5757),o=i(4141),a=i(1431),l=i(1983),h=(i(5661),i(2035));class c extends h.g{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this._markAllSubMeshesAsTexturesDirty()}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){this._texture&&(this._texture._isRGBD=e)}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=(0,l.f)()),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=c.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=new Array,this.onDisposeObservable=new r.y$,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?c._IsScene(e)?this._scene=e:this._engine=e:this._scene=a.l.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 null!==e}getTextureMatrix(){return o.y3.IdentityReadOnly}getReflectionTextureMatrix(){return o.y3.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,n,s,r){const o=this._getEngine();if(!o)return null;const a=o._getUseSRGBBuffer(!!s,t),l=o.getLoadedTexturesCache();for(let o=0;o<l.length;o++){const h=l[o];if(!(void 0!==s&&a!==h._useSRGBBuffer||void 0!==n&&n!==h.invertY||h.url!==e||h.generateMipMaps!==!t||i&&i!==h.samplingMode||void 0!==r&&r!==h.isCube))return h.incrementReferences(),h}return null}_rebuild(){}clone(){return null}get textureType(){return this._texture&&void 0!==this._texture.type?this._texture.type:0}get textureFormat(){return this._texture&&void 0!==this._texture.format?this._texture.format:5}_markAllSubMeshesAsTexturesDirty(){const e=this.getScene();e&&e.markAllMaterialsAsDirty(1)}readPixels(e=0,t=0,i=null,n=!0,s=!1,r=0,o=0,a=Number.MAX_VALUE,l=Number.MAX_VALUE){if(!this._texture)return null;const h=this._getEngine();if(!h)return null;const c=this.getSize();let u=c.width,d=c.height;0!==t&&(u/=Math.pow(2,t),d/=Math.pow(2,t),u=Math.round(u),d=Math.round(d)),a=Math.min(u,a),l=Math.min(d,l);try{return this._texture.isCube?h._readTexturePixels(this._texture,a,l,e,t,i,n,s,r,o):h._readTexturePixels(this._texture,a,l,-1,t,i,n,s,r,o)}catch(e){return null}}_readPixelsSync(e=0,t=0,i=null,n=!0,s=!1){if(!this._texture)return null;const r=this.getSize();let o=r.width,a=r.height;const l=this._getEngine();if(!l)return null;0!=t&&(o/=Math.pow(2,t),a/=Math.pow(2,t),o=Math.round(o),a=Math.round(a));try{return this._texture.isCube?l._readTexturePixelsSync(this._texture,o,a,e,t,i,n,s):l._readTexturePixelsSync(this._texture,o,a,-1,t,i,n,s)}catch(e){return null}}get _lodTextureHigh(){return this._texture?this._texture._lodTextureHigh:null}get _lodTextureMid(){return this._texture?this._texture._lodTextureMid:null}get _lodTextureLow(){return this._texture?this._texture._lodTextureLow:null}dispose(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene.removePendingData(this);const e=this._scene.textures.indexOf(this);if(e>=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=s.p4.Serialize(this);return s.p4.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let n=0;n<e.length;n++){const s=e[n];if(s.isReady())0==--i&&t();else{const e=s.onLoadObservable;e?e.addOnce((()=>{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}c.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,(0,n.gn)([(0,s.qC)()],c.prototype,"uniqueId",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"name",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"metadata",void 0),(0,n.gn)([(0,s.qC)("hasAlpha")],c.prototype,"_hasAlpha",void 0),(0,n.gn)([(0,s.qC)("getAlphaFromRGB")],c.prototype,"_getAlphaFromRGB",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"level",void 0),(0,n.gn)([(0,s.qC)("coordinatesIndex")],c.prototype,"_coordinatesIndex",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"optimizeUVAllocation",void 0),(0,n.gn)([(0,s.qC)("coordinatesMode")],c.prototype,"_coordinatesMode",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"wrapU",null),(0,n.gn)([(0,s.qC)()],c.prototype,"wrapV",null),(0,n.gn)([(0,s.qC)()],c.prototype,"wrapR",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"anisotropicFilteringLevel",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"isCube",null),(0,n.gn)([(0,s.qC)()],c.prototype,"is3D",null),(0,n.gn)([(0,s.qC)()],c.prototype,"is2DArray",null),(0,n.gn)([(0,s.qC)()],c.prototype,"gammaSpace",null),(0,n.gn)([(0,s.qC)()],c.prototype,"invertZ",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"lodLevelInAlpha",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"lodGenerationOffset",null),(0,n.gn)([(0,s.qC)()],c.prototype,"lodGenerationScale",null),(0,n.gn)([(0,s.qC)()],c.prototype,"linearSpecularLOD",null),(0,n.gn)([(0,s.oU)()],c.prototype,"irradianceTexture",null),(0,n.gn)([(0,s.qC)()],c.prototype,"isRenderTarget",void 0)},452:(e,t,i)=>{var n=i(123),s=i(6702);s.V.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(s.V.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=n.$.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0})},4051:(e,t,i)=>{i.d(t,{B:()=>u});var n=i(9472),s=i(3956),r=i(7257),o=i(4141),a=i(6702),l=i(2262),h=i(2208),c=(i(2477),i(5757));class u extends a.V{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(o.y3.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let n="";return e.forEach((e=>n+=e)),new u(n,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,n=!0){const s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const r=new u(e,t,null,!1,null,null,null,void 0,!0,i,n);return t.useDelayedTextureLoading=s,r}constructor(e,t,i=null,n=!1,s=null,r=null,a=null,h=5,u=!1,d=null,p=!1,f=.8,_=0,m,g){var v;super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new c.y$,this.boundingBoxPosition=o.P.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new o.y3,this.name=e,this.url=e,this._noMipmap=n,this.hasAlpha=!1,this._format=h,this.isCube=!0,this._textureMatrix=o.y3.Identity(),this._createPolynomials=p,this.coordinatesMode=l.x.CUBIC_MODE,this._extensions=i,this._files=s,this._forcedExtension=d,this._loaderOptions=m,this._useSRGBBuffer=g,this._lodScale=f,this._lodOffset=_,(e||s)&&this.updateURL(e,d,r,u,a,i,null===(v=this.getScene())||void 0===v?void 0:v.useDelayedTextureLoading,s)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,n=!1,s=null,r=null,o=!1,a=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),u=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(u?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=n,n&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),a)this._files=a;else if(d||u||c||r||(r=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,r){for(let t=0;t<r.length;t++)this._files.push(e+r[t]);this._extensions=r}o?(this.delayLoadState=4,this._delayedOnLoad=i,this._delayedOnError=s):this._loadTexture(i,s)}delayLoad(e){4===this.delayLoadState&&(e&&(this._forcedExtension=e),this.delayLoadState=1,this._loadTexture(this._delayedOnLoad,this._delayedOnError))}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t,i;if(e.updateFlag===this._textureMatrix.updateFlag)return;if(e.isIdentity()!==this._textureMatrix.isIdentity()&&(null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this)))),this._textureMatrix=e,!(null===(i=this.getScene())||void 0===i?void 0:i.useRightHandedSystem))return;const n=o.jp.Vector3[0],s=o.jp.Quaternion[0],r=o.jp.Vector3[1];this._textureMatrix.decompose(n,s,r),s.z*=-1,s.w*=-1,o.y3.ComposeToRef(n,s,r,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return(null===(e=this.getScene())||void 0===e?void 0:e.useRightHandedSystem)?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var i;const n=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const o=()=>{var t;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1)),e&&e()},a=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),l.x.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?r.w1.SetImmediate((()=>o())):this._texture.onLoadedObservable.add((()=>o())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,n,this._lodScale,this._lodOffset,e,a,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,n,this._files,this._noMipmap,e,a,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),null===(i=this._texture)||void 0===i||i.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const n=s.p4.Parse((()=>{let n=!1;return e.prefiltered&&(n=e.prefiltered),new u(i+e.name,t,e.extensions,!1,e.files||null,null,null,void 0,n,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(n.boundingBoxPosition=o.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=o.P.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t<e.animations.length;t++){const i=e.animations[t],s=(0,h.q)("BABYLON.Animation");s&&n.animations.push(s.Parse(i))}return n}clone(){let e=0;const t=s.p4.Clone((()=>{const t=new u(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}(0,n.gn)([(0,s.qC)()],u.prototype,"url",void 0),(0,n.gn)([(0,s.hd)()],u.prototype,"boundingBoxPosition",void 0),(0,n.gn)([(0,s.hd)()],u.prototype,"boundingBoxSize",null),(0,n.gn)([(0,s.qC)("rotationY")],u.prototype,"rotationY",null),(0,n.gn)([(0,s.qC)("files")],u.prototype,"_files",void 0),(0,n.gn)([(0,s.qC)("forcedExtension")],u.prototype,"_forcedExtension",void 0),(0,n.gn)([(0,s.qC)("extensions")],u.prototype,"_extensions",void 0),(0,n.gn)([(0,s.oQ)("textureMatrix")],u.prototype,"_textureMatrix",void 0),(0,n.gn)([(0,s.oQ)("textureMatrixRefraction")],u.prototype,"_textureMatrixRefraction",void 0),l.x._CubeTextureParser=u.Parse,(0,h.H)("BABYLON.CubeTexture",u)},4160:(e,t,i)=>{i.d(t,{c:()=>r});var n=i(2722),s=i(2262);i(6914);class r extends s.x{constructor(e,t,i=null,n=!1,r=3,o=5,a){super(null,i,!n,a,r,void 0,void 0,void 0,void 0,o),this.name=e,this.wrapU=s.x.CLAMP_ADDRESSMODE,this.wrapV=s.x.CLAMP_ADDRESSMODE,this._generateMipMaps=n;const l=this._getEngine();if(!l)return;t.getContext?(this._canvas=t,this._texture=l.createDynamicTexture(t.width,t.height,n,r)):(this._canvas=l.createCanvas(1,1),t.width||0===t.width?this._texture=l.createDynamicTexture(t.width,t.height,n,r):this._texture=l.createDynamicTexture(t,t,n,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(){const e=this.getSize();this._context.fillRect(0,0,e.width,e.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,n,s,r,o,a=!0){const l=this.getSize();if(r&&(this._context.fillStyle=r,this._context.fillRect(0,0,l.width,l.height)),this._context.font=n,null==t){const i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){const e=parseInt(n.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),a&&this.update(o)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new r(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()&&n.Y.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return r._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}},6202:(e,t,i)=>{i.d(t,{S:()=>n,l:()=>o});var n,s=i(5757),r=i(3297);!function(e){e[e.Unknown=0]="Unknown",e[e.Url=1]="Url",e[e.Temp=2]="Temp",e[e.Raw=3]="Raw",e[e.Dynamic=4]="Dynamic",e[e.RenderTarget=5]="RenderTarget",e[e.MultiRenderTarget=6]="MultiRenderTarget",e[e.Cube=7]="Cube",e[e.CubeRaw=8]="CubeRaw",e[e.CubePrefiltered=9]="CubePrefiltered",e[e.Raw3D=10]="Raw3D",e[e.Raw2DArray=11]="Raw2DArray",e[e.DepthStencil=12]="DepthStencil",e[e.CubeRawRGBD=13]="CubeRawRGBD",e[e.Depth=14]="Depth"}(n||(n={}));class o extends r.a{get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new s.y$,this.onErrorObservable=new s.y$,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=n.Unknown,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._engine=e,this._source=t,this._uniqueId=o._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){var e;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const e=this.onRebuildCallback(this),t=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let t;switch(this.source){case n.Temp:break;case n.Url:return void(t=this._engine.createTexture(null!==(e=this._originalUrl)&&void 0!==e?e:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case n.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 n.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 n.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 n.Dynamic:t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),t._swapAndDie(this,!1),this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);break;case n.Cube:return void(t=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{t._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer));case n.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 n.CubeRawRGBD:return;case n.CubePrefiltered:return t=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(t._sphericalPolynomial=this._sphericalPolynomial)}}_swapAndDie(e,t=!0){var i;null===(i=this._hardwareTexture)||void 0===i||i.setUsage(e._source,this.generateMipMaps,this.isCube,this.width,this.height),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const n=this._engine.getLoadedTexturesCache();let s=n.indexOf(this);-1!==s&&n.splice(s,1),s=n.indexOf(e),-1===s&&n.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}}o._Counter=0},9630:(e,t,i)=>{i.d(t,{N:()=>a});var n=i(3956),s=i(4277),r=i(6202),o=i(4051);i(6599);class a extends o.B{constructor(e,t,i,n=5,s=0,r=!1,o=!1,a=3,l=null){super("",e),this._texture=e.getEngine().createRawCubeTexture(t,i,n,s,r,o,a,l)}update(e,t,i,n,s=null){this._texture.getEngine().updateRawCubeTexture(this._texture,e,t,i,n,s)}updateRGBDAsync(e,t=null,i=.8,n=0){return(0,s.Lf)(this._texture,e,t,i,n).then((()=>{}))}clone(){return n.p4.Clone((()=>{const e=this.getScene(),t=this._texture,i=new a(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===r.S.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i}),this)}}},7647:(e,t,i)=>{i.d(t,{l:()=>s});var n=i(2262);i(6599);class s extends n.x{constructor(e,t,i,s,r,o=!0,a=!1,l=3,h=0,c,u){super(null,r,!o,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,c),this.format=s,this._engine&&(this._engine._caps.textureFloatLinearFiltering||1!==h||(l=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==h||(l=1),this._texture=this._engine.createRawTexture(e,t,i,s,o,a,l,null,h,null!=c?c:0,null!=u&&u),this.wrapU=n.x.CLAMP_ADDRESSMODE,this.wrapV=n.x.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,n,r=!0,o=!1,a=3){return new s(e,t,i,1,n,r,o,a)}static CreateLuminanceAlphaTexture(e,t,i,n,r=!0,o=!1,a=3){return new s(e,t,i,2,n,r,o,a)}static CreateAlphaTexture(e,t,i,n,r=!0,o=!1,a=3){return new s(e,t,i,0,n,r,o,a)}static CreateRGBTexture(e,t,i,n,r=!0,o=!1,a=3,l=0,h=0,c=!1){return new s(e,t,i,4,n,r,o,a,l,h,c)}static CreateRGBATexture(e,t,i,n,r=!0,o=!1,a=3,l=0,h=0,c=!1){return new s(e,t,i,5,n,r,o,a,l,h,c)}static CreateRGBAStorageTexture(e,t,i,n,r=!0,o=!1,a=3,l=0,h=!1){return new s(e,t,i,5,n,r,o,a,l,1,h)}static CreateRTexture(e,t,i,r,o=!0,a=!1,l=n.x.TRILINEAR_SAMPLINGMODE,h=1){return new s(e,t,i,6,r,o,a,l,h)}static CreateRStorageTexture(e,t,i,r,o=!0,a=!1,l=n.x.TRILINEAR_SAMPLINGMODE,h=1){return new s(e,t,i,6,r,o,a,l,h,1)}}},3324:(e,t,i)=>{i.d(t,{e:()=>s});var n=i(2262);i(6599);class s extends n.x{get depth(){return this._depth}constructor(e,t,i,s,r,o,a=!0,l=!1,h=n.x.TRILINEAR_SAMPLINGMODE,c=0){super(null,o,!a,l),this.format=r,this._texture=o.getEngine().createRawTexture2DArray(e,t,i,s,r,a,l,h,null,c),this._depth=s,this.is2DArray=!0}update(e){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}static CreateRGBATexture(e,t,i,n,r,o=!0,a=!1,l=3,h=0){return new s(e,t,i,n,5,r,o,a,l,h)}}},4246:(e,t,i)=>{i.d(t,{_:()=>u});var n=i(5757),s=i(4141),r=i(2262),o=i(727),a=i(4221),l=(i(7246),i(6697),i(7814)),h=i(5860),c=i(2286);class u extends r.x{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=(0,h.M)(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e<i.length;++e)for(let n=0;n<this._renderPassIds.length;++n)i[e].setMaterialForRenderPass(this._renderPassIds[n],void 0!==t?Array.isArray(t)?t[n]:t:void 0)}get isMulti(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e.isMulti)&&void 0!==t&&t}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e._depthStencilTexture)&&void 0!==t?t:null}constructor(e,t,i,o=!1,l=!0,h=0,c=!1,u=r.x.TRILINEAR_SAMPLINGMODE,d=!0,p=!1,f=!1,_=5,m=!1,g,v,y=!1,x=!1){var b,T,S,E,C,A;let P;if("object"==typeof o){const e=o;o=!!e.generateMipMaps,l=null===(b=e.doNotChangeAspectRatio)||void 0===b||b,h=null!==(T=e.type)&&void 0!==T?T:0,c=!!e.isCube,u=null!==(S=e.samplingMode)&&void 0!==S?S:r.x.TRILINEAR_SAMPLINGMODE,d=null===(E=e.generateDepthBuffer)||void 0===E||E,p=!!e.generateStencilBuffer,f=!!e.isMulti,_=null!==(C=e.format)&&void 0!==C?C:5,m=!!e.delayAllocation,g=e.samples,v=e.creationFlags,y=!!e.noColorAttachment,x=!!e.useSRGBBuffer,P=e.colorAttachment}if(super(null,i,!o,void 0,u,void 0,void 0,void 0,void 0,_),this._unObserveRenderList=null,this._renderListHasChanged=(e,t)=>{var i;const n=this._renderList?this._renderList.length:0;(0===t&&n>0||0===n)&&(null===(i=this.getScene())||void 0===i||i.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()})))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new n.y$,this.onAfterUnbindObservable=new n.y$,this.onBeforeRenderObservable=new n.y$,this.onAfterRenderObservable=new n.y$,this.onClearObservable=new n.y$,this.onResizeObservable=new n.y$,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=s.P.Zero(),!(i=this.getScene()))return;const R=this.getScene().getEngine();this._coordinatesMode=r.x.PROJECTION_MODE,this.renderList=new Array,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=c,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=R.onResizeObservable.add((()=>{})),this._generateMipMaps=!!o,this._doNotChangeAspectRatio=l,this._renderingManager=new a.$(i),this._renderingManager._useSceneAutoClearSetup=!0,f||(this._renderTargetOptions={generateMipMaps:o,type:h,format:null!==(A=this._format)&&void 0!==A?A:void 0,samplingMode:this.samplingMode,generateDepthBuffer:d,generateStencilBuffer:p,samples:g,creationFlags:v,noColorAttachment:y,useSRGBBuffer:x,colorAttachment:P,label:this.name},this.samplingMode===r.x.NEAREST_SAMPLINGMODE&&(this.wrapU=r.x.CLAMP_ADDRESSMODE,this.wrapV=r.x.CLAMP_ADDRESSMODE),m||(c?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=r.x.INVCUBIC_MODE,this._textureMatrix=s.y3.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==g&&(this.samples=g)))}createDepthStencilTexture(e=0,t=!0,i=!1,n=1,s=14){var r;null===(r=this._renderTarget)||void 0===r||r.createDepthStencilTexture(e,t,i,n,s)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t<this._renderPassIds.length;++t)e.releaseRenderPassId(this._renderPassIds[t])}this._renderPassIds=[]}_createRenderPassId(){this._releaseRenderPassId();const e=this._scene.getEngine(),t=this._isCubeData?6:this.getRenderLayers()||1;for(let i=0;i<t;++i)this._renderPassIds[i]=e.createRenderPassId(`RenderTargetTexture - ${this.name}#${i}`)}_processSizeParameter(e){if(e.ratio){this._sizeRatio=e.ratio;const t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e;this._createRenderPassId()}get samples(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e.samples)&&void 0!==t?t:this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}addPostProcess(e){if(!this._postProcessManager){const e=this.getScene();if(!e)return;this._postProcessManager=new o.O(e),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(const e of this._postProcesses)e.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){return this._size.layers||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var t;const i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;const n=this.getScene();n&&(this._processSizeParameter(e),this._renderTarget=i?n.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):n.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){var n;const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let e=0;e<this._waitingRenderList.length;e++){const t=this._waitingRenderList[e],i=s.getMeshById(t);i&&this.renderList.push(i)}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];const e=this.getScene();if(!e)return i;const t=e.meshes;for(let e=0;e<t.length;e++){const i=t[e];this.renderListPredicate(i)&&this.renderList.push(i)}}const o=r.currentRenderPassId;this.onBeforeBindObservable.notifyObservers(this);const a=null!==(n=this.activeCamera)&&void 0!==n?n:s.activeCamera,l=s.activeCamera;a&&(a!==s.activeCamera&&(s.setTransformMatrix(a.getViewMatrix(),a.getProjectionMatrix(!0)),s.activeCamera=a),r.setViewport(a.rigParent?a.rigParent.viewport:a.viewport,this.getRenderWidth(),this.getRenderHeight())),this._defaultRenderListPrepared=!1;let h=i;if(i){s.getViewMatrix()||s.updateTransformMatrix();const e=this.is2DArray?this.getRenderLayers():this.isCube?6:1;for(let t=0;t<e&&h;t++){let e=null;const n=this.renderList?this.renderList:s.getActiveMeshes().data,o=this.renderList?this.renderList.length:s.getActiveMeshes().length;r.currentRenderPassId=this._renderPassIds[t],this.onBeforeRenderObservable.notifyObservers(t),this.getCustomRenderList&&(e=this.getCustomRenderList(t,n,o)),e||(e=n),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0);for(let t=0;t<e.length&&h;++t){const n=e[t];if(n.isEnabled()&&!n.isBlocked&&n.isVisible&&n.subMeshes)if(this.customIsReadyFunction){if(!this.customIsReadyFunction(n,this.refreshRate,i)){h=!1;continue}}else if(!n.isReady(!0)){h=!1;continue}}this.onAfterRenderObservable.notifyObservers(t),(this.is2DArray||this.isCube)&&(s.incrementRenderId(),s.resetCachedMaterial())}}else if(this.is2DArray&&!this.isMulti)for(let i=0;i<this.getRenderLayers();i++)this._renderToTarget(0,e,t,i,a),s.incrementRenderId(),s.resetCachedMaterial();else if(this.isCube&&!this.isMulti)for(let i=0;i<6;i++)this._renderToTarget(i,e,t,void 0,a),s.incrementRenderId(),s.resetCachedMaterial();else this._renderToTarget(0,e,t,void 0,a);return this.onAfterUnbindObservable.notifyObservers(this),r.currentRenderPassId=o,l&&(s.activeCamera=l,(s.getEngine().scenes.length>1||this.activeCamera&&this.activeCamera!==s.activeCamera)&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),r.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){const i=e*t,n=l.D.NearestPOT(i+16384/(128+i));return Math.min(l.D.FloorPOT(e),n)}_prepareRenderingManager(e,t,i,n){const s=this.getScene();if(!s)return;this._renderingManager.reset();const r=s.getRenderId();for(let o=0;o<t;o++){const t=e[o];if(t&&!t.isBlocked){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(t,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!t.isReady(0===this.refreshRate)){this.resetRefreshCounter();continue}if(!t._internalAbstractMeshDataInfo._currentLODIsUpToDate&&s.activeCamera&&(t._internalAbstractMeshDataInfo._currentLOD=s.customLODSelector?s.customLODSelector(t,this.activeCamera||s.activeCamera):t.getLOD(this.activeCamera||s.activeCamera),t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0),!t._internalAbstractMeshDataInfo._currentLOD)continue;let e,o=t._internalAbstractMeshDataInfo._currentLOD;if(o._preActivateForIntermediateRendering(r),e=!(!n||!i)&&0==(t.layerMask&i.layerMask),t.isEnabled()&&t.isVisible&&t.subMeshes&&!e&&(o!==t&&o._activate(r,!0),t._activate(r,!0)&&t.subMeshes.length)){t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(o=t):o._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,o._internalAbstractMeshDataInfo._isActiveIntermediate=!0;for(let e=0;e<o.subMeshes.length;e++){const t=o.subMeshes[e];this._renderingManager.dispatch(t,o)}}}}for(let e=0;e<s.particleSystems.length;e++){const t=s.particleSystems[e],i=t.emitter;t.isStarted()&&i&&(!i.position||i.isEnabled())&&this._renderingManager.dispatchParticles(t)}}_bindFrameBuffer(e=0,t=0){const i=this.getScene();if(!i)return;const n=i.getEngine();this._renderTarget&&n.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,(()=>{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,n){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):n&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,n=0,s=null){var r,o,a,l,h,u;const d=this.getScene();if(!d)return;const p=d.getEngine();if(null===(r=p._debugPushGroup)||void 0===r||r.call(p,`render to face #${e} layer #${n}`,1),this._prepareFrame(d,e,n,t),this.is2DArray?(p.currentRenderPassId=this._renderPassIds[n],this.onBeforeRenderObservable.notifyObservers(n)):(p.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),p.snapshotRendering&&1===p.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(p):this.skipInitialClear||p.clear(this.clearColor||d.clearColor,!0,!0,!0);else{let r=null;const u=this.renderList?this.renderList:d.getActiveMeshes().data,f=this.renderList?this.renderList.length:d.getActiveMeshes().length;this.getCustomRenderList&&(r=this.getCustomRenderList(this.is2DArray?n:e,u,f)),r?this._prepareRenderingManager(r,r.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(u,f,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),r=u);for(const t of d._beforeRenderTargetClearStage)t.action(this,e,n);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(p):this.skipInitialClear||p.clear(this.clearColor||d.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0);for(const t of d._beforeRenderTargetDrawStage)t.action(this,e,n);this._renderingManager.render(this.customRenderFunction,r,this.renderParticles,this.renderSprites);for(const t of d._afterRenderTargetDrawStage)t.action(this,e,n);const _=null!==(a=null===(o=this._texture)||void 0===o?void 0:o.generateMipMaps)&&void 0!==a&&a;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,null!==(l=this._renderTarget)&&void 0!==l?l:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&d.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e);for(const t of d._afterRenderTargetPostProcessStage)t.action(this,e,n);this._texture&&(this._texture.generateMipMaps=_),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0),i&&c.B.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),p)}this._unbindFrameBuffer(p,e),this._texture&&this.isCube&&5===e&&p.generateMipMapsForCubemap(this._texture),null===(u=p._debugPopGroup)||void 0===u||u.call(p,1)}setRenderingOrder(e,t=null,i=null,n=null){this._renderingManager.setRenderingOrder(e,t,i,n)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new u(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t<this.renderList.length;t++)e.renderList.push(this.renderList[t].id);return e}disposeFramebufferObjects(){var e;null===(e=this._renderTarget)||void 0===e||e.dispose(!0)}releaseInternalTexture(){var e;null===(e=this._renderTarget)||void 0===e||e.releaseTextures(),this._texture=null}dispose(){var e;this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterRenderObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this.onBeforeRenderObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._releaseRenderPassId(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.renderList=null;const t=this.getScene();if(!t)return;let i=t.customRenderTargets.indexOf(this);i>=0&&t.customRenderTargets.splice(i,1);for(const e of t.cameras)i=e.customRenderTargets.indexOf(this),i>=0&&e.customRenderTargets.splice(i,1);null===(e=this._renderTarget)||void 0===e||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===u.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=u.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}u.REFRESHRATE_RENDER_ONCE=0,u.REFRESHRATE_RENDER_ONEVERYFRAME=1,u.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,r.x._CreateRenderTargetTexture=(e,t,i,n,s)=>new u(e,t,i,n)},2262:(e,t,i)=>{i.d(t,{x:()=>m});var n=i(9472),s=i(3956),r=i(5757),o=i(4141),a=i(6702),l=i(2208),h=i(4934),c=i(6290),u=i(8126),d=i(142),p=i(2655),f=i(9703),_=i(4892);class m extends a.V{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,n,s=m.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=null,h=!1,u,d,p,f,g){var v,y,x,b,T,S,E,C,A;let P;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 r.y$,this._isBlocking=!0,this.name=e||"",this.url=e;let R=!1,M=null;"object"==typeof i&&null!==i?(P=null!==(v=i.noMipmap)&&void 0!==v&&v,n=null!==(y=i.invertY)&&void 0!==y?y:!_.e.UseOpenGLOrientationForUV,s=null!==(x=i.samplingMode)&&void 0!==x?x:m.TRILINEAR_SAMPLINGMODE,o=null!==(b=i.onLoad)&&void 0!==b?b:null,a=null!==(T=i.onError)&&void 0!==T?T:null,l=null!==(S=i.buffer)&&void 0!==S?S:null,h=null!==(E=i.deleteBuffer)&&void 0!==E&&E,u=i.format,d=i.mimeType,p=i.loaderOptions,f=i.creationFlags,R=null!==(C=i.useSRGBBuffer)&&void 0!==C&&C,M=null!==(A=i.internalTexture)&&void 0!==A?A:null):P=!!i,this._noMipmap=P,this._invertY=void 0===n?!_.e.UseOpenGLOrientationForUV:n,this._initialSamplingMode=s,this._buffer=l,this._deleteBuffer=h,this._mimeType=d,this._loaderOptions=p,this._creationFlags=f,this._useSRGBBuffer=R,this._forcedExtension=g,u&&(this._format=u);const I=this.getScene(),D=this._getEngine();if(!D)return;D.onBeforeTextureInitObservable.notifyObservers(this);const O=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),o&&o(),!this.isBlocking&&I&&I.resetCachedMaterial()},w=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),m.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!M)return this._delayedOnLoad=O,void(this._delayedOnError=w);if(this._texture=null!=M?M:this._getFromCache(this.url,P,s,this._invertY,R),this._texture)if(this._texture.isReady)c.Q.SetImmediate((()=>O()));else{const e=this._texture.onLoadedObservable.add(O);this._texture.onErrorObservable.add((t=>{var i;w(t.message,t.exception),null===(i=this._texture)||void 0===i||i.onLoadedObservable.remove(e)}))}else if(I&&I.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=O,this._delayedOnError=w;else{try{this._texture=D.createTexture(this.url,P,this._invertY,I,s,O,w,this._buffer,void 0,this._format,this._forcedExtension,d,p,f,R)}catch(e){throw w("error loading",e),e}h&&(this._buffer=null)}}updateURL(e,t=null,i,n){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1)),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=n,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer),this._texture?this._delayedOnLoad&&(this._texture.isReady?c.Q.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,n){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,o.P.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,n),n.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,n.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,n.z+=this.wRotationCenter}checkTransformsAreIdentical(e){return null!==e&&this.uOffset===e.uOffset&&this.vOffset===e.vOffset&&this.uScale===e.uScale&&this.vScale===e.vScale&&this.uAng===e.uAng&&this.vAng===e.vAng&&this.wAng===e.wAng}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=o.y3.Zero(),this._rowGenerationMatrix=new o.y3,this._t0=o.P.Zero(),this._t1=o.P.Zero(),this._t2=o.P.Zero()),o.y3.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(o.y3.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,o.jp.Matrix[0]),o.y3.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,o.jp.Matrix[1]),o.y3.ScalingToRef(this._cachedUScale,this._cachedVScale,0,o.jp.Matrix[2]),o.y3.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,o.jp.Matrix[3]),o.jp.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.jp.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.jp.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.jp.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),o.y3.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();return t?(this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedTextureMatrix):this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode){if(this.coordinatesMode!==m.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=o.y3.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=o.y3.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 m.PLANAR_MODE:o.y3.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 m.PROJECTION_MODE:{o.y3.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:o.y3.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this))),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return s.p4.Clone((()=>new m(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){var e,t;const i=this.name;m.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const n=super.serialize(m._SerializeInternalTextureUniqueId);return n?((m.SerializeBuffers||m.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(n.base64String=this._buffer,n.name=n.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?n.base64String="data:image/png;base64,"+(0,p.Gh)(this._buffer):(m.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(n.base64String=!this._engine||this._engine._features.supportSyncTextureRead?(0,f._u)(this):(0,f.Jj)(this))),n.invertY=this._invertY,n.samplingMode=this.samplingMode,n._creationFlags=this._creationFlags,n._useSRGBBuffer=this._useSRGBBuffer,m._SerializeInternalTextureUniqueId&&(n.internalTextureUniqueId=null!==(t=null===(e=this._texture)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:void 0),this.name=i,n):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const n=u.K.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&n.updateSamplingMode&&n._samplingMode&&n._samplingMode!==e.samplingMode&&n.updateSamplingMode(e.samplingMode),n}if(e.isCube&&!e.isRenderTarget)return m._CubeTextureParser(e,t,i);const n=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!n)return null;let r;if(n){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const o=t=>{var i;if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i<e.animations.length;i++){const n=e.animations[i],s=(0,l.q)("BABYLON.Animation");s&&t.animations.push(s.Parse(n))}n&&!r&&(null===(i=null==t?void 0:t._texture)||void 0===i||i._setUniqueId(e.internalTextureUniqueId))};return s.p4.Parse((()=>{var n,s,a;let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){const i=m._CreateMirror(e.name,e.renderTargetSize,t,l);return i._waitingRenderList=e.renderList,i.mirrorPlane=d.J.FromArray(e.mirrorPlane),o(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i<t.reflectionProbes.length;i++){const n=t.reflectionProbes[i];if(n.name===e.name)return n.cubeTexture}}else i=m._CreateRenderTargetTexture(e.name,e.renderTargetSize,t,l,null!==(n=e._creationFlags)&&void 0!==n?n:0),i._waitingRenderList=e.renderList;return o(i),i}{let n;if(e.base64String&&!r)n=m.CreateFromBase64String(e.base64String,e.base64String,t,!l,e.invertY,e.samplingMode,(()=>{o(n)}),null!==(s=e._creationFlags)&&void 0!==s?s:0,null!==(a=e._useSRGBBuffer)&&void 0!==a&&a),n.name=e.name;else{let s;s=e.name&&e.name.indexOf("://")>0?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||m.UseSerializedUrlIfAny)&&(s=e.url);const a={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{o(n)},internalTexture:r};n=new m(s,t,a)}return n}}),e,t)}static CreateFromBase64String(e,t,i,n,s,r=m.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=5,h){return new m("data:"+t,i,n,s,r,o,a,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,n=!1,s,r=!0,o=m.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c){return"data:"!==e.substr(0,5)&&(e="data:"+e),new m(e,i,s,r,o,a,l,t,n,h,void 0,void 0,c)}}m.SerializeBuffers=!0,m.ForceSerializeBuffers=!1,m.OnTextureLoadErrorObservable=new r.y$,m._SerializeInternalTextureUniqueId=!1,m._CubeTextureParser=(e,t,i)=>{throw(0,h.S)("CubeTexture")},m._CreateMirror=(e,t,i,n)=>{throw(0,h.S)("MirrorTexture")},m._CreateRenderTargetTexture=(e,t,i,n,s)=>{throw(0,h.S)("RenderTargetTexture")},m.NEAREST_SAMPLINGMODE=1,m.NEAREST_NEAREST_MIPLINEAR=8,m.BILINEAR_SAMPLINGMODE=2,m.LINEAR_LINEAR_MIPNEAREST=11,m.TRILINEAR_SAMPLINGMODE=3,m.LINEAR_LINEAR_MIPLINEAR=3,m.NEAREST_NEAREST_MIPNEAREST=4,m.NEAREST_LINEAR_MIPNEAREST=5,m.NEAREST_LINEAR_MIPLINEAR=6,m.NEAREST_LINEAR=7,m.NEAREST_NEAREST=1,m.LINEAR_NEAREST_MIPNEAREST=9,m.LINEAR_NEAREST_MIPLINEAR=10,m.LINEAR_LINEAR=2,m.LINEAR_NEAREST=12,m.EXPLICIT_MODE=0,m.SPHERICAL_MODE=1,m.PLANAR_MODE=2,m.CUBIC_MODE=3,m.PROJECTION_MODE=4,m.SKYBOX_MODE=5,m.INVCUBIC_MODE=6,m.EQUIRECTANGULAR_MODE=7,m.FIXED_EQUIRECTANGULAR_MODE=8,m.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,m.CLAMP_ADDRESSMODE=0,m.WRAP_ADDRESSMODE=1,m.MIRROR_ADDRESSMODE=2,m.UseSerializedUrlIfAny=!1,(0,n.gn)([(0,s.qC)()],m.prototype,"url",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"uOffset",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"vOffset",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"uScale",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"vScale",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"uAng",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"vAng",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"wAng",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"uRotationCenter",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"vRotationCenter",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"wRotationCenter",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"homogeneousRotationInUVTransform",void 0),(0,n.gn)([(0,s.qC)()],m.prototype,"isBlocking",null),(0,l.H)("BABYLON.Texture",m),s.p4._TextureParser=m.Parse},3297:(e,t,i)=>{i.d(t,{a:()=>n});class n{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,n=1,s=2,r=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=n,this.samplingMode=s,this._comparisonFunction=r,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}},2035:(e,t,i)=>{i.d(t,{g:()=>s});var n=i(9697);class s{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}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==(null==e?void 0:e._shareDepth)}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=n.$.Zero(),this._cachedBaseSize=n.$.Zero(),this._initialSamplingMode=2,this._texture=s._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}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._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):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,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)}}},99:(e,t,i)=>{function n(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function s(e,t,i){var n,s,r,o,a,l;const h=!!(null!==(n=e.clipPlane)&&void 0!==n?n:t.clipPlane),c=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),u=!!(null!==(r=e.clipPlane3)&&void 0!==r?r:t.clipPlane3),d=!!(null!==(o=e.clipPlane4)&&void 0!==o?o:t.clipPlane4),p=!!(null!==(a=e.clipPlane5)&&void 0!==a?a:t.clipPlane5),f=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);h&&i.push("#define CLIPPLANE"),c&&i.push("#define CLIPPLANE2"),u&&i.push("#define CLIPPLANE3"),d&&i.push("#define CLIPPLANE4"),p&&i.push("#define CLIPPLANE5"),f&&i.push("#define CLIPPLANE6")}function r(e,t,i){var n,s,r,o,a,l;let h=!1;const c=!!(null!==(n=e.clipPlane)&&void 0!==n?n:t.clipPlane),u=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),d=!!(null!==(r=e.clipPlane3)&&void 0!==r?r:t.clipPlane3),p=!!(null!==(o=e.clipPlane4)&&void 0!==o?o:t.clipPlane4),f=!!(null!==(a=e.clipPlane5)&&void 0!==a?a:t.clipPlane5),_=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);return i.CLIPPLANE!==c&&(i.CLIPPLANE=c,h=!0),i.CLIPPLANE2!==u&&(i.CLIPPLANE2=u,h=!0),i.CLIPPLANE3!==d&&(i.CLIPPLANE3=d,h=!0),i.CLIPPLANE4!==p&&(i.CLIPPLANE4=p,h=!0),i.CLIPPLANE5!==f&&(i.CLIPPLANE5=f,h=!0),i.CLIPPLANE6!==_&&(i.CLIPPLANE6=_,h=!0),h}function o(e,t,i){var n,s,r,o,l,h;let c=null!==(n=t.clipPlane)&&void 0!==n?n:i.clipPlane;a(e,"vClipPlane",c),c=null!==(s=t.clipPlane2)&&void 0!==s?s:i.clipPlane2,a(e,"vClipPlane2",c),c=null!==(r=t.clipPlane3)&&void 0!==r?r:i.clipPlane3,a(e,"vClipPlane3",c),c=null!==(o=t.clipPlane4)&&void 0!==o?o:i.clipPlane4,a(e,"vClipPlane4",c),c=null!==(l=t.clipPlane5)&&void 0!==l?l:i.clipPlane5,a(e,"vClipPlane5",c),c=null!==(h=t.clipPlane6)&&void 0!==h?h:i.clipPlane6,a(e,"vClipPlane6",c)}function a(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}i.d(t,{AN:()=>r,an:()=>o,lK:()=>s,qx:()=>n})},8237:(e,t,i)=>{i.d(t,{U:()=>o});var n=i(9472),s=i(3956),r=i(4649);class o{constructor(){this._dirty=!0,this._tempColor=new r.HE(0,0,0,0),this._globalCurve=new r.HE(0,0,0,0),this._highlightsCurve=new r.HE(0,0,0,0),this._midtonesCurve=new r.HE(0,0,0,0),this._shadowsCurve=new r.HE(0,0,0,0),this._positiveCurve=new r.HE(0,0,0,0),this._negativeCurve=new r.HE(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",n="vCameraColorCurveNeutral",s="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(n,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}static PrepareUniforms(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}_getColorGradingDataToRef(e,t,i,n,s){null!=e&&(e=o._Clamp(e,0,360),t=o._Clamp(t,-100,100),i=o._Clamp(i,-100,100),n=o._Clamp(n,-100,100),t=o._ApplyColorGradingSliderNonlinear(t),t*=.5,n=o._ApplyColorGradingSliderNonlinear(n),t<0&&(t*=-1,e=(e+180)%360),o._FromHSBToRef(e,t,50+.25*n,s),s.scaleToRef(2,s),s.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,n){let s=o._Clamp(e,0,360);const r=o._Clamp(t/100,0,1),a=o._Clamp(i/100,0,1);if(0===r)n.r=a,n.g=a,n.b=a;else{s/=60;const e=Math.floor(s),t=s-e,i=a*(1-r),o=a*(1-r*t),l=a*(1-r*(1-t));switch(e){case 0:n.r=a,n.g=l,n.b=i;break;case 1:n.r=o,n.g=a,n.b=i;break;case 2:n.r=i,n.g=a,n.b=l;break;case 3:n.r=i,n.g=o,n.b=a;break;case 4:n.r=l,n.g=i,n.b=a;break;default:n.r=a,n.g=i,n.b=o}}n.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return s.p4.Clone((()=>new o),this)}serialize(){return s.p4.Serialize(this)}static Parse(e){return s.p4.Parse((()=>new o),e,null,null)}}(0,n.gn)([(0,s.qC)()],o.prototype,"_globalHue",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_globalDensity",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_globalSaturation",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_globalExposure",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsHue",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsDensity",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsSaturation",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsExposure",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesHue",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesDensity",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesSaturation",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesExposure",void 0),s.p4._ColorCurvesParser=o.Parse},1345:(e,t,i)=>{i.d(t,{q:()=>n});class n{static IsWrapper(e){return void 0===e.getPipelineContext}static GetEffect(e){return void 0===e.getPipelineContext?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 n;this.effect=e,void 0!==t&&(this.defines=t),i&&(null===(n=this.drawContext)||void 0===n||n.reset())}dispose(){var e;null===(e=this.drawContext)||void 0===e||e.dispose()}}},1979:(e,t,i)=>{i.d(t,{Q:()=>h});var n=i(5757),s=i(6797),r=i(2722),o=i(8198),a=i(8104),l=i(9131);class h{static get ShadersRepository(){return a.v.ShadersRepository}static set ShadersRepository(e){a.v.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new n.y$),this._onBindObservable}constructor(e,t,i,r=null,c,u=null,d=null,p=null,f=null,_,m="",g=l.x.GLSL){var v,y,x;let b;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new n.y$,this.onErrorObservable=new n.y$,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!1,this._wasPreviouslyUsingInstances=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this.name=e,this._key=m;let T,S,E=null;if(t.attributes){const e=t;if(this._engine=i,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=null!==(v=e.shaderLanguage)&&void 0!==v?v:l.x.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t<e.uniformBuffersNames.length;t++)this._uniformBuffersNames[e.uniformBuffersNames[t]]=t}E=null!==(y=e.processFinalCode)&&void 0!==y?y:null,b=null!==(x=e.processCodeAfterIncludes)&&void 0!==x?x:void 0}else this._engine=c,this.defines=null==u?"":u,this._uniformsNames=i.concat(r),this._samplerList=r?r.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=g,this.onError=f,this.onCompiled=p,this._indexParameters=_,this._fallbacks=d;this._attributeLocationByName={},this.uniqueId=h._UniqueIdSeed++;const C=(0,s.CG)()?this._engine.getHostDocument():null;e.vertexSource?T="source:"+e.vertexSource:e.vertexElement?(T=C?C.getElementById(e.vertexElement):null,T||(T=e.vertexElement)):T=e.vertex||e,e.fragmentSource?S="source:"+e.fragmentSource:e.fragmentElement?(S=C?C.getElementById(e.fragmentElement):null,S||(S=e.fragmentElement)):S=e.fragment||e,this._processingContext=this._engine._getShaderProcessingContext(this._shaderLanguage);let A={defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:a.v.GetShadersRepository(this._shaderLanguage),includesShadersStore:a.v.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:b};const P=[void 0,void 0],R=()=>{if(P[0]&&P[1]){A.isFragment=!0;const[t,i]=P;o.L.Process(i,A,((i,n)=>{this._fragmentSourceCodeBeforeMigration=n,E&&(i=E("fragment",i));const s=o.L.Finalize(t,i,A);A=null,this._useFinalCode(s.vertexCode,s.fragmentCode,e)}),this._engine)}};this._loadShader(T,"Vertex","",(e=>{o.L.Initialize(A),o.L.Process(e,A,((t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,E&&(t=E("vertex",t)),P[0]=t,R()}),this._engine)})),this._loadShader(S,"Fragment","Pixel",(e=>{this._rawFragmentSourceCode=e,P[1]=e,R()}))}_useFinalCode(e,t,i){if(i){const n=i.vertexElement||i.vertex||i.spectorName||i,s=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===l.x.WGSL?"//":"")+"#define SHADER_NAME vertex:"+n+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===l.x.WGSL?"//":"")+"#define SHADER_NAME fragment:"+s+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void n((0,s.v)(e));if("source:"===e.substr(0,7))return void n(e.substr(7));if("base64:"===e.substr(0,7))return void n(window.atob(e.substr(7)));const r=a.v.GetShadersStore(this._shaderLanguage);if(r[e+t+"Shader"])return void n(r[e+t+"Shader"]);if(i&&r[e+i+"Shader"])return void n(r[e+i+"Shader"]);let o;o="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:a.v.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(o+"."+t.toLowerCase()+".fx",n)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getVertexShaderCode())&&void 0!==t?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getFragmentShaderCode())&&void 0!==t?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,n){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{n&&n(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;t<e.length;t++)e[t].markAllMaterialsAsDirty(63);this._pipelineContext._handlesSpectorRebuildCallback(i)},this._fallbacks=null,this._prepareEffect()}_prepareEffect(){const e=this._attributesNames,t=this.defines,i=this._pipelineContext;this._isReady=!1;try{const n=this._engine;this._pipelineContext=n.createPipelineContext(this._processingContext),this._pipelineContext._name=this._key;const s=this._rebuildProgram.bind(this);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?n._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,s,null,this._transformFeedbackVaryings,this._key):n._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,s,t,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,e,this._attributes),e)for(let t=0;t<e.length;t++){const i=e[t];this._attributeLocationByName[i]=this._attributes[t]}n.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh(),i&&this.getEngine()._deletePipelineContext(i)})),this._pipelineContext.isAsync&&this._checkIsReady(i)}catch(e){this._processCompilationErrors(e,i)}}_getShaderCodeAndErrorLine(e,t,i){const n=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let s=null;if(t&&e){const r=t.match(n);if(r&&2===r.length){const t=parseInt(r[1]),n=e.split("\n",-1);n.length>=t&&(s=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${n[t-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){var i,n,s;this._compilationError=e.message;const o=this._attributesNames,a=this._fallbacks;if(r.Y.Error("Unable to compile effect:"),r.Y.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),r.Y.Error("Attributes: "+o.map((function(e){return" "+e}))),r.Y.Error("Defines:\r\n"+this.defines),h.LogShaderCodeOnCompilationError){let e=null,t=null,o=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([o,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),o&&(r.Y.Error("Vertex code:"),r.Y.Error(o))),(null===(n=this._pipelineContext)||void 0===n?void 0:n._getFragmentShaderCode())&&([o,t]=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0),o&&(r.Y.Error("Fragment code:"),r.Y.Error(o))),e&&r.Y.Error(e),t&&r.Y.Error(t)}r.Y.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,r.Y.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(-1===this._samplerList.indexOf(i+"0")){const n=this._samplerList.indexOf(e);for(let e=1;e<t.length;e++){const t=i+(e-1).toString();this._samplerList.splice(n+e,0,t)}let s=0;for(const e of this._samplerList)this._samplers[e]=s,s+=1}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)}setTextureFromPostProcess(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)}setTextureFromPostProcessOutput(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)}bindUniformBuffer(e,t){const i=this._uniformBuffersNames[t];void 0===i||h._BaseCache[i]===e&&this._engine._features.useUBOBindingCache||(h._BaseCache[i]=e,this._engine.bindUniformBufferBase(e,i,t))}bindUniformBlock(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)}setInt(e,t){return this._pipelineContext.setInt(e,t),this}setInt2(e,t,i){return this._pipelineContext.setInt2(e,t,i),this}setInt3(e,t,i,n){return this._pipelineContext.setInt3(e,t,i,n),this}setInt4(e,t,i,n,s){return this._pipelineContext.setInt4(e,t,i,n,s),this}setIntArray(e,t){return this._pipelineContext.setIntArray(e,t),this}setIntArray2(e,t){return this._pipelineContext.setIntArray2(e,t),this}setIntArray3(e,t){return this._pipelineContext.setIntArray3(e,t),this}setIntArray4(e,t){return this._pipelineContext.setIntArray4(e,t),this}setUInt(e,t){return this._pipelineContext.setInt(e,t),this}setUInt2(e,t,i){return this._pipelineContext.setInt2(e,t,i),this}setUInt3(e,t,i,n){return this._pipelineContext.setInt3(e,t,i,n),this}setUInt4(e,t,i,n,s){return this._pipelineContext.setInt4(e,t,i,n,s),this}setUIntArray(e,t){return this._pipelineContext.setUIntArray(e,t),this}setUIntArray2(e,t){return this._pipelineContext.setUIntArray2(e,t),this}setUIntArray3(e,t){return this._pipelineContext.setUIntArray3(e,t),this}setUIntArray4(e,t){return this._pipelineContext.setUIntArray4(e,t),this}setFloatArray(e,t){return this._pipelineContext.setArray(e,t),this}setFloatArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setFloatArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setFloatArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setArray(e,t){return this._pipelineContext.setArray(e,t),this}setArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setMatrices(e,t){return this._pipelineContext.setMatrices(e,t),this}setMatrix(e,t){return this._pipelineContext.setMatrix(e,t),this}setMatrix3x3(e,t){return this._pipelineContext.setMatrix3x3(e,t),this}setMatrix2x2(e,t){return this._pipelineContext.setMatrix2x2(e,t),this}setFloat(e,t){return this._pipelineContext.setFloat(e,t),this}setBool(e,t){return this._pipelineContext.setInt(e,t?1:0),this}setVector2(e,t){return this._pipelineContext.setVector2(e,t),this}setFloat2(e,t,i){return this._pipelineContext.setFloat2(e,t,i),this}setVector3(e,t){return this._pipelineContext.setVector3(e,t),this}setFloat3(e,t,i,n){return this._pipelineContext.setFloat3(e,t,i,n),this}setVector4(e,t){return this._pipelineContext.setVector4(e,t),this}setQuaternion(e,t){return this._pipelineContext.setQuaternion(e,t),this}setFloat4(e,t,i,n,s){return this._pipelineContext.setFloat4(e,t,i,n,s),this}setColor3(e,t){return this._pipelineContext.setColor3(e,t),this}setColor4(e,t,i){return this._pipelineContext.setColor4(e,t,i),this}setDirectColor4(e,t){return this._pipelineContext.setDirectColor4(e,t),this}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseEffect(this),this._isDisposed=!0}static RegisterShader(e,t,i,n=l.x.GLSL){t&&(a.v.GetShadersStore(n)[`${e}PixelShader`]=t),i&&(a.v.GetShadersStore(n)[`${e}VertexShader`]=i)}static ResetCache(){h._BaseCache={}}}h.LogShaderCodeOnCompilationError=!0,h._UniqueIdSeed=0,h._BaseCache={},h.ShadersStore=a.v.ShadersStore,h.IncludesShadersStore=a.v.IncludesShadersStore},1434:(e,t,i)=>{i.d(t,{L:()=>n});class n{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e<i.meshes.length;e++){const n=i.meshes[e];if(n.material){if(n.computeBonesUsingShaders&&0!==n.numBoneInfluencers)if(n.material.getEffect()===t)n.computeBonesUsingShaders=!1;else if(n.subMeshes)for(const e of n.subMeshes)if(e.effect===t){n.computeBonesUsingShaders=!1;break}}else!this._mesh.material&&n.computeBonesUsingShaders&&n.numBoneInfluencers>0&&(n.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i<t.length;i++)e=e.replace("#define "+t[i],"");this._currentRank++}return e}}},7218:(e,t,i)=>{i.d(t,{H:()=>c,I:()=>h});var n=i(708),s=i(4538),r=i(5757),o=i(1979),a=i(1345);i(8793);const l={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class h{constructor(e,t=l){var i,r;this._fullscreenViewport=new s.l(0,0,1,1);const o=null!==(i=t.positions)&&void 0!==i?i:l.positions,a=null!==(r=t.indices)&&void 0!==r?r:l.indices;this.engine=e,this._vertexBuffers={[n.o.PositionKind]:new n.o(e,o,n.o.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(a),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(a);for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild()}))}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}restoreStates(){this.engine.depthCullingState.depthTest=!0,this.engine.stencilState.stencilTest=!0}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.setViewport();const i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[n.o.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[n.o.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class c{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new r.y$;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 n=e.defines?e.defines.join("\n"):"";this._drawWrapper=new a.q(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,n,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new o.Q(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,n,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()}}},4475:(e,t,i)=>{i.d(t,{$:()=>u,b:()=>c});var n=i(9472),s=i(3956),r=i(5757),o=i(7257),a=i(4649),l=i(1917),h=i(8237);class c extends l.H{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 u{constructor(){this.colorCurves=new h.U,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=u.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new a.HE(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=u.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new r.y$}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&&h.U.PrepareUniforms(e),t.DITHER&&e.push("ditherIntensity")}static PrepareSamplers(e,t){t.COLORGRADING&&e.push("txColorTransform")}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled)return e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===u._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType===u.TONEMAPPING_ACES?e.TONEMAPPING_ACES=!0:e.TONEMAPPING_ACES=!1,e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&h.U.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),n=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,n),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const s=null!=t?t:n/i;let r=Math.tan(.5*this.vignetteCameraFov),a=r*s;const l=Math.sqrt(a*r);a=o.w1.Mix(a,l,this.vignetteStretch),r=o.w1.Mix(r,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,r,-a*this.vignetteCenterX,-r*this.vignetteCenterY);const h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return s.p4.Clone((()=>new u),this)}serialize(){return s.p4.Serialize(this)}static Parse(e){const t=s.p4.Parse((()=>new u),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}u.TONEMAPPING_STANDARD=0,u.TONEMAPPING_ACES=1,u._VIGNETTEMODE_MULTIPLY=0,u._VIGNETTEMODE_OPAQUE=1,(0,n.gn)([(0,s.N$)()],u.prototype,"colorCurves",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_colorCurvesEnabled",void 0),(0,n.gn)([(0,s.oU)("colorGradingTexture")],u.prototype,"_colorGradingTexture",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_colorGradingEnabled",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_colorGradingWithGreenDepth",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_colorGradingBGR",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_exposure",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_toneMappingEnabled",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_toneMappingType",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_contrast",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"vignetteStretch",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"vignetteCenterX",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"vignetteCenterY",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"vignetteWeight",void 0),(0,n.gn)([(0,s.XX)()],u.prototype,"vignetteColor",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"vignetteCameraFov",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_vignetteBlendMode",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_vignetteEnabled",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_ditheringEnabled",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_ditheringIntensity",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_skipFinalColorClamp",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_applyByPostProcess",void 0),(0,n.gn)([(0,s.qC)()],u.prototype,"_isEnabled",void 0),s.p4._ImageProcessingConfigurationParser=u.Parse},6150:(e,t,i)=>{i.d(t,{G:()=>c,p:()=>u});var n=i(9472),s=i(7104),r=i(3956),o=i(85),a=i(5346),l=i(1917),h=i(8449);class c extends l.H{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class u extends h.n{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new c,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=s.F.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&&o.k.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&o.k.DetailTextureEnabled&&this._isEnabled?(a.G.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&&o.k.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),a.G.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&o.k.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}(0,n.gn)([(0,r.oU)("detailTexture"),(0,r.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"texture",void 0),(0,n.gn)([(0,r.qC)()],u.prototype,"diffuseBlendLevel",void 0),(0,n.gn)([(0,r.qC)()],u.prototype,"roughnessBlendLevel",void 0),(0,n.gn)([(0,r.qC)()],u.prototype,"bumpLevel",void 0),(0,n.gn)([(0,r.qC)(),(0,r.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"normalBlendMethod",void 0),(0,n.gn)([(0,r.qC)(),(0,r.wz)("_markAllSubMeshesAsTexturesDirty")],u.prototype,"isEnabled",void 0)},7104:(e,t,i)=>{i.d(t,{F:()=>g});var n=i(9472),s=i(3956),r=i(7257),o=i(5757),a=i(1431),l=i(9401),h=i(3743),c=i(2722),u=i(142),d=i(5346),p=i(1345);class f{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){s.p4.Clone((()=>e),this)}serialize(){return s.p4.Serialize(this)}parse(e,t,i){s.p4.Parse((()=>this),e,t,i)}}(0,n.gn)([(0,s.qC)()],f.prototype,"func",null),(0,n.gn)([(0,s.qC)()],f.prototype,"funcRef",null),(0,n.gn)([(0,s.qC)()],f.prototype,"funcMask",null),(0,n.gn)([(0,s.qC)()],f.prototype,"opStencilFail",null),(0,n.gn)([(0,s.qC)()],f.prototype,"opDepthFail",null),(0,n.gn)([(0,s.qC)()],f.prototype,"opStencilDepthPass",null),(0,n.gn)([(0,s.qC)()],f.prototype,"mask",null),(0,n.gn)([(0,s.qC)()],f.prototype,"enabled",null);var _=i(1057),m=i(1698);class g{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;const t=this._alpha;this._alpha=e,1!==t&&1!==e||this.markAsDirty(g.MiscDirtyFlag+g.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(g.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(g.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 o.y$),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 o.y$),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new o.y$),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(g.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(g.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case g.WireFrameFillMode:case g.LineListDrawMode:case g.LineLoopDrawMode:case g.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?g.WireFrameFillMode:g.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case g.PointFillMode:case g.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?g.PointFillMode:g.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(g.MiscDirtyFlag))}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new o.y$,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 f,this._useUBO=!1,this._fillMode=g.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 n=t||a.l.LastCreatedScene;n&&(this._scene=n,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||r.w1.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new p.q(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=g.ClockWiseSideOrientation:this.sideOrientation=g.CounterClockWiseSideOrientation,this._uniformBuffer=new h.M(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),g.OnEventObservable.notifyObservers(this,m.S.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 n=t.materialDefines;return!!n&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===g.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===g.MATERIAL_OPAQUE||this._transparencyMode===g.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(e.hasVertexAlpha||this.needAlphaBlending())}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)t.getMaterial()===this&&t.effect&&(t.effect._wasPreviouslyReady=!1,t.effect._wasPreviouslyUsingInstances=null,t.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(g.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),n=(null==t?this.sideOrientation:t)===g.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,n,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),n}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(m.S.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const n=i.effect;n&&(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),n._forceRebindOnNextCall=!1)}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,d.G.BindSceneUniformBuffer(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(m.S.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(m.S.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(m.S.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}getBindedMeshes(){if(this.meshMap){const e=new Array;for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,n){const s={clipPlane:!1,useInstances:!1,...i},r=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const a=()=>{if(!this._scene||!this._scene.getEngine())return;const i=r.clipPlane;if(s.clipPlane&&(r.clipPlane=new u.J(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,r=null;if(e.subMeshes){const t=new l.P(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,s.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?r=t.effect.getCompilationError():(i=!1,setTimeout(a,16)))}i&&(this.allowShaderHotSwapping=o,r&&n&&n(r),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(a,16);s.clipPlane&&(r.clipPlane=i)};a()}forceCompilationAsync(e,t){return new Promise(((i,n)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{n(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(g._DirtyCallbackArray.length=0,e&g.TextureDirtyFlag&&g._DirtyCallbackArray.push(g._TextureDirtyCallBack),e&g.LightDirtyFlag&&g._DirtyCallbackArray.push(g._LightsDirtyCallBack),e&g.FresnelDirtyFlag&&g._DirtyCallbackArray.push(g._FresnelDirtyCallBack),e&g.AttributesDirtyFlag&&g._DirtyCallbackArray.push(g._AttributeDirtyCallBack),e&g.MiscDirtyFlag&&g._DirtyCallbackArray.push(g._MiscDirtyCallBack),e&g.PrePassDirtyFlag&&g._DirtyCallbackArray.push(g._PrePassDirtyCallBack),g._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(g._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(g._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(g._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(g._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(g._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(g._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(g._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(g._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(g._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(g._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(g._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==_.a.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 n=this.getScene();if(n.stopAnimation(this),n.freeProcessedMaterials(),n.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(m.S.Disposed,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(const t in this.meshMap){const i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{const t=n.meshes;for(const i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){if(e.geometry){const i=e.geometry;if(this._storeEffectOnSubMeshes)for(const n of e.subMeshes)i._releaseVertexArrayObject(n.effect),t&&n.effect&&n.effect.dispose();else i._releaseVertexArrayObject(this._drawWrapper.effect)}}serialize(){const e=s.p4.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,e}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return c.Y.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const n=r.w1.Instantiate(e.customType).Parse(e,t,i);return n._loadedUniqueId=e.uniqueId,n}}g.TriangleFillMode=0,g.WireFrameFillMode=1,g.PointFillMode=2,g.PointListDrawMode=3,g.LineListDrawMode=4,g.LineLoopDrawMode=5,g.LineStripDrawMode=6,g.TriangleStripDrawMode=7,g.TriangleFanDrawMode=8,g.ClockWiseSideOrientation=0,g.CounterClockWiseSideOrientation=1,g.TextureDirtyFlag=1,g.LightDirtyFlag=2,g.FresnelDirtyFlag=4,g.AttributesDirtyFlag=8,g.MiscDirtyFlag=16,g.PrePassDirtyFlag=32,g.AllDirtyFlag=63,g.MATERIAL_OPAQUE=0,g.MATERIAL_ALPHATEST=1,g.MATERIAL_ALPHABLEND=2,g.MATERIAL_ALPHATESTANDBLEND=3,g.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,g.MATERIAL_NORMALBLENDMETHOD_RNM=1,g.OnEventObservable=new o.y$,a.l.OnEnginesDisposedObservable.addOnce((()=>{g.OnEventObservable.clear()})),g._AllDirtyCallBack=e=>e.markAllAsDirty(),g._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),g._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),g._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),g._MiscDirtyCallBack=e=>e.markAsMiscDirty(),g._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),g._LightsDirtyCallBack=e=>e.markAsLightDirty(),g._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),g._FresnelAndMiscDirtyCallBack=e=>{g._FresnelDirtyCallBack(e),g._MiscDirtyCallBack(e)},g._TextureAndMiscDirtyCallBack=e=>{g._TextureDirtyCallBack(e),g._MiscDirtyCallBack(e)},g._DirtyCallbackArray=[],g._RunDirtyCallBacks=e=>{for(const t of g._DirtyCallbackArray)t(e)},(0,n.gn)([(0,s.qC)()],g.prototype,"id",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"uniqueId",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"name",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"metadata",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"checkReadyOnEveryCall",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"checkReadyOnlyOnce",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"state",void 0),(0,n.gn)([(0,s.qC)("alpha")],g.prototype,"_alpha",void 0),(0,n.gn)([(0,s.qC)("backFaceCulling")],g.prototype,"_backFaceCulling",void 0),(0,n.gn)([(0,s.qC)("cullBackFaces")],g.prototype,"_cullBackFaces",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"sideOrientation",void 0),(0,n.gn)([(0,s.qC)("alphaMode")],g.prototype,"_alphaMode",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"_needDepthPrePass",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"disableDepthWrite",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"disableColorWrite",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"forceDepthWrite",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"depthFunction",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"separateCullingPass",void 0),(0,n.gn)([(0,s.qC)("fogEnabled")],g.prototype,"_fogEnabled",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"pointSize",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"zOffset",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"zOffsetUnits",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"pointsCloud",null),(0,n.gn)([(0,s.qC)()],g.prototype,"fillMode",null),(0,n.gn)([(0,s.qC)()],g.prototype,"transparencyMode",null)},1917:(e,t,i)=>{i.d(t,{H:()=>n});class n{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;t<this._keys.length;t++){const i=this._keys[t];if(this[i]!==e[i])return!1}return!0}cloneTo(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(let t=0;t<this._keys.length;t++){const i=this._keys[t];e[i]=this[i]}}reset(){this._keys.forEach((e=>this._setDefaultValue(e)))}_setDefaultValue(e){var t,i,n,s,r;const o=null!==(n=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==n?n:typeof this[e],a=null===(r=null===(s=this._externalProperties)||void 0===s?void 0:s[e])||void 0===r?void 0:r.default;switch(o){case"number":this[e]=null!=a?a:0;break;case"string":this[e]=null!=a?a:"";break;default:this[e]=null!=a&&a}}toString(){let e="";for(let t=0;t<this._keys.length;t++){const i=this._keys[t],n=this[i];switch(typeof n){case"number":case"string":e+="#define "+i+" "+n+"\n";break;default:n&&(e+="#define "+i+"\n")}}return e}}},85:(e,t,i)=>{i.d(t,{k:()=>s});var n=i(7814);class s{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,n.D.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,n.D.MarkAllMaterialsAsDirty(1))}}s._DiffuseTextureEnabled=!0,s._DetailTextureEnabled=!0,s._DecalMapEnabled=!0,s._AmbientTextureEnabled=!0,s._OpacityTextureEnabled=!0,s._ReflectionTextureEnabled=!0,s._EmissiveTextureEnabled=!0,s._SpecularTextureEnabled=!0,s._BumpTextureEnabled=!0,s._LightmapTextureEnabled=!0,s._RefractionTextureEnabled=!0,s._ColorGradingTextureEnabled=!0,s._FresnelEnabled=!0,s._ClearCoatTextureEnabled=!0,s._ClearCoatBumpTextureEnabled=!0,s._ClearCoatTintTextureEnabled=!0,s._SheenTextureEnabled=!0,s._AnisotropicTextureEnabled=!0,s._ThicknessTextureEnabled=!0,s._RefractionIntensityTextureEnabled=!0,s._TranslucencyIntensityTextureEnabled=!0,s._IridescenceTextureEnabled=!0},5346:(e,t,i)=>{i.d(t,{G:()=>u});var n=i(2722),s=i(2704),r=i(1057),o=i(1431),a=i(708),l=i(4185),h=i(4649),c=i(99);class u{static BindSceneUniformBuffer(e,t){t.bindToEffect(e,"Scene")}static PrepareDefinesForMergedUV(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}static BindTextureMatrix(e,t,i){const n=e.getTextureMatrix();t.updateMatrix(i+"Matrix",n)}static GetFogState(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==r.x.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,n,s,r,o){o._areMiscDirty&&(o.LOGARITHMICDEPTH=i,o.POINTSIZE=n,o.FOG=s&&this.GetFogState(e,t),o.NONUNIFORMSCALING=e.nonUniformScaling,o.ALPHATEST=r)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){const n=t.CAMERA_ORTHOGRAPHIC?1:0,r=t.CAMERA_PERSPECTIVE?1:0,o=e.activeCamera.mode===s.V.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===s.V.PERSPECTIVE_CAMERA?1:0;(n^o||r^a)&&(t.CAMERA_ORTHOGRAPHIC=1===o,t.CAMERA_PERSPECTIVE=1===a,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,n,s,r=null,o=!1){let a=u.PrepareDefinesForCamera(e,n);!1!==r&&(a=(0,c.AN)(i,e,n)),n.DEPTHPREPASS!==!t.getColorWrite()&&(n.DEPTHPREPASS=!n.DEPTHPREPASS,a=!0),n.INSTANCES!==s&&(n.INSTANCES=s,a=!0),n.THIN_INSTANCES!==o&&(n.THIN_INSTANCES=o,a=!0),a&&n.markAsUnprocessed()}static PrepareDefinesForBones(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const n=e.getScene().prePassRenderer;if(n&&n.enabled){const i=-1===n.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}static PrepareDefinesForMorphTargets(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}static PrepareDefinesForBakedVertexAnimation(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}static PrepareDefinesForAttributes(e,t,i,n,s=!1,r=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(a.o.NormalKind),t._needNormals&&e.isVerticesDataPresent(a.o.TangentKind)&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent(a.o.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&r}return e.isVerticesDataPresent(a.o.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),n&&this.PrepareDefinesForBones(e,t),s&&this.PrepareDefinesForMorphTargets(e,t),o&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){const n=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,n===t.ORDER_INDEPENDENT_TRANSPARENCY&&s===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){const n=t.PREPASS;if(!t._arePrePassDirty)return;const s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount;for(let i=0;i<s.length;i++){const n=e.prePassRenderer.getIndex(s[i].type);-1!==n?(t[s[i].define]=!0,t[s[i].index]=n):t[s[i].define]=!1}}else{t.PREPASS=!1;for(let e=0;e<s.length;e++)t[s[e].define]=!1}t.PREPASS!=n&&(t.markAsUnprocessed(),t.markAsImageProcessingDirty())}static PrepareDefinesForLight(e,t,i,n,s,r,o){var a;switch(o.needNormals=!0,void 0===s["LIGHT"+n]&&(o.needRebuild=!0),s["LIGHT"+n]=!0,s["SPOTLIGHT"+n]=!1,s["HEMILIGHT"+n]=!1,s["POINTLIGHT"+n]=!1,s["DIRLIGHT"+n]=!1,i.prepareLightSpecificDefines(s,n),s["LIGHT_FALLOFF_PHYSICAL"+n]=!1,s["LIGHT_FALLOFF_GLTF"+n]=!1,s["LIGHT_FALLOFF_STANDARD"+n]=!1,i.falloffType){case l.m.FALLOFF_GLTF:s["LIGHT_FALLOFF_GLTF"+n]=!0;break;case l.m.FALLOFF_PHYSICAL:s["LIGHT_FALLOFF_PHYSICAL"+n]=!0;break;case l.m.FALLOFF_STANDARD:s["LIGHT_FALLOFF_STANDARD"+n]=!0}if(r&&!i.specular.equalsFloats(0,0,0)&&(o.specularEnabled=!0),s["SHADOW"+n]=!1,s["SHADOWCSM"+n]=!1,s["SHADOWCSMDEBUG"+n]=!1,s["SHADOWCSMNUM_CASCADES"+n]=!1,s["SHADOWCSMUSESHADOWMAXZ"+n]=!1,s["SHADOWCSMNOBLEND"+n]=!1,s["SHADOWCSM_RIGHTHANDED"+n]=!1,s["SHADOWPCF"+n]=!1,s["SHADOWPCSS"+n]=!1,s["SHADOWPOISSON"+n]=!1,s["SHADOWESM"+n]=!1,s["SHADOWCLOSEESM"+n]=!1,s["SHADOWCUBE"+n]=!1,s["SHADOWLOWQUALITY"+n]=!1,s["SHADOWMEDIUMQUALITY"+n]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&i.shadowEnabled){const t=null!==(a=i.getShadowGenerator(e.activeCamera))&&void 0!==a?a:i.getShadowGenerator();if(t){const e=t.getShadowMap();e&&e.renderList&&e.renderList.length>0&&(o.shadowEnabled=!0,t.prepareDefines(s,n))}}i.lightmapMode!=l.m.LIGHTMAP_DEFAULT?(o.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+n]=!0,s["LIGHTMAPNOSPECULAR"+n]=i.lightmapMode==l.m.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+n]=!1,s["LIGHTMAPNOSPECULAR"+n]=!1)}static PrepareDefinesForLights(e,t,i,n,s=4,r=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const a={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!r)for(const r of t.lightSources)if(this.PrepareDefinesForLight(e,t,r,o,i,n,a),o++,o===s)break;i.SPECULARTERM=a.specularEnabled,i.SHADOWS=a.shadowEnabled;for(let e=o;e<s;e++)void 0!==i["LIGHT"+e]&&(i["LIGHT"+e]=!1,i["HEMILIGHT"+e]=!1,i["POINTLIGHT"+e]=!1,i["DIRLIGHT"+e]=!1,i["SPOTLIGHT"+e]=!1,i["SHADOW"+e]=!1,i["SHADOWCSM"+e]=!1,i["SHADOWCSMDEBUG"+e]=!1,i["SHADOWCSMNUM_CASCADES"+e]=!1,i["SHADOWCSMUSESHADOWMAXZ"+e]=!1,i["SHADOWCSMNOBLEND"+e]=!1,i["SHADOWCSM_RIGHTHANDED"+e]=!1,i["SHADOWPCF"+e]=!1,i["SHADOWPCSS"+e]=!1,i["SHADOWPOISSON"+e]=!1,i["SHADOWESM"+e]=!1,i["SHADOWCLOSEESM"+e]=!1,i["SHADOWCUBE"+e]=!1,i["SHADOWLOWQUALITY"+e]=!1,i["SHADOWMEDIUMQUALITY"+e]=!1);const l=e.getEngine().getCaps();return void 0===i.SHADOWFLOAT&&(a.needRebuild=!0),i.SHADOWFLOAT=a.shadowEnabled&&(l.textureFloatRender&&l.textureFloatLinearFiltering||l.textureHalfFloatRender&&l.textureHalfFloatLinearFiltering),i.LIGHTMAPEXCLUDED=a.lightmapMode,a.needRebuild&&i.rebuild(),a.needNormals}static PrepareUniformsAndSamplersForLight(e,t,i,n,s=null,r=!1){s&&s.push("Light"+e),r||(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),i.push("shadowSampler"+e),i.push("depthSampler"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),n&&(i.push("projectionLightSampler"+e),t.push("textureProjectionMatrix"+e)))}static PrepareUniformsAndSamplersList(e,t,i,n=4){let s,r=null;if(e.uniformsNames){const o=e;s=o.uniformsNames,r=o.uniformBuffersNames,t=o.samplers,i=o.defines,n=o.maxSimultaneousLights||0}else s=e,t||(t=[]);for(let e=0;e<n&&i["LIGHT"+e];e++)this.PrepareUniformsAndSamplersForLight(e,s,t,i["PROJECTEDLIGHTTEXTURE"+e],r);i.NUM_MORPH_INFLUENCERS&&s.push("morphTargetInfluences"),i.BAKED_VERTEX_ANIMATION_TEXTURE&&(s.push("bakedVertexAnimationSettings"),s.push("bakedVertexAnimationTextureSizeInverted"),s.push("bakedVertexAnimationTime"),t.push("bakedVertexAnimationTexture"))}static HandleFallbacksForShadows(e,t,i=4,n=0){let s=0;for(let r=0;r<i&&e["LIGHT"+r];r++)r>0&&(s=n+r,t.addFallback(s,"LIGHT"+r)),e.SHADOWS||(e["SHADOW"+r]&&t.addFallback(n,"SHADOW"+r),e["SHADOWPCF"+r]&&t.addFallback(n,"SHADOWPCF"+r),e["SHADOWPCSS"+r]&&t.addFallback(n,"SHADOWPCSS"+r),e["SHADOWPOISSON"+r]&&t.addFallback(n,"SHADOWPOISSON"+r),e["SHADOWESM"+r]&&t.addFallback(n,"SHADOWESM"+r),e["SHADOWCLOSEESM"+r]&&t.addFallback(n,"SHADOWCLOSEESM"+r));return s++}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&&o.l.LastCreatedEngine){const r=o.l.LastCreatedEngine.getCaps().maxVertexAttribs,l=t.morphTargetManager;if(null==l?void 0:l.isUsingTextureForTargets)return;const h=l&&l.supportsNormals&&i.NORMAL,c=l&&l.supportsTangents&&i.TANGENT,u=l&&l.supportsUVs&&i.UV1;for(let i=0;i<s;i++)e.push(a.o.PositionKind+i),h&&e.push(a.o.NormalKind+i),c&&e.push(a.o.TangentKind+i),u&&e.push(a.o.UVKind+"_"+i),e.length>r&&n.Y.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,n){i.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,t),e.push(a.o.MatricesIndicesKind),e.push(a.o.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(a.o.MatricesIndicesExtraKind),e.push(a.o.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(a.o.ColorInstanceKind)}static PushAttributesForInstances(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,n,s,r=!0){e._bindLight(t,i,n,s,r)}static BindLights(e,t,i,n,s=4){const r=Math.min(t.lightSources.length,s);for(let s=0;s<r;s++){const r=t.lightSources[s];this.BindLight(r,s,e,i,"boolean"==typeof n?n:n.SPECULARTERM,t.receiveShadows)}}static BindFogParameters(e,t,i,n=!1){e.fogEnabled&&t.applyFog&&e.fogMode!==r.x.FOGMODE_NONE&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),n?(e.fogColor.toLinearSpaceToRef(this._TempFogColor,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",this._TempFogColor)):i.setColor3("vFogColor",e.fogColor))}static BindBonesParameters(e,t,i){if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const n=e.skeleton;if(n.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=n.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(n.bones.length+1))}else{const s=n.getTransformMatrices(e);s&&(t.setMatrices("mBones",s),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=s.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),u._CopyBonesTransformationMatrices(s,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;e.mode===s.V.ORTHOGRAPHIC_CAMERA&&n.Y.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}}u._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},u._TempFogColor=h.Wo.Black()},8449:(e,t,i)=>{i.d(t,{n:()=>o});var n=i(9472),s=i(3956),r=i(9249);class o{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,n,s=!0,o=!1){this.priority=500,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,e.pluginManager||(e.pluginManager=new r.BK(e),e.onDisposeObservable.add((()=>{e.pluginManager=void 0}))),this._pluginDefineNames=n,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),o&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,n){return!0}hardBindForSubMesh(e,t,i,n){}bindForSubMesh(e,t,i,n){}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:"number"===i?"number":"string"===i?"string":"boolean"===i?"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){s.p4.Clone((()=>e),this)}serialize(){return s.p4.Serialize(this)}parse(e,t,i){s.p4.Parse((()=>this),e,t,i)}}(0,n.gn)([(0,s.qC)()],o.prototype,"name",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"priority",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"registerForExtraEvents",void 0)},1698:(e,t,i)=>{var n;i.d(t,{S:()=>n}),function(e){e[e.Created=1]="Created",e[e.Disposed=2]="Disposed",e[e.GetDefineNames=4]="GetDefineNames",e[e.PrepareUniformBuffer=8]="PrepareUniformBuffer",e[e.IsReadyForSubMesh=16]="IsReadyForSubMesh",e[e.PrepareDefines=32]="PrepareDefines",e[e.BindForSubMesh=64]="BindForSubMesh",e[e.PrepareEffect=128]="PrepareEffect",e[e.GetAnimatables=256]="GetAnimatables",e[e.GetActiveTextures=512]="GetActiveTextures",e[e.HasTexture=1024]="HasTexture",e[e.FillRenderTargetTextures=2048]="FillRenderTargetTextures",e[e.HasRenderTargetTextures=4096]="HasRenderTargetTextures",e[e.HardBindForSubMesh=8192]="HardBindForSubMesh"}(n||(n={}))},9249:(e,t,i)=>{i.d(t,{BK:()=>o,Dh:()=>d,jD:()=>u,rs:()=>c});var n=i(7104),s=i(1698);const r=new RegExp("^([gimus]+)!");class o{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e.name)throw`Plugin "${e.name}" already added to the material "${this._material.name}"!`;if(this._material._uniformBufferLayoutBuilt)throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because this material has already been used for rendering! Please add plugins to materials before any rendering with this material occurs.`;const t=e.getClassName();o._MaterialPluginClassToMainDefine[t]||(o._MaterialPluginClassToMainDefine[t]="MATERIALPLUGIN_"+ ++o._MaterialPluginCounter),this._material._callbackPluginEventGeneric=this._handlePluginEvent.bind(this),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[o._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));this._defineNamesFromPlugins=i}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e)return this._plugins[t];return null}_handlePluginEventIsReadyForSubMesh(e){let t=!0;for(const i of this._activePlugins)t=t&&i.isReadyForSubMesh(e.defines,this._scene,this._engine,e.subMesh);e.isReadyForSubMesh=t}_handlePluginEventPrepareDefinesBeforeAttributes(e){for(const t of this._activePlugins)t.prepareDefinesBeforeAttributes(e.defines,this._scene,e.mesh)}_handlePluginEventPrepareDefines(e){for(const t of this._activePlugins)t.prepareDefines(e.defines,this._scene,e.mesh)}_handlePluginEventHardBindForSubMesh(e){for(const t of this._activePluginsForExtraEvents)t.hardBindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventBindForSubMesh(e){for(const t of this._activePlugins)t.bindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventHasRenderTargetTextures(e){let t=!1;for(const e of this._activePluginsForExtraEvents)if(t=e.hasRenderTargetTextures(),t)break;e.hasRenderTargetTextures=t}_handlePluginEventFillRenderTargetTextures(e){for(const t of this._activePluginsForExtraEvents)t.fillRenderTargetTextures(e.renderTargets)}_handlePluginEvent(e,t){var i;switch(e){case s.S.GetActiveTextures:{const e=t;for(const t of this._activePlugins)t.getActiveTextures(e.activeTextures);break}case s.S.GetAnimatables:{const e=t;for(const t of this._activePlugins)t.getAnimatables(e.animatables);break}case s.S.HasTexture:{const e=t;let i=!1;for(const t of this._activePlugins)if(i=t.hasTexture(e.texture),i)break;e.hasTexture=i;break}case s.S.Disposed:{const e=t;for(const t of this._plugins)t.dispose(e.forceDisposeTextures);break}case s.S.GetDefineNames:t.defineNames=this._defineNamesFromPlugins;break;case s.S.PrepareEffect:{const e=t;for(const t of this._activePlugins)e.fallbackRank=t.addFallbacks(e.defines,e.fallbacks,e.fallbackRank),t.getAttributes(e.attributes,this._scene,e.mesh);this._uniformList.length>0&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e.customCode);break}case s.S.PrepareUniformBuffer:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const n=t.getUniforms();if(n){if(n.ubo)for(const t of n.ubo){if(t.size&&t.type){const n=null!==(i=t.arraySize)&&void 0!==i?i:0;e.ubo.addUniform(t.name,t.size,n),this._uboDeclaration+=`${t.type} ${t.name}${n>0?`[${n}]`:""};\r\n`}this._uniformList.push(t.name)}n.vertex&&(this._vertexDeclaration+=n.vertex+"\r\n"),n.fragment&&(this._fragmentDeclaration+=n.fragment+"\r\n")}t.getSamplers(this._samplerList),t.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e){return(t,i)=>{var n;e&&(i=e(t,i)),this._uboDeclaration&&(i=i.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(i=i.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(i=i.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const s=null===(n=this._codeInjectionPoints)||void 0===n?void 0:n[t];if(!s)return i;for(let e in s){let n="";for(const i of this._activePlugins){const s=i.getCustomCode(t);(null==s?void 0:s[e])&&(n+=s[e]+"\r\n")}if(n.length>0)if("!"===e.charAt(0)){e=e.substring(1);let t="g";if("!"===e.charAt(0))t="",e=e.substring(1);else{const i=r.exec(e);i&&i.length>=2&&(t=i[1],e=e.substring(t.length+1))}t.indexOf("g")<0&&(t+="g");const s=i,o=new RegExp(e,t);let a=o.exec(s);for(;null!==a;){let e=n;for(let t=0;t<a.length;++t)e=e.replace("$"+t,a[t]);i=i.replace(a[0],e),a=o.exec(s)}}else{const t="#define "+e;i=i.replace(t,"\r\n"+n+"\r\n"+t)}}return i}}}o._MaterialPluginClassToMainDefine={},o._MaterialPluginCounter=0;const a=[];let l=!1,h=null;function c(e,t){l||(h=n.F.OnEventObservable.add((e=>{for(const[,t]of a)t(e)}),s.S.Created),l=!0);const i=a.filter((([t,i])=>t===e));i.length>0?i[0][1]=t:a.push([e,t])}function u(e){for(let t=0;t<a.length;++t)if(a[t][0]===e)return a.splice(t,1),0===a.length&&d(),!0;return!1}function d(){a.length=0,l=!1,n.F.OnEventObservable.remove(h)}},9828:(e,t,i)=>{i.d(t,{G:()=>o});var n=i(7104),s=i(4875),r=i(2208);class o extends n.F{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().multiMaterials.push(this),this.subMaterials=new Array,this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...i)=>{const n=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),n};const i=e.splice;e.splice=(t,n)=>{const s=i.apply(e,[t,n]);return this._markAllSubMeshesAsTexturesDirty(),s}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map((e=>e?e.getActiveTextures():[])))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i<this.subMaterials.length;i++)if(null===(t=this.subMaterials[i])||void 0===t?void 0:t.hasTexture(e))return!0;return!1}getClassName(){return"MultiMaterial"}isReadyForSubMesh(e,t,i){for(let n=0;n<this.subMaterials.length;n++){const s=this.subMaterials[n];if(s){if(s._storeEffectOnSubMeshes){if(!s.isReadyForSubMesh(e,t,i))return!1;continue}if(!s.isReady(e))return!1}}return!0}clone(e,t){const i=new o(e,this.getScene());for(let n=0;n<this.subMaterials.length;n++){let s=null;const r=this.subMaterials[n];s=t&&r?r.clone(e+"-"+r.name):this.subMaterials[n],i.subMaterials.push(s)}return i}serialize(){const e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,s.$&&(e.tags=s.$.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(let t=0;t<this.subMaterials.length;t++){const i=this.subMaterials[t];i?(e.materialsUniqueIds.push(i.uniqueId),e.materials.push(i.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e}dispose(e,t,i){const n=this.getScene();if(!n)return;if(i)for(let i=0;i<this.subMaterials.length;i++){const n=this.subMaterials[i];n&&n.dispose(e,t)}const s=n.multiMaterials.indexOf(this);s>=0&&n.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new o(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,s.$&&s.$.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}(0,r.H)("BABYLON.MultiMaterial",o)},178:(e,t,i)=>{i.d(t,{o:()=>n});class n{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,n,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=n.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const s=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==s.frameId&&(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=n.clone()}}}},580:(e,t,i)=>{i.d(t,{a:()=>r});var n=i(4141),s=i(7104);class r extends s.F{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new n.y3,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return!!e&&(!this._storeEffectOnSubMeshes||!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t))}_isReadyForSubMesh(e){const t=e.materialDefines;return!(this.checkReadyOnEveryCall||!e.effect||!t||t._renderId!==this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null){super._afterBind(e,t),this.getScene()._cachedEffect=t,t&&(t._forceRebindOnNextCall=!1)}_mustRebind(e,t,i=1){return e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}},9131:(e,t,i)=>{var n;i.d(t,{x:()=>n}),function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(n||(n={}))},8097:(e,t,i)=>{i.d(t,{j:()=>m});var n=i(3956),s=i(4141),r=i(708),o=i(2262),a=i(5346),l=i(2208),h=i(4649),c=i(1434),u=i(6662),d=i(580),p=i(1431),f=i(99);const _={effect:null,subMesh:null};class m extends d.a{constructor(e,t,i,n={},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 s.y3,this._cachedWorldViewProjectionMatrix=new s.y3,this._multiview=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...n}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&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(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;e<t.length;e++)t[e].copyToArray(i,16*e);return this._matrixArrays[e]=i,this}setMatrix3x3(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this}setMatrix2x2(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this}setArray2(e,t){return this._checkUniform(e),this._vectors2Arrays[e]=t,this}setArray3(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this}setArray4(e,t){return this._checkUniform(e),this._vectors4Arrays[e]=t,this}setUniformBuffer(e,t){return-1===this._options.uniformBuffers.indexOf(e)&&this._options.uniformBuffers.push(e),this._uniformBuffers[e]=t,this}setTextureSampler(e,t){return-1===this._options.samplerObjects.indexOf(e)&&this._options.samplerObjects.push(e),this._textureSamplers[e]=t,this}setStorageBuffer(e,t){return-1===this._options.storageBuffers.indexOf(e)&&this._options.storageBuffers.push(e),this._storageBuffers[e]=t,this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var n,s,o,l;const h=i&&this._storeEffectOnSubMeshes;if(this.isFrozen)if(h){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{const e=this._drawWrapper.effect;if(e&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const u=this.getScene(),d=u.getEngine(),p=[],m=[],g=new c.L;let v=this._shaderPath,y=this._options.uniforms,x=this._options.uniformBuffers,b=this._options.samplers;d.getCaps().multiview&&u.activeCamera&&u.activeCamera.outputRenderTarget&&u.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,p.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.indexOf("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(let e=0;e<this._options.defines.length;e++){const t=0===this._options.defines[e].indexOf("#define")?this._options.defines[e]:`#define ${this._options.defines[e]}`;p.push(t)}for(let e=0;e<this._options.attributes.length;e++)m.push(this._options.attributes[e]);if(e&&e.isVerticesDataPresent(r.o.ColorKind)&&(m.push(r.o.ColorKind),p.push("#define VERTEXCOLOR")),t&&(p.push("#define INSTANCES"),a.G.PushAttributesForInstances(m),(null==e?void 0:e.hasThinInstances)&&(p.push("#define THIN_INSTANCES"),e&&e.isVerticesDataPresent(r.o.ColorInstanceKind)&&(m.push(r.o.ColorInstanceKind),p.push("#define INSTANCESCOLOR")))),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){m.push(r.o.MatricesIndicesKind),m.push(r.o.MatricesWeightsKind),e.numBoneInfluencers>4&&(m.push(r.o.MatricesIndicesExtraKind),m.push(r.o.MatricesWeightsExtraKind));const t=e.skeleton;p.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),g.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(p.push("#define BONETEXTURE"),-1===this._options.uniforms.indexOf("boneTextureWidth")&&this._options.uniforms.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(p.push("#define BonesPerMesh "+(t.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else p.push("#define NUM_BONE_INFLUENCERS 0");let T=0;const S=e?e.morphTargetManager:null;if(S){const e=S.supportsUVs&&-1!==p.indexOf("#define UV1"),t=S.supportsTangents&&-1!==p.indexOf("#define TANGENT"),i=S.supportsNormals&&-1!==p.indexOf("#define NORMAL");T=S.numInfluencers,e&&p.push("#define MORPHTARGETS_UV"),t&&p.push("#define MORPHTARGETS_TANGENT"),i&&p.push("#define MORPHTARGETS_NORMAL"),T>0&&p.push("#define MORPHTARGETS"),S.isUsingTextureForTargets&&(p.push("#define MORPHTARGETS_TEXTURE"),-1===this._options.uniforms.indexOf("morphTargetTextureIndices")&&this._options.uniforms.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),p.push("#define NUM_MORPH_INFLUENCERS "+T);for(let n=0;n<T;n++)m.push(r.o.PositionKind+n),i&&m.push(r.o.NormalKind+n),t&&m.push(r.o.TangentKind+n),e&&m.push(r.o.UVKind+"_"+n);T>0&&(y=y.slice(),y.push("morphTargetInfluences"),y.push("morphTargetTextureInfo"),y.push("morphTargetTextureIndices"))}else p.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(p.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===this._options.uniforms.indexOf("bakedVertexAnimationSettings")&&this._options.uniforms.push("bakedVertexAnimationSettings"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTime")&&this._options.uniforms.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),a.G.PrepareAttributesForBakedVertexAnimation(m,e,p)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&p.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&((0,f.qx)(y),(0,f.lK)(this,u,p)),this.customShaderNameResolve&&(y=y.slice(),x=x.slice(),b=b.slice(),v=this.customShaderNameResolve(v,y,x,b,p,m));const E=h?i._getDrawWrapper():this._drawWrapper,C=null!==(n=null==E?void 0:E.effect)&&void 0!==n?n:null,A=null!==(s=null==E?void 0:E.defines)&&void 0!==s?s:null,P=p.join("\n");let R=C;return A!==P&&(R=d.createEffect(v,{attributes:m,uniformsNames:y,uniformBuffersNames:x,samplers:b,defines:P,fallbacks:g,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:T},shaderLanguage:this._options.shaderLanguage},d),h?i.setEffect(R,P,this._materialContext):E&&E.setEffect(R,P),this._onEffectCreatedObservable&&(_.effect=R,_.subMesh=null!==(o=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==o?o:null,this._onEffectCreatedObservable.notifyObservers(_))),R._wasPreviouslyUsingInstances=!!t,null!==(l=!(null==R?void 0:R.isReady()))&&void 0!==l&&!l&&(C!==R&&u.resetCachedMaterial(),R._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),n=null!=t?t:this.getEffect();n&&(-1!==this._options.uniforms.indexOf("world")&&n.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),n.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),n.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var n;this.bind(e,t,null===(n=i._drawWrapperOverride)||void 0===n?void 0:n.effect,i)}bind(e,t,i,n){var s;const r=n&&this._storeEffectOnSubMeshes,o=null!=i?i:r?n.effect:this.getEffect();if(!o)return;this._activeEffect=o,this.bindOnlyWorldMatrix(e,i);const l=this._options.uniformBuffers;let h=!1;if(o&&l&&l.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let i=0;i<l.length;++i)switch(l[i]){case"Mesh":t&&(t.getMeshUniformBuffer().bindToEffect(o,"Mesh"),t.transferToEffect(e));break;case"Scene":a.G.BindSceneUniformBuffer(o,this.getScene().getSceneUniformBuffer()),this.getScene().finalizeSceneUbo(),h=!0}const c=t&&r?this._mustRebind(this.getScene(),o,t.visibility):this.getScene().getCachedMaterial()!==this;if(o&&c){let e;for(e in h||-1===this._options.uniforms.indexOf("view")||o.setMatrix("view",this.getScene().getViewMatrix()),h||-1===this._options.uniforms.indexOf("projection")||o.setMatrix("projection",this.getScene().getProjectionMatrix()),h||-1===this._options.uniforms.indexOf("viewProjection")||(o.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._multiview&&o.setMatrix("viewProjectionR",this.getScene()._transformMatrixR)),this.getScene().activeCamera&&-1!==this._options.uniforms.indexOf("cameraPosition")&&o.setVector3("cameraPosition",this.getScene().activeCamera.globalPosition),a.G.BindBonesParameters(t,o),(0,f.an)(o,this,this.getScene()),this._textures)o.setTexture(e,this._textures[e]);for(e in this._textureArrays)o.setTextureArray(e,this._textureArrays[e]);for(e in this._externalTextures)o.setExternalTexture(e,this._externalTextures[e]);for(e in this._ints)o.setInt(e,this._ints[e]);for(e in this._uints)o.setUInt(e,this._uints[e]);for(e in this._floats)o.setFloat(e,this._floats[e]);for(e in this._floatsArrays)o.setArray(e,this._floatsArrays[e]);for(e in this._colors3)o.setColor3(e,this._colors3[e]);for(e in this._colors3Arrays)o.setArray3(e,this._colors3Arrays[e]);for(e in this._colors4){const t=this._colors4[e];o.setFloat4(e,t.r,t.g,t.b,t.a)}for(e in this._colors4Arrays)o.setArray4(e,this._colors4Arrays[e]);for(e in this._vectors2)o.setVector2(e,this._vectors2[e]);for(e in this._vectors3)o.setVector3(e,this._vectors3[e]);for(e in this._vectors4)o.setVector4(e,this._vectors4[e]);for(e in this._quaternions)o.setQuaternion(e,this._quaternions[e]);for(e in this._matrices)o.setMatrix(e,this._matrices[e]);for(e in this._matrixArrays)o.setMatrices(e,this._matrixArrays[e]);for(e in this._matrices3x3)o.setMatrix3x3(e,this._matrices3x3[e]);for(e in this._matrices2x2)o.setMatrix2x2(e,this._matrices2x2[e]);for(e in this._vectors2Arrays)o.setArray2(e,this._vectors2Arrays[e]);for(e in this._vectors3Arrays)o.setArray3(e,this._vectors3Arrays[e]);for(e in this._vectors4Arrays)o.setArray4(e,this._vectors4Arrays[e]);for(e in this._quaternionsArrays)o.setArray4(e,this._quaternionsArrays[e]);for(e in this._uniformBuffers){const t=this._uniformBuffers[e].getBuffer();t&&o.bindUniformBuffer(t,e)}for(e in this._textureSamplers)o.setTextureSampler(e,this._textureSamplers[e]);for(e in this._storageBuffers)o.setStorageBuffer(e,this._storageBuffers[e])}if(o&&t&&(c||!this.isFrozen)){const e=t.morphTargetManager;e&&e.numInfluencers>0&&a.G.BindMorphTargetParameters(t,o);const i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(s=t.bakedVertexAnimationManager)||void 0===s||s.bind(o,!!o._wasPreviouslyUsingInstances))}this._afterBind(t,o)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;t<i.length;t++)e.push(i[t])}return e}hasTexture(e){if(super.hasTexture(e))return!0;for(const t in this._textures)if(this._textures[t]===e)return!0;for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;t<i.length;t++)if(i[t]===e)return!0}return!1}clone(e){const t=n.p4.Clone((()=>new m(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;e<t.length;e++)t[e].dispose()}}this._textures={},super.dispose(e,t,i)}serialize(){const e=n.p4.Serialize(this);let t;for(t in e.customType="BABYLON.ShaderMaterial",e.uniqueId=this.uniqueId,e.options=this._options,e.shaderPath=this._shaderPath,e.storeEffectOnSubMeshes=this._storeEffectOnSubMeshes,e.stencil=this.stencil.serialize(),e.textures={},this._textures)e.textures[t]=this._textures[t].serialize();for(t in e.textureArrays={},this._textureArrays){e.textureArrays[t]=[];const i=this._textureArrays[t];for(let n=0;n<i.length;n++)e.textureArrays[t].push(i[n].serialize())}for(t in e.ints={},this._ints)e.ints[t]=this._ints[t];for(t in e.uints={},this._uints)e.uints[t]=this._uints[t];for(t in e.floats={},this._floats)e.floats[t]=this._floats[t];for(t in e.FloatArrays={},this._floatsArrays)e.FloatArrays[t]=this._floatsArrays[t];for(t in e.colors3={},this._colors3)e.colors3[t]=this._colors3[t].asArray();for(t in e.colors3Arrays={},this._colors3Arrays)e.colors3Arrays[t]=this._colors3Arrays[t];for(t in e.colors4={},this._colors4)e.colors4[t]=this._colors4[t].asArray();for(t in e.colors4Arrays={},this._colors4Arrays)e.colors4Arrays[t]=this._colors4Arrays[t];for(t in e.vectors2={},this._vectors2)e.vectors2[t]=this._vectors2[t].asArray();for(t in e.vectors3={},this._vectors3)e.vectors3[t]=this._vectors3[t].asArray();for(t in e.vectors4={},this._vectors4)e.vectors4[t]=this._vectors4[t].asArray();for(t in e.quaternions={},this._quaternions)e.quaternions[t]=this._quaternions[t].asArray();for(t in e.matrices={},this._matrices)e.matrices[t]=this._matrices[t].asArray();for(t in e.matrixArray={},this._matrixArrays)e.matrixArray[t]=this._matrixArrays[t];for(t in e.matrices3x3={},this._matrices3x3)e.matrices3x3[t]=this._matrices3x3[t];for(t in e.matrices2x2={},this._matrices2x2)e.matrices2x2[t]=this._matrices2x2[t];for(t in e.vectors2Arrays={},this._vectors2Arrays)e.vectors2Arrays[t]=this._vectors2Arrays[t];for(t in e.vectors3Arrays={},this._vectors3Arrays)e.vectors3Arrays[t]=this._vectors3Arrays[t];for(t in e.vectors4Arrays={},this._vectors4Arrays)e.vectors4Arrays[t]=this._vectors4Arrays[t];for(t in e.quaternionsArrays={},this._quaternionsArrays)e.quaternionsArrays[t]=this._quaternionsArrays[t];return e}static Parse(e,t,i){const r=n.p4.Parse((()=>new m(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let a;for(a in e.stencil&&r.stencil.parse(e.stencil,t,i),e.textures)r.setTexture(a,o.x.Parse(e.textures[a],t,i));for(a in e.textureArrays){const n=e.textureArrays[a],s=new Array;for(let e=0;e<n.length;e++)s.push(o.x.Parse(n[e],t,i));r.setTextureArray(a,s)}for(a in e.ints)r.setInt(a,e.ints[a]);for(a in e.uints)r.setUInt(a,e.uints[a]);for(a in e.floats)r.setFloat(a,e.floats[a]);for(a in e.floatsArrays)r.setFloats(a,e.floatsArrays[a]);for(a in e.colors3)r.setColor3(a,h.Wo.FromArray(e.colors3[a]));for(a in e.colors3Arrays){const t=e.colors3Arrays[a].reduce(((e,t,i)=>(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>h.Wo.FromArray(e)));r.setColor3Array(a,t)}for(a in e.colors4)r.setColor4(a,h.HE.FromArray(e.colors4[a]));for(a in e.colors4Arrays){const t=e.colors4Arrays[a].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>h.HE.FromArray(e)));r.setColor4Array(a,t)}for(a in e.vectors2)r.setVector2(a,s.FM.FromArray(e.vectors2[a]));for(a in e.vectors3)r.setVector3(a,s.P.FromArray(e.vectors3[a]));for(a in e.vectors4)r.setVector4(a,s.Lt.FromArray(e.vectors4[a]));for(a in e.quaternions)r.setQuaternion(a,s._f.FromArray(e.quaternions[a]));for(a in e.matrices)r.setMatrix(a,s.y3.FromArray(e.matrices[a]));for(a in e.matrixArray)r._matrixArrays[a]=new Float32Array(e.matrixArray[a]);for(a in e.matrices3x3)r.setMatrix3x3(a,e.matrices3x3[a]);for(a in e.matrices2x2)r.setMatrix2x2(a,e.matrices2x2[a]);for(a in e.vectors2Arrays)r.setArray2(a,e.vectors2Arrays[a]);for(a in e.vectors3Arrays)r.setArray3(a,e.vectors3Arrays[a]);for(a in e.vectors4Arrays)r.setArray4(a,e.vectors4Arrays[a]);for(a in e.quaternionsArrays)r.setArray4(a,e.quaternionsArrays[a]);return r}static ParseFromFileAsync(e,t,i,n=""){return new Promise(((s,r)=>{const o=new u.g;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),r=this.Parse(t,i||p.l.LastCreatedScene,n);e&&(r.name=e),s(r)}else r("Unable to load the ShaderMaterial")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((n,s)=>{const r=new u.g;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){const s=JSON.parse(JSON.parse(r.responseText).jsonPayload),o=JSON.parse(s.shaderMaterial),a=this.Parse(o,t||p.l.LastCreatedScene,i);a.snippetId=e,n(a)}else s("Unable to load the snippet "+e)})),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()}))}}m.SnippetUrl="https://snippet.babylonjs.com",m.CreateFromSnippetAsync=m.ParseFromSnippetAsync,(0,l.H)("BABYLON.ShaderMaterial",m)},252:(e,t,i)=>{i.d(t,{K:()=>A,R:()=>C});var n=i(9472),s=i(3956),r=i(5363),o=i(1057),a=i(4141),l=i(4649),h=i(708),c=i(178),u=i(4475),d=i(7104),p=i(1698),f=i(1917),_=i(580),m=i(5346),g=i(2262),v=i(2208),y=i(85),x=i(8104);i(3055);x.v.IncludesShadersStore.defaultFragmentDeclaration="uniform vec4 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\nuniform vec3 vAmbientColor;\nuniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;\nuniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include<decalFragmentDeclaration>\n#define ADDITIONAL_FRAGMENT_DECLARATION\n",i(2963),i(4804);x.v.IncludesShadersStore.defaultUboDeclaration="layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor;\nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix;\nvec2 vTangentSpaceParams;\nfloat pointSize;\nfloat alphaCutOff;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec3 vRefractionPosition;\nvec3 vRefractionSize;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nvec3 vAmbientColor;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include<sceneUboDeclaration>\n#include<meshUboDeclaration>\n",i(8190),i(1868),i(6637),i(1423),i(2557),i(3756),i(6568),i(3996),i(1015),i(8491),i(2132),i(5141),i(3660),i(8882),i(7441),i(6390),i(1030),i(9519),i(5791),i(2321),i(8074),i(783),i(9490),i(8773),i(6043),i(4643);x.v.ShadersStore.defaultPixelShader="#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#include<prePassDeclaration>[SCENE_MRT_COUNT]\n#include<oitDeclaration>\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#define RECIPROCAL_PI2 0.15915494\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<mainUVVaryingDeclaration>[1..7]\n#include<helperFunctions>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULARTERM)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)\n#endif\n#include<fresnelFunction>\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentMainFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef DECAL\nvec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);\n#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)\n#endif\n#include<depthPrePass>\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef DETAIL\nbaseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y);\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\n#endif\nlightmapColor.rgb*=vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\nvec4 refractionColor=vec4(0.,0.,0.,1.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\n#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=refractionLookup;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords);\n#endif\n#ifdef RGBDREFRACTION\nrefractionColor.rgb=fromRGBD(refractionColor);\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor.rgb=toGammaSpace(refractionColor.rgb);\n#endif\nrefractionColor.rgb*=vRefractionInfos.x;\n#endif\nvec4 reflectionColor=vec4(0.,0.,0.,1.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nvReflectionUVW.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias);\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW);\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords);\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor.rgb=toGammaSpace(reflectionColor.rgb);\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n#ifdef ALPHATEST\n#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS\nif (alpha<alphaCutOff)\ndiscard;\n#endif\n#ifndef ALPHABLEND\nalpha=1.0;\n#endif\n#endif\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor.rgb,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor.rgb;\n#else\ncolor.rgb+=lightmapColor.rgb;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\ncolor.a*=visibility;\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nfloat writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;\ngl_FragData[0]=color; \n#ifdef PREPASS_POSITION\ngl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);\n#endif\n#ifdef PREPASS_VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=abs(a-b);\nvelocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;\ngl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_IRRADIANCE\ngl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_DEPTH\ngl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); \n#endif\n#ifdef PREPASS_ALBEDO_SQRT\ngl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_REFLECTIVITY\n#if defined(SPECULARTERM)\n#if defined(SPECULAR)\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; \n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo;\n#endif\n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo;\n#endif\n#endif\n#endif\n#if !defined(PREPASS) || defined(WEBGL2)\ngl_FragColor=color;\n#endif\n#include<oitFragment>\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {\nfrontColor.rgb+=color.rgb*color.a*alphaMultiplier;\nfrontColor.a=1.0-alphaMultiplier*(1.0-color.a);\n} else {\nbackColor+=color;\n}\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n",i(5613);x.v.IncludesShadersStore.defaultVertexDeclaration="uniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\nuniform mat4 detailMatrix;\n#endif\n#include<decalVertexDeclaration>\n#define ADDITIONAL_VERTEX_DECLARATION\n",i(6467),i(7520),i(493),i(1063),i(7019),i(9478),i(2838),i(6343),i(9042),i(1542),i(9935),i(9901),i(8073),i(6757),i(9085),i(6883),i(6655),i(3206),i(8741),i(3088),i(2508),i(6255),i(5215),i(962),i(1101),i(9025);x.v.IncludesShadersStore.pointCloudVertex="#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n",i(5501);x.v.ShadersStore.defaultVertexShader="#include<__decl__defaultVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#include<uvAttributeDeclaration>[2..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\n#include<prePassVertexDeclaration>\n#include<mainUVVaryingDeclaration>[1..7]\n#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#if defined(SPECULARTERM)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)\n#endif\n#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));\nvNormalW=normalize(normalWorld*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\nvPositionW=vec3(worldPos);\n#include<prePassVertex>\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#include<uvVariableDeclaration>[2..7]\n#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#if defined(SPECULARTERM)\n#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)\n#endif\n#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n";var b=i(1434),T=i(6150),S=i(99);const E={effect:null,subMesh:null};class C extends f.H{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class A extends _.a{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}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 l.Wo(0,0,0),this.diffuseColor=new l.Wo(1,1,1),this.specularColor=new l.Wo(1,1,1),this.emissiveColor=new l.Wo(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._renderTargets=new r.t(16),this._worldViewProjectionMatrix=a.y3.Zero(),this._globalAmbientColor=new l.Wo(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new T.p(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new c.o,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),A.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),A.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!!(A.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(A.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===d.F.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==d.F.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(p.S.GetDefineNames,this._eventInfo),t.materialDefines=new C(this._eventInfo.defineNames));const n=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=n.getEngine();s._needNormals=m.G.PrepareDefinesForLights(n,e,s,!0,this._maxSimultaneousLights,this._disableLighting),m.G.PrepareDefinesForMultiview(n,s);const o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(m.G.PrepareDefinesForPrePass(n,s,this.canRenderToMRT&&!o),m.G.PrepareDefinesForOIT(n,s,o),s._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,s._needUVs=!1;for(let e=1;e<=6;++e)s["MAINUV"+e]=!1;if(n.texturesEnabled){if(s.DIFFUSEDIRECTUV=0,s.BUMPDIRECTUV=0,s.AMBIENTDIRECTUV=0,s.OPACITYDIRECTUV=0,s.EMISSIVEDIRECTUV=0,s.SPECULARDIRECTUV=0,s.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&A.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;m.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE")}else s.DIFFUSE=!1;if(this._ambientTexture&&A.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;m.G.PrepareDefinesForMergedUV(this._ambientTexture,s,"AMBIENT")}else s.AMBIENT=!1;if(this._opacityTexture&&A.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;m.G.PrepareDefinesForMergedUV(this._opacityTexture,s,"OPACITY"),s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&A.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(s._needNormals=!0,s.REFLECTION=!0,s.ROUGHNESS=this._roughness>0,s.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,s.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===g.x.INVCUBIC_MODE,s.REFLECTIONMAP_3D=this._reflectionTexture.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,s.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case g.x.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case g.x.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case g.x.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case g.x.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case g.x.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case g.x.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case g.x.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case g.x.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case g.x.CUBIC_MODE:case g.x.INVCUBIC_MODE:default:s.setReflectionMode("REFLECTIONMAP_CUBIC")}s.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else s.REFLECTION=!1,s.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&A.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;m.G.PrepareDefinesForMergedUV(this._emissiveTexture,s,"EMISSIVE")}else s.EMISSIVE=!1;if(this._lightmapTexture&&A.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;m.G.PrepareDefinesForMergedUV(this._lightmapTexture,s,"LIGHTMAP"),s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,s.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else s.LIGHTMAP=!1;if(this._specularTexture&&A.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;m.G.PrepareDefinesForMergedUV(this._specularTexture,s,"SPECULAR"),s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(n.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&A.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;m.G.PrepareDefinesForMergedUV(this._bumpTexture,s,"BUMP"),s.PARALLAX=this._useParallax,s.PARALLAXOCCLUSION=this._useParallaxOcclusion,s.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else s.BUMP=!1,s.PARALLAX=!1,s.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&A.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.REFRACTION=!0,s.REFRACTIONMAP_3D=this._refractionTexture.isCube,s.RGBDREFRACTION=this._refractionTexture.isRGBD,s.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else s.REFRACTION=!1;s.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else s.DIFFUSE=!1,s.AMBIENT=!1,s.OPACITY=!1,s.REFLECTION=!1,s.EMISSIVE=!1,s.LIGHTMAP=!1,s.BUMP=!1,s.REFRACTION=!1;s.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),s.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,s.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,s.SPECULAROVERALPHA=this._useSpecularOverAlpha,s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,s.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s),s.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,s.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}s._areFresnelDirty&&(A.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(s.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,s.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,s.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,s.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,s.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,s.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,s._needNormals=!0,s.FRESNEL=!0):s.FRESNEL=!1),m.G.PrepareDefinesForMisc(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,s),m.G.PrepareDefinesForFrameBoundValues(n,r,this,s,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=s,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),m.G.PrepareDefinesForAttributes(e,s,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let a=!1;if(s.isDirty){const i=s._areLightsDisposed;s.markAsProcessed();const o=new b.L;s.REFLECTION&&o.addFallback(0,"REFLECTION"),s.SPECULAR&&o.addFallback(0,"SPECULAR"),s.BUMP&&o.addFallback(0,"BUMP"),s.PARALLAX&&o.addFallback(1,"PARALLAX"),s.PARALLAXOCCLUSION&&o.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&o.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&o.addFallback(1,"FOG"),s.POINTSIZE&&o.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&o.addFallback(0,"LOGARITHMICDEPTH"),m.G.HandleFallbacksForShadows(s,o,this._maxSimultaneousLights),s.SPECULARTERM&&o.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&o.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&o.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&o.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&o.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&o.addFallback(4,"FRESNEL"),s.MULTIVIEW&&o.addFallback(0,"MULTIVIEW");const l=[h.o.PositionKind];s.NORMAL&&l.push(h.o.NormalKind),s.TANGENT&&l.push(h.o.TangentKind);for(let e=1;e<=6;++e)s["UV"+e]&&l.push(`uv${1===e?"":e}`);s.VERTEXCOLOR&&l.push(h.o.ColorKind),m.G.PrepareAttributesForBones(l,e,s,o),m.G.PrepareAttributesForInstances(l,s),m.G.PrepareAttributesForMorphTargets(l,e,s),m.G.PrepareAttributesForBakedVertexAnimation(l,e,s);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"],_=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],g=["Material","Scene","Mesh"];this._eventInfo.fallbacks=o,this._eventInfo.fallbackRank=0,this._eventInfo.defines=s,this._eventInfo.uniforms=f,this._eventInfo.attributes=l,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=g,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(p.S.PrepareEffect,this._eventInfo),c.o.AddUniforms(f),c.o.AddSamplers(_),u.$&&(u.$.PrepareUniforms(f,s),u.$.PrepareSamplers(_,s)),m.G.PrepareUniformsAndSamplersList({uniformsNames:f,uniformBuffersNames:g,samplers:_,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),(0,S.qx)(f);const v={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,f,g,_,s,l,v));const y=s.toString(),x=t.effect;let T=n.getEngine().createEffect(d,{attributes:l,uniformsNames:f,uniformBuffersNames:g,samplers:_,defines:y,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS},processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:s.PREPASS},r);if(this._eventInfo.customCode=void 0,T)if(this._onEffectCreatedObservable&&(E.effect=T,E.subMesh=t,this._onEffectCreatedObservable.notifyObservers(E)),this.allowShaderHotSwapping&&x&&!T.isReady()){if(T=x,s.markAsUnprocessed(),a=this.isFrozen,i)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(T,s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!a,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 n;const s=this.getScene(),r=i.materialDefines;if(!r)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,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const h=a._forceRebindOnNextCall||this._mustRebind(s,a,t.visibility);m.G.BindBonesParameters(t,a);const c=this._uniformBuffer;if(h){if(this.bindViewProjection(a),!c.useUbo||!this.isFrozen||!c.isSync||a._forceRebindOnNextCall){if(A.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(c.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),c.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&c.updateColor4("opacityParts",new l.Wo(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(c.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),c.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(c.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),c.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(c.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),c.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&A.DiffuseTextureEnabled&&(c.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),m.G.BindTextureMatrix(this._diffuseTexture,c,"diffuse")),this._ambientTexture&&A.AmbientTextureEnabled&&(c.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),m.G.BindTextureMatrix(this._ambientTexture,c,"ambient")),this._opacityTexture&&A.OpacityTextureEnabled&&(c.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),m.G.BindTextureMatrix(this._opacityTexture,c,"opacity")),this._hasAlphaChannel()&&c.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&A.ReflectionTextureEnabled&&(c.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),c.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;c.updateVector3("vReflectionPosition",e.boundingBoxPosition),c.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&A.EmissiveTextureEnabled&&(c.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),m.G.BindTextureMatrix(this._emissiveTexture,c,"emissive")),this._lightmapTexture&&A.LightmapTextureEnabled&&(c.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),m.G.BindTextureMatrix(this._lightmapTexture,c,"lightmap")),this._specularTexture&&A.SpecularTextureEnabled&&(c.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),m.G.BindTextureMatrix(this._specularTexture,c,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&A.BumpTextureEnabled&&(c.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),m.G.BindTextureMatrix(this._bumpTexture,c,"bump"),s._mirroredCameraPosition?c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&A.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(c.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),c.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;c.updateVector3("vRefractionPosition",e.boundingBoxPosition),c.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&c.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&c.updateColor4("vSpecularColor",this.specularColor,this.specularPower),c.updateColor3("vEmissiveColor",A.EmissiveTextureEnabled?this.emissiveColor:l.Wo.BlackReadOnly),c.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),c.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&A.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&A.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&A.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&A.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&A.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&A.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&A.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&A.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&A.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),(0,S.an)(a,this,s),this.bindEyePosition(a)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!h&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&m.G.BindLights(s,t,a,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==o.x.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(a),m.G.BindFogParameters(s,t,a),r.NUM_MORPH_INFLUENCERS&&m.G.BindMorphTargetParameters(t,a),r.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(n=t.bakedVertexAnimationManager)||void 0===n||n.bind(a,r.INSTANCES)),this.useLogarithmicDepth&&m.G.BindLogDepth(r,a,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),c.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){var i,n,s,r,o,a,l,h,c;t&&(null===(i=this._diffuseTexture)||void 0===i||i.dispose(),null===(n=this._ambientTexture)||void 0===n||n.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(r=this._reflectionTexture)||void 0===r||r.dispose(),null===(o=this._emissiveTexture)||void 0===o||o.dispose(),null===(a=this._specularTexture)||void 0===a||a.dispose(),null===(l=this._bumpTexture)||void 0===l||l.dispose(),null===(h=this._lightmapTexture)||void 0===h||h.dispose(),null===(c=this._refractionTexture)||void 0===c||c.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0){const i=s.p4.Clone((()=>new A(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return i.name=e,i.id=e,this.stencil.copyTo(i.stencil),i}static Parse(e,t,i){const n=s.p4.Parse((()=>new A(e.name,t)),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),n}static get DiffuseTextureEnabled(){return y.k.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){y.k.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return y.k.DetailTextureEnabled}static set DetailTextureEnabled(e){y.k.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return y.k.AmbientTextureEnabled}static set AmbientTextureEnabled(e){y.k.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return y.k.OpacityTextureEnabled}static set OpacityTextureEnabled(e){y.k.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return y.k.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){y.k.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return y.k.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){y.k.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return y.k.SpecularTextureEnabled}static set SpecularTextureEnabled(e){y.k.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return y.k.BumpTextureEnabled}static set BumpTextureEnabled(e){y.k.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return y.k.LightmapTextureEnabled}static set LightmapTextureEnabled(e){y.k.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return y.k.RefractionTextureEnabled}static set RefractionTextureEnabled(e){y.k.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return y.k.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){y.k.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return y.k.FresnelEnabled}static set FresnelEnabled(e){y.k.FresnelEnabled=e}}(0,n.gn)([(0,s.oU)("diffuseTexture")],A.prototype,"_diffuseTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],A.prototype,"diffuseTexture",void 0),(0,n.gn)([(0,s.oU)("ambientTexture")],A.prototype,"_ambientTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"ambientTexture",void 0),(0,n.gn)([(0,s.oU)("opacityTexture")],A.prototype,"_opacityTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],A.prototype,"opacityTexture",void 0),(0,n.gn)([(0,s.oU)("reflectionTexture")],A.prototype,"_reflectionTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"reflectionTexture",void 0),(0,n.gn)([(0,s.oU)("emissiveTexture")],A.prototype,"_emissiveTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"emissiveTexture",void 0),(0,n.gn)([(0,s.oU)("specularTexture")],A.prototype,"_specularTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"specularTexture",void 0),(0,n.gn)([(0,s.oU)("bumpTexture")],A.prototype,"_bumpTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"bumpTexture",void 0),(0,n.gn)([(0,s.oU)("lightmapTexture")],A.prototype,"_lightmapTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"lightmapTexture",void 0),(0,n.gn)([(0,s.oU)("refractionTexture")],A.prototype,"_refractionTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"refractionTexture",void 0),(0,n.gn)([(0,s.n9)("ambient")],A.prototype,"ambientColor",void 0),(0,n.gn)([(0,s.n9)("diffuse")],A.prototype,"diffuseColor",void 0),(0,n.gn)([(0,s.n9)("specular")],A.prototype,"specularColor",void 0),(0,n.gn)([(0,s.n9)("emissive")],A.prototype,"emissiveColor",void 0),(0,n.gn)([(0,s.qC)()],A.prototype,"specularPower",void 0),(0,n.gn)([(0,s.qC)("useAlphaFromDiffuseTexture")],A.prototype,"_useAlphaFromDiffuseTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],A.prototype,"useAlphaFromDiffuseTexture",void 0),(0,n.gn)([(0,s.qC)("useEmissiveAsIllumination")],A.prototype,"_useEmissiveAsIllumination",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"useEmissiveAsIllumination",void 0),(0,n.gn)([(0,s.qC)("linkEmissiveWithDiffuse")],A.prototype,"_linkEmissiveWithDiffuse",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"linkEmissiveWithDiffuse",void 0),(0,n.gn)([(0,s.qC)("useSpecularOverAlpha")],A.prototype,"_useSpecularOverAlpha",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"useSpecularOverAlpha",void 0),(0,n.gn)([(0,s.qC)("useReflectionOverAlpha")],A.prototype,"_useReflectionOverAlpha",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"useReflectionOverAlpha",void 0),(0,n.gn)([(0,s.qC)("disableLighting")],A.prototype,"_disableLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],A.prototype,"disableLighting",void 0),(0,n.gn)([(0,s.qC)("useObjectSpaceNormalMap")],A.prototype,"_useObjectSpaceNormalMap",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"useObjectSpaceNormalMap",void 0),(0,n.gn)([(0,s.qC)("useParallax")],A.prototype,"_useParallax",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"useParallax",void 0),(0,n.gn)([(0,s.qC)("useParallaxOcclusion")],A.prototype,"_useParallaxOcclusion",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"useParallaxOcclusion",void 0),(0,n.gn)([(0,s.qC)()],A.prototype,"parallaxScaleBias",void 0),(0,n.gn)([(0,s.qC)("roughness")],A.prototype,"_roughness",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"roughness",void 0),(0,n.gn)([(0,s.qC)()],A.prototype,"indexOfRefraction",void 0),(0,n.gn)([(0,s.qC)()],A.prototype,"invertRefractionY",void 0),(0,n.gn)([(0,s.qC)()],A.prototype,"alphaCutOff",void 0),(0,n.gn)([(0,s.qC)("useLightmapAsShadowmap")],A.prototype,"_useLightmapAsShadowmap",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"useLightmapAsShadowmap",void 0),(0,n.gn)([(0,s.qQ)("diffuseFresnelParameters")],A.prototype,"_diffuseFresnelParameters",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsFresnelDirty")],A.prototype,"diffuseFresnelParameters",void 0),(0,n.gn)([(0,s.qQ)("opacityFresnelParameters")],A.prototype,"_opacityFresnelParameters",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsFresnelAndMiscDirty")],A.prototype,"opacityFresnelParameters",void 0),(0,n.gn)([(0,s.qQ)("reflectionFresnelParameters")],A.prototype,"_reflectionFresnelParameters",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsFresnelDirty")],A.prototype,"reflectionFresnelParameters",void 0),(0,n.gn)([(0,s.qQ)("refractionFresnelParameters")],A.prototype,"_refractionFresnelParameters",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsFresnelDirty")],A.prototype,"refractionFresnelParameters",void 0),(0,n.gn)([(0,s.qQ)("emissiveFresnelParameters")],A.prototype,"_emissiveFresnelParameters",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsFresnelDirty")],A.prototype,"emissiveFresnelParameters",void 0),(0,n.gn)([(0,s.qC)("useReflectionFresnelFromSpecular")],A.prototype,"_useReflectionFresnelFromSpecular",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsFresnelDirty")],A.prototype,"useReflectionFresnelFromSpecular",void 0),(0,n.gn)([(0,s.qC)("useGlossinessFromSpecularMapAlpha")],A.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"useGlossinessFromSpecularMapAlpha",void 0),(0,n.gn)([(0,s.qC)("maxSimultaneousLights")],A.prototype,"_maxSimultaneousLights",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],A.prototype,"maxSimultaneousLights",void 0),(0,n.gn)([(0,s.qC)("invertNormalMapX")],A.prototype,"_invertNormalMapX",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"invertNormalMapX",void 0),(0,n.gn)([(0,s.qC)("invertNormalMapY")],A.prototype,"_invertNormalMapY",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"invertNormalMapY",void 0),(0,n.gn)([(0,s.qC)("twoSidedLighting")],A.prototype,"_twoSidedLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],A.prototype,"twoSidedLighting",void 0),(0,n.gn)([(0,s.qC)()],A.prototype,"useLogarithmicDepth",null),(0,v.H)("BABYLON.StandardMaterial",A),o.x.DefaultMaterialFactory=e=>new A("default material",e)},3743:(e,t,i)=>{i.d(t,{M:()=>r});var n=i(2722),s=i(7257);i(4901);class r{constructor(e,t,i,n,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=null!=n?n:"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const i=this._uniformLocationPointer-e;for(let e=0;e<i;e++)this._data.push(0)}}addUniform(e,t,i=0){if(this._noUBO)return;if(void 0!==this._uniformLocations[e])return;let n;if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,n=[];for(let e=0;e<t;e++)n.push(0)}else{if(t instanceof Array)n=t,t=n.length;else{n=[];for(let e=0;e<t;e++)n.push(0)}this._fillAlignment(t)}this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t;for(let e=0;e<t;e++)this._data.push(n[e]);this._needSync=!0}addMatrix(e,t){this.addUniform(e,Array.prototype.slice.call(t.toArray()))}addFloat2(e,t,i){const n=[t,i];this.addUniform(e,n)}addFloat3(e,t,i,n){const s=[t,i,n];this.addUniform(e,s)}addColor3(e,t){const i=[t.r,t.g,t.b];this.addUniform(e,i)}addColor4(e,t,i){const n=[t.r,t.g,t.b,i];this.addUniform(e,n)}addVector3(e,t){const i=[t.x,t.y,t.z];this.addUniform(e,i)}addMatrix3x3(e){this.addUniform(e,12)}addMatrix2x2(e){this.addUniform(e,8)}create(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)}_rebuild(){!this._noUBO&&this._bufferData&&(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData):this._buffer=this._engine.createUniformBuffer(this._bufferData),this._engine._features.trackUbosInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}_copyBuffer(e,t){for(let i=0;i<e.length;++i)t[i]=e[i]}update(){if(!this._noUBO)if(this.bindUniformBuffer(),this._buffer)if(this._dynamic||this._needSync){if(this._buffers&&this._buffers.length>1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(r._UpdatedUbosInFrame[this._name]||(r._UpdatedUbosInFrame[this._name]=0),r._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()}_checkNewFrame(){this._engine._features.trackUbosInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(void 0===r){if(this._buffer)return void n.Y.Error("Cannot add an uniform after UBO has been created.");this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e<i;e++)this._bufferData[r+e]=t[e];else{let e=!1;for(let n=0;n<i;n++)(16===i&&!this._engine._features.uniformBufferHardCheckMatrix||this._bufferData[r+n]!==s.w1.FloatRound(t[n]))&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[r+n]=t[n]);this._needSync=this._needSync||e}}updateUniformArray(e,t,i){this._checkNewFrame();const r=this._uniformLocations[e];if(void 0===r)return void n.Y.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.");this._buffer||this.create();const o=this._uniformArraySizes[e];if(this._dynamic)for(let e=0;e<i;e++)this._bufferData[r+e]=t[e];else{let e=!1,n=0,a=0;for(let l=0;l<i;l++)if(this._bufferData[r+4*a+n]!==s.w1.FloatRound(t[l])&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[r+4*a+n]=t[l]),n++,n===o.strideSize){for(;n<4;n++)this._bufferData[r+4*a+n]=0;n=0,a++}this._needSync=this._needSync||e}}_cacheMatrix(e,t){this._checkNewFrame();const i=this._valueCache[e],n=t.updateFlag;return(void 0===i||i!==n)&&(this._valueCache[e]=n,!0)}_updateMatrix3x3ForUniform(e,t){for(let e=0;e<3;e++)r._TempBuffer[4*e]=t[3*e],r._TempBuffer[4*e+1]=t[3*e+1],r._TempBuffer[4*e+2]=t[3*e+2],r._TempBuffer[4*e+3]=0;this.updateUniform(e,r._TempBuffer,12)}_updateMatrix3x3ForEffect(e,t){this._currentEffect.setMatrix3x3(e,t)}_updateMatrix2x2ForEffect(e,t){this._currentEffect.setMatrix2x2(e,t)}_updateMatrix2x2ForUniform(e,t){for(let e=0;e<2;e++)r._TempBuffer[4*e]=t[2*e],r._TempBuffer[4*e+1]=t[2*e+1],r._TempBuffer[4*e+2]=0,r._TempBuffer[4*e+3]=0;this.updateUniform(e,r._TempBuffer,8)}_updateFloatForEffect(e,t){this._currentEffect.setFloat(e,t)}_updateFloatForUniform(e,t){r._TempBuffer[0]=t,this.updateUniform(e,r._TempBuffer,1)}_updateFloat2ForEffect(e,t,i,n=""){this._currentEffect.setFloat2(e+n,t,i)}_updateFloat2ForUniform(e,t,i){r._TempBuffer[0]=t,r._TempBuffer[1]=i,this.updateUniform(e,r._TempBuffer,2)}_updateFloat3ForEffect(e,t,i,n,s=""){this._currentEffect.setFloat3(e+s,t,i,n)}_updateFloat3ForUniform(e,t,i,n){r._TempBuffer[0]=t,r._TempBuffer[1]=i,r._TempBuffer[2]=n,this.updateUniform(e,r._TempBuffer,3)}_updateFloat4ForEffect(e,t,i,n,s,r=""){this._currentEffect.setFloat4(e+r,t,i,n,s)}_updateFloat4ForUniform(e,t,i,n,s){r._TempBuffer[0]=t,r._TempBuffer[1]=i,r._TempBuffer[2]=n,r._TempBuffer[3]=s,this.updateUniform(e,r._TempBuffer,4)}_updateFloatArrayForEffect(e,t){this._currentEffect.setFloatArray(e,t)}_updateFloatArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateArrayForEffect(e,t){this._currentEffect.setArray(e,t)}_updateArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateIntArrayForEffect(e,t){this._currentEffect.setIntArray(e,t)}_updateIntArrayForUniform(e,t){r._TempBufferInt32View.set(t),this.updateUniformArray(e,r._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){r._TempBufferUInt32View.set(t),this.updateUniformArray(e,r._TempBuffer,t.length)}_updateMatrixForEffect(e,t){this._currentEffect.setMatrix(e,t)}_updateMatrixForUniform(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.toArray(),16)}_updateMatricesForEffect(e,t){this._currentEffect.setMatrices(e,t)}_updateMatricesForUniform(e,t){this.updateUniform(e,t,t.length)}_updateVector3ForEffect(e,t){this._currentEffect.setVector3(e,t)}_updateVector3ForUniform(e,t){r._TempBuffer[0]=t.x,r._TempBuffer[1]=t.y,r._TempBuffer[2]=t.z,this.updateUniform(e,r._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){r._TempBuffer[0]=t.x,r._TempBuffer[1]=t.y,r._TempBuffer[2]=t.z,r._TempBuffer[3]=t.w,this.updateUniform(e,r._TempBuffer,4)}_updateColor3ForEffect(e,t,i=""){this._currentEffect.setColor3(e+i,t)}_updateColor3ForUniform(e,t){r._TempBuffer[0]=t.r,r._TempBuffer[1]=t.g,r._TempBuffer[2]=t.b,this.updateUniform(e,r._TempBuffer,3)}_updateColor4ForEffect(e,t,i,n=""){this._currentEffect.setColor4(e+n,t,i)}_updateDirectColor4ForEffect(e,t,i=""){this._currentEffect.setDirectColor4(e+i,t)}_updateColor4ForUniform(e,t,i){r._TempBuffer[0]=t.r,r._TempBuffer[1]=t.g,r._TempBuffer[2]=t.b,r._TempBuffer[3]=i,this.updateUniform(e,r._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){r._TempBuffer[0]=t.r,r._TempBuffer[1]=t.g,r._TempBuffer[2]=t.b,r._TempBuffer[3]=t.a,this.updateUniform(e,r._TempBuffer,4)}_updateIntForEffect(e,t,i=""){this._currentEffect.setInt(e+i,t)}_updateIntForUniform(e,t){r._TempBufferInt32View[0]=t,this.updateUniform(e,r._TempBuffer,1)}_updateInt2ForEffect(e,t,i,n=""){this._currentEffect.setInt2(e+n,t,i)}_updateInt2ForUniform(e,t,i){r._TempBufferInt32View[0]=t,r._TempBufferInt32View[1]=i,this.updateUniform(e,r._TempBuffer,2)}_updateInt3ForEffect(e,t,i,n,s=""){this._currentEffect.setInt3(e+s,t,i,n)}_updateInt3ForUniform(e,t,i,n){r._TempBufferInt32View[0]=t,r._TempBufferInt32View[1]=i,r._TempBufferInt32View[2]=n,this.updateUniform(e,r._TempBuffer,3)}_updateInt4ForEffect(e,t,i,n,s,r=""){this._currentEffect.setInt4(e+r,t,i,n,s)}_updateInt4ForUniform(e,t,i,n,s){r._TempBufferInt32View[0]=t,r._TempBufferInt32View[1]=i,r._TempBufferInt32View[2]=n,r._TempBufferInt32View[3]=s,this.updateUniform(e,r._TempBuffer,4)}_updateUIntForEffect(e,t,i=""){this._currentEffect.setUInt(e+i,t)}_updateUIntForUniform(e,t){r._TempBufferUInt32View[0]=t,this.updateUniform(e,r._TempBuffer,1)}_updateUInt2ForEffect(e,t,i,n=""){this._currentEffect.setUInt2(e+n,t,i)}_updateUInt2ForUniform(e,t,i){r._TempBufferUInt32View[0]=t,r._TempBufferUInt32View[1]=i,this.updateUniform(e,r._TempBuffer,2)}_updateUInt3ForEffect(e,t,i,n,s=""){this._currentEffect.setUInt3(e+s,t,i,n)}_updateUInt3ForUniform(e,t,i,n){r._TempBufferUInt32View[0]=t,r._TempBufferUInt32View[1]=i,r._TempBufferUInt32View[2]=n,this.updateUniform(e,r._TempBuffer,3)}_updateUInt4ForEffect(e,t,i,n,s,r=""){this._currentEffect.setUInt4(e+r,t,i,n,s)}_updateUInt4ForUniform(e,t,i,n,s){r._TempBufferUInt32View[0]=t,r._TempBufferUInt32View[1]=i,r._TempBufferUInt32View[2]=n,r._TempBufferUInt32View[3]=s,this.updateUniform(e,r._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(e,t)}updateUniformDirectly(e,t){this.updateUniform(e,t,t.length),this.update()}bindToEffect(e,t){this._currentEffect=e,this._currentEffectName=t}bindUniformBuffer(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)}unbindEffect(){this._currentEffect=void 0,this._currentEffectName=void 0}setDataBuffer(e){if(!this._buffers)return this._buffer===e;for(let t=0;t<this._buffers.length;++t)if(this._buffers[t][0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,!0;return!1}dispose(){if(this._noUBO)return;const e=this._engine._uniformBuffers,t=e.indexOf(this);if(-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._features.trackUbosInFrame&&this._buffers)for(let e=0;e<this._buffers.length;++e){const t=this._buffers[e][0];this._engine._releaseBuffer(t)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}}r._UpdatedUbosInFrame={},r._MAX_UNIFORM_SIZE=256,r._TempBuffer=new Float32Array(r._MAX_UNIFORM_SIZE),r._TempBufferInt32View=new Int32Array(r._TempBuffer.buffer),r._TempBufferUInt32View=new Uint32Array(r._TempBuffer.buffer)},5203:(e,t,i)=>{i.d(t,{RD:()=>o,T:()=>n,c7:()=>s});var n,s,r=i(4141);!function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(n||(n={}));class o{}o.X=new r.P(1,0,0),o.Y=new r.P(0,1,0),o.Z=new r.P(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(s||(s={}))},4649:(e,t,i)=>{i.d(t,{HE:()=>d,Wo:()=>u,zZ:()=>p});var n=i(1128),s=i(1341),r=i(5860),o=i(2208);function a(e){return Math.pow(e,s.Nn)}function l(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function h(e){return Math.pow(e,s.zp)}function c(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}class u{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return e=397*e^(255*this.g|0),e=397*e^(255*this.b|0),e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return u.FromArrayToRef(e,t,this),this}toColor4(e=1){return new d(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new u(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 u(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=n.R.Clamp(this.r,e,t),i.g=n.R.Clamp(this.g,e,t),i.b=n.R.Clamp(this.b,e,t),this}add(e){return new u(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 u(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 u(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}toHexString(){const e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+n.R.ToHex(e)+n.R.ToHex(t)+n.R.ToHex(i)}toHSV(){const e=new u;return this.toHSVToRef(e),e}toHSVToRef(e){const t=this.r,i=this.g,n=this.b,s=Math.max(t,i,n),r=Math.min(t,i,n);let o=0,a=0;const l=s,h=s-r;0!==s&&(a=h/s),s!=r&&(s==t?(o=(i-n)/h,i<n&&(o+=6)):s==i?o=(n-t)/h+2:s==n&&(o=(t-i)/h+4),o*=60),e.r=o,e.g=a,e.b=l}toLinearSpace(e=!1){const t=new u;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=l(this.r),e.g=l(this.g),e.b=l(this.b)):(e.r=a(this.r),e.g=a(this.g),e.b=a(this.b)),this}toGammaSpace(e=!1){const t=new u;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=c(this.r),e.g=c(this.g),e.b=c(this.b)):(e.r=h(this.r),e.g=h(this.g),e.b=h(this.b)),this}static HSVtoRGBToRef(e,t,i,n){const s=i*t,r=e/60,o=s*(1-Math.abs(r%2-1));let a=0,l=0,h=0;r>=0&&r<=1?(a=s,l=o):r>=1&&r<=2?(a=o,l=s):r>=2&&r<=3?(l=s,h=o):r>=3&&r<=4?(l=o,h=s):r>=4&&r<=5?(a=o,h=s):r>=5&&r<=6&&(a=s,h=o);const c=i-s;n.set(a+c,l+c,h+c)}static FromHSV(e,t,i){const n=new u(0,0,0);return u.HSVtoRGBToRef(e,t,i,n),n}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new u(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16);return u.FromInts(t,i,n)}static FromArray(e,t=0){return new u(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 u(e/255,t/255,i/255)}static Lerp(e,t,i){const n=new u(0,0,0);return u.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,n,s){const r=s*s,o=s*r,a=2*o-3*r+1,l=-2*o+3*r,h=o-2*r+s,c=o-r,d=e.r*a+i.r*l+t.r*h+n.r*c,p=e.g*a+i.g*l+t.g*h+n.g*c,f=e.b*a+i.b*l+t.b*h+n.b*c;return new u(d,p,f)}static Hermite1stDerivative(e,t,i,n,s){const r=u.Black();return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const o=s*s;r.r=6*(o-s)*e.r+(3*o-4*s+1)*t.r+6*(-o+s)*i.r+(3*o-2*s)*n.r,r.g=6*(o-s)*e.g+(3*o-4*s+1)*t.g+6*(-o+s)*i.g+(3*o-2*s)*n.g,r.b=6*(o-s)*e.b+(3*o-4*s+1)*t.b+6*(-o+s)*i.b+(3*o-2*s)*n.b}static Red(){return new u(1,0,0)}static Green(){return new u(0,1,0)}static Blue(){return new u(0,0,1)}static Black(){return new u(0,0,0)}static get BlackReadOnly(){return u._BlackReadOnly}static White(){return new u(1,1,1)}static Purple(){return new u(.5,0,.5)}static Magenta(){return new u(1,0,1)}static Yellow(){return new u(1,1,0)}static Gray(){return new u(.5,.5,.5)}static Teal(){return new u(0,1,1)}static Random(){return new u(Math.random(),Math.random(),Math.random())}}u._BlackReadOnly=u.Black();class d{constructor(e=0,t=0,i=0,n=1){this.r=e,this.g=t,this.b=i,this.a=n}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return d.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 d(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new d(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 d(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=n.R.Clamp(this.r,e,t),i.g=n.R.Clamp(this.g,e,t),i.b=n.R.Clamp(this.b,e,t),i.a=n.R.Clamp(this.a,e,t),this}multiply(e){return new d(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=255*this.r|0;return e=397*e^(255*this.g|0),e=397*e^(255*this.b|0),e=397*e^(255*this.a|0),e}clone(){return new d(this.r,this.g,this.b,this.a)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,n){return this.r=e,this.g=t,this.b=i,this.a=n,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+n.R.ToHex(t)+n.R.ToHex(i)+n.R.ToHex(s);const r=Math.round(255*this.a);return"#"+n.R.ToHex(t)+n.R.ToHex(i)+n.R.ToHex(s)+n.R.ToHex(r)}toLinearSpace(e=!1){const t=new d;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=l(this.r),e.g=l(this.g),e.b=l(this.b)):(e.r=a(this.r),e.g=a(this.g),e.b=a(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new d;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=c(this.r),e.g=c(this.g),e.b=c(this.b)):(e.r=h(this.r),e.g=h(this.g),e.b=h(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new d(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16),s=9===e.length?parseInt(e.substring(7,9),16):255;return d.FromInts(t,i,n,s)}static Lerp(e,t,i){const n=new d(0,0,0,0);return d.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i,n.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,n,s){const r=s*s,o=s*r,a=2*o-3*r+1,l=-2*o+3*r,h=o-2*r+s,c=o-r,u=e.r*a+i.r*l+t.r*h+n.r*c,p=e.g*a+i.g*l+t.g*h+n.g*c,f=e.b*a+i.b*l+t.b*h+n.b*c,_=e.a*a+i.a*l+t.a*h+n.a*c;return new d(u,p,f,_)}static Hermite1stDerivative(e,t,i,n,s){const r=new d;return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const o=s*s;r.r=6*(o-s)*e.r+(3*o-4*s+1)*t.r+6*(-o+s)*i.r+(3*o-2*s)*n.r,r.g=6*(o-s)*e.g+(3*o-4*s+1)*t.g+6*(-o+s)*i.g+(3*o-2*s)*n.g,r.b=6*(o-s)*e.b+(3*o-4*s+1)*t.b+6*(-o+s)*i.b+(3*o-2*s)*n.b,r.a=6*(o-s)*e.a+(3*o-4*s+1)*t.a+6*(-o+s)*i.a+(3*o-2*s)*n.a}static FromColor3(e,t=1){return new d(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new d(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,n){return new d(e/255,t/255,i/255,n/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;i<e.length;i+=3){const n=i/3*4;t[n]=e[i],t[n+1]=e[i+1],t[n+2]=e[i+2],t[n+3]=1}return t}return e}}class p{}p.Color3=r.B.BuildArray(3,u.Black),p.Color4=r.B.BuildArray(3,(()=>new d(0,0,0,0))),(0,o.H)("BABYLON.Color3",u),(0,o.H)("BABYLON.Color4",d)},1341:(e,t,i)=>{i.d(t,{Nn:()=>s,Q_:()=>r,kn:()=>o,zp:()=>n});const n=1/2.2,s=2.2,r=(1+Math.sqrt(5))/2,o=.001},1560:(e,t,i)=>{i.d(t,{i:()=>s});var n=i(142);class s{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new n.J(0,0,0,0));return s.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){s.GetNearPlaneToRef(e,t[0]),s.GetFarPlaneToRef(e,t[1]),s.GetLeftPlaneToRef(e,t[2]),s.GetRightPlaneToRef(e,t[3]),s.GetTopPlaneToRef(e,t[4]),s.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}}},1372:(e,t,i)=>{i.d(t,{k:()=>l,y:()=>a});var n=i(9472),s=i(4141),r=i(3956);class o{static extractMinAndMaxIndexed(e,t,i,n,s,r){for(let o=i;o<i+n;o++){const i=3*t[o],n=e[i],a=e[i+1],l=e[i+2];s.minimizeInPlaceFromFloats(n,a,l),r.maximizeInPlaceFromFloats(n,a,l)}}static extractMinAndMax(e,t,i,n,s,r){for(let o=t,a=t*n;o<t+i;o++,a+=n){const t=e[a],i=e[a+1],n=e[a+2];s.minimizeInPlaceFromFloats(t,i,n),r.maximizeInPlaceFromFloats(t,i,n)}}}function a(e,t,i,n,r=null){const a=new s.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),l=new s.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return o.extractMinAndMaxIndexed(e,t,i,n,a,l),r&&(a.x-=a.x*r.x+r.y,a.y-=a.y*r.x+r.y,a.z-=a.z*r.x+r.y,l.x+=l.x*r.x+r.y,l.y+=l.y*r.x+r.y,l.z+=l.z*r.x+r.y),{minimum:a,maximum:l}}function l(e,t,i,n=null,r){const a=new s.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),l=new s.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return r||(r=3),o.extractMinAndMax(e,t,i,r,a,l),n&&(a.x-=a.x*n.x+n.y,a.y-=a.y*n.x+n.y,a.z-=a.z*n.x+n.y,l.x+=l.x*n.x+n.y,l.y+=l.y*n.x+n.y,l.z+=l.z*n.x+n.y),{minimum:a,maximum:l}}(0,n.gn)([r.G6.filter(((...[e,t])=>!Array.isArray(e)&&!Array.isArray(t)))],o,"extractMinAndMaxIndexed",null),(0,n.gn)([r.G6.filter(((...[e])=>!Array.isArray(e)))],o,"extractMinAndMax",null)},6913:(e,t,i)=>{i.d(t,{RZ:()=>a.RZ,Q:()=>a.Q,RD:()=>n.RD,hr:()=>a.hr,Wo:()=>s.Wo,HE:()=>s.HE,c7:()=>n.c7,j_:()=>a.j_,kn:()=>r.kn,iW:()=>o.i,y3:()=>c.y3,i5:()=>a.i5,Q_:()=>r.Q_,ZZ:()=>a.ZZ,$B:()=>a.$B,JO:()=>l.J,eN:()=>d,$S:()=>u,_f:()=>c._f,$u:()=>h.$,T:()=>n.T,zZ:()=>s.zZ,jp:()=>c.jp,zp:()=>r.zp,Nn:()=>r.Nn,FM:()=>c.FM,P:()=>c.P,Lt:()=>c.Lt,l_:()=>p.l});var n=i(5203),s=i(4649),r=i(1341),o=i(1560),a=i(1277),l=i(142),h=i(9697),c=i(4141);class u{constructor(e=c.P.Zero(),t=c.P.Up()){this.position=e,this.normal=t}clone(){return new u(this.position.clone(),this.normal.clone())}}class d{constructor(e=c.P.Zero(),t=c.P.Up(),i=c.FM.Zero()){this.position=e,this.normal=t,this.uv=i}clone(){return new d(this.position.clone(),this.normal.clone(),this.uv.clone())}}var p=i(4538)},1277:(e,t,i)=>{i.d(t,{$B:()=>u,Q:()=>h,RZ:()=>l,ZZ:()=>c,hr:()=>a,i5:()=>n,j_:()=>d});var n,s=i(1128),r=i(4141),o=i(1341);!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(n||(n={}));class a{static Interpolate(e,t,i,n,s){const r=1-3*n+3*t,o=3*n-6*t,a=3*t;let l=e;for(let t=0;t<5;t++){const t=l*l;l-=1/(3*r*t+2*o*l+a)*(r*(t*l)+o*t+a*l-e),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*s+Math.pow(l,3)}}class l{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),n=Math.atan2(i.y,i.x);return new l(n)}static FromRadians(e){return new l(e)}static FromDegrees(e){return new l(e*Math.PI/180)}}class h{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),o=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,a=(s-Math.pow(i.x,2)-Math.pow(i.y,2))/2,h=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new r.FM((o*(t.y-i.y)-a*(e.y-t.y))/h,((e.x-t.x)*a-(t.x-i.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);const c=this.startAngle.degrees();let u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),d=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-c>180&&(u-=360),u-c<-180&&(u+=360),d-u>180&&(d-=360),d-u<-180&&(d+=360),this.orientation=u-c<0?n.CW:n.CCW,this.angle=l.FromDegrees(this.orientation===n.CW?c-d:d-c)}}class c{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r.FM(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new r.FM(e,t),n=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(n).length(),this}addArcTo(e,t,i,s,o=36){if(this.closed)return this;const a=this._points[this._points.length-1],l=new r.FM(e,t),c=new r.FM(i,s),u=new h(a,l,c);let d=u.angle.radians()/o;u.orientation===n.CW&&(d*=-1);let p=u.startAngle.radians()+d;for(let e=0;e<o;e++){const e=Math.cos(p)*u.radius+u.centerPoint.x,t=Math.sin(p)*u.radius+u.centerPoint.y;this.addLineTo(e,t),p+=d}return this}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e}getPoints(){return this._points}getPointAtLengthPosition(e){if(e<0||e>1)return r.FM.Zero();const t=e*this.length();let i=0;for(let e=0;e<this._points.length;e++){const n=(e+1)%this._points.length,s=this._points[e],o=this._points[n].subtract(s),a=o.length()+i;if(t>=i&&t<=a){const e=o.normalize(),n=t-i;return new r.FM(s.x+e.x*n,s.y+e.y*n)}i=a}return r.FM.Zero()}static StartingAt(e,t){return new c(e,t)}}class u{constructor(e,t=null,i,n=!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:r.P.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:r.y3.Identity()};for(let t=0;t<e.length;t++)this._curve[t]=e[t].clone();this._raw=i||!1,this._alignTangentsWithPath=n,this._compute(t,n)}getCurve(){return this._curve}getPoints(){return this._curve}length(){return this._distances[this._distances.length-1]}getTangents(){return this._tangents}getNormals(){return this._normals}getBinormals(){return this._binormals}getDistances(){return this._distances}getPointAt(e){return this._updatePointAtData(e).point}getTangentAt(e,t=!1){return this._updatePointAtData(e,t),t?r.P.TransformCoordinates(r.P.Forward(),this._pointAtData.interpolationMatrix):this._tangents[this._pointAtData.previousPointArrayIndex]}getNormalAt(e,t=!1){return this._updatePointAtData(e,t),t?r.P.TransformCoordinates(r.P.Right(),this._pointAtData.interpolationMatrix):this._normals[this._pointAtData.previousPointArrayIndex]}getBinormalAt(e,t=!1){return this._updatePointAtData(e,t),t?r.P.TransformCoordinates(r.P.UpReadOnly,this._pointAtData.interpolationMatrix):this._binormals[this._pointAtData.previousPointArrayIndex]}getDistanceAt(e){return this.length()*e}getPreviousPointIndexAt(e){return this._updatePointAtData(e),this._pointAtData.previousPointArrayIndex}getSubPositionAt(e){return this._updatePointAtData(e),this._pointAtData.subPosition}getClosestPositionTo(e){let t=Number.MAX_VALUE,i=0;for(let n=0;n<this._curve.length-1;n++){const s=this._curve[n+0],o=this._curve[n+1].subtract(s).normalize(),a=this._distances[n+1]-this._distances[n+0],l=Math.min(Math.max(r.P.Dot(o,e.subtract(s).normalize()),0)*r.P.Distance(s,e)/a,1),h=r.P.Distance(s.add(o.scale(l*a)),e);h<t&&(t=h,i=(this._distances[n+0]+a*l)/this.length())}return i}slice(e=0,t=1){if(e<0&&(e=1- -1*e%1),t<0&&(t=1- -1*t%1),e>t){const i=e;e=t,t=i}const i=this.getCurve(),n=this.getPointAt(e);let s=this.getPreviousPointIndexAt(e);const r=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,a=[];return 0!==e&&(s++,a.push(n)),a.push(...i.slice(s,o)),1===t&&1!==e||a.push(r),new u(a,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;t<e.length;t++)this._curve[t].x=e[t].x,this._curve[t].y=e[t].y,this._curve[t].z=e[t].z;return this._compute(t,i),this}_compute(e,t=!1){const i=this._curve.length;if(i<2)return;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();const n=this._tangents[0],s=this._normalVector(n,e);let o,a,l,h,c;this._normals[0]=s,this._raw||this._normals[0].normalize(),this._binormals[0]=r.P.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(let e=1;e<i;e++)o=this._getLastNonNullVector(e),e<i-1&&(a=this._getFirstNonNullVector(e),this._tangents[e]=t?a:o.add(a),this._tangents[e].normalize()),this._distances[e]=this._distances[e-1]+this._curve[e].subtract(this._curve[e-1]).length(),l=this._tangents[e],c=this._binormals[e-1],this._normals[e]=r.P.Cross(c,l),this._raw||(0===this._normals[e].length()?(h=this._normals[e-1],this._normals[e]=h.clone()):this._normals[e].normalize()),this._binormals[e]=r.P.Cross(l,this._normals[e]),this._raw||this._binormals[e].normalize();this._pointAtData.id=NaN}_getFirstNonNullVector(e){let t=1,i=this._curve[e+t].subtract(this._curve[e]);for(;0===i.length()&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i}_getLastNonNullVector(e){let t=1,i=this._curve[e].subtract(this._curve[e-t]);for(;0===i.length()&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,n=e.length();if(0===n&&(n=1),null==t){let t;t=s.R.WithinEpsilon(Math.abs(e.y)/n,1,o.kn)?s.R.WithinEpsilon(Math.abs(e.x)/n,1,o.kn)?s.R.WithinEpsilon(Math.abs(e.z)/n,1,o.kn)?r.P.Zero():new r.P(0,0,1):new r.P(1,0,0):new r.P(0,-1,0),i=r.P.Cross(e,t)}else i=r.P.Cross(e,t),r.P.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 n,s=i[0],o=0;const a=e*this.length();for(let l=1;l<i.length;l++){n=i[l];const h=r.P.Distance(s,n);if(o+=h,o===a)return this._setPointAtData(e,1,n,l,t);if(o>a){const i=(o-a)/h,r=s.subtract(n),c=n.add(r.scaleInPlace(i));return this._setPointAtData(e,1-i,c,l-1,t)}s=n}return this._pointAtData}_setPointAtData(e,t,i,n,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=n,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=r.y3.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),n=this._normals[e].clone(),s=this._binormals[e].clone(),o=this._tangents[t].clone(),a=this._normals[t].clone(),l=this._binormals[t].clone(),h=r._f.RotationQuaternionFromAxis(n,s,i),c=r._f.RotationQuaternionFromAxis(a,l,o);r._f.Slerp(h,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class d{static CreateQuadraticBezier(e,t,i,n){n=n>2?n:3;const s=new Array,o=(e,t,i,n)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*n;for(let a=0;a<=n;a++)s.push(new r.P(o(a/n,e.x,t.x,i.x),o(a/n,e.y,t.y,i.y),o(a/n,e.z,t.z,i.z)));return new d(s)}static CreateCubicBezier(e,t,i,n,s){s=s>3?s:4;const o=new Array,a=(e,t,i,n,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*n+e*e*e*s;for(let l=0;l<=s;l++)o.push(new r.P(a(l/s,e.x,t.x,i.x,n.x),a(l/s,e.y,t.y,i.y,n.y),a(l/s,e.z,t.z,i.z,n.z)));return new d(o)}static CreateHermiteSpline(e,t,i,n,s){const o=new Array,a=1/s;for(let l=0;l<=s;l++)o.push(r.P.Hermite(e,t,i,n,l*a));return new d(o)}static CreateCatmullRomSpline(e,t,i){const n=new Array,s=1/t;let o=0;if(i){const i=e.length;for(let a=0;a<i;a++){o=0;for(let l=0;l<t;l++)n.push(r.P.CatmullRom(e[a%i],e[(a+1)%i],e[(a+2)%i],e[(a+3)%i],o)),o+=s}n.push(n[0])}else{const i=new Array;i.push(e[0].clone()),Array.prototype.push.apply(i,e),i.push(e[e.length-1].clone());let a=0;for(;a<i.length-3;a++){o=0;for(let e=0;e<t;e++)n.push(r.P.CatmullRom(i[a],i[a+1],i[a+2],i[a+3],o)),o+=s}a--,n.push(r.P.CatmullRom(i[a],i[a+1],i[a+2],i[a+3],o))}return new d(n)}static ArcThru3Points(e,t,i,n=32,s=!1,o=!1){const a=new Array,l=t.subtract(e),h=i.subtract(t),c=e.subtract(i),u=r.P.Cross(l,h),p=u.length();if(p<Math.pow(10,-8))return new d(a);const f=l.lengthSquared(),_=h.lengthSquared(),m=c.lengthSquared(),g=u.lengthSquared(),v=.5*l.length()*h.length()*c.length()/p,y=-.5*_*r.P.Dot(l,c)/g,x=-.5*m*r.P.Dot(l,h)/g,b=-.5*f*r.P.Dot(h,c)/g,T=e.scale(y).add(t.scale(x)).add(i.scale(b)),S=e.subtract(T).normalize(),E=r.P.Cross(u,S).normalize();if(o){const t=2*Math.PI/n;for(let e=0;e<=2*Math.PI;e+=t)a.push(T.add(S.scale(v*Math.cos(e)).add(E.scale(v*Math.sin(e)))));a.push(e)}else{const t=1/n;let o=0,l=r.P.Zero();do{l=T.add(S.scale(v*Math.cos(o)).add(E.scale(v*Math.sin(o)))),a.push(l),o+=t}while(!l.equalsWithEpsilon(i,v*t*1.1));a.push(i),s&&a.push(e)}return new d(a)}constructor(e){this._length=0,this._points=e,this._length=this._computeLength(e)}getPoints(){return this._points}length(){return this._length}continue(e){const t=this._points[this._points.length-1],i=this._points.slice(),n=e.getPoints();for(let e=1;e<n.length;e++)i.push(n[e].subtract(n[0]).add(t));return new d(i)}_computeLength(e){let t=0;for(let i=1;i<e.length;i++)t+=e[i].subtract(e[i-1]).length();return t}}},142:(e,t,i)=>{i.d(t,{J:()=>s});var n=i(4141);class s{constructor(e,t,i,s){this.normal=new n.P(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new s(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^(0|this.d),e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=s._TmpMatrix;e.invertToRef(t);const i=t.m,n=this.normal.x,r=this.normal.y,o=this.normal.z,a=this.d,l=n*i[0]+r*i[1]+o*i[2]+a*i[3],h=n*i[4]+r*i[5]+o*i[6]+a*i[7],c=n*i[8]+r*i[9]+o*i[10]+a*i[11],u=n*i[12]+r*i[13]+o*i[14]+a*i[15];return new s(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 n=t.x-e.x,s=t.y-e.y,r=t.z-e.z,o=i.x-e.x,a=i.y-e.y,l=i.z-e.z,h=s*l-r*a,c=r*o-n*l,u=n*a-s*o,d=Math.sqrt(h*h+c*c+u*u);let p;return p=0!==d?1/d:0,this.normal.x=h*p,this.normal.y=c*p,this.normal.z=u*p,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return n.P.Dot(this.normal,e)<=t}signedDistanceTo(e){return n.P.Dot(e,this.normal)+this.d}static FromArray(e){return new s(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const n=new s(0,0,0,0);return n.copyFromPoints(e,t,i),n}static FromPositionAndNormal(e,t){const i=new s(0,0,0,0);return t.normalize(),i.normal=t,i.d=-(t.x*e.x+t.y*e.y+t.z*e.z),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return n.P.Dot(i,t)+s}}s._TmpMatrix=n.y3.Identity()},1128:(e,t,i)=>{i.d(t,{R:()=>n});class n{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Clamp(e,t=0,i=1){return Math.min(i,Math.max(t,e))}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=n.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=n.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=n.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 s=Math.abs(t-e)<=i?t:e+n.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=n.DeltaAngle(e,t);let r=0;return-i<s&&s<i?r=t:(t=e+s,r=n.MoveTowards(e,t,i)),r}static Lerp(e,t,i){return e+(t-e)*i}static LerpAngle(e,t,i){let s=n.Repeat(t-e,360);return s>180&&(s-=360),e+s*n.Clamp(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?n.Clamp((i-e)/(t-e)):0,s}static Hermite(e,t,i,n,s){const r=s*s,o=s*r;return e*(2*o-3*r+1)+i*(-2*o+3*r)+t*(o-2*r+s)+n*(o-r)}static Hermite1stDerivative(e,t,i,n,s){const r=s*s;return 6*(r-s)*e+(3*r-4*s+1)*t+6*(-r+s)*i+(3*r-2*s)*n}static RandomRange(e,t){return e===t?e:Math.random()*(t-e)+e}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static NormalizeRadians(e){return e-n.TwoPi*Math.floor((e+Math.PI)/n.TwoPi)}static HCF(e,t){const i=e%t;return 0===i?t:n.HCF(t,i)}}n.TwoPi=2*Math.PI},9697:(e,t,i)=>{i.d(t,{$:()=>n});class n{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^(0|this.height),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 n(this.width*e,this.height*t)}clone(){return new n(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new n(0,0)}add(e){return new n(this.width+e.width,this.height+e.height)}subtract(e){return new n(this.width-e.width,this.height-e.height)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new n(s,r)}}},4141:(e,t,i)=>{i.d(t,{FM:()=>c,Lt:()=>d,P:()=>u,_f:()=>p,jp:()=>m,y3:()=>f});var n=i(1128),s=i(1341),r=i(5860),o=i(2208),a=i(771),l=i(1431);const h=e=>parseInt(e.toString().replace(/\W/g,""));class c{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=h(this.x);return e=397*e^h(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return c.FromArrayToRef(e,t,this),this}asArray(){const e=new Array;return this.toArray(e,0),e}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}add(e){return new this.constructor(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addVector3(e){return new this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new this.constructor(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.divideToRef(e,this)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(-1*this.x,-1*this.y)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){const t=new this.constructor(0,0);return this.scaleToRef(e,t),t}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=s.kn){return e&&n.R.WithinEpsilon(this.x,e.x,t)&&n.R.WithinEpsilon(this.y,e.y,t)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(e,t){const i=Math.cos(e),n=Math.sin(e),s=i*this.x-n*this.y,r=n*this.x+i*this.y;return t.x=s,t.y=r,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return c.NormalizeToRef(this,this),this}clone(){return new this.constructor(this.x,this.y)}static Zero(){return new c(0,0)}static One(){return new c(1,1)}static Random(e=0,t=1){return new c(n.R.RandomRange(e,t),n.R.RandomRange(e,t))}static get ZeroReadOnly(){return c._ZeroReadOnly}static FromArray(e,t=0){return new c(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static CatmullRom(e,t,i,n,s){const r=s*s,o=s*r,a=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-n.x)*r+(-e.x+3*t.x-3*i.x+n.x)*o),l=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-n.y)*r+(-e.y+3*t.y-3*i.y+n.y)*o);return new e.constructor(a,l)}static Clamp(e,t,i){let n=e.x;n=n>i.x?i.x:n,n=n<t.x?t.x:n;let s=e.y;return s=s>i.y?i.y:s,s=s<t.y?t.y:s,new e.constructor(n,s)}static Hermite(e,t,i,n,s){const r=s*s,o=s*r,a=2*o-3*r+1,l=-2*o+3*r,h=o-2*r+s,c=o-r,u=e.x*a+i.x*l+t.x*h+n.x*c,d=e.y*a+i.y*l+t.y*h+n.y*c;return new e.constructor(u,d)}static Hermite1stDerivative(e,t,i,n,s){const r=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const o=s*s;return r.x=6*(o-s)*e.x+(3*o-4*s+1)*t.x+6*(-o+s)*i.x+(3*o-2*s)*n.x,r.y=6*(o-s)*e.y+(3*o-4*s+1)*t.y+6*(-o+s)*i.y+(3*o-2*s)*n.y,r}static Lerp(e,t,i){const n=e.x+(t.x-e.x)*i,s=e.y+(t.y-e.y)*i;return new e.constructor(n,s)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){const t=new e.constructor;return this.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){const i=e.length();return 0===i||(t.x=e.x/i,t.y=e.y/i),t}static Minimize(e,t){const i=e.x<t.x?e.x:t.x,n=e.y<t.y?e.y:t.y;return new e.constructor(i,n)}static Maximize(e,t){const i=e.x>t.x?e.x:t.x,n=e.y>t.y?e.y:t.y;return new e.constructor(i,n)}static Transform(e,t){const i=new e.constructor;return c.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){const n=t.m,s=e.x*n[0]+e.y*n[4]+n[12],r=e.x*n[1]+e.y*n[5]+n[13];return i.x=s,i.y=r,i}static PointInTriangle(e,t,i,n){const s=.5*(-i.y*n.x+t.y*(-i.x+n.x)+t.x*(i.y-n.y)+i.x*n.y),r=s<0?-1:1,o=(t.y*n.x-t.x*n.y+(n.y-t.y)*e.x+(t.x-n.x)*e.y)*r,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*r;return o>0&&a>0&&o+a<2*s*r}static Distance(e,t){return Math.sqrt(c.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,n=e.y-t.y;return i*i+n*n}static Center(e,t){const i=new e.constructor;return c.CenterToRef(e,t,i)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const n=c.DistanceSquared(t,i);if(0===n)return c.Distance(e,t);const s=i.subtract(t),r=Math.max(0,Math.min(1,c.Dot(e.subtract(t),s)/n)),o=t.add(s.multiplyByFloats(r,r));return c.Distance(e,o)}}c._ZeroReadOnly=c.Zero();class u{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(){let e=h(this._x);return e=397*e^h(this._y),e=397*e^h(this._z),e}asArray(){const e=[];return this.toArray(e,0),e}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return u.FromArrayToRef(e,t,this),this}toQuaternion(){return p.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,n){return n.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new this.constructor(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._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 n=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const s=t*Math.sin(i)*Math.cos(n),r=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(n);return e.set(s,r,o),e}applyRotationQuaternionToRef(e,t){const i=e._w*this._x+e._y*this._z-e._z*this._y,n=e._w*this._y+e._z*this._x-e._x*this._z,s=e._w*this._z+e._x*this._y-e._y*this._x,r=-e._x*this._x-e._y*this._y-e._z*this._z;return t._x=i*e._w+r*-e._x+n*-e._z-s*-e._y,t._y=n*e._w+r*-e._y+s*-e._x-i*-e._z,t._z=s*e._w+r*-e._z+i*-e._y-n*-e._x,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 n=e.normal,s=e.d,r=_.Vector3[0];this.subtractToRef(t,r),r.normalize();const o=u.Dot(r,n);if(Math.abs(o)<Math.pow(10,-10))i.setAll(1/0);else{const e=-(u.Dot(t,n)+s)/o,a=r.scaleInPlace(e);t.addToRef(a,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=s.kn){return e&&n.R.WithinEpsilon(this._x,e._x,t)&&n.R.WithinEpsilon(this._y,e._y,t)&&n.R.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 e<this._x&&(this.x=e),t<this._y&&(this.y=t),i<this._z&&(this.z=i),this}maximizeInPlaceFromFloats(e,t,i){return e>this._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!n.R.WithinEpsilon(t,i,e))return!0;const s=Math.abs(this._z);return!n.R.WithinEpsilon(t,s,e)||!n.R.WithinEpsilon(i,s,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fract(){return new this.constructor(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z==0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){return"xyz"===(e=e.toLowerCase())||(_.Vector3[0].copyFrom(this),["x","y","z"].forEach(((t,i)=>{this[t]=_.Vector3[0][e[i]]}))),this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(_.Matrix[0]),u.TransformCoordinatesToRef(this,_.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,_.Vector3[0]),_.Vector3[0].rotateByQuaternionToRef(e,_.Vector3[0]),t.addToRef(_.Vector3[0],i),i}cross(e){const t=new this.constructor;return u.CrossToRef(this,e,t)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor(0,0,0);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._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,n){const s=u.Dot(e,i)-n;return s/(s-(u.Dot(t,i)-n))}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(_.Vector3[1]),r=t.normalizeToRef(_.Vector3[2]);let o=u.Dot(s,r);o=n.R.Clamp(o,-1,1);const a=Math.acos(o),l=_.Vector3[3];return u.CrossToRef(s,r,l),u.Dot(l,i)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(o)}static GetAngleBetweenVectorsOnPlane(e,t,i){_.Vector3[0].copyFrom(e);const s=_.Vector3[0];_.Vector3[1].copyFrom(t);const r=_.Vector3[1];_.Vector3[2].copyFrom(i);const o=_.Vector3[2],a=_.Vector3[3],l=_.Vector3[4];s.normalize(),r.normalize(),o.normalize(),u.CrossToRef(o,s,a),u.CrossToRef(a,o,l);const h=Math.atan2(u.Dot(r,a),u.Dot(r,l));return n.R.NormalizeRadians(h)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const n=m.Vector3[0];return t.subtractToRef(e,n),i._y=Math.atan2(n.x,n.z)||0,i._x=Math.atan2(Math.sqrt(n.x**2+n.z**2),n.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=u.Zero();return u.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,r){i=n.R.Clamp(i,0,1);const o=_.Vector3[0],a=_.Vector3[1];o.copyFrom(e);const l=o.length();o.normalizeFromLength(l),a.copyFrom(t);const h=a.length();a.normalizeFromLength(h);const c=u.Dot(o,a);let d,p;if(c<1-s.kn){const e=Math.acos(c),t=1/Math.sin(e);d=Math.sin((1-i)*e)*t,p=Math.sin(i*e)*t}else d=1-i,p=i;return o.scaleInPlace(d),a.scaleInPlace(p),r.copyFrom(o).addInPlace(a),r.scaleInPlace(n.R.Lerp(l,h,i)),r}static SmoothToRef(e,t,i,n,s){return u.SlerpToRef(e,t,0===n?1:i/n,s),s}static FromArray(e,t=0){return new u(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return u.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 u.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,n){return n.copyFromFloats(e,t,i),n}static Zero(){return new u(0,0,0)}static One(){return new u(1,1,1)}static Up(){return new u(0,1,0)}static get UpReadOnly(){return u._UpReadOnly}static get DownReadOnly(){return u._DownReadOnly}static get RightReadOnly(){return u._RightReadOnly}static get LeftReadOnly(){return u._LeftReadOnly}static get LeftHandedForwardReadOnly(){return u._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return u._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return u._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return u._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return u._ZeroReadOnly}static Down(){return new u(0,-1,0)}static Forward(e=!1){return new u(0,0,e?-1:1)}static Backward(e=!1){return new u(0,0,e?1:-1)}static Right(){return new u(1,0,0)}static Left(){return new u(-1,0,0)}static Random(e=0,t=1){return new u(n.R.RandomRange(e,t),n.R.RandomRange(e,t),n.R.RandomRange(e,t))}static TransformCoordinates(e,t){const i=u.Zero();return u.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return u.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,n,s){const r=n.m,o=e*r[0]+t*r[4]+i*r[8]+r[12],a=e*r[1]+t*r[5]+i*r[9]+r[13],l=e*r[2]+t*r[6]+i*r[10]+r[14],h=1/(e*r[3]+t*r[7]+i*r[11]+r[15]);return s._x=o*h,s._y=a*h,s._z=l*h,s._isDirty=!0,s}static TransformNormal(e,t){const i=u.Zero();return u.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,n,s){const r=n.m;return s._x=e*r[0]+t*r[4]+i*r[8],s._y=e*r[1]+t*r[5]+i*r[9],s._z=e*r[2]+t*r[6]+i*r[10],s._isDirty=!0,s}static CatmullRom(e,t,i,n,s){const r=s*s,o=s*r,a=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-n._x)*r+(-e._x+3*t._x-3*i._x+n._x)*o),l=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-n._y)*r+(-e._y+3*t._y-3*i._y+n._y)*o),h=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-n._z)*r+(-e._z+3*t._z-3*i._z+n._z)*o);return new e.constructor(a,l,h)}static Clamp(e,t,i){const n=new e.constructor;return u.ClampToRef(e,t,i,n),n}static ClampToRef(e,t,i,n){let s=e._x;s=s>i._x?i._x:s,s=s<t._x?t._x:s;let r=e._y;r=r>i._y?i._y:r,r=r<t._y?t._y:r;let o=e._z;return o=o>i._z?i._z:o,o=o<t._z?t._z:o,n.copyFromFloats(s,r,o),n}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static Hermite(e,t,i,n,s){const r=s*s,o=s*r,a=2*o-3*r+1,l=-2*o+3*r,h=o-2*r+s,c=o-r,u=e._x*a+i._x*l+t._x*h+n._x*c,d=e._y*a+i._y*l+t._y*h+n._y*c,p=e._z*a+i._z*l+t._z*h+n._z*c;return new e.constructor(u,d,p)}static Hermite1stDerivative(e,t,i,n,s){const r=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const o=s*s;return r._x=6*(o-s)*e._x+(3*o-4*s+1)*t._x+6*(-o+s)*i._x+(3*o-2*s)*n._x,r._y=6*(o-s)*e._y+(3*o-4*s+1)*t._y+6*(-o+s)*i._y+(3*o-2*s)*n._y,r._z=6*(o-s)*e._z+(3*o-4*s+1)*t._z+6*(-o+s)*i._z+(3*o-2*s)*n._z,r._isDirty=!0,r}static Lerp(e,t,i){const n=new e.constructor(0,0,0);return u.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){return n._x=e._x+(t._x-e._x)*i,n._y=e._y+(t._y-e._y)*i,n._z=e._z+(t._z-e._z)*i,n._isDirty=!0,n}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z}static Cross(e,t){const i=new e.constructor;return u.CrossToRef(e,t,i),i}static CrossToRef(e,t,i){const n=e._y*t._z-e._z*t._y,s=e._z*t._x-e._x*t._z,r=e._x*t._y-e._y*t._x;return i.copyFromFloats(n,s,r),i}static Normalize(e){const t=u.Zero();return u.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Project(e,t,i,n){const s=new e.constructor;return u.ProjectToRef(e,t,i,n,s),s}static ProjectToRef(e,t,i,n,s){const r=n.width,o=n.height,a=n.x,l=n.y,h=_.Matrix[1];f.FromValuesToRef(r/2,0,0,0,0,-o/2,0,0,0,0,.5,0,a+r/2,o/2+l,.5,1,h);const c=_.Matrix[0];return t.multiplyToRef(i,c),c.multiplyToRef(h,c),u.TransformCoordinatesToRef(e,c,s),s}static Reflect(e,t){return this.ReflectToRef(e,t,new u)}static ReflectToRef(e,t,i){const n=m.Vector3[0];return n.copyFrom(t).scaleInPlace(2*u.Dot(e,t)),i.copyFrom(e).subtractInPlace(n)}static _UnprojectFromInvertedMatrixToRef(e,t,i){u.TransformCoordinatesToRef(e,t,i);const s=t.m,r=e._x*s[3]+e._y*s[7]+e._z*s[11]+s[15];return n.R.WithinEpsilon(r,1)&&i.scaleInPlace(1/r),i}static UnprojectFromTransform(e,t,i,n,s){return this.Unproject(e,t,i,n,s,f.IdentityReadOnly)}static Unproject(e,t,i,n,s,r){const o=new e.constructor;return u.UnprojectToRef(e,t,i,n,s,r,o),o}static UnprojectToRef(e,t,i,n,s,r,o){return u.UnprojectFloatsToRef(e._x,e._y,e._z,t,i,n,s,r,o),o}static UnprojectFloatsToRef(e,t,i,n,s,r,o,a,h){var c;const d=_.Matrix[0];r.multiplyToRef(o,d),d.multiplyToRef(a,d),d.invert();const p=_.Vector3[0];return p.x=e/n*2-1,p.y=-(t/s*2-1),(null===(c=l.l.LastCreatedEngine)||void 0===c?void 0:c.isNDCHalfZRange)?p.z=i:p.z=2*i-1,u._UnprojectFromInvertedMatrixToRef(p,d,h),h}static Minimize(e,t){const i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(u.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e._x-t._x,n=e._y-t._y,s=e._z-t._z;return i*i+n*n+s*s}static ProjectOnTriangleToRef(e,t,i,r,o){const a=_.Vector3[0],l=_.Vector3[1],h=_.Vector3[2],c=_.Vector3[3],d=_.Vector3[4];i.subtractToRef(t,a),r.subtractToRef(t,l),r.subtractToRef(i,h);const p=a.length(),f=l.length(),m=h.length();if(p<s.kn||f<s.kn||m<s.kn)return o.copyFrom(t),u.Distance(e,t);e.subtractToRef(t,d),u.CrossToRef(a,l,c);const g=c.length();if(g<s.kn)return o.copyFrom(t),u.Distance(e,t);c.normalizeFromLength(g);let v=d.length();if(v<s.kn)return o.copyFrom(t),0;d.normalizeFromLength(v);const y=u.Dot(c,d),x=_.Vector3[5],b=_.Vector3[6];x.copyFrom(c).scaleInPlace(-v*y),b.copyFrom(e).addInPlace(x);const T=_.Vector3[4],S=_.Vector3[5],E=_.Vector3[7],C=_.Vector3[8];T.copyFrom(a).scaleInPlace(1/p),C.copyFrom(l).scaleInPlace(1/f),T.addInPlace(C).scaleInPlace(-1),S.copyFrom(a).scaleInPlace(-1/p),C.copyFrom(h).scaleInPlace(1/m),S.addInPlace(C).scaleInPlace(-1),E.copyFrom(h).scaleInPlace(-1/m),C.copyFrom(l).scaleInPlace(-1/f),E.addInPlace(C).scaleInPlace(-1);const A=_.Vector3[9];let P;A.copyFrom(b).subtractInPlace(t),u.CrossToRef(T,A,C),P=u.Dot(C,c);const R=P;A.copyFrom(b).subtractInPlace(i),u.CrossToRef(S,A,C),P=u.Dot(C,c);const M=P;A.copyFrom(b).subtractInPlace(r),u.CrossToRef(E,A,C),P=u.Dot(C,c);const I=P,D=_.Vector3[10];let O,w;R>0&&M<0?(D.copyFrom(a),O=t,w=i):M>0&&I<0?(D.copyFrom(h),O=i,w=r):(D.copyFrom(l).scaleInPlace(-1),O=r,w=t);const N=_.Vector3[9],F=_.Vector3[4];if(O.subtractToRef(b,C),w.subtractToRef(b,N),u.CrossToRef(C,N,F),!(u.Dot(F,c)<0))return o.copyFrom(b),Math.abs(v*y);const L=_.Vector3[5];u.CrossToRef(D,F,L),L.normalize();const B=_.Vector3[9];B.copyFrom(O).subtractInPlace(b);const U=B.length();if(U<s.kn)return o.copyFrom(O),u.Distance(e,O);B.normalizeFromLength(U);const V=u.Dot(L,B),k=_.Vector3[7];k.copyFrom(b).addInPlace(L.scaleInPlace(U*V)),C.copyFrom(k).subtractInPlace(O),v=D.length(),D.normalizeFromLength(v);let G=u.Dot(C,D)/Math.max(v,s.kn);return G=n.R.Clamp(G,0,1),k.copyFrom(O).addInPlace(D.scaleInPlace(G*v)),o.copyFrom(k),u.Distance(e,k)}static Center(e,t){return u.CenterToRef(e,t,u.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 n=new e.constructor;return u.RotationFromAxisToRef(e,t,i,n),n}static RotationFromAxisToRef(e,t,i,n){const s=_.Quaternion[0];return p.RotationQuaternionFromAxisToRef(e,t,i,s),s.toEulerAnglesToRef(n),n}}u._UpReadOnly=u.Up(),u._DownReadOnly=u.Down(),u._LeftHandedForwardReadOnly=u.Forward(!1),u._RightHandedForwardReadOnly=u.Forward(!0),u._LeftHandedBackwardReadOnly=u.Backward(!1),u._RightHandedBackwardReadOnly=u.Backward(!0),u._RightReadOnly=u.Right(),u._LeftReadOnly=u.Left(),u._ZeroReadOnly=u.Zero();class d{constructor(e=0,t=0,i=0,n=0){this.x=e,this.y=t,this.z=i,this.w=n}toString(){return`{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`}getClassName(){return"Vector4"}getHashCode(){let e=h(this.x);return e=397*e^h(this.y),e=397*e^h(this.z),e=397*e^h(this.w),e}asArray(){const e=new Array;return this.toArray(e,0),e}toArray(e,t){return void 0===t&&(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 d.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,n){return new this.constructor(this.x-e,this.y-t,this.z-i,this.w-n)}subtractFromFloatsToRef(e,t,i,n,s){return s.x=this.x-e,s.y=this.y-t,s.z=this.z-i,s.w=this.w-n,s}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(-1*this.x,-1*this.y,-1*this.z,-1*this.w)}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=s.kn){return e&&n.R.WithinEpsilon(this.x,e.x,t)&&n.R.WithinEpsilon(this.y,e.y,t)&&n.R.WithinEpsilon(this.z,e.z,t)&&n.R.WithinEpsilon(this.w,e.w,t)}equalsToFloats(e,t,i,n){return this.x===e&&this.y===t&&this.z===i&&this.w===n}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,n){return new this.constructor(this.x*e,this.y*t,this.z*i,this.w*n)}divide(e){return new this.constructor(this.x/e.x,this.y/e.y,this.z/e.z,this.w/e.w)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,t.w=this.w/e.w,t}divideInPlace(e){return this.divideToRef(e,this)}minimizeInPlace(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this}maximizeInPlace(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){const e=this.length();return 0===e?this:this.scaleInPlace(1/e)}toVector3(){return new u(this.x,this.y,this.z)}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}setAll(e){return this.x=this.y=this.z=this.w=e,this}static FromArray(e,t){return t||(t=0),new d(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 d.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,n,s){return s.x=e,s.y=t,s.z=i,s.w=n,s}static Zero(){return new d(0,0,0,0)}static One(){return new d(1,1,1,1)}static Random(e=0,t=1){return new d(n.R.RandomRange(e,t),n.R.RandomRange(e,t),n.R.RandomRange(e,t),n.R.RandomRange(e,t))}static get ZeroReadOnly(){return d._ZeroReadOnly}static Normalize(e){const t=d.Zero();return d.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return t.copyFrom(e),t.normalize(),t}static Minimize(e,t){const i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(d.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,n=e.y-t.y,s=e.z-t.z,r=e.w-t.w;return i*i+n*n+s*s+r*r}static Center(e,t){return d.CenterToRef(e,t,d.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=d.Zero();return d.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return d.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,n,s){const r=n.m,o=e*r[0]+t*r[4]+i*r[8]+r[12],a=e*r[1]+t*r[5]+i*r[9]+r[13],l=e*r[2]+t*r[6]+i*r[10]+r[14],h=e*r[3]+t*r[7]+i*r[11]+r[15];return s.x=o,s.y=a,s.z=l,s.w=h,s}static TransformNormal(e,t){const i=new e.constructor;return d.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){const n=t.m,s=e.x*n[0]+e.y*n[4]+e.z*n[8],r=e.x*n[1]+e.y*n[5]+e.z*n[9],o=e.x*n[2]+e.y*n[6]+e.z*n[10];return i.x=s,i.y=r,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,n,s,r){const o=s.m;return r.x=e*o[0]+t*o[4]+i*o[8],r.y=e*o[1]+t*o[5]+i*o[9],r.z=e*o[2]+t*o[6]+i*o[10],r.w=n,r}static FromVector3(e,t=0){return new d(e._x,e._y,e._z,t)}}d._ZeroReadOnly=d.Zero();class p{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,n=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=n}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=h(this._x);return e=397*e^h(this._y),e=397*e^h(this._z),e=397*e^h(this._w),e}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=s.kn){return e&&n.R.WithinEpsilon(this._x,e._x,t)&&n.R.WithinEpsilon(this._y,e._y,t)&&n.R.WithinEpsilon(this._z,e._z,t)&&n.R.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,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._isDirty=!0,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._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,n=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,r=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,n,s,r),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 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||this.scaleInPlace(1/e),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){const e=this.length();if(0===e)return this;const t=1/e;return this.scaleInPlace(t),this}normalizeToNew(){const e=this.length();if(0===e)return this.clone();const t=1/e;return this.scale(t)}toEulerAngles(){const e=u.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,n=this._y,s=this._w,r=n*t-i*s,o=.4999999;if(r<-o)e._y=2*Math.atan2(n,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(r>o)e._y=2*Math.atan2(n,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const o=s*s,a=t*t,l=i*i,h=n*n;e._z=Math.atan2(2*(i*n+t*s),-a-l+h+o),e._x=Math.asin(-2*r),e._y=Math.atan2(2*(t*i+n*s),a-l-h+o),e._isDirty=!0}return e}toRotationMatrix(e){return f.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return p.FromRotationMatrixToRef(e,this),this}static FromRotationMatrix(e){const t=new p;return p.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,n=i[0],s=i[4],r=i[8],o=i[1],a=i[5],l=i[9],h=i[2],c=i[6],u=i[10],d=n+a+u;let p;return d>0?(p=.5/Math.sqrt(d+1),t._w=.25/p,t._x=(c-l)*p,t._y=(r-h)*p,t._z=(o-s)*p,t._isDirty=!0):n>a&&n>u?(p=2*Math.sqrt(1+n-a-u),t._w=(c-l)/p,t._x=.25*p,t._y=(s+o)/p,t._z=(r+h)/p,t._isDirty=!0):a>u?(p=2*Math.sqrt(1+a-n-u),t._w=(r-h)/p,t._x=(s+o)/p,t._y=.25*p,t._z=(l+c)/p,t._isDirty=!0):(p=2*Math.sqrt(1+u-n-a),t._w=(o-s)/p,t._x=(r+h)/p,t._y=(l+c)/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 n=p.Dot(e,t);return 1-n*n<=i}static SmoothToRef(e,t,i,s,r){let o=0===s?1:i/s;return o=n.R.Clamp(o,0,1),p.SlerpToRef(e,t,o,r),r}static Zero(){return new p(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 p(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return p.RotationAxisToRef(e,t,new p)}static RotationAxisToRef(e,t,i){const n=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*n,i._y=e._y*n,i._z=e._z*n,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new p(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 n=new p;return p.RotationYawPitchRollToRef(t,e,i,n),n}static FromEulerAnglesToRef(e,t,i,n){return p.RotationYawPitchRollToRef(t,e,i,n),n}static FromEulerVector(e){const t=new p;return p.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return p.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i){const n=u.Dot(e,t)+1;return n<s.kn?Math.abs(e.x)>Math.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(u.CrossToRef(e,t,m.Vector3[0]),i.set(m.Vector3[0].x,m.Vector3[0].y,m.Vector3[0].z,n)),i.normalize()}static RotationYawPitchRoll(e,t,i){const n=new p;return p.RotationYawPitchRollToRef(e,t,i,n),n}static RotationYawPitchRollToRef(e,t,i,n){const s=.5*i,r=.5*t,o=.5*e,a=Math.sin(s),l=Math.cos(s),h=Math.sin(r),c=Math.cos(r),u=Math.sin(o),d=Math.cos(o);return n._x=d*h*l+u*c*a,n._y=u*c*l-d*h*a,n._z=d*c*a-u*h*l,n._w=d*c*l+u*h*a,n._isDirty=!0,n}static RotationAlphaBetaGamma(e,t,i){const n=new p;return p.RotationAlphaBetaGammaToRef(e,t,i,n),n}static RotationAlphaBetaGammaToRef(e,t,i,n){const s=.5*(i+e),r=.5*(i-e),o=.5*t;return n._x=Math.cos(r)*Math.sin(o),n._y=Math.sin(r)*Math.sin(o),n._z=Math.sin(s)*Math.cos(o),n._w=Math.cos(s)*Math.cos(o),n._isDirty=!0,n}static RotationQuaternionFromAxis(e,t,i){const n=new p(0,0,0,0);return p.RotationQuaternionFromAxisToRef(e,t,i,n),n}static RotationQuaternionFromAxisToRef(e,t,i,n){const s=_.Matrix[0];return f.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),s),p.FromRotationMatrixToRef(s,n),n}static FromLookDirectionLH(e,t){const i=new p;return p.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const n=_.Matrix[0];return f.LookDirectionLHToRef(e,t,n),p.FromRotationMatrixToRef(n,i),i}static FromLookDirectionRH(e,t){const i=new p;return p.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const n=_.Matrix[0];return f.LookDirectionRHToRef(e,t,n),p.FromRotationMatrixToRef(n,i)}static Slerp(e,t,i){const n=p.Identity();return p.SlerpToRef(e,t,i,n),n}static SlerpToRef(e,t,i,n){let s,r,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,a=!1;if(o<0&&(a=!0,o=-o),o>.999999)r=1-i,s=a?-i:i;else{const e=Math.acos(o),t=1/Math.sin(e);r=Math.sin((1-i)*e)*t,s=a?-Math.sin(i*e)*t:Math.sin(i*e)*t}return n._x=r*e._x+s*t._x,n._y=r*e._y+s*t._y,n._z=r*e._z+s*t._z,n._w=r*e._w+s*t._w,n._isDirty=!0,n}static Hermite(e,t,i,n,s){const r=s*s,o=s*r,a=2*o-3*r+1,l=-2*o+3*r,h=o-2*r+s,c=o-r,u=e._x*a+i._x*l+t._x*h+n._x*c,d=e._y*a+i._y*l+t._y*h+n._y*c,p=e._z*a+i._z*l+t._z*h+n._z*c,f=e._w*a+i._w*l+t._w*h+n._w*c;return new e.constructor(u,d,p,f)}static Hermite1stDerivative(e,t,i,n,s){const r=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const o=s*s;return r._x=6*(o-s)*e._x+(3*o-4*s+1)*t._x+6*(-o+s)*i._x+(3*o-2*s)*n._x,r._y=6*(o-s)*e._y+(3*o-4*s+1)*t._y+6*(-o+s)*i._y+(3*o-2*s)*n._y,r._z=6*(o-s)*e._z+(3*o-4*s+1)*t._z+6*(-o+s)*i._z+(3*o-2*s)*n._z,r._w=6*(o-s)*e._w+(3*o-4*s+1)*t._w+6*(-o+s)*i._w+(3*o-2*s)*n._w,r._isDirty=!0,r}}class f{static get Use64Bits(){return a.Z.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=f._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,n=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&n}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,a.Z.MatrixTrackPrecisionChange&&a.Z.MatrixTrackedMatrices.push(this),this._m=new a.Z.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],i=e[1],n=e[2],s=e[3],r=e[4],o=e[5],a=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],_=e[14],m=e[15],g=u*m-_*d,v=c*m-f*d,y=c*_-f*u,x=h*m-p*d,b=h*_-u*p,T=h*f-p*c;return t*+(o*g-a*v+l*y)+i*-(r*g-a*x+l*b)+n*+(r*v-o*x+l*T)+s*-(r*y-o*b+a*T)}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return f.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new this.constructor;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,n=t._m,s=e.m;for(let e=0;e<16;e++)n[e]=i[e]+s[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}invertToRef(e){if(!0===this._isIdentity)return f.IdentityToRef(e),e;const t=this._m,i=t[0],n=t[1],s=t[2],r=t[3],o=t[4],a=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],p=t[11],_=t[12],m=t[13],g=t[14],v=t[15],y=d*v-g*p,x=u*v-m*p,b=u*g-m*d,T=c*v-_*p,S=c*g-d*_,E=c*m-_*u,C=+(a*y-l*x+h*b),A=-(o*y-l*T+h*S),P=+(o*x-a*T+h*E),R=-(o*b-a*S+l*E),M=i*C+n*A+s*P+r*R;if(0===M)return e.copyFrom(this),e;const I=1/M,D=l*v-g*h,O=a*v-m*h,w=a*g-m*l,N=o*v-_*h,F=o*g-_*l,L=o*m-_*a,B=l*p-d*h,U=a*p-u*h,V=a*d-u*l,k=o*p-c*h,G=o*d-c*l,z=o*u-c*a,W=-(n*y-s*x+r*b),H=+(i*y-s*T+r*S),X=-(i*x-n*T+r*E),j=+(i*b-n*S+s*E),Y=+(n*D-s*O+r*w),q=-(i*D-s*N+r*F),K=+(i*O-n*N+r*L),$=-(i*w-n*F+s*L),Q=-(n*B-s*U+r*V),Z=+(i*B-s*k+r*G),J=-(i*U-n*k+r*z),ee=+(i*V-n*G+s*z);return f.FromValuesToRef(C*I,W*I,Y*I,Q*I,A*I,H*I,q*I,Z*I,P*I,X*I,K*I,J*I,R*I,j*I,$*I,ee*I,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 u(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 f.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),this}multiply(e){const t=new this.constructor;return this.multiplyToRef(e,t),t}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const n=this._m,s=e.m,r=n[0],o=n[1],a=n[2],l=n[3],h=n[4],c=n[5],u=n[6],d=n[7],p=n[8],f=n[9],_=n[10],m=n[11],g=n[12],v=n[13],y=n[14],x=n[15],b=s[0],T=s[1],S=s[2],E=s[3],C=s[4],A=s[5],P=s[6],R=s[7],M=s[8],I=s[9],D=s[10],O=s[11],w=s[12],N=s[13],F=s[14],L=s[15];return t[i]=r*b+o*C+a*M+l*w,t[i+1]=r*T+o*A+a*I+l*N,t[i+2]=r*S+o*P+a*D+l*F,t[i+3]=r*E+o*R+a*O+l*L,t[i+4]=h*b+c*C+u*M+d*w,t[i+5]=h*T+c*A+u*I+d*N,t[i+6]=h*S+c*P+u*D+d*F,t[i+7]=h*E+c*R+u*O+d*L,t[i+8]=p*b+f*C+_*M+m*w,t[i+9]=p*T+f*A+_*I+m*N,t[i+10]=p*S+f*P+_*D+m*F,t[i+11]=p*E+f*R+_*O+m*L,t[i+12]=g*b+v*C+y*M+x*w,t[i+13]=g*T+v*A+y*I+x*N,t[i+14]=g*S+v*P+y*D+x*F,t[i+15]=g*E+v*R+y*O+x*L,this}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,n=t.m;return i[0]===n[0]&&i[1]===n[1]&&i[2]===n[2]&&i[3]===n[3]&&i[4]===n[4]&&i[5]===n[5]&&i[6]===n[6]&&i[7]===n[7]&&i[8]===n[8]&&i[9]===n[9]&&i[10]===n[10]&&i[11]===n[11]&&i[12]===n[12]&&i[13]===n[13]&&i[14]===n[14]&&i[15]===n[15]}clone(){const e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=h(this._m[0]);for(let t=1;t<16;t++)e=397*e^h(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new p,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,n){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const s=this._m;if(i&&i.copyFromFloats(s[12],s[13],s[14]),(e=e||_.Vector3[0]).x=Math.sqrt(s[0]*s[0]+s[1]*s[1]+s[2]*s[2]),e.y=Math.sqrt(s[4]*s[4]+s[5]*s[5]+s[6]*s[6]),e.z=Math.sqrt(s[8]*s[8]+s[9]*s[9]+s[10]*s[10]),n){const t=n.scaling.x<0?-1:1,i=n.scaling.y<0?-1:1,s=n.scaling.z<0?-1:1;e.x*=t,e.y*=i,e.z*=s}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,n=1/e._y,r=1/e._z;f.FromValuesToRef(s[0]*i,s[1]*i,s[2]*i,0,s[4]*n,s[5]*n,s[6]*n,0,s[8]*r,s[9]*r,s[10]*r,0,0,0,0,1,_.Matrix[0]),p.FromRotationMatrixToRef(_.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new d(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<3){const i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new this.constructor;return f.TransposeToRef(this,e),e}transposeToRef(e){return f.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,n,s){if(e<0||e>3)return this;const r=4*e;return this._m[r+0]=t,this._m[r+1]=i,this._m[r+2]=n,this._m[r+3]=s,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=_.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return f.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=_.Vector3[0];if(!this.decompose(t))return f.IdentityToRef(e),e;const i=this._m,n=1/t._x,s=1/t._y,r=1/t._z;return f.FromValuesToRef(i[0]*n,i[1]*n,i[2]*n,0,i[4]*s,i[5]*s,i[6]*s,0,i[8]*r,i[9]*r,i[10]*r,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new f;return f.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let n=0;n<16;n++)i._m[n]=e[n+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,n){for(let s=0;s<16;s++)n._m[s]=e[s+t]*i;return n.markAsUpdated(),n}static get IdentityReadOnly(){return f._IdentityReadOnly}static FromValuesToRef(e,t,i,n,s,r,o,a,l,h,c,u,d,p,f,_,m){const g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=n,g[4]=s,g[5]=r,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=p,g[14]=f,g[15]=_,m.markAsUpdated()}static FromValues(e,t,i,n,s,r,o,a,l,h,c,u,d,p,_,m){const g=new f,v=g._m;return v[0]=e,v[1]=t,v[2]=i,v[3]=n,v[4]=s,v[5]=r,v[6]=o,v[7]=a,v[8]=l,v[9]=h,v[10]=c,v[11]=u,v[12]=d,v[13]=p,v[14]=_,v[15]=m,g.markAsUpdated(),g}static Compose(e,t,i){const n=new f;return f.ComposeToRef(e,t,i,n),n}static ComposeToRef(e,t,i,n){const s=n._m,r=t._x,o=t._y,a=t._z,l=t._w,h=r+r,c=o+o,u=a+a,d=r*h,p=r*c,f=r*u,_=o*c,m=o*u,g=a*u,v=l*h,y=l*c,x=l*u,b=e._x,T=e._y,S=e._z;return s[0]=(1-(_+g))*b,s[1]=(p+x)*b,s[2]=(f-y)*b,s[3]=0,s[4]=(p-x)*T,s[5]=(1-(d+g))*T,s[6]=(m+v)*T,s[7]=0,s[8]=(f+y)*S,s[9]=(m-v)*S,s[10]=(1-(d+_))*S,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,n.markAsUpdated(),n}static Identity(){const e=f.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 f.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=f.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 f;return f.RotationXToRef(e,t),t}static Invert(e){const t=new e.constructor;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return f.FromValuesToRef(1,0,0,0,0,n,i,0,0,-i,n,0,0,0,0,1,t),t._updateIdentityStatus(1===n&&0===i),t}static RotationY(e){const t=new f;return f.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return f.FromValuesToRef(n,0,-i,0,0,1,0,0,i,0,n,0,0,0,0,1,t),t._updateIdentityStatus(1===n&&0===i),t}static RotationZ(e){const t=new f;return f.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return f.FromValuesToRef(n,i,0,0,-i,n,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===n&&0===i),t}static RotationAxis(e,t){const i=new f;return f.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const n=Math.sin(-t),s=Math.cos(-t),r=1-s;e.normalize();const o=i._m;return o[0]=e._x*e._x*r+s,o[1]=e._x*e._y*r-e._z*n,o[2]=e._x*e._z*r+e._y*n,o[3]=0,o[4]=e._y*e._x*r+e._z*n,o[5]=e._y*e._y*r+s,o[6]=e._y*e._z*r-e._x*n,o[7]=0,o[8]=e._z*e._x*r-e._y*n,o[9]=e._z*e._y*r+e._x*n,o[10]=e._z*e._z*r+s,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i){const n=u.Dot(t,e),r=i._m;if(n<-1+s.kn)r[0]=-1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=-1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=1,r[11]=0;else{const i=u.Cross(t,e),s=1/(1+n);r[0]=i._x*i._x*s+n,r[1]=i._y*i._x*s-i._z,r[2]=i._z*i._x*s+i._y,r[3]=0,r[4]=i._x*i._y*s+i._z,r[5]=i._y*i._y*s+n,r[6]=i._z*i._y*s-i._x,r[7]=0,r[8]=i._x*i._z*s-i._y,r[9]=i._y*i._z*s+i._x,r[10]=i._z*i._z*s+n,r[11]=0}return r[12]=0,r[13]=0,r[14]=0,r[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const n=new f;return f.RotationYawPitchRollToRef(e,t,i,n),n}static RotationYawPitchRollToRef(e,t,i,n){return p.RotationYawPitchRollToRef(e,t,i,_.Quaternion[0]),_.Quaternion[0].toRotationMatrix(n),n}static Scaling(e,t,i){const n=new f;return f.ScalingToRef(e,t,i,n),n}static ScalingToRef(e,t,i,n){return f.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,n),n._updateIdentityStatus(1===e&&1===t&&1===i),n}static Translation(e,t,i){const n=new f;return f.TranslationToRef(e,t,i,n),n}static TranslationToRef(e,t,i,n){return f.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,n),n._updateIdentityStatus(0===e&&0===t&&0===i),n}static Lerp(e,t,i){const n=new e.constructor;return f.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){const s=n._m,r=e.m,o=t.m;for(let e=0;e<16;e++)s[e]=r[e]*(1-i)+o[e]*i;return n.markAsUpdated(),n}static DecomposeLerp(e,t,i){const n=new e.constructor;return f.DecomposeLerpToRef(e,t,i,n),n}static DecomposeLerpToRef(e,t,i,n){const s=_.Vector3[0],r=_.Quaternion[0],o=_.Vector3[1];e.decompose(s,r,o);const a=_.Vector3[2],l=_.Quaternion[1],h=_.Vector3[3];t.decompose(a,l,h);const c=_.Vector3[4];u.LerpToRef(s,a,i,c);const d=_.Quaternion[2];p.SlerpToRef(r,l,i,d);const m=_.Vector3[5];return u.LerpToRef(o,h,i,m),f.ComposeToRef(c,d,m,n),n}static LookAtLH(e,t,i){const n=new f;return f.LookAtLHToRef(e,t,i,n),n}static LookAtLHToRef(e,t,i,n){const s=_.Vector3[0],r=_.Vector3[1],o=_.Vector3[2];t.subtractToRef(e,o),o.normalize(),u.CrossToRef(i,o,s);const a=s.lengthSquared();0===a?s.x=1:s.normalizeFromLength(Math.sqrt(a)),u.CrossToRef(o,s,r),r.normalize();const l=-u.Dot(s,e),h=-u.Dot(r,e),c=-u.Dot(o,e);f.FromValuesToRef(s._x,r._x,o._x,0,s._y,r._y,o._y,0,s._z,r._z,o._z,0,l,h,c,1,n)}static LookAtRH(e,t,i){const n=new f;return f.LookAtRHToRef(e,t,i,n),n}static LookAtRHToRef(e,t,i,n){const s=_.Vector3[0],r=_.Vector3[1],o=_.Vector3[2];e.subtractToRef(t,o),o.normalize(),u.CrossToRef(i,o,s);const a=s.lengthSquared();0===a?s.x=1:s.normalizeFromLength(Math.sqrt(a)),u.CrossToRef(o,s,r),r.normalize();const l=-u.Dot(s,e),h=-u.Dot(r,e),c=-u.Dot(o,e);return f.FromValuesToRef(s._x,r._x,o._x,0,s._y,r._y,o._y,0,s._z,r._z,o._z,0,l,h,c,1,n),n}static LookDirectionLH(e,t){const i=new f;return f.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const n=_.Vector3[0];n.copyFrom(e),n.scaleInPlace(-1);const s=_.Vector3[1];return u.CrossToRef(t,n,s),f.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,n._x,n._y,n._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new f;return f.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const n=_.Vector3[2];return u.CrossToRef(t,e,n),f.FromValuesToRef(n._x,n._y,n._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,n,s){const r=new f;return f.OrthoLHToRef(e,t,i,n,r,s),r}static OrthoLHToRef(e,t,i,n,s,r){const o=2/e,a=2/t,l=2/(n-i),h=-(n+i)/(n-i);return f.FromValuesToRef(o,0,0,0,0,a,0,0,0,0,l,0,0,0,h,1,s),r&&s.multiplyToRef(g,s),s._updateIdentityStatus(1===o&&1===a&&1===l&&0===h),s}static OrthoOffCenterLH(e,t,i,n,s,r,o){const a=new f;return f.OrthoOffCenterLHToRef(e,t,i,n,s,r,a,o),a}static OrthoOffCenterLHToRef(e,t,i,n,s,r,o,a){const l=2/(t-e),h=2/(n-i),c=2/(r-s),u=-(r+s)/(r-s),d=(e+t)/(e-t),p=(n+i)/(i-n);return f.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,d,p,u,1,o),a&&o.multiplyToRef(g,o),o.markAsUpdated(),o}static OrthoOffCenterRH(e,t,i,n,s,r,o){const a=new f;return f.OrthoOffCenterRHToRef(e,t,i,n,s,r,a,o),a}static OrthoOffCenterRHToRef(e,t,i,n,s,r,o,a){return f.OrthoOffCenterLHToRef(e,t,i,n,s,r,o,a),o._m[10]*=-1,o}static PerspectiveLH(e,t,i,n,s,r=0){const o=new f,a=2*i/e,l=2*i/t,h=(n+i)/(n-i),c=-2*n*i/(n-i),u=Math.tan(r);return f.FromValuesToRef(a,0,0,0,0,l,0,u,0,0,h,1,0,0,c,0,o),s&&o.multiplyToRef(g,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,n,s,r=0,o=!1){const a=new f;return f.PerspectiveFovLHToRef(e,t,i,n,a,!0,s,r,o),a}static PerspectiveFovLHToRef(e,t,i,n,s,r=!0,o,a=0,l=!1){const h=i,c=n,u=1/Math.tan(.5*e),d=r?u/t:u,p=r?u:u*t,_=l&&0===h?-1:0!==c?(c+h)/(c-h):1,m=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,v=Math.tan(a);return f.FromValuesToRef(d,0,0,0,0,p,0,v,0,0,_,1,0,0,m,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,n,s,r=!0,o,a=0){const l=1/Math.tan(.5*e),h=r?l/t:l,c=r?l:l*t,u=Math.tan(a);return f.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,1,0,0,1,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,n,s,r=0,o=!1){const a=new f;return f.PerspectiveFovRHToRef(e,t,i,n,a,!0,s,r,o),a}static PerspectiveFovRHToRef(e,t,i,n,s,r=!0,o,a=0,l=!1){const h=i,c=n,u=1/Math.tan(.5*e),d=r?u/t:u,p=r?u:u*t,_=l&&0===h?1:0!==c?-(c+h)/(c-h):-1,m=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,v=Math.tan(a);return f.FromValuesToRef(d,0,0,0,0,p,0,v,0,0,_,-1,0,0,m,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,n,s,r=!0,o,a=0){const l=1/Math.tan(.5*e),h=r?l/t:l,c=r?l:l*t,u=Math.tan(a);return f.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,-1,0,0,-1,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static PerspectiveFovWebVRToRef(e,t,i,n,s=!1,r,o=0){const a=s?-1:1,l=Math.tan(e.upDegrees*Math.PI/180),h=Math.tan(e.downDegrees*Math.PI/180),c=Math.tan(e.leftDegrees*Math.PI/180),u=Math.tan(e.rightDegrees*Math.PI/180),d=2/(c+u),p=2/(l+h),f=Math.tan(o),_=n._m;return _[0]=d,_[1]=_[2]=_[3]=_[4]=0,_[5]=p,_[6]=0,_[7]=f,_[8]=(c-u)*d*.5,_[9]=-(l-h)*p*.5,_[10]=-i/(t-i),_[11]=1*a,_[12]=_[13]=_[15]=0,_[14]=-2*i*t/(i-t),r&&n.multiplyToRef(g,n),n.markAsUpdated(),n}static GetFinalMatrix(e,t,i,n,s,r){const o=e.width,a=e.height,l=e.x,h=e.y,c=f.FromValues(o/2,0,0,0,0,-a/2,0,0,0,0,r-s,0,l+o/2,a/2+h,s,1),u=new t.constructor;return t.multiplyToRef(i,u),u.multiplyToRef(n,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return a.Z.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 a.Z.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return f.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=t._m,n=e.m;return i[0]=n[0],i[1]=n[4],i[2]=n[8],i[3]=n[12],i[4]=n[1],i[5]=n[5],i[6]=n[9],i[7]=n[13],i[8]=n[2],i[9]=n[6],i[10]=n[10],i[11]=n[14],i[12]=n[3],i[13]=n[7],i[14]=n[11],i[15]=n[15],t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new f;return f.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,n=e.normal.y,s=e.normal.z,r=-2*i,o=-2*n,a=-2*s;return f.FromValuesToRef(r*i+1,o*i,a*i,0,r*n,o*n+1,a*n,0,r*s,o*s,a*s+1,0,r*e.d,o*e.d,a*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,n){return f.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,n),n}static FromQuaternionToRef(e,t){const i=e._x*e._x,n=e._y*e._y,s=e._z*e._z,r=e._x*e._y,o=e._z*e._w,a=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(n+s),t._m[1]=2*(r+o),t._m[2]=2*(a-l),t._m[3]=0,t._m[4]=2*(r-o),t._m[5]=1-2*(s+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(a+l),t._m[9]=2*(h-c),t._m[10]=1-2*(n+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}f._UpdateFlagSeed=0,f._IdentityReadOnly=f.Identity();class _{}_.Vector3=r.B.BuildTuple(11,u.Zero),_.Matrix=r.B.BuildTuple(2,f.Identity),_.Quaternion=r.B.BuildTuple(3,p.Zero);class m{}m.Vector2=r.B.BuildTuple(3,c.Zero),m.Vector3=r.B.BuildTuple(13,u.Zero),m.Vector4=r.B.BuildTuple(3,d.Zero),m.Quaternion=r.B.BuildTuple(2,p.Zero),m.Matrix=r.B.BuildTuple(8,f.Identity),(0,o.H)("BABYLON.Vector2",c),(0,o.H)("BABYLON.Vector3",u),(0,o.H)("BABYLON.Vector4",d),(0,o.H)("BABYLON.Matrix",f);const g=f.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1)},4538:(e,t,i)=>{i.d(t,{l:()=>n});class n{constructor(e,t,i,n){this.x=e,this.y=t,this.width=i,this.height=n}toGlobal(e,t){return new n(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 n(this.x,this.y,this.width,this.height)}}},6113:(e,t,i)=>{i.d(t,{_:()=>h,i:()=>c});var n=i(4141),s=i(6913);const r=[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))],o=[()=>1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],a=(e,t)=>r[e]*o[e](t),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 h{constructor(){this.preScaled=!1,this.l00=n.P.Zero(),this.l1_1=n.P.Zero(),this.l10=n.P.Zero(),this.l11=n.P.Zero(),this.l2_2=n.P.Zero(),this.l2_1=n.P.Zero(),this.l20=n.P.Zero(),this.l21=n.P.Zero(),this.l22=n.P.Zero()}addLight(e,t,i){s.jp.Vector3[0].set(t.r,t.g,t.b);const n=s.jp.Vector3[0],r=s.jp.Vector3[1];n.scaleToRef(i,r),r.scaleToRef(a(0,e),s.jp.Vector3[2]),this.l00.addInPlace(s.jp.Vector3[2]),r.scaleToRef(a(1,e),s.jp.Vector3[2]),this.l1_1.addInPlace(s.jp.Vector3[2]),r.scaleToRef(a(2,e),s.jp.Vector3[2]),this.l10.addInPlace(s.jp.Vector3[2]),r.scaleToRef(a(3,e),s.jp.Vector3[2]),this.l11.addInPlace(s.jp.Vector3[2]),r.scaleToRef(a(4,e),s.jp.Vector3[2]),this.l2_2.addInPlace(s.jp.Vector3[2]),r.scaleToRef(a(5,e),s.jp.Vector3[2]),this.l2_1.addInPlace(s.jp.Vector3[2]),r.scaleToRef(a(6,e),s.jp.Vector3[2]),this.l20.addInPlace(s.jp.Vector3[2]),r.scaleToRef(a(7,e),s.jp.Vector3[2]),this.l21.addInPlace(s.jp.Vector3[2]),r.scaleToRef(a(8,e),s.jp.Vector3[2]),this.l22.addInPlace(s.jp.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(r[0]),this.l1_1.scaleInPlace(r[1]),this.l10.scaleInPlace(r[2]),this.l11.scaleInPlace(r[3]),this.l2_2.scaleInPlace(r[4]),this.l2_1.scaleInPlace(r[5]),this.l20.scaleInPlace(r[6]),this.l21.scaleInPlace(r[7]),this.l22.scaleInPlace(r[8])}updateFromArray(e){return n.P.FromArrayToRef(e[0],0,this.l00),n.P.FromArrayToRef(e[1],0,this.l1_1),n.P.FromArrayToRef(e[2],0,this.l10),n.P.FromArrayToRef(e[3],0,this.l11),n.P.FromArrayToRef(e[4],0,this.l2_2),n.P.FromArrayToRef(e[5],0,this.l2_1),n.P.FromArrayToRef(e[6],0,this.l20),n.P.FromArrayToRef(e[7],0,this.l21),n.P.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return n.P.FromFloatsToRef(e[0],e[1],e[2],this.l00),n.P.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),n.P.FromFloatsToRef(e[6],e[7],e[8],this.l10),n.P.FromFloatsToRef(e[9],e[10],e[11],this.l11),n.P.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),n.P.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),n.P.FromFloatsToRef(e[18],e[19],e[20],this.l20),n.P.FromFloatsToRef(e[21],e[22],e[23],this.l21),n.P.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new h).updateFromArray(e)}static FromPolynomial(e){const t=new h;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 c{constructor(){this.x=n.P.Zero(),this.y=n.P.Zero(),this.z=n.P.Zero(),this.xx=n.P.Zero(),this.yy=n.P.Zero(),this.zz=n.P.Zero(),this.xy=n.P.Zero(),this.yz=n.P.Zero(),this.zx=n.P.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=h.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){s.jp.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=s.jp.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),s.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),s.jp.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(s.jp.Vector3[0]).addInPlace(s.jp.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(s.jp.Vector3[0]).subtractInPlace(s.jp.Vector3[1]),this.zz.copyFrom(e.l00),s.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(s.jp.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 c).updateFromHarmonics(e)}static FromArray(e){const t=new c;return n.P.FromArrayToRef(e[0],0,t.x),n.P.FromArrayToRef(e[1],0,t.y),n.P.FromArrayToRef(e[2],0,t.z),n.P.FromArrayToRef(e[3],0,t.xx),n.P.FromArrayToRef(e[4],0,t.yy),n.P.FromArrayToRef(e[5],0,t.zz),n.P.FromArrayToRef(e[6],0,t.yz),n.P.FromArrayToRef(e[7],0,t.zx),n.P.FromArrayToRef(e[8],0,t.xy),t}}},7422:(e,t,i)=>{i.d(t,{NR:()=>h,aR:()=>l,kg:()=>c});var n=i(4141),s=i(4649),r=i(4496),o=i(2101),a=i(4892);function l(e){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],r=[];let l=[];const h=e.width||e.size||1,c=e.height||e.size||1,u=e.depth||e.size||1,d=e.wrap||!1;let p=void 0===e.topBaseAt?1:e.topBaseAt,f=void 0===e.bottomBaseAt?0:e.bottomBaseAt;p=(p+4)%4,f=(f+4)%4;let _=[2,0,3,1][p],m=[2,0,1,3][f],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(d){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 e=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const n=[17,18,19,16],s=[22,23,20,21];for(;_>0;)e.unshift(e.pop()),n.unshift(n.pop()),_--;for(;m>0;)i.unshift(i.pop()),s.unshift(s.pop()),m--;e=e.flat(),i=i.flat(),g=g.concat(e).concat(i),t.push(n[0],n[2],n[3],n[0],n[1],n[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}const v=[h/2,c/2,u/2];l=g.reduce(((e,t,i)=>e.concat(t*v[i%3])),[]);const y=0===e.sideOrientation?0:e.sideOrientation||o.x.DEFAULTSIDE,x=e.faceUV||new Array(6),b=e.faceColors,T=[];for(let e=0;e<6;e++)void 0===x[e]&&(x[e]=new n.Lt(0,0,1,1)),b&&void 0===b[e]&&(b[e]=new s.HE(1,1,1,1));for(let e=0;e<6;e++)if(r.push(x[e].z,a.e.UseOpenGLOrientationForUV?1-x[e].w:x[e].w),r.push(x[e].x,a.e.UseOpenGLOrientationForUV?1-x[e].w:x[e].w),r.push(x[e].x,a.e.UseOpenGLOrientationForUV?1-x[e].y:x[e].y),r.push(x[e].z,a.e.UseOpenGLOrientationForUV?1-x[e].y:x[e].y),b)for(let t=0;t<4;t++)T.push(b[e].r,b[e].g,b[e].b,b[e].a);o.x._ComputeSides(y,l,t,i,r,e.frontUVs,e.backUVs);const S=new o.x;if(S.indices=t,S.positions=l,S.normals=i,S.uvs=r,b){const e=y===o.x.DOUBLESIDE?T.concat(T):T;S.colors=e}return S}function h(e,t={},i=null){const n=new r.Kj(e,i);return t.sideOrientation=r.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,l(t).applyToMesh(n,t.updatable),n}const c={CreateBox:h};o.x.CreateBox=l,r.Kj.CreateBox=(e,t,i=null,n,s)=>h(e,{size:t,sideOrientation:s,updatable:n},i)},8027:(e,t,i)=>{i.d(t,{$6:()=>_,DG:()=>m,Es:()=>p,Qq:()=>f,W:()=>g,kt:()=>d,vU:()=>v});var n=i(4141),s=i(4649),r=i(4496),o=i(2101),a=i(8475),l=i(7257),h=i(1431),c=i(1341),u=i(4892);function d(e){const t=[],i=[],s=[],r=[];let a,l;const h=e.width||1,c=e.height||1,d=e.subdivisionsX||e.subdivisions||1,p=e.subdivisionsY||e.subdivisions||1;for(a=0;a<=p;a++)for(l=0;l<=d;l++){const e=new n.P(l*h/d-h/2,0,(p-a)*c/p-c/2),t=new n.P(0,1,0);i.push(e.x,e.y,e.z),s.push(t.x,t.y,t.z),r.push(l/d,u.e.UseOpenGLOrientationForUV?a/p:1-a/p)}for(a=0;a<p;a++)for(l=0;l<d;l++)t.push(l+1+(a+1)*(d+1)),t.push(l+1+a*(d+1)),t.push(l+a*(d+1)),t.push(l+(a+1)*(d+1)),t.push(l+1+(a+1)*(d+1)),t.push(l+a*(d+1));const f=new o.x;return f.indices=t,f.positions=i,f.normals=s,f.uvs=r,f}function p(e){const t=void 0!==e.xmin&&null!==e.xmin?e.xmin:-1,i=void 0!==e.zmin&&null!==e.zmin?e.zmin:-1,s=void 0!==e.xmax&&null!==e.xmax?e.xmax:1,r=void 0!==e.zmax&&null!==e.zmax?e.zmax:1,a=e.subdivisions||{w:1,h:1},l=e.precision||{w:1,h:1},h=new Array,c=new Array,u=new Array,d=new Array;let p,f,_,m;a.h=a.h<1?1:a.h,a.w=a.w<1?1:a.w,l.w=l.w<1?1:l.w,l.h=l.h<1?1:l.h;const g=(s-t)/a.w,v=(r-i)/a.h;function y(e,t,i,s){const r=c.length/3,o=l.w+1;for(p=0;p<l.h;p++)for(f=0;f<l.w;f++){const e=[r+f+p*o,r+(f+1)+p*o,r+(f+1)+(p+1)*o,r+f+(p+1)*o];h.push(e[1]),h.push(e[2]),h.push(e[3]),h.push(e[0]),h.push(e[1]),h.push(e[3])}const a=n.P.Zero(),_=new n.P(0,1,0);for(p=0;p<=l.h;p++)for(a.z=p*(s-t)/l.h+t,f=0;f<=l.w;f++)a.x=f*(i-e)/l.w+e,a.y=0,c.push(a.x,a.y,a.z),u.push(_.x,_.y,_.z),d.push(f/l.w,p/l.h)}for(_=0;_<a.h;_++)for(m=0;m<a.w;m++)y(t+m*g,i+_*v,t+(m+1)*g,i+(_+1)*v);const x=new o.x;return x.indices=h,x.positions=c,x.normals=u,x.uvs=d,x}function f(e){const t=[],i=[],r=[],a=[];let l,h;const u=e.colorFilter||new s.Wo(.3,.59,.11),d=e.alphaFilter||0;let p=!1;if(e.minHeight>e.maxHeight){p=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(l=0;l<=e.subdivisions;l++)for(h=0;h<=e.subdivisions;h++){const t=new n.P(h*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-l)*e.height/e.subdivisions-e.height/2),s=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let o=e.buffer[s]/255,f=e.buffer[s+1]/255,_=e.buffer[s+2]/255;const m=e.buffer[s+3]/255;p&&(o=1-o,f=1-f,_=1-_);const g=o*u.r+f*u.g+_*u.b;t.y=m>=d?e.minHeight+(e.maxHeight-e.minHeight)*g:e.minHeight-c.kn,i.push(t.x,t.y,t.z),r.push(0,0,0),a.push(h/e.subdivisions,1-l/e.subdivisions)}for(l=0;l<e.subdivisions;l++)for(h=0;h<e.subdivisions;h++){const n=h+1+(l+1)*(e.subdivisions+1),s=h+1+l*(e.subdivisions+1),r=h+l*(e.subdivisions+1),o=h+(l+1)*(e.subdivisions+1),a=i[3*n+1]>=e.minHeight,c=i[3*s+1]>=e.minHeight,u=i[3*r+1]>=e.minHeight;a&&c&&u&&(t.push(n),t.push(s),t.push(r)),i[3*o+1]>=e.minHeight&&a&&u&&(t.push(o),t.push(n),t.push(r))}o.x.ComputeNormals(i,t,r);const f=new o.x;return f.indices=t,f.positions=i,f.normals=r,f.uvs=a,f}function _(e,t={},i){const n=new a.E(e,i);return n._setReady(!1),n._subdivisionsX=t.subdivisionsX||t.subdivisions||1,n._subdivisionsY=t.subdivisionsY||t.subdivisions||1,n._width=t.width||1,n._height=t.height||1,n._maxX=n._width/2,n._maxZ=n._height/2,n._minX=-n._maxX,n._minZ=-n._maxZ,d(t).applyToMesh(n,t.updatable),n._setReady(!0),n}function m(e,t,i=null){const n=new r.Kj(e,i);return p(t).applyToMesh(n,t.updatable),n}function g(e,t,i={},n=null){const r=i.width||10,o=i.height||10,c=i.subdivisions||1,u=i.minHeight||0,d=i.maxHeight||1,p=i.colorFilter||new s.Wo(.3,.59,.11),_=i.alphaFilter||0,m=i.updatable,g=i.onReady;n=n||h.l.LastCreatedScene;const v=new a.E(e,n);return v._subdivisionsX=c,v._subdivisionsY=c,v._width=r,v._height=o,v._maxX=v._width/2,v._maxZ=v._height/2,v._minX=-v._maxX,v._minZ=-v._maxZ,v._setReady(!1),l.w1.LoadImage(t,(e=>{const t=e.width,i=e.height;if(n.isDisposed)return;const s=null==n?void 0:n.getEngine().resizeImageBitmap(e,t,i);f({width:r,height:o,subdivisions:c,minHeight:u,maxHeight:d,colorFilter:p,buffer:s,bufferWidth:t,bufferHeight:i,alphaFilter:_}).applyToMesh(v,m),g&&g(v),v._setReady(!0)}),(()=>{}),n.offlineProvider),v}const v={CreateGround:_,CreateGroundFromHeightMap:g,CreateTiledGround:m};o.x.CreateGround=d,o.x.CreateTiledGround=p,o.x.CreateGroundFromHeightMap=f,r.Kj.CreateGround=(e,t,i,n,s,r)=>_(e,{width:t,height:i,subdivisions:n,updatable:r},s),r.Kj.CreateTiledGround=(e,t,i,n,s,r,o,a,l)=>m(e,{xmin:t,zmin:i,xmax:n,zmax:s,subdivisions:r,precision:o,updatable:l},a),r.Kj.CreateGroundFromHeightMap=(e,t,i,n,s,r,o,a,l,h,c)=>g(e,t,{width:i,height:n,subdivisions:s,minHeight:r,maxHeight:o,updatable:l,onReady:h,alphaFilter:c},a)},6272:(e,t,i)=>{i.d(t,{Au:()=>l,GM:()=>h,GQ:()=>a});var n=i(4141),s=i(4496),r=i(2101),o=i(4892);function a(e){const t=e.sideOrientation||r.x.DEFAULTSIDE,i=e.radius||1,s=void 0===e.flat||e.flat,a=e.subdivisions||4,l=e.radiusX||i,h=e.radiusY||i,c=e.radiusZ||i,u=(1+Math.sqrt(5))/2,d=[-1,u,-0,1,u,0,-1,-u,0,1,-u,0,0,-1,-u,0,1,-u,0,-1,u,0,1,u,u,0,1,u,0,-1,-u,0,1,-u,0,-1],p=[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],f=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],_=[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],m=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],g=new Array,v=new Array,y=new Array,x=new Array;let b=0;const T=new Array(3),S=new Array(3);let E;for(E=0;E<3;E++)T[E]=n.P.Zero(),S[E]=n.FM.Zero();for(let e=0;e<20;e++){for(E=0;E<3;E++){const t=p[3*e+E];T[E].copyFromFloats(d[3*f[t]],d[3*f[t]+1],d[3*f[t]+2]),T[E].normalize(),S[E].copyFromFloats(.134765625*_[2*t]+.05859375+-.0390625*m[e],.2333984375*_[2*t+1]+.025390625+.01953125*m[e])}const t=(e,t,i,r)=>{const u=n.P.Lerp(T[0],T[2],t/a),d=n.P.Lerp(T[1],T[2],t/a),p=a===t?T[2]:n.P.Lerp(u,d,e/(a-t));let f;if(p.normalize(),s){const e=n.P.Lerp(T[0],T[2],r/a),t=n.P.Lerp(T[1],T[2],r/a);f=n.P.Lerp(e,t,i/(a-r))}else f=new n.P(p.x,p.y,p.z);f.x/=l,f.y/=h,f.z/=c,f.normalize();const _=n.FM.Lerp(S[0],S[2],t/a),m=n.FM.Lerp(S[1],S[2],t/a),E=a===t?S[2]:n.FM.Lerp(_,m,e/(a-t));v.push(p.x*l,p.y*h,p.z*c),y.push(f.x,f.y,f.z),x.push(E.x,o.e.UseOpenGLOrientationForUV?1-E.y:E.y),g.push(b),b++};for(let e=0;e<a;e++)for(let i=0;i+e<a;i++)t(i,e,i+1/3,e+1/3),t(i+1,e,i+1/3,e+1/3),t(i,e+1,i+1/3,e+1/3),i+e+1<a&&(t(i+1,e,i+2/3,e+2/3),t(i+1,e+1,i+2/3,e+2/3),t(i,e+1,i+2/3,e+2/3))}r.x._ComputeSides(t,v,g,y,x,e.frontUVs,e.backUVs);const C=new r.x;return C.indices=g,C.positions=v,C.normals=y,C.uvs=x,C}function l(e,t={},i=null){const n=new s.Kj(e,i);return t.sideOrientation=s.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,a(t).applyToMesh(n,t.updatable),n}const h={CreateIcoSphere:l};r.x.CreateIcoSphere=a,s.Kj.CreateIcoSphere=(e,t,i)=>l(e,t,i)},3615:(e,t,i)=>{i.d(t,{Hq:()=>o,mx:()=>l,pT:()=>a});var n=i(4496),s=i(2101),r=i(4892);function o(e){const t=[],i=[],n=[],o=[],a=e.width||e.size||1,l=e.height||e.size||1,h=0===e.sideOrientation?0:e.sideOrientation||s.x.DEFAULTSIDE,c=a/2,u=l/2;i.push(-c,-u,0),n.push(0,0,-1),o.push(0,r.e.UseOpenGLOrientationForUV?1:0),i.push(c,-u,0),n.push(0,0,-1),o.push(1,r.e.UseOpenGLOrientationForUV?1:0),i.push(c,u,0),n.push(0,0,-1),o.push(1,r.e.UseOpenGLOrientationForUV?0:1),i.push(-c,u,0),n.push(0,0,-1),o.push(0,r.e.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),s.x._ComputeSides(h,i,t,n,o,e.frontUVs,e.backUVs);const d=new s.x;return d.indices=t,d.positions=i,d.normals=n,d.uvs=o,d}function a(e,t={},i=null){const s=new n.Kj(e,i);return t.sideOrientation=n.Kj._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,o(t).applyToMesh(s,t.updatable),t.sourcePlane&&(s.translate(t.sourcePlane.normal,-t.sourcePlane.d),s.setDirection(t.sourcePlane.normal.scale(-1))),s}const l={CreatePlane:a};s.x.CreatePlane=o,n.Kj.CreatePlane=(e,t,i,n,s)=>a(e,{size:t,width:t,height:t,sideOrientation:s,updatable:n},i)},1500:(e,t,i)=>{i.d(t,{J:()=>l});var n=i(7257),s=i(6250),r=i(2101);function o(e,t,i,n,s,r){const o=new e.DecoderBuffer;o.Init(t,t.byteLength);const a=new e.Decoder;let l,h;try{const t=a.GetEncodedGeometryType(o);switch(t){case e.TRIANGULAR_MESH:l=new e.Mesh,h=a.DecodeBufferToMesh(o,l);break;case e.POINT_CLOUD:l=new e.PointCloud,h=a.DecodeBufferToPointCloud(o,l);break;default:throw new Error(`Invalid geometry type ${t}`)}if(!h.ok()||!l.ptr)throw new Error(h.error_msg());if(t===e.TRIANGULAR_MESH){const t=3*l.num_faces(),i=4*t,s=e._malloc(i);try{a.GetTrianglesUInt32Array(l,i,s);const r=new Uint32Array(t);r.set(new Uint32Array(e.HEAPF32.buffer,s,t)),n(r)}finally{e._free(s)}}const c=(t,i,n=1)=>{const r=i.num_components(),o=l.num_points(),h=o*r,c=h*Float32Array.BYTES_PER_ELEMENT,u=e._malloc(c);try{a.GetAttributeDataArrayForAllPoints(l,i,e.DT_FLOAT32,c,u);const d=new Float32Array(e.HEAPF32.buffer,u,h);if("color"===t&&3===r){const e=new Float32Array(4*o);for(let t=0,i=0;t<e.length;t+=4,i+=r)e[t+0]=d[i+0],e[t+1]=d[i+1],e[t+2]=d[i+2],e[t+3]=1;s(t,e)}else{const i=new Float32Array(h);if(i.set(new Float32Array(e.HEAPF32.buffer,u,h)),1!==n)for(let e=0;e<i.length;e++)i[e]=i[e]/n;s(t,i)}}finally{e._free(u)}};if(i)for(const e in i){const t=i[e];c(e,a.GetAttributeByUniqueId(l,t),r&&r[e]||1)}else{const t={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"};for(const i in t){const n=a.GetAttributeId(l,e[t[i]]);-1!==n&&c(i,a.GetAttribute(l,n))}}}finally{l&&e.destroy(l),e.destroy(a),e.destroy(o)}}function a(){let e;onmessage=t=>{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&(importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary})),postMessage("done");break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{o(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",value:e},[e.buffer])}),((e,t)=>{postMessage({id:e,value:t},[t.buffer])})),postMessage("done")}))}}}class l{static get DecoderAvailable(){const e=l.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly||e.fallbackUrl)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static get Default(){return l._Default||(l._Default=new l),l._Default}constructor(e=l.DefaultNumWorkers){const t=l.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:n.w1.GetAbsoluteUrl(t.wasmUrl),wasmBinaryPromise:n.w1.LoadFileAsync(n.w1.GetAbsoluteUrl(t.wasmBinaryUrl))}:{url:n.w1.GetAbsoluteUrl(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&"function"==typeof Worker&&"function"==typeof URL?this._workerPoolPromise=i.wasmBinaryPromise.then((t=>{const n=`${o}(${a})()`,r=URL.createObjectURL(new Blob([n],{type:"application/javascript"}));return new s.v(e,(()=>new Promise(((e,n)=>{const s=new Worker(r),o=e=>{s.removeEventListener("error",o),s.removeEventListener("message",a),n(e)},a=t=>{"done"===t.data&&(s.removeEventListener("error",o),s.removeEventListener("message",a),e(s))};s.addEventListener("error",o),s.addEventListener("message",a),s.postMessage({id:"init",decoder:{url:i.url,wasmBinary:t}})}))))})):this._decoderModulePromise=i.wasmBinaryPromise.then((e=>{if(!i.url)throw new Error("Draco decoder module is not available");return n.w1.LoadScriptAsync(i.url).then((()=>{return t=e,new Promise((e=>{DracoDecoderModule({wasmBinary:t}).then((t=>{e({module:t})}))}));var t}))}))}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}whenReadyAsync(){return this._workerPoolPromise?this._workerPoolPromise.then((()=>{})):this._decoderModulePromise?this._decoderModulePromise.then((()=>{})):Promise.resolve()}decodeMeshAsync(e,t,i){const n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((s,o)=>{e.push(((e,a)=>{const l=new r.x,h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",c),o(t),a()},c=t=>{if("done"===t.data)e.removeEventListener("error",h),e.removeEventListener("message",c),s(l),a();else if("indices"===t.data.id)l.indices=t.data.value;else{const e=i&&i[t.data.id]?i[t.data.id]:1;if(1!==e)for(let i=0;i<t.data.value.length;i++)t.data.value[i]=t.data.value[i]/e;l.set(t.data.value,t.data.id)}};e.addEventListener("error",h),e.addEventListener("message",c);const u=new Uint8Array(n.byteLength);u.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{const s=new r.x;return o(e.module,n,t,(e=>{s.indices=e}),((e,t)=>{s.set(t,e)}),i),s}));throw new Error("Draco decoder module is not available")}}l.Configuration={decoder:{wasmUrl:"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://preview.babylonjs.com/draco_decoder_gltf.wasm",fallbackUrl:"https://preview.babylonjs.com/draco_decoder_gltf.js"}},l.DefaultNumWorkers=l.GetDefaultNumWorkers(),l._Default=null},9481:(e,t,i)=>{i.d(t,{K:()=>s});var n=i(7257);class s{static get Default(){return s._Default||(s._Default=new s),s._Default}constructor(){const e=s.Configuration.decoder;this._decoderModulePromise=n.w1.LoadScriptAsync(n.w1.GetAbsoluteUrl(e.url)).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,n,s){return this._decoderModulePromise.then((()=>{const r=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(r,t,i,e,n,s),r}))}}s.Configuration={decoder:{url:"https://preview.babylonjs.com/meshopt_decoder.js"}},s._Default=null},8261:(e,t,i)=>{i.d(t,{M:()=>s});var n=i(7698);class s extends n.h{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}},1795:(e,t,i)=>{i.d(t,{x:()=>T});var n=i(5757),s=i(1057),r=i(4141),o=i(7814),a=i(708),l=i(2101),h=i(4674),c=i(5670),u=i(3722),d=i(3743),p=i(9356),f=i(4934),_=i(1372),m=i(4649),g=i(1341),v=i(5203),y=i(2208);class x{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=r.P.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class b{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new x,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 p.a,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class T extends h.Y{static get BILLBOARDMODE_NONE(){return h.Y.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return h.Y.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return h.Y.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return h.Y.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return h.Y.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return h.Y.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)}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,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.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 null===(t=this._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new b,this._waitingMaterialId=null,this.cullingStrategy=T.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new n.y$,this.onCollisionPositionChangeObservable=new n.y$,this.onMaterialChangedObservable=new n.y$,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=m.Wo.Red(),this.outlineWidth=.02,this.overlayColor=m.Wo.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 r.P(.5,1,.5),this.ellipsoidOffset=new r.P(0,0,0),this.edgesWidth=1,this.edgesColor=new m.HE(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new n.y$,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>o.D.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new d.M(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case s.a.Aggressive:this.doNotSyncBoundingInfo=!0;case s.a.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+("InstancedMesh"!==this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==h.Y.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes)for(const e of this.subMeshes)e._rebuild()}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let n=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;n=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(n)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;i<t._drawWrappers.length;++i){const n=t._drawWrappers[i];n&&n.defines&&n.defines.markAllAsDirty&&e(n.defines)}}_markSubMeshesAsLightDirty(e=!1){this._markSubMeshesAsDirty((t=>t.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,n){return this}updateVerticesData(e,t,i,n){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){var e;return null!==(e=this.rawBoundingInfo)&&void 0!==e?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new u.j(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(a.o.MatricesIndicesKind)&&this.isVerticesDataPresent(a.o.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===h.Y.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const n=new r.y3;(this.rotationQuaternion?this.rotationQuaternion:r._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(n);const s=r.P.Zero(),o=this.definedFacingForward?-1:1;return r.P.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,n,s),s}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const n=this.definedFacingForward?1:-1;return new r.P(e*n,t,i*n)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=(0,_.k)(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new u.j(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t<this.subMeshes.length;t++)this.subMeshes[t].refreshBoundingInfo(e);this._updateBoundingInfo()}_getData(e=!1,t=!1,i,n=a.o.PositionKind){if((i=null!=i?i:this.getVerticesData(n).slice())&&t&&this.morphTargetManager){let e=0,t=0;for(let s=0;s<i.length;s++){for(let e=0;e<this.morphTargetManager.numTargets;e++){const t=this.morphTargetManager.getTarget(e),n=t.influence;if(n>0){const e=t.getPositions();e&&(i[s]+=(e[s]-i[s])*n)}}if(e++,n===a.o.PositionKind&&this._positions&&3===e){e=0;const n=3*t;this._positions[t++].copyFromFloats(i[n],i[n+1],i[n+2])}}}if(i&&e&&this.skeleton){const e=this.getVerticesData(a.o.MatricesIndicesKind),t=this.getVerticesData(a.o.MatricesWeightsKind);if(t&&e){const s=this.numBoneInfluencers>4,o=s?this.getVerticesData(a.o.MatricesIndicesExtraKind):null,l=s?this.getVerticesData(a.o.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this),c=r.jp.Vector3[0],u=r.jp.Matrix[0],d=r.jp.Matrix[1];let p=0;for(let f=0;f<i.length;f+=3,p+=4){let _,m;for(u.reset(),_=0;_<4;_++)m=t[p+_],m>0&&(r.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*e[p+_]),m,d),u.addToSelf(d));if(s)for(_=0;_<4;_++)m=l[p+_],m>0&&(r.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*o[p+_]),m,d),u.addToSelf(d));n===a.o.NormalKind?r.P.TransformNormalFromFloatsToRef(i[f],i[f+1],i[f+2],u,c):r.P.TransformCoordinatesFromFloatsToRef(i[f],i[f+1],i[f+2],u,c),c.toArray(i,f),n===a.o.PositionKind&&this._positions&&this._positions[f/3].copyFrom(c)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,a.o.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,a.o.PositionKind)}_getPositionData(e,t){var i;let n=this.getVerticesData(a.o.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),n&&(e&&this.skeleton||t&&this.morphTargetManager)){if(n=n.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t<e.length;t++)this._internalAbstractMeshDataInfo._positions[t]=(null===(i=e[t])||void 0===i?void 0:i.clone())||new r.P}return this.getPositionData(e,t,n)}return n}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new u.j(r.P.Zero(),r.P.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}_updateSubMeshesBoundingInfo(e){if(!this.subMeshes)return this;const t=this.subMeshes.length;for(let i=0;i<t;i++){const n=this.subMeshes[i];(t>1||!n.IsGlobal)&&n.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const n=this.getBoundingInfo(),s=e.getBoundingInfo();if(n.intersects(s,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.intersectsMesh(e,t,!0))return!0;return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){var n;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,n=e.verticesStart+e.verticesCount;for(let s=i;s<n;s++)e._lastColliderWorldVertices.push(r.P.TransformCoordinates(this._positions[s],t))}return i._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),7===(null===(n=e.getMaterial())||void 0===n?void 0:n.fillMode)),this}_processCollisionsForSubMeshes(e,t){const i=this._scene.getCollidingSubMeshCandidates(this,e),n=i.length;for(let s=0;s<n;s++){const r=i.data[s];n>1&&!r._checkCollision(e)||this._collideForSubMesh(r,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=r.jp.Matrix[0],i=r.jp.Matrix[1];return r.y3.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,n=!1,s,o=!1){const a=new c.p,l="InstancedLinesMesh"===this.getClassName()||"LinesMesh"===this.getClassName()?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(o||e.intersectsSphere(h.boundingSphere,l)&&e.intersectsBox(h.boundingBox,l)))return a;if(n)return a.hit=!o,a.pickedMesh=o?null:this,a.distance=o?0:r.P.Distance(e.origin,h.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let u=null;const d=this._scene.getIntersectingSubMeshCandidates(this,e),p=d.length;let f=!1;for(let e=0;e<p;e++){const t=d.data[e].getMaterial();if(t&&(7==t.fillMode||0==t.fillMode||1==t.fillMode||2==t.fillMode||4==t.fillMode)){f=!0;break}}if(!f)return a.hit=!0,a.pickedMesh=this,a.distance=r.P.Distance(e.origin,h.boundingSphere.center),a.subMeshId=-1,a;for(let n=0;n<p;n++){const s=d.data[n];if(p>1&&!s.canIntersects(e))continue;const r=s.intersects(e,this._positions,this.getIndices(),t,i);if(r&&(t||!u||r.distance<u.distance)&&(u=r,u.subMeshId=n,t))break}if(u){const t=null!=s?s:this.getWorldMatrix(),i=r.jp.Vector3[0],n=r.jp.Vector3[1];r.P.TransformCoordinatesToRef(e.origin,t,i),e.direction.scaleToRef(u.distance,n);const o=r.P.TransformNormal(n,t).addInPlace(i);return a.hit=!0,a.distance=r.P.Distance(i,o),a.pickedPoint=o,a.pickedMesh=this,a.bu=u.bu||0,a.bv=u.bv||0,a.subMeshFaceId=u.faceId,a.faceId=u.faceId+d.data[u.subMeshId].indexStart/(-1!==this.getClassName().indexOf("LinesMesh")?2:3),a.subMeshId=u.subMeshId,a}return a}clone(e,t,i){return null}releaseSubMeshes(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=new Array;return this}dispose(e,t=!1){let i;for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this.getScene().freeActiveMeshes(),this.getScene().freeRenderingGroups(),void 0!==this.actionManager&&null!==this.actionManager&&(this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i<this._intersectionsInProgress.length;i++){const e=this._intersectionsInProgress[i],t=e._intersectionsInProgress.indexOf(this);e._intersectionsInProgress.splice(t,1)}this._intersectionsInProgress.length=0,this.getScene().lights.forEach((e=>{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const n=this.getScene().getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),this.getScene().removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i<this.getScene().particleSystems.length;i++)this.getScene().particleSystems[i].emitter===this&&(this.getScene().particleSystems[i].dispose(),i--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),super.dispose(e,t)}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.setParent(null,t),this}_initFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=new Array),e.facetPositions||(e.facetPositions=new Array),e.facetPartitioning||(e.facetPartitioning=new Array),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(let t=0;t<e.facetNb;t++)e.facetNormals[t]=r.P.Zero(),e.facetPositions[t]=r.P.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();const t=this.getVerticesData(a.o.PositionKind),i=this.getIndices(),n=this.getVerticesData(a.o.NormalKind),s=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,i instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(i);else if(i instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(i);else{let t=!1;for(let e=0;e<i.length;e++)if(i[e]>65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:r.P.Zero()}e.depthSortedFacets=[];for(let t=0;t<e.facetNb;t++){const i={ind:3*t,sqDistance:0};e.depthSortedFacets.push(i)}e.invertedMatrix=r.y3.Identity(),e.facetDepthSortOrigin=r.P.Zero()}e.bbSize.x=s.maximum.x-s.minimum.x>g.kn?s.maximum.x-s.minimum.x:g.kn,e.bbSize.y=s.maximum.y-s.minimum.y>g.kn?s.maximum.y-s.minimum.y:g.kn,e.bbSize.z=s.maximum.z-s.minimum.z>g.kn?s.maximum.z-s.minimum.z:g.kn;let o=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(o=o>e.bbSize.z?o:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/o),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/o),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/o),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=s,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),r.P.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,n&&l.x.ComputeNormals(t,i,n,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let n=0;n<t;n++){const t=e.depthSortedFacets[n].ind;e.depthSortedIndices[3*n]=i[t],e.depthSortedIndices[3*n+1]=i[t+1],e.depthSortedIndices[3*n+2]=i[t+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this}getFacetLocalNormals(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals}getFacetLocalPositions(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions}getFacetLocalPartitioning(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning}getFacetPosition(e){const t=r.P.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){const i=this.getFacetLocalPositions()[e],n=this.getWorldMatrix();return r.P.TransformCoordinatesToRef(i,n,t),this}getFacetNormal(e){const t=r.P.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){const i=this.getFacetLocalNormals()[e];return r.P.TransformNormalToRef(i,this.getWorldMatrix(),t),this}getFacetsAtLocalCoordinates(e,t,i){const n=this.getBoundingInfo(),s=this._internalAbstractMeshDataInfo._facetData,r=Math.floor((e-n.minimum.x*s.partitioningBBoxRatio)*s.subDiv.X*s.partitioningBBoxRatio/s.bbSize.x),o=Math.floor((t-n.minimum.y*s.partitioningBBoxRatio)*s.subDiv.Y*s.partitioningBBoxRatio/s.bbSize.y),a=Math.floor((i-n.minimum.z*s.partitioningBBoxRatio)*s.subDiv.Z*s.partitioningBBoxRatio/s.bbSize.z);return r<0||r>s.subDiv.max||o<0||o>s.subDiv.max||a<0||a>s.subDiv.max?null:s.facetPartitioning[r+s.subDiv.max*o+s.subDiv.max*s.subDiv.max*a]}getClosestFacetAtCoordinates(e,t,i,n,s=!1,o=!0){const a=this.getWorldMatrix(),l=r.jp.Matrix[5];a.invertToRef(l);const h=r.jp.Vector3[8];r.P.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);const c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,n,s,o);return n&&r.P.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,a,n),c}getClosestFacetAtLocalCoordinates(e,t,i,n,s=!1,r=!0){let o=null,a=0,l=0,h=0,c=0,u=0,d=0,p=0,f=0;const _=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,y,x,b=Number.MAX_VALUE,T=b;for(let S=0;S<g.length;S++)v=g[S],y=m[v],x=_[v],c=(e-x.x)*y.x+(t-x.y)*y.y+(i-x.z)*y.z,(!s||s&&r&&c>=0||s&&!r&&c<=0)&&(c=y.x*x.x+y.y*x.y+y.z*x.z,u=-(y.x*e+y.y*t+y.z*i-c)/(y.x*y.x+y.y*y.y+y.z*y.z),d=e+y.x*u,p=t+y.y*u,f=i+y.z*u,a=d-e,l=p-t,h=f-i,T=a*a+l*l+h*h,T<b&&(b=T,o=v,n&&(n.x=d,n.y=p,n.z=f)));return o}getFacetDataParameters(){return this._internalAbstractMeshDataInfo._facetData.facetParameters}disableFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=new Array,e.facetNormals=new Array,e.facetPartitioning=new Array,e.facetParameters=null,e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,i=!1){return this}createNormals(e){const t=this.getVerticesData(a.o.PositionKind),i=this.getIndices();let n;return n=this.isVerticesDataPresent(a.o.NormalKind)?this.getVerticesData(a.o.NormalKind):[],l.x.ComputeNormals(t,i,n,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(a.o.NormalKind,n,e),this}alignWithNormal(e,t){t||(t=v.RD.Y);const i=r.jp.Vector3[0],n=r.jp.Vector3[1];return r.P.CrossToRef(t,e,n),r.P.CrossToRef(e,n,i),this.rotationQuaternion?r._f.RotationQuaternionFromAxisToRef(i,e,n,this.rotationQuaternion):r.P.RotationFromAxisToRef(i,e,n,this.rotation),this}_checkOcclusionQuery(){return!1}disableEdgesRendering(){throw(0,f.S)("EdgesRenderer")}enableEdgesRendering(e,t,i){throw(0,f.S)("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter((e=>e.emitter===this))}}T.OCCLUSION_TYPE_NONE=0,T.OCCLUSION_TYPE_OPTIMISTIC=1,T.OCCLUSION_TYPE_STRICT=2,T.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,T.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,T.CULLINGSTRATEGY_STANDARD=0,T.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,T.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,T.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,(0,y.H)("BABYLON.AbstractMesh",T)},7321:(e,t,i)=>{i.d(t,{Z:()=>_});var n=i(4141),s=i(4649),r=i(2101),o=i(708),a=i(9401),l=i(1376),h=i(3722),c=i(7257),u=i(4875),d=i(1372),p=i(1431),f=i(4892);class _{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 _(_.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,n=!1,s=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||p.l.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=n,i?this.setAllVerticesData(i,n):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0}_rebuild(){this._vertexArrayObjects&&(this._vertexArrayObjects={}),0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable));for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild()}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,n){i&&Array.isArray(t)&&(t=new Float32Array(t));const s=new o.o(this._engine,t,e,i,0===this._meshes.length,n);this.setVerticesBuffer(s)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const n=e.getKind();this._vertexBuffers[n]&&i&&this._vertexBuffers[n].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[n]=e;const s=this._meshes,r=s.length;if(n===o.o.PositionKind){const i=e.getData();null!=t?this._totalVertices=t:null!=i&&(this._totalVertices=i.length/(e.type===o.o.BYTE?e.byteStride:e.byteStride/4)),this._updateExtend(i),this._resetPointsArrayCache();for(let e=0;e<r;e++){const t=s[e];t.buildBoundingInfo(this._extend.minimum,this._extend.maximum),t._createGlobalSubMesh(t.isUnIndexed),t.computeWorldMatrix(!0),t.synchronizeInstances()}}this._notifyUpdate(n)}updateVerticesDataDirectly(e,t,i,n=!1){const s=this.getVertexBuffer(e);s&&(s.updateDirectly(t,i,n),this._notifyUpdate(e))}updateVerticesData(e,t,i=!1){const n=this.getVertexBuffer(e);n&&(n.update(t),e===o.o.PositionKind&&this._updateBoundingInfo(i,t),this._notifyUpdate(e))}_updateBoundingInfo(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e){const e=this._meshes;for(const t of e){t.hasBoundingInfo?t.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):t.buildBoundingInfo(this._extend.minimum,this._extend.maximum);const e=t.subMeshes;for(const t of e)t.refreshBoundingInfo()}}}_bind(e,t,i,n){if(!e)return;void 0===t&&(t=this._indexBuffer);const s=this.getVertexBuffers();if(!s)return;if(t!=this._indexBuffer||!this._vertexArrayObjects&&!n)return void this._engine.bindBuffers(s,t,e,i);const r=n||this._vertexArrayObjects;r[e.key]||(r[e.key]=this._engine.recordVertexArrayObject(s,t,e,i)),this._engine.bindVertexArrayObject(r[e.key],t)}getTotalVertices(){return this.isReady()?this._totalVertices:0}getVerticesData(e,t,i){const n=this.getVertexBuffer(e);return n?n.getFloatData(this._totalVertices,i||t&&1!==this._meshes.length):null}isVertexBufferUpdatable(e){const t=this._vertexBuffers[e];return!!t&&t.isUpdatable()}getVertexBuffer(e){return this.isReady()?this._vertexBuffers[e]:null}getVertexBuffers(){return this.isReady()?this._vertexBuffers:null}isVerticesDataPresent(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}getVerticesDataKinds(){const e=[];let t;if(!this._vertexBuffers&&this._delayInfo)for(t in this._delayInfo)e.push(t);else for(t in this._vertexBuffers)e.push(t);return e}updateIndices(e,t,i=!1){if(this._indexBuffer)if(this._indexBufferIsUpdatable){const n=e.length!==this._indices.length;if(i||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),n)for(const e of this._meshes)e._createGlobalSubMesh(!0)}else this.setIndices(e,null,!0)}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i)),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}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,n=i.indexOf(e);-1!==n&&(i.splice(n,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&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(o.o.PositionKind)))return;this._extend=(0,d.k)(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===o.o.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&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 e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const n=this._meshes,s=n.length;for(let e=0;e<s;e++)this._applyToMesh(n[e]);t&&t()}),void 0,!0))}toLeftHanded(){const e=this.getIndices(!1);if(null!=e&&e.length>0){for(let t=0;t<e.length;t+=3){const i=e[t+0];e[t+0]=e[t+2],e[t+2]=i}this.setIndices(e)}const t=this.getVerticesData(o.o.PositionKind,!1);if(null!=t&&t.length>0){for(let e=0;e<t.length;e+=3)t[e+2]=-t[e+2];this.setVerticesData(o.o.PositionKind,t,!1)}const i=this.getVerticesData(o.o.NormalKind,!1);if(null!=i&&i.length>0){for(let e=0;e<i.length;e+=3)i[e+2]=-i[e+2];this.setVerticesData(o.o.NormalKind,i,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;const e=this.getVerticesData(o.o.PositionKind);if(!e||0===e.length)return!1;for(let t=3*this._positionsCache.length,i=this._positionsCache.length;t<e.length;t+=3,++i)this._positionsCache[i]=n.P.FromArray(e,t);for(let t=0,i=0;t<e.length;t+=3,++i)this._positionsCache[i].set(e[0+t],e[1+t],e[2+t]);return this._positionsCache.length=e.length/3,this._positions=this._positionsCache,!0}isDisposed(){return this._isDisposed}_disposeVertexArrayObjects(){if(this._vertexArrayObjects){for(const e in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e]);this._vertexArrayObjects={};const e=this._meshes,t=e.length;for(let i=0;i<t;i++)e[i]._invalidateInstanceVertexArrayObject()}}dispose(){const e=this._meshes,t=e.length;let i;for(i=0;i<t;i++)this.releaseForMesh(e[i]);this._meshes.length=0,this._disposeVertexArrayObjects();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=0,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){const e=this._parentContainer.geometries.indexOf(this);e>-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new r.x;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e<i.length;e++)t.indices.push(i[e]);let n,s=!1,o=!1;for(n in this._vertexBuffers){const e=this.getVerticesData(n);if(e&&(e instanceof Float32Array?t.set(new Float32Array(e),n):t.set(e.slice(0),n),!o)){const e=this.getVertexBuffer(n);e&&(s=e.isUpdatable(),o=!s)}}const a=new _(e,this._scene,t,s);for(n in a.delayLoadState=this.delayLoadState,a.delayLoadingFile=this.delayLoadingFile,a._delayLoadingFunction=this._delayLoadingFunction,this._delayInfo)a._delayInfo=a._delayInfo||[],a._delayInfo.push(n);return a._boundingInfo=new h.j(this._extend.minimum,this._extend.maximum),a}serialize(){const e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,u.$&&u.$.HasTags(this)&&(e.tags=u.$.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){this._indices=[],this._resetPointsArrayCache();for(const e in this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){const e=this.serialize();return this.isVerticesDataPresent(o.o.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(o.o.PositionKind)),this.isVertexBufferUpdatable(o.o.PositionKind)&&(e.positions._updatable=!0)),this.isVerticesDataPresent(o.o.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(o.o.NormalKind)),this.isVertexBufferUpdatable(o.o.NormalKind)&&(e.normals._updatable=!0)),this.isVerticesDataPresent(o.o.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(o.o.TangentKind)),this.isVertexBufferUpdatable(o.o.TangentKind)&&(e.tangents._updatable=!0)),this.isVerticesDataPresent(o.o.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(o.o.UVKind)),this.isVertexBufferUpdatable(o.o.UVKind)&&(e.uvs._updatable=!0)),this.isVerticesDataPresent(o.o.UV2Kind)&&(e.uv2s=this._toNumberArray(this.getVerticesData(o.o.UV2Kind)),this.isVertexBufferUpdatable(o.o.UV2Kind)&&(e.uv2s._updatable=!0)),this.isVerticesDataPresent(o.o.UV3Kind)&&(e.uv3s=this._toNumberArray(this.getVerticesData(o.o.UV3Kind)),this.isVertexBufferUpdatable(o.o.UV3Kind)&&(e.uv3s._updatable=!0)),this.isVerticesDataPresent(o.o.UV4Kind)&&(e.uv4s=this._toNumberArray(this.getVerticesData(o.o.UV4Kind)),this.isVertexBufferUpdatable(o.o.UV4Kind)&&(e.uv4s._updatable=!0)),this.isVerticesDataPresent(o.o.UV5Kind)&&(e.uv5s=this._toNumberArray(this.getVerticesData(o.o.UV5Kind)),this.isVertexBufferUpdatable(o.o.UV5Kind)&&(e.uv5s._updatable=!0)),this.isVerticesDataPresent(o.o.UV6Kind)&&(e.uv6s=this._toNumberArray(this.getVerticesData(o.o.UV6Kind)),this.isVertexBufferUpdatable(o.o.UV6Kind)&&(e.uv6s._updatable=!0)),this.isVerticesDataPresent(o.o.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(o.o.ColorKind)),this.isVertexBufferUpdatable(o.o.ColorKind)&&(e.colors._updatable=!0)),this.isVerticesDataPresent(o.o.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(o.o.MatricesIndicesKind)),e.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(o.o.MatricesIndicesKind)&&(e.matricesIndices._updatable=!0)),this.isVerticesDataPresent(o.o.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(o.o.MatricesWeightsKind)),this.isVertexBufferUpdatable(o.o.MatricesWeightsKind)&&(e.matricesWeights._updatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){const i=e._geometry;return i?i.copy(t):null}static RandomId(){return c.w1.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let i=0;i<t.geometries.length;i++)if(t.geometries[i]._loadedUniqueId===e)return t.geometries[i];return null}static _ImportGeometry(e,t){const i=t.getScene(),n=e.geometryUniqueId,r=e.geometryId;if(n||r){const e=n?this._GetGeometryByLoadedUniqueId(n,i):i.getGeometryById(r);e&&e.applyToMesh(t)}else if(e instanceof ArrayBuffer){const i=t._binaryInfo;if(i.positionsAttrDesc&&i.positionsAttrDesc.count>0){const n=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(o.o.PositionKind,n,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const n=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(o.o.NormalKind,n,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const n=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(o.o.TangentKind,n,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const n=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e<n.length;e+=2)n[e]=1-n[e];t.setVerticesData(o.o.UVKind,n,!1)}if(i.uvs2AttrDesc&&i.uvs2AttrDesc.count>0){const n=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e<n.length;e+=2)n[e]=1-n[e];t.setVerticesData(o.o.UV2Kind,n,!1)}if(i.uvs3AttrDesc&&i.uvs3AttrDesc.count>0){const n=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e<n.length;e+=2)n[e]=1-n[e];t.setVerticesData(o.o.UV3Kind,n,!1)}if(i.uvs4AttrDesc&&i.uvs4AttrDesc.count>0){const n=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e<n.length;e+=2)n[e]=1-n[e];t.setVerticesData(o.o.UV4Kind,n,!1)}if(i.uvs5AttrDesc&&i.uvs5AttrDesc.count>0){const n=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e<n.length;e+=2)n[e]=1-n[e];t.setVerticesData(o.o.UV5Kind,n,!1)}if(i.uvs6AttrDesc&&i.uvs6AttrDesc.count>0){const n=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e<n.length;e+=2)n[e]=1-n[e];t.setVerticesData(o.o.UV6Kind,n,!1)}if(i.colorsAttrDesc&&i.colorsAttrDesc.count>0){const n=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(o.o.ColorKind,n,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const n=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e<n.length;e++){const t=n[e];s.push(255&t),s.push((65280&t)>>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(o.o.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const n=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e<n.length;e++){const t=n[e];s.push(255&t),s.push((65280&t)>>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(o.o.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const n=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(o.o.MatricesWeightsKind,n,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const n=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(n,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const n=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e<i.subMeshesAttrDesc.count;e++){const i=n[5*e+0],s=n[5*e+1],r=n[5*e+2],o=n[5*e+3],l=n[5*e+4];a.P.AddToMesh(i,s,r,o,l,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(o.o.PositionKind,e.positions,e.positions._updatable),t.setVerticesData(o.o.NormalKind,e.normals,e.normals._updatable),e.tangents&&t.setVerticesData(o.o.TangentKind,e.tangents,e.tangents._updatable),e.uvs&&t.setVerticesData(o.o.UVKind,e.uvs,e.uvs._updatable),e.uvs2&&t.setVerticesData(o.o.UV2Kind,e.uvs2,e.uvs2._updatable),e.uvs3&&t.setVerticesData(o.o.UV3Kind,e.uvs3,e.uvs3._updatable),e.uvs4&&t.setVerticesData(o.o.UV4Kind,e.uvs4,e.uvs4._updatable),e.uvs5&&t.setVerticesData(o.o.UV5Kind,e.uvs5,e.uvs5._updatable),e.uvs6&&t.setVerticesData(o.o.UV6Kind,e.uvs6,e.uvs6._updatable),e.colors&&t.setVerticesData(o.o.ColorKind,s.HE.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices)if(e.matricesIndices._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(o.o.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable);else{const i=[];for(let t=0;t<e.matricesIndices.length;t++){const n=e.matricesIndices[t];i.push(255&n),i.push((65280&n)>>8),i.push((16711680&n)>>16),i.push(n>>24&255)}t.setVerticesData(o.o.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(o.o.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t<e.matricesIndicesExtra.length;t++){const n=e.matricesIndicesExtra[t];i.push(255&n),i.push((65280&n)>>8),i.push((16711680&n)>>16),i.push(n>>24&255)}t.setVerticesData(o.o.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(_._CleanMatricesWeights(e,t),t.setVerticesData(o.o.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(o.o.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i<e.subMeshes.length;i++){const n=e.subMeshes[i];a.P.AddToMesh(n.materialIndex,n.verticesStart,n.verticesCount,n.indexStart,n.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),i.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){const i=.001;if(!l.Z.CleanBoneMatrixWeights)return;let n=0;if(!(e.skeletonId>-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;n=i.bones.length}const s=t.getVerticesData(o.o.MatricesIndicesKind),r=t.getVerticesData(o.o.MatricesIndicesExtraKind),a=e.matricesWeights,h=e.matricesWeightsExtra,c=e.numBoneInfluencer,u=a.length;for(let e=0;e<u;e+=4){let t=0,o=-1;for(let n=0;n<4;n++){const s=a[e+n];t+=s,s<i&&o<0&&(o=n)}if(h)for(let n=0;n<4;n++){const s=h[e+n];t+=s,s<i&&o<0&&(o=n+4)}if((o<0||o>c-1)&&(o=c-1),t>i){const i=1/t;for(let t=0;t<4;t++)a[e+t]*=i;if(h)for(let t=0;t<4;t++)h[e+t]*=i}else o>=4?(h[e+o-4]=1-t,r[e+o-4]=n):(a[e+o]=1-t,s[e+o]=n)}t.setVerticesData(o.o.MatricesIndicesKind,s),e.matricesWeightsExtra&&t.setVerticesData(o.o.MatricesIndicesExtraKind,r)}static Parse(e,t,i){const s=new _(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,u.$&&u.$.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new h.j(n.P.FromArray(e.boundingBoxMinimum),n.P.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(o.o.UVKind),e.hasUVs2&&s._delayInfo.push(o.o.UV2Kind),e.hasUVs3&&s._delayInfo.push(o.o.UV3Kind),e.hasUVs4&&s._delayInfo.push(o.o.UV4Kind),e.hasUVs5&&s._delayInfo.push(o.o.UV5Kind),e.hasUVs6&&s._delayInfo.push(o.o.UV6Kind),e.hasColors&&s._delayInfo.push(o.o.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(o.o.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(o.o.MatricesWeightsKind),s._delayLoadingFunction=r.x.ImportVertexData):r.x.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}},8475:(e,t,i)=>{i.d(t,{E:()=>o});var n=i(4141),s=i(708),r=i(4496);r.Kj._GroundMeshParser=(e,t)=>o.Parse(e,t);class o extends r.Kj{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=n.jp.Matrix[5];i.invertToRef(s);const r=n.jp.Vector3[8];if(n.P.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e<this._minX||e>=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t),a=-(o.x*e+o.z*t+o.w)/o.y;return n.P.TransformCoordinatesFromFloatsToRef(0,a,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new n.P(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=n.jp.Matrix[5];s.invertToRef(r);const o=n.jp.Vector3[8];if(n.P.TransformCoordinatesFromFloatsToRef(e,0,t,r,o),e=o.x,t=o.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return n.P.TransformNormalFromFloatsToRef(a.x,a.y,a.z,s,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),n=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[n*this._subdivisionsX+i];let r;return r=t<s.slope.x*e+s.slope.y?s.facet1:s.facet2,r}_initHeightQuads(){const e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=new Array;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const s={slope:n.FM.Zero(),facet1:new n.Lt(0,0,0,0),facet2:new n.Lt(0,0,0,0)};this._heightQuads[i*e+t]=s}return this}_computeHeightQuads(){const e=this.getVerticesData(s.o.PositionKind);if(!e)return this;const t=n.jp.Vector3[3],i=n.jp.Vector3[2],r=n.jp.Vector3[1],o=n.jp.Vector3[0],a=n.jp.Vector3[4],l=n.jp.Vector3[5],h=n.jp.Vector3[6],c=n.jp.Vector3[7],u=n.jp.Vector3[8];let d=0,p=0,f=0,_=0,m=0,g=0,v=0;const y=this._subdivisionsX,x=this._subdivisionsY;for(let s=0;s<x;s++)for(let x=0;x<y;x++){d=3*x,p=s*(y+1)*3,f=(s+1)*(y+1)*3,t.x=e[p+d],t.y=e[p+d+1],t.z=e[p+d+2],i.x=e[p+d+3],i.y=e[p+d+4],i.z=e[p+d+5],r.x=e[f+d],r.y=e[f+d+1],r.z=e[f+d+2],o.x=e[f+d+3],o.y=e[f+d+4],o.z=e[f+d+5],_=(o.z-t.z)/(o.x-t.x),m=t.z-_*t.x,i.subtractToRef(t,a),r.subtractToRef(t,l),o.subtractToRef(t,h),n.P.CrossToRef(h,l,c),n.P.CrossToRef(a,h,u),c.normalize(),u.normalize(),g=-(c.x*t.x+c.y*t.y+c.z*t.z),v=-(u.x*i.x+u.y*i.y+u.z*i.z);const b=this._heightQuads[s*y+x];b.slope.copyFromFloats(_,m),b.facet1.copyFromFloats(c.x,c.y,c.z,g),b.facet2.copyFromFloats(u.x,u.y,u.z,v)}return this}serialize(e){super.serialize(e),e.subdivisionsX=this._subdivisionsX,e.subdivisionsY=this._subdivisionsY,e.minX=this._minX,e.maxX=this._maxX,e.minZ=this._minZ,e.maxZ=this._maxZ,e.width=this._width,e.height=this._height}static Parse(e,t){const i=new o(e.name,t);return i._subdivisionsX=e.subdivisionsX||1,i._subdivisionsY=e.subdivisionsY||1,i._minX=e.minX,i._maxX=e.maxX,i._minZ=e.minZ,i._maxZ=e.maxZ,i._width=e.width,i._height=e.height,i}}},7338:(e,t,i)=>{i.d(t,{S:()=>u});var n=i(4141),s=i(2722),r=i(1795),o=i(4496),a=i(6387),l=i(4674),h=i(708),c=i(7257);o.Kj._instancedMeshFactory=(e,t)=>{const i=new u(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class u extends r.x{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.receiveShadows)!==e&&c.w1.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.material)!==e&&c.w1.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.visibility)!==e&&c.w1.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.skeleton)!==e&&c.w1.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&&s.Y.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,n){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,n),this.sourceMesh}updateVerticesData(e,t,i,n){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,n),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||s.Y.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!==l.Y.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new n.y3);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,n.jp.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(n.jp.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this}_generatePointsArray(){return this._sourceMesh._generatePointsArray()}_updateBoundingInfo(){return this.hasBoundingInfo?this.getBoundingInfo().update(this.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}clone(e,t=null,i,n){const s=(n||this._sourceMesh).createInstance(e);if(a.j.DeepCopy(this,s,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","hasBoundingInfo"],[]),this.refreshBoundingInfo(),t&&(s.parent=t),!i)for(let e=0;e<this.getScene().meshes.length;e++){const t=this.getScene().meshes[e];t.parent===this&&t.clone(t.name,s)}return s.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(s),s}dispose(e,t=!1){this._sourceMesh.removeInstance(this),super.dispose(e,t)}_serializeAsParent(e){super._serializeAsParent(e),e.parentId=this._sourceMesh.uniqueId,e.parentInstanceIndex=this._indexInSourceMeshInstanceArray}instantiateHierarchy(e=null,t,i){const n=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0,t&&t.newSourcedMesh);n&&i&&i(this,n);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(n,t,i);return n}}o.Kj.prototype.registerInstancedBuffer=function(e,t){var i,n;if(null===(n=null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e])||void 0===n||n.dispose(),!this.instancedBuffers){this.instancedBuffers={};for(const e of this.instances)e.instancedBuffers={};this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0})}this.instancedBuffers[e]=null,this._userInstancedBuffersStorage.strides[e]=t,this._userInstancedBuffersStorage.sizes[e]=32*t,this._userInstancedBuffersStorage.data[e]=new Float32Array(this._userInstancedBuffersStorage.sizes[e]),this._userInstancedBuffersStorage.vertexBuffers[e]=new h.o(this.getEngine(),this._userInstancedBuffersStorage.data[e],e,!0,!1,t,!0);for(const t of this.instances)t.instancedBuffers[e]=null;this._invalidateInstanceVertexArrayObject(),this._markSubMeshesAsAttributesDirty()},o.Kj.prototype._processInstancedBuffers=function(e,t){const i=e?e.length:0;for(const n in this.instancedBuffers){let s=this._userInstancedBuffersStorage.sizes[n];const r=this._userInstancedBuffersStorage.strides[n],o=(i+1)*r;for(;s<o;)s*=2;this._userInstancedBuffersStorage.data[n].length!=s&&(this._userInstancedBuffersStorage.data[n]=new Float32Array(s),this._userInstancedBuffersStorage.sizes[n]=s,this._userInstancedBuffersStorage.vertexBuffers[n]&&(this._userInstancedBuffersStorage.vertexBuffers[n].dispose(),this._userInstancedBuffersStorage.vertexBuffers[n]=null));const a=this._userInstancedBuffersStorage.data[n];let l=0;if(t){const e=this.instancedBuffers[n];e.toArray?e.toArray(a,l):e.copyToArray?e.copyToArray(a,l):a[l]=e,l+=r}for(let t=0;t<i;t++){const i=e[t].instancedBuffers[n];i.toArray?i.toArray(a,l):i.copyToArray?i.copyToArray(a,l):a[l]=i,l+=r}this._userInstancedBuffersStorage.vertexBuffers[n]?this._userInstancedBuffersStorage.vertexBuffers[n].updateDirectly(a,0):(this._userInstancedBuffersStorage.vertexBuffers[n]=new h.o(this.getEngine(),this._userInstancedBuffersStorage.data[n],n,!0,!1,r,!0),this._invalidateInstanceVertexArrayObject())}},o.Kj.prototype._invalidateInstanceVertexArrayObject=function(){if(this._userInstancedBuffersStorage&&void 0!==this._userInstancedBuffersStorage.vertexArrayObjects){for(const e in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[e]);this._userInstancedBuffersStorage.vertexArrayObjects={}}},o.Kj.prototype._disposeInstanceSpecificData=function(){for(this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(const e in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[e]&&this._userInstancedBuffersStorage.vertexBuffers[e].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}}},8591:(e,t,i)=>{i.d(t,{E:()=>c,_:()=>h});var n=i(4649),s=i(708),r=i(4496),o=i(7338),a=i(7104),l=i(8097);i(6980),i(9753),r.Kj._LinesMeshParser=(e,t)=>h.Parse(e,t);class h extends r.Kj{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,r=null,o,a,h,c){super(e,t,i,r,o),this.useVertexColor=a,this.useVertexAlpha=h,this.color=new n.Wo(1,1,1),this.alpha=1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;const u={attributes:[s.o.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===h?u.needAlphaBlending=!1:u.defines.push("#define VERTEXALPHA"),a?(u.defines.push("#define VERTEXCOLOR"),u.attributes.push(s.o.ColorKind)):(u.uniforms.push("color"),this._color4=new n.HE),c?this.material=c:(this.material=new l.j("colorShader",this.getScene(),"color",u,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=a.F.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(this._userInstancedBuffersStorage?this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,i),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const n=this.getScene().getEngine();return this._unIndexed?n.drawArraysType(a.F.LineListDrawMode,e.verticesStart,e.verticesCount,i):n.drawElementsType(a.F.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 h(e,this.getScene(),t,this,i)}createInstance(e){const t=new c(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new h(e.name,t);return i.color=n.Wo.FromArray(e.color),i.alpha=e.alpha,i}}class c extends o.S{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}},4496:(e,t,i)=>{i.d(t,{Kj:()=>O,Wv:()=>M,gW:()=>P});var n=i(5757),s=i(7257),r=i(6387),o=i(4875),a=i(2697),l=i(2704),h=i(1057),c=i(4141),u=i(4649),d=i(9257),p=i(708),f=i(2101),_=i(7321),m=i(1795),g=i(9401),v=i(7104),y=i(9828),x=i(1376),b=i(3956),T=i(2722),S=i(2208),E=i(4934),C=i(2333),A=i(447);class P{}class R{constructor(){this.visibleInstances={},this.batchCache=new M,this.batchCacheReplacementModeInFrozenMode=new M,this.instancesBufferSize=2048}}class M{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=new Array,this.hardwareInstancedRendering=new Array}}class I{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class D{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 O extends m.x{static _GetDefaultSideOrientation(e){return e||O.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.o.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(p.o.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new n.y$),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new n.y$),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new n.y$),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new n.y$),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new n.y$),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){var e;return(null!==(e=this._thinInstanceDataStorage.instancesCount)&&void 0!==e?e:0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get 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,a,l=!0){if(super(e,t),this._internalMeshDataInfo=new D,this.delayLoadState=0,this.instances=new Array,this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new R,this._thinInstanceDataStorage=new I,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=O.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},s){if(s._geometry&&s._geometry.applyToMesh(this),r.j.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"],["_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 e=s._ranges;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,o.$&&o.$.HasTags(s)&&o.$.AddTagsTo(this,o.$.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,!a){const t=s.getDescendants(!0);for(let i=0;i<t.length;i++){const n=t[i];n.clone&&n.clone(e+"."+n.name,this)}}if(s.morphTargetManager&&(this.morphTargetManager=s.morphTargetManager),t.getPhysicsEngine){const e=t.getPhysicsEngine();if(l&&e)if(1===e.getPluginVersion()){const t=e.getImpostorForPhysicsObject(s);t&&(this.physicsImpostor=t.clone(this))}else 2===e.getPluginVersion()&&s.physicsBody&&s.physicsBody.clone(this)}for(let e=0;e<t.particleSystems.length;e++){const i=t.particleSystems[e];i.emitter===s&&i.clone(i.name,this)}this.skeleton=s.skeleton,this.refreshBoundingInfo(!0,!0),this.computeWorldMatrix(!0)}null!==i&&(this.parent=i),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=e=>{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add((()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))})))},this.onMeshReadyObservable=new n.y$(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const n=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));n.parent=e||this.parent,n.position=this.position.clone(),n.scaling=this.scaling.clone(),this.rotationQuaternion?n.rotationQuaternion=this.rotationQuaternion.clone():n.rotation=this.rotation.clone(),i&&i(this,n);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===n.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(n,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:n},i):e.instantiateHierarchy(n,t,i);return n}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);if(e)if(this._geometry){const e=this.getIndices(),i=this.getVerticesData(p.o.PositionKind);i&&e&&(t+=", flat shading: "+(i.length/3===e.length?"YES":"NO"))}else t+=", flat shading: UNKNOWN";return t}_unBindEffect(){super._unBindEffect();for(const e of this.instances)e._unBindEffect()}get hasLODLevels(){return this._internalMeshDataInfo._LODLevels.length>0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,i)=>t.distanceOrScreenCoverage<i.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>i.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return T.Y.Warn("You cannot use a mesh as LOD level twice"),this;const i=new A.g(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++){const n=t._LODLevels[i];if(n.distanceOrScreenCoverage===e)return n.mesh}return null}removeLODLevel(e){const t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++)t._LODLevels[i].mesh===e&&(t._LODLevels.splice(i,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this}getLOD(e,t){const i=this._internalMeshDataInfo;if(!i._LODLevels||0===i._LODLevels.length)return this;const n=t||this.getBoundingInfo().boundingSphere,s=e.mode===l.V.ORTHOGRAPHIC_CAMERA?e.minZ:n.centerWorld.subtract(e.globalPosition).length();let r=s,o=1;if(i._useLODScreenCoverage){const t=e.screenArea;let i=n.radiusWorld*e.minZ/s;i=i*i*Math.PI,r=i/t,o=-1}if(o*i._LODLevels[i._LODLevels.length-1].distanceOrScreenCoverage>o*r)return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this),this;for(let e=0;e<i._LODLevels.length;e++){const t=i._LODLevels[e];if(o*t.distanceOrScreenCoverage<o*r){if(t.mesh){if(4===t.mesh.delayLoadState)return t.mesh._checkDelayState(),this;if(2===t.mesh.delayLoadState)return this;t.mesh._preActivate(),t.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,t.mesh),t.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this),this}get geometry(){return this._geometry}getTotalVertices(){return null===this._geometry||void 0===this._geometry?0:this._geometry.getTotalVertices()}getVerticesData(e,t,i,n){var s,r;if(!this._geometry)return null;let o=n||null===(r=null===(s=this._userInstancedBuffersStorage)||void 0===s?void 0:s.vertexBuffers[e])||void 0===r?void 0:r.getFloatData(this.instances.length+1,i||t&&1!==this._geometry.meshes.length);return o||(o=this._geometry.getVerticesData(e,t,i)),o}getVertexBuffer(e,t){var i,n;return this._geometry?null!==(n=t||null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e])&&void 0!==n?n:this._geometry.getVertexBuffer(e):null}isVerticesDataPresent(e,t){var i;return this._geometry?!t&&void 0!==(null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e])||this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}isVertexBufferUpdatable(e,t){var i;if(!this._geometry)return!!this._delayInfo&&-1!==this._delayInfo.indexOf(e);if(!t){const t=null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e];if(t)return t.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)}getVerticesDataKinds(e){if(!this._geometry){const e=new Array;return this._delayInfo&&this._delayInfo.forEach((function(t){e.push(t)})),e}const t=this._geometry.getVerticesDataKinds();if(!e&&this._userInstancedBuffersStorage)for(const e in this._userInstancedBuffersStorage.vertexBuffers)-1===t.indexOf(e)&&t.push(e);return t}getTotalIndices(){return this._geometry?this._geometry.getTotalIndices():0}getIndices(e,t){return this._geometry?this._geometry.getIndices(e,t):[]}get isBlocked(){return null!==this._masterMesh&&void 0!==this._masterMesh}isReady(e=!1,t=!1){var i,n,s,r,o,a;if(2===this.delayLoadState)return!1;if(!super.isReady(e))return!1;if(!this.subMeshes||0===this.subMeshes.length)return!0;if(!e)return!0;const l=this.getEngine(),h=this.getScene(),c=t||l.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();const u=this.material||h.defaultMaterial;if(u)if(u._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,c))return!1}else if(!t.isReady(this,c))return!1}else if(!u.isReady(this,c))return!1;const d=l.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const h=t.values();for(let e=h.next();!0!==e.done;e=h.next()){const t=e.value;if(t&&(!(null===(i=t.getShadowMap())||void 0===i?void 0:i.renderList)||(null===(n=t.getShadowMap())||void 0===n?void 0:n.renderList)&&-1!==(null===(r=null===(s=t.getShadowMap())||void 0===s?void 0:s.renderList)||void 0===r?void 0:r.indexOf(this)))){t.getShadowMap()&&(l.currentRenderPassId=t.getShadowMap().renderPassId);for(const e of this.subMeshes)if(!t.isReady(e,c,null!==(a=null===(o=e.getMaterial())||void 0===o?void 0:o.needAlphaBlendingForMesh(this))&&void 0!==a&&a))return l.currentRenderPassId=d,!1;l.currentRenderPassId=d}}}for(const e of this._internalMeshDataInfo._LODLevels)if(e.mesh&&!e.mesh.isReady(c))return!1;return!0}get areNormalsFrozen(){return this._internalMeshDataInfo._areNormalsFrozen}freezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this}unfreezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this}set overridenInstanceCount(e){this._instanceDataStorage.overridenInstanceCount=e}_preActivate(){const e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t||(e._preActivateId=t,this._instanceDataStorage.visibleInstances=null),this}_preActivateForIntermediateRendering(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[t]||(void 0!==this._instanceDataStorage.previousRenderId&&this._instanceDataStorage.isFrozen&&(this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId]=null),this._instanceDataStorage.previousRenderId=t,this._instanceDataStorage.visibleInstances[t]=new Array),this._instanceDataStorage.visibleInstances[t].push(e),this}_afterComputeWorldMatrix(){super._afterComputeWorldMatrix(),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))}_postActivate(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getPositionData(e,t),i),this}_createGlobalSubMesh(e){const t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){const i=this.getIndices();if(!i)return null;const n=i.length;let s=!1;if(e)s=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>n){s=!0;break}if(e.verticesStart+e.verticesCount>t){s=!0;break}}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new g.P(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,n=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let s=0;s<e&&!(n>=t);s++)g.P.CreateFromIndices(0,n,s===e-1?t-n:i,this),n+=i;this.synchronizeInstances()}setVerticesData(e,t,i=!1,n){if(this._geometry)this._geometry.setVerticesData(e,t,i,n);else{const n=new f.x;n.set(t,e);const s=this.getScene();new _.Z(_.Z.RandomId(),s,n,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=_.Z.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,n){return this._geometry?(n?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(p.o.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(p.o.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(p.o.NormalKind);if(!t)return this;f.x.ComputeNormals(i,e,t),this.updateVerticesData(p.o.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(_.Z.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new f.x;t.indices=e;const n=this.getScene();new _.Z(_.Z.RandomId(),n,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,n=!0){if(!this._geometry)return this;const s=this.getScene().getEngine();let r;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)r=null;else switch(this._getRenderingFillMode(i)){case v.F.PointFillMode:r=null;break;case v.F.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),s);break;default:case v.F.TriangleFillMode:r=this._geometry.getIndexBuffer()}return n&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,r,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,r),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const n=this.getScene().getEngine();return this._unIndexed||t==v.F.PointFillMode?n.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==v.F.WireFrameFillMode?n.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):n.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),n=i._isInIntermediateRendering(),s=n?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,r=this._instanceDataStorage.batchCache;if(r.mustReturn=!1,r.renderSelf[e]=t||!s&&this.isEnabled()&&this.isVisible,r.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,s=i.getRenderId(),o=n?t.intermediateDefaultRenderId:t.defaultRenderId;r.visibleInstances[e]=t[s],!r.visibleInstances[e]&&o&&(r.visibleInstances[e]=t[o])}return r.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==r.visibleInstances[e]&&void 0!==r.visibleInstances[e],this._instanceDataStorage.previousBatch=r,r}_renderWithInstances(e,t,i,n,s){var r;const o=i.visibleInstances[e._id],a=o?o.length:0,l=this._instanceDataStorage,h=l.instancesBufferSize;let u=l.instancesBuffer,d=l.instancesPreviousBuffer;const f=16*(a+1)*4;for(;l.instancesBufferSize<f;)l.instancesBufferSize*=2;l.instancesData&&h==l.instancesBufferSize||(l.instancesData=new Float32Array(l.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!l.instancesPreviousData||h!=l.instancesBufferSize)&&(l.instancesPreviousData=new Float32Array(l.instancesBufferSize/4));let _=0,m=0;const g=i.renderSelf[e._id],v=!u||h!==l.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!l.instancesPreviousBuffer;if(this._instanceDataStorage.manualUpdate||l.isFrozen&&!v)m=(g?1:0)+a;else{const t=this.getWorldMatrix();if(g&&(this._scene.needsPreviousWorldMatrices&&(l.masterMeshPreviousWorldMatrix?(l.masterMeshPreviousWorldMatrix.copyToArray(l.instancesPreviousData,_),l.masterMeshPreviousWorldMatrix.copyFrom(t)):(l.masterMeshPreviousWorldMatrix=t.clone(),l.masterMeshPreviousWorldMatrix.copyToArray(l.instancesPreviousData,_))),t.copyToArray(l.instancesData,_),_+=16,m++),o){if(O.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&(null===(r=e.getMaterial())||void 0===r?void 0:r.needAlphaBlendingForMesh(e.getRenderingMesh()))){const e=this._scene.activeCamera.globalPosition;for(let t=0;t<o.length;t++){const i=o[t];i._distanceToCamera=c.P.Distance(i.getBoundingInfo().boundingSphere.centerWorld,e)}o.sort(((e,t)=>e._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera<t._distanceToCamera?1:0))}for(let e=0;e<o.length;e++){const t=o[e],i=t.getWorldMatrix();i.copyToArray(l.instancesData,_),this._scene.needsPreviousWorldMatrices&&(t._previousWorldMatrix?(t._previousWorldMatrix.copyToArray(l.instancesPreviousData,_),t._previousWorldMatrix.copyFrom(i)):(t._previousWorldMatrix=i.clone(),t._previousWorldMatrix.copyToArray(l.instancesPreviousData,_))),_+=16,m++}}}return v?(u&&u.dispose(),d&&d.dispose(),u=new p.l(s,l.instancesData,!0,16,!1,!0),l.instancesBuffer=u,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._userInstancedBuffersStorage.vertexBuffers.world0=u.createVertexBuffer("world0",0,4),this._userInstancedBuffersStorage.vertexBuffers.world1=u.createVertexBuffer("world1",4,4),this._userInstancedBuffersStorage.vertexBuffers.world2=u.createVertexBuffer("world2",8,4),this._userInstancedBuffersStorage.vertexBuffers.world3=u.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(d=new p.l(s,l.instancesPreviousData,!0,16,!1,!0),l.instancesPreviousBuffer=d,this._userInstancedBuffersStorage.vertexBuffers.previousWorld0=d.createVertexBuffer("previousWorld0",0,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld1=d.createVertexBuffer("previousWorld1",4,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld2=d.createVertexBuffer("previousWorld2",8,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld3=d.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()):this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||(u.updateDirectly(l.instancesData,0,m),!this._scene.needsPreviousWorldMatrices||this._instanceDataStorage.manualUpdate&&!this._instanceDataStorage.previousManualUpdate||d.updateDirectly(l.instancesPreviousData,0,m)),this._processInstancedBuffers(o,g),this.getScene()._activeIndices.addCount(e.indexCount*m,!1),s._currentDrawContext&&(s._currentDrawContext.useInstancing=!0),this._bind(e,n,t),this._draw(e,t,m),!this._scene.needsPreviousWorldMatrices||v||!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||this._instanceDataStorage.previousManualUpdate||d.updateDirectly(l.instancesData,0,m),s.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,i,n){var s,r;const o=null!==(r=null===(s=this._thinInstanceDataStorage)||void 0===s?void 0:s.instancesCount)&&void 0!==r?r:0;this.getScene()._activeIndices.addCount(e.indexCount*o,!1),n._currentDrawContext&&(n._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,o),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,o):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),n.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,i,n,s,r,o,a){const l=this.getScene(),h=l.getEngine();if(n=this._getRenderingFillMode(n),r&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,n,i,h),this;if(r)this._renderWithInstances(t,n,s,i,h);else{h._currentDrawContext&&(h._currentDrawContext.useInstancing=!1);let i=0;s.renderSelf[t._id]&&(o&&o(!1,e.getWorldMatrix(),a),i++,this._draw(t,n,this._instanceDataStorage.overridenInstanceCount));const r=s.visibleInstances[t._id];if(r){const e=r.length;i+=e;for(let i=0;i<e;i++){const e=r[i].getWorldMatrix();o&&o(!0,e,a),this._draw(t,n)}}l._activeIndices.addCount(t.indexCount*i,!1)}return this}_rebuild(e=!1){if(this._instanceDataStorage.instancesBuffer&&(e&&this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null),this._userInstancedBuffersStorage){for(const t in this._userInstancedBuffersStorage.vertexBuffers){const i=this._userInstancedBuffersStorage.vertexBuffers[t];i&&(e&&i.dispose(),this._userInstancedBuffersStorage.vertexBuffers[t]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,super._rebuild(e)}_freeze(){if(this.subMeshes){for(let e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}}_unFreeze(){this._instanceDataStorage.isFrozen=!1,this._instanceDataStorage.previousBatch=null}render(e,t,i){var n,s,r;const o=this.getScene();if(this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1,this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const a=this._getInstancesRenderList(e._id,!!i);if(a.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const l=o.getEngine();let c=0,u=null;this.ignoreCameraMaxZ&&o.activeCamera&&!o._isInIntermediateRendering()&&(c=o.activeCamera.maxZ,u=o.activeCamera,o.activeCamera.maxZ=0,o.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const d=e.getRenderingMesh(),p=a.hardwareInstancedRendering[e._id]||d.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,f=this._instanceDataStorage,_=e.getMaterial();if(!_)return u&&(u.maxZ=c,o.updateTransformMatrix(!0)),this;if(f.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===_){if(_._storeEffectOnSubMeshes&&!(null===(n=e.effect)||void 0===n?void 0:n._wasPreviouslyReady)||!_._storeEffectOnSubMeshes&&!(null===(s=_.getEffect())||void 0===s?void 0:s._wasPreviouslyReady))return u&&(u.maxZ=c,o.updateTransformMatrix(!0)),this}else{if(_._storeEffectOnSubMeshes){if(!_.isReadyForSubMesh(this,e,p))return u&&(u.maxZ=c,o.updateTransformMatrix(!0)),this}else if(!_.isReady(this,p))return u&&(u.maxZ=c,o.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=_}let m;t&&l.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),m=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const g=null!==(r=null==m?void 0:m.effect)&&void 0!==r?r:null;for(const t of o._beforeRenderingMeshStage)t.action(this,e,a,g);if(!m||!g)return u&&(u.maxZ=c,o.updateTransformMatrix(!0)),this;const y=i||this;let x;if(f.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this.overrideMaterialSideOrientation)x=f.sideOrientation;else{const e=y._getWorldMatrixDeterminant();x=this.overrideMaterialSideOrientation,null==x&&(x=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(x=x===v.F.ClockWiseSideOrientation?v.F.CounterClockWiseSideOrientation:v.F.ClockWiseSideOrientation),f.sideOrientation=x}const b=this._internalMeshDataInfo._effectiveMaterial._preBind(m,x);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&l.setDepthWrite(!0);const T=this._internalMeshDataInfo._effectiveMaterial,S=T.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),p||this._bind(e,g,S,!1);const E=y.getWorldMatrix();T._storeEffectOnSubMeshes?T.bindForSubMesh(E,this,e):T.bind(E,this),!T.backFaceCulling&&T.separateCullingPass&&(l.setState(!0,T.zOffset,!1,!b,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._processRendering(this,e,g,S,a,p,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),l.setState(!0,T.zOffset,!1,b,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,g,S,a,p,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of o._afterRenderingMeshStage)t.action(this,e,a,g);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),u&&(u.maxZ=c,o.updateTransformMatrix(!0)),o.performancePriority!==h.a.Aggressive||f.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(p.o.MatricesWeightsKind)&&(this.isVerticesDataPresent(p.o.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(p.o.MatricesWeightsKind),t=e.length;for(let i=0;i<t;i+=4){const t=e[i]+e[i+1]+e[i+2]+e[i+3];if(0===t)e[i]=1;else{const n=1/t;e[i]*=n,e[i+1]*=n,e[i+2]*=n,e[i+3]*=n}}this.setVerticesData(p.o.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){const e=this.getVerticesData(p.o.MatricesWeightsExtraKind),t=this.getVerticesData(p.o.MatricesWeightsKind),i=t.length;for(let n=0;n<i;n+=4){let i=t[n]+t[n+1]+t[n+2]+t[n+3];if(i+=e[n]+e[n+1]+e[n+2]+e[n+3],0===i)t[n]=1;else{const s=1/i;t[n]*=s,t[n+1]*=s,t[n+2]*=s,t[n+3]*=s,e[n]*=s,e[n+1]*=s,e[n+2]*=s,e[n+3]*=s}}this.setVerticesData(p.o.MatricesWeightsKind,t),this.setVerticesData(p.o.MatricesWeightsKind,e)}validateSkinning(){const e=this.getVerticesData(p.o.MatricesWeightsExtraKind),t=this.getVerticesData(p.o.MatricesWeightsKind);if(null===t||null==this.skeleton)return{skinned:!1,valid:!0,report:"not skinned"};const i=t.length;let n=0,s=0,r=0,o=0;const a=null===e?4:8,l=new Array;for(let e=0;e<=a;e++)l[e]=0;for(let h=0;h<i;h+=4){let i=t[h],c=i,u=0===c?0:1;for(let s=1;s<a;s++){const r=s<4?t[h+s]:e[h+s-4];r>i&&n++,0!==r&&u++,c+=r,i=r}if(l[u]++,u>r&&(r=u),0===c)s++;else{const i=1/c;let n=0;for(let s=0;s<a;s++)n+=s<4?Math.abs(t[h+s]-t[h+s]*i):Math.abs(e[h+s-4]-e[h+s-4]*i);n>.001&&o++}}const h=this.skeleton.bones.length,c=this.getVerticesData(p.o.MatricesIndicesKind),u=this.getVerticesData(p.o.MatricesIndicesExtraKind);let d=0;for(let e=0;e<i;e+=4)for(let t=0;t<a;t++){const i=t<4?c[e+t]:u[e+t-4];(i>=h||i<0)&&d++}return{skinned:!0,valid:0===s&&0===o&&0===d,report:"Number of Weights = "+i/4+"\nMaximum influences = "+r+"\nMissing Weights = "+s+"\nNot Sorted = "+n+"\nNot Normalized = "+o+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return s.w1.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!super.isInFrustum(e)&&(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const n=this.getScene().multiMaterials;for(i=n.length-1;i>-1;i--)if(n[i].id===e)return this.material=n[i],this;return this}getAnimatables(){const e=new Array;return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(p.o.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(p.o.PositionKind);const n=c.P.Zero();let s;for(s=0;s<i.length;s+=3)c.P.TransformCoordinatesFromFloatsToRef(i[s],i[s+1],i[s+2],e,n).toArray(i,s);if(this.setVerticesData(p.o.PositionKind,i,this.getVertexBuffer(p.o.PositionKind).isUpdatable()),this.isVerticesDataPresent(p.o.NormalKind)){for(i=this.getVerticesData(p.o.NormalKind),s=0;s<i.length;s+=3)c.P.TransformNormalFromFloatsToRef(i[s],i[s+1],i[s+2],e,n).normalize().toArray(i,s);this.setVerticesData(p.o.NormalKind,i,this.getVertexBuffer(p.o.NormalKind).isUpdatable())}return e.determinant()<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=t,this}bakeCurrentTransformIntoVertices(e=!0){return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions?this._internalAbstractMeshDataInfo._positions:this._geometry?this._geometry._positions:null}_resetPointsArrayCache(){return this._geometry&&this._geometry._resetPointsArrayCache(),this}_generatePointsArray(){return!!this._geometry&&this._geometry._generatePointsArray()}clone(e="",t=null,i,n=!0){return new O(e,this.getScene(),t,this,i,n)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);const i=this._internalMeshDataInfo;if(i._onBeforeDrawObservable&&i._onBeforeDrawObservable.clear(),i._onBeforeBindObservable&&i._onBeforeBindObservable.clear(),i._onBeforeRenderObservable&&i._onBeforeRenderObservable.clear(),i._onAfterRenderObservable&&i._onAfterRenderObservable.clear(),i._onBetweenPassObservable&&i._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(i.meshMap)for(const e in i.meshMap){const t=i.meshMap[e];t&&(t._internalMeshDataInfo._source=null,i.meshMap[e]=void 0)}i._source&&i._source._internalMeshDataInfo.meshMap&&(i._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else{const e=this.getScene().meshes;for(const t of e){const e=t;e._internalMeshDataInfo&&e._internalMeshDataInfo._source&&e._internalMeshDataInfo._source===this&&(e._internalMeshDataInfo._source=null)}}i._source=null,this._instanceDataStorage.visibleInstances={},this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),super.dispose(e,t)}_disposeInstanceSpecificData(){}_disposeThinInstanceSpecificData(){}_invalidateInstanceVertexArrayObject(){}applyDisplacementMap(e,t,i,n,r,o,a=!1){const l=this.getScene();return s.w1.LoadImage(e,(e=>{const s=e.width,l=e.height,h=this.getEngine().createCanvas(s,l).getContext("2d");h.drawImage(e,0,0);const c=h.getImageData(0,0,s,l).data;this.applyDisplacementMapFromBuffer(c,s,l,t,i,r,o,a),n&&n(this)}),(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,n,s,r,o,a=!1){if(!this.isVerticesDataPresent(p.o.PositionKind)||!this.isVerticesDataPresent(p.o.NormalKind)||!this.isVerticesDataPresent(p.o.UVKind))return T.Y.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(p.o.PositionKind,!0,!0),h=this.getVerticesData(p.o.NormalKind),u=this.getVerticesData(p.o.UVKind);let d=c.P.Zero();const _=c.P.Zero(),m=c.FM.Zero();r=r||c.FM.Zero(),o=o||new c.FM(1,1);for(let a=0;a<l.length;a+=3){c.P.FromArrayToRef(l,a,d),c.P.FromArrayToRef(h,a,_),c.FM.FromArrayToRef(u,a/3*2,m);const p=4*((Math.abs(m.x*o.x+r.x%1)*(t-1)%t|0)+(Math.abs(m.y*o.y+r.y%1)*(i-1)%i|0)*t),f=e[p]/255*.3+e[p+1]/255*.59+e[p+2]/255*.11;_.normalize(),_.scaleInPlace(n+(s-n)*f),d=d.add(_),d.toArray(l,a)}return f.x.ComputeNormals(l,this.getIndices(),h),a?(this.setVerticesData(p.o.PositionKind,l),this.setVerticesData(p.o.NormalKind,h),this.setVerticesData(p.o.UVKind,u)):(this.updateVerticesData(p.o.PositionKind,l),this.updateVerticesData(p.o.NormalKind,h)),this}convertToFlatShadedMesh(){const e=this.getVerticesDataKinds(),t={},i={},n={};let s,r,o=!1;for(s=0;s<e.length;s++){r=e[s];const a=this.getVertexBuffer(r),l=a.getData();(l instanceof Array||l instanceof Float32Array)&&0===l.length||(r!==p.o.NormalKind?(t[r]=a,i[r]=this.getVerticesData(r),n[r]=[]):(o=a.isUpdatable(),e.splice(s,1),s--))}const a=this.subMeshes.slice(0),l=this.getIndices(),h=this.getTotalIndices();let u;for(u=0;u<h;u++){const o=l[u];for(s=0;s<e.length;s++){if(r=e[s],!t[r])continue;const a=t[r].getStrideSize();for(let e=0;e<a;e++)n[r].push(i[r][o*a+e])}}const d=[],f=n[p.o.PositionKind];let _;for(_=this.getScene().useRightHandedSystem?1===this.overrideMaterialSideOrientation:0===this.overrideMaterialSideOrientation,u=0;u<h;u+=3){l[u]=u,l[u+1]=u+1,l[u+2]=u+2;const e=c.P.FromArray(f,3*u),t=c.P.FromArray(f,3*(u+1)),i=c.P.FromArray(f,3*(u+2)),n=e.subtract(t),s=i.subtract(t),r=c.P.Normalize(c.P.Cross(n,s));_&&r.scaleInPlace(-1);for(let e=0;e<3;e++)d.push(r.x),d.push(r.y),d.push(r.z)}for(this.setIndices(l),this.setVerticesData(p.o.NormalKind,d,o),s=0;s<e.length;s++)r=e[s],n[r]&&this.setVerticesData(r,n[r],t[r].isUpdatable());this.releaseSubMeshes();for(let e=0;e<a.length;e++){const t=a[e];g.P.AddToMesh(t.materialIndex,t.indexStart,t.indexCount,t.indexStart,t.indexCount,this)}return this.synchronizeInstances(),this}convertToUnIndexedMesh(){const e=this.getVerticesDataKinds(),t={},i={},n={};let s,r;for(s=0;s<e.length;s++){r=e[s];const o=this.getVertexBuffer(r);t[r]=o,i[r]=t[r].getData(),n[r]=[]}const o=this.subMeshes.slice(0),a=this.getIndices(),l=this.getTotalIndices();let h;for(h=0;h<l;h++){const o=a[h];for(s=0;s<e.length;s++){r=e[s];const a=t[r].getStrideSize();for(let e=0;e<a;e++)n[r].push(i[r][o*a+e])}}for(h=0;h<l;h+=3)a[h]=h,a[h+1]=h+1,a[h+2]=h+2;for(this.setIndices(a),s=0;s<e.length;s++)r=e[s],this.setVerticesData(r,n[r],t[r].isUpdatable(),t[r].getStrideSize());this.releaseSubMeshes();for(let e=0;e<o.length;e++){const t=o[e];g.P.AddToMesh(t.materialIndex,t.indexStart,t.indexCount,t.indexStart,t.indexCount,this)}return this._unIndexed=!0,this.synchronizeInstances(),this}flipFaces(e=!1){const t=f.x.ExtractFromMesh(this);let i;if(e&&this.isVerticesDataPresent(p.o.NormalKind)&&t.normals)for(i=0;i<t.normals.length;i++)t.normals[i]*=-1;if(t.indices){let e;for(i=0;i<t.indices.length;i+=3)e=t.indices[i+1],t.indices[i+1]=t.indices[i+2],t.indices[i+2]=e}return t.applyToMesh(this,this.isVertexBufferUpdatable(p.o.PositionKind)),this}increaseVertices(e=1){const t=f.x.ExtractFromMesh(this),i=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,n=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,s=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,r=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(i&&n){t.indices=i,t.positions=n,s&&(t.uvs=s),r&&(t.normals=r);const o=e+1,a=new Array;for(let e=0;e<o+1;e++)a[e]=new Array;let l,h;const u=new c.P(0,0,0),d=new c.P(0,0,0),f=new c.FM(0,0),_=new Array,m=new Array,g=new Array;let v,y,x,b=n.length;s&&(y=s.length),r&&(x=r.length);for(let e=0;e<i.length;e+=3){m[0]=i[e],m[1]=i[e+1],m[2]=i[e+2];for(let e=0;e<3;e++)if(l=m[e],h=m[(e+1)%3],void 0===g[l]&&void 0===g[h]?(g[l]=new Array,g[h]=new Array):(void 0===g[l]&&(g[l]=new Array),void 0===g[h]&&(g[h]=new Array)),void 0===g[l][h]&&void 0===g[h][l]){g[l][h]=[],u.x=(n[3*h]-n[3*l])/o,u.y=(n[3*h+1]-n[3*l+1])/o,u.z=(n[3*h+2]-n[3*l+2])/o,r&&(d.x=(r[3*h]-r[3*l])/o,d.y=(r[3*h+1]-r[3*l+1])/o,d.z=(r[3*h+2]-r[3*l+2])/o),s&&(f.x=(s[2*h]-s[2*l])/o,f.y=(s[2*h+1]-s[2*l+1])/o),g[l][h].push(l);for(let e=1;e<o;e++)g[l][h].push(n.length/3),n[b++]=n[3*l]+e*u.x,n[b++]=n[3*l+1]+e*u.y,n[b++]=n[3*l+2]+e*u.z,r&&(r[x++]=r[3*l]+e*d.x,r[x++]=r[3*l+1]+e*d.y,r[x++]=r[3*l+2]+e*d.z),s&&(s[y++]=s[2*l]+e*f.x,s[y++]=s[2*l+1]+e*f.y);g[l][h].push(h),g[h][l]=new Array,v=g[l][h].length;for(let e=0;e<v;e++)g[h][l][e]=g[l][h][v-1-e]}a[0][0]=i[e],a[1][0]=g[i[e]][i[e+1]][1],a[1][1]=g[i[e]][i[e+2]][1];for(let t=2;t<o;t++){a[t][0]=g[i[e]][i[e+1]][t],a[t][t]=g[i[e]][i[e+2]][t],u.x=(n[3*a[t][t]]-n[3*a[t][0]])/t,u.y=(n[3*a[t][t]+1]-n[3*a[t][0]+1])/t,u.z=(n[3*a[t][t]+2]-n[3*a[t][0]+2])/t,r&&(d.x=(r[3*a[t][t]]-r[3*a[t][0]])/t,d.y=(r[3*a[t][t]+1]-r[3*a[t][0]+1])/t,d.z=(r[3*a[t][t]+2]-r[3*a[t][0]+2])/t),s&&(f.x=(s[2*a[t][t]]-s[2*a[t][0]])/t,f.y=(s[2*a[t][t]+1]-s[2*a[t][0]+1])/t);for(let e=1;e<t;e++)a[t][e]=n.length/3,n[b++]=n[3*a[t][0]]+e*u.x,n[b++]=n[3*a[t][0]+1]+e*u.y,n[b++]=n[3*a[t][0]+2]+e*u.z,r&&(r[x++]=r[3*a[t][0]]+e*d.x,r[x++]=r[3*a[t][0]+1]+e*d.y,r[x++]=r[3*a[t][0]+2]+e*d.z),s&&(s[y++]=s[2*a[t][0]]+e*f.x,s[y++]=s[2*a[t][0]+1]+e*f.y)}a[o]=g[i[e+1]][i[e+2]],_.push(a[0][0],a[1][0],a[1][1]);for(let e=1;e<o;e++){let t;for(t=0;t<e;t++)_.push(a[e][t],a[e+1][t],a[e+1][t+1]),_.push(a[e][t],a[e+1][t+1],a[e][t+1]);_.push(a[e][t],a[e+1][t],a[e+1][t+1])}}t.indices=_,t.applyToMesh(this,this.isVertexBufferUpdatable(p.o.PositionKind))}else T.Y.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions")}forceSharedVertices(){const e=f.x.ExtractFromMesh(this),t=e.uvs,i=e.indices,n=e.positions,s=e.colors,r=e.matricesIndices,o=e.matricesWeights,a=e.matricesIndicesExtra,l=e.matricesWeightsExtra;if(void 0===i||void 0===n||null===i||null===n)T.Y.Warn("VertexData contains empty entries");else{const h=new Array,c=new Array,u=new Array,d=new Array,_=new Array,m=new Array,g=new Array,v=new Array;let y=new Array,x=0;const b={};let T,S;for(let e=0;e<i.length;e+=3){S=[i[e],i[e+1],i[e+2]],y=new Array;for(let e=0;e<3;e++){y[e]="";for(let t=0;t<3;t++)Math.abs(n[3*S[e]+t])<1e-8&&(n[3*S[e]+t]=0),y[e]+=n[3*S[e]+t]+"|"}if(y[0]!=y[1]&&y[0]!=y[2]&&y[1]!=y[2])for(let e=0;e<3;e++){if(T=b[y[e]],void 0===T){b[y[e]]=x,T=x++;for(let t=0;t<3;t++)h.push(n[3*S[e]+t]);if(null!=s)for(let t=0;t<4;t++)d.push(s[4*S[e]+t]);if(null!=t)for(let i=0;i<2;i++)u.push(t[2*S[e]+i]);if(null!=r)for(let t=0;t<4;t++)_.push(r[4*S[e]+t]);if(null!=o)for(let t=0;t<4;t++)m.push(o[4*S[e]+t]);if(null!=a)for(let t=0;t<4;t++)g.push(a[4*S[e]+t]);if(null!=l)for(let t=0;t<4;t++)v.push(l[4*S[e]+t])}c.push(T)}}const E=new Array;f.x.ComputeNormals(h,c,E),e.positions=h,e.indices=c,e.normals=E,null!=t&&(e.uvs=u),null!=s&&(e.colors=d),null!=r&&(e.matricesIndices=_),null!=o&&(e.matricesWeights=m),null!=a&&(e.matricesIndicesExtra=g),null!=o&&(e.matricesWeightsExtra=v),e.applyToMesh(this,this.isVertexBufferUpdatable(p.o.PositionKind))}}static _instancedMeshFactory(e,t){throw(0,E.S)("InstancedMesh")}static _PhysicsImpostorParser(e,t,i){throw(0,E.S)("PhysicsImpostor")}createInstance(e){return O._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e<this.instances.length;e++)this.instances[e]._syncSubMeshes();return this}optimizeIndices(e){const t=this.getIndices(),i=this.getVerticesData(p.o.PositionKind);if(!i||!t)return this;const n=new Array;for(let e=0;e<i.length;e+=3)n.push(c.P.FromArray(i,e));const r=new Array;return s.$g.SyncAsyncForLoop(n.length,40,(e=>{const t=n.length-1-e,i=n[t];for(let e=0;e<t;++e){const s=n[e];if(i.equals(s)){r[t]=e;break}}}),(()=>{for(let e=0;e<t.length;++e)t[e]=r[t[e]]||t[e];const i=this.subMeshes.slice(0);this.setIndices(t),this.subMeshes=i,e&&e(this)})),this}serialize(e={}){e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),o.$&&o.$.HasTags(this)&&(e.tags=o.$.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.checkCollisions=this.checkCollisions,e.isBlocker=this.isBlocker,e.overrideMaterialSideOrientation=this.overrideMaterialSideOrientation,this.parent&&this.parent._serializeAsParent(e),e.isUnIndexed=this.isUnIndexed;const t=this._geometry;if(t&&this.subMeshes){e.geometryUniqueId=t.uniqueId,e.geometryId=t.id,e.subMeshes=[];for(let t=0;t<this.subMeshes.length;t++){const i=this.subMeshes[t];e.subMeshes.push({materialIndex:i.materialIndex,verticesStart:i.verticesStart,verticesCount:i.verticesCount,indexStart:i.indexStart,indexCount:i.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialUniqueId=this.material.uniqueId,e.materialId=this.material.id):(this.material=null,e.materialUniqueId=this._scene.defaultMaterial.uniqueId,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(C.l.NAME_PHYSICSENGINE)){const t=this.getPhysicsImpostor();t&&(e.physicsMass=t.getParam("mass"),e.physicsFriction=t.getParam("friction"),e.physicsRestitution=t.getParam("mass"),e.physicsImpostor=t.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(let t=0;t<this.instances.length;t++){const i=this.instances[t];if(i.doNotSerialize)continue;const n={name:i.name,id:i.id,isEnabled:i.isEnabled(!1),isVisible:i.isVisible,isPickable:i.isPickable,checkCollisions:i.checkCollisions,position:i.position.asArray(),scaling:i.scaling.asArray()};if(i.parent&&i.parent._serializeAsParent(n),i.rotationQuaternion?n.rotationQuaternion=i.rotationQuaternion.asArray():i.rotation&&(n.rotation=i.rotation.asArray()),this.getScene()._getComponent(C.l.NAME_PHYSICSENGINE)){const e=i.getPhysicsImpostor();e&&(n.physicsMass=e.getParam("mass"),n.physicsFriction=e.getParam("friction"),n.physicsRestitution=e.getParam("mass"),n.physicsImpostor=e.type)}i.metadata&&(n.metadata=i.metadata),i.actionManager&&(n.actions=i.actionManager.serialize(i.name)),e.instances.push(n),b.p4.AppendSerializedAnimations(i,n),n.ranges=i.serializeAnimationRanges()}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Array.from(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){const t={data:{},sizes:{},strides:{}};for(const e in this._userThinInstanceBuffersStorage.data)t.data[e]=Array.from(this._userThinInstanceBuffersStorage.data[e]),t.sizes[e]=this._userThinInstanceBuffersStorage.sizes[e],t.strides[e]=this._userThinInstanceBuffersStorage.strides[e];e.thinInstances.userThinInstance=t}return b.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name)),e}_syncGeometryWithMorphTargetManager(){if(!this.geometry)return;this._markSubMeshesAsAttributesDirty();const e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices())return T.Y.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),void(this.morphTargetManager=null);if(e.isUsingTextureForTargets)return;for(let t=0;t<e.numInfluencers;t++){const i=e.getActiveTarget(t),n=i.getPositions();if(!n)return void T.Y.Error("Invalid morph target. Target must have positions.");this.geometry.setVerticesData(p.o.PositionKind+t,n,!1,3);const s=i.getNormals();s&&this.geometry.setVerticesData(p.o.NormalKind+t,s,!1,3);const r=i.getTangents();r&&this.geometry.setVerticesData(p.o.TangentKind+t,r,!1,3);const o=i.getUVs();o&&this.geometry.setVerticesData(p.o.UVKind+"_"+t,o,!1,2)}}else{let e=0;for(;this.geometry.isVerticesDataPresent(p.o.PositionKind+e);)this.geometry.removeVerticesData(p.o.PositionKind+e),this.geometry.isVerticesDataPresent(p.o.NormalKind+e)&&this.geometry.removeVerticesData(p.o.NormalKind+e),this.geometry.isVerticesDataPresent(p.o.TangentKind+e)&&this.geometry.removeVerticesData(p.o.TangentKind+e),this.geometry.isVerticesDataPresent(p.o.UVKind+e)&&this.geometry.removeVerticesData(p.o.UVKind+"_"+e),e++}}static Parse(e,t,i){let n;if(n=e.type&&"LinesMesh"===e.type?O._LinesMeshParser(e,t):e.type&&"GroundMesh"===e.type?O._GroundMeshParser(e,t):e.type&&"GoldbergMesh"===e.type?O._GoldbergMeshParser(e,t):new O(e.name,t),n.id=e.id,n._waitingParsedUniqueId=e.uniqueId,o.$&&o.$.AddTagsTo(n,e.tags),n.position=c.P.FromArray(e.position),void 0!==e.metadata&&(n.metadata=e.metadata),e.rotationQuaternion?n.rotationQuaternion=c._f.FromArray(e.rotationQuaternion):e.rotation&&(n.rotation=c.P.FromArray(e.rotation)),n.scaling=c.P.FromArray(e.scaling),e.localMatrix?n.setPreTransformMatrix(c.y3.FromArray(e.localMatrix)):e.pivotMatrix&&n.setPivotMatrix(c.y3.FromArray(e.pivotMatrix)),n.setEnabled(e.isEnabled),n.isVisible=e.isVisible,n.infiniteDistance=e.infiniteDistance,n.showBoundingBox=e.showBoundingBox,n.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,void 0!==e.applyFog&&(n.applyFog=e.applyFog),void 0!==e.pickable&&(n.isPickable=e.pickable),void 0!==e.alphaIndex&&(n.alphaIndex=e.alphaIndex),n.receiveShadows=e.receiveShadows,void 0!==e.billboardMode&&(n.billboardMode=e.billboardMode),void 0!==e.visibility&&(n.visibility=e.visibility),n.checkCollisions=e.checkCollisions,n.overrideMaterialSideOrientation=e.overrideMaterialSideOrientation,void 0!==e.isBlocker&&(n.isBlocker=e.isBlocker),n._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(n._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.actions&&(n._waitingData.actions=e.actions),void 0!==e.overlayAlpha&&(n.overlayAlpha=e.overlayAlpha),void 0!==e.overlayColor&&(n.overlayColor=u.Wo.FromArray(e.overlayColor)),void 0!==e.renderOverlay&&(n.renderOverlay=e.renderOverlay),n.isUnIndexed=!!e.isUnIndexed,n.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(n.delayLoadState=4,n.delayLoadingFile=i+e.delayLoadingFile,n.buildBoundingInfo(c.P.FromArray(e.boundingBoxMinimum),c.P.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(n._binaryInfo=e._binaryInfo),n._delayInfo=[],e.hasUVs&&n._delayInfo.push(p.o.UVKind),e.hasUVs2&&n._delayInfo.push(p.o.UV2Kind),e.hasUVs3&&n._delayInfo.push(p.o.UV3Kind),e.hasUVs4&&n._delayInfo.push(p.o.UV4Kind),e.hasUVs5&&n._delayInfo.push(p.o.UV5Kind),e.hasUVs6&&n._delayInfo.push(p.o.UV6Kind),e.hasColors&&n._delayInfo.push(p.o.ColorKind),e.hasMatricesIndices&&n._delayInfo.push(p.o.MatricesIndicesKind),e.hasMatricesWeights&&n._delayInfo.push(p.o.MatricesWeightsKind),n._delayLoadingFunction=_.Z._ImportGeometry,x.Z.ForceFullSceneLoadingForIncremental&&n._checkDelayState()):_.Z._ImportGeometry(e,n),e.materialUniqueId?n._waitingMaterialId=e.materialUniqueId:e.materialId&&(n._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(n.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(n.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(n.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],s=(0,S.q)("BABYLON.Animation");s&&n.animations.push(s.Parse(i))}d.N.ParseAnimationRanges(n,e,t)}if(e.autoAnimate&&t.beginAnimation(n,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?n.layerMask=Math.abs(parseInt(e.layerMask)):n.layerMask=268435455,e.physicsImpostor&&O._PhysicsImpostorParser(t,n,e),e.lodMeshIds&&(n._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(let i=0;i<e.instances.length;i++){const s=e.instances[i],r=n.createInstance(s.name);if(s.id&&(r.id=s.id),o.$&&(s.tags?o.$.AddTagsTo(r,s.tags):o.$.AddTagsTo(r,e.tags)),r.position=c.P.FromArray(s.position),void 0!==s.metadata&&(r.metadata=s.metadata),void 0!==s.parentId&&(r._waitingParentId=s.parentId),void 0!==s.parentInstanceIndex&&(r._waitingParentInstanceIndex=s.parentInstanceIndex),void 0!==s.isEnabled&&null!==s.isEnabled&&r.setEnabled(s.isEnabled),void 0!==s.isVisible&&null!==s.isVisible&&(r.isVisible=s.isVisible),void 0!==s.isPickable&&null!==s.isPickable&&(r.isPickable=s.isPickable),s.rotationQuaternion?r.rotationQuaternion=c._f.FromArray(s.rotationQuaternion):s.rotation&&(r.rotation=c.P.FromArray(s.rotation)),r.scaling=c.P.FromArray(s.scaling),null!=s.checkCollisions&&null!=s.checkCollisions&&(r.checkCollisions=s.checkCollisions),null!=s.pickable&&null!=s.pickable&&(r.isPickable=s.pickable),null!=s.showBoundingBox&&null!=s.showBoundingBox&&(r.showBoundingBox=s.showBoundingBox),null!=s.showSubMeshesBoundingBox&&null!=s.showSubMeshesBoundingBox&&(r.showSubMeshesBoundingBox=s.showSubMeshesBoundingBox),null!=s.alphaIndex&&null!=s.showSubMeshesBoundingBox&&(r.alphaIndex=s.alphaIndex),s.physicsImpostor&&O._PhysicsImpostorParser(t,r,s),void 0!==s.actions&&(r._waitingData.actions=s.actions),s.animations){for(let e=0;e<s.animations.length;e++){const t=s.animations[e],i=(0,S.q)("BABYLON.Animation");i&&r.animations.push(i.Parse(t))}d.N.ParseAnimationRanges(r,s,t),s.autoAnimate&&t.beginAnimation(r,s.autoAnimateFrom,s.autoAnimateTo,s.autoAnimateLoop,s.autoAnimateSpeed||1)}}if(e.thinInstances){const t=e.thinInstances;if(n.thinInstanceEnablePicking=!!t.enablePicking,t.matrixData?(n.thinInstanceSetBuffer("matrix",new Float32Array(t.matrixData),16,!1),n._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,n._thinInstanceDataStorage.instancesCount=t.instancesCount):n._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,e.thinInstances.userThinInstance){const t=e.thinInstances.userThinInstance;for(const e in t.data)n.thinInstanceSetBuffer(e,new Float32Array(t.data[e]),t.strides[e],!1),n._userThinInstanceBuffersStorage.sizes[e]=t.sizes[e]}}return n}setPositionsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourcePositions){const t=this.getVerticesData(p.o.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(p.o.PositionKind)||this.setVerticesData(p.o.PositionKind,t,!0)}return e._sourcePositions}setNormalsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourceNormals){const t=this.getVerticesData(p.o.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(p.o.NormalKind)||this.setVerticesData(p.o.NormalKind,t,!0)}return e._sourceNormals}applySkeleton(e){if(!this.geometry)return this;if(this.geometry._softwareSkinningFrameId==this.getScene().getFrameId())return this;if(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(p.o.PositionKind))return this;if(!this.isVerticesDataPresent(p.o.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(p.o.MatricesWeightsKind))return this;const t=this.isVerticesDataPresent(p.o.NormalKind),i=this._internalMeshDataInfo;if(!i._sourcePositions){const e=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=e}t&&!i._sourceNormals&&this.setNormalsForCPUSkinning();let n=this.getVerticesData(p.o.PositionKind);if(!n)return this;n instanceof Float32Array||(n=new Float32Array(n));let s=this.getVerticesData(p.o.NormalKind);if(t){if(!s)return this;s instanceof Float32Array||(s=new Float32Array(s))}const r=this.getVerticesData(p.o.MatricesIndicesKind),o=this.getVerticesData(p.o.MatricesWeightsKind);if(!o||!r)return this;const a=this.numBoneInfluencers>4,l=a?this.getVerticesData(p.o.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(p.o.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),d=c.P.Zero(),f=new c.y3,_=new c.y3;let m,g=0;for(let e=0;e<n.length;e+=3,g+=4){let p;for(m=0;m<4;m++)p=o[g+m],p>0&&(c.y3.FromFloat32ArrayToRefScaled(u,Math.floor(16*r[g+m]),p,_),f.addToSelf(_));if(a)for(m=0;m<4;m++)p=h[g+m],p>0&&(c.y3.FromFloat32ArrayToRefScaled(u,Math.floor(16*l[g+m]),p,_),f.addToSelf(_));c.P.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],f,d),d.toArray(n,e),t&&(c.P.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],f,d),d.toArray(s,e)),f.reset()}return this.updateVerticesData(p.o.PositionKind,n),t&&this.updateVerticesData(p.o.NormalKind,s),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const n=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(n.minimumWorld),i.maximizeInPlace(n.maximumWorld)):(t=n.minimumWorld,i=n.maximumWorld)})),t&&i?{min:t,max:i}:{min:c.P.Zero(),max:c.P.Zero()}}static Center(e){const t=e instanceof Array?O.MinMax(e):e;return c.P.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,n,s,r){return(0,a.s3)(O._MergeMeshesCoroutine(e,t,i,n,s,r,!1))}static MergeMeshesAsync(e,t=!0,i,n,s,r){return(0,a.sM)(O._MergeMeshesCoroutine(e,t,i,n,s,r,!0),(0,a.KO)())}static*_MergeMeshesCoroutine(e,t=!0,i,n,s,r,o){if(0===(e=e.filter(Boolean)).length)return null;let a;if(!i){let t=0;for(a=0;a<e.length;a++)if(t+=e[a].getTotalVertices(),t>=65536)return T.Y.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}r&&(s=!1);const l=new Array,h=new Array,c=new Array,u=e[0].overrideMaterialSideOrientation;for(a=0;a<e.length;a++){const t=e[a];if(t.isAnInstance)return T.Y.Warn("Cannot merge instance meshes."),null;if(u!==t.overrideMaterialSideOrientation)return T.Y.Warn("Cannot merge meshes with different overrideMaterialSideOrientation values."),null;if(s&&c.push(t.getTotalIndices()),r)if(t.material){const e=t.material;if(e instanceof y.G){for(let t=0;t<e.subMaterials.length;t++)l.indexOf(e.subMaterials[t])<0&&l.push(e.subMaterials[t]);for(let i=0;i<t.subMeshes.length;i++)h.push(l.indexOf(e.subMaterials[t.subMeshes[i].materialIndex])),c.push(t.subMeshes[i].indexCount)}else{l.indexOf(e)<0&&l.push(e);for(let i=0;i<t.subMeshes.length;i++)h.push(l.indexOf(e)),c.push(t.subMeshes[i].indexCount)}}else for(let e=0;e<t.subMeshes.length;e++)h.push(0),c.push(t.subMeshes[e].indexCount)}const d=e[0],p=e=>{const t=e.computeWorldMatrix(!0);return{vertexData:f.x.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:_,transform:m}=p(d);o&&(yield);const v=new Array(e.length-1);for(let t=1;t<e.length;t++)v[t-1]=p(e[t]),o&&(yield);const x=_._mergeCoroutine(m,v,i,o,!t);let b=x.next();for(;!b.done;)o&&(yield),b=x.next();const S=b.value;n||(n=new O(d.name+"_merged",d.getScene()));const E=S._applyToCoroutine(n,void 0,o);let C=E.next();for(;!C.done;)o&&(yield),C=E.next();if(n.checkCollisions=d.checkCollisions,n.overrideMaterialSideOrientation=d.overrideMaterialSideOrientation,t)for(a=0;a<e.length;a++)e[a].dispose();if(s||r){n.releaseSubMeshes(),a=0;let e=0;for(;a<c.length;)g.P.CreateFromIndices(0,e,c[a],n,void 0,!1),e+=c[a],a++;for(const e of n.subMeshes)e.refreshBoundingInfo();n.computeWorldMatrix(!0)}if(r){const e=new y.G(d.name+"_merged",d.getScene());e.subMaterials=l;for(let e=0;e<n.subMeshes.length;e++)n.subMeshes[e].materialIndex=h[e];n.material=e}else n.material=d.material;return n}addInstance(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)}removeInstance(e){const t=e._indexInSourceMeshInstanceArray;if(-1!=t){if(t!==this.instances.length-1){const e=this.instances[this.instances.length-1];this.instances[t]=e,e._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}}_shouldConvertRHS(){return this.overrideMaterialSideOrientation===v.F.CounterClockWiseSideOrientation}_getRenderingFillMode(e){var t;const i=this.getScene();return i.forcePointsCloud?v.F.PointFillMode:i.forceWireframe?v.F.WireFrameFillMode:null!==(t=this.overrideRenderingFillMode)&&void 0!==t?t:e}}O.FRONTSIDE=f.x.FRONTSIDE,O.BACKSIDE=f.x.BACKSIDE,O.DOUBLESIDE=f.x.DOUBLESIDE,O.DEFAULTSIDE=f.x.DEFAULTSIDE,O.NO_CAP=0,O.CAP_START=1,O.CAP_END=2,O.CAP_ALL=3,O.NO_FLIP=0,O.FLIP_TILE=1,O.ROTATE_TILE=2,O.FLIP_ROW=3,O.ROTATE_ROW=4,O.FLIP_N_ROTATE_TILE=5,O.FLIP_N_ROTATE_ROW=6,O.CENTER=0,O.LEFT=1,O.RIGHT=2,O.TOP=3,O.BOTTOM=4,O.INSTANCEDMESH_SORT_TRANSPARENT=!1,O._GroundMeshParser=(e,t)=>{throw(0,E.S)("GroundMesh")},O._GoldbergMeshParser=(e,t)=>{throw(0,E.S)("GoldbergMesh")},O._LinesMeshParser=(e,t)=>{throw(0,E.S)("LinesMesh")},(0,S.H)("BABYLON.Mesh",O),O.prototype.setMaterialByID=function(e){return this.setMaterialById(e)},O.CreateDisc=O.CreateDisc||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateBox=O.CreateBox||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateSphere=O.CreateSphere||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateCylinder=O.CreateCylinder||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateTorusKnot=O.CreateTorusKnot||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateTorus=O.CreateTorus||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreatePlane=O.CreatePlane||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateGround=O.CreateGround||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateTiledGround=O.CreateTiledGround||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateGroundFromHeightMap=O.CreateGroundFromHeightMap||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateTube=O.CreateTube||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreatePolyhedron=O.CreatePolyhedron||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateIcoSphere=O.CreateIcoSphere||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateDecal=O.CreateDecal||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.CreateCapsule=O.CreateCapsule||(()=>{throw new Error("Import MeshBuilder to populate this function")}),O.ExtendToGoldberg=O.ExtendToGoldberg||(()=>{throw new Error("Import MeshBuilder to populate this function")})},2101:(e,t,i)=>{i.d(t,{x:()=>d});var n=i(9472),s=i(4141),r=i(708),o=i(4934),a=i(4649),l=i(2722),h=i(3956),c=i(2697),u=i(1722);class d{constructor(){this._applyTo=(0,c.vp)(this._applyToCoroutine.bind(this))}set(e,t){switch(e.length||l.Y.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case r.o.PositionKind:this.positions=e;break;case r.o.NormalKind:this.normals=e;break;case r.o.TangentKind:this.tangents=e;break;case r.o.UVKind:this.uvs=e;break;case r.o.UV2Kind:this.uvs2=e;break;case r.o.UV3Kind:this.uvs3=e;break;case r.o.UV4Kind:this.uvs4=e;break;case r.o.UV5Kind:this.uvs5=e;break;case r.o.UV6Kind:this.uvs6=e;break;case r.o.ColorKind:this.colors=e;break;case r.o.MatricesIndicesKind:this.matricesIndices=e;break;case r.o.MatricesWeightsKind:this.matricesWeights=e;break;case r.o.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case r.o.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){return this.positions&&(e.setVerticesData(r.o.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(r.o.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(r.o.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(r.o.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(r.o.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(r.o.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(r.o.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(r.o.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(r.o.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(r.o.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(r.o.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(r.o.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),this}_update(e,t,i){return this.positions&&e.updateVerticesData(r.o.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(r.o.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(r.o.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(r.o.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(r.o.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(r.o.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(r.o.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(r.o.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(r.o.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(r.o.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(r.o.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(r.o.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,n=e.length){const r=s.jp.Vector3[0],o=s.jp.Vector3[1];for(let a=i;a<i+n;a+=3)s.P.FromArrayToRef(e,a,r),s.P.TransformCoordinatesToRef(r,t,o),e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z}static _TransformVector3Normals(e,t,i=0,n=e.length){const r=s.jp.Vector3[0],o=s.jp.Vector3[1];for(let a=i;a<i+n;a+=3)s.P.FromArrayToRef(e,a,r),s.P.TransformNormalToRef(r,t,o),e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z}static _TransformVector4Normals(e,t,i=0,n=e.length){const r=s.jp.Vector4[0],o=s.jp.Vector4[1];for(let a=i;a<i+n;a+=4)s.Lt.FromArrayToRef(e,a,r),s.Lt.TransformNormalToRef(r,t,o),e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z,e[a+3]=o.w}static _FlipFaces(e,t=0,i=e.length){for(let n=t;n<t+i;n+=3){const t=e[n+1];e[n+1]=e[n+2],e[n+2]=t}}transform(e){const t=e.determinant()<0;return this.positions&&d._TransformVector3Coordinates(this.positions,e),this.normals&&d._TransformVector3Normals(this.normals,e),this.tangents&&d._TransformVector4Normals(this.tangents,e),t&&this.indices&&d._FlipFaces(this.indices),this}merge(e,t=!1,i=!1){const n=Array.isArray(e)?e.map((e=>({vertexData:e}))):[{vertexData:e}];return(0,c.s3)(this._mergeCoroutine(void 0,n,t,!1,i))}*_mergeCoroutine(e,t,i=!1,n,s){var o,a,l,h;this._validate();const c=t.map((e=>e.vertexData));for(const e of c)if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");const u=c.reduce(((e,t)=>{var i,n;return e+(null!==(n=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==n?n:0)}),null!==(a=null===(o=this.indices)||void 0===o?void 0:o.length)&&void 0!==a?a:0);let p=s||c.some((e=>e.indices===this.indices))?null===(l=this.indices)||void 0===l?void 0:l.slice():this.indices;if(u>0){let s=null!==(h=null==p?void 0:p.length)&&void 0!==h?h:0;if(p||(p=new Array(u)),p.length!==u){if(Array.isArray(p))p.length=u;else{const e=i||p instanceof Uint32Array?new Uint32Array(u):new Uint16Array(u);e.set(p),p=e}e&&e.determinant()<0&&d._FlipFaces(p,0,s)}let r=this.positions?this.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t<e.indices.length;t++)p[s+t]=e.indices[t]+r;i&&i.determinant()<0&&d._FlipFaces(p,s,e.indices.length),r+=e.positions.length/3,s+=e.indices.length,n&&(yield)}}return this.indices=p,this.positions=d._MergeElement(r.o.PositionKind,this.positions,e,t.map((e=>[e.vertexData.positions,e.transform]))),n&&(yield),this.normals=d._MergeElement(r.o.NormalKind,this.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),n&&(yield),this.tangents=d._MergeElement(r.o.TangentKind,this.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),n&&(yield),this.uvs=d._MergeElement(r.o.UVKind,this.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),n&&(yield),this.uvs2=d._MergeElement(r.o.UV2Kind,this.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),n&&(yield),this.uvs3=d._MergeElement(r.o.UV3Kind,this.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),n&&(yield),this.uvs4=d._MergeElement(r.o.UV4Kind,this.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),n&&(yield),this.uvs5=d._MergeElement(r.o.UV5Kind,this.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),n&&(yield),this.uvs6=d._MergeElement(r.o.UV6Kind,this.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),n&&(yield),this.colors=d._MergeElement(r.o.ColorKind,this.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),n&&(yield),this.matricesIndices=d._MergeElement(r.o.MatricesIndicesKind,this.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),n&&(yield),this.matricesWeights=d._MergeElement(r.o.MatricesWeightsKind,this.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),n&&(yield),this.matricesIndicesExtra=d._MergeElement(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),n&&(yield),this.matricesWeightsExtra=d._MergeElement(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(e,t,i,n){const s=n.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));const o=s.reduce(((e,t)=>e+t[0].length),t.length),a=e===r.o.PositionKind?d._TransformVector3Coordinates:e===r.o.NormalKind?d._TransformVector3Normals:e===r.o.TangentKind?d._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(o);e.set(t),i&&a(e,i,0,t.length);let n=t.length;for(const[t,i]of s)e.set(t,n),i&&a(e,i,n,t.length),n+=t.length;return e}{const e=new Array(o);for(let i=0;i<t.length;i++)e[i]=t[i];i&&a(e,i,0,t.length);let n=t.length;for(const[t,i]of s){for(let i=0;i<t.length;i++)e[n+i]=t[i];i&&a(e,i,n,t.length),n+=t.length}return e}}_validate(){if(!this.positions)throw new u.LH("Positions are required",u.SM.MeshInvalidPositionsError);const e=(e,t)=>{const i=r.o.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(r.o.PositionKind,this.positions),i=(i,n)=>{const s=e(i,n);if(s!==t)throw new Error("The "+i+"s element count ("+s+") does not match the positions count ("+t+")")};this.normals&&i(r.o.NormalKind,this.normals),this.tangents&&i(r.o.TangentKind,this.tangents),this.uvs&&i(r.o.UVKind,this.uvs),this.uvs2&&i(r.o.UV2Kind,this.uvs2),this.uvs3&&i(r.o.UV3Kind,this.uvs3),this.uvs4&&i(r.o.UV4Kind,this.uvs4),this.uvs5&&i(r.o.UV5Kind,this.uvs5),this.uvs6&&i(r.o.UV6Kind,this.uvs6),this.colors&&i(r.o.ColorKind,this.colors),this.matricesIndices&&i(r.o.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(r.o.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra)}serialize(){const e={};return this.positions&&(e.positions=this.positions),this.normals&&(e.normals=this.normals),this.tangents&&(e.tangents=this.tangents),this.uvs&&(e.uvs=this.uvs),this.uvs2&&(e.uvs2=this.uvs2),this.uvs3&&(e.uvs3=this.uvs3),this.uvs4&&(e.uvs4=this.uvs4),this.uvs5&&(e.uvs5=this.uvs5),this.uvs6&&(e.uvs6=this.uvs6),this.colors&&(e.colors=this.colors),this.matricesIndices&&(e.matricesIndices=this.matricesIndices,e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=this.matricesWeights),this.matricesIndicesExtra&&(e.matricesIndicesExtra=this.matricesIndicesExtra,e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=this.matricesWeightsExtra),e.indices=this.indices,e}static ExtractFromMesh(e,t,i){return d._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return d._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const n=new d;return e.isVerticesDataPresent(r.o.PositionKind)&&(n.positions=e.getVerticesData(r.o.PositionKind,t,i)),e.isVerticesDataPresent(r.o.NormalKind)&&(n.normals=e.getVerticesData(r.o.NormalKind,t,i)),e.isVerticesDataPresent(r.o.TangentKind)&&(n.tangents=e.getVerticesData(r.o.TangentKind,t,i)),e.isVerticesDataPresent(r.o.UVKind)&&(n.uvs=e.getVerticesData(r.o.UVKind,t,i)),e.isVerticesDataPresent(r.o.UV2Kind)&&(n.uvs2=e.getVerticesData(r.o.UV2Kind,t,i)),e.isVerticesDataPresent(r.o.UV3Kind)&&(n.uvs3=e.getVerticesData(r.o.UV3Kind,t,i)),e.isVerticesDataPresent(r.o.UV4Kind)&&(n.uvs4=e.getVerticesData(r.o.UV4Kind,t,i)),e.isVerticesDataPresent(r.o.UV5Kind)&&(n.uvs5=e.getVerticesData(r.o.UV5Kind,t,i)),e.isVerticesDataPresent(r.o.UV6Kind)&&(n.uvs6=e.getVerticesData(r.o.UV6Kind,t,i)),e.isVerticesDataPresent(r.o.ColorKind)&&(n.colors=e.getVerticesData(r.o.ColorKind,t,i)),e.isVerticesDataPresent(r.o.MatricesIndicesKind)&&(n.matricesIndices=e.getVerticesData(r.o.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(r.o.MatricesWeightsKind)&&(n.matricesWeights=e.getVerticesData(r.o.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(r.o.MatricesIndicesExtraKind)&&(n.matricesIndicesExtra=e.getVerticesData(r.o.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(r.o.MatricesWeightsExtraKind)&&(n.matricesWeightsExtra=e.getVerticesData(r.o.MatricesWeightsExtraKind,t,i)),n.indices=e.getIndices(t,i),n}static CreateRibbon(e){throw(0,o.S)("ribbonBuilder")}static CreateBox(e){throw(0,o.S)("boxBuilder")}static CreateTiledBox(e){throw(0,o.S)("tiledBoxBuilder")}static CreateTiledPlane(e){throw(0,o.S)("tiledPlaneBuilder")}static CreateSphere(e){throw(0,o.S)("sphereBuilder")}static CreateCylinder(e){throw(0,o.S)("cylinderBuilder")}static CreateTorus(e){throw(0,o.S)("torusBuilder")}static CreateLineSystem(e){throw(0,o.S)("linesBuilder")}static CreateDashedLines(e){throw(0,o.S)("linesBuilder")}static CreateGround(e){throw(0,o.S)("groundBuilder")}static CreateTiledGround(e){throw(0,o.S)("groundBuilder")}static CreateGroundFromHeightMap(e){throw(0,o.S)("groundBuilder")}static CreatePlane(e){throw(0,o.S)("planeBuilder")}static CreateDisc(e){throw(0,o.S)("discBuilder")}static CreatePolygon(e,t,i,n,s,r,a){throw(0,o.S)("polygonBuilder")}static CreateIcoSphere(e){throw(0,o.S)("icoSphereBuilder")}static CreatePolyhedron(e){throw(0,o.S)("polyhedronBuilder")}static CreateCapsule(e={orientation:s.P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw(0,o.S)("capsuleBuilder")}static CreateTorusKnot(e){throw(0,o.S)("torusKnotBuilder")}static ComputeNormals(e,t,i,n){let r=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0,p=0,f=0,_=0,m=0,g=0,v=0,y=0,x=0,b=0,T=0,S=0,E=0,C=!1,A=!1,P=!1,R=!1,M=1,I=0,D=null;n&&(C=!!n.facetNormals,A=!!n.facetPositions,P=!!n.facetPartitioning,M=!0===n.useRightHandedSystem?-1:1,I=n.ratio||0,R=!!n.depthSort,D=n.distanceTo,R&&void 0===D&&(D=s.P.Zero()));let O=0,w=0,N=0,F=0;for(P&&n&&n.bbSize&&(O=n.subDiv.X*I/n.bbSize.x,w=n.subDiv.Y*I/n.bbSize.y,N=n.subDiv.Z*I/n.bbSize.z,F=n.subDiv.max*n.subDiv.max,n.facetPartitioning.length=0),r=0;r<e.length;r++)i[r]=0;const L=t.length/3|0;for(r=0;r<L;r++){if(m=3*t[3*r],g=m+1,v=m+2,y=3*t[3*r+1],x=y+1,b=y+2,T=3*t[3*r+2],S=T+1,E=T+2,o=e[m]-e[y],a=e[g]-e[x],l=e[v]-e[b],h=e[T]-e[y],c=e[S]-e[x],u=e[E]-e[b],d=M*(a*u-l*c),p=M*(l*h-o*u),f=M*(o*c-a*h),_=Math.sqrt(d*d+p*p+f*f),_=0===_?1:_,d/=_,p/=_,f/=_,C&&n&&(n.facetNormals[r].x=d,n.facetNormals[r].y=p,n.facetNormals[r].z=f),A&&n&&(n.facetPositions[r].x=(e[m]+e[y]+e[T])/3,n.facetPositions[r].y=(e[g]+e[x]+e[S])/3,n.facetPositions[r].z=(e[v]+e[b]+e[E])/3),P&&n){const t=Math.floor((n.facetPositions[r].x-n.bInfo.minimum.x*I)*O),i=Math.floor((n.facetPositions[r].y-n.bInfo.minimum.y*I)*w),s=Math.floor((n.facetPositions[r].z-n.bInfo.minimum.z*I)*N),o=Math.floor((e[m]-n.bInfo.minimum.x*I)*O),a=Math.floor((e[g]-n.bInfo.minimum.y*I)*w),l=Math.floor((e[v]-n.bInfo.minimum.z*I)*N),h=Math.floor((e[y]-n.bInfo.minimum.x*I)*O),c=Math.floor((e[x]-n.bInfo.minimum.y*I)*w),u=Math.floor((e[b]-n.bInfo.minimum.z*I)*N),d=Math.floor((e[T]-n.bInfo.minimum.x*I)*O),p=Math.floor((e[S]-n.bInfo.minimum.y*I)*w),f=Math.floor((e[E]-n.bInfo.minimum.z*I)*N),_=o+n.subDiv.max*a+F*l,C=h+n.subDiv.max*c+F*u,A=d+n.subDiv.max*p+F*f,P=t+n.subDiv.max*i+F*s;n.facetPartitioning[P]=n.facetPartitioning[P]?n.facetPartitioning[P]:new Array,n.facetPartitioning[_]=n.facetPartitioning[_]?n.facetPartitioning[_]:new Array,n.facetPartitioning[C]=n.facetPartitioning[C]?n.facetPartitioning[C]:new Array,n.facetPartitioning[A]=n.facetPartitioning[A]?n.facetPartitioning[A]:new Array,n.facetPartitioning[_].push(r),C!=_&&n.facetPartitioning[C].push(r),A!=C&&A!=_&&n.facetPartitioning[A].push(r),P!=_&&P!=C&&P!=A&&n.facetPartitioning[P].push(r)}if(R&&n&&n.facetPositions){const e=n.depthSortedFacets[r];e.ind=3*r,e.sqDistance=s.P.DistanceSquared(n.facetPositions[r],D)}i[m]+=d,i[g]+=p,i[v]+=f,i[y]+=d,i[x]+=p,i[b]+=f,i[T]+=d,i[S]+=p,i[E]+=f}for(r=0;r<i.length/3;r++)d=i[3*r],p=i[3*r+1],f=i[3*r+2],_=Math.sqrt(d*d+p*p+f*f),_=0===_?1:_,d/=_,p/=_,f/=_,i[3*r]=d,i[3*r+1]=p,i[3*r+2]=f}static _ComputeSides(e,t,i,n,r,o,a){const l=i.length,h=n.length;let c,u;switch(e=e||d.DEFAULTSIDE){case d.FRONTSIDE:break;case d.BACKSIDE:for(c=0;c<l;c+=3){const e=i[c];i[c]=i[c+2],i[c+2]=e}for(u=0;u<h;u++)n[u]=-n[u];break;case d.DOUBLESIDE:{const e=t.length,d=e/3;for(let i=0;i<e;i++)t[e+i]=t[i];for(c=0;c<l;c+=3)i[c+l]=i[c+2]+d,i[c+1+l]=i[c+1]+d,i[c+2+l]=i[c]+d;for(u=0;u<h;u++)n[h+u]=-n[u];const p=r.length;let f=0;for(f=0;f<p;f++)r[f+p]=r[f];for(o=o||new s.Lt(0,0,1,1),a=a||new s.Lt(0,0,1,1),f=0,c=0;c<p/2;c++)r[f]=o.x+(o.z-o.x)*r[f],r[f+1]=o.y+(o.w-o.y)*r[f+1],r[f+p]=a.x+(a.z-a.x)*r[f+p],r[f+p+1]=a.y+(a.w-a.y)*r[f+p+1],f+=2;break}}}static ImportVertexData(e,t){const i=new d,n=e.positions;n&&i.set(n,r.o.PositionKind);const s=e.normals;s&&i.set(s,r.o.NormalKind);const o=e.tangents;o&&i.set(o,r.o.TangentKind);const l=e.uvs;l&&i.set(l,r.o.UVKind);const h=e.uv2s;h&&i.set(h,r.o.UV2Kind);const c=e.uv3s;c&&i.set(c,r.o.UV3Kind);const u=e.uv4s;u&&i.set(u,r.o.UV4Kind);const p=e.uv5s;p&&i.set(p,r.o.UV5Kind);const f=e.uv6s;f&&i.set(f,r.o.UV6Kind);const _=e.colors;_&&i.set(a.HE.CheckColors4(_,n.length/3),r.o.ColorKind);const m=e.matricesIndices;m&&i.set(m,r.o.MatricesIndicesKind);const g=e.matricesWeights;g&&i.set(g,r.o.MatricesWeightsKind);const v=e.indices;v&&(i.indices=v),t.setAllVerticesData(i,e.updatable)}}d.FRONTSIDE=0,d.BACKSIDE=1,d.DOUBLESIDE=2,d.DEFAULTSIDE=0,(0,n.gn)([h.G6.filter(((...[e])=>!Array.isArray(e)))],d,"_TransformVector3Coordinates",null),(0,n.gn)([h.G6.filter(((...[e])=>!Array.isArray(e)))],d,"_TransformVector3Normals",null),(0,n.gn)([h.G6.filter(((...[e])=>!Array.isArray(e)))],d,"_TransformVector4Normals",null),(0,n.gn)([h.G6.filter(((...[e])=>!Array.isArray(e)))],d,"_FlipFaces",null)},447:(e,t,i)=>{i.d(t,{g:()=>n});class n{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}},9401:(e,t,i)=>{i.d(t,{P:()=>l});var n=i(708),s=i(2312),r=i(3722),o=i(1372),a=i(1345);class l{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:null===(e=this._getDrawWrapper())||void 0===e?void 0:e.defines}set materialDefines(e){var t;(null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=null!=e?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new a.q(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&(null===(i=this._drawWrappers[e])||void 0===i||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:null!==(t=null===(e=this._getDrawWrapper())||void 0===e?void 0:e.effect)&&void 0!==t?t:null}get _drawWrapper(){var e;return null!==(e=this._mainDrawWrapperOverride)&&void 0!==e?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,n=!0){const s=this._drawWrapper;s.setEffect(e,t,n),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)null==e||e.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,n,s,r,o,a=!0){return new l(e,t,i,n,s,r,o,a)}constructor(e,t,i,n,s,r,o,a=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=n,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=r,this._renderingMesh=o||r,l&&r.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=r.subMeshes.length-1,a&&(this.refreshBoundingInfo(),r.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){var t;const i=null!==(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))&&void 0!==t?t:this._renderingMesh.material;if(!i)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(i)){const e=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return i}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(n.o.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=(0,o.y)(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new r.j(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let t=this.indexStart;t<this.indexStart+this.indexCount;t+=3)i.push(e[t],e[t+1],e[t+1],e[t+2],e[t+2],e[t]);this._linesIndexBuffer=t.createIndexBuffer(i),this._linesIndexCount=i.length}return this._linesIndexBuffer}canIntersects(e){const t=this.getBoundingInfo();return!!t&&e.intersectsBox(t.boundingBox)}intersects(e,t,i,n,s){const r=this.getMaterial();if(!r)return null;let o=3,a=!1;switch(r.fillMode){case 3:case 5:case 6:case 8:return null;case 7:o=1,a=!0}return 4===r.fillMode?i.length?this._intersectLines(e,t,i,this._mesh.intersectionThreshold,n):this._intersectUnIndexedLines(e,t,i,this._mesh.intersectionThreshold,n):!i.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,i,n,s):this._intersectTriangles(e,t,i,o,a,n,s)}_intersectLines(e,t,i,n,r){let o=null;for(let a=this.indexStart;a<this.indexStart+this.indexCount;a+=2){const l=t[i[a]],h=t[i[a+1]],c=e.intersectionSegment(l,h,n);if(!(c<0)&&(r||!o||c<o.distance)&&(o=new s.c(null,null,c),o.faceId=a/2,r))break}return o}_intersectUnIndexedLines(e,t,i,n,r){let o=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=2){const a=t[i],l=t[i+1],h=e.intersectionSegment(a,l,n);if(!(h<0)&&(r||!o||h<o.distance)&&(o=new s.c(null,null,h),o.faceId=i/2,r))break}return o}_intersectTriangles(e,t,i,n,s,r,o){let a=null,l=-1;for(let h=this.indexStart;h<this.indexStart+this.indexCount-(3-n);h+=n){l++;const n=i[h],c=i[h+1],u=i[h+2];if(s&&4294967295===u){h+=2;continue}const d=t[n],p=t[c],f=t[u];if(!d||!p||!f)continue;if(o&&!o(d,p,f,e,n,c,u))continue;const _=e.intersectsTriangle(d,p,f);if(_){if(_.distance<0)continue;if((r||!a||_.distance<a.distance)&&(a=_,a.faceId=l,r))break}}return a}_intersectUnIndexedTriangles(e,t,i,n,s){let r=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=3){const o=t[i],a=t[i+1],l=t[i+2];if(s&&!s(o,a,l,e,-1,-1,-1))continue;const h=e.intersectsTriangle(o,a,l);if(h){if(h.distance<0)continue;if((n||!r||h.distance<r.distance)&&(r=h,r.faceId=i/3,n))break}}return r}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){const i=new l(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);if(!this.IsGlobal){const e=this.getBoundingInfo();if(!e)return i;i._boundingInfo=new r.j(e.minimum,e.maximum)}return i}dispose(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);const e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1),this.resetDrawCache()}getClassName(){return"SubMesh"}static CreateFromIndices(e,t,i,n,s,r=!0){let o=Number.MAX_VALUE,a=-Number.MAX_VALUE;const h=(s||n).getIndices();for(let e=t;e<t+i;e++){const t=h[e];t<o&&(o=t),t>a&&(a=t)}return new l(e,o,a-o+1,t,i,n,s,r)}}},2708:(e,t,i)=>{var n=i(4496),s=i(708),r=i(4141),o=i(2722),a=i(3722);n.Kj.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return o.Y.Error("Thin Instances are not supported on this device as Instanced Array extension not supported"),-1;this._thinInstanceUpdateBufferSize("matrix",Array.isArray(e)?e.length:1);const i=this._thinInstanceDataStorage.instancesCount;if(Array.isArray(e))for(let i=0;i<e.length;++i)this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e[i],i===e.length-1&&t);else this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e,t);return i},n.Kj.prototype.thinInstanceAddSelf=function(e=!0){return this.thinInstanceAdd(r.y3.IdentityReadOnly,e)},n.Kj.prototype.thinInstanceRegisterAttribute=function(e,t){e===s.o.ColorKind&&(e=s.o.ColorInstanceKind),this.removeVerticesData(e),this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.strides[e]=t,this._userThinInstanceBuffersStorage.sizes[e]=t*Math.max(32,this._thinInstanceDataStorage.instancesCount),this._userThinInstanceBuffersStorage.data[e]=new Float32Array(this._userThinInstanceBuffersStorage.sizes[e]),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new s.o(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!0,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])},n.Kj.prototype.thinInstanceSetMatrixAt=function(e,t,i=!0){if(!this._thinInstanceDataStorage.matrixData||e>=this._thinInstanceDataStorage.instancesCount)return!1;const n=this._thinInstanceDataStorage.matrixData;return t.copyToArray(n,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},n.Kj.prototype.thinInstanceSetAttributeAt=function(e,t,i,n=!0){return e===s.o.ColorKind&&(e=s.o.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount||(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),n&&this.thinInstanceBufferUpdated(e),0))},Object.defineProperty(n.Kj.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i;const n=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData;e<=(n?n.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),n.Kj.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!1){e===s.o.ColorKind&&(e=s.o.ColorInstanceKind);const n=new s.l(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(n.createVertexBuffer(e+t,4*t,4));return n},n.Kj.prototype.thinInstanceSetBuffer=function(e,t,i=0,n=!1){var r,o,a;i=i||16,"matrix"===e?(null===(r=this._thinInstanceDataStorage.matrixBuffer)||void 0===r||r.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,n),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(null===(o=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===o||o.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,n))):(e===s.o.ColorKind&&(e=s.o.ColorInstanceKind),null===t?(null===(a=this._userThinInstanceBuffersStorage)||void 0===a?void 0:a.data[e])&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new s.o(this.getEngine(),t,e,!n,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},n.Kj.prototype.thinInstanceBufferUpdated=function(e){var t,i,n;"matrix"===e?null===(t=this._thinInstanceDataStorage.matrixBuffer)||void 0===t||t.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):"previousMatrix"===e?null===(i=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===i||i.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(e===s.o.ColorKind&&(e=s.o.ColorInstanceKind),(null===(n=this._userThinInstanceBuffersStorage)||void 0===n?void 0:n.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0))},n.Kj.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var n;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===s.o.ColorKind&&(e=s.o.ColorInstanceKind),(null===(n=this._userThinInstanceBuffersStorage)||void 0===n?void 0:n.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},n.Kj.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=new Array;for(let t=0;t<this._thinInstanceDataStorage.instancesCount;++t)this._thinInstanceDataStorage.worldMatrices[t]=r.y3.FromArray(e,16*t)}return this._thinInstanceDataStorage.worldMatrices},n.Kj.prototype.thinInstanceRefreshBoundingInfo=function(e=!1,t=!1,i=!1){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return;const n=this._thinInstanceDataStorage.boundingVectors;if(e||!this.rawBoundingInfo){n.length=0,this.refreshBoundingInfo(t,i);const e=this.getBoundingInfo();this.rawBoundingInfo=new a.j(e.minimum,e.maximum)}const s=this.getBoundingInfo(),o=this._thinInstanceDataStorage.matrixData;if(0===n.length)for(let e=0;e<s.boundingBox.vectors.length;++e)n.push(s.boundingBox.vectors[e].clone());r.jp.Vector3[0].setAll(Number.POSITIVE_INFINITY),r.jp.Vector3[1].setAll(Number.NEGATIVE_INFINITY);for(let e=0;e<this._thinInstanceDataStorage.instancesCount;++e){r.y3.FromArrayToRef(o,16*e,r.jp.Matrix[0]);for(let e=0;e<n.length;++e)r.P.TransformCoordinatesToRef(n[e],r.jp.Matrix[0],r.jp.Vector3[2]),r.jp.Vector3[0].minimizeInPlace(r.jp.Vector3[2]),r.jp.Vector3[1].maximizeInPlace(r.jp.Vector3[2])}s.reConstruct(r.jp.Vector3[0],r.jp.Vector3[1]),this._updateBoundingInfo()},n.Kj.prototype._thinInstanceUpdateBufferSize=function(e,t=1){var i,n,r;e===s.o.ColorKind&&(e=s.o.ColorInstanceKind);const o="matrix"===e;if(!(o||this._userThinInstanceBuffersStorage&&this._userThinInstanceBuffersStorage.strides[e]))return;const a=o?16:this._userThinInstanceBuffersStorage.strides[e],l=o?this._thinInstanceDataStorage.matrixBufferSize:this._userThinInstanceBuffersStorage.sizes[e];let h=o?this._thinInstanceDataStorage.matrixData:this._userThinInstanceBuffersStorage.data[e];const c=(this._thinInstanceDataStorage.instancesCount+t)*a;let u=l;for(;u<c;)u*=2;if(!h||l!=u){if(h){const e=new Float32Array(u);e.set(h,0),h=e}else h=new Float32Array(u);o?(null===(i=this._thinInstanceDataStorage.matrixBuffer)||void 0===i||i.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",h,!1),this._thinInstanceDataStorage.matrixData=h,this._thinInstanceDataStorage.matrixBufferSize=u,this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&(null===(n=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===n||n.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",h,!1))):(null===(r=this._userThinInstanceBuffersStorage.vertexBuffers[e])||void 0===r||r.dispose(),this._userThinInstanceBuffersStorage.data[e]=h,this._userThinInstanceBuffersStorage.sizes[e]=u,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new s.o(this.getEngine(),h,e,!0,!1,a,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))}},n.Kj.prototype._thinInstanceInitializeUserStorage=function(){this._userThinInstanceBuffersStorage||(this._userThinInstanceBuffersStorage={data:{},sizes:{},vertexBuffers:{},strides:{}})},n.Kj.prototype._disposeThinInstanceSpecificData=function(){var e;(null===(e=this._thinInstanceDataStorage)||void 0===e?void 0:e.matrixBuffer)&&(this._thinInstanceDataStorage.matrixBuffer.dispose(),this._thinInstanceDataStorage.matrixBuffer=null)}},4674:(e,t,i)=>{i.d(t,{Y:()=>h});var n=i(9472),s=i(3956),r=i(5757),o=i(4141),a=i(9257),l=i(5203);class h extends a.N{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=0!=(this._billboardMode&h.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==h.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 o.P(0,0,1),this._up=new o.P(0,1,0),this._right=new o.P(1,0,0),this._position=o.P.Zero(),this._rotation=o.P.Zero(),this._rotationQuaternion=null,this._scaling=o.P.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=h.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=o.y3.Zero(),this._usePivotMatrix=!1,this._absolutePosition=o.P.Zero(),this._absoluteScaling=o.P.Zero(),this._absoluteRotationQuaternion=o._f.Identity(),this._pivotMatrix=o.y3.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new r.y$,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return o.P.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return o.P.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return o.P.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=o.y3.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==h.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1,e.useBillboardPath=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=o.y3.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const n=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);n&&i&&i(this,n);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(n,t,i);return n}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||o._f.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,n;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],n=arguments[2]}else t=e.x,i=e.y,n=e.z;if(this.parent){const e=o.jp.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),o.P.TransformCoordinatesFromFloatsToRef(t,i,n,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=n;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=o.P.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=o.jp.Matrix[0];return this._localMatrix.invertToRef(e),o.P.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=o.P.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,n=0,s=l.T.LOCAL){const r=h._LookAtVectorCache,a=s===l.T.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,r),this.setDirection(r,t,i,n),s===l.T.WORLD&&this.parent)if(this.rotationQuaternion){const e=o.jp.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=o.jp.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=o.jp.Quaternion[0];o._f.FromEulerVectorToRef(this.rotation,e);const t=o.jp.Matrix[0];e.toRotationMatrix(t);const i=o.jp.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=o.P.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return o.P.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,n=0){const s=-Math.atan2(e.z,e.x)+Math.PI/2,r=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,r);return this.rotationQuaternion?o._f.RotationYawPitchRollToRef(s+t,a+i,n,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=s+t,this.rotation.z=n),this}setPivotPoint(e,t=l.T.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==l.T.WORLD){const t=o.jp.Matrix[0];i.invertToRef(t),e=o.P.TransformCoordinates(e,t)}return this.setPivotMatrix(o.y3.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=o.P.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=o.P.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),o.P.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const n=o.jp.Quaternion[0],s=o.jp.Vector3[0],r=o.jp.Vector3[1],a=o.jp.Matrix[1];o.y3.IdentityToRef(a);const l=o.jp.Matrix[0];this.computeWorldMatrix(!0);let c=this.rotationQuaternion;return c||(c=h._TmpRotation,o._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,c)),o.y3.ComposeToRef(this.scaling,c,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(a),l.multiplyToRef(a,l)),l.decompose(r,n,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(n):n.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(r),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(o.y3.Identity()),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(),e.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let n;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==l.T.LOCAL){if(this.parent){const t=o.jp.Matrix[0];this.parent.getWorldMatrix().invertToRef(t),e=o.P.TransformNormal(e,t)}n=o._f.RotationAxisToRef(e,t,h._RotationAxisCache),n.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else n=o._f.RotationAxisToRef(e,t,h._RotationAxisCache),this.rotationQuaternion.multiplyToRef(n,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=o._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const n=o.jp.Vector3[0],s=o.jp.Vector3[1],r=o.jp.Vector3[2],a=o.jp.Quaternion[0],l=o.jp.Matrix[0],h=o.jp.Matrix[1],c=o.jp.Matrix[2],u=o.jp.Matrix[3];return e.subtractToRef(this.position,n),o.y3.TranslationToRef(n.x,n.y,n.z,l),o.y3.TranslationToRef(-n.x,-n.y,-n.z,h),o.y3.RotationAxisToRef(t,i,c),h.multiplyToRef(c,u),u.multiplyToRef(l,u),u.decompose(s,a,r),this.position.addInPlace(r),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const n=e.scale(t);if(i&&i!==l.T.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{const e=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let n;this.rotationQuaternion?n=this.rotationQuaternion:(n=o.jp.Quaternion[1],o._f.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));const s=o.jp.Quaternion[0];return o._f.RotationYawPitchRollToRef(t,e,i,s),n.multiplyInPlace(s),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==h.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 n=this._cache;n.pivotMatrixUpdated=!1,n.billboardMode=this.billboardMode,n.infiniteDistance=this.infiniteDistance,n.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 s=this._getEffectiveParent(),r=h._TmpScaling;let a,l=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new o.P(e.m[12],e.m[13],e.m[14]);l=h._TmpTranslation,l.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(r.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,a=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(o._f.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(a=h._TmpRotation,o._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,a)),this._usePivotMatrix){const e=o.jp.Matrix[1];o.y3.ScalingToRef(r.x,r.y,r.z,e);const t=o.jp.Matrix[0];a.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,o.jp.Matrix[4]),o.jp.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(l.x,l.y,l.z)}else o.y3.ComposeToRef(r,a,l,this._localMatrix);if(s&&s.getWorldMatrix){if(e&&s.computeWorldMatrix(e),n.useBillboardPath){this._transformToBoneReferal?s.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),o.jp.Matrix[7]):o.jp.Matrix[7].copyFrom(s.getWorldMatrix());const e=o.jp.Vector3[5],t=o.jp.Vector3[6],i=o.jp.Quaternion[0];o.jp.Matrix[7].decompose(t,i,e),o.y3.ScalingToRef(t.x,t.y,t.z,o.jp.Matrix[7]),o.jp.Matrix[7].setTranslation(e),h.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(o.jp.Matrix[7],this._worldMatrix)}else this._transformToBoneReferal?(this._localMatrix.multiplyToRef(s.getWorldMatrix(),o.jp.Matrix[6]),o.jp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localMatrix.multiplyToRef(s.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(n.useBillboardPath&&t&&this.billboardMode&&!n.useBillboardPosition){const e=o.jp.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),o.jp.Matrix[1].copyFrom(t.getViewMatrix()),o.jp.Matrix[1].setTranslationFromFloats(0,0,0),o.jp.Matrix[1].invertToRef(o.jp.Matrix[0]),(this.billboardMode&h.BILLBOARDMODE_ALL)!==h.BILLBOARDMODE_ALL){o.jp.Matrix[0].decompose(void 0,o.jp.Quaternion[0],void 0);const e=o.jp.Vector3[1];o.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&h.BILLBOARDMODE_X)!==h.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&h.BILLBOARDMODE_Y)!==h.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&h.BILLBOARDMODE_Z)!==h.BILLBOARDMODE_Z&&(e.z=0),o.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,o.jp.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(o.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(o.jp.Vector3[0])}else if(n.useBillboardPath&&t&&n.useBillboardPosition){const e=o.jp.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(o.jp.Matrix[1]);const n=o.jp.Vector3[1];o.P.TransformCoordinatesToRef(i,o.jp.Matrix[1],n),n.normalize();const s=-Math.atan2(n.z,n.x)+Math.PI/2,r=Math.sqrt(n.x*n.x+n.z*n.z),a=-Math.atan2(n.y,r);if(o._f.RotationYawPitchRollToRef(s,a,0,o.jp.Quaternion[0]),(this.billboardMode&h.BILLBOARDMODE_ALL)!==h.BILLBOARDMODE_ALL){const e=o.jp.Vector3[1];o.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&h.BILLBOARDMODE_X)!==h.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&h.BILLBOARDMODE_Y)!==h.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&h.BILLBOARDMODE_Z)!==h.BILLBOARDMODE_Z&&(e.z=0),o.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,o.jp.Matrix[0])}else o.y3.FromQuaternionToRef(o.jp.Quaternion[0],o.jp.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(o.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(o.jp.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):s&&s._nonUniformScaling?this._updateNonUniformScalingState(s._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=o.y3.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;t<e.length;++t){const i=e[t];if(i){i.computeWorldMatrix();const e=o.jp.Matrix[0];i._localMatrix.multiplyToRef(this._localMatrix,e);const t=o.jp.Quaternion[0];e.decompose(i.scaling,t,i.position),i.rotationQuaternion?i.rotationQuaternion.copyFrom(t):t.toEulerAnglesToRef(i.rotation)}}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=o._f.Identity()),this._worldMatrix=o.y3.Identity()}_afterComputeWorldMatrix(){}registerAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this}unregisterAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this}getPositionInCameraSpace(e=null){return e||(e=this.getScene().activeCamera),o.P.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())}getDistanceToCamera(e=null){return e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()}clone(e,t,i){const n=s.p4.Clone((()=>new h(e,this.getScene())),this);if(n.name=e,n.id=e,t&&(n.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i<t.length;i++){const s=t[i];s.clone&&s.clone(e+"."+s.name,n)}}return n}serialize(e){const t=s.p4.Serialize(this,e);return t.type=this.getClassName(),t.uniqueId=this.uniqueId,this.parent&&this.parent._serializeAsParent(t),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),t}static Parse(e,t,i){const n=s.p4.Parse((()=>new h(e.name,t)),e,t,i);return e.localMatrix?n.setPreTransformMatrix(o.y3.FromArray(e.localMatrix)):e.pivotMatrix&&n.setPivotMatrix(o.y3.FromArray(e.pivotMatrix)),n.setEnabled(e.isEnabled),n._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),n}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,(e=>(!t||t(e))&&e instanceof h)),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let n=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(n=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const r=this.getHierarchyBoundingVectors(e,i),o=r.max.subtract(r.min),a=Math.max(o.x,o.y,o.z);if(0===a)return this;const l=1/a;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&n&&this.rotation.copyFrom(n)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}h.BILLBOARDMODE_NONE=0,h.BILLBOARDMODE_X=1,h.BILLBOARDMODE_Y=2,h.BILLBOARDMODE_Z=4,h.BILLBOARDMODE_ALL=7,h.BILLBOARDMODE_USE_POSITION=128,h.BillboardUseParentOrientation=!1,h._TmpRotation=o._f.Zero(),h._TmpScaling=o.P.Zero(),h._TmpTranslation=o.P.Zero(),h._LookAtVectorCache=new o.P(0,0,0),h._RotationAxisCache=new o._f,(0,n.gn)([(0,s.hd)("position")],h.prototype,"_position",void 0),(0,n.gn)([(0,s.hd)("rotation")],h.prototype,"_rotation",void 0),(0,n.gn)([(0,s.mv)("rotationQuaternion")],h.prototype,"_rotationQuaternion",void 0),(0,n.gn)([(0,s.hd)("scaling")],h.prototype,"_scaling",void 0),(0,n.gn)([(0,s.qC)("billboardMode")],h.prototype,"_billboardMode",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"scalingDeterminant",void 0),(0,n.gn)([(0,s.qC)("infiniteDistance")],h.prototype,"_infiniteDistance",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"ignoreNonUniformScaling",void 0),(0,n.gn)([(0,s.qC)()],h.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0)},123:(e,t,i)=>{i.d(t,{$:()=>h});var n=i(4141),s=i(1128),r=i(6113),o=i(1341),a=i(4649);class l{constructor(e,t,i,n){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=n}}class h{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();const i=e.getSize().width,n=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,o;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),o=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),o=e.readPixels(3,void 0,void 0,!1));const a=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace;let c=0;return 1!=e.textureType&&2!=e.textureType||(c=1),new Promise((e=>{Promise.all([s,n,r,o,a,l]).then((([t,n,s,r,o,a])=>{const l={size:i,right:n,left:t,up:s,down:r,front:o,back:a,format:5,type:c,gammaSpace:h};e(this.ConvertCubeMapToSphericalPolynomial(l))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new r._;let i=0;const n=2/e.size,l=n,h=.5*n,c=h-1;for(let r=0;r<6;r++){const u=this._FileFaces[r],d=e[u.name];let p=c;const f=5===e.format?4:3;for(let r=0;r<e.size;r++){let _=c;for(let l=0;l<e.size;l++){const c=u.worldAxisForFileX.scale(_).add(u.worldAxisForFileY.scale(p)).add(u.worldAxisForNormal);c.normalize();const m=this._AreaElement(_-h,p-h)-this._AreaElement(_-h,p+h)-this._AreaElement(_+h,p-h)+this._AreaElement(_+h,p+h);let g=d[r*e.size*f+l*f+0],v=d[r*e.size*f+l*f+1],y=d[r*e.size*f+l*f+2];isNaN(g)&&(g=0),isNaN(v)&&(v=0),isNaN(y)&&(y=0),0===e.type&&(g/=255,v/=255,y/=255),e.gammaSpace&&(g=Math.pow(s.R.Clamp(g),o.Nn),v=Math.pow(s.R.Clamp(v),o.Nn),y=Math.pow(s.R.Clamp(y),o.Nn));const x=this.MAX_HDRI_VALUE;if(this.PRESERVE_CLAMPED_COLORS){const e=Math.max(g,v,y);if(e>x){const t=x/e;g*=t,v*=t,y*=t}}else g=s.R.Clamp(g,0,x),v=s.R.Clamp(v,0,x),y=s.R.Clamp(y,0,x);const b=new a.Wo(g,v,y);t.addLight(c,b,m),i+=m,_+=n}p+=l}}const u=4*Math.PI*6/6/i;return t.scaleInPlace(u),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),r.i.FromHarmonics(t)}}h._FileFaces=[new l("right",new n.P(1,0,0),new n.P(0,0,-1),new n.P(0,-1,0)),new l("left",new n.P(-1,0,0),new n.P(0,0,1),new n.P(0,-1,0)),new l("up",new n.P(0,1,0),new n.P(1,0,0),new n.P(0,0,1)),new l("down",new n.P(0,-1,0),new n.P(1,0,0),new n.P(0,0,-1)),new l("front",new n.P(0,0,1),new n.P(1,0,0),new n.P(0,-1,0)),new l("back",new n.P(0,0,-1),new n.P(-1,0,0),new n.P(0,-1,0))],h.MAX_HDRI_VALUE=4096,h.PRESERVE_CLAMPED_COLORS=!1},5559:(e,t,i)=>{i.d(t,{q:()=>n});class n{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),n._HandleParenthesisContent(e,t)))):n._HandleParenthesisContent(e,t))||"false"!==e&&n.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let r=n._SimplifyNegation(s[e].trim());const o=r.split("&&");if(o.length>1)for(let e=0;e<o.length;++e){const s=n._SimplifyNegation(o[e].trim());if(i="true"!==s&&"false"!==s?"!"===s[0]?!t(s.substring(1)):t(s):"true"===s,!i){r="false";break}}if(i||"true"===r){i=!0;break}i="true"!==r&&"false"!==r?"!"===r[0]?!t(r.substring(1)):t(r):"true"===r}return i?"true":"false"}static _SimplifyNegation(e){return"!true"===(e=(e=e.replace(/^[\s!]+/,(e=>(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}},5860:(e,t,i)=>{i.d(t,{B:()=>n,M:()=>r});class n{static BuildArray(e,t){const i=[];for(let n=0;n<e;++n)i.push(t());return i}static BuildTuple(e,t){return n.BuildArray(e,t)}}const s=["push","splice","pop","shift","unshift"];function r(e,t){const i=s.map((i=>function(e,t,i){const n=e[t];if("function"!=typeof n)return null;const s=function(){const n=e.length,r=s.previous.apply(e,arguments);return i(t,n),r};return n.next=s,s.previous=n,e[t]=s,()=>{const i=s.previous;if(!i)return;const n=s.next;n?(i.next=n,n.previous=i):(i.next=void 0,e[t]=i),s.next=void 0,s.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{null==e||e()}))}}},6344:(e,t,i)=>{i.d(t,{$:()=>a,D:()=>l});var n=i(2262),s=i(8121),r=i(7257);let o=0;const a=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const a=n.x.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+o++,e,!0,!1,n.x.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const l=e.getEngine().getLoadedTexturesCache(),h=l.indexOf(a.getInternalTexture());-1!==h&&l.splice(h,1),a.isRGBD=!0,a.wrapU=n.x.CLAMP_ADDRESSMODE,a.wrapV=n.x.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=a,e.useDelayedTextureLoading=t,s.r.ExpandRGBDTexture(a);const c=e.getEngine().onContextRestoredObservable.add((()=>{a.isRGBD=!0;const e=()=>{a.isReady()?s.r.ExpandRGBDTexture(a):r.w1.SetImmediate(e)};e()}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(c)}))}return e.environmentBRDFTexture},l={GetEnvironmentBRDFTexture:a}},8985:(e,t,i)=>{function n(e,t,i,n){let s=n,r=0,o="";for(;s<i.length;){const n=i.charAt(s);if(o)n===o?'"'===o||"'"===o?"\\"!==i.charAt(s-1)&&(o=""):o="":"*/"===o&&"*"===n&&s+1<i.length&&("/"===i.charAt(s+1)&&(o=""),""===o&&s++);else switch(n){case e:r++;break;case t:r--;break;case'"':case"'":case"`":o=n;break;case"/":if(s+1<i.length){const e=i.charAt(s+1);"/"===e?o="\n":"*"===e&&(o="*/")}}if(s++,0===r)break}return 0===r?s-1:-1}function s(e,t){for(;t<e.length;){const i=e[t];if(" "!==i&&"\n"!==i&&"\r"!==i&&"\t"!==i&&"\n"!==i&&" "!==i)break;t++}return t}function r(e){const t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function o(e){let t=0,i="",n=!1;const s=[];for(;t<e.length;){const r=e.charAt(t);if(i)r===i?'"'===i||"'"===i?("\\"!==e.charAt(t-1)&&(i=""),s.push(r)):(i="",n=!1):"*/"===i&&"*"===r&&t+1<e.length?("/"===e.charAt(t+1)&&(i=""),""===i&&(n=!1,t++)):n||s.push(r);else{switch(r){case'"':case"'":case"`":i=r;break;case"/":if(t+1<e.length){const s=e.charAt(t+1);"/"===s?(i="\n",n=!0):"*"===s&&(i="*/",n=!0)}}n||s.push(r)}t++}return s.join("")}function a(e,t,i){for(;t>=0&&e.charAt(t)!==i;)t--;return t}function l(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i.d(t,{AW:()=>l,Kt:()=>o,Pm:()=>s,uA:()=>r,vt:()=>n,wm:()=>a})},9703:(e,t,i)=>{function n(e,t,i=!1){const n=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let n=e[t];n<0?n=0:n>1&&(n=1),i[t]=255*n}e=i}const r=document.createElement("canvas");r.width=n,r.height=s;const o=r.getContext("2d");if(!o)return null;const a=o.createImageData(n,s);if(a.data.set(e),o.putImageData(a,0,0),i){const e=document.createElement("canvas");e.width=n,e.height=s;const t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(r,0,0),e.toDataURL("image/png")):null}return r.toDataURL("image/png")}function s(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=e._readPixelsSync(t,i);return r?n(r,e.getSize(),s.invertY):null}async function r(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=await e.readPixels(t,i);return r?n(r,e.getSize(),s.invertY):null}i.d(t,{Jj:()=>r,_u:()=>s,r1:()=>o,xj:()=>n});const o={GenerateBase64StringFromPixelData:n,GenerateBase64StringFromTexture:s,GenerateBase64StringFromTextureAsync:r}},2697:(e,t,i)=>{function n(e,t,i){try{const n=e.next();n.done?t(n):n.value?n.value.then((()=>{n.value=void 0,t(n)}),i):t(n)}catch(e){i(e)}}function s(e=25){let t;return(i,s,r)=>{const o=performance.now();void 0===t||o-t>e?(t=o,setTimeout((()=>{n(i,s,r)}),0)):n(i,s,r)}}function r(e,t,i,n,s){const r=()=>{let o;const a=e=>{e.done?i(e.value):void 0===o?o=!0:r()};do{o=void 0,s&&s.aborted?n(new Error("Aborted")):t(e,a,n),void 0===o&&(o=!1)}while(o)};r()}function o(e,t){let i;return r(e,n,(e=>i=e),(e=>{throw e}),t),i}function a(e,t,i){return new Promise(((n,s)=>{r(e,t,n,s,i)}))}function l(e,t){return(...i)=>o(e(...i),t)}function h(e,t,i){return(...n)=>a(e(...n),t,i)}i.d(t,{KO:()=>s,U3:()=>h,WP:()=>n,d_:()=>r,s3:()=>o,sM:()=>a,vp:()=>l})},1918:(e,t,i)=>{i.d(t,{d:()=>s});var n=i(2655);class s{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then((e=>{this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._dataByteOffset=0}))}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return(0,n.fJ)(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}},3956:(e,t,i)=>{i.d(t,{G6:()=>P,N$:()=>x,QC:()=>g,RR:()=>y,VE:()=>C,XX:()=>b,hd:()=>v,mv:()=>S,n9:()=>_,oQ:()=>E,oU:()=>f,p4:()=>A,qC:()=>p,qQ:()=>m,rX:()=>T,wz:()=>d});var n=i(4875),s=i(4141),r=i(4934),o=i(4649);const a={},l={},h=function(e,t,i,s={}){const r=e();n.$&&n.$.HasTags(t)&&n.$.AddTagsTo(r,n.$.GetTags(t,!0));const o=c(r),a={};for(const e in o){const n=o[e],l=t[e],h=n.type;if(null!=l&&("uniqueId"!==e||A.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:r[e]=l;break;case 1:s.cloneTexturesOnlyOnce&&a[l.uniqueId]?r[e]=a[l.uniqueId]:(r[e]=i||l.isRenderTarget?l:l.clone(),a[l.uniqueId]=r[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[e]=i?l:l.clone()}}return r};function c(e){const t=e.getClassName();if(l[t])return l[t];l[t]={};const i=l[t];let n=e,s=t;for(;s;){const e=a[s];for(const t in e)i[t]=e[t];let t,r=!1;do{if(t=Object.getPrototypeOf(n),!t.getClassName){r=!0;break}if(t.getClassName()!==s)break;n=t}while(t);if(r)break;s=t.getClassName(),n=t}return i}function u(e,t){return(i,n)=>{const s=function(e){const t=e.getClassName();return a[t]||(a[t]={}),a[t]}(i);s[n]||(s[n]={type:e,sourceName:t})}}function d(e,t=null){return function(e,t=null){return(i,n)=>{const s=t||"_"+n;Object.defineProperty(i,n,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]!==t&&(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function p(e){return u(0,e)}function f(e){return u(1,e)}function _(e){return u(2,e)}function m(e){return u(3,e)}function g(e){return u(4,e)}function v(e){return u(5,e)}function y(e){return u(6,e)}function x(e){return u(7,e)}function b(e){return u(8,e)}function T(e){return u(9,e)}function S(e){return u(10,e)}function E(e){return u(12,e)}function C(e){return u(11,e)}class A{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i<e.animations.length;i++){const n=e.animations[i];t.animations.push(n.serialize())}}}static Serialize(e,t){t||(t={}),n.$&&(t.tags=n.$.GetTags(e));const i=c(e);for(const n in i){const s=i[n],r=s.sourceName||n,o=s.type,a=e[n];if(null!=a&&("uniqueId"!==n||A.AllowLoadingUniqueId))switch(o){case 0:t[r]=a;break;case 1:case 3:case 7:case 9:t[r]=a.serialize();break;case 2:case 4:case 5:case 8:case 10:case 12:t[r]=a.asArray();break;case 6:case 11:t[r]=a.id}}return t}static ParseProperties(e,t,i,n){n||(n="");const r=c(t);for(const a in r){const l=r[a],h=e[l.sourceName||a],c=l.type;if(null!=h&&("uniqueId"!==a||A.AllowLoadingUniqueId)){const e=t;switch(c){case 0:e[a]=h;break;case 1:i&&(e[a]=A._TextureParser(h,i,n));break;case 2:e[a]=o.Wo.FromArray(h);break;case 3:e[a]=A._FresnelParametersParser(h);break;case 4:e[a]=s.FM.FromArray(h);break;case 5:e[a]=s.P.FromArray(h);break;case 6:i&&(e[a]=i.getLastMeshById(h));break;case 7:e[a]=A._ColorCurvesParser(h);break;case 8:e[a]=o.HE.FromArray(h);break;case 9:e[a]=A._ImageProcessingConfigurationParser(h);break;case 10:e[a]=s._f.FromArray(h);break;case 11:i&&(e[a]=i.getCameraById(h));break;case 12:e[a]=s.y3.FromArray(h)}}}}static Parse(e,t,i,s=null){const r=e();return n.$&&n.$.AddTagsTo(r,t.tags),A.ParseProperties(t,r,i,s),r}static Clone(e,t,i={}){return h(e,t,!1,i)}static Instanciate(e,t){return h(e,t,!0)}}function P(e,t,i,n){const s=i.value;i.value=(...i)=>{let r=s;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];r=n?(...t)=>n(...t)?e(...t):s(...t):e}return e[t]=r,r(...i)}}A.AllowLoadingUniqueId=!1,A._ImageProcessingConfigurationParser=e=>{throw(0,r.S)("ImageProcessingConfiguration")},A._FresnelParametersParser=e=>{throw(0,r.S)("FresnelParameters")},A._ColorCurvesParser=e=>{throw(0,r.S)("ColorCurves")},A._TextureParser=(e,t,i)=>{throw(0,r.S)("Texture")},P.filter=function(e){return(t,i,n)=>P(t,i,n,e)}},6387:(e,t,i)=>{i.d(t,{j:()=>r});var n=i(2722);const s=(e,t)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&"SubMesh"===e.getClassName()?e.clone(t):e.clone?e.clone():null:null;class r{static DeepCopy(e,t,i,r){const o=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const a of o){if("_"===a[0]&&(!r||-1===r.indexOf(a)))continue;if(a.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(a))continue;const o=e[a],l=typeof o;if("function"!==l)try{if("object"===l)if(o instanceof Array){if(t[a]=[],o.length>0)if("object"==typeof o[0])for(let e=0;e<o.length;e++){const i=s(o[e],t);-1===t[a].indexOf(i)&&t[a].push(i)}else t[a]=o.slice(0)}else t[a]=s(o,t);else t[a]=o}catch(e){n.Y.Warn(e.message)}}}}},7188:(e,t,i)=>{i.d(t,{B:()=>n});class n{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}},4934:(e,t,i)=>{function n(e){return`${e} needs to be imported before as it contains a side-effect required by your code.`}i.d(t,{S:()=>n})},6797:(e,t,i)=>{function n(){return"undefined"!=typeof window}function s(){return"undefined"!=typeof navigator}function r(){return"undefined"!=typeof document}function o(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}i.d(t,{CG:()=>n,MZ:()=>a,n5:()=>r,up:()=>s,v:()=>o});const a={IsWindowObjectExist:n,IsNavigatorAvailable:s,IsDocumentAvailable:r,GetDOMTextContent:o}},2286:(e,t,i)=>{i.d(t,{B:()=>a});var n=i(3230),s=i(7218),r=i(7257),o=i(7182);class a{static _CreateDumpRenderer(){if(!a._DumpToolsEngine){const e=new OffscreenCanvas(100,100),t=new n.B(e,!1,{preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1});t.getCaps().parallelShaderCompile=void 0;const i=new s.I(t),r=new s.H({engine:t,name:o.T.name,fragmentShader:o.T.shader,samplerNames:["textureSampler"]});a._DumpToolsEngine={canvas:e,engine:t,renderer:i,wrapper:r}}return a._DumpToolsEngine}static async DumpFramebuffer(e,t,i,n,s="image/png",r){const o=await i.readPixels(0,0,e,t),l=new Uint8Array(o.buffer);a.DumpData(e,t,l,n,s,r,!0)}static DumpDataAsync(e,t,i,n="image/png",s,r=!1,o=!1,l){return new Promise((h=>{a.DumpData(e,t,i,(e=>h(e)),n,s,r,o,l)}))}static DumpData(e,t,i,n,s="image/png",o,l=!1,h=!1,c){const u=a._CreateDumpRenderer();if(u.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const n=i[t];e[t]=n<0?0:n>1?1:Math.round(255*n)}i=e}const d=u.engine.createRawTexture(i,e,t,5,!1,!l,1);u.renderer.setViewport(),u.renderer.applyEffectWrapper(u.wrapper),u.wrapper.effect._bindTexture("textureSampler",d),u.renderer.draw(),h?r.w1.ToBlob(u.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;n&&n(t)},t.readAsArrayBuffer(e)}),s,c):r.w1.EncodeScreenshotCanvasData(u.canvas,n,s,o,c),d.dispose()}static Dispose(){a._DumpToolsEngine&&(a._DumpToolsEngine.wrapper.dispose(),a._DumpToolsEngine.renderer.dispose(),a._DumpToolsEngine.engine.dispose()),a._DumpToolsEngine=null}}r.w1.DumpData=a.DumpData,r.w1.DumpDataAsync=a.DumpDataAsync,r.w1.DumpFramebuffer=a.DumpFramebuffer},4277:(e,t,i)=>{i.d(t,{p6:()=>x,Do:()=>T,qh:()=>R,qJ:()=>v,Ro:()=>S,qC:()=>A,qZ:()=>C,Lf:()=>P,QH:()=>y});var n=i(7257),s=i(4141),r=i(1128),o=i(6113),a=i(6202),l=i(6702),h=i(1057),c=i(392),u=i(2722),d=i(8121),p=(i(6697),i(9075),i(452),i(8104));i(1423);p.v.ShadersStore.rgbdEncodePixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}",i(7161);var f=i(2286);const _="image/png",m=2,g=[134,22,135,150,246,214,150,54];function v(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;e<g.length;e++)if(t.getUint8(i++)!==g[e])return u.Y.Error("Not a babylon environment map"),null;let n="",s=0;for(;s=t.getUint8(i++);)n+=String.fromCharCode(s);let r=JSON.parse(n);return r=y(r),r.specular&&(r.specular.specularDataPosition=i,r.specular.lodGenerationScale=r.specular.lodGenerationScale||.8),r}function y(e){if(e.version>m)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${m}".`);return 2===e.version?e:e={...e,version:2,imageType:_}}async function x(e,t={}){var i;const n=e.getInternalTexture();if(!n)return Promise.reject("The cube texture is invalid.");const s=null!==(i=t.imageType)&&void 0!==i?i:_,o=n.getEngine();if(2!==e.textureType&&1!==e.textureType&&0!==e.textureType&&0!==e.textureType&&7!==e.textureType&&-1!==e.textureType)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let a=1;if(!o.getCaps().textureFloatRender&&(a=2,!o.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");const l=n.width,c=new h.x(o),u={};o.flushFramebuffer();const p=r.R.ILog2(n.width);for(let i=0;i<=p;i++){const n=Math.pow(2,p-i);for(let r=0;r<6;r++){let l=await e.readPixels(r,i,void 0,!1);if(l&&l.byteLength===l.length){const e=new Float32Array(4*l.byteLength);for(let t=0;t<l.byteLength;t++)e[t]=l[t]/255,e[t]=Math.pow(e[t],2.2);l=e}else if(l&&e.gammaSpace){const e=l;for(let t=0;t<e.length;t++)e[t]=Math.pow(e[t],2.2)}const h=o.createRawTexture(l,n,n,5,!1,!0,1,null,a);await d.r.EncodeTextureToRGBD(h,c,a);const p=await o._readTexturePixels(h,n,n),_=await f.B.DumpDataAsync(n,n,p,s,void 0,!1,!0,t.imageQuality);u[6*i+r]=_,h.dispose()}}c.dispose();const v={version:m,width:l,imageType:s,irradiance:b(e),specular:{mipmaps:[],lodGenerationScale:e.lodGenerationScale}};let y=0;for(let e=0;e<=p;e++)for(let t=0;t<6;t++){const i=u[6*e+t].byteLength;v.specular.mipmaps.push({length:i,position:y}),y+=i}const x=JSON.stringify(v),T=new ArrayBuffer(x.length+1),S=new Uint8Array(T);for(let e=0,t=x.length;e<t;e++)S[e]=x.charCodeAt(e);S[x.length]=0;const E=g.length+y+T.byteLength,C=new ArrayBuffer(E),A=new Uint8Array(C),P=new DataView(C);let R=0;for(let e=0;e<g.length;e++)P.setUint8(R++,g[e]);A.set(new Uint8Array(T),R),R+=T.byteLength;for(let e=0;e<=p;e++)for(let t=0;t<6;t++){const i=u[6*e+t];A.set(new Uint8Array(i),R),R+=i.byteLength}return C}function b(e){const t=e.sphericalPolynomial;return null==t?null:{x:[t.x.x,t.x.y,t.x.z],y:[t.y.x,t.y.y,t.y.z],z:[t.z.x,t.z.y,t.z.z],xx:[t.xx.x,t.xx.y,t.xx.z],yy:[t.yy.x,t.yy.y,t.yy.z],zz:[t.zz.x,t.zz.y,t.zz.z],yz:[t.yz.x,t.yz.y,t.yz.z],zx:[t.zx.x,t.zx.y,t.zx.z],xy:[t.xy.x,t.xy.y,t.xy.z]}}function T(e,t){const i=(t=y(t)).specular;let n=r.R.Log2(t.width);if(n=Math.round(n)+1,i.mipmaps.length!==6*n)throw new Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);const s=new Array(n);for(let t=0;t<n;t++){s[t]=new Array(6);for(let n=0;n<6;n++){const r=i.mipmaps[6*t+n];s[t][n]=new Uint8Array(e.buffer,e.byteOffset+i.specularDataPosition+r.position,r.length)}}return s}function S(e,t,i){const n=(i=y(i)).specular;return n?(e._lodGenerationScale=n.lodGenerationScale,C(e,T(t,i),i.imageType)):Promise.resolve()}function E(e,t,i,n,s,r,o,a,l,h,c){return new Promise(((u,d)=>{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{d(e)}),e);n.getEffect().executeWhenCompiled((()=>{n.externalTextureSamplerBinding=!0,n.onApply=n=>{n._bindTexture("textureSampler",i),n.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([n],h,!0,r,o),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),u())}))}else{if(t._uploadImageToTexture(c,e,r,o),a){const i=l[o];i&&t._uploadImageToTexture(i._texture,e,r,0)}u()}}))}function C(e,t,i=_){if(!n.w1.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const s=r.R.ILog2(e.width)+1,o=e.getEngine();let h=!1,u=!1,d=null,p=null,f=null;const m=o.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,o.updateTextureSamplingMode(3,e),m.textureLOD?o._features.supportRenderAndCopyToLodForFloatTextures?m.textureHalfFloatRender&&m.textureHalfFloatLinearFiltering?(h=!0,e.type=2):m.textureFloatRender&&m.textureFloatLinearFiltering&&(h=!0,e.type=1):h=!1:(h=!1,u=!0,f={}),h)d=new c.D("rgbdDecode","rgbdDecode",null,null,1,null,3,o,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,p=o.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,u){const t=3,i=e._lodGenerationScale,n=e._lodGenerationOffset;for(let r=0;r<t;r++){const h=(s-1)*i+n,c=n+(h-n)*(1-r/(t-1)),u=Math.round(Math.min(Math.max(c,0),h)),d=new a.l(o,a.S.Temp);d.isCube=!0,d.invertY=!0,d.generateMipMaps=!1,o.updateTextureSamplingMode(2,d);const p=new l.V(null);switch(p._isCube=!0,p._texture=d,f[u]=p,r){case 0:e._lodTextureLow=p;break;case 1:e._lodTextureMid=p;break;case 2:e._lodTextureHigh=p}}}const g=[];for(let n=0;n<t.length;n++)for(let s=0;s<6;s++){const r=t[n][s],a=new Blob([r],{type:i}),l=URL.createObjectURL(a);let c;if("undefined"==typeof Image||o._features.forceBitmapOverHTMLImageElement)c=o.createImageBitmap(a,{premultiplyAlpha:"none"}).then((t=>E(t,o,h,d,l,s,n,u,f,p,e)));else{const t=new Image;t.src=l,c=new Promise(((i,r)=>{t.onload=()=>{E(t,o,h,d,l,s,n,u,f,p,e).then((()=>i())).catch((e=>{r(e)}))},t.onerror=e=>{r(e)}}))}g.push(c)}if(t.length<s){let i;const n=Math.pow(2,s-1-t.length),r=n*n*4;switch(e.type){case 0:i=new Uint8Array(r);break;case 2:i=new Uint16Array(r);break;case 1:i=new Float32Array(r)}for(let n=t.length;n<s;n++)for(let t=0;t<6;t++)o._uploadArrayBufferViewToTexture(e,i,t,n)}return Promise.all(g).then((()=>{p&&(o._releaseTexture(e),p._swapAndDie(e)),d&&d.dispose(),u&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}function A(e,t){const i=(t=y(t)).irradiance;if(!i)return;const n=new o.i;s.P.FromArrayToRef(i.x,0,n.x),s.P.FromArrayToRef(i.y,0,n.y),s.P.FromArrayToRef(i.z,0,n.z),s.P.FromArrayToRef(i.xx,0,n.xx),s.P.FromArrayToRef(i.yy,0,n.yy),s.P.FromArrayToRef(i.zz,0,n.zz),s.P.FromArrayToRef(i.yz,0,n.yz),s.P.FromArrayToRef(i.zx,0,n.zx),s.P.FromArrayToRef(i.xy,0,n.xy),e._sphericalPolynomial=n}function P(e,t,i,n,s){const r=C(e.getEngine().createRawCubeTexture(null,e.width,e.format,e.type,e.generateMipMaps,e.invertY,e.samplingMode,e._compression),t).then((()=>e));return e.onRebuildCallback=e=>({proxy:r,isReady:!0,isAsync:!0}),e._source=a.S.CubeRawRGBD,e._bufferViewArrayArray=t,e._lodGenerationScale=n,e._lodGenerationOffset=s,e._sphericalPolynomial=i,C(e,t).then((()=>(e.isReady=!0,e)))}const R={GetEnvInfo:v,CreateEnvTextureAsync:x,CreateImageDataArrayBufferViews:T,UploadEnvLevelsAsync:S,UploadLevelsAsync:C,UploadEnvSpherical:A}},1722:(e,t,i)=>{i.d(t,{GU:()=>n,LH:()=>r,SM:()=>s});class n extends Error{}n._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const s={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class r extends n{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",n._setPrototypeOf(this,r.prototype)}}},5661:(e,t,i)=>{i.d(t,{$K:()=>M,$M:()=>b,A2:()=>I,FV:()=>C,Ip:()=>S,RC:()=>v,Uh:()=>A,VL:()=>P,W5:()=>O,e0:()=>D,eh:()=>m,kK:()=>g,qC:()=>R,r6:()=>T,rN:()=>y,vP:()=>E});var n=i(6662),s=i(6797),r=i(5757),o=i(679),a=i(4918),l=i(1722),h=i(2655),c=i(8198),u=i(3230),d=i(1431),p=i(2722),f=i(6290);const _=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class m extends l.LH{constructor(e,t){super(e,l.SM.LoadFileError),this.name="LoadFileError",l.GU._setPrototypeOf(this,m.prototype),t instanceof n.g?this.request=t:this.file=t}}class g extends l.LH{constructor(e,t){super(e,l.SM.RequestFileError),this.request=t,this.name="RequestFileError",l.GU._setPrototypeOf(this,g.prototype)}}class v extends l.LH{constructor(e,t){super(e,l.SM.ReadFileError),this.file=t,this.name="ReadFileError",l.GU._setPrototypeOf(this,v.prototype)}}const y={DefaultRetryStrategy:a.b.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e},x=e=>e.replace(/#/gm,"%23"),b=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&y.CorsBehavior)if("string"==typeof y.CorsBehavior||y.CorsBehavior instanceof String)t.crossOrigin=y.CorsBehavior;else{const i=y.CorsBehavior(e);i&&(t.crossOrigin=i)}},T=(e,t,i,n,s="",r)=>{var a;let l,c=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(l=URL.createObjectURL(new Blob([e],{type:s})),c=!0):l=`data:${s};base64,`+(0,h.Gh)(e):e instanceof Blob?(l=URL.createObjectURL(e),c=!0):(l=x(e),l=y.PreprocessUrl(e));const u=d.l.LastCreatedEngine,p=t=>{if(i){const n=l||e.toString();i(`Error while trying to load image: ${0===n.indexOf("http")||n.length<=128?n:n.slice(0,128)+"..."}`,t)}};if("undefined"==typeof Image||null!==(a=null==u?void 0:u._features.forceBitmapOverHTMLImageElement)&&void 0!==a&&a)return E(l,(n=>{u.createImageBitmap(new Blob([n],{type:s}),{premultiplyAlpha:"none",...r}).then((e=>{t(e),c&&URL.revokeObjectURL(l)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,n||void 0,!0,((e,t)=>{p(t)})),null;const f=new Image;b(l,f);const _=[],m=()=>{_.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),_.length=0};_.push({target:f,name:"load",handler:()=>{m(),t(f),c&&f.src&&URL.revokeObjectURL(f.src)}}),_.push({target:f,name:"error",handler:e=>{m(),p(e),c&&f.src&&URL.revokeObjectURL(f.src)}}),_.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==f.src)return;m();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);d.l.UseFallbackTexture=!1,p(t),c&&f.src&&URL.revokeObjectURL(f.src),f.src=""}}),_.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const g="blob:"===l.substring(0,5),v="data:"===l.substring(0,5),T=()=>{g||v?f.src=l:E(l,((e,t,i)=>{const n=new Blob([e],{type:!s&&i?i:s}),r=URL.createObjectURL(n);c=!0,f.src=r}),void 0,n||void 0,!0,((e,t)=>{p(t)}))};if(!g&&!v&&n&&n.enableTexturesOffline)n.open((()=>{n&&n.loadImage(l,f)}),T);else{if(-1!==l.indexOf("file:")){const e=decodeURIComponent(l.substring(5).toLowerCase());if(o.X.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(o.X.FilesToLoad[e])}catch(i){t=URL.createObjectURL(o.X.FilesToLoad[e])}f.src=t,c=!0}catch(e){f.src=""}return f}}T()}return f},S=(e,t,i,n,s)=>{const o=new FileReader,a={onCompleteObservable:new r.y$,abort:()=>o.abort()};return o.onloadend=()=>a.onCompleteObservable.notifyObservers(a),s&&(o.onerror=()=>{s(new v(`Unable to read ${e.name}`,e))}),o.onload=e=>{t(e.target.result)},i&&(o.onprogress=i),n?o.readAsArrayBuffer(e):o.readAsText(e),a},E=(e,t,i,n,s,a,l)=>{if(e.name)return S(e,t,i,s,a?e=>{a(void 0,e)}:void 0);const h=e;if(-1!==h.indexOf("file:")){let e=decodeURIComponent(h.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const n=o.X.FilesToLoad[e];if(n)return S(n,t,i,s,a?e=>a(void 0,new m(e.message,e.file)):void 0)}const{match:c,type:u}=R(h);if(c){const e={onCompleteObservable:new r.y$,abort:()=>()=>{}};try{const e=s?M(h):I(h);t(e,void 0,u)}catch(e){a?a(void 0,e):p.Y.Error(e.message||"Failed to parse the Data URL")}return f.Q.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return C(h,((e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))}),i,n,s,a?e=>{a(e.request,new m(e.message,e.request))}:void 0,l)},C=(e,t,i,o,a,l,h)=>{e=x(e),e=y.PreprocessUrl(e);const c=y.BaseUrl+e;let u=!1;const d={onCompleteObservable:new r.y$,abort:()=>u=!0},f=()=>{let e,r=new n.g,o=null;const f=()=>{r&&(i&&r.removeEventListener("progress",i),e&&r.removeEventListener("readystatechange",e),r.removeEventListener("loadend",_))};let _=()=>{f(),d.onCompleteObservable.notifyObservers(d),d.onCompleteObservable.clear(),i=void 0,e=null,_=null,l=void 0,h=void 0,t=void 0};d.abort=()=>{u=!0,_&&_(),r&&r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort(),null!==o&&(clearTimeout(o),o=null),r=null};const m=e=>{const t=e.message||"Unknown error";l&&r?l(new g(t,r)):p.Y.Error(t)},v=d=>{if(r){if(r.open("GET",c),h)try{h(r)}catch(e){return void m(e)}a&&(r.responseType="arraybuffer"),i&&r.addEventListener("progress",i),_&&r.addEventListener("loadend",_),e=()=>{if(!u&&r&&r.readyState===(XMLHttpRequest.DONE||4)){if(e&&r.removeEventListener("readystatechange",e),r.status>=200&&r.status<300||0===r.status&&(!(0,s.CG)()||A())){try{t&&t(a?r.response:r.responseText,r)}catch(e){m(e)}return}const i=y.DefaultRetryStrategy;if(i){const e=i(c,r,d);if(-1!==e)return f(),r=new n.g,void(o=setTimeout((()=>v(d+1)),e))}const h=new g("Error status: "+r.status+" "+r.statusText+" - Unable to load "+c,r);l&&l(h)}},r.addEventListener("readystatechange",e),r.send()}};v(0)};if(o&&o.enableSceneOffline){const n=e=>{e&&e.status>400?l&&l(e):f()},s=()=>{o&&o.loadFile(y.BaseUrl+e,(e=>{!u&&t&&t(e),d.onCompleteObservable.notifyObservers(d)}),i?e=>{!u&&i&&i(e)}:void 0,n,a)};o.open(s,n)}else f();return d},A=()=>"undefined"!=typeof location&&"file:"===location.protocol,P=e=>_.test(e),R=e=>{const t=_.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function M(e){return(0,h.HQ)(e.split(",")[1])}const I=e=>(0,h.rP)(e.split(",")[1]);let D;u.B._FileToolsLoadImage=T,u.B._FileToolsLoadFile=E,c.L._FileToolsLoadFile=E;const O=(e,t,i,n,s,r,o,a,l,h)=>{D={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:n,IsFileURL:s,LoadFile:r,LoadImage:o,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(D,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(D,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(D,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(D,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})};O(M,I,y,P,A,E,T,S,C,b)},679:(e,t,i)=>{i.d(t,{X:()=>n});class n{}n.FilesToLoad={}},1983:(e,t,i)=>{function n(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}i.d(t,{f:()=>n,x:()=>s});const s={RandomId:n}},8126:(e,t,i)=>{i.d(t,{K:()=>r});var n=i(2722),s=i(2208);class r{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=(0,s.q)(e);if(t)return t;n.Y.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let r=window||this;for(let e=0,t=i.length;e<t;e++)r=r[i[e]];return"function"!=typeof r?null:r}}r.RegisteredExternalClasses={}},2722:(e,t,i)=>{i.d(t,{Y:()=>n});class n{static _CheckLimit(e,t){let i=n._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},n._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var i;const s=n._LogLimitOutputs[e];if(!s||!n.MessageLimitReached)return;const r=this._Levels[t];s.current===s.limit&&n[r.name](n.MessageLimitReached.replace(/%LIMIT%/g,""+s.limit).replace(/%TYPE%/g,null!==(i=r.name)&&void 0!==i?i:""))}static _AddLogEntry(e){n._LogCache=e+n._LogCache,n.OnNewCacheEntry&&n.OnNewCacheEntry(e)}static _FormatMessage(e){const t=e=>e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){if(void 0!==i&&!n._CheckLimit(t,i))return;const s=n._FormatMessage(t),r=this._Levels[e];r.logFunc&&r.logFunc("BJS - "+s);const o=`<div style='color:${r.color}'>${s}</div><br>`;n._AddLogEntry(o),n._GenerateLimitMessage(t,e)}static get LogCache(){return n._LogCache}static ClearLogCache(){n._LogCache="",n._LogLimitOutputs={},n.errorsCount=0}static set LogLevels(e){n.Log=n._LogDisabled,n.Warn=n._LogDisabled,n.Error=n._LogDisabled,[n.MessageLogLevel,n.WarningLogLevel,n.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];n[e.name]=n._LogEnabled.bind(n,t)}}))}}n.NoneLogLevel=0,n.MessageLogLevel=1,n.WarningLogLevel=2,n.ErrorLogLevel=4,n.AllLogLevel=7,n.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",n._LogCache="",n._LogLimitOutputs={},n._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],n.errorsCount=0,n.Log=n._LogEnabled.bind(n,n.MessageLogLevel),n.Warn=n._LogEnabled.bind(n,n.WarningLogLevel),n.Error=n._LogEnabled.bind(n,n.ErrorLogLevel)},5757:(e,t,i)=>{i.d(t,{Qj:()=>s,he:()=>n,y$:()=>r});class n{constructor(e,t=!1,i,n){this.initialize(e,t,i,n)}initialize(e,t=!1,i,n){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=n,this}}class s{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1}}class r{static FromPromise(e,t){const i=new r;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),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 n(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,n=null,r=!1){if(!e)return null;const o=new s(e,t,n);return o.unregisterOnNextCall=r,i?this._observers.unshift(o):this._observers.push(o),this._onObserverAdded&&this._onObserverAdded(o),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(o,this._lastNotifiedValue),o}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}removeCallback(e,t){for(let i=0;i<this._observers.length;i++){const n=this._observers[i];if(!(n._willBeUnregistered||n.callback!==e||t&&t!==n.scope))return this._deferUnregister(n),!0}return!1}_deferUnregister(e){e._willBeUnregistered||(this._numObserversMarkedAsDeleted++,e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout((()=>{this._remove(e)}),0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,n,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const r=this._eventState;r.mask=t,r.target=i,r.currentTarget=n,r.skipNextObservers=!1,r.lastReturnValue=e,r.userInfo=s;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?r.lastReturnValue=i.callback.apply(i.scope,[e,r]):r.lastReturnValue=i.callback(e,r)),r.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const n=this._eventState;n.mask=i,n.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,n)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){this._observers.length=0,this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new r;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}}},8215:(e,t,i)=>{i.d(t,{z:()=>s});var n=i(8108);class s{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){s.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){s.Enabled&&(this._startMonitoringTime=n.F.Now)}endMonitoring(e=!0){if(!s.Enabled)return;e&&this.fetchNewFrame();const t=n.F.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=n.F.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}s.Enabled=!0},4757:(e,t,i)=>{i.d(t,{A:()=>s,Z:()=>r});var n=i(8108);class s{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new r(e)}sampleFrame(e=n.F.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class r{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}},6746:(e,t,i)=>{i.d(t,{m:()=>s});var n=i(4141);class s{static _RemoveAndStorePivotPoint(e){e&&0===s._PivotCached&&(e.getPivotPointToRef(s._OldPivotPoint),s._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,s._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(n.y3.IdentityReadOnly),s._OldPivotPoint.subtractToRef(e.getPivotPoint(),s._PivotTranslation),s._PivotTmpVector.copyFromFloats(1,1,1),s._PivotTmpVector.subtractInPlace(e.scaling),s._PivotTmpVector.multiplyInPlace(s._PivotTranslation),e.position.addInPlace(s._PivotTmpVector))),s._PivotCached++}static _RestorePivotPoint(e){e&&!s._OldPivotPoint.equalsToFloats(0,0,0)&&1===s._PivotCached&&(e.setPivotPoint(s._OldPivotPoint),e._postMultiplyPivotMatrix=s._PivotPostMultiplyPivotMatrix,s._PivotTmpVector.copyFromFloats(1,1,1),s._PivotTmpVector.subtractInPlace(e.scaling),s._PivotTmpVector.multiplyInPlace(s._PivotTranslation),e.position.subtractInPlace(s._PivotTmpVector)),this._PivotCached--}}s._PivotCached=0,s._OldPivotPoint=new n.P,s._PivotTranslation=new n.P,s._PivotTmpVector=new n.P,s._PivotPostMultiplyPivotMatrix=!1},8108:(e,t,i)=>{i.d(t,{F:()=>s});var n=i(6797);class s{static get Now(){return n.MZ.IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}},4918:(e,t,i)=>{i.d(t,{b:()=>n});class n{static ExponentialBackoff(e=3,t=500){return(i,n,s)=>0!==n.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}}},8121:(e,t,i)=>{i.d(t,{r:()=>r});var n=i(392),s=(i(7161),i(7246),i(806));class r{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),r=t.isReady;let o=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(o=!0,t.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(o=!0,t.type=1),o&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const a=()=>{if(o){const s=new n.D("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);s.externalTextureSamplerBinding=!0;const r=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});s.getEffect().executeWhenCompiled((()=>{s.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([s],r,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),s&&s.dispose(),r._swapAndDie(t),t.isReady=!0}))}};r?a():e.onLoadObservable.addOnce(a)}static EncodeTextureToRGBD(e,t,i=0){return(0,s.$0)("rgbdEncode",e,t,i,1,5)}}},5363:(e,t,i)=>{i.d(t,{f:()=>s,t:()=>n});class n{constructor(e){this.length=0,this.data=new Array(e),this._id=n._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;t<this.length;t++)e(this.data[t])}sort(e){this.data.sort(e)}reset(){this.length=0}dispose(){this.reset(),this.data&&(this.data.length=0)}concat(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}}indexOf(e){const t=this.data.indexOf(e);return t>=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}n._GlobalId=0;class s extends n{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return!(e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId||(this.push(e),0))}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t<e.length;t++){const i=(e.data||e)[t];this.pushNoDuplicate(i)}}}}},7090:(e,t,i)=>{i.d(t,{x:()=>n});class n{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach(((e,t)=>this.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data)e(t,this._data[t])}first(e){for(const t in this._data){const i=e(t,this._data[t]);if(i)return i}return null}}},2655:(e,t,i)=>{i.d(t,{Gh:()=>o,HQ:()=>l,Ml:()=>c,Ri:()=>s,fJ:()=>r,gi:()=>n,rP:()=>a,zA:()=>h});const n=(e,t)=>e.endsWith(t),s=(e,t)=>!!e&&e.startsWith(t),r=e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0;i<e.byteLength;i++)t+=String.fromCharCode(e[i]);return t},o=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,n,s,r,o,a,l,h="",c=0;const u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c<u.length;)i=u[c++],n=c<u.length?u[c++]:Number.NaN,s=c<u.length?u[c++]:Number.NaN,r=i>>2,o=(3&i)<<4|n>>4,a=(15&n)<<2|s>>6,l=63&s,isNaN(n)?a=l=64:isNaN(s)&&(l=64),h+=t.charAt(r)+t.charAt(o)+t.charAt(a)+t.charAt(l);return h},a=e=>atob(e),l=e=>{const t=a(e),i=t.length,n=new Uint8Array(new ArrayBuffer(i));for(let e=0;e<i;e++)n[e]=t.charCodeAt(e);return n.buffer},h=(e,t)=>{let i=String(e);for(;i.length<t;)i="0"+i;return i},c={EndsWith:n,StartsWith:s,Decode:r,EncodeArrayBufferToBase64:o,DecodeBase64ToString:a,DecodeBase64ToBinary:l,PadNumber:h}},4875:(e,t,i)=>{i.d(t,{$:()=>s});var n=i(5559);class s{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>s.HasTags(e),e.addTags=t=>s.AddTagsTo(e,t),e.removeTags=t=>s.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>s.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach((function(t){s._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(s.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!s.HasTags(e))return;const i=t.split(" ");for(const t in i)s._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?s.HasTags(e):n.q.Eval(t,(t=>s.HasTags(e)&&e._tags[t])))}}},806:(e,t,i)=>{i.d(t,{$0:()=>l,Oi:()=>p,ay:()=>u,cW:()=>a,qZ:()=>d});var n=i(2262),s=i(4246),r=i(9525),o=i(392);function a(e,t,i,o=!0){const a=e.getScene(),l=a.getEngine(),h=new s._("resized"+e.name,{width:t,height:i},a,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);h.wrapU=e.wrapU,h.wrapV=e.wrapV,h.uOffset=e.uOffset,h.vOffset=e.vOffset,h.uScale=e.uScale,h.vScale=e.vScale,h.uAng=e.uAng,h.vAng=e.vAng,h.wAng=e.wAng,h.coordinatesIndex=e.coordinatesIndex,h.level=e.level,h.anisotropicFilteringLevel=e.anisotropicFilteringLevel,h._texture.isReady=!1,e.wrapU=n.x.CLAMP_ADDRESSMODE,e.wrapV=n.x.CLAMP_ADDRESSMODE;const c=new r.Q("pass",1,null,o?n.x.BILINEAR_SAMPLINGMODE:n.x.NEAREST_SAMPLINGMODE,l,!1,0);return c.externalTextureSamplerBinding=!0,c.getEffect().executeWhenCompiled((()=>{c.onApply=function(t){t.setTexture("textureSampler",e)};const t=h.renderTarget;t&&(a.postProcessManager.directRender([c],t),l.unBindFramebuffer(t),h.disposeFramebufferObjects(),c.dispose(),h.getInternalTexture().isReady=!0)})),h}function l(e,t,i,n,s,r,a,l){const h=t.getEngine();return t.isReady=!1,s=null!=s?s:t.samplingMode,n=null!=n?n:t.type,r=null!=r?r:t.format,a=null!=a?a:t.width,l=null!=l?l:t.height,-1===n&&(n=0),new Promise((c=>{const u=new o.D("postprocess",e,null,null,1,null,s,h,!1,void 0,n,void 0,null,!1,r);u.externalTextureSamplerBinding=!0;const d=h.createRenderTargetTexture({width:a,height:l},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:n,format:r});u.getEffect().executeWhenCompiled((()=>{u.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([u],d,!0),h.restoreDefaultFramebuffer(),h._releaseTexture(t),u&&u.dispose(),d._swapAndDie(t),t.type=n,t.format=5,t.isReady=!0,c(t)}))}))}let h,c;function u(e){h||(h=new Float32Array(1),c=new Int32Array(h.buffer)),h[0]=e;const t=c[0];let i=t>>16&32768,n=t>>12&2047;const s=t>>23&255;return s<103?i:s>142?(i|=31744,i|=(255==s?0:1)&&8388607&t,i):s<113?(n|=2048,i|=(n>>114-s)+(n>>113-s&1),i):(i|=s-112<<10|n>>1,i+=1&n,i)}function d(e){const t=(32768&e)>>15,i=(31744&e)>>10,n=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(n/Math.pow(2,10)):31==i?n?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+n/Math.pow(2,10))}const p={CreateResizedCopy:a,ApplyPostProcess:l,ToHalfFloat:u,FromHalfFloat:d}},6290:(e,t,i)=>{i.d(t,{Q:()=>s});var n=i(6797);class s{static SetImmediate(e){(0,n.CG)()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}},7257:(e,t,i)=>{i.d(t,{$g:()=>g,ok:()=>m,w1:()=>_});var n=i(5757),s=i(6797),r=i(2722),o=i(6387),a=i(8108),l=i(4934),h=i(6662),c=i(1431),u=i(5661),d=i(6290),p=i(8126),f=i(1983);class _{static get BaseUrl(){return u.rN.BaseUrl}static set BaseUrl(e){u.rN.BaseUrl=e}static get DefaultRetryStrategy(){return u.rN.DefaultRetryStrategy}static set DefaultRetryStrategy(e){u.rN.DefaultRetryStrategy=e}static get CorsBehavior(){return u.rN.CorsBehavior}static set CorsBehavior(e){u.rN.CorsBehavior=e}static get UseFallbackTexture(){return c.l.UseFallbackTexture}static set UseFallbackTexture(e){c.l.UseFallbackTexture=e}static get RegisteredExternalClasses(){return p.K.RegisteredExternalClasses}static set RegisteredExternalClasses(e){p.K.RegisteredExternalClasses=e}static get fallbackTexture(){return c.l.FallbackTexture}static set fallbackTexture(e){c.l.FallbackTexture=e}static FetchToRef(e,t,i,n,s,r){const o=4*((Math.abs(e)*i%i|0)+(Math.abs(t)*n%n|0)*i);r.r=s[o]/255,r.g=s[o+1]/255,r.b=s[o+2]/255,r.a=s[o+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return p.K.Instantiate(e)}static SetImmediate(e){d.Q.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do{t*=2}while(t<e);return t===e}static FloatRound(e){return Math.fround?Math.fround(e):(_._TmpFloatArray[0]=e,_._TmpFloatArray[0])}static GetFilename(e){const t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){const i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)}static ToDegrees(e){return 180*e/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,i=.9){const n=this.ToRadians(e),s=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-i)*Math.sin(s)+i*Math.sin(n),(1-i)*Math.cos(s)+i*Math.cos(n)))}static MakeArray(e,t){return!0===t||void 0!==e&&null!=e?Array.isArray(e)?e:[e]:null}static GetPointerPrefix(e){let t="pointer";return(0,s.CG)()&&!window.PointerEvent&&(t="mouse"),!e._badDesktopOS||e._badOS||document&&"ontouchend"in document||(t="mouse"),t}static SetCorsBehavior(e,t){(0,u.$M)(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static CleanUrl(e){return e.replace(/#/gm,"%23")}static get PreprocessUrl(){return u.rN.PreprocessUrl}static set PreprocessUrl(e){u.rN.PreprocessUrl=e}static LoadImage(e,t,i,n,s,r){return(0,u.r6)(e,t,i,n,s,r)}static LoadFile(e,t,i,n,s,r){return(0,u.vP)(e,t,i,n,s,r)}static LoadFileAsync(e,t=!0){return new Promise(((i,n)=>{(0,u.vP)(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{n(t)}))}))}static LoadScript(e,t,i,n){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){null==i||i(`Unable to load script '${e}' in worker`,t)}return}if(!(0,s.CG)())return void(null==i||i(`Cannot load script '${e}' outside of a window or a worker`));const r=document.getElementsByTagName("head")[0],o=document.createElement("script");o.setAttribute("type","text/javascript"),o.setAttribute("src",e),n&&(o.id=n),o.onload=()=>{t&&t()},o.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(o)}static LoadScriptAsync(e){return new Promise(((t,i)=>{this.LoadScript(e,(()=>{t()}),((e,t)=>{i(t||new Error(e))}))}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new n.y$,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,n,s){return(0,u.Ip)(e,t,i,n,s)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,n){o.j.DeepCopy(e,t,i,n)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){const n=t[i];e.addEventListener(n.name,n.handler,!1);try{window.parent&&window.parent.addEventListener(n.name,n.handler,!1)}catch(e){}}}static UnregisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){const n=t[i];e.removeEventListener(n.name,n.handler);try{e.parent&&e.parent.removeEventListener(n.name,n.handler)}catch(e){}}}static async DumpFramebuffer(e,t,i,n,s="image/png",r){throw(0,l.S)("DumpTools")}static DumpData(e,t,i,n,s="image/png",r,o=!1,a=!1,h){throw(0,l.S)("DumpTools")}static DumpDataAsync(e,t,i,n="image/png",s,r=!1,o=!1,a){throw(0,l.S)("DumpTools")}static _IsOffScreenCanvas(e){return void 0!==e.convertToBlob}static ToBlob(e,t,i="image/png",n){_._IsOffScreenCanvas(e)||e.toBlob||(e.toBlob=function(e,t,i){setTimeout((()=>{const n=atob(this.toDataURL(t,i).split(",")[1]),s=n.length,r=new Uint8Array(s);for(let e=0;e<s;e++)r[e]=n.charCodeAt(e);e(new Blob([r]))}))}),_._IsOffScreenCanvas(e)?e.convertToBlob({type:i,quality:n}).then((e=>t(e))):e.toBlob((function(e){t(e)}),i,n)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2)+".png"}_.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const n=i.document.createElement("img");n.onload=function(){URL.revokeObjectURL(t)},n.src=t,i.document.body.appendChild(n)}}static EncodeScreenshotCanvasData(e,t,i="image/png",n,s){if("string"!=typeof n&&t){if(t){if(_._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:s}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const n=e.toDataURL(i,s);t(n)}}else this.ToBlob(e,(function(e){e&&_.DownloadBlob(e,n),t&&t("")}),i,s)}static Download(e,t){if("undefined"==typeof URL)return;const i=window.URL.createObjectURL(e),n=document.createElement("a");document.body.appendChild(n),n.style.display="none",n.href=i,n.download=t,n.addEventListener("click",(()=>{n.parentElement&&n.parentElement.removeChild(n)})),n.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,n,s="image/png"){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,n="image/png"){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,n,s="image/png",r=1,o=!1,a){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,n="image/png",s=1,r=!1,o){throw(0,l.S)("ScreenshotTools")}static RandomId(){return(0,f.f)()}static IsBase64(e){return(0,u.VL)(e)}static DecodeBase64(e){return(0,u.$K)(e)}static get errorsCount(){return r.Y.errorsCount}static Log(e){r.Y.Log(e)}static Warn(e){r.Y.Warn(e)}static Error(e){r.Y.Error(e)}static get LogCache(){return r.Y.LogCache}static ClearLogCache(){r.Y.ClearLogCache()}static set LogLevels(e){r.Y.LogLevels=e}static set PerformanceLogLevel(e){return(e&_.PerformanceUserMarkLogLevel)===_.PerformanceUserMarkLogLevel?(_.StartPerformanceCounter=_._StartUserMark,void(_.EndPerformanceCounter=_._EndUserMark)):(e&_.PerformanceConsoleLogLevel)===_.PerformanceConsoleLogLevel?(_.StartPerformanceCounter=_._StartPerformanceConsole,void(_.EndPerformanceCounter=_._EndPerformanceConsole)):(_.StartPerformanceCounter=_._StartPerformanceCounterDisabled,void(_.EndPerformanceCounter=_._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!_._Performance){if(!(0,s.CG)())return;_._Performance=window.performance}t&&_._Performance.mark&&_._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&_._Performance.mark&&(_._Performance.mark(e+"-End"),_._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(_._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(_._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return a.F.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,n=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,n=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=n?n+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!(0,s.up)()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}function m(e,t){return i=>{i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}_.UseCustomRequestHeaders=!1,_.CustomRequestHeaders=h.g.CustomRequestHeaders,_._TmpFloatArray=new Float32Array(1),_.GetDOMTextContent=s.v,_.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},_.NoneLogLevel=r.Y.NoneLogLevel,_.MessageLogLevel=r.Y.MessageLogLevel,_.WarningLogLevel=r.Y.WarningLogLevel,_.ErrorLogLevel=r.Y.ErrorLogLevel,_.AllLogLevel=r.Y.AllLogLevel,_.IsWindowObjectExist=s.CG,_.PerformanceNoneLogLevel=0,_.PerformanceUserMarkLogLevel=1,_.PerformanceConsoleLogLevel=2,_.StartPerformanceCounter=_._StartPerformanceCounterDisabled,_.EndPerformanceCounter=_._EndPerformanceCounterDisabled;class g{constructor(e,t,i,n=0){this.iterations=e,this.index=n-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())}breakLoop(){this._done=!0,this._successCallback()}static Run(e,t,i,n=0){const s=new g(e,t,i,n);return s.executeNext(),s}static SyncAsyncForLoop(e,t,i,n,s,r=0){return g.Run(Math.ceil(e/t),(n=>{s&&s()?n.breakLoop():setTimeout((()=>{for(let r=0;r<t;++r){const o=n.index*t+r;if(o>=e)break;if(i(o),s&&s()){n.breakLoop();break}}n.executeNext()}),r)}),n)}}c.l.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"},2208:(e,t,i)=>{i.d(t,{H:()=>s,q:()=>r});const n={};function s(e,t){n[e]=t}function r(e){return n[e]}},8718:(e,t,i)=>{i.d(t,{K:()=>n});class n{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}n._UniqueIdCounter=1},6662:(e,t,i)=>{i.d(t,{g:()=>n});class n{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in n.CustomRequestHeaders){const t=n.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return n.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){n.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of n.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}return t=(t=t.replace("file:http:","http:")).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)}}n.CustomRequestHeaders={},n.CustomRequestModifiers=new Array,n.SkipRequestModificationForBabylonCDN=!0},6250:(e,t,i)=>{i.d(t,{h:()=>n,v:()=>s});class n{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map((e=>({workerPromise:Promise.resolve(e),idle:!0})))}dispose(){for(const e of this._workerInfos)e.workerPromise.then((e=>{e.terminate()}));this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then((i=>{t(i,(()=>{const t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0}))}))}}class s extends n{constructor(e,t,i=s.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length<this._maxWorkers){const t={workerPromise:this._createWorkerAsync(),idle:!1};this._workerInfos.push(t),this._execute(t,e)}else this._pendingActions.push(e)}_execute(e,t){e.timeoutId&&(clearTimeout(e.timeoutId),delete e.timeoutId),super._execute(e,((i,n)=>{t(i,(()=>{n(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}s.DefaultOptions={idleTimeElapsedBeforeRelease:1e3}},7780:(e,t,i)=>{i.d(t,{Y:()=>h});var n=i(9472),s=i(5757),r=i(1431),o=i(708),a=i(3956),l=i(2208);class h{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(0===t||0===e)}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=new Array,this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new s.y$,this._onDataLayoutChanged=new s.y$,this._animationPropertiesOverride=null,this._scene=i||r.l.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=a.p4.Clone((()=>new h(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()),null!=this.id&&(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())),a.p4.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new h(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(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 t=0;t<e.animations.length;t++){const n=e.animations[t],s=(0,l.q)("BABYLON.Animation");s&&i.animations.push(s.Parse(n))}e.autoAnimate&&t&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1)}return i}static FromMesh(e,t,i){t||(t=e.name);const n=new h(t,i,e.getScene());return n.setPositions(e.getVerticesData(o.o.PositionKind)),e.isVerticesDataPresent(o.o.NormalKind)&&n.setNormals(e.getVerticesData(o.o.NormalKind)),e.isVerticesDataPresent(o.o.TangentKind)&&n.setTangents(e.getVerticesData(o.o.TangentKind)),e.isVerticesDataPresent(o.o.UVKind)&&n.setUVs(e.getVerticesData(o.o.UVKind)),n}}(0,n.gn)([(0,a.qC)()],h.prototype,"id",void 0)},4702:(e,t,i)=>{i.d(t,{O:()=>l});var n=i(5363),s=i(2722),r=i(1431),o=i(7780),a=i(3324);class l{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new n.t(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=r.l.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.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 l.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!(null===(e=this._scene)||void 0===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((e=>{this._syncActiveTargets(e)}))),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 l(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 e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=l.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const n=e.getPositions();if(n){const e=n.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void s.Y.Error("Incompatible target. Targets must all have the same vertices count.")}}this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e<t;e++)this._influences[e]=this._tempInfluences[e];e&&this.synchronize()}synchronize(){if(this._scene&&!this.areUpdatesFrozen){if(this.isUsingTextureForTargets&&this._vertexCount){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let n=0;n<e;n++){const e=this._targets[n],r=e.getPositions(),o=e.getNormals(),a=e.getUVs(),l=e.getTangents();if(!r)return void(0===n&&s.Y.Error("Invalid morph target. Target must have positions."));i=n*this._textureWidth*this._textureHeight*4;for(let e=0;e<this._vertexCount;e++)t[i]=r[3*e],t[i+1]=r[3*e+1],t[i+2]=r[3*e+2],i+=4,o&&(t[i]=o[3*e],t[i+1]=o[3*e+1],t[i+2]=o[3*e+2],i+=4),a&&(t[i]=a[2*e],t[i+1]=a[2*e+1],i+=4),l&&(t[i]=l[3*e],t[i+1]=l[3*e+1],t[i+2]=l[3*e+2],i+=4)}this._targetStoreTexture=a.e.CreateRGBATexture(t,this._textureWidth,this._textureHeight,e,this._scene,!1,!1,1,1)}}for(const e of this._scene.meshes)e.morphTargetManager===this&&e._syncGeometryWithMorphTargetManager()}}dispose(){if(this._targetStoreTexture&&this._targetStoreTexture.dispose(),this._targetStoreTexture=null,this._scene){if(this._scene.removeMorphTargetManager(this),this._parentContainer){const e=this._parentContainer.morphTargetManagers.indexOf(this);e>-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new l(t);i._uniqueId=e.id;for(const n of e.targets)i.addTarget(o.Y.Parse(n,t));return i}}l.EnableTextureStorage=!0,l.MaxActiveMorphTargetsInVertexAttributeMode=8},1499:(e,t,i)=>{i.d(t,{S:()=>o});var n=i(6387),s=i(4141),r=i(1128);class o{constructor(){this.direction1=new s.P(0,1,0),this.direction2=new s.P(0,1,0),this.minEmitBox=new s.P(-.5,-.5,-.5),this.maxEmitBox=new s.P(.5,.5,.5)}startDirectionFunction(e,t,i,n){const o=r.R.RandomRange(this.direction1.x,this.direction2.x),a=r.R.RandomRange(this.direction1.y,this.direction2.y),l=r.R.RandomRange(this.direction1.z,this.direction2.z);if(n)return t.x=o,t.y=a,void(t.z=l);s.P.TransformNormalFromFloatsToRef(o,a,l,e,t)}startPositionFunction(e,t,i,n){const o=r.R.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),a=r.R.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),l=r.R.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(n)return t.x=o,t.y=a,void(t.z=l);s.P.TransformCoordinatesFromFloatsToRef(o,a,l,e,t)}clone(){const e=new o;return n.j.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){s.P.FromArrayToRef(e.direction1,0,this.direction1),s.P.FromArrayToRef(e.direction2,0,this.direction2),s.P.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),s.P.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}},5098:(e,t,i)=>{i.d(t,{E:()=>r});var n=i(6387),s=i(4141);class r{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,n){const r=s.jp.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const e=s.jp.Vector3[1];r.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,r)}else r.set(0,0,0);n?t.copyFrom(r):s.P.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,n){const r=s.jp.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),n?t.copyFrom(r):s.P.TransformCoordinatesToRef(r,e,t)}clone(){const e=new r;return n.j.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){}}},5089:(e,t,i)=>{i.d(t,{S3:()=>n.S,LV:()=>a,E0:()=>f.E,z:()=>h,kT:()=>l,VD:()=>c,F3:()=>m,cl:()=>u,cE:()=>p,Ai:()=>d});var n=i(1499),s=i(6387),r=i(4141),o=i(1128);class a{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}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,n){n?r.jp.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),r.jp.Vector3[0]).normalize();const s=o.R.RandomRange(0,this.directionRandomizer),a=o.R.RandomRange(0,this.directionRandomizer),l=o.R.RandomRange(0,this.directionRandomizer);t.x=r.jp.Vector3[0].x+s,t.y=r.jp.Vector3[0].y+a,t.z=r.jp.Vector3[0].z+l,t.normalize()}startPositionFunction(e,t,i,n){const s=o.R.RandomRange(0,2*Math.PI);let a;this.emitFromSpawnPointOnly?a=1e-4:(a=o.R.RandomRange(0,this.heightRange),a=1-a*a);let l=this._radius-o.R.RandomRange(0,this._radius*this.radiusRange);l*=a;const h=l*Math.sin(s),c=l*Math.cos(s),u=a*this._height;if(n)return t.x=h,t.y=u,void(t.z=c);r.P.TransformCoordinatesFromFloatsToRef(h,u,c,e,t)}clone(){const e=new a(this._radius,this._angle,this.directionRandomizer);return s.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class l{constructor(e=1,t=1,i=1,n=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=n,this._tempVector=r.P.Zero()}startDirectionFunction(e,t,i,n,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),r.P.TransformNormalToRef(this._tempVector,s,this._tempVector);const a=o.R.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let l=Math.atan2(this._tempVector.x,this._tempVector.z);l+=o.R.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=a,this._tempVector.x=Math.sin(l),this._tempVector.z=Math.cos(l),this._tempVector.normalize(),n?t.copyFrom(this._tempVector):r.P.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,n){const s=o.R.RandomRange(-this.height/2,this.height/2),a=o.R.RandomRange(0,2*Math.PI),l=o.R.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),h=Math.sqrt(l)*this.radius,c=h*Math.cos(a),u=h*Math.sin(a);n?t.copyFromFloats(c,s,u):r.P.TransformCoordinatesFromFloatsToRef(c,s,u,e,t)}clone(){const e=new l(this.radius,this.directionRandomizer);return s.j.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 h extends l{constructor(e=1,t=1,i=1,n=new r.P(0,1,0),s=new r.P(0,1,0)){super(e,t,i),this.direction1=n,this.direction2=s}startDirectionFunction(e,t){const i=o.R.RandomRange(this.direction1.x,this.direction2.x),n=o.R.RandomRange(this.direction1.y,this.direction2.y),s=o.R.RandomRange(this.direction1.z,this.direction2.z);r.P.TransformNormalFromFloatsToRef(i,n,s,e,t)}clone(){const e=new h(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return s.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class c{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const s=i.position.subtract(e.getTranslation()).normalize(),a=o.R.RandomRange(0,this.directionRandomizer),l=o.R.RandomRange(0,this.directionRandomizer),h=o.R.RandomRange(0,this.directionRandomizer);s.x+=a,s.y+=l,s.z+=h,s.normalize(),n?t.copyFrom(s):r.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,n){const s=this.radius-o.R.RandomRange(0,this.radius*this.radiusRange),a=o.R.RandomRange(0,1),l=o.R.RandomRange(0,2*Math.PI),h=Math.acos(2*a-1),c=s*Math.cos(l)*Math.sin(h),u=s*Math.cos(h),d=s*Math.sin(l)*Math.sin(h);n?t.copyFromFloats(c,Math.abs(u),d):r.P.TransformCoordinatesFromFloatsToRef(c,Math.abs(u),d,e,t)}clone(){const e=new c(this.radius,this.directionRandomizer);return s.j.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 u{constructor(){this.direction1=new r.P(0,1,0),this.direction2=new r.P(0,1,0)}startDirectionFunction(e,t,i,n){const s=o.R.RandomRange(this.direction1.x,this.direction2.x),a=o.R.RandomRange(this.direction1.y,this.direction2.y),l=o.R.RandomRange(this.direction1.z,this.direction2.z);n?t.copyFromFloats(s,a,l):r.P.TransformNormalFromFloatsToRef(s,a,l,e,t)}startPositionFunction(e,t,i,n){n?t.copyFromFloats(0,0,0):r.P.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new u;return s.j.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){r.P.FromArrayToRef(e.direction1,0,this.direction1),r.P.FromArrayToRef(e.direction2,0,this.direction2)}}class d{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const s=i.position.subtract(e.getTranslation()).normalize(),a=o.R.RandomRange(0,this.directionRandomizer),l=o.R.RandomRange(0,this.directionRandomizer),h=o.R.RandomRange(0,this.directionRandomizer);s.x+=a,s.y+=l,s.z+=h,s.normalize(),n?t.copyFrom(s):r.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,n){const s=this.radius-o.R.RandomRange(0,this.radius*this.radiusRange),a=o.R.RandomRange(0,1),l=o.R.RandomRange(0,2*Math.PI),h=Math.acos(2*a-1),c=s*Math.cos(l)*Math.sin(h),u=s*Math.cos(h),d=s*Math.sin(l)*Math.sin(h);n?t.copyFromFloats(c,u,d):r.P.TransformCoordinatesFromFloatsToRef(c,u,d,e,t)}clone(){const e=new d(this.radius,this.directionRandomizer);return s.j.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 p extends d{constructor(e=1,t=new r.P(0,1,0),i=new r.P(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=o.R.RandomRange(this.direction1.x,this.direction2.x),n=o.R.RandomRange(this.direction1.y,this.direction2.y),s=o.R.RandomRange(this.direction1.z,this.direction2.z);r.P.TransformNormalFromFloatsToRef(i,n,s,e,t)}clone(){const e=new p(this.radius,this.direction1,this.direction2);return s.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}var f=i(5098),_=i(708);class m{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(_.o.PositionKind),this._normals=e.getVerticesData(_.o.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=r.P.Zero(),this._mesh=null,this.direction1=new r.P(0,1,0),this.direction2=new r.P(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,n){if(this.useMeshNormalsForDirection&&this._normals)return void r.P.TransformNormalToRef(this._storedNormal,e,t);const s=o.R.RandomRange(this.direction1.x,this.direction2.x),a=o.R.RandomRange(this.direction1.y,this.direction2.y),l=o.R.RandomRange(this.direction1.z,this.direction2.z);n?t.copyFromFloats(s,a,l):r.P.TransformNormalFromFloatsToRef(s,a,l,e,t)}startPositionFunction(e,t,i,n){if(!this._indices||!this._positions)return;const s=3*Math.random()*(this._indices.length/3)|0,o=Math.random(),a=Math.random()*(1-o),l=1-o-a,h=this._indices[s],c=this._indices[s+1],u=this._indices[s+2],d=r.jp.Vector3[0],p=r.jp.Vector3[1],f=r.jp.Vector3[2],_=r.jp.Vector3[3];r.P.FromArrayToRef(this._positions,3*h,d),r.P.FromArrayToRef(this._positions,3*c,p),r.P.FromArrayToRef(this._positions,3*u,f),_.x=o*d.x+a*p.x+l*f.x,_.y=o*d.y+a*p.y+l*f.y,_.z=o*d.z+a*p.z+l*f.z,n?t.copyFromFloats(_.x,_.y,_.z):r.P.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(r.P.FromArrayToRef(this._normals,3*h,d),r.P.FromArrayToRef(this._normals,3*c,p),r.P.FromArrayToRef(this._normals,3*u,f),this._storedNormal.x=o*d.x+a*p.x+l*f.x,this._storedNormal.y=o*d.y+a*p.y+l*f.y,this._storedNormal.z=o*d.z+a*p.z+l*f.z)}clone(){const e=new m(this.mesh);return s.j.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=null===(e=this.mesh)||void 0===e?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t}parse(e,t){r.P.FromArrayToRef(e.direction1,0,this.direction1),r.P.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}},5753:(e,t,i)=>{i.d(t,{U:()=>a});var n=i(4141),s=i(4475),r=i(5089),o=i(4649);i(3742);class a{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:n.P.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:n.P.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:n.P.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:n.P.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let n=0;for(const i of t){if(i.gradient===e){t.splice(n,1);break}n++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=n.P.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 n.P(10,10,10),this.onAnimationEnd=null,this.blendMode=a.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 n.FM(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new n.P(0,0,0),this._useLogarithmicDepth=!1,this.gravity=n.P.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 o.HE(1,1,1,1),this.color2=new o.HE(1,1,1,1),this.colorDead=new o.HE(0,0,0,1),this.textureMask=new o.HE(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new s.b,this.id=e,this.name=e}createPointEmitter(e,t){const i=new r.cl;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=new r.VD(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=new r.Ai(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new n.P(0,1,0),i=new n.P(0,1,0)){const s=new r.cE(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,n=0){const s=new r.kT(e,t,i,n);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new n.P(0,1,0),o=new n.P(0,1,0)){const a=new r.z(e,t,i,s,o);return this.particleEmitterType=a,a}createConeEmitter(e=1,t=Math.PI/4){const i=new r.LV(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,n){const s=new r.S3;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=n,s}}a.BLENDMODE_ONEONE=0,a.BLENDMODE_STANDARD=1,a.BLENDMODE_ADD=2,a.BLENDMODE_MULTIPLY=3,a.BLENDMODE_MULTIPLYADD=4},4453:(e,t,i)=>{i.d(t,{d:()=>s});var n=i(4141);class s{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=n.P.Zero(),this._hitPointWorld=n.P.Zero(),this._rayFromWorld=n.P.Zero(),this._rayToWorld=n.P.Zero()}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}setHitData(e,t){this._hasHit=!0,this._hitNormalWorld.set(e.x,e.y,e.z),this._hitPointWorld.set(t.x,t.y,t.z)}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=n.P.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=n.P.Zero(),t=n.P.Zero()){this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld.setAll(0),this._hitPointWorld.setAll(0)}}},934:(e,t,i)=>{i.d(t,{T:()=>r});var n=i(4141),s=i(4934);class r{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,s.S)("CannonJSPlugin")}constructor(e,t=r.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 n.P(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 n={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(n),this._physicsPlugin.generateJoint(n)}removeJoint(e,t,i){const n=this._joints.filter((function(n){return n.connectedImpostor===t&&n.joint===i&&n.mainImpostor===e}));n.length&&this._physicsPlugin.removeJoint(n[0])}_step(e){this._impostors.forEach((e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t<this._impostors.length;++t)if(this._impostors[t].object===e)return this._impostors[t];return null}getImpostorWithPhysicsBody(e){for(let t=0;t<this._impostors.length;++t)if(this._impostors[t].physicsBody===e)return this._impostors[t];return null}raycast(e,t){return this._physicsPlugin.raycast(e,t)}raycastToRef(e,t,i){return this._physicsPlugin.raycastToRef(e,t,i)}}},4389:(e,t,i)=>{i.d(t,{Q:()=>c});var n=i(2722),s=i(5860),r=i(4141),o=i(1795),a=i(4496),l=i(58),h=i(5203);a.Kj._PhysicsImpostorParser=function(e,t,i){return new c(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class c{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){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=r.P.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new r._f,this._tmpQuat2=new r._f,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 r._f),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach((e=>{e(this)})))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach((e=>{e(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,c._TmpVecs[0]),this.object.translate(c._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent)return;if(!this._physicsEngine)return;const t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter((e=>-1!==e.otherImpostors.indexOf(t))).forEach((i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)})))},this.object?(this.object.parent&&0!==i.mass&&n.Y.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=r._f.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new r._f),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&n.Y.Warn("You must affect impostors to children before affecting impostor to parent.")):n.Y.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):n.Y.Error("No object was provided. A physics object is obligatory")}_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 o.x?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=c.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const n=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return n.x=Math.abs(n.x),n.y=Math.abs(n.y),n.z=Math.abs(n.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),n}return c.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):r.P.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):r.P.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):n.Y.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):n.Y.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(((e,n)=>{if(e.callback===t&&e.otherImpostors.length===i.length){const t=e.otherImpostors.every((e=>i.indexOf(e)>-1));return t&&(s=n),t}return!1}))?this._onPhysicsCollideCallbacks.splice(s,1):n.Y.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):r._f.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 n=new l.q7(t,i);return this.addJoint(e,n),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,n,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendAnchor(this,e,t,i,n,s),this):this}addHook(e,t,i,n){if(!this._physicsEngine)return this;const s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor?(this._physicsEngine&&s.appendHook(this,e,t,i,n),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 c(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 r._f),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,n,s){const r=c._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(s){const i=c._TmpQuat;o.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,h.T.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,h.T.WORLD,t);r.x=0,r.y=0,r.z=0,i&&(r.x=i.x,r.y=i.y,r.z=i.z,e.getDirectionToRef(r,t,r),null==n&&(n=i.length()),r.x*=n,r.y*=n,r.z*=n),e.getParent()?(r.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(r,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=r.x,t.position.y-=r.y,t.position.z-=r.z)}syncImpostorWithBone(e,t,i,n,s,r){const o=this.object;if(o.rotationQuaternion)if(s){const i=c._TmpQuat;e.getRotationQuaternionToRef(h.T.WORLD,t,i),i.multiplyToRef(s,o.rotationQuaternion)}else e.getRotationQuaternionToRef(h.T.WORLD,t,o.rotationQuaternion);const a=c._TmpVecs[0],l=c._TmpVecs[1];r||((r=c._TmpVecs[2]).x=0,r.y=1,r.z=0),e.getDirectionToRef(r,t,l),e.getAbsolutePositionToRef(t,a),null==n&&i&&(n=i.length()),null!=n&&(a.x+=l.x*n,a.y+=l.y*n,a.z+=l.z*n),o.setAbsolutePosition(a)}}c.DEFAULT_OBJECT_SIZE=new r.P(1,1,1),c.IDENTITY_QUATERNION=r._f.Identity(),c._TmpVecs=s.B.BuildArray(3,r.P.Zero),c._TmpQuat=r._f.Identity(),c.NoImpostor=0,c.SphereImpostor=1,c.BoxImpostor=2,c.PlaneImpostor=3,c.MeshImpostor=4,c.CapsuleImpostor=6,c.CylinderImpostor=7,c.ParticleImpostor=8,c.HeightmapImpostor=9,c.ConvexHullImpostor=10,c.CustomImpostor=100,c.RopeImpostor=101,c.ClothImpostor=102,c.SoftbodyImpostor=103},58:(e,t,i)=>{i.d(t,{$Q:()=>r,OT:()=>a,mN:()=>s,q7:()=>n,yr:()=>o});class n{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)}}n.DistanceJoint=0,n.HingeJoint=1,n.BallAndSocketJoint=2,n.WheelJoint=3,n.SliderJoint=4,n.PrismaticJoint=5,n.UniversalJoint=6,n.Hinge2Joint=n.WheelJoint,n.PointToPointJoint=8,n.SpringJoint=9,n.LockJoint=10;class s extends n{constructor(e){super(n.DistanceJoint,e)}updateDistance(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)}}class r extends n{constructor(e,t){super(e,t)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class o extends r{constructor(e){super(n.HingeJoint,e)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class a extends r{constructor(e){super(n.Hinge2Joint,e)}setMotor(e,t,i=0){this._physicsPlugin.setMotor(this,e||0,t,i)}setLimit(e,t,i=0){this._physicsPlugin.setLimit(this,e,t,i)}}},9525:(e,t,i)=>{i.d(t,{Z:()=>l,Q:()=>a});var n=i(392),s=i(7814);i(7182);i(8104).v.ShadersStore.passCubePixelShader="varying vec2 vUV;\nuniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";var r=i(2208),o=i(3956);class a extends n.D{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,n,s,r,o=0,a=!1){super(e,"pass",null,null,t,i,n,s,r,void 0,o,void 0,null,a)}static _Parse(e,t,i,n){return o.p4.Parse((()=>new a(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,n)}}(0,r.H)("BABYLON.PassPostProcess",a);class l extends n.D{get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ")}}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,n,s,r,o=0,a=!1){super(e,"passCube",null,null,t,i,n,s,r,"#define POSITIVEX",o,void 0,null,a),this._face=0}static _Parse(e,t,i,n){return o.p4.Parse((()=>new l(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,n)}}s.D._RescalePostProcessFactory=e=>new a("rescale",1,null,2,e,!1,0)},392:(e,t,i)=>{i.d(t,{D:()=>d});var n=i(9472),s=i(5363),r=i(5757),o=i(4141),a=(i(8793),i(7814)),l=(i(7246),i(3956)),h=i(2208),c=i(1345),u=i(9131);class d{static RegisterShaderCodeProcessing(e,t){t?d._CustomShaderCodeProcessing[null!=e?e:""]=t:delete d._CustomShaderCodeProcessing[null!=e?e:""]}static _GetShaderCodeProcessing(e){var t;return null!==(t=d._CustomShaderCodeProcessing[e])&&void 0!==t?t:d._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,n,a,l,h=1,d,p,f=null,_=0,m="postprocess",g,v=!1,y=5,x=u.x.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=new Array,this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new s.t(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new o.FM(1,1),this._texelSize=o.FM.Zero(),this.onActivateObservable=new r.y$,this.onSizeChangedObservable=new r.y$,this.onApplyObservable=new r.y$,this.onBeforeRenderObservable=new r.y$,this.onAfterRenderObservable=new r.y$,this.name=e,null!=l?(this._camera=l,this._scene=l.getScene(),l.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):d&&(this._engine=d,this._engine.postProcesses.push(this)),this._options=a,this.renderTargetSamplingMode=h||1,this._reusable=p||!1,this._textureType=_,this._textureFormat=y,this._shaderLanguage=x,this._samplers=n||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=m,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=g,this._drawWrapper=new c.q(this._engine),v||this.updateEffect(f)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new s.t(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,n,s,r,o,a){var l,h;const c=d._GetShaderCodeProcessing(this.name);if(null==c?void 0:c.defineCustomBindings){const n=null!==(l=null==t?void 0:t.slice())&&void 0!==l?l:[];n.push(...this._parameters);const s=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];s.push(...this._samplers),e=c.defineCustomBindings(this.name,e,n,s),t=n,i=s}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=o?o:this._vertexUrl,fragment:null!=a?a:this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:[],samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:null!=s?s:null,onError:null!=r?r:null,indexParameters:n||this._indexParameters,processCodeAfterIncludes:(null==c?void 0:c.processCodeAfterIncludes)?(e,t)=>c.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:(null==c?void 0:c.processFinalCode)?(e,t)=>c.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let n=0;n<this._textureCache.length;n++)if(this._textureCache[n].texture.width===e.width&&this._textureCache[n].texture.height===e.height&&this._textureCache[n].postProcessChannel===i&&this._textureCache[n].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[n].texture.samples===t.samples)return this._textureCache[n].texture;const n=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:n,postProcessChannel:i,lastUsedRenderId:-1}),n}_flushTextureCache(){const e=this._renderId;for(let t=this._textureCache.length-1;t>=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i<this._textures.length;i++)if(this._textures.data[i]===this._textureCache[t].texture){e=!0;break}e||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}}_resize(e,t,i,n,s){this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;let r=null;for(let e=0;e<i._postProcesses.length;e++)if(null!==i._postProcesses[e]){r=i._postProcesses[e];break}const o={width:this.width,height:this.height},a={generateMipMaps:n,generateDepthBuffer:s||r===this,generateStencilBuffer:(s||r===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat,samples:this._samples,label:"PostProcessRTT-"+this.name};this._textures.push(this._createRenderTargetTexture(o,a,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(o,a,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)}activate(e,t=null,i){var n,s;const r=(e=e||this._camera).getScene(),o=r.getEngine(),l=o.getCaps().maxTextureSize;let h=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0;const c=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0,u=e.parent;!u||u.leftCamera!=e&&u.rightCamera!=e||(h/=2);let d=this._options.width||h,p=this._options.height||c;const f=7!==this.renderTargetSamplingMode&&1!==this.renderTargetSamplingMode&&2!==this.renderTargetSamplingMode;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){const e=o.currentViewport;e&&(d*=e.width,p*=e.height)}(f||this.alwaysForcePOT)&&(this._options.width||(d=o.needPOTTextures?a.D.GetExponentOfTwo(d,l,this.scaleMode):d),this._options.height||(p=o.needPOTTextures?a.D.GetExponentOfTwo(p,l,this.scaleMode):p)),this.width===d&&this.height===p||this._resize(d,p,e,f,i),this._textures.forEach((e=>{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}let _;if(this._shareOutputWithPostProcess)_=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)_=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let e;_=this.inputTexture;for(let t=0;t<this._textureCache.length;t++)if(this._textureCache[t].texture===_){e=this._textureCache[t];break}e&&(e.lastUsedRenderId=this._renderId)}return this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(h/d,c/p),this._engine.bindFramebuffer(_,0,h,c,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(_,0,void 0,void 0,this.forceFullscreenViewport)),null===(s=(n=this._engine)._debugInsertMarker)||void 0===s||s.call(n,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:r.clearColor,r._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),_}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 null!==(t=null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}apply(){var e,t,i;if(!(null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady()))return null;let n;return 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),n=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",null==n?void 0:n.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),null===(i=null===(t=d._GetShaderCodeProcessing(this.name))||void 0===t?void 0:t.bindCustomBindings)||void 0===i||i.call(t,this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(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)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=l.p4.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=d.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const n=(0,h.q)(e.customType);if(!n||!n._Parse)return null;const s=t?t.getCameraById(e.cameraId):null;return n._Parse(e,s,t,i)}static _Parse(e,t,i,n){return l.p4.Parse((()=>new d(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,i,n)}}d._CustomShaderCodeProcessing={},(0,n.gn)([(0,l.qC)()],d.prototype,"uniqueId",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"name",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"width",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"height",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"renderTargetSamplingMode",void 0),(0,n.gn)([(0,l.XX)()],d.prototype,"clearColor",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"autoClear",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"forceAutoClearInAlphaMode",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"alphaMode",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"alphaConstants",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"enablePixelPerfectMode",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"forceFullscreenViewport",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"scaleMode",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"alwaysForcePOT",void 0),(0,n.gn)([(0,l.qC)("samples")],d.prototype,"_samples",void 0),(0,n.gn)([(0,l.qC)()],d.prototype,"adaptScaleToCurrentViewport",void 0),(0,h.H)("BABYLON.PostProcess",d)},727:(e,t,i)=>{i.d(t,{O:()=>s});var n=i(708);class s{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[n.o.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[n.o.PositionKind]=new n.o(this._scene.getEngine(),e,n.o.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[n.o.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))}directRender(e,t=null,i=!1,n=0,s=0,r=!1){var o;const a=this._scene.getEngine();for(let l=0;l<e.length;l++){l<e.length-1?e[l+1].activate(this._scene.activeCamera,null==t?void 0:t.texture):(t?a.bindFramebuffer(t,n,void 0,void 0,i,s):r||a.restoreDefaultFramebuffer(),null===(o=a._debugInsertMarker)||void 0===o||o.call(a,`post process ${e[l].name} output`));const h=e[l],c=h.apply();c&&(h.onBeforeRenderObservable.notifyObservers(c),this._prepareBuffers(),a.bindBuffers(this._vertexBuffers,this._indexBuffer,c),a.drawElementsType(0,0,6),h.onAfterRenderObservable.notifyObservers(c))}a.setDepthBuffer(!0),a.setDepthWrite(!0)}_finalizeFrame(e,t,i,n,s=!1){var r;const o=this._scene.activeCamera;if(!o)return;if(0===(n=n||o._postProcesses.filter((e=>null!=e))).length||!this._scene.postProcessesEnabled)return;const a=this._scene.getEngine();for(let l=0,h=n.length;l<h;l++){const c=n[l];if(l<h-1?c._outputTexture=n[l+1].activate(o,null==t?void 0:t.texture):(t?(a.bindFramebuffer(t,i,void 0,void 0,s),c._outputTexture=t):(a.restoreDefaultFramebuffer(),c._outputTexture=null),null===(r=a._debugInsertMarker)||void 0===r||r.call(a,`post process ${n[l].name} output`)),e)break;const u=c.apply();u&&(c.onBeforeRenderObservable.notifyObservers(u),this._prepareBuffers(),a.bindBuffers(this._vertexBuffers,this._indexBuffer,u),a.drawElementsType(0,0,6),c.onAfterRenderObservable.notifyObservers(u))}a.setDepthBuffer(!0),a.setDepthWrite(!0),a.setAlphaMode(0)}dispose(){const e=this._vertexBuffers[n.o.PositionKind];e&&(e.dispose(),this._vertexBuffers[n.o.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}}},1617:(e,t,i)=>{i.d(t,{S:()=>r});var n=i(5363),s=i(4141);class r{set opaqueSortCompareFn(e){this._opaqueSortCompareFn=e||r.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){this._alphaTestSortCompareFn=e||r.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){this._transparentSortCompareFn=e||r.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,s=null,r=null){this.index=e,this._opaqueSubMeshes=new n.t(256),this._transparentSubMeshes=new n.t(256),this._alphaTestSubMeshes=new n.t(256),this._depthOnlySubMeshes=new n.t(256),this._particleSystems=new n.t(256),this._spriteManagers=new n.t(256),this._empty=!0,this._edgesRenderers=new n.f(16),this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=s,this.transparentSortCompareFn=r}render(e,t,i,n){if(e)return void e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);const s=this._scene.getEngine();0!==this._depthOnlySubMeshes.length&&(s.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),s.setColorWrite(!0)),0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);const r=s.getStencilBuffer();if(s.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(n),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),0!==this._transparentSubMeshes.length||this._scene.useOrderIndependentTransparency){if(s.setStencilBuffer(r),this._scene.useOrderIndependentTransparency){const e=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);e.length&&this._renderTransparent(e)}else this._renderTransparent(this._transparentSubMeshes);s.setAlphaMode(0)}if(s.setStencilBuffer(!1),this._edgesRenderers.length){for(let e=0;e<this._edgesRenderers.length;e++)this._edgesRenderers.data[e].render();s.setAlphaMode(0)}s.setStencilBuffer(r)}_renderOpaqueSorted(e){return r._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1)}_renderAlphaTestSorted(e){return r._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)}_renderTransparentSorted(e){return r._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0)}static _RenderSorted(e,t,i,n){let o,a=0;const l=i?i.globalPosition:r._ZeroVector;if(n)for(;a<e.length;a++)o=e.data[a],o._alphaIndex=o.getMesh().alphaIndex,o._distanceToCamera=s.P.Distance(o.getBoundingInfo().boundingSphere.centerWorld,l);const h=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&h.sort(t);const c=h[0].getMesh().getScene();for(a=0;a<h.length;a++)if(o=h[a],!c._activeMeshesFrozenButKeepClipping||o.isInFrustum(c._frustumPlanes)){if(n){const e=o.getMaterial();if(e&&e.needDepthPrePass){const t=e.getScene().getEngine();t.setColorWrite(!1),t.setAlphaMode(0),o.render(!1),t.setColorWrite(!0)}}o.render(n)}}static defaultTransparentSortCompare(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:r.backToFrontSortCompare(e,t)}static backToFrontSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),n=t.getMesh();return i.material&&n.material?i.material.uniqueId-n.material.uniqueId:i.uniqueId-n.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i<this._particleSystems.length;i++){const n=this._particleSystems.data[i];if(0===(t&&t.layerMask&n.layerMask))continue;const s=n.emitter;s.position&&e&&-1===e.indexOf(s)||this._scene._activeParticles.addCount(n.render(),!1)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}_renderSprites(){if(!this._scene.spritesEnabled||0===this._spriteManagers.length)return;const e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(let t=0;t<this._spriteManagers.length;t++){const i=this._spriteManagers.data[t];0!==(e&&e.layerMask&i.layerMask)&&i.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}}r._ZeroVector=s.P.Zero()},4221:(e,t,i)=>{i.d(t,{$:()=>r,t:()=>s});var n=i(1617);class s{}class r{get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){if(e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,!this._maintainStateBetweenFrames)){for(const e of this._scene.meshes)if(e.subMeshes)for(const t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(const e of this._scene.spriteManagers)e._wasDispatched=!1;for(const e of this._scene.particleSystems)e._wasDispatched=!1}}constructor(e){this._useSceneAutoClearSetup=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new s,this._maintainStateBetweenFrames=!1,this._scene=e;for(let e=r.MIN_RENDERINGGROUPS;e<r.MAX_RENDERINGGROUPS;e++)this._autoClearDepthStencil[e]={autoClear:!0,depth:!0,stencil:!0}}getRenderingGroup(e){const t=e||0;return this._prepareRenderingGroup(t),this._renderingGroups[t]}_clearDepthStencilBuffer(e=!0,t=!0){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)}render(e,t,i,n){const s=this._renderingGroupInfo;if(s.scene=this._scene,s.camera=this._scene.activeCamera,this._scene.spriteManagers&&n)for(let e=0;e<this._scene.spriteManagers.length;e++){const t=this._scene.spriteManagers[e];this.dispatchSprites(t)}for(let o=r.MIN_RENDERINGGROUPS;o<r.MAX_RENDERINGGROUPS;o++){this._depthStencilBufferAlreadyCleaned=o===r.MIN_RENDERINGGROUPS;const a=this._renderingGroups[o];if(!a||a._empty)continue;const l=Math.pow(2,o);if(s.renderingGroupId=o,this._scene.onBeforeRenderingGroupObservable.notifyObservers(s,l),r.AUTOCLEAR){const e=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(o):this._autoClearDepthStencil[o];e&&e.autoClear&&this._clearDepthStencilBuffer(e.depth,e.stencil)}for(const e of this._scene._beforeRenderingGroupDrawStage)e.action(o);a.render(e,n,i,t);for(const e of this._scene._afterRenderingGroupDrawStage)e.action(o);this._scene.onAfterRenderingGroupObservable.notifyObservers(s,l)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=r.MIN_RENDERINGGROUPS;e<r.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=r.MIN_RENDERINGGROUPS;e<r.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepareSprites()}}dispose(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null}freeRenderingGroups(){for(let e=r.MIN_RENDERINGGROUPS;e<r.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){void 0===this._renderingGroups[e]&&(this._renderingGroups[e]=new n.S(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]))}dispatchSprites(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e))}dispatchParticles(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e))}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,i))}setRenderingOrder(e,t=null,i=null,n=null){if(this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=n,this._renderingGroups[e]){const t=this._renderingGroups[e];t.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],t.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],t.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}}setRenderingAutoClearDepthStencil(e,t,i=!0,n=!0){this._autoClearDepthStencil[e]={autoClear:t,depth:i,stencil:n}}getAutoClearDepthStencilSetup(e){return this._autoClearDepthStencil[e]}}r.MAX_RENDERINGGROUPS=4,r.MIN_RENDERINGGROUPS=0,r.AUTOCLEAR=!0},9803:(e,t,i)=>{i.d(t,{x:()=>u});var n=i(1057),s=i(5757),r=i(1903),o=i(5670),a=i(1431),l=i(7616),h=i(4141),c=i(4649);class u{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new l.e("shared gizmo light",new h.P(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=c.Wo.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==u._DefaultUtilityLayer?u._CreateDefaultUtilityLayerFromScene(a.l.LastCreatedScene):u._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return u._DefaultUtilityLayer=new u(e),u._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{u._DefaultUtilityLayer=null})),u._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==u._DefaultKeepDepthUtilityLayer&&(u._DefaultKeepDepthUtilityLayer=new u(a.l.LastCreatedScene),u._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,u._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{u._DefaultKeepDepthUtilityLayer=null}))),u._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 s.y$,this.utilityLayerScene=new n.x(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==r.kD.POINTERMOVE&&t.type!==r.kD.POINTERUP&&t.type!==r.kD.POINTERDOWN&&t.type!==r.kD.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const n=i=>{let n=null;if(t.nearInteractionPickingInfo)n=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new o.p;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)n=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),n=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return n},s=n(this.utilityLayerScene);if(!t.ray&&s&&(t.ray=s.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=r.kD.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new r.R5(t.type,t.event,s),t.type),void(t.type===r.kD.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)s&&s.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new r.R5(t.type,t.event,s),t.type),t.skipOnPointerObservable=!0);else{const i=n(e),o=t.event;i&&s&&(0===s.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,o),t.skipOnPointerObservable=!0):t.type===r.kD.POINTERDOWN?this._pointerCaptures[o.pointerId]=!0:t.type!==r.kD.POINTERMOVE&&t.type!==r.kD.POINTERUP||(this._lastPointerEvents[o.pointerId]&&(this.onPointerOutObservable.notifyObservers(o.pointerId),delete this._lastPointerEvents[o.pointerId]),this._notifyObservers(t,i,o)):!this._pointerCaptures[o.pointerId]&&(s.distance<i.distance||0===i.distance)?(this._notifyObservers(t,s,o),t.skipOnPointerObservable||(t.skipOnPointerObservable=s.distance>0)):!this._pointerCaptures[o.pointerId]&&s.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,o),t.skipOnPointerObservable=!0):(t.type!==r.kD.POINTERMOVE&&t.type!==r.kD.POINTERUP||this._lastPointerEvents[o.pointerId]&&(this.onPointerOutObservable.notifyObservers(o.pointerId),delete this._lastPointerEvents[o.pointerId]),this._notifyObservers(t,s,o))),t.type===r.kD.POINTERUP&&this._pointerCaptures[o.pointerId]&&(this._pointerCaptures[o.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((()=>{this.dispose()})),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new r.R5(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()}}u._DefaultUtilityLayer=null,u._DefaultKeepDepthUtilityLayer=null},3206:(e,t,i)=>{i(8104).v.IncludesShadersStore.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\n#define BVASNAME bakedVertexAnimationSettingsInstanced\n#else\n#define BVASNAME bakedVertexAnimationSettings\n#endif\nfloat VATStartFrame=BVASNAME.x;\nfloat VATEndFrame=BVASNAME.y;\nfloat VATOffsetFrame=BVASNAME.z;\nfloat VATSpeed=BVASNAME.w;\nfloat totalFrames=VATEndFrame-VATStartFrame+1.0;\nfloat time=bakedVertexAnimationTime*VATSpeed/totalFrames;\nfloat frameCorrection=time<1.0 ? 0.0 : 1.0;\nfloat numOfFrames=totalFrames-frameCorrection;\nfloat VATFrameNum=fract(time)*numOfFrames;\nVATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);\nVATFrameNum=floor(VATFrameNum);\nVATFrameNum+=VATStartFrame+frameCorrection;\nmat4 VATInfluence;\nVATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;\n}\n#endif\n"},493:(e,t,i)=>{i(8104).v.IncludesShadersStore.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform float bakedVertexAnimationTime;\nuniform vec2 bakedVertexAnimationTextureSizeInverted;\nuniform vec4 bakedVertexAnimationSettings;\nuniform sampler2D bakedVertexAnimationTexture;\n#ifdef INSTANCES\nattribute vec4 bakedVertexAnimationSettingsInstanced;\n#endif\n#define inline\nmat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)\n{\nfloat offset=index*4.0;\nfloat frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;\nfloat dx=bakedVertexAnimationTextureSizeInverted.x;\nvec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));\nvec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));\nvec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));\nvec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));\nreturn mat4(m0,m1,m2,m3);\n}\n#endif\n"},7520:(e,t,i)=>{i(8104).v.IncludesShadersStore.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nuniform sampler2D boneSampler;\nuniform float boneTextureWidth;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#ifdef BONES_VELOCITY_ENABLED\nuniform mat4 mPreviousBones[BonesPerMesh];\n#endif\n#endif\n#ifdef BONETEXTURE\n#define inline\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{\nfloat offset=index *4.0;\nfloat dx=1.0/boneTextureWidth;\nvec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));\nvec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));\nvec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));\nvec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));\nreturn mat4(m0,m1,m2,m3);\n}\n#endif\n#endif\n#endif\n"},6655:(e,t,i)=>{i(8104).v.IncludesShadersStore.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];\n#endif\n#else\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n"},2321:(e,t,i)=>{i(8104).v.IncludesShadersStore.bumpFragment="vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#elif defined(BUMP)\nfloat normalScale=vBumpInfos.y;\n#else\nfloat normalScale=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#elif defined(BUMP)\nvec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);\n#else\nvec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nvec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;\nmat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);\nvec2 detailNormalRG=detailColor.wy*2.0-1.0;\nfloat detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));\nvec3 detailNormal=vec3(detailNormalRG,detailNormalB);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);\n#else\nvec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal.xy*=vDetailInfos.z;\nvec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal.xy*=vDetailInfos.z;\nbumpNormal+=vec3(0.0,0.0,1.0);\ndetailNormal*=vec3(-1.0,-1.0,1.0);\nvec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal.xy*=vDetailInfos.z;\nnormalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);\n#endif\n"},7441:(e,t,i)=>{var n=i(8104);i(1015);n.v.IncludesShadersStore.bumpFragmentFunctions="#if defined(BUMP)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nbool keepWorking=true;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;\nif (!keepWorking)\n{\n}\nelse if (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\nkeepWorking=false;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n"},8882:(e,t,i)=>{i(8104).v.IncludesShadersStore.bumpFragmentMainFunctions="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#if defined(WEBGL2) || defined(WEBGPU)\nmat4 toNormalMatrix(mat4 wMatrix)\n{\nmat4 ret=inverse(wMatrix);\nret=transpose(ret);\nret[0][3]=0.;\nret[1][3]=0.;\nret[2][3]=0.;\nret[3]=vec4(0.,0.,0.,1.);\nreturn ret;\n}\n#else\nmat4 toNormalMatrix(mat4 m)\n{\nfloat\na00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],\na10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],\na20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],\na30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],\nb00=a00*a11-a01*a10,\nb01=a00*a12-a02*a10,\nb02=a00*a13-a03*a10,\nb03=a01*a12-a02*a11,\nb04=a01*a13-a03*a11,\nb05=a02*a13-a03*a12,\nb06=a20*a31-a21*a30,\nb07=a20*a32-a22*a30,\nb08=a20*a33-a23*a30,\nb09=a21*a32-a22*a31,\nb10=a21*a33-a23*a31,\nb11=a22*a33-a23*a32,\ndet=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;\nmat4 mi=mat4(\na11*b11-a12*b10+a13*b09,\na02*b10-a01*b11-a03*b09,\na31*b05-a32*b04+a33*b03,\na22*b04-a21*b05-a23*b03,\na12*b08-a10*b11-a13*b07,\na00*b11-a02*b08+a03*b07,\na32*b02-a30*b05-a33*b01,\na20*b05-a22*b02+a23*b01,\na10*b10-a11*b08+a13*b06,\na01*b08-a00*b10-a03*b06,\na30*b04-a31*b02+a33*b00,\na21*b02-a20*b04-a23*b00,\na11*b07-a10*b09-a12*b06,\na00*b09-a01*b07+a02*b06,\na31*b01-a30*b03-a32*b00,\na20*b03-a21*b01+a22*b00)/det;\nreturn mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);\n}\n#endif\n#endif\nvec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)\n{\n#ifdef NORMALXYSCALE\nnormal=normalize(normal*vec3(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)\n{\nreturn perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);\n}\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)\n{\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\ntangent*=tangentSpaceParams.x;\nbitangent*=tangentSpaceParams.y;\nfloat det=max(dot(tangent,tangent),dot(bitangent,bitangent));\nfloat invmax=det==0.0 ? 0.0 : inversesqrt(det);\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\n#endif\n"},6255:(e,t,i)=>{i(8104).v.IncludesShadersStore.bumpVertex="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif\n"},2838:(e,t,i)=>{i(8104).v.IncludesShadersStore.bumpVertexDeclaration="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n"},5791:(e,t,i)=>{i(8104).v.IncludesShadersStore.clipPlaneFragment="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nelse if (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nelse if (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nelse if (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE5\nelse if (fClipDistance5>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE6\nelse if (fClipDistance6>0.0)\n{\ndiscard;\n}\n#endif\n"},6390:(e,t,i)=>{i(8104).v.IncludesShadersStore.clipPlaneFragmentDeclaration="#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nvarying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nvarying float fClipDistance6;\n#endif\n"},5215:(e,t,i)=>{i(8104).v.IncludesShadersStore.clipPlaneVertex="#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nfClipDistance5=dot(worldPos,vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nfClipDistance6=dot(worldPos,vClipPlane6);\n#endif\n"},6343:(e,t,i)=>{i(8104).v.IncludesShadersStore.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;\nvarying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;\nvarying float fClipDistance6;\n#endif\n"},8074:(e,t,i)=>{i(8104).v.IncludesShadersStore.decalFragment="#ifdef DECAL\n#ifdef GAMMADECAL\ndecalColor.rgb=toLinearSpace(decalColor.rgb);\n#endif\n#ifdef DECAL_SMOOTHALPHA\ndecalColor.a*=decalColor.a;\n#endif\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a);\n#endif\n"},3055:(e,t,i)=>{i(8104).v.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n"},5613:(e,t,i)=>{i(8104).v.IncludesShadersStore.decalVertexDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\nuniform mat4 decalMatrix;\n#endif\n"},783:(e,t,i)=>{i(8104).v.IncludesShadersStore.depthPrePass="#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif\n"},6043:(e,t,i)=>{i(8104).v.IncludesShadersStore.fogFragment="#ifdef FOG\nfloat fog=CalcFogFactor();\n#ifdef PBR\nfog=toLinearSpace(fog);\n#endif\ncolor.rgb=mix(vFogColor,color.rgb,fog);\n#endif\n"},9519:(e,t,i)=>{i(8104).v.IncludesShadersStore.fogFragmentDeclaration="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR==vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP==vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2==vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif\n"},962:(e,t,i)=>{i(8104).v.IncludesShadersStore.fogVertex="#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif\n"},9042:(e,t,i)=>{i(8104).v.IncludesShadersStore.fogVertexDeclaration="#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n"},8491:(e,t,i)=>{i(8104).v.IncludesShadersStore.fresnelFunction="#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif\n"},4115:(e,t,i)=>{i(8104).v.IncludesShadersStore.hdrFilteringFunctions="#ifdef NUM_SAMPLES\n#if NUM_SAMPLES>0\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfloat radicalInverse_VdC(uint bits) \n{\nbits=(bits<<16u) | (bits>>16u);\nbits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);\nbits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);\nbits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);\nbits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);\nreturn float(bits)*2.3283064365386963e-10; \n}\nvec2 hammersley(uint i,uint N)\n{\nreturn vec2(float(i)/float(N),radicalInverse_VdC(i));\n}\n#else\nfloat vanDerCorpus(int n,int base)\n{\nfloat invBase=1.0/float(base);\nfloat denom =1.0;\nfloat result =0.0;\nfor(int i=0; i<32; ++i)\n{\nif(n>0)\n{\ndenom =mod(float(n),2.0);\nresult+=denom*invBase;\ninvBase=invBase/2.0;\nn =int(float(n)/2.0);\n}\n}\nreturn result;\n}\nvec2 hammersley(int i,int N)\n{\nreturn vec2(float(i)/float(N),vanDerCorpus(i,2));\n}\n#endif\nfloat log4(float x) {\nreturn log2(x)/2.;\n}\nconst float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);\nconst float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;\nconst float K=4.;\n#define inline\nvec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\n{\nvec3 n=normalize(inputN);\nvec3 result=vec3(0.0);\nvec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);\ntangent=normalize(cross(tangent,n));\nvec3 bitangent=cross(n,tangent);\nmat3 tbn=mat3(tangent,bitangent,n);\nfloat maxLevel=filteringInfo.y;\nfloat dim0=filteringInfo.x;\nfloat omegaP=(4.*PI)/(6.*dim0*dim0);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(uint i=0u; i<NUM_SAMPLES; ++i)\n#else\nfor(int i=0; i<NUM_SAMPLES; ++i)\n#endif\n{\nvec2 Xi=hammersley(i,NUM_SAMPLES);\nvec3 Ls=hemisphereCosSample(Xi);\nLs=normalize(Ls);\nvec3 Ns=vec3(0.,0.,1.);\nfloat NoL=dot(Ns,Ls);\nif (NoL>0.) {\nfloat pdf_inversed=PI/NoL;\nfloat omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;\nfloat l=log4(omegaS)-log4(omegaP)+log4(K);\nfloat mipLevel=clamp(l,0.0,maxLevel);\nvec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c;\n}\n}\nresult=result*NUM_SAMPLES_FLOAT_INVERSED;\nreturn result;\n}\n#define inline\nvec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\n{\nvec3 n=normalize(inputN);\nif (alphaG==0.) {\nvec3 c=textureCube(inputTexture,n).rgb;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nreturn c;\n} else {\nvec3 result=vec3(0.);\nvec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);\ntangent=normalize(cross(tangent,n));\nvec3 bitangent=cross(n,tangent);\nmat3 tbn=mat3(tangent,bitangent,n);\nfloat maxLevel=filteringInfo.y;\nfloat dim0=filteringInfo.x;\nfloat omegaP=(4.*PI)/(6.*dim0*dim0);\nfloat weight=0.;\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(uint i=0u; i<NUM_SAMPLES; ++i)\n#else\nfor(int i=0; i<NUM_SAMPLES; ++i)\n#endif\n{\nvec2 Xi=hammersley(i,NUM_SAMPLES);\nvec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);\nfloat NoV=1.;\nfloat NoH=H.z;\nfloat NoH2=H.z*H.z;\nfloat NoL=2.*NoH2-1.;\nvec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);\nL=normalize(L);\nif (NoL>0.) {\nfloat pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);\nfloat omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;\nfloat l=log4(omegaS)-log4(omegaP)+log4(K);\nfloat mipLevel=clamp(float(l),0.0,maxLevel);\nweight+=NoL;\nvec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c*NoL;\n}\n}\nresult=result/weight;\nreturn result;\n}\n}\n#endif\n#endif\n"},1423:(e,t,i)=>{i(8104).v.IncludesShadersStore.helperFunctions="const float PI=3.1415926535897932384626433832795;\nconst float HALF_MIN=5.96046448e-08; \nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nconst float Epsilon=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{\nvec3 nearZeroSection=0.0773993808*color;\nvec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{\nvec3 nearZeroSection=12.92*color;\nvec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;\nfloat remainingSection=pow(0.947867299*(color+0.055),2.4);\nreturn color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;\nfloat remainingSection=1.055*pow(color,0.41666)-0.055;\nreturn color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nvec3 square(vec3 value)\n{\nreturn value*value;\n}\nfloat pow5(float value) {\nfloat sq=value*value;\nreturn sq*sq*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat normVariance=varianceAmount/255.0;\nfloat dither=mix(-normVariance,normVariance,rand);\nreturn dither;\n}\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=maxEps(max(color.r,max(color.g,color.b)));\nfloat D =max(rgbdMaxRange/maxRGB,1.);\nD =clamp(floor(D)/255.0,0.,1.);\nvec3 rgb=color.rgb*D;\nrgb=toGammaSpace(rgb);\nreturn vec4(clamp(rgb,0.,1.),D); \n}\nvec3 fromRGBD(vec4 rgbd) {\nrgbd.rgb=toLinearSpace(rgbd.rgb);\nreturn rgbd.rgb/rgbd.a;\n}\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\nvec3 intersectPositionWS=vertexPos+origVec*distance;\nreturn intersectPositionWS-cubePos;\n}\n"},689:(e,t,i)=>{i(8104).v.IncludesShadersStore.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n"},5141:(e,t,i)=>{i(8104).v.IncludesShadersStore.imageProcessingDeclaration="#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#if defined(VIGNETTE) || defined(DITHER)\nuniform vec2 vInverseScreenSize;\n#endif\n#ifdef VIGNETTE\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef DITHER\nuniform float ditherIntensity;\n#endif\n"},3660:(e,t,i)=>{i(8104).v.IncludesShadersStore.imageProcessingFunctions="#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n/** \n* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL.\n* sampler3dSetting.x=textureOffset (0.5/textureSize).\n* sampler3dSetting.y=textureSize.\n*/\n#define inline\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=saturate(sliceUV);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=saturate(sliceUV);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108, 1.10813,-0.07276),\nvec3(-0.07367,-0.00605, 1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\ncolor=saturate(color);\nreturn color;\n}\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS\nvec4 applyImageProcessing(vec4 result) {\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=saturate(result.rgb);\n#ifdef CONTRAST\nvec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);\nif (contrast<1.0) {\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\n#ifdef DITHER\nfloat rand=getRand(gl_FragCoord.xy*vInverseScreenSize);\nfloat dither=mix(-ditherIntensity,ditherIntensity,rand);\nresult.rgb=saturate(result.rgb+vec3(dither));\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND\nreturn result;\n}"},3897:(e,t,i)=>{i(8104).v.IncludesShadersStore.importanceSampling="vec3 hemisphereCosSample(vec2 u) {\nfloat phi=2.*PI*u.x;\nfloat cosTheta2=1.-u.y;\nfloat cosTheta=sqrt(cosTheta2);\nfloat sinTheta=sqrt(1.-cosTheta2);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {\nfloat phi=2.*PI*u.x;\nfloat cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));\nfloat cosTheta=sqrt(cosTheta2);\nfloat sinTheta=sqrt(1.-cosTheta2);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;\nfloat sinTheta=pow(u.y,a/(2.*a+1.));\nfloat cosTheta=sqrt(1.-sinTheta*sinTheta);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}"},1063:(e,t,i)=>{i(8104).v.IncludesShadersStore.instancesDeclaration="#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#ifdef INSTANCESCOLOR\nattribute vec4 instanceColor;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute vec4 previousWorld0;\nattribute vec4 previousWorld1;\nattribute vec4 previousWorld2;\nattribute vec4 previousWorld3;\n#ifdef THIN_INSTANCES\nuniform mat4 previousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform mat4 previousWorld;\n#endif\n#endif\n"},6883:(e,t,i)=>{i(8104).v.IncludesShadersStore.instancesVertex="#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nmat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\nfinalWorld=world*finalWorld;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\nmat4 finalWorld=world;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nmat4 finalPreviousWorld=previousWorld;\n#endif\n#endif\n"},9490:(e,t,i)=>{i(8104).v.IncludesShadersStore.lightFragment="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\npreInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\npreInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\npreInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\npreInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);\ninfo.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nfor (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) \n{\n#ifdef SHADOWCSM_RIGHTHANDED{X}\ndiff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z;\n#else\ndiff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z;\n#endif\nif (diff{X}>=0.) {\nindex{X}=i;\nbreak;\n}\n}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nfloat frustumLength=frustumLengths{X}[index{X}];\nfloat diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};\nif (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{\nindex{X}+=1;\nfloat nextShadow=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n"},2557:(e,t,i)=>{i(8104).v.IncludesShadersStore.lightFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float cascadeBlendFactor{X};\nvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\nuniform highp sampler2DArray depthSampler{X};\nuniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);\nvec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif\n"},3756:(e,t,i)=>{i(8104).v.IncludesShadersStore.lightUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float cascadeBlendFactor{X};\nvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\nuniform highp sampler2DArray depthSampler{X};\nuniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);\nvec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n"},1542:(e,t,i)=>{i(8104).v.IncludesShadersStore.lightVxFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromCamera{X};\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#endif\n"},9935:(e,t,i)=>{i(8104).v.IncludesShadersStore.lightVxUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromCamera{X};\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n"},6568:(e,t,i)=>{i(8104).v.IncludesShadersStore.lightsFragmentFunctions="struct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w==0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}"},1030:(e,t,i)=>{i(8104).v.IncludesShadersStore.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif\n"},8773:(e,t,i)=>{i(8104).v.IncludesShadersStore.logDepthFragment="#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif\n"},5501:(e,t,i)=>{i(8104).v.IncludesShadersStore.logDepthVertex="#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif\n"},6637:(e,t,i)=>{i(8104).v.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n"},4804:(e,t,i)=>{i(8104).v.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;\nuniform float visibility;\n#else\nlayout(std140,column_major) uniform;\nuniform Mesh\n{\nmat4 world;\nfloat visibility;\n};\n#endif\n#define WORLD_UBO\n"},9085:(e,t,i)=>{i(8104).v.IncludesShadersStore.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE \nvertexID=float(gl_VertexID)*morphTargetTextureInfo.x;\npositionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];\nvertexID+=1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(readVector3FromRawSampler({X},vertexID) -normal)*morphTargetInfluences[{X}];\nvertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];\nvertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID) -tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#else\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n"},8073:(e,t,i)=>{i(8104).v.IncludesShadersStore.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#ifdef MORPHTARGETS_UV\nattribute vec2 uv_{X};\n#endif\n#endif\n#endif\n"},6757:(e,t,i)=>{i(8104).v.IncludesShadersStore.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nfloat vertexID;\n#endif\n#endif\n"},9901:(e,t,i)=>{i(8104).v.IncludesShadersStore.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#ifdef MORPHTARGETS_TEXTURE \nprecision mediump sampler2DArray; \nuniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];\nuniform vec3 morphTargetTextureInfo;\nuniform sampler2DArray morphTargets;\nvec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)\n{ \nfloat y=floor(vertexIndex/morphTargetTextureInfo.y);\nfloat x=vertexIndex-y*morphTargetTextureInfo.y;\nvec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);\nreturn texture(morphTargets,textureUV).xyz;\n}\n#endif\n#endif\n"},1868:(e,t,i)=>{i(8104).v.IncludesShadersStore.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;\nlayout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;\nuniform sampler2D oitDepthSampler;\nuniform sampler2D oitFrontColorSampler;\n#endif\n"},4643:(e,t,i)=>{i(8104).v.IncludesShadersStore.oitFragment="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\nfloat fragDepth=gl_FragCoord.z; \n#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS\nuint halfFloat=packHalf2x16(vec2(fragDepth));\nvec2 full=unpackHalf2x16(halfFloat);\nfragDepth=full.x;\n#endif\nivec2 fragCoord=ivec2(gl_FragCoord.xy);\nvec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;\nvec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);\ndepth.rg=vec2(-MAX_DEPTH);\nfrontColor=lastFrontColor;\nbackColor=vec4(0.0);\n#ifdef USE_REVERSE_DEPTHBUFFER\nfloat furthestDepth=-lastDepth.x;\nfloat nearestDepth=lastDepth.y;\n#else\nfloat nearestDepth=-lastDepth.x;\nfloat furthestDepth=lastDepth.y;\n#endif\nfloat alphaMultiplier=1.0-lastFrontColor.a;\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth>nearestDepth || fragDepth<furthestDepth) {\n#else\nif (fragDepth<nearestDepth || fragDepth>furthestDepth) {\n#endif\nreturn;\n}\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth<nearestDepth && fragDepth>furthestDepth) {\n#else\nif (fragDepth>nearestDepth && fragDepth<furthestDepth) {\n#endif\ndepth.rg=vec2(-fragDepth,fragDepth);\nreturn;\n}\n#endif\n"},3154:(e,t,i)=>{i(8104).v.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\nreturn 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);\n}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {\nvec2 UV=vec2(NdotV,perceptualRoughness);\nvec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;\n}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;\n}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;\n}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{\nfloat c=1.0-NdotV;\nfloat c3=c*c*c;\nreturn 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));\n}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\n}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {\nvec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;\nreturn sheenEnvironmentReflectance;\n}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\n#ifdef CLEARCOAT\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);\nvec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);\nreturn square(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst mat3 XYZ_TO_REC709=mat3(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);\nvec3 getIORTfromAirToSurfaceR0(vec3 f0) {\nvec3 sqrtF0=sqrt(f0);\nreturn (1.+sqrtF0)/(1.-sqrtF0);\n}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {\nreturn square((iorT-vec3(iorI))/(iorT+vec3(iorI)));\n}\nfloat getR0fromIORs(float iorT,float iorI) {\nreturn square((iorT-iorI)/(iorT+iorI));\n}\nvec3 evalSensitivity(float opd,vec3 shift) {\nfloat phase=2.0*PI*opd*1.0e-9;\nconst vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);\nconst vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);\nconst vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);\nvec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);\nxyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));\nxyz/=1.0685e-7;\nvec3 srgb=XYZ_TO_REC709*xyz;\nreturn srgb;\n}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {\nvec3 I=vec3(1.0);\nfloat iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));\nfloat sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));\nfloat cosTheta2Sq=1.0-sinTheta2Sq;\nif (cosTheta2Sq<0.0) {\nreturn I;\n}\nfloat cosTheta2=sqrt(cosTheta2Sq);\nfloat R0=getR0fromIORs(iridescenceIOR,outsideIOR);\nfloat R12=fresnelSchlickGGX(cosTheta1,R0,1.);\nfloat R21=R12;\nfloat T121=1.0-R12;\nfloat phi12=0.0;\nif (iridescenceIOR<outsideIOR) phi12=PI;\nfloat phi21=PI-phi12;\nvec3 baseIOR=getIORTfromAirToSurfaceR0(clamp(baseF0,0.0,0.9999)); \nvec3 R1=getR0fromIORs(baseIOR,iridescenceIOR);\nvec3 R23=fresnelSchlickGGX(cosTheta2,R1,vec3(1.));\nvec3 phi23=vec3(0.0);\nif (baseIOR[0]<iridescenceIOR) phi23[0]=PI;\nif (baseIOR[1]<iridescenceIOR) phi23[1]=PI;\nif (baseIOR[2]<iridescenceIOR) phi23[2]=PI;\nfloat opd=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;\nvec3 phi=vec3(phi21)+phi23;\nvec3 R123=clamp(R12*R23,1e-5,0.9999);\nvec3 r123=sqrt(R123);\nvec3 Rs=square(T121)*R23/(vec3(1.0)-R123);\nvec3 C0=R12+Rs;\nI=C0;\nvec3 Cm=Rs-T121;\nfor (int m=1; m<=2; ++m)\n{\nCm*=r123;\nvec3 Sm=2.0*evalSensitivity(float(m)*opd,float(m)*phi);\nI+=Cm*Sm;\n}\nreturn max(I,vec3(0.0));\n}\n#endif\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\n#ifdef SHEEN\nfloat normalDistributionFunction_CharlieSheen(float NdotH,float alphaG)\n{\nfloat invR=1./alphaG;\nfloat cos2h=NdotH*NdotH;\nfloat sin2h=1.-cos2h;\nreturn (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);\n}\n#endif\n#ifdef ANISOTROPIC\nfloat normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {\nfloat a2=alphaTB.x*alphaTB.y;\nvec3 v=vec3(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);\nfloat v2=dot(v,v);\nfloat w2=a2/v2;\nreturn a2*w2*w2*RECIPROCAL_PI;\n}\n#endif\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) {\n#ifdef MOBILE\nfloat GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);\nfloat GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);\nreturn 0.5/(GGXV+GGXL);\n#else\nfloat a2=alphaG*alphaG;\nfloat GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);\nfloat GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);\nreturn 0.5/(GGXV+GGXL);\n#endif\n}\n#else\nfloat smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG)\n{\n#ifdef MOBILE\nreturn 1.0/(dot+alphaG+(1.0-alphaG)*dot ));\n#else\nfloat alphaSquared=alphaG*alphaG;\nreturn 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));\n#endif\n}\nfloat smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG)\n{\nfloat visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);\nreturn visibility;\n}\n#endif\n#ifdef ANISOTROPIC\nfloat smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {\nfloat lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));\nfloat lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));\nfloat v=0.5/(lambdaV+lambdaL);\nreturn v;\n}\n#endif\n#ifdef CLEARCOAT\nfloat visibility_Kelemen(float VdotH) {\nreturn 0.25/(VdotH*VdotH); \n}\n#endif\n#ifdef SHEEN\nfloat visibility_Ashikhmin(float NdotL,float NdotV)\n{\nreturn 1./(4.*(NdotL+NdotV-NdotL*NdotV));\n}\n/* NOT USED\n#ifdef SHEEN_SOFTER\nfloat l(float x,float alphaG)\n{\nfloat oneMinusAlphaSq=(1.0-alphaG)*(1.0-alphaG);\nfloat a=mix(21.5473,25.3245,oneMinusAlphaSq);\nfloat b=mix(3.82987,3.32435,oneMinusAlphaSq);\nfloat c=mix(0.19823,0.16801,oneMinusAlphaSq);\nfloat d=mix(-1.97760,-1.27393,oneMinusAlphaSq);\nfloat e=mix(-4.32054,-4.85967,oneMinusAlphaSq);\nreturn a/(1.0+b*pow(x,c))+d*x+e;\n}\nfloat lambdaSheen(float cosTheta,float alphaG)\n{\nreturn abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));\n}\nfloat visibility_CharlieSheen(float NdotL,float NdotV,float alphaG)\n{\nfloat G=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));\nreturn G/(4.0*NdotV*NdotL);\n}\n#endif\n*/\n#endif\nfloat diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {\nfloat diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));\nfloat diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel/PI;\n}\n#ifdef SS_TRANSLUCENCY\nvec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {\nvec3 S=1./maxEps(diffusionDistance);\nvec3 temp=exp((-0.333333333*thickness)*S);\nreturn tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);\n}\nfloat computeWrappedDiffuseNdotL(float NdotL,float w) {\nfloat t=1.0+w;\nfloat invt2=1.0/square(t);\nreturn saturate((NdotL+w)*invt2);\n}\n#endif\n"},8190:(e,t,i)=>{i(8104).v.IncludesShadersStore.prePassDeclaration="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n"},8741:(e,t,i)=>{i(8104).v.IncludesShadersStore.prePassVertex="#ifdef PREPASS_DEPTH\nvViewPos=(view*worldPos).rgb;\n#endif\n#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*worldPos;\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;\npreviousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n"},7019:(e,t,i)=>{i(8104).v.IncludesShadersStore.prePassVertexDeclaration="#ifdef PREPASS\n#ifdef PREPASS_DEPTH\nvarying vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nuniform mat4 previousViewProjection;\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#endif\n"},2132:(e,t,i)=>{i(8104).v.IncludesShadersStore.reflectionFunction="vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y;\nreturn vec3(s,t,0); \n}\nvec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y;\nreturn vec3(1.0-s,t,0); \n}\nvec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{\nvec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nr=vec3(reflectionMatrix*vec4(r,0));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y;\nreturn vec3(s,t,0);\n}\nvec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)\n{\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr=vec3(reflectionMatrix*vec4(r,0));\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n}\nvec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{\nvec3 viewDir=worldPos.xyz-eyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n}\nvec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{\nvec3 viewDir=normalize(worldPos.xyz-eyePosition);\nvec3 coords=reflect(viewDir,worldNormal);\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n}\nvec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)\n{\nvec3 viewDir=normalize(worldPos.xyz-eyePosition);\nvec3 coords=reflect(viewDir,worldNormal);\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n}\nvec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)\n{\nreturn vec3(reflectionMatrix*(view*worldPos));\n}\nvec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)\n{\nreturn vec3(reflectionMatrix*vec4(positionW,1.));\n}\n#ifdef REFLECTION\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nreturn computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nreturn computeFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nreturn computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nreturn computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nreturn computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nreturn computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);\n#else\nreturn computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn computeProjectionCoords(worldPos,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn computeSkyBoxCoords(vPositionUVW,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\n"},1015:(e,t,i)=>{i(8104).v.IncludesShadersStore.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\nuniform sampler2D _SAMPLERNAME_Sampler;\n#endif\n"},9478:(e,t,i)=>{i(8104).v.IncludesShadersStore.samplerVertexDeclaration="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n"},2508:(e,t,i)=>{i(8104).v.IncludesShadersStore.samplerVertexImplementation="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nif (v_INFONAME_==0.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));\n}\n#ifdef UV2\nelse if (v_INFONAME_==1.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef UV3\nelse if (v_INFONAME_==2.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));\n}\n#endif\n#ifdef UV4\nelse if (v_INFONAME_==3.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));\n}\n#endif\n#ifdef UV5\nelse if (v_INFONAME_==4.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));\n}\n#endif\n#ifdef UV6\nelse if (v_INFONAME_==5.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));\n}\n#endif\n#endif\n"},2963:(e,t,i)=>{i(8104).v.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;\nuniform Scene {\nmat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;\nmat4 projection;\nvec4 vEyePosition;\n};\n"},3996:(e,t,i)=>{i(8104).v.IncludesShadersStore.shadowsFragmentFunctions="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\n#define inline\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;\n}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#define inline\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\n#define inline\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define inline\nfloat computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nvec3 uvLayer=vec3(uv.x,uv.y,layer);\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uvLayer));\n#else\nfloat shadow=texture2D(shadowSampler,uvLayer).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;\n}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;\n}\n}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;\n#else\nif (TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;\nif (TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;\nif (TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;\nif (TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#define inline\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\nfloat shadow=texture2D(shadowSampler,uvDepthLayer);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nfloat shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);\nshadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);\nshadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);\nshadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);\nshadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);\nshadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);\nshadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\nfloat AAOffset=shadowMapSizeInverse*10.;\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);\nvec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec4 offset=vec4(poissonSamplers[i],0.);\noffset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);\nshadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\nshadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));\nshadow=mix(darkness,1.,shadow);\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nelse\n{\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#define inline\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=TEXTUREFUNC(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0.).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nelse\n{\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\nfloat AAOffset=shadowMapSizeInverse*10.;\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=TEXTUREFUNC(shadowSampler,uvDepth+offset*filterRadius,0.);\n}\nshadow/=float(pcfTapCount);\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n}\n#define inline\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\n#define inline\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\n#define inline\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#define inline\nfloat computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{\nreturn computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);\n}\n#define inline\nfloat computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{\nreturn computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);\n}\n#define inline\nfloat computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{\nreturn computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);\n}\n#endif\n#endif\n"},1101:(e,t,i)=>{i(8104).v.IncludesShadersStore.shadowsVertex="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvPositionFromCamera{X}=view*worldPos;\nfor (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {\nvPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n}\n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#endif\n"},4022:(e,t,i)=>{i(8104).v.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{\nreturn diffusionProfile<1.;\n}"},6467:(e,t,i)=>{i(8104).v.IncludesShadersStore.uvAttributeDeclaration="#ifdef UV{X}\nattribute vec2 uv{X};\n#endif\n"},3088:(e,t,i)=>{i(8104).v.IncludesShadersStore.uvVariableDeclaration="#if !defined(UV{X}) && defined(MAINUV{X})\nvec2 uv{X}=vec2(0.,0.);\n#endif\n#ifdef MAINUV{X}\nvMainUV{X}=uv{X};\n#endif\n"},9025:(e,t,i)=>{i(8104).v.IncludesShadersStore.vertexColorMixing="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvColor=vec4(1.0);\n#ifdef VERTEXCOLOR\n#ifdef VERTEXALPHA\nvColor*=color;\n#else\nvColor.rgb*=color.rgb;\n#endif\n#endif\n#ifdef INSTANCESCOLOR\nvColor*=instanceColor;\n#endif\n#endif\n"},6980:(e,t,i)=>{var n=i(8104);i(6390),i(5791);n.v.ShadersStore.colorPixelShader="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}"},9753:(e,t,i)=>{var n=i(8104);i(7520),i(493),i(6343),i(1063),i(6883),i(6655),i(3206),i(5215),i(9025);n.v.ShadersStore.colorVertexShader="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include<clipPlaneVertex>\n#include<vertexColorMixing>\n#define CUSTOM_VERTEX_MAIN_END\n}"},7182:(e,t,i)=>{i.d(t,{T:()=>r});const n="passPixelShader",s="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}";i(8104).v.ShadersStore[n]=s;const r={name:n,shader:s}},8793:(e,t,i)=>{i(8104).v.ShadersStore.postprocessVertexShader="attribute vec2 position;\nuniform vec2 scale;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}"},7161:(e,t,i)=>{var n=i(8104);i(1423);n.v.ShadersStore.rgbdDecodePixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}"},4710:(e,t,i)=>{i.d(t,{Q:()=>n});class n{constructor(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,n){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===n||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=n,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,n){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===n||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=n,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}},6533:(e,t,i)=>{i.d(t,{k:()=>n});class n{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}},8657:(e,t,i)=>{i.d(t,{s:()=>n});class n{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=n.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=n.KEEP,this.opDepthFail=n.KEEP,this.opStencilDepthPass=n.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}n.ALWAYS=519,n.KEEP=7680,n.REPLACE=7681},9468:(e,t,i)=>{i.d(t,{C:()=>n});class n{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,null===(e=this.stencilGlobal)||void 0===e||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&&!!(null===(t=this.stencilMaterial)||void 0===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))}}},2844:(e,t,i)=>{i.d(t,{F:()=>n});class n{constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName=""}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach((e=>{e.observable.remove(e.observer)})),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0}isCompatible(){return!0}_addNewAttachObserver(e,t){this._removeOnDetach.push({observable:e,observer:e.add(t)})}}},9596:(e,t,i)=>{i.d(t,{OF:()=>n,e0:()=>x,en:()=>b,fL:()=>s});var n,s,r=i(2844),o=i(4370),a=i(4141),l=i(4389),h=i(5757),c=i(9953),u=i(4649),d=i(4834),p=i(7104),f=i(6272),_=i(4674),m=i(5203),g=i(1431);!function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(n||(n={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(s||(s={}));const v=[s.WRIST,s.THUMB_METACARPAL,s.THUMB_PHALANX_PROXIMAL,s.THUMB_PHALANX_DISTAL,s.THUMB_TIP,s.INDEX_FINGER_METACARPAL,s.INDEX_FINGER_PHALANX_PROXIMAL,s.INDEX_FINGER_PHALANX_INTERMEDIATE,s.INDEX_FINGER_PHALANX_DISTAL,s.INDEX_FINGER_TIP,s.MIDDLE_FINGER_METACARPAL,s.MIDDLE_FINGER_PHALANX_PROXIMAL,s.MIDDLE_FINGER_PHALANX_INTERMEDIATE,s.MIDDLE_FINGER_PHALANX_DISTAL,s.MIDDLE_FINGER_TIP,s.RING_FINGER_METACARPAL,s.RING_FINGER_PHALANX_PROXIMAL,s.RING_FINGER_PHALANX_INTERMEDIATE,s.RING_FINGER_PHALANX_DISTAL,s.RING_FINGER_TIP,s.PINKY_FINGER_METACARPAL,s.PINKY_FINGER_PHALANX_PROXIMAL,s.PINKY_FINGER_PHALANX_INTERMEDIATE,s.PINKY_FINGER_PHALANX_DISTAL,s.PINKY_FINGER_TIP],y={[n.WRIST]:[s.WRIST],[n.THUMB]:[s.THUMB_METACARPAL,s.THUMB_PHALANX_PROXIMAL,s.THUMB_PHALANX_DISTAL,s.THUMB_TIP],[n.INDEX]:[s.INDEX_FINGER_METACARPAL,s.INDEX_FINGER_PHALANX_PROXIMAL,s.INDEX_FINGER_PHALANX_INTERMEDIATE,s.INDEX_FINGER_PHALANX_DISTAL,s.INDEX_FINGER_TIP],[n.MIDDLE]:[s.MIDDLE_FINGER_METACARPAL,s.MIDDLE_FINGER_PHALANX_PROXIMAL,s.MIDDLE_FINGER_PHALANX_INTERMEDIATE,s.MIDDLE_FINGER_PHALANX_DISTAL,s.MIDDLE_FINGER_TIP],[n.RING]:[s.RING_FINGER_METACARPAL,s.RING_FINGER_PHALANX_PROXIMAL,s.RING_FINGER_PHALANX_INTERMEDIATE,s.RING_FINGER_PHALANX_DISTAL,s.RING_FINGER_TIP],[n.LITTLE]:[s.PINKY_FINGER_METACARPAL,s.PINKY_FINGER_PHALANX_PROXIMAL,s.PINKY_FINGER_PHALANX_INTERMEDIATE,s.PINKY_FINGER_PHALANX_DISTAL,s.PINKY_FINGER_TIP]};class x{get handMesh(){return this._handMesh}getHandPartMeshes(e){return y[e].map((e=>this._jointMeshes[v.indexOf(e)]))}getJointMesh(e){return this._jointMeshes[v.indexOf(e)]}constructor(e,t,i,n,s=!1,r=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=n,this._leftHandedMeshes=s,this._jointsInvisible=r,this._jointScaleFactor=o,this._jointTransforms=new Array(v.length),this._jointTransformMatrices=new Float32Array(16*v.length),this._tempJointMatrix=new a.y3,this._jointRadii=new Float32Array(v.length),this._scene=t[0].getScene();for(let e=0;e<this._jointTransforms.length;e++)(this._jointTransforms[e]=new _.Y(v[e],this._scene)).rotationQuaternion=new a._f,t[e].rotationQuaternion=new a._f;i&&this.setHandMesh(i,n),this.xrController.motionController&&(this.xrController.motionController.rootMesh?this.xrController.motionController.rootMesh.setEnabled(!1):this.xrController.motionController.onModelLoadedObservable.add((e=>{e.rootMesh&&e.rootMesh.setEnabled(!1)}))),this.xrController.onMotionControllerInitObservable.add((e=>{e.onModelLoadedObservable.add((e=>{e.rootMesh&&e.rootMesh.setEnabled(!1)})),e.rootMesh&&e.rootMesh.setEnabled(!1)}))}setHandMesh(e,t){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((e=>e.alwaysSelectAsActiveMesh=!0)),this._handMesh.skeleton){const e=this._handMesh.skeleton;v.forEach(((i,n)=>{const s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[n])}))}}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const n=i,s=v.map((e=>n[e]||i.get(e)));let r=!1;if(e.fillPoses&&e.fillJointRadii)r=e.fillPoses(s,t,this._jointTransformMatrices)&&e.fillJointRadii(s,this._jointRadii);else if(e.getJointPose){r=!0;for(let i=0;i<s.length;i++){const n=e.getJointPose(s[i],t);if(!n){r=!1;break}this._jointTransformMatrices.set(n.transform.matrix,16*i),this._jointRadii[i]=n.radius||.008}}r&&(v.forEach(((e,t)=>{const i=this._jointTransforms[t];a.y3.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);const n=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(n),this._scene.useRightHandedSystem||(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(){this._handMesh&&(this._handMesh.isVisible=!1)}}class b extends r.F{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map((i=>{var n,s,r,o,h;const c=[],u=(null===(n=e.jointMeshes)||void 0===n?void 0:n.sourceMesh)||(0,f.Au)("jointParent",b._ICOSPHERE_PARAMS);u.isVisible=!!(null===(s=e.jointMeshes)||void 0===s?void 0:s.keepOriginalVisible);for(let t=0;t<v.length;++t){let n=u.createInstance(`${i}-handJoint-${t}`);if(null===(r=e.jointMeshes)||void 0===r?void 0:r.onHandJointMeshGenerated){const s=e.jointMeshes.onHandJointMeshGenerated(n,t,i);s&&s!==n&&(n.dispose(),n=s)}if(n.isPickable=!1,null===(o=e.jointMeshes)||void 0===o?void 0:o.enablePhysics){const t=(null===(h=e.jointMeshes)||void 0===h?void 0:h.physicsProps)||{};n.scaling.setAll(.02);const i=void 0!==t.impostorType?t.impostorType:l.Q.SphereImpostor;n.physicsImpostor=new l.Q(n,i,{mass:0,...t})}n.rotationQuaternion=new a._f,n.isVisible=!1,c.push(n)}t[i]=c})),{left:t.left,right:t.right}}static _GenerateDefaultHandMeshesAsync(e,t){return new Promise((async i=>{var n,s,r,o,a;const l={};(null===(s=null===(n=b._RightHandGLB)||void 0===n?void 0:n.meshes[1])||void 0===s?void 0:s.isDisposed())&&(b._RightHandGLB=null),(null===(o=null===(r=b._LeftHandGLB)||void 0===r?void 0:r.meshes[1])||void 0===o?void 0:o.isDisposed())&&(b._LeftHandGLB=null);const h=!(!b._RightHandGLB||!b._LeftHandGLB),f=await Promise.all([b._RightHandGLB||c.n.ImportMeshAsync("",b.DEFAULT_HAND_MODEL_BASE_URL,b.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),b._LeftHandGLB||c.n.ImportMeshAsync("",b.DEFAULT_HAND_MODEL_BASE_URL,b.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);b._RightHandGLB=f[0],b._LeftHandGLB=f[1];const _=new d.O("handShader",e,{emitComments:!1});await _.loadAsync(b.DEFAULT_HAND_MODEL_SHADER_URL),_.needDepthPrePass=!0,_.transparencyMode=p.F.MATERIAL_ALPHABLEND,_.alphaMode=2,_.build(!1);const g={base:u.Wo.FromInts(116,63,203),fresnel:u.Wo.FromInts(149,102,229),fingerColor:u.Wo.FromInts(177,130,255),tipFresnel:u.Wo.FromInts(220,200,255),...null===(a=null==t?void 0:t.handMeshes)||void 0===a?void 0:a.customColors},v={base:_.getBlockByName("baseColor"),fresnel:_.getBlockByName("fresnelColor"),fingerColor:_.getBlockByName("fingerColor"),tipFresnel:_.getBlockByName("tipFresnelColor")};v.base.value=g.base,v.fresnel.value=g.fresnel,v.fingerColor.value=g.fingerColor,v.tipFresnel.value=g.tipFresnel,["left","right"].forEach((t=>{const i="left"==t?b._LeftHandGLB:b._RightHandGLB;if(!i)throw new Error("Could not load hand model");const n=i.meshes[1];n._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,n.material=_.clone(`${t}HandShaderClone`,!0),n.isVisible=!1,l[t]=n,h||e.useRightHandedSystem||i.meshes[1].rotate(m.RD.Y,Math.PI)})),_.dispose(),i({left:l.left,right:l.right})}))}static _GenerateDefaultHandMeshRigMapping(e){const t="right"==e?"R":"L";return{[s.WRIST]:`wrist_${t}`,[s.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[s.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[s.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[s.THUMB_TIP]:`thumb_tip_${t}`,[s.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[s.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[s.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[s.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[s.INDEX_FINGER_TIP]:`index_tip_${t}`,[s.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[s.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[s.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[s.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[s.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[s.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[s.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[s.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[s.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[s.RING_FINGER_TIP]:`ring_tip_${t}`,[s.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[s.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[s.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[s.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[s.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?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 h.y$,this.onHandRemovedObservable=new h.y$,this._attachHand=e=>{var t,i,n;if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;const s=e.inputSource.handedness,r=new x(e,this._handResources.jointMeshes[s],this._handResources.handMeshes&&this._handResources.handMeshes[s],this._handResources.rigMappings&&this._handResources.rigMappings[s],null===(t=this.options.handMeshes)||void 0===t?void 0:t.meshesUseLeftHandedCoordinates,null===(i=this.options.jointMeshes)||void 0===i?void 0:i.invisible,null===(n=this.options.jointMeshes)||void 0===n?void 0:n.scaleFactor);this._attachedHands[e.uniqueId]=r,this._trackingHands[s]=r,this.onHandAddedObservable.notifyObservers(r)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";const i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};const e={},n={};[[i.rigMapping.left,e],[i.rigMapping.right,n]].forEach((e=>{const t=e[0],i=e[1];t.forEach(((e,t)=>{i[v[t]]=e}))})),t.handMeshes.customRigMappings={left:e,right:n}}}attach(){var e,t,i,n;return!!super.attach()&&(this._handResources={jointMeshes:b._GenerateTrackedJointMeshes(this.options),handMeshes:(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)||null,rigMappings:(null===(t=this.options.handMeshes)||void 0===t?void 0:t.customRigMappings)||null},(null===(i=this.options.handMeshes)||void 0===i?void 0:i.customMeshes)||(null===(n=this.options.handMeshes)||void 0===n?void 0:n.disableDefaultMeshes)||b._GenerateDefaultHandMeshesAsync(g.l.LastCreatedScene,this.options).then((e=>{var t,i;this._handResources.handMeshes=e,this._handResources.rigMappings={left:b._GenerateDefaultHandMeshRigMapping("left"),right:b._GenerateDefaultHandMeshRigMapping("right")},null===(t=this._trackingHands.left)||void 0===t||t.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left),null===(i=this._trackingHands.right)||void 0===i||i.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)}_onXRFrame(e){var t,i;null===(t=this._trackingHands.left)||void 0===t||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),null===(i=this._trackingHands.right)||void 0===i||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e){var t;const i=this.getHandByControllerId(e);if(i){const n="left"==i.xrController.inputSource.handedness?"left":"right";(null===(t=this._trackingHands[n])||void 0===t?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[n]=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)}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),b._RightHandGLB=null,b._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())))}}b.Name=o.b.HAND_TRACKING,b.Version=1,b.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",b.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",b.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",b.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",b._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},b._RightHandGLB=null,b._LeftHandGLB=null,o.d.AddWebXRFeature(b.Name,((e,t)=>()=>new b(e,t)),b.Version,!1)},4370:(e,t,i)=>{i.d(t,{b:()=>s,d:()=>r});var n=i(7257);class s{}s.ANCHOR_SYSTEM="xr-anchor-system",s.BACKGROUND_REMOVER="xr-background-remover",s.HIT_TEST="xr-hit-test",s.MESH_DETECTION="xr-mesh-detection",s.PHYSICS_CONTROLLERS="xr-physics-controller",s.PLANE_DETECTION="xr-plane-detection",s.POINTER_SELECTION="xr-controller-pointer-selection",s.TELEPORTATION="xr-controller-teleportation",s.FEATURE_POINTS="xr-feature-points",s.HAND_TRACKING="xr-hand-tracking",s.IMAGE_TRACKING="xr-image-tracking",s.NEAR_INTERACTION="xr-near-interaction",s.DOM_OVERLAY="xr-dom-overlay",s.MOVEMENT="xr-controller-movement",s.LIGHT_ESTIMATION="xr-light-estimation",s.EYE_TRACKING="xr-eye-tracking",s.WALKING_LOCOMOTION="xr-walking-locomotion",s.LAYERS="xr-layers",s.DEPTH_SENSING="xr-depth-sensing";class r{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,n=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),n&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,n){const s=this._AvailableFeatures[e][t];if(!s)throw new Error("feature not found");return s(i,n)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()}disableFeature(e){const t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled||(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],0))}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},s=!0,o=!0){const a="string"==typeof e?e:e.Name;let l=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${a} (${t})`);if(l="stable"===t?r.GetStableVersionOfFeature(a):"latest"===t?r.GetLatestVersionOfFeature(a):+t,-1===l||isNaN(l))throw new Error(`feature not found - ${a} (${t})`)}else l=t;const h=r._ConflictingFeatures[a];if(void 0!==h&&-1!==this.getEnabledFeatures().indexOf(h))throw new Error(`Feature ${a} cannot be enabled while ${h} is enabled.`);const c=this._features[a],u=r.ConstructFeature(a,l,this._xrSessionManager,i);if(!u)throw new Error(`feature not found - ${a}`);c&&this.disableFeature(a);const d=u();if(d.dependsOn){const e=d.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${d.dependsOn.join(", ")}`)}if(d.isCompatible())return this._features[a]={featureImplementation:d,enabled:!0,version:l,required:o},s?this._xrSessionManager.session&&!this._features[a].featureImplementation.attached&&this.attachFeature(a):this._features[a].featureImplementation.disableAutoAttach=!0,this._features[a].featureImplementation;if(o)throw new Error("required feature not compatible");return n.w1.Warn(`Feature ${a} not compatible with the current environment/browser and was not enabled.`),d}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const t=this._features[i],n=t.featureImplementation.xrNativeFeatureName;if(n&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(n)&&e.requiredFeatures.push(n)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(n)&&e.optionalFeatures.push(n))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e={...e,...i}}}return e}}r._AvailableFeatures={},r._ConflictingFeatures={[s.TELEPORTATION]:s.MOVEMENT,[s.MOVEMENT]:s.TELEPORTATION}},5655:(e,t,i)=>{i.d(t,{p:()=>n});class n{constructor(){this.rootNodes=new Array,this.cameras=new Array,this.lights=new Array,this.meshes=new Array,this.skeletons=new Array,this.particleSystems=new Array,this.animations=[],this.animationGroups=new Array,this.multiMaterials=new Array,this.materials=new Array,this.morphTargetManagers=new Array,this.geometries=new Array,this.transformNodes=new Array,this.actionManagers=new Array,this.textures=new Array,this._environmentTexture=null,this.postProcesses=new Array}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,n){for(const s in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,s)&&this._BabylonFileParsers[s](e,t,i,n)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=new Array;return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}n._BabylonFileParsers={},n._IndividualBabylonFileParsers={}},1468:(e,t,i)=>{i.d(t,{TJ:()=>f,fD:()=>d,ve:()=>p});var n=i(5655),s=i(4496),r=i(4674),o=i(2722),a=i(1431),l=i(7338),h=i(9311),c=i(2704),u=i(7257);class d extends n.p{}class p{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 f extends n.p{constructor(e){super(),this._wasAddedToScene=!1,(e=e||a.l.LastCreatedScene)&&(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 e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const n of e){const e=n.uniqueId,s=i.dependsOn.get(e);if(n instanceof l.S){const r=n.sourceMesh;t.has(r.uniqueId)&&(s.add(r.uniqueId),i.dependedBy.get(r.uniqueId).add(e))}const r=i.dependedBy.get(e);for(const s of n.getDescendants()){const n=s.uniqueId;t.has(n)&&(r.add(n),i.dependsOn.get(n).add(e))}}const n=[],s=[];for(const n of e){const e=n.uniqueId;0===i.dependsOn.get(e).size&&(s.push(n),t.delete(e))}const r=s;for(;r.length>0;){const e=r.shift();n.push(e);const s=i.dependedBy.get(e.uniqueId);for(const n of Array.from(s.values())){const s=i.dependsOn.get(n);s.delete(e.uniqueId),0===s.size&&t.get(n)&&(r.push(t.get(n)),t.delete(n))}}return t.size>0&&(console.error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>console.error(e.name)))),n}_addNodeAndDescendantsToList(e,t,i,n){if(i&&(!n||n(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const s of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,s,n)}}_isNodeInContainer(e){return e instanceof s.Kj&&-1!==this.meshes.indexOf(e)||e instanceof r.Y&&-1!==this.transformNodes.indexOf(e)||e instanceof h._&&-1!==this.lights.indexOf(e)||e instanceof c.V&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return o.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return o.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return o.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return o.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||u.w1.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const n={},r={},o=new p,a=[],l=[],h={doNotInstantiate:!0,...i},c=[],d=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(c,d,e,h.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(c,d,e,h.predicate);const f=this._topologicalSort(c),_=(i,a)=>{if(((t,i)=>{if(n[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof s.Kj){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;t<i.numTargets;t++){const s=i.getTarget(t),o=e.morphTargetManager.getTarget(t);n[s.uniqueId]=o.uniqueId,r[o.uniqueId]=o}}}})(i,a),i.parent){const e=n[i.parent.uniqueId],t=r[e];a.parent=t||i.parent}if(a.position&&i.position&&a.position.copyFrom(i.position),a.rotationQuaternion&&i.rotationQuaternion&&a.rotationQuaternion.copyFrom(i.rotationQuaternion),a.rotation&&i.rotation&&a.rotation.copyFrom(i.rotation),a.scaling&&i.scaling&&a.scaling.copyFrom(i.scaling),a.material){const s=a;if(s.material)if(t){const t=i.material;if(-1===l.indexOf(t)){let i=t.clone(e?e(t.name):"Clone of "+t.name);if(l.push(t),n[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,"MultiMaterial"===t.getClassName()){const s=t;for(const t of s.subMaterials)t&&(i=t.clone(e?e(t.name):"Clone of "+t.name),l.push(t),n[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i);s.subMaterials=s.subMaterials.map((e=>e&&r[n[e.uniqueId]]))}}"InstancedMesh"!==s.getClassName()&&(s.material=r[n[t.uniqueId]])}else"MultiMaterial"===s.material.getClassName()?-1===this.scene.multiMaterials.indexOf(s.material)&&this.scene.addMultiMaterial(s.material):-1===this.scene.materials.indexOf(s.material)&&this.scene.addMaterial(s.material)}null===a.parent&&o.rootNodes.push(a)};return f.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,s=n[i.uniqueId],o=("number"==typeof s?r[s]:i).createInstance(t.name);_(t,o)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||0===e.getTotalVertices()?t=!1:h.doNotInstantiate&&(t="function"==typeof h.doNotInstantiate?!h.doNotInstantiate(e):!h.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);_(e,i)}})),this.skeletons.forEach((t=>{if(h.predicate&&!h.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=r[n[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==a.indexOf(i))continue;a.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=r[n[e._linkedTransformNode.uniqueId]])}o.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(h.predicate&&!h.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>r[n[e.uniqueId]]||e));o.animationGroups.push(i)})),o}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||u.w1.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){this.cameras.forEach((t=>{e&&!e(t)||this.scene.addCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.addLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.addMesh(t)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.addTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}))}removeAllFromScene(){this._isValidHierarchy()||u.w1.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)})),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 n of e){let e=!0;if(i)for(const t of i)if(n===t){e=!1;break}e&&(t.push(n),n._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new d);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new s.Kj("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=a.l.LastCreatedScene,t,i=null){if(!e)return o.Y.Error("No scene available to merge animations to"),[];const n=i||(t=>{let i=null;const n=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(n){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i});this.getNodes().forEach((e=>{const t=n(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const s=new Array;return this.animationGroups.slice().forEach((e=>{s.push(e.clone(e.name,n)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=n(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),s}}},8099:(e,t,i)=>{i.r(t),i.d(t,{AbstractActionManager:()=>s.O,AbstractAssetTask:()=>Fg,AbstractMesh:()=>Un.x,AbstractScene:()=>n.p,AcquireNativeObjectAsync:()=>Ks,Action:()=>h,ActionEvent:()=>c.V,ActionManager:()=>R,AddBlock:()=>Xu,AddressMode:()=>ur,AdvancedTimer:()=>zl,AlphaState:()=>Og.Q,AmmoJSPlugin:()=>Vh,AnaglyphArcRotateCamera:()=>ai,AnaglyphFreeCamera:()=>li,AnaglyphGamepadCamera:()=>hi,AnaglyphPostProcess:()=>ri,AnaglyphUniversalCamera:()=>ci,Analyser:()=>pe,AndOrNotEvaluator:()=>Ng.q,Angle:()=>Gr.RZ,Animatable:()=>W,AnimatedInputBlockTypes:()=>Wu.c,Animation:()=>D.f,AnimationEvent:()=>re.O,AnimationGroup:()=>oe.O,AnimationKeyInterpolation:()=>ae.N,AnimationPropertiesOverride:()=>H,AnimationRange:()=>le.X,AnisotropyBlock:()=>Ud,ApplyPostProcess:()=>ro.$0,Arc2:()=>Gr.Q,ArcFollowCamera:()=>Gt,ArcRotateCamera:()=>Ft,ArcRotateCameraGamepadInput:()=>nt,ArcRotateCameraInputsManager:()=>ut,ArcRotateCameraKeyboardMoveInput:()=>rt,ArcRotateCameraMouseWheelInput:()=>ht,ArcRotateCameraPointersInput:()=>ct,ArcRotateCameraVRDeviceOrientationInput:()=>dt,ArcTan2Block:()=>xd,AssetContainer:()=>ce.TJ,AssetTaskState:()=>Dg,AssetsManager:()=>jg,AssetsProgressEvent:()=>Lg,AsyncLoop:()=>de.$g,AttachToBoxBehavior:()=>Ne,AudioEngine:()=>_e,AudioSceneComponent:()=>ye,AutoLayoutMode:()=>Tr,AutoReleaseWorkerPool:()=>cl.v,AutoRotationBehavior:()=>Ie,AxesViewer:()=>Hn,Axis:()=>Gr.RD,AxisDragGizmo:()=>Wn,AxisScaleGizmo:()=>ca,BRDFTextureTools:()=>Bd.D,BabylonFileLoaderConfiguration:()=>zh,BackEase:()=>q,BackgroundMaterial:()=>Wa,BakedVertexAnimationManager:()=>Se,BallAndSocketConstraint:()=>U_,BaseCameraMouseWheelInput:()=>Qe.Y,BaseCameraPointersInput:()=>Ze,BaseError:()=>Hs.GU,BaseParticleSystem:()=>Wf.U,BaseSixDofDragBehavior:()=>ke.N,BaseTexture:()=>Oa.V,BasisTools:()=>zc,BasisToolsOptions:()=>Nc,BasisTranscodeConfiguration:()=>Oc,BezierCurve:()=>Gr.hr,BezierCurveEase:()=>se,BiPlanarBlock:()=>sp,BinaryFileAssetTask:()=>kg,BlackAndWhitePostProcess:()=>om,BlendFactor:()=>Pr,BlendOperation:()=>Rr,BloomEffect:()=>cm,BloomMergePostProcess:()=>hm,BlurPostProcess:()=>wa,Bone:()=>z.N,BoneAxesViewer:()=>Xn,BoneIKController:()=>He,BoneLookController:()=>je,BonesBlock:()=>_u,BounceEase:()=>K,BouncingBehavior:()=>De,BoundingBox:()=>On.k,BoundingBoxGizmo:()=>da,BoundingBoxRenderer:()=>$m,BoundingInfo:()=>wn.j,BoundingSphere:()=>Nn.K,BoxBuilder:()=>Yn.kg,BoxParticleEmitter:()=>Hf.S3,Buffer:()=>qe.l,BufferBindingType:()=>mr,BufferMapState:()=>nr,BufferUsage:()=>sr,CSG:()=>Lp,Camera:()=>Mt.V,CameraGizmo:()=>Da,CameraInputTypes:()=>Je.u,CameraInputsManager:()=>Je.p,CannonJSPlugin:()=>Bh,CanvasAlphaMode:()=>Ur,CapsuleBuilder:()=>es,CascadedShadowGenerator:()=>Th,ChromaticAberrationPostProcess:()=>um,CircleEase:()=>Y,CircleOfConfusionPostProcess:()=>dm,ClampBlock:()=>Yu,ClearCoatBlock:()=>kd,ClipPlanesBlock:()=>zu,ClipboardEventTypes:()=>ea.p,ClipboardInfo:()=>ea.o,CloudBlock:()=>ep,CloudPoint:()=>d_,Collider:()=>yn,Color3:()=>Gr.Wo,Color3Gradient:()=>$f,Color4:()=>Gr.HE,ColorCorrectionPostProcess:()=>pm,ColorCurves:()=>Jh.U,ColorGradient:()=>Kf,ColorGradingTexture:()=>uc,ColorMergerBlock:()=>td,ColorSplitterBlock:()=>sd.v,ColorWriteFlags:()=>Ar,CombineAction:()=>S,CompareFunction:()=>fr,CompatibilityOptions:()=>rn.e,CompilationMessageType:()=>xr,ComputeBindingType:()=>Pn,ComputeEffect:()=>An,ComputePassTimestampLocation:()=>wr,ComputeShader:()=>Dn,ComputeShaderParticleSystem:()=>qf,Condition:()=>u,ConditionalBlock:()=>Jd,ConditionalBlockConditions:()=>jd,ConeParticleEmitter:()=>Hf.LV,Constants:()=>Cs.g,ContainerAssetTask:()=>Bg,ConversionMode:()=>vg,ConvolutionPostProcess:()=>fm,Coordinate:()=>Gr.c7,CopyTextureToTexture:()=>yg,CopyTools:()=>Uv.r1,CreateBox:()=>Yn.NR,CreateBoxVertexData:()=>Yn.aR,CreateCapsule:()=>Jn,CreateCapsuleVertexData:()=>Zn,CreateCylinder:()=>an,CreateCylinderVertexData:()=>on,CreateDashedLines:()=>as,CreateDashedLinesVertexData:()=>ss,CreateDecal:()=>vf,CreateDisc:()=>Ca,CreateDiscVertexData:()=>Ea,CreateEnvTextureAsync:()=>Gs.p6,CreateGeodesic:()=>Ef,CreateGoldberg:()=>Af,CreateGoldbergVertexData:()=>Cf,CreateGround:()=>dn.$6,CreateGroundFromHeightMap:()=>dn.W,CreateGroundFromHeightMapVertexData:()=>dn.Qq,CreateGroundVertexData:()=>dn.kt,CreateHemisphere:()=>Pa,CreateIcoSphere:()=>cf.Au,CreateIcoSphereVertexData:()=>cf.GQ,CreateImageDataArrayBufferViews:()=>Gs.Do,CreateLathe:()=>of,CreateLineSystem:()=>rs,CreateLineSystemVertexData:()=>ns,CreateLines:()=>os,CreatePlane:()=>pa.pT,CreatePlaneVertexData:()=>pa.Hq,CreatePolygon:()=>nf,CreatePolygonVertexData:()=>tf,CreatePolyhedron:()=>ya,CreatePolyhedronVertexData:()=>va,CreateResizedCopy:()=>ro.cW,CreateRibbon:()=>fs,CreateRibbonVertexData:()=>ps,CreateScreenshot:()=>yv,CreateScreenshotAsync:()=>xv,CreateScreenshotUsingRenderTarget:()=>Tv,CreateScreenshotUsingRenderTargetAsync:()=>Sv,CreateScreenshotWithResizeAsync:()=>bv,CreateSphere:()=>Kn,CreateSphereVertexData:()=>qn,CreateTiledBox:()=>jp,CreateTiledBoxVertexData:()=>Xp,CreateTiledGround:()=>dn.DG,CreateTiledGroundVertexData:()=>dn.Es,CreateTiledPlane:()=>Wp,CreateTiledPlaneVertexData:()=>zp,CreateTorus:()=>cn,CreateTorusKnot:()=>Kp,CreateTorusKnotVertexData:()=>qp,CreateTorusVertexData:()=>hn,CreateTube:()=>lf,CrossBlock:()=>qu,CubeMapToSphericalPolynomialTools:()=>Ka.$,CubeTexture:()=>Fa.B,CubeTextureAssetTask:()=>Wg,CubicEase:()=>$,CullMode:()=>Cr,CurrentScreenBlock:()=>ku.K,Curve3:()=>Gr.j_,CustomBlock:()=>Ku,CustomOptimization:()=>rv,CustomParticleEmitter:()=>Hf.E0,CustomProceduralTexture:()=>$c,CylinderBuilder:()=>ln,CylinderDirectedParticleEmitter:()=>Hf.z,CylinderParticleEmitter:()=>Hf.kT,DDSTools:()=>nl,DataBuffer:()=>Ke.h,DataReader:()=>Iv.d,DataStorage:()=>Dv,Database:()=>zf,DaydreamController:()=>ia,DebugLayer:()=>jn,DebugLayerTab:()=>kn,DecalBuilder:()=>yf,DecalMapConfiguration:()=>gp,DecalMapDefines:()=>mp,Decode:()=>Ae.fJ,DecodeBase64ToBinary:()=>Ae.HQ,DecodeBase64ToString:()=>Ae.rP,DecodeBase64UrlToBinary:()=>dc.$K,DecodeBase64UrlToString:()=>dc.A2,DeepCopier:()=>P.j,DefaultCollisionCoordinator:()=>xn,DefaultKTX2DecoderOptions:()=>pl,DefaultLoadingScreen:()=>Ch,DefaultRenderingPipeline:()=>Nm,Deferred:()=>Yg.B,DepthCullingState:()=>bo.k,DepthOfFieldBlurPostProcess:()=>_m,DepthOfFieldEffect:()=>vm,DepthOfFieldEffectBlurLevel:()=>gm,DepthOfFieldMergePostProcess:()=>mm,DepthPeelingRenderer:()=>Jm,DepthPeelingSceneComponent:()=>eg,DepthReducer:()=>mh,DepthRenderer:()=>ph,DepthRendererSceneComponent:()=>Qm,DepthSortedParticle:()=>h_,DerivativeBlock:()=>Au,DesaturateBlock:()=>Fd,DetailMapConfiguration:()=>_p.p,DeviceInputEventType:()=>at.g,DeviceLostReason:()=>Vr,DeviceOrientationCamera:()=>Lt,DeviceSource:()=>Ss.p,DeviceSourceManager:()=>Es.U,DeviceType:()=>Ts.Yi,DirectionalLight:()=>Sa.O,DirectionalLightFrustumViewer:()=>bs,DiscBuilder:()=>Aa,DiscardBlock:()=>Eu,DisplayPassPostProcess:()=>ym,DistanceBlock:()=>_d,DistanceConstraint:()=>V_,DistanceJoint:()=>Nh.mN,DivideBlock:()=>ad,DoNothingAction:()=>T,DomManagement:()=>fe.MZ,DotBlock:()=>$u,DracoCompression:()=>Mp.J,DrawWrapper:()=>Ps.q,DualSenseInput:()=>Ts.s2,DualShockButton:()=>Xt,DualShockDpad:()=>jt,DualShockInput:()=>Ts.V7,DualShockPad:()=>Qt,DumpTools:()=>gv.B,DynamicFloat32Array:()=>Gv,DynamicTexture:()=>zi.c,EasingFunction:()=>j,EdgesRenderer:()=>ig,Effect:()=>ds.Q,EffectFallbacks:()=>ka.L,EffectLayer:()=>Jl,EffectLayerSceneComponent:()=>eh,EffectRenderer:()=>Ih.I,EffectWrapper:()=>Ih.H,ElasticEase:()=>Q,ElbowBlock:()=>ip,EncodeArrayBufferToBase64:()=>Ae.Gh,EndsWith:()=>Ae.gi,Engine:()=>ue.D,EngineFactory:()=>Jo,EngineFormat:()=>hl,EngineInstrumentation:()=>$l,EngineStore:()=>A.l,EngineView:()=>Fs,EnvironmentHelper:()=>Ha,EnvironmentTextureTools:()=>Gs.qh,Epsilon:()=>Gr.kn,EquiRectangularCubeTexture:()=>pc,EquiRectangularCubeTextureAssetTask:()=>Xg,ErrorCodes:()=>Hs.SM,ErrorFilter:()=>kr,EventConstants:()=>at.G,EventState:()=>r.he,ExecuteCodeAction:()=>E,ExponentialEase:()=>Z,ExternalTexture:()=>So,ExtractHighlightsPostProcess:()=>lm,ExtrudePolygon:()=>sf,ExtrudeShape:()=>ms,ExtrudeShapeCustom:()=>gs,FactorGradient:()=>Qf,FadeInOutBehavior:()=>Fe.Y,FeatureName:()=>ir,FileTools:()=>dc.e0,FileToolsOptions:()=>dc.rN,FilesInput:()=>$g,FilesInputStore:()=>Kg.X,FilterMode:()=>dr,FilterPostProcess:()=>xm,FluidRenderer:()=>Sg,FluidRendererSceneComponent:()=>Tg,FluidRenderingDebug:()=>ug,FluidRenderingObject:()=>pg,FluidRenderingObjectCustomParticles:()=>gg,FluidRenderingObjectParticleSystem:()=>fg,FluidRenderingTargetRenderer:()=>mg,FlyCamera:()=>Ut,FlyCameraInputsManager:()=>Bt,FlyCameraKeyboardInput:()=>pt,FlyCameraMouseInput:()=>ft,FogBlock:()=>Nu,FollowBehavior:()=>Ge.j,FollowCamera:()=>kt,FollowCameraInputsManager:()=>Vt,FollowCameraKeyboardMoveInput:()=>_t,FollowCameraMouseWheelInput:()=>mt,FollowCameraPointersInput:()=>gt,FragCoordBlock:()=>Pu,FragDepthBlock:()=>Ou,FragmentOutputBlock:()=>yu.g,FramingBehavior:()=>Oe,FreeCamera:()=>Dt.c,FreeCameraDeviceOrientationInput:()=>yt,FreeCameraGamepadInput:()=>xt,FreeCameraInputsManager:()=>vt.a,FreeCameraKeyboardMoveInput:()=>Tt.Y,FreeCameraMouseInput:()=>St.A,FreeCameraMouseWheelInput:()=>Et.A,FreeCameraTouchInput:()=>Ct.y,FreeCameraVirtualJoystickInput:()=>Rt,FresnelBlock:()=>dd,FresnelParameters:()=>ec,FromHalfFloat:()=>ro.qZ,FrontFace:()=>Er,FrontFacingBlock:()=>Cu,Frustum:()=>Gr.iW,FxaaPostProcess:()=>bm,GPUParticleSystem:()=>s_,GUID:()=>hp.x,Gamepad:()=>tt,GamepadCamera:()=>ti,GamepadManager:()=>Zt,GamepadSystemSceneComponent:()=>Jt,GearVRController:()=>na,GenerateBase64StringFromPixelData:()=>Uv.xj,GenerateBase64StringFromTexture:()=>Uv._u,GenerateBase64StringFromTextureAsync:()=>Uv.Jj,GenericController:()=>sa,GenericPad:()=>it,GeodesicData:()=>Sf,Geometry:()=>Ah.Z,GeometryBufferRenderer:()=>Cm,GeometryBufferRendererSceneComponent:()=>Pm,GetClass:()=>l.q,GetDOMTextContent:()=>fe.v,GetEnvInfo:()=>Gs.qJ,GetEnvironmentBRDFTexture:()=>Bd.$,GetInternalFormatFromBasisFormat:()=>Fc,GetTGAHeader:()=>Pc,Gizmo:()=>Gn.t,GizmoManager:()=>Ta,GlowLayer:()=>th,GoldbergMesh:()=>Vp,GradientBlock:()=>Pd,GradientBlockColorStep:()=>Ad,GradientHelper:()=>Zf,GrainPostProcess:()=>Tm,GroundBuilder:()=>dn.vU,GroundMesh:()=>Up.E,HDRCubeTexture:()=>Oh,HDRCubeTextureAssetTask:()=>Hg,HDRFiltering:()=>Dh,HDRTools:()=>Mh,HandConstraintBehavior:()=>ze.q_,HandConstraintOrientation:()=>ze.rX,HandConstraintVisibility:()=>ze.bH,HandConstraintZone:()=>ze.$6,HandPart:()=>oy.OF,HardwareScalingOptimization:()=>tv,HavokPlugin:()=>K_,HeightToNormalBlock:()=>Du,HemisphereBuilder:()=>Ra,HemisphericLight:()=>Li.e,HemisphericParticleEmitter:()=>Hf.VD,HighlightLayer:()=>nh,HighlightsPostProcess:()=>Sm,Hinge2Joint:()=>Nh.OT,HingeConstraint:()=>k_,HingeJoint:()=>Nh.yr,HtmlElementTexture:()=>fc,IWebXRControllerPhysicsOptions:()=>iy,IcoSphereBuilder:()=>cf.GM,ImageAssetTask:()=>Gg,ImageProcessingBlock:()=>bu,ImageProcessingConfiguration:()=>ki.$,ImageProcessingConfigurationDefines:()=>ki.b,ImageProcessingPostProcess:()=>Wi,ImageSourceBlock:()=>Lu,IncrementValueAction:()=>y,IndexFormat:()=>Ir,InputBlock:()=>fu.S,InputStepMode:()=>Or,InspectableType:()=>Av,InstancedLinesMesh:()=>is.E,InstancedMesh:()=>Gp.S,InstancesBlock:()=>mu,InstantiatedEntries:()=>ce.ve,InternalTexture:()=>Ei.l,InternalTextureSource:()=>Ei.S,InterpolateValueAction:()=>O,IntersectionInfo:()=>Tn.c,IsBase64DataUrl:()=>dc.VL,IsDocumentAvailable:()=>fe.n5,IsFileURL:()=>dc.Uh,IsNavigatorAvailable:()=>fe.up,IsWindowObjectExist:()=>fe.CG,JoystickAxis:()=>bt,KeepAssets:()=>ce.fD,KeyboardEventTypes:()=>st.OG,KeyboardInfo:()=>st.NG,KeyboardInfoPre:()=>st.WZ,KhronosTextureContainer:()=>ol,KhronosTextureContainer2:()=>fl,LatheBuilder:()=>af,Layer:()=>sh.m,LayerSceneComponent:()=>rh.N,LengthBlock:()=>md,LensFlare:()=>oh,LensFlareSystem:()=>ah,LensFlareSystemSceneComponent:()=>lh,LensFlaresOptimization:()=>sv,LensRenderingPipeline:()=>Fm,LerpBlock:()=>od,Light:()=>hh._,LightBlock:()=>Fu,LightGizmo:()=>Ia,LightInformationBlock:()=>vu,LineEdgesRenderer:()=>ng,LinesBuilder:()=>ls,LinesMesh:()=>is._,LoadFile:()=>dc.vP,LoadFileError:()=>dc.eh,LoadImage:()=>dc.r6,LoadOp:()=>Fr,LoadTextureFromTranscodeResult:()=>Gc,LockConstraint:()=>z_,Logger:()=>_.Y,MapMode:()=>rr,Material:()=>cs.F,MaterialAnisotropicDefines:()=>ic.i,MaterialClearCoatDefines:()=>rc.d,MaterialDefines:()=>Ba.H,MaterialDetailMapDefines:()=>_p.G,MaterialFlags:()=>Va.k,MaterialHelper:()=>La.G,MaterialIridescenceDefines:()=>oc.f,MaterialPluginBase:()=>dp.n,MaterialPluginEvent:()=>fp.S,MaterialPluginManager:()=>pp.BK,MaterialSheenDefines:()=>hc.A,MaterialSubSurfaceDefines:()=>cc.H,Matrix:()=>Gr.y3,MatrixBuilderBlock:()=>Zd,MatrixDeterminantBlock:()=>rp,MatrixTransposeBlock:()=>op,MaxBlock:()=>pd,MergeMeshesOptimization:()=>lv,Mesh:()=>Nt.Kj,MeshAssetTask:()=>Ug,MeshAttributeExistsBlock:()=>ap,MeshAttributeExistsBlockTypes:()=>Yd,MeshBuilder:()=>Pf,MeshExploder:()=>qg,MeshLODLevel:()=>Bf.g,MeshParticleEmitter:()=>Hf.F3,MeshUVSpaceRenderer:()=>Bp,MeshoptCompression:()=>Ip.K,MinBlock:()=>fd,MinMaxReducer:()=>_h,MipmapFilterMode:()=>pr,MirrorTexture:()=>Na,ModBlock:()=>Qd,ModelShape:()=>l_,MorphTarget:()=>Vf.Y,MorphTargetManager:()=>wh.O,MorphTargetsBlock:()=>gu,MotionBlurPostProcess:()=>Rm,MotorEnabledJoint:()=>Nh.$Q,MultiMaterial:()=>Ph.G,MultiObserver:()=>Qg,MultiPointerScaleBehavior:()=>Be,MultiRenderTarget:()=>Xc,MultiplyBlock:()=>Hu.U,NLerpBlock:()=>Rd,NativeDataStream:()=>ks,NativeEngine:()=>Js,NativePointerInput:()=>Ts.FP,NativeXRFrame:()=>By,NativeXRLayerRenderTargetTextureProvider:()=>en,NativeXRLayerWrapper:()=>Ji,NativeXRRenderTarget:()=>tn,NegateBlock:()=>gd,Node:()=>Ot.N,NodeMaterial:()=>Fl.O,NodeMaterialBlock:()=>du.k,NodeMaterialBlockConnectionPointMode:()=>au.M,NodeMaterialBlockConnectionPointTypes:()=>ou.E,NodeMaterialBlockTargets:()=>ru.u,NodeMaterialConnectionPoint:()=>cu.VT,NodeMaterialConnectionPointCompatibilityStates:()=>cu.WS,NodeMaterialConnectionPointCustomObject:()=>uu,NodeMaterialConnectionPointDirection:()=>cu.Ab,NodeMaterialDefines:()=>Fl.n,NodeMaterialModes:()=>hu.a,NodeMaterialOptimizer:()=>lp,NodeMaterialSystemValues:()=>lu.$,NoiseProceduralTexture:()=>Qc,NormalBlendBlock:()=>Dd,NormalizeBlock:()=>Ju,NullEngine:()=>Is,NullEngineOptions:()=>Ms,Observable:()=>r.y$,Observer:()=>r.Qj,OcclusionMaterial:()=>tc,Octree:()=>Bn,OctreeBlock:()=>Ln,OctreeSceneComponent:()=>Vn,OculusTouchController:()=>ra,OimoJSPlugin:()=>Uh,OnAfterEnteringVRObservableEvent:()=>mn,OneMinusBlock:()=>cd,Orientation:()=>Gr.i5,OutlineRenderer:()=>cg,PBRAnisotropicConfiguration:()=>ic.u,PBRBaseMaterial:()=>nc.m,PBRBaseSimpleMaterial:()=>sc,PBRClearCoatConfiguration:()=>rc.Y,PBRIridescenceConfiguration:()=>oc.B,PBRMaterial:()=>Ya.Y,PBRMaterialDefines:()=>nc.r,PBRMetallicRoughnessBlock:()=>Xd,PBRMetallicRoughnessMaterial:()=>ac,PBRSheenConfiguration:()=>hc.B,PBRSpecularGlossinessMaterial:()=>lc,PBRSubSurfaceConfiguration:()=>cc.u,PHI:()=>Gr.Q_,PadNumber:()=>Ae.zA,PanoramaToCubeMapTools:()=>Rh,Particle:()=>Jf,ParticleBlendMultiplyBlock:()=>$d.D,ParticleHelper:()=>o_,ParticleRampGradientBlock:()=>Kd.p,ParticleSystem:()=>i_,ParticleSystemSet:()=>r_,ParticleTextureBlock:()=>qd.P,ParticlesOptimization:()=>ov,PassCubePostProcess:()=>ii.Z,PassPostProcess:()=>ii.Q,Path2:()=>Gr.ZZ,Path3D:()=>Gr.$B,PathCursor:()=>he,PerfCollectionStrategy:()=>qv,PerfCounter:()=>Os.z,PerformanceConfigurator:()=>As.Z,PerformanceMonitor:()=>Zg.A,PerformanceViewerCollector:()=>jv,PerturbNormalBlock:()=>Su,PhotoDome:()=>ja,Physics6DoFConstraint:()=>B_,Physics6DoFLimit:()=>L_,PhysicsAggregate:()=>H_,PhysicsBody:()=>A_,PhysicsConstraint:()=>F_,PhysicsConstraintAxis:()=>m_,PhysicsConstraintAxisLimitMode:()=>__,PhysicsConstraintMotorType:()=>y_,PhysicsConstraintType:()=>g_,PhysicsEngine:()=>Lh.T,PhysicsEngineV2:()=>C_,PhysicsHelper:()=>Z_,PhysicsImpostor:()=>Qn.Q,PhysicsJoint:()=>Nh.q7,PhysicsMaterialCombineMode:()=>b_,PhysicsMotionType:()=>x_,PhysicsRadialExplosionEventOptions:()=>nm,PhysicsRadialImpulseFalloff:()=>T_,PhysicsRaycastResult:()=>Fh.d,PhysicsShape:()=>P_,PhysicsShapeBox:()=>D_,PhysicsShapeCapsule:()=>M_,PhysicsShapeContainer:()=>N_,PhysicsShapeConvexHull:()=>O_,PhysicsShapeCylinder:()=>I_,PhysicsShapeMesh:()=>w_,PhysicsShapeSphere:()=>R_,PhysicsShapeType:()=>v_,PhysicsUpdraftEventOptions:()=>sm,PhysicsUpdraftMode:()=>S_,PhysicsViewer:()=>ts,PhysicsVortexEventOptions:()=>rm,PickingInfo:()=>bn.p,PipelineErrorReason:()=>br,PivotTools:()=>ua.m,Plane:()=>Gr.JO,PlaneBuilder:()=>pa.mx,PlaneDragGizmo:()=>ma,PlaneRotationGizmo:()=>fa,PlayAnimationAction:()=>x,PlaySoundAction:()=>M,PointColor:()=>f_,PointLight:()=>Eh.c,PointParticleEmitter:()=>Hf.cl,PointerDragBehavior:()=>Le.M,PointerEventTypes:()=>Re.kD,PointerInfo:()=>Re.R5,PointerInfoBase:()=>Re.CU,PointerInfoPre:()=>Re.FV,PointerInput:()=>Ts.Fz,PointsCloudSystem:()=>E_,PointsGroup:()=>p_,Polar:()=>Pp,Polygon:()=>Jp,PolygonBuilder:()=>rf,PolygonMeshBuilder:()=>ef,PolyhedronBuilder:()=>xa,PolyhedronData:()=>Tf,PoseEnabledController:()=>Kt,PoseEnabledControllerHelper:()=>qt,PoseEnabledControllerType:()=>zt,PositionGizmo:()=>ga,PositionNormalTextureVertex:()=>Gr.eN,PositionNormalVertex:()=>Gr.$S,PostProcess:()=>ni.D,PostProcessManager:()=>fh.O,PostProcessRenderEffect:()=>am,PostProcessRenderPipeline:()=>Dm,PostProcessRenderPipelineManager:()=>Om,PostProcessRenderPipelineManagerSceneComponent:()=>wm,PostProcessesOptimization:()=>nv,PosterizeBlock:()=>Ed,PowBlock:()=>vd,PowerEase:()=>J,PowerPreference:()=>tr,PrePassRenderer:()=>rg,PrePassRendererSceneComponent:()=>og,PrecisionDate:()=>G.F,PredicateCondition:()=>p,PressureObserverWrapper:()=>kv,PrimitiveTopology:()=>Sr,PrismaticConstraint:()=>W_,ProceduralTexture:()=>qc.g,ProceduralTextureSceneComponent:()=>Zc.O,PropertyTypeForEdition:()=>xu.U,PushMaterial:()=>Ua.a,QuadraticEase:()=>ee,QuadraticErrorSimplification:()=>Ff,QuarticEase:()=>te,Quaternion:()=>Gr._f,QueryType:()=>Br,QuinticEase:()=>ie,RGBDTextureTools:()=>Rv.r,RandomGUID:()=>hp.f,RandomNumberBlock:()=>yd,RawCubeTexture:()=>Jc.N,RawTexture:()=>Ee.l,RawTexture2DArray:()=>eu.e,RawTexture3D:()=>tu,Ray:()=>Yt.z,RayHelper:()=>hs,ReadFile:()=>dc.Ip,ReadFileError:()=>dc.RC,RecastJSCrowd:()=>Gf,RecastJSPlugin:()=>kf,ReciprocalBlock:()=>Td,ReflectBlock:()=>wd,ReflectionBlock:()=>Vd,ReflectionProbe:()=>kh,ReflectionTextureBlock:()=>Vu,Reflector:()=>Vv,RefractBlock:()=>Nd,RefractionBlock:()=>zd,RefractionPostProcess:()=>Mm,RefractionTexture:()=>iu,RegisterClass:()=>l.H,RegisterMaterialPlugin:()=>pp.rs,RegisterNativeTypeAsync:()=>$s,RemapBlock:()=>Zu.w,RenderPassTimestampLocation:()=>Nr,RenderTargetTexture:()=>Ai._,RenderTargetWrapper:()=>Rs.r,RenderTargetsOptimization:()=>av,RenderingGroup:()=>dg.S,RenderingGroupInfo:()=>uh.t,RenderingManager:()=>uh.$,ReplaceColorBlock:()=>Sd,RequestFile:()=>dc.FV,RequestFileError:()=>dc.kK,RetryStrategy:()=>Mv.b,RibbonBuilder:()=>_s,RollingAverage:()=>Zg.Z,Rotate2dBlock:()=>Od,RotationGizmo:()=>_a,RuntimeAnimation:()=>V,RuntimeError:()=>Hs.LH,SSAO2RenderingPipeline:()=>Bm,SSAORenderingPipeline:()=>Um,SSRRenderingPipeline:()=>Xm,SamplerBindingType:()=>gr,Scalar:()=>lt.R,ScaleBlock:()=>ju,ScaleGizmo:()=>ba,Scene:()=>k.x,SceneComponentConstants:()=>ve.l,SceneDepthBlock:()=>Gu,SceneInstrumentation:()=>Ql,SceneLoader:()=>ta.n,SceneLoaderAnimationGroupLoadingMode:()=>ta.O,SceneLoaderFlags:()=>Zh.Z,SceneOptimization:()=>Jg,SceneOptimizer:()=>cv,SceneOptimizerOptions:()=>hv,ScenePerformancePriority:()=>k.a,SceneRecorder:()=>Ov,SceneSerializer:()=>fv,ScreenSizeBlock:()=>Ru,ScreenSpaceBlock:()=>Mu,ScreenSpaceCurvaturePostProcess:()=>Km,ScreenSpaceReflectionPostProcess:()=>km,ScreenshotTools:()=>Cv,SerializationHelper:()=>Te.p4,SetCorsBehavior:()=>dc.$M,SetParentAction:()=>C,SetStateAction:()=>g,SetValueAction:()=>v,ShaderCodeInliner:()=>zs.Z,ShaderLanguage:()=>Cn.x,ShaderMaterial:()=>us.j,ShaderStage:()=>_r,ShaderStore:()=>si.v,ShadowDepthWrapper:()=>up,ShadowGenerator:()=>dh,ShadowGeneratorSceneComponent:()=>Sh,ShadowLight:()=>ch.O,ShadowMapBlock:()=>wu,ShadowsOptimization:()=>iv,ShapeBuilder:()=>ys,SharpenPostProcess:()=>Im,SheenBlock:()=>Ld,SimplexPerlin3DBlock:()=>Id,SimplicationQueueSceneComponent:()=>Lf,SimplificationQueue:()=>Mf,SimplificationSettings:()=>Rf,SimplificationType:()=>If,SineEase:()=>ne,SixDofDragBehavior:()=>Ue.K,Size:()=>Gr.$u,Skeleton:()=>Ye.O,SkeletonViewer:()=>xs,SliderConstraint:()=>G_,SmartArray:()=>Fn.t,SmartArrayNoDuplicate:()=>Fn.f,SmoothStepBlock:()=>bd,SolidParticle:()=>a_,SolidParticleSystem:()=>u_,SolidParticleVertex:()=>c_,Sound:()=>me.$,SoundTrack:()=>ge,SourceTextureFormat:()=>al,Space:()=>Gr.T,SphereBuilder:()=>$n,SphereDirectedParticleEmitter:()=>Hf.cE,SphereParticleEmitter:()=>Hf.Ai,Spherical:()=>Rp,SphericalHarmonics:()=>qa._,SphericalPolynomial:()=>qa.i,SpotLight:()=>Ma.P,Sprite:()=>Cg,SpriteManager:()=>Rg,SpriteMap:()=>Mg,SpritePackedManager:()=>Ig,SpriteSceneComponent:()=>Ag,Stage:()=>ve.H,StandardMaterial:()=>Gi.K,StandardMaterialDefines:()=>Gi.R,StandardRenderingPipeline:()=>Gm,StartsWith:()=>Ae.Ri,StateCondition:()=>f,StencilOperation:()=>Mr,StencilState:()=>wg.s,StencilStateComposer:()=>yo.C,StepBlock:()=>hd,StereoscopicArcRotateCamera:()=>_i,StereoscopicFreeCamera:()=>mi,StereoscopicGamepadCamera:()=>gi,StereoscopicInterlacePostProcess:()=>pi,StereoscopicInterlacePostProcessI:()=>di,StereoscopicScreenUniversalCamera:()=>xi,StereoscopicUniversalCamera:()=>vi,StickValues:()=>et,StopAnimationAction:()=>b,StopSoundAction:()=>I,StorageBuffer:()=>$e,StorageTextureAccess:()=>yr,StoreOp:()=>Lr,StringDictionary:()=>At.x,StringTools:()=>Ae.Ml,SubEmitter:()=>t_,SubEmitterType:()=>e_,SubMesh:()=>Ll.P,SubSurfaceBlock:()=>Wd,SubSurfaceSceneComponent:()=>hg,SubtractBlock:()=>ld,SurfaceMagnetismBehavior:()=>Ve.p,SwitchBooleanAction:()=>m,SwitchInput:()=>Ts.D_,TBNBlock:()=>Tu,TGATools:()=>Mc,Tags:()=>_v.$,TargetCamera:()=>It.C,TargetedAnimation:()=>oe.U,TestBase64DataUrl:()=>dc.qC,TextFileAssetTask:()=>Vg,Texture:()=>Ce.x,TextureAspect:()=>hr,TextureAssetTask:()=>zg,TextureBlock:()=>Bu,TextureDimension:()=>or,TextureFormat:()=>cr,TextureOptimization:()=>ev,TexturePacker:()=>Yc,TexturePackerFrame:()=>jc,TextureSampleType:()=>vr,TextureSampler:()=>In.a,TextureTools:()=>ro.Oi,TextureUsage:()=>ar,TextureViewDimension:()=>lr,ThinEngine:()=>Rn.B,ThinRenderTargetTexture:()=>su,ThinTexture:()=>nu.g,TiledBoxBuilder:()=>Yp,TiledPlaneBuilder:()=>Hp,TimerState:()=>Nl,TmpColors:()=>Gr.zZ,TmpVectors:()=>Gr.jp,ToGammaSpace:()=>Gr.zp,ToHalfFloat:()=>ro.ay,ToLinearSpace:()=>Gr.Nn,TonemapPostProcess:()=>Ym,TonemappingOperator:()=>jm,Tools:()=>de.w1,TorusBuilder:()=>un,TorusKnotBuilder:()=>$p,TouchCamera:()=>wt,TrailMesh:()=>kp,Trajectory:()=>wv,TrajectoryClassifier:()=>Bv,TranscodeAsync:()=>Vc,TranscodeTarget:()=>ll,TransformBlock:()=>Qu.m,TransformNode:()=>yi.Y,TriPlanarBlock:()=>np,TrigonometryBlock:()=>ed.S,TrigonometryBlockOperations:()=>ed.p,TubeBuilder:()=>hf,TwirlBlock:()=>Iu,UniformBuffer:()=>Ci.M,UniversalCamera:()=>ei,UnregisterAllMaterialPlugins:()=>pp.Dh,UnregisterMaterialPlugin:()=>pp.jD,UploadContent:()=>Rc,UploadEnvLevelsAsync:()=>Gs.Ro,UploadEnvSpherical:()=>Gs.qC,UploadLevelsAsync:()=>Gs.qZ,UtilityLayerRenderer:()=>zn.x,VRCameraMetrics:()=>Ti,VRDeviceOrientationArcRotateCamera:()=>wi,VRDeviceOrientationFreeCamera:()=>Ni,VRDeviceOrientationGamepadCamera:()=>Fi,VRDistortionCorrectionPostProcess:()=>Si,VRExperienceHelper:()=>gn,VRMultiviewToSingleviewPostProcess:()=>Di,ValidatedNativeDataStream:()=>er,ValueCondition:()=>d,Vector2:()=>Gr.FM,Vector3:()=>Gr.P,Vector4:()=>Gr.Lt,VectorMergerBlock:()=>nd.t,VectorSplitterBlock:()=>rd,VertexAnimationBaker:()=>Pe,VertexBuffer:()=>qe.o,VertexData:()=>sn.x,VertexFormat:()=>Dr,VertexOutputBlock:()=>pu.t,VideoDome:()=>Kl,VideoRecorder:()=>mv,VideoTexture:()=>ql,ViewDirectionBlock:()=>ud,Viewport:()=>Gr.l_,VirtualJoystick:()=>Pt,VirtualJoysticksCamera:()=>bi,ViveController:()=>oa,VolumetricLightScatteringPostProcess:()=>qm,VoronoiNoiseBlock:()=>tp,WaveBlock:()=>Cd,WaveBlockKind:()=>id,WebGL2ParticleSystem:()=>Yf,WebGL2ShaderProcessor:()=>Ws.C,WebGLDataBuffer:()=>Uf.M,WebGLHardwareTexture:()=>Yi.B,WebGLPipelineContext:()=>Zo.y,WebGPUCacheBindGroups:()=>Po,WebGPUCacheRenderPipeline:()=>mo,WebGPUCacheRenderPipelineTree:()=>vo,WebGPUCacheSampler:()=>uo,WebGPUDataBuffer:()=>so,WebGPUDrawContext:()=>Co,WebGPUEngine:()=>jo,WebGPUTintWASM:()=>Go,WebRequest:()=>Kc.g,WebVRController:()=>Vi,WebVRFreeCamera:()=>Ui,WebXRAbstractFeature:()=>Il.F,WebXRAbstractMotionController:()=>bl,WebXRAnchorSystem:()=>Zv,WebXRBackgroundRemover:()=>ty,WebXRCamera:()=>gl,WebXRCompositionLayerWrapper:()=>by,WebXRControllerComponent:()=>xl,WebXRControllerMovement:()=>dy,WebXRControllerPhysics:()=>ny,WebXRControllerPointerSelection:()=>Dl,WebXRDefaultExperience:()=>Xl,WebXRDefaultExperienceOptions:()=>Hl,WebXRDepthSensing:()=>Ry,WebXRDomOverlay:()=>uy,WebXREnterExitUI:()=>kl,WebXREnterExitUIButton:()=>Ul,WebXREnterExitUIOptions:()=>Vl,WebXRExperienceHelper:()=>yl,WebXREyeTracking:()=>_y,WebXRFeatureName:()=>vl.b,WebXRFeaturePointSystem:()=>ry,WebXRFeaturesManager:()=>vl.d,WebXRGenericHandController:()=>My,WebXRGenericTriggerMotionController:()=>Tl,WebXRHTCViveMotionController:()=>Fy,WebXRHand:()=>oy.e0,WebXRHandJoint:()=>oy.fL,WebXRHandTracking:()=>oy.en,WebXRHitTest:()=>sy,WebXRHitTestLegacy:()=>$v,WebXRImageTracking:()=>cy,WebXRInput:()=>Ml,WebXRInputSource:()=>Rl,WebXRLayers:()=>Py,WebXRLightEstimation:()=>fy,WebXRManagedOutputCanvas:()=>Zi,WebXRManagedOutputCanvasOptions:()=>Qi,WebXRMeshDetector:()=>ly,WebXRMicrosoftMixedRealityController:()=>Dy,WebXRMotionControllerManager:()=>Al,WebXRMotionControllerTeleportation:()=>Wl,WebXRNearControllerMode:()=>wl,WebXRNearInteraction:()=>Bl,WebXROculusTouchMotionController:()=>wy,WebXRPlaneDetector:()=>ey,WebXRProfiledMotionController:()=>El,WebXRProjectionLayerWrapper:()=>Sy,WebXRSessionManager:()=>nn,WebXRState:()=>Xi,WebXRTrackingState:()=>ji,WebXRWalkingLocomotion:()=>xy,WeightedSound:()=>xe.s,WindowsMotionController:()=>la,WorkerPool:()=>cl.h,WorleyNoise3DBlock:()=>Md,XRWindowsMotionController:()=>ha,Xbox360Button:()=>Wt,Xbox360Dpad:()=>Ht,Xbox360Pad:()=>$t,XboxInput:()=>Ts.$i,_BabylonLoaderRegistered:()=>Gh,_BasisTextureLoader:()=>Hc,_CreationDataStorage:()=>Nt.gW,_DDSTextureLoader:()=>sl,_ENVTextureLoader:()=>rl,_HDRTextureLoader:()=>Dc,_IAnimationState:()=>D.u,_InstancesBatch:()=>Nt.Wv,_KTXTextureLoader:()=>ml,_MeshCollisionData:()=>Sn.a,_OcclusionDataStorage:()=>ws,_PrimaryIsoTriangle:()=>bf,_TGATextureLoader:()=>Ic,_TimeToken:()=>Ds,_UpdateRGBDAsync:()=>Gs.Lf,_forceSceneHelpersToBundle:()=>jl,_forceTransformFeedbackToBundle:()=>Ns,_injectLTSFileTools:()=>dc.W5,addClipPlaneUniforms:()=>Ga.qx,allocateAndCopyTypedBuffer:()=>Us.A,bindClipPlane:()=>Ga.an,className:()=>de.ok,createDetailMapPlugin:()=>Cp,createPBRAnisotropicPlugin:()=>yp,createPBRBRDFPlugin:()=>xp,createPBRClearCoatPlugin:()=>bp,createPBRIridescencePlugin:()=>Tp,createPBRSheenPlugin:()=>Sp,createPBRSubSurfacePlugin:()=>Ep,createYieldingScheduler:()=>Kv.KO,editableInPropertyPage:()=>xu.p,expandToProperty:()=>Te.wz,extractMinAndMax:()=>Ap.k,extractMinAndMaxIndexed:()=>Ap.y,inlineScheduler:()=>Kv.WP,makeAsyncFunction:()=>Kv.U3,makeSyncFunction:()=>Kv.vp,nativeOverride:()=>Te.G6,normalizeEnvInfo:()=>Gs.QH,prepareDefinesForClipPlanes:()=>Ga.AN,prepareStringDefinesForClipPlanes:()=>Ga.lK,runCoroutine:()=>Kv.d_,runCoroutineAsync:()=>Kv.sM,runCoroutineSync:()=>Kv.s3,serialize:()=>Te.qC,serializeAsCameraReference:()=>Te.VE,serializeAsColor3:()=>Te.n9,serializeAsColor4:()=>Te.XX,serializeAsColorCurves:()=>Te.N$,serializeAsFresnelParameters:()=>Te.qQ,serializeAsImageProcessingConfiguration:()=>Te.rX,serializeAsMatrix:()=>Te.oQ,serializeAsMeshReference:()=>Te.RR,serializeAsQuaternion:()=>Te.mv,serializeAsTexture:()=>Te.oU,serializeAsVector2:()=>Te.QC,serializeAsVector3:()=>Te.hd,setAndStartTimer:()=>Gl,setStereoscopicAnaglyphRigMode:()=>oi,setStereoscopicRigMode:()=>fi,setVRRigMode:()=>Oi,setWebVRRigMode:()=>Bi});var n=i(5655),s=i(1803),r=i(5757),o=i(4141),a=i(4649),l=i(2208);class h{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new r.y$,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 e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}h._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof o.FM?e.x+", "+e.y:e instanceof o.P?e.x+", "+e.y+", "+e.z:e instanceof a.Wo?e.r+", "+e.g+", "+e.b:e instanceof a.HE?e.r+", "+e.g+", "+e.b+", "+e.a:e,h._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),(0,l.H)("BABYLON.Action",h);var c=i(2633);class u{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 d extends u{static get IsEqual(){return d._IsEqual}static get IsDifferent(){return d._IsDifferent}static get IsGreater(){return d._IsGreater}static get IsLesser(){return d._IsLesser}constructor(e,t,i,n,s=d.IsEqual){super(e),this.propertyPath=i,this.value=n,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case d.IsGreater:return this._effectiveTarget[this._property]>this.value;case d.IsLesser:return this._effectiveTarget[this._property]<this.value;case d.IsEqual:case d.IsDifferent:{let e;return e=this.value.equals?this.value.equals(this._effectiveTarget[this._property]):this.value===this._effectiveTarget[this._property],this.operator===d.IsEqual?e:!e}}return!1}serialize(){return this._serialize({name:"ValueCondition",properties:[h._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:h._SerializeValueAsString(this.value)},{name:"operator",value:d.GetOperatorName(this.operator)}]})}static GetOperatorName(e){switch(e){case d._IsEqual:return"IsEqual";case d._IsDifferent:return"IsDifferent";case d._IsGreater:return"IsGreater";case d._IsLesser:return"IsLesser";default:return""}}}d._IsEqual=0,d._IsDifferent=1,d._IsGreater=2,d._IsLesser=3;class p extends u{constructor(e,t){super(e),this.predicate=t}isValid(){return this.predicate()}}class f extends u{constructor(e,t,i){super(e),this.value=i,this._target=t}isValid(){return this._target.state===this.value}serialize(){return this._serialize({name:"StateCondition",properties:[h._GetTargetProperty(this._target),{name:"value",value:this.value}]})}}(0,l.H)("BABYLON.ValueCondition",d),(0,l.H)("BABYLON.PredicateCondition",p),(0,l.H)("BABYLON.StateCondition",f);var _=i(2722);class m extends h{constructor(e,t,i,n){super(e,n),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:[h._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class g extends h{constructor(e,t,i,n){super(e,n),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[h._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class v extends h{constructor(e,t,i,n,s){super(e,s),this.propertyPath=i,this.value=n,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:[h._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:h._SerializeValueAsString(this.value)}]},e)}}class y extends h{constructor(e,t,i,n,s){super(e,s),this.propertyPath=i,this.value=n,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&_.Y.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:[h._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:h._SerializeValueAsString(this.value)}]},e)}}class x extends h{constructor(e,t,i,n,s,r){super(e,r),this.from=i,this.to=n,this.loop=s,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:[h._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:h._SerializeValueAsString(this.loop)||!1}]},e)}}class b extends h{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:[h._GetTargetProperty(this._target)]},e)}}class T extends h{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class S extends h{constructor(e,t,i,n=!0){super(e,i),this.children=t,this.enableChildrenConditions=n}_prepare(){for(let e=0;e<this.children.length;e++)this.children[e]._actionManager=this._actionManager,this.children[e]._prepare()}execute(e){for(const t of this.children)this.enableChildrenConditions&&!t._evaluateConditionForCurrentFrame()||t.execute(e)}serialize(e){const t=super._serialize({name:"CombineAction",properties:[],combine:[]},e);for(let e=0;e<this.children.length;e++)t.combine.push(this.children[e].serialize(null));return t}}class E extends h{constructor(e,t,i){super(e,i),this.func=t}execute(e){this.func(e)}}class C extends h{constructor(e,t,i,n){super(e,n),this._target=t,this._parent=i}_prepare(){}execute(){if(this._target.parent===this._parent)return;const e=this._parent.getWorldMatrix().clone();e.invert(),this._target.position=o.P.TransformCoordinates(this._target.position,e),this._target.parent=this._parent}serialize(e){return super._serialize({name:"SetParentAction",properties:[h._GetTargetProperty(this._target),h._GetTargetProperty(this._parent)]},e)}}(0,l.H)("BABYLON.SetParentAction",C),(0,l.H)("BABYLON.ExecuteCodeAction",E),(0,l.H)("BABYLON.DoNothingAction",T),(0,l.H)("BABYLON.StopAnimationAction",b),(0,l.H)("BABYLON.PlayAnimationAction",x),(0,l.H)("BABYLON.IncrementValueAction",y),(0,l.H)("BABYLON.SetValueAction",v),(0,l.H)("BABYLON.SetStateAction",g),(0,l.H)("BABYLON.SetParentAction",C),(0,l.H)("BABYLON.SwitchBooleanAction",m),(0,l.H)("BABYLON.CombineAction",S);var A=i(1431),P=i(6387);class R extends s.O{constructor(e){super(),(e=e||A.l.LastCreatedScene)&&(this._scene=e,e.actionManagers.push(this))}dispose(){const e=this._scene.actionManagers.indexOf(this);for(let e=0;e<this.actions.length;e++){const t=this.actions[e];R.Triggers[t.trigger]--,0===R.Triggers[t.trigger]&&delete R.Triggers[t.trigger]}e>-1&&this._scene.actionManagers.splice(e,1)}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t<this.actions.length;t++){const i=this.actions[t];if(e.indexOf(i.trigger)>-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i<this.actions.length;i++){const n=this.actions[i];if(e==n.trigger||t==n.trigger)return!0}return!1}hasSpecificTrigger(e,t){for(let i=0;i<this.actions.length;i++){const n=this.actions[i];if(n.trigger===e){if(!t)return!0;if(t(n.getTriggerParameter()))return!0}}return!1}get hasPointerTriggers(){for(let e=0;e<this.actions.length;e++){const t=this.actions[e];if(t.trigger>=R.OnPickTrigger&&t.trigger<=R.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e<this.actions.length;e++){const t=this.actions[e];if(t.trigger>=R.OnPickTrigger&&t.trigger<=R.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===R.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(_.Y.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,R.Triggers[e.trigger]?R.Triggers[e.trigger]++:R.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return-1!==t&&(this.actions.splice(t,1),R.Triggers[e.trigger]-=1,0===R.Triggers[e.trigger]&&delete R.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i<this.actions.length;i++){const n=this.actions[i];if(n.trigger===e){if(t&&(e===R.OnKeyUpTrigger||e===R.OnKeyDownTrigger)){const e=n.getTriggerParameter();if("function"==typeof e){if(!e(t))continue}else if(e&&e!==t.sourceEvent.keyCode){if(!e.toLowerCase)continue;const i=e.toLowerCase();if(i!==t.sourceEvent.key){const e=t.sourceEvent.charCode?t.sourceEvent.charCode:t.sourceEvent.keyCode;if(String.fromCharCode(e).toLowerCase()!==i)continue}}}n._executeCurrent(t)}}}_getEffectiveTarget(e,t){const i=t.split(".");for(let t=0;t<i.length-1;t++)e=e[i[t]];return e}_getProperty(e){const t=e.split(".");return t[t.length-1]}serialize(e){const t={children:new Array,name:e,type:3,properties:new Array};for(let e=0;e<this.actions.length;e++){const i={type:0,children:new Array,name:R.GetTriggerName(this.actions[e].trigger),properties:new Array},n=this.actions[e].triggerOptions;if(n&&"number"!=typeof n)if(n.parameter instanceof Node)i.properties.push(h._GetTargetProperty(n.parameter));else if("object"==typeof n.parameter){const e={};P.j.DeepCopy(n.parameter,e,["mesh"]),n.parameter&&n.parameter.mesh&&(e._meshId=n.parameter.mesh.id),i.properties.push({name:"parameter",targetType:null,value:e})}else i.properties.push({name:"parameter",targetType:null,value:n.parameter});this.actions[e].serialize(i),t.children.push(i)}return t}static Parse(e,t,i){const n=new R(i);null===t?i.actionManager=n:t.actionManager=n;const s=(e,t,i,n)=>{if(null===n){const e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}const s=n.split("."),r=t.split(",");for(let e=0;e<s.length;e++)i=i[s[e]];if("boolean"==typeof i)return"true"===r[0];if("string"==typeof i)return r[0];const l=new Array;for(let e=0;e<r.length;e++)l.push(parseFloat(r[e]));return i instanceof o.P?o.P.FromArray(l):i instanceof o.Lt?o.Lt.FromArray(l):i instanceof a.Wo?a.Wo.FromArray(l):i instanceof a.HE?a.HE.FromArray(l):parseFloat(r[0])},r=(e,t,o,a,h=null)=>{if(e.detached)return;const c=new Array;let p=null,f=null;const _=e.combine&&e.combine.length>0;if(2===e.type?c.push(n):c.push(t),_){const t=new Array;for(let i=0;i<e.combine.length;i++)r(e.combine[i],R.NothingTrigger,o,a,t);c.push(t)}else for(let t=0;t<e.properties.length;t++){let n=e.properties[t].value;const r=e.properties[t].name,o=e.properties[t].targetType;"target"===r?n=p="SceneProperties"===o?i:"MaterialProperties"===o?i.getMaterialByName(n):i.getNodeByName(n):"parent"===r?n=i.getNodeByName(n):"sound"===r?i.getSoundByName&&(n=i.getSoundByName(n)):"propertyPath"!==r?n=2===e.type&&"operator"===r?d[n]:s(0,n,p,"value"===r?f:null):f=n,c.push(n)}if(null===h?c.push(o):c.push(null),"InterpolateValueAction"===e.name){const e=c[c.length-2];c[c.length-1]=e,c[c.length-2]=o}let m=((e,t)=>{const i=(0,l.q)("BABYLON."+e);return i&&new i(...t)})(e.name,c);if(m instanceof u&&null!==o){const e=new T(t,o);a?a.then(e):n.registerAction(e),a=e}null===h?m instanceof u?(o=m,m=a):(o=null,a?a.then(m):n.registerAction(m)):h.push(m);for(let i=0;i<e.children.length;i++)r(e.children[i],t,o,m,null)};for(let t=0;t<e.children.length;t++){let n;const s=e.children[t];if(s.properties.length>0){const e=s.properties[0].value,t=null===s.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),n={trigger:R[s.name],parameter:t}}else n=R[s.name];for(let e=0;e<s.children.length;e++)s.detached||r(s.children[e],n,null,null)}}static GetTriggerName(e){switch(e){case 0:return"NothingTrigger";case 1:return"OnPickTrigger";case 2:return"OnLeftPickTrigger";case 3:return"OnRightPickTrigger";case 4:return"OnCenterPickTrigger";case 5:return"OnPickDownTrigger";case 6:return"OnDoublePickTrigger";case 7:return"OnPickUpTrigger";case 8:return"OnLongPressTrigger";case 9:return"OnPointerOverTrigger";case 10:return"OnPointerOutTrigger";case 11:return"OnEveryFrameTrigger";case 12:return"OnIntersectionEnterTrigger";case 13:return"OnIntersectionExitTrigger";case 14:return"OnKeyDownTrigger";case 15:return"OnKeyUpTrigger";case 16:return"OnPickOutTrigger";default:return""}}}R.NothingTrigger=0,R.OnPickTrigger=1,R.OnLeftPickTrigger=2,R.OnRightPickTrigger=3,R.OnCenterPickTrigger=4,R.OnPickDownTrigger=5,R.OnDoublePickTrigger=6,R.OnPickUpTrigger=7,R.OnPickOutTrigger=16,R.OnLongPressTrigger=8,R.OnPointerOverTrigger=9,R.OnPointerOutTrigger=10,R.OnEveryFrameTrigger=11,R.OnIntersectionEnterTrigger=12,R.OnIntersectionExitTrigger=13,R.OnKeyDownTrigger=14,R.OnKeyUpTrigger=15;class M extends h{constructor(e,t,i){super(e,i),this._sound=t}_prepare(){}execute(){void 0!==this._sound&&this._sound.play()}serialize(e){return super._serialize({name:"PlaySoundAction",properties:[{name:"sound",value:this._sound.name}]},e)}}class I extends h{constructor(e,t,i){super(e,i),this._sound=t}_prepare(){}execute(){void 0!==this._sound&&this._sound.stop()}serialize(e){return super._serialize({name:"StopSoundAction",properties:[{name:"sound",value:this._sound.name}]},e)}}(0,l.H)("BABYLON.PlaySoundAction",M),(0,l.H)("BABYLON.StopSoundAction",I);var D=i(4676);class O extends h{constructor(e,t,i,n,s=1e3,o,a,l){super(e,o),this.duration=1e3,this.onInterpolationDoneObservable=new r.y$,this.propertyPath=i,this.value=n,this.duration=s,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("number"==typeof this.value)i=D.f.ANIMATIONTYPE_FLOAT;else if(this.value instanceof a.Wo)i=D.f.ANIMATIONTYPE_COLOR3;else if(this.value instanceof o.P)i=D.f.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof o.y3)i=D.f.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof o._f))return void _.Y.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");i=D.f.ANIMATIONTYPE_QUATERNION}const n=new D.f("InterpolateValueAction",this._property,1e3/this.duration*100,i,D.f.ANIMATIONLOOPMODE_CONSTANT);n.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget),e.beginDirectAnimation(this._effectiveTarget,[n],0,100,!1,1,(()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()}))}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[h._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:h._SerializeValueAsString(this.value)},{name:"duration",value:h._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:h._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}(0,l.H)("BABYLON.InterpolateValueAction",O);var w=i(9697);const N=Object.freeze(new o._f(0,0,0,0)),F=Object.freeze(o.P.Zero()),L=Object.freeze(o.FM.Zero()),B=Object.freeze(w.$.Zero()),U=Object.freeze(a.Wo.Black());class V{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,n){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._ratioOffset=0,this._previousDelay=0,this._previousRatio=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=n,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===D.f.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=o.y3.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const s=t.getEvents();s&&s.length>0&&s.forEach((e=>{this._events.push(e._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 n=e[i[0]];for(let e=1;e<i.length-1;e++)n=n[i[e]];this._targetPath=i[i.length-1],this._activeTargets[t]=n}else this._targetPath=i[0],this._activeTargets[t]=e}get animation(){return this._animation}reset(e=!1){if(e)if(this._target instanceof Array){let e=0;for(const t of this._target)void 0!==this._originalValue[e]&&this._setValue(t,this._activeTargets[e],this._originalValue[e],-1,e),e++}else void 0!==this._originalValue[0]&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0);this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0;for(let e=0;e<this._events.length;e++)this._events[e].isDone=!1}isStopped(){return this._stopped}dispose(){const e=this._animation.runtimeAnimations.indexOf(this);e>-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;i<this._target.length;i++){const n=this._target[i];this._setValue(n,this._activeTargets[i],e,t,i)}else this._setValue(this._target,this._directTarget,e,t,0)}_getOriginalValues(e=0){let t;const i=this._activeTargets[e];t=i.getRestPose&&"_matrix"===this._targetPath?i.getRestPose():i[this._targetPath],t&&t.clone?this._originalValue[e]=t.clone():this._originalValue[e]=t}_setValue(e,t,i,n,s){if(this._currentActiveTarget=t,this._weight=n,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){const e=t[this._targetPath];e.clone?this._originalBlendValue=e.clone():this._originalBlendValue=e}this._originalBlendValue.m?D.f.AllowMatrixDecomposeForInterpolation?this._currentValue?o.y3.DecomposeLerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=o.y3.DecomposeLerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue?o.y3.LerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=o.y3.Lerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue=D.f._UniversalLerp(this._originalBlendValue,i,this._blendingFactor);const n=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=n}else this._currentValue?this._currentValue.copyFrom?this._currentValue.copyFrom(i):this._currentValue=i:(null==i?void 0:i.clone)?this._currentValue=i.clone():this._currentValue=i;-1!==n?this._scene._registerTargetForLateAnimationBinding(this,this._originalValue[s]):t[this._targetPath]=this._currentValue,e.markAsDirty&&e.markAsDirty(this._animation.targetProperty)}_getCorrectLoopMode(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode}goToFrame(e){const t=this._animation.getKeys();e<t[0].frame?e=t[0].frame:e>t[t.length-1].frame&&(e=t[t.length-1].frame);const i=this._events;if(i.length)for(let t=0;t<i.length;t++)i[t].onlyOnce||(i[t].isDone=i[t].frame<e);this._currentFrame=e;const n=this._animation._interpolate(e,this._animationState);this.setValue(n,-1)}_prepareForSpeedRatioChange(e){const t=this._previousDelay*(this._animation.framePerSecond*e)/1e3;this._ratioOffset=this._previousRatio-t}animate(e,t,i,n,s,r=-1){const o=this._animation,a=o.targetPropertyPath;if(!a||a.length<1)return this._stopped=!0,!1;let l=!0;(t<this._minFrame||t>this._maxFrame)&&(t=this._minFrame),(i<this._minFrame||i>this._maxFrame)&&(i=this._maxFrame);const h=i-t;let c;const u=e*(o.framePerSecond*s)/1e3+this._ratioOffset;let d,p=0;if(this._previousDelay=e,this._previousRatio=u,!n&&i>=t&&u>=h)l=!1,p=o._getKeyValue(this._maxValue);else if(!n&&t>=i&&u<=h)l=!1,p=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==D.f.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=D.f.ANIMATIONLOOPMODE_CYCLE;const n=o._interpolate(t,this._animationState),s=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case D.f.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=s-n;break;case D.f.ANIMATIONTYPE_QUATERNION:case D.f.ANIMATIONTYPE_VECTOR3:case D.f.ANIMATIONTYPE_VECTOR2:case D.f.ANIMATIONTYPE_SIZE:case D.f.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=s.subtract(n)}this._highLimitsCache[e]=s}p=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(o.dataType){case D.f.ANIMATIONTYPE_FLOAT:c=0;break;case D.f.ANIMATIONTYPE_QUATERNION:c=N;break;case D.f.ANIMATIONTYPE_VECTOR3:c=F;break;case D.f.ANIMATIONTYPE_VECTOR2:c=L;break;case D.f.ANIMATIONTYPE_SIZE:c=B;break;case D.f.ANIMATIONTYPE_COLOR3:c=U}if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;d=t+(i-t)*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else d=u>0&&t>i||u<0&&t<i?l&&0!==h?i+u%h:t:l&&0!==h?t+u%h:i;const f=this._events;if(s>0&&this.currentFrame>d||s<0&&this.currentFrame<d){this._onLoop();for(let e=0;e<f.length;e++)f[e].onlyOnce||(f[e].isDone=!1);this._animationState.key=s>0?0:o.getKeys().length-1}this._currentFrame=d,this._animationState.repeatCount=0===h?0:u/h>>0,this._animationState.highLimitValue=p,this._animationState.offsetValue=c;const _=o._interpolate(d,this._animationState);if(this.setValue(_,r),f.length)for(let e=0;e<f.length;e++)if(h>0&&d>=f[e].frame&&f[e].frame>=t||h<0&&d<=f[e].frame&&f[e].frame<=t){const t=f[e];t.isDone||(t.onlyOnce&&(f.splice(e,1),e--),t.isDone=!0,t.action(d))}return l||(this._stopped=!0),l}}var k=i(1057),G=i(8108),z=i(4026);class W{get syncRoot(){return this._syncRoot}get masterFrame(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){this._weight=-1!==e?Math.min(Math.max(e,0),1):-1}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t<this._runtimeAnimations.length;t++)this._runtimeAnimations[t]._prepareForSpeedRatioChange(e);this._speedRatio=e,null!==this._goToFrame&&this.goToFrame(this._goToFrame)}constructor(e,t,i=0,n=100,s=!1,o=1,a,l,h,c=!1){this.target=t,this.fromFrame=i,this.toFrame=n,this.loopAnimation=s,this.onAnimationEnd=a,this.onAnimationLoop=h,this.isAdditive=c,this._localDelayOffset=null,this._pausedDelay=null,this._manualJumpDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this._syncRoot=null,this._frameToSyncFromJump=null,this._goToFrame=null,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new r.y$,this.onAnimationLoopObservable=new r.y$,this._scene=e,l&&this.appendAnimations(t,l),this._speedRatio=o,e._activeAnimatables.push(this)}syncWith(e){if(this._syncRoot=e,e){const e=this._scene._activeAnimatables.indexOf(this);e>-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i<t.length;i++){const n=t[i],s=new V(e,n,this._scene,this);s._onLoop=()=>{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i].animation;return null}getRuntimeAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i];return null}reset(){const e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].reset(!0);this._localDelayOffset=null,this._pausedDelay=null}enableBlending(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)t[i].animation.enableBlending=!0,t[i].animation.blendingSpeed=e}disableBlending(){const e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].animation.enableBlending=!1}goToFrame(e){var t;const i=this._runtimeAnimations;if(i[0]){const n=i[0].animation.framePerSecond;this._frameToSyncFromJump=null!==(t=this._frameToSyncFromJump)&&void 0!==t?t:i[0].currentFrame;const s=0===this.speedRatio?0:(e-this._frameToSyncFromJump)/n*1e3/this.speedRatio;this._manualJumpDelay=-s}for(let t=0;t<i.length;t++)i[t].goToFrame(e);this._goToFrame=e}pause(){this._paused||(this._paused=!0)}restart(){this._paused=!1}_raiseOnAnimationEnd(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)}stop(e,t,i=!1){if(e||t){const n=this._scene._activeAnimatables.indexOf(this);if(n>-1){const s=this._runtimeAnimations;for(let i=s.length-1;i>=0;i--){const n=s[i];e&&n.animation.name!=e||t&&!t(n.target)||(n.dispose(),s.splice(i,1))}0==s.length&&(i||this._scene._activeAnimatables.splice(n,1),this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e<t.length;e++)t[e].dispose();this._runtimeAnimations.length=0,this._raiseOnAnimationEnd()}}}waitAsync(){return new Promise((e=>{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let n;for(n=0;n<i.length;n++){const s=i[n].animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);t=t||s}if(this.animationStarted=t,!t){if(this.disposeOnEnd)for(n=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(n,1),n=0;n<i.length;n++)i[n].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return t}}k.x.prototype._animate=function(){if(!this.animationsEnabled)return;const e=G.F.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;const t=this._activeAnimatables;if(0===t.length)return;this._animationTime+=this.deltaTime;const i=this._animationTime;for(let e=0;e<t.length;e++){const n=t[e];!n._animate(i)&&n.disposeOnEnd&&e--}this._processLateAnimationBindings()},k.x.prototype.beginWeightedAnimation=function(e,t,i,n=1,s,r=1,o,a,l,h,c=!1){const u=this.beginAnimation(e,t,i,s,r,o,a,!1,l,h,c);return u.weight=n,u},k.x.prototype.beginAnimation=function(e,t,i,n,s=1,r,o,a=!0,l,h,c=!1){t>i&&s>0&&(s*=-1),a&&this.stopAnimation(e,void 0,l),o||(o=new W(this,e,t,i,n,s,r,void 0,h,c));const u=!l||l(e);if(e.animations&&u&&o.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;e<c.length;e++)this.beginAnimation(c[e],t,i,n,s,r,o,a,l,h)}return o.reset(),o},k.x.prototype.beginHierarchyAnimation=function(e,t,i,n,s,r=1,o,a,l=!0,h,c,u=!1){const d=e.getDescendants(t),p=[];p.push(this.beginAnimation(e,i,n,s,r,o,a,l,h,void 0,u));for(const e of d)p.push(this.beginAnimation(e,i,n,s,r,o,a,l,h,void 0,u));return p},k.x.prototype.beginDirectAnimation=function(e,t,i,n,s,r,o,a,l=!1){if(void 0===r&&(r=1),i>n&&r>0)r*=-1;else if(n>i&&r<0){const e=n;n=i,i=e}return new W(this,e,i,n,s,r,o,t,a,l)},k.x.prototype.beginDirectHierarchyAnimation=function(e,t,i,n,s,r,o,a,l,h=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,n,s,r,o,a,l,h));for(const e of c)u.push(this.beginDirectAnimation(e,i,n,s,r,o,a,l,h));return u},k.x.prototype.getAnimatableByTarget=function(e){for(let t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},k.x.prototype.getAllAnimatablesByTarget=function(e){const t=[];for(let i=0;i<this._activeAnimatables.length;i++)this._activeAnimatables[i].target===e&&t.push(this._activeAnimatables[i]);return t},k.x.prototype.stopAnimation=function(e,t,i){const n=this.getAllAnimatablesByTarget(e);for(const e of n)e.stop(t,i)},k.x.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(let e=0;e<this._activeAnimatables.length;e++)this._activeAnimatables[e].stop(void 0,void 0,!0);this._activeAnimatables.length=0}for(const e of this.animationGroups)e.stop()},k.x.prototype._registerTargetForLateAnimationBinding=function(e,t){const i=e.target;this._registeredForLateAnimationBindings.pushNoDuplicate(i),i._lateAnimationHolders||(i._lateAnimationHolders={}),i._lateAnimationHolders[e.targetPath]||(i._lateAnimationHolders[e.targetPath]={totalWeight:0,totalAdditiveWeight:0,animations:[],additiveAnimations:[],originalValue:t}),e.isAdditive?(i._lateAnimationHolders[e.targetPath].additiveAnimations.push(e),i._lateAnimationHolders[e.targetPath].totalAdditiveWeight+=e.weight):(i._lateAnimationHolders[e.targetPath].animations.push(e),i._lateAnimationHolders[e.targetPath].totalWeight+=e.weight)},k.x.prototype._processLateAnimationBindingsForMatrices=function(e){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return e.originalValue;let t=1;const i=o.jp.Vector3[0],n=o.jp.Vector3[1],s=o.jp.Quaternion[0];let r=0;const a=e.animations[0],l=e.originalValue;let h=1,c=!1;if(e.totalWeight<1)h=1-e.totalWeight,l.decompose(n,s,i);else{if(r=1,t=e.totalWeight,h=a.weight/t,1==h){if(!e.totalAdditiveWeight)return a.currentValue;c=!0}a.currentValue.decompose(n,s,i)}if(!c){n.scaleInPlace(h),i.scaleInPlace(h),s.scaleInPlace(h);for(let a=r;a<e.animations.length;a++){const r=e.animations[a];if(0===r.weight)continue;h=r.weight/t;const l=o.jp.Vector3[2],c=o.jp.Vector3[3],u=o.jp.Quaternion[1];r.currentValue.decompose(c,u,l),c.scaleAndAddToRef(h,n),u.scaleAndAddToRef(o._f.Dot(s,u)>0?h:-h,s),l.scaleAndAddToRef(h,i)}s.normalize()}for(let t=0;t<e.additiveAnimations.length;t++){const r=e.additiveAnimations[t];if(0===r.weight)continue;const a=o.jp.Vector3[2],l=o.jp.Vector3[3],h=o.jp.Quaternion[1];r.currentValue.decompose(l,h,a),l.multiplyToRef(n,l),o.P.LerpToRef(n,l,r.weight,n),s.multiplyToRef(h,h),o._f.SlerpToRef(s,h,r.weight,s),a.scaleAndAddToRef(r.weight,i)}const u=a?a._animationState.workValue:o.jp.Matrix[0].clone();return o.y3.ComposeToRef(n,s,i,u),u},k.x.prototype._processLateAnimationBindingsForQuaternions=function(e,t){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return t;const i=e.animations[0],n=e.originalValue;let s=t;if(0===e.totalWeight&&e.totalAdditiveWeight>0)s.copyFrom(n);else if(1===e.animations.length){if(o._f.SlerpToRef(n,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,r,a=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],r=[],i.push(n),r.push(t)}else{if(2===e.animations.length&&(o._f.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],r=[],a=e.totalWeight}for(let t=0;t<e.animations.length;t++){const n=e.animations[t];i.push(n.currentValue),r.push(n.weight/a)}let l=0;for(let e=0;e<i.length;)e?(l+=r[e],o._f.SlerpToRef(s,i[e],r[e]/l,s),e++):(o._f.SlerpToRef(i[e],i[e+1],r[e+1]/(r[e]+r[e+1]),t),s=t,l=r[e]+r[e+1],e+=2)}for(let t=0;t<e.additiveAnimations.length;t++){const i=e.additiveAnimations[t];0!==i.weight&&(s.multiplyToRef(i.currentValue,o.jp.Quaternion[0]),o._f.SlerpToRef(s,o.jp.Quaternion[0],i.weight,s))}return s},k.x.prototype._processLateAnimationBindings=function(){if(this._registeredForLateAnimationBindings.length){for(let e=0;e<this._registeredForLateAnimationBindings.length;e++){const t=this._registeredForLateAnimationBindings.data[e];for(const e in t._lateAnimationHolders){const i=t._lateAnimationHolders[e],n=i.animations[0],s=i.originalValue;if(null==s)continue;const r=D.f.AllowMatrixDecomposeForInterpolation&&s.m;let a=t[e];if(r)a=this._processLateAnimationBindingsForMatrices(i);else if(void 0!==s.w)a=this._processLateAnimationBindingsForQuaternions(i,a||o._f.Identity());else{let e=0,t=1;if(i.totalWeight<1)a=n&&s.scale?s.scale(1-i.totalWeight):n?s*(1-i.totalWeight):s.clone?s.clone():s;else if(n){t=i.totalWeight;const s=n.weight/t;a=1!==s?n.currentValue.scale?n.currentValue.scale(s):n.currentValue*s:n.currentValue,e=1}for(let n=e;n<i.animations.length;n++){const e=i.animations[n],s=e.weight/t;s&&(e.currentValue.scaleAndAddToRef?e.currentValue.scaleAndAddToRef(s,a):a+=e.currentValue*s)}for(let e=0;e<i.additiveAnimations.length;e++){const t=i.additiveAnimations[e],n=t.weight;n&&(t.currentValue.scaleAndAddToRef?t.currentValue.scaleAndAddToRef(n,a):a+=t.currentValue*n)}}t[e]=a}t._lateAnimationHolders={}}this._registeredForLateAnimationBindings.reset()}},z.N.prototype.copyAnimationRange=function(e,t,i,n=!1,s=null){0===this.animations.length&&(this.animations.push(new D.f(this.name,"_matrix",e.animations[0].framePerSecond,D.f.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));const r=e.animations[0].getRange(t);if(!r)return!1;const o=r.from,a=r.to,l=e.animations[0].getKeys(),h=e.length,c=e.getParent(),u=this.getParent(),d=n&&c&&h&&this.length&&h!==this.length,p=d&&u&&c?u.length/c.length:1,f=n&&!u&&s&&(1!==s.x||1!==s.y||1!==s.z),_=this.animations[0].getKeys();let m,g,v;for(let e=0,t=l.length;e<t;e++)m=l[e],m.frame>=o&&m.frame<=a&&(n?(v=m.value.clone(),d?(g=v.getTranslation(),v.setTranslation(g.scaleInPlace(p))):f&&s?(g=v.getTranslation(),v.setTranslation(g.multiplyInPlace(s))):v=m.value):v=m.value,_.push({frame:m.frame+i,value:v}));return this.animations[0].createRange(t,o+i,a+i),!0};class H{constructor(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=D.f.ANIMATIONLOOPMODE_CYCLE}}var X=i(1277);class j{constructor(){this._easingMode=j.EASINGMODE_EASEIN}setEasingMode(e){const t=Math.min(Math.max(e,0),2);this._easingMode=t}getEasingMode(){return this._easingMode}easeInCore(e){throw new Error("You must implement this method")}ease(e){switch(this._easingMode){case j.EASINGMODE_EASEIN:return this.easeInCore(e);case j.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}j.EASINGMODE_EASEIN=0,j.EASINGMODE_EASEOUT=1,j.EASINGMODE_EASEINOUT=2;class Y extends j{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class q extends j{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 K extends j{constructor(e=3,t=2){super(),this.bounces=e,this.bounciness=t}easeInCore(e){const t=Math.max(0,this.bounces);let i=this.bounciness;i<=1&&(i=1.001);const n=Math.pow(i,t),s=1-i,r=(1-n)/s+.5*n,o=e*r,a=Math.log(-o*(1-i)+1)/Math.log(i),l=Math.floor(a),h=l+1,c=(1-Math.pow(i,l))/(s*r),u=.5*(c+(1-Math.pow(i,h))/(s*r)),d=e-u,p=u-c;return-Math.pow(1/i,t-l)/(p*p)*(d-p)*(d+p)}}class $ extends j{easeInCore(e){return e*e*e}}class Q extends j{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const i=Math.max(0,this.oscillations),n=Math.max(0,this.springiness);return t=0==n?e:(Math.exp(n*e)-1)/(Math.exp(n)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)}}class Z extends j{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 J extends j{constructor(e=2){super(),this.power=e}easeInCore(e){const t=Math.max(0,this.power);return Math.pow(e,t)}}class ee extends j{easeInCore(e){return e*e}}class te extends j{easeInCore(e){return e*e*e*e}}class ie extends j{easeInCore(e){return e*e*e*e*e}}class ne extends j{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class se extends j{constructor(e=0,t=0,i=1,n=1){super(),this.x1=e,this.y1=t,this.x2=i,this.y2=n}easeInCore(e){return X.hr.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}var re=i(8117),oe=i(2323),ae=i(4173),le=i(2695);class he{constructor(e){this._path=e,this._onchange=new Array,this.value=0,this.animations=new Array}getPoint(){const e=this._path.getPointAtLengthPosition(this.value);return new o.P(e.x,0,e.y)}moveAhead(e=.002){return this.move(e),this}moveBack(e=.002){return this.move(-e),this}move(e){if(Math.abs(e)>1)throw"step size should be less than 1.";return this.value+=e,this._ensureLimits(),this._raiseOnChange(),this}_ensureLimits(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this}_raiseOnChange(){return this._onchange.forEach((e=>e(this))),this}onchange(e){return this._onchange.push(e),this}}var ce=i(1468),ue=i(7814),de=i(7257);class pe{constructor(e){this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},(e=e||A.l.LastCreatedScene)&&(this._scene=e,ue.D.audioEngine?(this._audioEngine=ue.D.audioEngine,this._audioEngine.canUseWebAudio&&this._audioEngine.audioContext&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))):de.w1.Warn("No audio engine initialized, failed to create an audio analyser"))}getFrequencyBinCount(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0}getByteFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs}getByteTimeDomainData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime}getFloatFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs}drawDebugCanvas(){if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=()=>{this.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc&&this._debugCanvasContext)){const e=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(let t=0;t<this.getFrequencyBinCount();t++){const i=e[t]/this.BARGRAPHAMPLITUDE,n=this.DEBUGCANVASSIZE.height*i,s=this.DEBUGCANVASSIZE.height-n-1,r=this.DEBUGCANVASSIZE.width/this.getFrequencyBinCount(),o=t/this.getFrequencyBinCount()*360;this._debugCanvasContext.fillStyle="hsl("+o+", 100%, 50%)",this._debugCanvasContext.fillRect(t*r,s,r,n)}}}stopDebugCanvas(){this._debugCanvas&&(this._registerFunc&&(this._scene.unregisterBeforeRender(this._registerFunc),this._registerFunc=null),document.body.removeChild(this._debugCanvas),this._debugCanvas=null,this._debugCanvasContext=null)}connectAudioNodes(e,t){this._audioEngine.canUseWebAudio&&(e.connect(this._webAudioAnalyser),this._webAudioAnalyser.connect(t))}dispose(){this._audioEngine.canUseWebAudio&&this._webAudioAnalyser.disconnect()}}var fe=i(6797);ue.D.AudioEngineFactory=(e,t,i)=>new _e(e,t,i);class _e{get audioContext(){return this._audioContextInitialized?this.unlocked||this._muteButton||this._displayMuteButton():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=!0,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new r.y$,this.onAudioLockedObservable=new r.y$,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!(0,fe.CG)())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const n=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{n&&n.canPlayType&&(n.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||n.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{n&&n.canPlayType&&n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){this._triggerRunningState()}_resumeAudioContext(){let e;return void 0!==this._audioContext.resume&&(e=this._audioContext.resume()),e||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,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,_.Y.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 e=".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) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",(()=>{this._triggerRunningState()}),!0),this._muteButton.addEventListener("click",(()=>{this._triggerRunningState()}),!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))}}var me=i(3642);class ge{constructor(e,t={}){this.id=-1,this._isInitialized=!1,(e=e||A.l.LastCreatedScene)&&(this._scene=e,this.soundCollection=new Array,this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){var e;(null===(e=ue.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&ue.D.audioEngine.audioContext&&(this._outputAudioNode=ue.D.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(ue.D.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(ue.D.audioEngine&&ue.D.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(),(null===(t=ue.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),e.soundTrackId&&(-1===e.soundTrackId?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);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){var t;(null===(t=ue.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(null===(e=ue.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToHRTF()}switchPanningModelToEqualPower(){var e;if(null===(e=ue.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToEqualPower()}connectToAnalyser(e){var t;this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=e,(null===(t=ue.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,ue.D.audioEngine.masterGain))}}var ve=i(2333);n.p.AddParser(ve.l.NAME_AUDIO,((e,t,i,n)=>{var s;let r,o=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let a=0,l=e.sounds.length;a<l;a++){const l=e.sounds[a];(null===(s=ue.D.audioEngine)||void 0===s?void 0:s.canUseWebAudio)?(l.url||(l.url=l.name),o[l.url]?i.sounds.push(me.$.Parse(l,t,n,o[l.url])):(r=me.$.Parse(l,t,n),o[l.url]=r,i.sounds.push(r))):i.sounds.push(new me.$(l.name,null,t))}o=[]})),Object.defineProperty(k.x.prototype,"mainSoundTrack",{get:function(){let e=this._getComponent(ve.l.NAME_AUDIO);return e||(e=new ye(this),this._addComponent(e)),this._mainSoundTrack||(this._mainSoundTrack=new ge(this,{mainTrack:!0})),this._mainSoundTrack},enumerable:!0,configurable:!0}),k.x.prototype.getSoundByName=function(e){let t;for(t=0;t<this.mainSoundTrack.soundCollection.length;t++)if(this.mainSoundTrack.soundCollection[t].name===e)return this.mainSoundTrack.soundCollection[t];if(this.soundTracks)for(let i=0;i<this.soundTracks.length;i++)for(t=0;t<this.soundTracks[i].soundCollection.length;t++)if(this.soundTracks[i].soundCollection[t].name===e)return this.soundTracks[i].soundCollection[t];return null},Object.defineProperty(k.x.prototype,"audioEnabled",{get:function(){let e=this._getComponent(ve.l.NAME_AUDIO);return e||(e=new ye(this),this._addComponent(e)),e.audioEnabled},set:function(e){let t=this._getComponent(ve.l.NAME_AUDIO);t||(t=new ye(this),this._addComponent(t)),e?t.enableAudio():t.disableAudio()},enumerable:!0,configurable:!0}),Object.defineProperty(k.x.prototype,"headphone",{get:function(){let e=this._getComponent(ve.l.NAME_AUDIO);return e||(e=new ye(this),this._addComponent(e)),e.headphone},set:function(e){let t=this._getComponent(ve.l.NAME_AUDIO);t||(t=new ye(this),this._addComponent(t)),e?t.switchAudioModeForHeadphones():t.switchAudioModeForNormalSpeakers()},enumerable:!0,configurable:!0}),Object.defineProperty(k.x.prototype,"audioListenerPositionProvider",{get:function(){let e=this._getComponent(ve.l.NAME_AUDIO);return e||(e=new ye(this),this._addComponent(e)),e.audioListenerPositionProvider},set:function(e){let t=this._getComponent(ve.l.NAME_AUDIO);if(t||(t=new ye(this),this._addComponent(t)),"function"!=typeof e)throw new Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");t.audioListenerPositionProvider=e},enumerable:!0,configurable:!0}),Object.defineProperty(k.x.prototype,"audioListenerRotationProvider",{get:function(){let e=this._getComponent(ve.l.NAME_AUDIO);return e||(e=new ye(this),this._addComponent(e)),e.audioListenerRotationProvider},set:function(e){let t=this._getComponent(ve.l.NAME_AUDIO);if(t||(t=new ye(this),this._addComponent(t)),"function"!=typeof e)throw new Error("The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3");t.audioListenerRotationProvider=e},enumerable:!0,configurable:!0}),Object.defineProperty(k.x.prototype,"audioPositioningRefreshRate",{get:function(){let e=this._getComponent(ve.l.NAME_AUDIO);return e||(e=new ye(this),this._addComponent(e)),e.audioPositioningRefreshRate},set:function(e){let t=this._getComponent(ve.l.NAME_AUDIO);t||(t=new ye(this),this._addComponent(t)),t.audioPositioningRefreshRate=e},enumerable:!0,configurable:!0});class ye{get audioEnabled(){return this._audioEnabled}get headphone(){return this._headphone}constructor(e){this.name=ve.l.NAME_AUDIO,this._audioEnabled=!0,this._headphone=!1,this.audioPositioningRefreshRate=500,this.audioListenerPositionProvider=null,this.audioListenerRotationProvider=null,this._cachedCameraDirection=new o.P,this._cachedCameraPosition=new o.P,this._lastCheck=0,this._invertMatrixTemp=new o.y3,this._cameraDirectionTemp=new o.P,(e=e||A.l.LastCreatedScene)&&(this.scene=e,e.soundTracks=new Array,e.sounds=new Array)}register(){this.scene._afterRenderStage.registerStep(ve.l.STEP_AFTERRENDER_AUDIO,this,this._afterRender)}rebuild(){}serialize(e){if(e.sounds=[],this.scene.soundTracks)for(let t=0;t<this.scene.soundTracks.length;t++){const i=this.scene.soundTracks[t];for(let t=0;t<i.soundCollection.length;t++)e.sounds.push(i.soundCollection[t].serialize())}}addFromContainer(e){e.sounds&&e.sounds.forEach((e=>{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}))}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach((e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].dispose()}disableAudio(){const e=this.scene;let t;for(this._audioEnabled=!1,ue.D.audioEngine&&ue.D.audioEngine.audioContext&&ue.D.audioEngine.audioContext.suspend(),t=0;t<e.mainSoundTrack.soundCollection.length;t++)e.mainSoundTrack.soundCollection[t].pause();if(e.soundTracks)for(t=0;t<e.soundTracks.length;t++)for(let i=0;i<e.soundTracks[t].soundCollection.length;i++)e.soundTracks[t].soundCollection[i].pause()}enableAudio(){const e=this.scene;let t;for(this._audioEnabled=!0,ue.D.audioEngine&&ue.D.audioEngine.audioContext&&ue.D.audioEngine.audioContext.resume(),t=0;t<e.mainSoundTrack.soundCollection.length;t++)e.mainSoundTrack.soundCollection[t].isPaused&&e.mainSoundTrack.soundCollection[t].play();if(e.soundTracks)for(t=0;t<e.soundTracks.length;t++)for(let i=0;i<e.soundTracks[t].soundCollection.length;i++)e.soundTracks[t].soundCollection[i].isPaused&&e.soundTracks[t].soundCollection[i].play()}switchAudioModeForHeadphones(){const e=this.scene;if(this._headphone=!0,e.mainSoundTrack.switchPanningModelToHRTF(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToHRTF()}switchAudioModeForNormalSpeakers(){const e=this.scene;if(this._headphone=!1,e.mainSoundTrack.switchPanningModelToEqualPower(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToEqualPower()}_afterRender(){const e=G.F.Now;if(this._lastCheck&&e-this._lastCheck<this.audioPositioningRefreshRate)return;this._lastCheck=e;const t=this.scene;if(!this._audioEnabled||!t._mainSoundTrack||!t.soundTracks||0===t._mainSoundTrack.soundCollection.length&&1===t.soundTracks.length)return;const i=ue.D.audioEngine;if(i&&i.audioContext){let e,n=t.activeCamera;if(t.activeCameras&&t.activeCameras.length>0&&(n=t.activeCameras[0]),this.audioListenerPositionProvider){const e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else n?this._cachedCameraPosition.equals(n.globalPosition)||(this._cachedCameraPosition.copyFrom(n.globalPosition),i.audioContext.listener.setPosition(n.globalPosition.x,n.globalPosition.y,n.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else n?(n.rigCameras&&n.rigCameras.length>0&&(n=n.rigCameras[0]),n.getViewMatrix().invertToRef(this._invertMatrixTemp),o.P.TransformNormalToRef(ye._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);for(e=0;e<t.mainSoundTrack.soundCollection.length;e++){const i=t.mainSoundTrack.soundCollection[e];i.useCustomAttenuation&&i.updateDistanceFromListener()}if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(let i=0;i<t.soundTracks[e].soundCollection.length;i++){const n=t.soundTracks[e].soundCollection[i];n.useCustomAttenuation&&n.updateDistanceFromListener()}}}}ye._CameraDirection=new o.P(0,0,-1),me.$._SceneComponentInitialization=e=>{let t=e._getComponent(ve.l.NAME_AUDIO);t||(t=new ye(e),e._addComponent(t))};var xe=i(710),be=i(9472),Te=i(3956);class Se{constructor(e){this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,(e=e||A.l.LastCreatedScene)&&(this._scene=e,this.animationParameters=new o.Lt(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 Se(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,n=30){this.animationParameters=new o.Lt(e,t,i,n)}dispose(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){Te.p4.Clone((()=>e),this)}serialize(){return Te.p4.Serialize(this)}parse(e,t,i){Te.p4.Parse((()=>this),e,t,i)}}(0,be.gn)([(0,Te.oU)(),(0,Te.wz)("_markSubMeshesAsAttributesDirty")],Se.prototype,"texture",void 0),(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markSubMeshesAsAttributesDirty")],Se.prototype,"isEnabled",void 0),(0,be.gn)([(0,Te.qC)()],Se.prototype,"animationParameters",void 0),(0,be.gn)([(0,Te.qC)()],Se.prototype,"time",void 0);var Ee=i(7647),Ce=i(2262),Ae=i(2655);class Pe{constructor(e,t){this._scene=e,this._mesh=t}async bakeVertexData(e){if(!this._mesh.skeleton)throw new Error("No skeleton in this mesh.");const t=this._mesh.skeleton.bones.length,i=e.reduce(((e,t)=>e+t.to-t.from+1),0);if(isNaN(i))throw new Error("Invalid animation ranges.");let n=0;const s=new Float32Array(4*(t+1)*4*i);this._scene.stopAnimation(this._mesh),this._mesh.skeleton.returnToRest();for(const t of e)for(let e=t.from;e<=t.to;e++)await this._executeAnimationFrame(s,e,n++);return s}async _executeAnimationFrame(e,t,i){return new Promise(((n,s)=>{this._scene.beginAnimation(this._mesh.skeleton,t,t,!1,1,(()=>{const t=this._mesh.skeleton.getTransformMatrices(this._mesh);e.set(t,i*t.length),n()}))}))}textureFromBakedVertexData(e){if(!this._mesh.skeleton)throw new Error("No skeleton in this mesh.");const t=this._mesh.skeleton.bones.length,i=Ee.l.CreateRGBATexture(e,4*(t+1),e.length/(4*(t+1)*4),this._scene,!1,!1,Ce.x.NEAREST_NEAREST,1);return i.name="VAT"+this._mesh.skeleton.name,i}serializeBakedVertexDataToObject(e){if(!this._mesh.skeleton)throw new Error("No skeleton in this mesh.");const t=this._mesh.skeleton.bones.length,i=4*(t+1),n=e.length/(4*(t+1)*4);return{vertexData:(0,Ae.Gh)(e),width:i,height:n}}loadBakedVertexDataFromObject(e){return new Float32Array((0,Ae.HQ)(e.vertexData))}serializeBakedVertexDataToJSON(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))}loadBakedVertexDataFromJSON(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))}}var Re=i(1903),Me=i(1341);class Ie{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Re.kD.POINTERDOWN?e.type===Re.kD.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=G.F.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,n=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*n,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=null!=e?e:G.F.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha)<Me.kn}_userIsZooming(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset}_shouldAnimationStopForInteraction(){if(!this._attachedCamera)return!1;let e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()}_applyUserInteraction(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=G.F.Now)}_userIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}class De{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;const t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add((e=>{if(!e)return;e.computeWorldMatrix(!0);const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t})):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))}))}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return!!this._attachedCamera&&this._attachedCamera.radius===e&&!this._radiusIsAnimating}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(De.EasingFunction.setEasingMode(De.EasingMode),this._radiusBounceTransition=D.f.CreateAnimation("radius",D.f.ANIMATIONTYPE_FLOAT,60,De.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=D.f.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()}}De.EasingFunction=new q(.3),De.EasingMode=j.EASINGMODE_EASEOUT;class Oe{constructor(){this.onTargetFramingAnimationEndObservable=new r.y$,this._mode=Oe.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();Oe.EasingFunction.setEasingMode(Oe.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Re.kD.POINTERDOWN?e.type===Re.kD.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&this.zoomOnMesh(e,void 0,(()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const n=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(n.minimumWorld,n.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const n=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(n.min,n.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const n=new o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t<e.length;t++){const i=e[t].getHierarchyBoundingVectors(!0);o.P.CheckExtends(i.min,n,s),o.P.CheckExtends(i.max,n,s)}this.zoomOnBoundingInfo(n,s,t,i)}zoomOnBoundingInfo(e,t,i=!1,n=null){let s;if(!this._attachedCamera)return;const r=e.y,a=r+(t.y-r)*this._positionScale,l=t.subtract(e).scale(.5);if(i)s=new o.P(0,a,0);else{const t=e.add(l);s=new o.P(t.x,a,t.z)}this._vectorTransition||(this._vectorTransition=D.f.CreateAnimation("target",D.f.ANIMATIONTYPE_VECTOR3,60,Oe.EasingFunction)),this._betaIsAnimating=!0;let h=D.f.TransitionTo("target",s,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);h&&this._animatables.push(h);let c=0;if(this._mode===Oe.FitFrustumSidesMode){const i=this._calculateLowerRadiusFromModelBoundingSphere(e,t);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=l.length()+this._attachedCamera.minZ),c=i}else this._mode===Oe.IgnoreBoundsSizeMode&&(c=this._calculateLowerRadiusFromModelBoundingSphere(e,t),this.autoCorrectCameraLimitsAndSensibility&&null===this._attachedCamera.lowerRadiusLimit&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){const i=t.subtract(e).length();this._attachedCamera.panningSensibility=5e3/i,this._attachedCamera.wheelPrecision=100/c}this._radiusTransition||(this._radiusTransition=D.f.CreateAnimation("radius",D.f.ANIMATIONTYPE_FLOAT,60,Oe.EasingFunction)),h=D.f.TransitionTo("radius",c,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,(()=>{this.stopAllAnimations(),n&&n(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),h&&this._animatables.push(h)}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=t.subtract(e).length(),n=this._getFrustumSlope(),s=.5*i*this._radiusScale,r=s*Math.sqrt(1+1/(n.x*n.x)),o=s*Math.sqrt(1+1/(n.y*n.y));let a=Math.max(r,o);const l=this._attachedCamera;return l?(l.lowerRadiusLimit&&this._mode===Oe.IgnoreBoundsSizeMode&&(a=a<l.lowerRadiusLimit?l.lowerRadiusLimit:a),l.upperRadiusLimit&&(a=a>l.upperRadiusLimit?l.upperRadiusLimit:a),a):0}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=G.F.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=D.f.CreateAnimation("beta",D.f.ANIMATIONTYPE_FLOAT,60,Oe.EasingFunction));const e=D.f.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_getFrustumSlope(){const e=this._attachedCamera;if(!e)return o.FM.Zero();const t=e.getScene().getEngine().getAspectRatio(e),i=Math.tan(e.fov/2),n=i*t;return new o.FM(n,i)}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=G.F.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}Oe.EasingFunction=new Z,Oe.EasingMode=j.EASINGMODE_EASEINOUT,Oe.IgnoreBoundsSizeMode=0,Oe.FitFrustumSidesMode=1;class we{constructor(e,t=new o.P,i=0,n=!1){this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=n}}class Ne{constructor(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new we(o.P.Up()),new we(o.P.Down()),new we(o.P.Left()),new we(o.P.Right()),new we(o.P.Forward()),new we(o.P.Forward().scaleInPlace(-1))],this._tmpMatrix=new o.y3,this._tmpVector=new o.P,this._zeroVector=o.P.Zero(),this._lookAtTmpMatrix=new o.y3}init(){}_closestFace(e){return this._faceVectors.forEach((t=>{this._target.rotationQuaternion||(this._target.rotationQuaternion=o._f.RotationYawPitchRoll(this._target.rotation.y,this._target.rotation.x,this._target.rotation.z)),this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix),o.P.TransformCoordinatesToRef(t.direction,this._tmpMatrix,t.rotatedDirection),t.diff=o.P.GetAngleBetweenVectors(t.rotatedDirection,e,o.P.Cross(t.rotatedDirection,e))})),this._faceVectors.reduce(((e,t)=>e.ignore?t:t.ignore||e.diff<t.diff?e:t),this._faceVectors[0])}_lookAtToRef(e,t=new o.P(0,1,0),i){o.y3.LookAtLHToRef(this._zeroVector,e,t,this._lookAtTmpMatrix),this._lookAtTmpMatrix.invert(),o._f.FromRotationMatrixToRef(this._lookAtTmpMatrix,i)}attach(e){this._target=e,this._scene=this._target.getScene(),this._onRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(!this._scene.activeCamera)return;let t=this._scene.activeCamera.position;this._scene.activeCamera.devicePosition&&(t=this._scene.activeCamera.devicePosition);const i=this._closestFace(t.subtract(e.position));this._scene.activeCamera.leftCamera?this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix):this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix),o.P.TransformCoordinatesToRef(o.P.Up(),this._tmpMatrix,this._tmpVector),this._faceVectors.forEach((e=>{i.direction.x&&e.direction.x&&(e.ignore=!0),i.direction.y&&e.direction.y&&(e.ignore=!0),i.direction.z&&e.direction.z&&(e.ignore=!0)}));const n=this._closestFace(this._tmpVector);this._faceVectors.forEach((e=>{e.ignore=!1})),this._ui.position.copyFrom(e.position),i.direction.x&&(i.rotatedDirection.scaleToRef(e.scaling.x/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.y&&(i.rotatedDirection.scaleToRef(e.scaling.y/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.z&&(i.rotatedDirection.scaleToRef(e.scaling.z/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),this._ui.rotationQuaternion||(this._ui.rotationQuaternion=o._f.RotationYawPitchRoll(this._ui.rotation.y,this._ui.rotation.x,this._ui.rotation.z)),i.rotatedDirection.scaleToRef(-1,this._tmpVector),this._lookAtToRef(this._tmpVector,n.rotatedDirection,this._ui.rotationQuaternion),n.direction.x&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.x/2,this._tmpVector),n.direction.y&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.y/2,this._tmpVector),n.direction.z&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.z/2,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)}))}detach(){this._scene.onBeforeRenderObservable.remove(this._onRenderObserver)}}var Fe=i(1809),Le=i(9778);class Be{constructor(){this._startDistance=0,this._initialScale=new o.P(0,0,0),this._targetScale=new o.P(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new Le.M({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new Le.M({}),this._dragBehaviorB.moveAttached=!1}get name(){return"MultiPointerScale"}init(){}_getCurrentDistance(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()}attach(e){this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorA.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorB.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const e=this._getCurrentDistance()/this._startDistance;this._initialScale.scaleToRef(e,this._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const t=this._targetScale.subtract(e.scaling).scaleInPlace(.1);t.length()>.01&&e.scaling.addInPlace(t)}}))}detach(){this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragStartObservable.clear(),e.onDragObservable.clear(),this._ownerNode.removeBehavior(e)}))}}var Ue=i(498),Ve=i(120),ke=i(6981),Ge=i(4095),ze=i(4184),We=i(5203);class He{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=o.P.Zero(),this.poleTargetPosition=o.P.Zero(),this.poleTargetLocalOffset=o.P.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=o._f.Identity(),this._bone1Mat=o.y3.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=o.P.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const n=t.getParent();if(!n)return this._notEnoughInformation=!0,void _.Y.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=n,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void _.Y.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e;const s=t.getPosition();if(t.getAbsoluteTransform().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,s.x>s.y&&s.x>s.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),n=this._bone1.getAbsolutePosition(e);this._bone2Length=o.P.Distance(t,i),this._bone1Length=o.P.Distance(i,n)}else{e.computeWorldMatrix(!0);const t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;const i=this._bone2.getAbsolutePosition(e),n=this._bone1.getAbsolutePosition(e);this._bone1Length=o.P.Distance(i,n)}this._bone1.getRotationMatrixToRef(We.T.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=He._TmpMats[0],n=He._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&o.P.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const s=He._TmpVecs[0],r=He._TmpVecs[1],a=He._TmpVecs[2],l=He._TmpVecs[3],h=He._TmpVecs[4],c=He._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,h),0==h.x&&0==h.y&&0==h.z?h.y=1:h.normalize(),e.subtractToRef(s,l),l.normalize(),o.P.CrossToRef(l,h,r),r.normalize(),o.P.CrossToRef(l,r,a),a.normalize(),o.y3.FromXYZAxesToRef(a,l,r,i);const u=this._bone1Length,d=this._bone2Length;let p=o.P.Distance(s,e);this._maxReach>0&&(p=Math.min(this._maxReach,p));let f=(d*d+p*p-u*u)/(2*d*p),_=(p*p+u*u-d*d)/(2*p*u);f>1&&(f=1),_>1&&(_=1),f<-1&&(f=-1),_<-1&&(_=-1);const m=Math.acos(f),g=Math.acos(_);let v=-m-g;if(this._rightHandedSystem)o.y3.RotationYawPitchRollToRef(0,0,this._adjustRoll,n),n.multiplyToRef(i,i),o.y3.RotationAxisToRef(this._bendAxis,g,n),n.multiplyToRef(i,i);else{const e=He._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,o.y3.RotationAxisToRef(e,-g,n),n.multiplyToRef(i,i)}this.poleAngle&&(o.y3.RotationAxisToRef(l,this.poleAngle,n),i.multiplyToRef(n,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||o._f.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),o._f.FromRotationMatrixToRef(i,c),o._f.SlerpToRef(this._bone1Quat,c,this.slerpAmount,this._bone1Quat),v=this._bone2Ang*(1-this.slerpAmount)+v*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,We.T.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,We.T.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,v,We.T.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=v}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new o._f),e.getRotationQuaternionToRef(We.T.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}He._TmpVecs=[o.P.Zero(),o.P.Zero(),o.P.Zero(),o.P.Zero(),o.P.Zero(),o.P.Zero()],He._TmpQuat=o._f.Identity(),He._TmpMats=[o.y3.Identity(),o.y3.Identity()];var Xe=i(5860);class je{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,n){if(this.upAxis=o.P.Up(),this.upAxisSpace=We.T.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=o._f.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=o.P.Forward(),this.mesh=e,this.bone=t,this.target=i,n&&(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll),null!=n.maxYaw?this.maxYaw=n.maxYaw:this.maxYaw=Math.PI,null!=n.minYaw?this.minYaw=n.minYaw:this.minYaw=-Math.PI,null!=n.maxPitch?this.maxPitch=n.maxPitch:this.maxPitch=Math.PI,null!=n.minPitch?this.minPitch=n.minPitch:this.minPitch=-Math.PI,null!=n.slerpAmount&&(this.slerpAmount=n.slerpAmount),null!=n.upAxis&&(this.upAxis=n.upAxis),null!=n.upAxisSpace&&(this.upAxisSpace=n.upAxisSpace),null!=n.yawAxis||null!=n.pitchAxis)){let e=We.RD.Y,t=We.RD.X;null!=n.yawAxis&&(e=n.yawAxis.clone(),e.normalize()),null!=n.pitchAxis&&(t=n.pitchAxis.clone(),t.normalize());const i=o.P.Cross(t,e);this._transformYawPitch=o.y3.Identity(),o.y3.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}t.getParent()||this.upAxisSpace!=We.T.BONE||(this.upAxisSpace=We.T.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);const e=this.bone,t=je._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const n=je._TmpMats[0],s=je._TmpMats[1],r=this.mesh,a=e.getParent(),l=je._TmpVecs[1];l.copyFrom(this.upAxis),this.upAxisSpace==We.T.BONE&&a?(this._transformYawPitch&&o.P.TransformCoordinatesToRef(l,this._transformYawPitchInv,l),a.getDirectionToRef(l,this.mesh,l)):this.upAxisSpace==We.T.LOCAL&&(r.getDirectionToRef(l,l),1==r.scaling.x&&1==r.scaling.y&&1==r.scaling.z||l.normalize());let h=!1,c=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(h=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(c=!0),h||c){const e=je._TmpMats[2],n=je._TmpMats[3];if(this.upAxisSpace==We.T.BONE&&1==l.y&&a)a.getRotationMatrixToRef(We.T.WORLD,this.mesh,e);else if(this.upAxisSpace!=We.T.LOCAL||1!=l.y||a){let t=je._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&o.P.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),a?a.getDirectionToRef(t,this.mesh,t):r.getDirectionToRef(t,t);const i=o.P.Cross(l,t);i.normalize(),t=o.P.Cross(i,l),o.y3.FromXYZAxesToRef(i,l,t,e)}else e.copyFrom(r.getWorldMatrix());e.invertToRef(n);let s=null;if(c){const r=je._TmpVecs[3];i.subtractToRef(t,r),o.P.TransformCoordinatesToRef(r,n,r),s=Math.sqrt(r.x*r.x+r.z*r.z);const a=Math.atan2(r.y,s);let l=a;a>this._maxPitch?(r.y=this._maxPitchTan*s,l=this._maxPitch):a<this._minPitch&&(r.y=this._minPitchTan*s,l=this._minPitch),a!=l&&(o.P.TransformCoordinatesToRef(r,e,r),r.addInPlace(t),i=r)}if(h){const r=je._TmpVecs[4];i.subtractToRef(t,r),o.P.TransformCoordinatesToRef(r,n,r);const a=Math.atan2(r.x,r.z);let l=a;if((a>this._maxYaw||a<this._minYaw)&&(null==s&&(s=Math.sqrt(r.x*r.x+r.z*r.z)),this._yawRange>Math.PI?this._isAngleBetween(a,this._maxYaw,this._midYawConstraint)?(r.z=this._maxYawCos*s,r.x=this._maxYawSin*s,l=this._maxYaw):this._isAngleBetween(a,this._midYawConstraint,this._minYaw)&&(r.z=this._minYawCos*s,r.x=this._minYawSin*s,l=this._minYaw):a>this._maxYaw?(r.z=this._maxYawCos*s,r.x=this._maxYawSin*s,l=this._maxYaw):a<this._minYaw&&(r.z=this._minYawCos*s,r.x=this._minYawSin*s,l=this._minYaw)),this._slerping&&this._yawRange>Math.PI){const e=je._TmpVecs[8];e.copyFrom(We.RD.Z),this._transformYawPitch&&o.P.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);const t=je._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),o.P.TransformCoordinatesToRef(e,t,e),o.P.TransformCoordinatesToRef(e,n,e);const i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,a)>this._getAngleBetween(i,this._midYawConstraint)){null==s&&(s=Math.sqrt(r.x*r.x+r.z*r.z));const e=this._getAngleBetween(i,this._maxYaw);this._getAngleBetween(i,this._minYaw)<e?(l=i+.75*Math.PI,r.z=Math.cos(l)*s,r.x=Math.sin(l)*s):(l=i-.75*Math.PI,r.z=Math.cos(l)*s,r.x=Math.sin(l)*s)}}a!=l&&(o.P.TransformCoordinatesToRef(r,e,r),r.addInPlace(t),i=r)}}const u=je._TmpVecs[5],d=je._TmpVecs[6],p=je._TmpVecs[7],f=je._TmpQuat;i.subtractToRef(t,u),u.normalize(),o.P.CrossToRef(l,u,d),d.normalize(),o.P.CrossToRef(u,d,p),p.normalize(),o.y3.FromXYZAxesToRef(d,p,u,n),0===d.x&&0===d.y&&0===d.z||0===p.x&&0===p.y&&0===p.z||0===u.x&&0===u.y&&0===u.z||((this.adjustYaw||this.adjustPitch||this.adjustRoll)&&(o.y3.RotationYawPitchRollToRef(this.adjustYaw,this.adjustPitch,this.adjustRoll,s),s.multiplyToRef(n,n)),this.slerpAmount<1?(this._slerping||this.bone.getRotationQuaternionToRef(We.T.WORLD,this.mesh,this._boneQuat),this._transformYawPitch&&this._transformYawPitch.multiplyToRef(n,n),o._f.FromRotationMatrixToRef(n,f),o._f.SlerpToRef(this._boneQuat,f,this.slerpAmount,this._boneQuat),this.bone.setRotationQuaternion(this._boneQuat,We.T.WORLD,this.mesh),this._slerping=!0):(this._transformYawPitch&&this._transformYawPitch.multiplyToRef(n,n),this.bone.setRotationMatrix(n,We.T.WORLD,this.mesh),this._slerping=!1),this._updateLinkedTransformRotation())}_getAngleDiff(e,t){let i=t-e;return i%=2*Math.PI,i>Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){let i=0;return i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t,i>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&e<i)return!0}else if(e>i&&e<t)return!0;return!1}_updateLinkedTransformRotation(){const e=this.bone;e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new o._f),e.getRotationQuaternionToRef(We.T.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}je._TmpVecs=Xe.B.BuildArray(10,o.P.Zero),je._TmpQuat=o._f.Identity(),je._TmpMats=Xe.B.BuildArray(5,o.y3.Identity);var Ye=i(5047),qe=i(708),Ke=i(7698);class $e{constructor(e,t,i=3){this._engine=e,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)}_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){return this._engine.readFromStorageBuffer(this._buffer,e,t,i)}dispose(){const e=this._engine._storageBuffers,t=e.indexOf(this);-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}}var Qe=i(9563);class Ze{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=de.w1.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let n=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=r=>{var o,a;const l=r.event,h="touch"===l.pointerType;if(t.isInVRExclusivePointerMode)return;if(r.type!==Re.kD.POINTERMOVE&&-1===this.buttons.indexOf(l.button))return;const c=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){const e=l.movementX,t=l.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(r.type!==Re.kD.POINTERDOWN&&h&&(null===(o=this._pointA)||void 0===o?void 0:o.pointerId)!==l.pointerId&&(null===(a=this._pointB)||void 0===a?void 0:a.pointerId)!==l.pointerId)return;if(r.type!==Re.kD.POINTERDOWN||-1!==this._currentActiveButton&&!h)if(r.type===Re.kD.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(r.type!==Re.kD.POINTERUP||this._currentActiveButton!==l.button&&!h){if(r.type===Re.kD.POINTERMOVE)if(e||l.preventDefault(),this._pointA&&null===this._pointB){const e=l.clientX-this._pointA.x,t=l.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=l.clientX,this._pointA.y=l.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;e.x=l.clientX,e.y=l.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,o=t*t+i*i,a={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:r.type};this.onMultiTouch(this._pointA,this._pointB,n,o,s,a),s=a,n=o}}else{try{null==c||c.releasePointerCapture(l.pointerId)}catch(e){}h||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==n||s)&&(this.onMultiTouch(this._pointA,this._pointB,n,0,s,null),n=0,s=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else{try{null==c||c.setPointerCapture(l.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else{if(null!==this._pointB)return;this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType}}-1!==this._currentActiveButton||h||(this._currentActiveButton=l.button),this.onButtonDown(l),e||(l.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Re.kD.POINTERDOWN|Re.kD.POINTERUP|Re.kD.POINTERMOVE|Re.kD.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,n=0,s=null,this.onLostFocus()},this._contextMenuBind=this.onContextMenu.bind(this),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const r=this.camera.getScene().getEngine().getHostWindow();r&&de.w1.RegisterTopRootEvents(r,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&de.w1.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,n,s,r){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}(0,be.gn)([(0,Te.qC)()],Ze.prototype,"buttons",void 0);var Je=i(1181);class et{constructor(e,t){this.x=e,this.y=t}}class tt{get isConnected(){return this._isConnected}constructor(e,t,i,n=0,s=1,r=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=tt.GAMEPAD,this._leftStickAxisX=n,this._leftStickAxisY=s,this._rightStickAxisX=r,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}tt.GAMEPAD=0,tt.GENERIC=1,tt.XBOX=2,tt.POSE_ENABLED=3,tt.DUALSHOCK=4;class it extends tt{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new r.y$,this.onButtonUpObservable=new r.y$,this.type=tt.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e<this._buttons.length;e++)this._buttons[e]=this._setButtonValue(this.browserGamepad.buttons[e].value,this._buttons[e],e)}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear()}}class nt{constructor(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40,this._yAxisScale=1}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==tt.POSE_ENABLED&&(this.gamepad&&e.type!==tt.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(tt.XBOX)}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}(0,be.gn)([(0,Te.qC)()],nt.prototype,"gamepadRotationSensibility",void 0),(0,be.gn)([(0,Te.qC)()],nt.prototype,"gamepadMoveSensibility",void 0),Je.u.ArcRotateCameraGamepadInput=nt;var st=i(2925);class rt{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=de.w1.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===st.OG.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t<this._keys.length;t++){const i=this._keys[t];-1!==this.keysLeft.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX-=1/this.panningSensibility:e.inertialAlphaOffset-=this.angularSpeed:-1!==this.keysUp.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset+=1/this.zoomingSensibility:e.inertialBetaOffset-=this.angularSpeed:-1!==this.keysRight.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX+=1/this.panningSensibility:e.inertialAlphaOffset+=this.angularSpeed:-1!==this.keysDown.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset-=1/this.zoomingSensibility:e.inertialBetaOffset+=this.angularSpeed:-1!==this.keysReset.indexOf(i)&&e.useInputToRestoreState&&e.restoreState()}}}getClassName(){return"ArcRotateCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}}(0,be.gn)([(0,Te.qC)()],rt.prototype,"keysUp",void 0),(0,be.gn)([(0,Te.qC)()],rt.prototype,"keysDown",void 0),(0,be.gn)([(0,Te.qC)()],rt.prototype,"keysLeft",void 0),(0,be.gn)([(0,Te.qC)()],rt.prototype,"keysRight",void 0),(0,be.gn)([(0,Te.qC)()],rt.prototype,"keysReset",void 0),(0,be.gn)([(0,Te.qC)()],rt.prototype,"panningSensibility",void 0),(0,be.gn)([(0,Te.qC)()],rt.prototype,"zoomingSensibility",void 0),(0,be.gn)([(0,Te.qC)()],rt.prototype,"useAltToZoom",void 0),(0,be.gn)([(0,Te.qC)()],rt.prototype,"angularSpeed",void 0),Je.u.ArcRotateCameraKeyboardMoveInput=rt;var ot=i(142),at=i(2272),lt=i(1128);class ht{constructor(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._inertialPanning=o.P.Zero()}_computeDeltaFromMouseWheelLegacyEvent(e,t){let i=0;const n=.01*e*this.wheelDeltaPercentage*t;return i=e>0?n/(1+this.wheelDeltaPercentage):n*(1+this.wheelDeltaPercentage),i}attachControl(e){e=de.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Re.kD.POINTERWHEEL)return;const i=t.event;let n=0;const s=i.deltaMode===at.G.DOM_DELTA_LINE?40:1,r=-i.deltaY*s;if(this.customComputeDeltaFromMouseWheel)n=this.customComputeDeltaFromMouseWheel(r,this,i);else if(this.wheelDeltaPercentage){if(n=this._computeDeltaFromMouseWheelLegacyEvent(r,this.camera.radius),n>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+n;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=lt.R.Clamp(e,0,Number.MAX_VALUE),n=this._computeDeltaFromMouseWheelLegacyEvent(r,e)}}else n=r/(40*this.wheelPrecision);n&&(this.zoomToMouseLocation&&this._hitPlane?this._zoomToMouse(n):this.camera.inertialRadiusOffset+=n),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Re.kD.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=ot.J.FromPositionAndNormal(e.target,t)}_getPosition(){var e;const t=this.camera,i=t.getScene(),n=i.createPickingRay(i.pointerX,i.pointerY,o.y3.Identity(),t,!1);let s=0;return this._hitPlane&&(s=null!==(e=n.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),n.origin.addInPlace(n.direction.scaleInPlace(s))}_zoomToMouse(e){var t,i;const n=this.camera,s=1-n.inertia;if(n.lowerRadiusLimit){const i=null!==(t=n.lowerRadiusLimit)&&void 0!==t?t:0;n.radius-(n.inertialRadiusOffset+e)/s<i&&(e=(n.radius-i)*s-n.inertialRadiusOffset)}if(n.upperRadiusLimit){const t=null!==(i=n.upperRadiusLimit)&&void 0!==i?i:0;n.radius-(n.inertialRadiusOffset+e)/s>t&&(e=(n.radius-t)*s-n.inertialRadiusOffset)}const r=e/s/n.radius,a=this._getPosition(),l=o.jp.Vector3[6];a.subtractToRef(n.target,l),l.scaleInPlace(r),l.scaleInPlace(s),this._inertialPanning.addInPlace(l),n.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)<Me.kn&&(e.x=0),Math.abs(e.y)<Me.kn&&(e.y=0),Math.abs(e.z)<Me.kn&&(e.z=0)}}(0,be.gn)([(0,Te.qC)()],ht.prototype,"wheelPrecision",void 0),(0,be.gn)([(0,Te.qC)()],ht.prototype,"zoomToMouseLocation",void 0),(0,be.gn)([(0,Te.qC)()],ht.prototype,"wheelDeltaPercentage",void 0),Je.u.ArcRotateCameraMouseWheelInput=ht;class ct extends Ze{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.pinchZoom=!0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this.pinchInwards=!0,this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(0!==this.panningSensibility&&e&&t){const i=t.x-e.x,n=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=n/this.panningSensibility}}_computePinchZoom(e,t){const i=this.camera.radius||ct.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(t-e)*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,n,s,r){0===i&&null===s||0===n&&null===r||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,n),this._computeMultiTouchPanning(s,r)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(n)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,n),this._isPinching=!0):this._computeMultiTouchPanning(s,r)):this.multiTouchPanning?this._computeMultiTouchPanning(s,r):this.pinchZoom&&this._computePinchZoom(i,n))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}ct.MinimumRadiusForPinch=.001,(0,be.gn)([(0,Te.qC)()],ct.prototype,"buttons",void 0),(0,be.gn)([(0,Te.qC)()],ct.prototype,"angularSensibilityX",void 0),(0,be.gn)([(0,Te.qC)()],ct.prototype,"angularSensibilityY",void 0),(0,be.gn)([(0,Te.qC)()],ct.prototype,"pinchPrecision",void 0),(0,be.gn)([(0,Te.qC)()],ct.prototype,"pinchDeltaPercentage",void 0),(0,be.gn)([(0,Te.qC)()],ct.prototype,"useNaturalPinchZoom",void 0),(0,be.gn)([(0,Te.qC)()],ct.prototype,"pinchZoom",void 0),(0,be.gn)([(0,Te.qC)()],ct.prototype,"panningSensibility",void 0),(0,be.gn)([(0,Te.qC)()],ct.prototype,"multiTouchPanning",void 0),(0,be.gn)([(0,Te.qC)()],ct.prototype,"multiTouchPanAndZoom",void 0),Je.u.ArcRotateCameraPointersInput=ct;class ut extends Je.p{constructor(e){super(e)}addMouseWheel(){return this.add(new ht),this}addPointers(){return this.add(new ct),this}addKeyboard(){return this.add(new rt),this}}ut.prototype.addVRDeviceOrientation=function(){return this.add(new dt),this};class dt{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=this._onOrientationEvent.bind(this)}attachControl(e){e=de.w1.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):de.w1.Warn("Permission not granted.")})).catch((e=>{de.w1.Error(e)})):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*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"}}Je.u.ArcRotateCameraVRDeviceOrientationInput=dt;class pt{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=de.w1.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===st.OG.KEYDOWN)-1===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)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==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)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t<this._keys.length;t++){const i=this._keys[t],n=e._computeLocalCameraSpeed();-1!==this.keysForward.indexOf(i)?e._localDirection.copyFromFloats(0,0,n):-1!==this.keysBackward.indexOf(i)?e._localDirection.copyFromFloats(0,0,-n):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,n,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,-n,0):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(n,0,0):-1!==this.keysLeft.indexOf(i)&&e._localDirection.copyFromFloats(-n,0,0),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),o.P.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}}(0,be.gn)([(0,Te.qC)()],pt.prototype,"keysForward",void 0),(0,be.gn)([(0,Te.qC)()],pt.prototype,"keysBackward",void 0),(0,be.gn)([(0,Te.qC)()],pt.prototype,"keysUp",void 0),(0,be.gn)([(0,Te.qC)()],pt.prototype,"keysDown",void 0),(0,be.gn)([(0,Te.qC)()],pt.prototype,"keysRight",void 0),(0,be.gn)([(0,Te.qC)()],pt.prototype,"keysLeft",void 0),Je.u.FlyCameraKeyboardInput=pt;class ft{constructor(){this.buttons=[0,1,2],this.buttonsYaw=[-1,0,1],this.buttonsPitch=[-1,0,1],this.buttonsRoll=[2],this.activeButton=-1,this.angularSensibility=1e3,this._previousPosition=null}attachControl(e){e=de.w1.BackCompatCameraNoPreventDefault(arguments),this._noPreventDefault=e,this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver((e=>{this._pointerInput(e)}),Re.kD.POINTERDOWN|Re.kD.POINTERUP|Re.kD.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,i=this.camera.getEngine();if(i.isInVRExclusivePointerMode)return;if(!this.touchEnabled&&"touch"===t.pointerType)return;if(e.type!==Re.kD.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;const n=t.target;if(e.type===Re.kD.POINTERDOWN){try{null==n||n.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===Re.kD.POINTERUP){try{null==n||n.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===Re.kD.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));const n=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(n,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){const t=this.camera.getEngine();if(!t.isPointerLock||t.isInVRExclusivePointerMode)return;const i=e.movementX,n=e.movementY;this._rotateCamera(i,n),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera;this.camera.getScene().useRightHandedSystem&&(e*=-1),i.parent&&i.parent._getWorldMatrixDeterminant()<0&&(e*=-1);const n=e/this.angularSensibility,s=t/this.angularSensibility,r=o._f.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let a;if(this.buttonsPitch.some((e=>e===this.activeButton))&&(a=o._f.RotationAxis(We.RD.X,s),r.multiplyInPlace(a)),this.buttonsYaw.some((e=>e===this.activeButton))){a=o._f.RotationAxis(We.RD.Y,n),r.multiplyInPlace(a);const e=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-e<i.rotation.z&&i.rotation.z<e){const e=i.bankedTurnMultiplier*-n;a=o._f.RotationAxis(We.RD.Z,e),r.multiplyInPlace(a)}}this.buttonsRoll.some((e=>e===this.activeButton))&&(a=o._f.RotationAxis(We.RD.Z,-n),i._trackRoll-=n,r.multiplyInPlace(a)),r.toEulerAnglesToRef(i.rotation)}}(0,be.gn)([(0,Te.qC)()],ft.prototype,"buttons",void 0),(0,be.gn)([(0,Te.qC)()],ft.prototype,"angularSensibility",void 0),Je.u.FlyCameraMouseInput=ft;class _t{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=de.w1.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===st.OG.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(-1!==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)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==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)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach((e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&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}}(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysHeightOffsetIncr",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysHeightOffsetDecr",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysHeightOffsetModifierAlt",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysHeightOffsetModifierCtrl",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysHeightOffsetModifierShift",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysRotationOffsetIncr",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysRotationOffsetDecr",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysRotationOffsetModifierAlt",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysRotationOffsetModifierCtrl",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysRotationOffsetModifierShift",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysRadiusIncr",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysRadiusDecr",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysRadiusModifierAlt",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysRadiusModifierCtrl",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"keysRadiusModifierShift",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"heightSensibility",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"rotationSensibility",void 0),(0,be.gn)([(0,Te.qC)()],_t.prototype,"radiusSensibility",void 0),Je.u.FollowCameraKeyboardMoveInput=_t;class mt{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=de.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Re.kD.POINTERWHEEL)return;const i=t.event;let n=0;const s=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(console.assert(this.axisControlRadius+this.axisControlHeight+this.axisControlRotation<=1,"wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?n=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?n=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(n=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):n=s*this.wheelPrecision,n&&(this.axisControlRadius?this.camera.radius+=n:this.axisControlHeight?this.camera.heightOffset-=n:this.axisControlRotation&&(this.camera.rotationOffset-=n)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Re.kD.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}(0,be.gn)([(0,Te.qC)()],mt.prototype,"axisControlRadius",void 0),(0,be.gn)([(0,Te.qC)()],mt.prototype,"axisControlHeight",void 0),(0,be.gn)([(0,Te.qC)()],mt.prototype,"axisControlRotation",void 0),(0,be.gn)([(0,Te.qC)()],mt.prototype,"wheelPrecision",void 0),(0,be.gn)([(0,Te.qC)()],mt.prototype,"wheelDeltaPercentage",void 0),Je.u.FollowCameraMouseWheelInput=mt;class gt extends Ze{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,n,s,r){if(0===i&&null===s)return;if(0===n&&null===r)return;let o=(n-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";console.assert(this.axisXControlRotation+this.axisXControlHeight+this.axisXControlRadius<=1,e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),console.assert(this.axisYControlRotation+this.axisYControlHeight+this.axisYControlRadius<=1,e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),console.assert(this.axisPinchControlRotation+this.axisPinchControlHeight+this.axisPinchControlRadius<=1,e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}(0,be.gn)([(0,Te.qC)()],gt.prototype,"angularSensibilityX",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"angularSensibilityY",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"pinchPrecision",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"pinchDeltaPercentage",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"axisXControlRadius",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"axisXControlHeight",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"axisXControlRotation",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"axisYControlRadius",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"axisYControlHeight",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"axisYControlRotation",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"axisPinchControlRadius",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"axisPinchControlHeight",void 0),(0,be.gn)([(0,Te.qC)()],gt.prototype,"axisPinchControlRotation",void 0),Je.u.FollowCameraPointersInput=gt;var vt=i(189);vt.a.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new yt,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class yt{static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let n=!1;const s=()=>{window.removeEventListener("deviceorientation",s),n=!0,t()};e&&setTimeout((()=>{n||(window.removeEventListener("deviceorientation",s),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",s):de.w1.Warn("Permission not granted.")})).catch((e=>{de.w1.Error(e)})):window.addEventListener("deviceorientation",s)}))}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new o._f,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new r.y$,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-de.w1.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?de.w1.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?de.w1.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?de.w1.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new o._f(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new o._f),this._camera&&this._camera.onDisposeObservable.add((()=>{this._onDeviceOrientationChangedObservable.clear()}))}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():de.w1.Warn("Permission not granted.")})).catch((e=>{de.w1.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(o._f.RotationYawPitchRollToRef(de.w1.ToRadians(this._alpha),de.w1.ToRadians(this._beta),-de.w1.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"}}Je.u.FreeCameraDeviceOrientationInput=yt;class xt{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=o.y3.Identity(),this._deltaTransform=o.P.Zero(),this._vector3=o.P.Zero(),this._vector2=o.FM.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==tt.POSE_ENABLED&&(this.gamepad&&e.type!==tt.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(tt.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):o.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const n=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*n,0,-t.y*n),o.P.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"}}(0,be.gn)([(0,Te.qC)()],xt.prototype,"gamepadAngularSensibility",void 0),(0,be.gn)([(0,Te.qC)()],xt.prototype,"gamepadMoveSensibility",void 0),Je.u.FreeCameraGamepadInput=xt;var bt,Tt=i(1399),St=i(3516),Et=i(9891),Ct=i(7932),At=i(7090);!function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(bt||(bt={}));class Pt{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={...Pt._GetDefaultOptions(),...t};if(this._leftJoystick=!!e,Pt._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=bt.X,this._axisTargetedByUpAndDown=bt.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new At.x,this.deltaPosition=o.P.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{Pt._VJCanvasWidth=window.innerWidth,Pt._VJCanvasHeight=window.innerHeight,Pt.Canvas&&(Pt.Canvas.width=Pt._VJCanvasWidth,Pt.Canvas.height=Pt._VJCanvasHeight),Pt._HalfWidth=Pt._VJCanvasWidth/2},!Pt.Canvas){window.addEventListener("resize",this._onResize,!1),Pt.Canvas=document.createElement("canvas"),Pt._VJCanvasWidth=window.innerWidth,Pt._VJCanvasHeight=window.innerHeight,Pt.Canvas.width=window.innerWidth,Pt.Canvas.height=window.innerHeight,Pt.Canvas.style.width="100%",Pt.Canvas.style.height="100%",Pt.Canvas.style.position="absolute",Pt.Canvas.style.backgroundColor="transparent",Pt.Canvas.style.top="0px",Pt.Canvas.style.left="0px",Pt.Canvas.style.zIndex="5",Pt.Canvas.style.touchAction="none",Pt.Canvas.setAttribute("touch-action","none");const e=Pt.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");Pt._VJCanvasContext=e,Pt._VJCanvasContext.strokeStyle="#ffffff",Pt._VJCanvasContext.lineWidth=2,document.body.appendChild(Pt.Canvas)}Pt._HalfWidth=Pt.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&&Pt._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new o.FM(0,0),this._joystickPreviousPointerPos=new o.FM(0,0),this._joystickPointerStartPos=new o.FM(0,0),this._deltaJoystickVector=new o.FM(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},Pt.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),Pt.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),Pt.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),Pt.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),Pt.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientX<Pt._HalfWidth:e.clientX>Pt._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)):Pt._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 t=new o.FM(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0<Pt._AlwaysVisibleSticks&&(this._leftJoystick?this._joystickPointerPos.x=Math.min(Pt._HalfWidth,this._joystickPointerPos.x):this._joystickPointerPos.x=Math.max(Pt._HalfWidth,this._joystickPointerPos.x));const t=(this.reverseLeftRight?-1:1)*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case bt.X:this.deltaPosition.x=Math.min(1,Math.max(-1,t));break;case bt.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,t));break;case bt.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,t))}const i=(this.reverseUpDown?1:-1)*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case bt.X:this.deltaPosition.x=Math.min(1,Math.max(-1,i));break;case bt.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,i));break;case bt.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,i))}}else{const t=this._touches.get(e.pointerId.toString());t&&(t.x=e.clientX,t.y=e.clientY)}}_onPointerUp(e){if(this._joystickPointerId==e.pointerId)this._clearPreviousDraw(),this._joystickPointerId=-1,this.pressed=!1;else{const t=this._touches.get(e.pointerId.toString());t&&Pt._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(e.pointerId.toString())}setJoystickColor(e){this._joystickColor=e}set containerSize(e){this._joystickContainerSize=e,this._clearContainerSize=~~(2.1*this._joystickContainerSize),this._clearContainerSizeOffset=~~(this._clearContainerSize/2)}get containerSize(){return this._joystickContainerSize}set puckSize(e){this._joystickPuckSize=e,this._clearPuckSize=~~(2.1*this._joystickPuckSize),this._clearPuckSizeOffset=~~(this._clearPuckSize/2)}get puckSize(){return this._joystickPuckSize}clearPosition(){this.alwaysVisible=!1,this._joystickPosition=null}set alwaysVisible(e){this._alwaysVisible!==e&&(e&&this._joystickPosition?(Pt._AlwaysVisibleSticks++,this._alwaysVisible=!0):(Pt._AlwaysVisibleSticks--,this._alwaysVisible=!1))}get alwaysVisible(){return this._alwaysVisible}setPosition(e,t){this._joystickPointerStartPos&&this._clearPreviousDraw(),this._joystickPosition=new o.FM(e,t)}setActionOnTouch(e){this._action=e}setAxisForLeftRight(e){switch(e){case bt.X:case bt.Y:case bt.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=bt.X}}setAxisForUpDown(e){switch(e){case bt.X:case bt.Y:case bt.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=bt.Y}}_clearPreviousDraw(){const e=this._joystickPosition||this._joystickPointerStartPos;Pt._VJCanvasContext.clearRect(e.x-this._clearContainerSizeOffset,e.y-this._clearContainerSizeOffset,this._clearContainerSize,this._clearContainerSize),Pt._VJCanvasContext.clearRect(this._joystickPreviousPointerPos.x-this._clearPuckSizeOffset-1,this._joystickPreviousPointerPos.y-this._clearPuckSizeOffset-1,this._clearPuckSize+2,this._clearPuckSize+2)}setContainerImage(e){const t=new Image;t.src=e,t.onload=()=>this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?Pt._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(Pt._VJCanvasContext.beginPath(),Pt._VJCanvasContext.strokeStyle=this._joystickColor,Pt._VJCanvasContext.lineWidth=2,Pt._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),Pt._VJCanvasContext.stroke(),Pt._VJCanvasContext.closePath(),Pt._VJCanvasContext.beginPath(),Pt._VJCanvasContext.lineWidth=6,Pt._VJCanvasContext.strokeStyle=this._joystickColor,Pt._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),Pt._VJCanvasContext.stroke(),Pt._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?Pt._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(Pt._VJCanvasContext.beginPath(),Pt._VJCanvasContext.strokeStyle=this._joystickColor,Pt._VJCanvasContext.lineWidth=2,Pt._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),Pt._VJCanvasContext.stroke(),Pt._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()):(Pt._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),Pt._VJCanvasContext.beginPath(),Pt._VJCanvasContext.fillStyle="white",Pt._VJCanvasContext.beginPath(),Pt._VJCanvasContext.strokeStyle="red",Pt._VJCanvasContext.lineWidth=6,Pt._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),Pt._VJCanvasContext.stroke(),Pt._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){Pt.Canvas&&(Pt.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),Pt.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),Pt.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),Pt.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(Pt.Canvas),Pt.Canvas=null),this._released=!0}}Pt._GlobalJoystickIndex=0,Pt._AlwaysVisibleSticks=0,vt.a.prototype.addVirtualJoystick=function(){return this.add(new Rt),this};class Rt{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=50*e._computeLocalCameraSpeed(),i=o.y3.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),n=o.P.TransformCoordinates(new o.P(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(n),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 Pt(!0),this._leftjoystick.setAxisForUpDown(bt.Z),this._leftjoystick.setAxisForLeftRight(bt.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new Pt(!1),this._rightjoystick.setAxisForUpDown(bt.X),this._rightjoystick.setAxisForLeftRight(bt.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"}}Je.u.FreeCameraVirtualJoystickInput=Rt;var Mt=i(2704),It=i(3835),Dt=i(8482),Ot=i(9257);Ot.N.AddNodeConstructor("TouchCamera",((e,t)=>()=>new wt(e,o.P.Zero(),t)));class wt extends Dt.c{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}}var Nt=i(4496);Ot.N.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new Ft(e,0,0,1,o.P.Zero(),t)));class Ft extends It.C{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new o.y3,this._upToYMatrix=new o.y3,this._upVector=o.P.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){o.y3.RotationAlignToRef(o.P.UpReadOnly,this._upVector,this._yToUpMatrix),o.y3.RotationAlignToRef(this._upVector,o.P.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new De,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new Oe,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Ie,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,n,s,a,l=!0){super(e,o.P.Zero(),a,l),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=o.P.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=o.FM.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new o.y3,this.panningAxis=new o.P(1,1,0),this._transformedDirection=new o.P,this.mapPanning=!1,this.onMeshTargetChangedObservable=new r.y$,this.checkCollisions=!1,this.collisionRadius=new o.P(.5,.5,.5),this._previousPosition=o.P.Zero(),this._collisionVelocity=o.P.Zero(),this._newPosition=o.P.Zero(),this._computationVector=o.P.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const n=Math.cos(this.alpha),s=Math.sin(this.alpha),r=Math.cos(this.beta);let o=Math.sin(this.beta);0===o&&(o=1e-4);const a=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*n*o,this.radius*r,this.radius*s*o),a.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,a,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=o.P.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=n,this.getViewMatrix(),this.inputs=new ut(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new o.P(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=o.FM.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_isSynchronizedViewMatrix(){return!!super._isSynchronizedViewMatrix()&&this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset)}attachControl(e,t,i=!0,n=2){const s=arguments;t=de.w1.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=n,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1;let t=this.inertialAlphaOffset;this.beta<=0&&(t*=-1),this.getScene().useRightHandedSystem&&(t*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(t*=-1),this.alpha+=t*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<Me.kn&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<Me.kn&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<this.speed*Me.kn&&(this.inertialRadiusOffset=0)}if(0!==this.inertialPanningX||0!==this.inertialPanningY){const e=new o.P(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.multiplyInPlace(this.panningAxis),o.P.TransformNormalToRef(e,this._cameraTransformMatrix,this._transformedDirection),!this.mapPanning&&this.panningAxis.y||(this._transformedDirection.y=0),this._targetHost||(this.panningDistanceLimit?(this._transformedDirection.addInPlace(this._target),o.P.DistanceSquared(this._transformedDirection,this.panningOriginTarget)<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection)):this._target.addInPlace(this._transformedDirection)),this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<this.speed*Me.kn&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<this.speed*Me.kn&&(this.inertialPanningY=0)}this._checkLimits(),super._checkInputs()}}_checkLimits(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),null!==this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||o.P.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,n=!1){var s;if(n=null!==(s=this.overrideCloneAlphaBetaRadius)&&void 0!==s?s:n,e.getBoundingInfo)this._targetBoundingCenter=t?e.getBoundingInfo().boundingBox.centerWorld.clone():null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,n=this._getTargetPosition();if(n&&!i&&n.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}n||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let n=Math.sin(this.beta);0===n&&(n=1e-4),0===this.radius&&(this.radius=1e-4);const s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*n,this.radius*i,this.radius*t*n),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||o.P.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&n<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=Nt.Kj.MinMax(e),n=o.P.Distance(i.min,i.max);this.radius=n*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:n},t)}focusOn(e,t=!1){let i,n;if(void 0===e.min){const t=e||this.getScene().meshes;i=Nt.Kj.MinMax(t),n=o.P.Distance(i.min,i.max)}else i=e,n=e.distance;this._target=Nt.Kj.Center(i),t||(this.maxZ=2*n)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case Mt.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Mt.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Mt.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case Mt.V.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const n=new Ft(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return n._cameraRigParams={},n.isRigCamera=!0,n.rigParent=this,n.upVector=this.upVector,n.mode=this.mode,n.orthoLeft=this.orthoLeft,n.orthoRight=this.orthoRight,n.orthoBottom=this.orthoBottom,n.orthoTop=this.orthoTop,n}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case Mt.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Mt.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Mt.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case Mt.V.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}(0,be.gn)([(0,Te.qC)()],Ft.prototype,"alpha",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"beta",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"radius",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"overrideCloneAlphaBetaRadius",void 0),(0,be.gn)([(0,Te.hd)("target")],Ft.prototype,"_target",void 0),(0,be.gn)([(0,Te.RR)("targetHost")],Ft.prototype,"_targetHost",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"inertialAlphaOffset",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"inertialBetaOffset",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"inertialRadiusOffset",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"lowerAlphaLimit",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"upperAlphaLimit",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"lowerBetaLimit",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"upperBetaLimit",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"lowerRadiusLimit",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"upperRadiusLimit",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"inertialPanningX",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"inertialPanningY",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"pinchToPanMaxDistance",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"panningDistanceLimit",void 0),(0,be.gn)([(0,Te.hd)()],Ft.prototype,"panningOriginTarget",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"panningInertia",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"zoomToMouseLocation",null),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"zoomOnFactor",void 0),(0,be.gn)([(0,Te.QC)()],Ft.prototype,"targetScreenOffset",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"allowUpsideDown",void 0),(0,be.gn)([(0,Te.qC)()],Ft.prototype,"useInputToRestoreState",void 0),Ot.N.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new Lt(e,o.P.Zero(),t)));class Lt extends Dt.c{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new o._f,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new o._f,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce((()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new o._f),o._f.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))})))}))}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=We.RD.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new o._f),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 Bt extends Je.p{constructor(e){super(e)}addKeyboard(){return this.add(new pt),this}addMouse(){return this.add(new ft),this}}class Ut extends It.C{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,n=!0){super(e,t,i,n),this.ellipsoid=new o.P(1,1,1),this.ellipsoidOffset=new o.P(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=o.P.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=o.P.Zero(),this._diffPosition=o.P.Zero(),this._newPosition=o.P.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>ue.D.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new Bt(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=de.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new o.P(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?o.P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let n=e;this.applyGravity&&(n=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,n,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=o.P.Zero(),this._transformedDirection=o.P.Zero()),this.inputs.checkInputs(),super._checkInputs()}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}(0,be.gn)([(0,Te.hd)()],Ut.prototype,"ellipsoid",void 0),(0,be.gn)([(0,Te.hd)()],Ut.prototype,"ellipsoidOffset",void 0),(0,be.gn)([(0,Te.qC)()],Ut.prototype,"checkCollisions",void 0),(0,be.gn)([(0,Te.qC)()],Ut.prototype,"applyGravity",void 0);class Vt extends Je.p{constructor(e){super(e)}addKeyboard(){return this.add(new _t),this}addMouseWheel(){return this.add(new mt),this}addPointers(){return this.add(new gt),this}addVRDeviceOrientation(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Ot.N.AddNodeConstructor("FollowCamera",((e,t)=>()=>new kt(e,o.P.Zero(),t))),Ot.N.AddNodeConstructor("ArcFollowCamera",((e,t)=>()=>new Gt(e,0,0,1,null,t)));class kt extends It.C{constructor(e,t,i,n=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=n,this.inputs=new Vt(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=o.jp.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),n=de.w1.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),r=s.x+Math.sin(n)*this.radius,a=s.z+Math.cos(n)*this.radius,l=r-this.position.x,h=s.y+this.heightOffset-this.position.y,c=a-this.position.z;let u=l*this.cameraAcceleration*2,d=h*this.cameraAcceleration,p=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),(p>this.maxCameraSpeed||p<-this.maxCameraSpeed)&&(p=p<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new o.P(this.position.x+u,this.position.y+d,this.position.z+p),this.setTarget(s)}attachControl(e,t){t=de.w1.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(){null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffset<this.lowerHeightOffsetLimit&&(this.heightOffset=this.lowerHeightOffsetLimit),null!==this.upperHeightOffsetLimit&&this.heightOffset>this.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffset<this.lowerRotationOffsetLimit&&(this.rotationOffset=this.lowerRotationOffsetLimit),null!==this.upperRotationOffsetLimit&&this.rotationOffset>this.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}(0,be.gn)([(0,Te.qC)()],kt.prototype,"radius",void 0),(0,be.gn)([(0,Te.qC)()],kt.prototype,"lowerRadiusLimit",void 0),(0,be.gn)([(0,Te.qC)()],kt.prototype,"upperRadiusLimit",void 0),(0,be.gn)([(0,Te.qC)()],kt.prototype,"rotationOffset",void 0),(0,be.gn)([(0,Te.qC)()],kt.prototype,"lowerRotationOffsetLimit",void 0),(0,be.gn)([(0,Te.qC)()],kt.prototype,"upperRotationOffsetLimit",void 0),(0,be.gn)([(0,Te.qC)()],kt.prototype,"heightOffset",void 0),(0,be.gn)([(0,Te.qC)()],kt.prototype,"lowerHeightOffsetLimit",void 0),(0,be.gn)([(0,Te.qC)()],kt.prototype,"upperHeightOffsetLimit",void 0),(0,be.gn)([(0,Te.qC)()],kt.prototype,"cameraAcceleration",void 0),(0,be.gn)([(0,Te.qC)()],kt.prototype,"maxCameraSpeed",void 0),(0,be.gn)([(0,Te.RR)("lockedTargetId")],kt.prototype,"lockedTarget",void 0);class Gt extends It.C{constructor(e,t,i,n,s,r){super(e,o.P.Zero(),r),this.alpha=t,this.beta=i,this.radius=n,this._cartesianCoordinates=o.P.Zero(),this.setMeshTarget(s)}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 zt,Wt,Ht,Xt,jt,Yt=i(450);!function(e){e[e.VIVE=0]="VIVE",e[e.OCULUS=1]="OCULUS",e[e.WINDOWS=2]="WINDOWS",e[e.GEAR_VR=3]="GEAR_VR",e[e.DAYDREAM=4]="DAYDREAM",e[e.GENERIC=5]="GENERIC"}(zt||(zt={}));class qt{static InitiateController(e){for(const t of this._ControllerFactories)if(t.canCreate(e))return t.create(e);if(this._DefaultControllerFactory)return this._DefaultControllerFactory(e);throw"The type of gamepad you are trying to load needs to be imported first or is not supported."}}qt._ControllerFactories=[],qt._DefaultControllerFactory=null;class Kt extends tt{_disableTrackPosition(e){this._trackPosition&&(this._calculatedPosition.copyFrom(e),this._trackPosition=!1)}constructor(e){super(e.id,e.index,e),this.isXR=!1,this._deviceRoomPosition=o.P.Zero(),this._deviceRoomRotationQuaternion=new o._f,this.devicePosition=o.P.Zero(),this.deviceRotationQuaternion=new o._f,this.deviceScaleFactor=1,this._trackPosition=!0,this._maxRotationDistFromHeadset=Math.PI/5,this._draggedRoomRotation=0,this._leftHandSystemQuaternion=new o._f,this._deviceToWorld=o.y3.Identity(),this._pointingPoseNode=null,this._workingMatrix=o.y3.Identity(),this._meshAttachedObservable=new r.y$,this.type=tt.POSE_ENABLED,this.controllerType=zt.GENERIC,this.position=o.P.Zero(),this.rotationQuaternion=new o._f,this._calculatedPosition=o.P.Zero(),this._calculatedRotation=new o._f,o._f.RotationYawPitchRollToRef(Math.PI,0,0,this._leftHandSystemQuaternion)}update(){super.update(),this._updatePoseAndMesh()}_updatePoseAndMesh(){if(this.isXR)return;const e=this.browserGamepad.pose;if(this.updateFromDevice(e),!this._trackPosition&&A.l.LastCreatedScene&&A.l.LastCreatedScene.activeCamera&&A.l.LastCreatedScene.activeCamera.devicePosition){const e=A.l.LastCreatedScene.activeCamera;if(e._computeDevicePosition(),this._deviceToWorld.setTranslation(e.devicePosition),e.deviceRotationQuaternion){e._deviceRoomRotationQuaternion.toEulerAnglesToRef(o.jp.Vector3[0]);const t=Math.atan2(Math.sin(o.jp.Vector3[0].y-this._draggedRoomRotation),Math.cos(o.jp.Vector3[0].y-this._draggedRoomRotation));if(Math.abs(t)>this._maxRotationDistFromHeadset){const e=t-(t<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=e;const i=Math.sin(-e),n=Math.cos(-e);this._calculatedPosition.x=this._calculatedPosition.x*n-this._calculatedPosition.z*i,this._calculatedPosition.z=this._calculatedPosition.x*i+this._calculatedPosition.z*n}}}o.P.TransformCoordinatesToRef(this._calculatedPosition,this._deviceToWorld,this.devicePosition),this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix),o._f.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation),this._mesh&&(this._mesh.position.copyFrom(this.devicePosition),this._mesh.rotationQuaternion&&this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion))}updateFromDevice(e){if(!this.isXR&&e){this.rawPose=e,e.position&&(this._deviceRoomPosition.copyFromFloats(e.position[0],e.position[1],-e.position[2]),this._mesh&&this._mesh.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1),this._trackPosition&&this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor,this._calculatedPosition),this._calculatedPosition.addInPlace(this.position));const t=this.rawPose;e.orientation&&t.orientation&&4===t.orientation.length&&(this._deviceRoomRotationQuaternion.copyFromFloats(t.orientation[0],t.orientation[1],-t.orientation[2],-t.orientation[3]),this._mesh&&(this._mesh.getScene().useRightHandedSystem?(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1):this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion,this._deviceRoomRotationQuaternion)),this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion,this._calculatedRotation))}}attachToMesh(e){if(this._mesh&&(this._mesh.parent=null),this._mesh=e,this._poseControlledCamera&&(this._mesh.parent=this._poseControlledCamera),this._mesh.rotationQuaternion||(this._mesh.rotationQuaternion=new o._f),!this.isXR&&(this._updatePoseAndMesh(),this._pointingPoseNode)){const e=[];let t=this._pointingPoseNode;for(;t.parent;)e.push(t.parent),t=t.parent;e.reverse().forEach((e=>{e.computeWorldMatrix(!0)}))}this._meshAttachedObservable.notifyObservers(e)}attachToPoseControlledCamera(e){this._poseControlledCamera=e,this._mesh&&(this._mesh.parent=this._poseControlledCamera)}dispose(){this._mesh&&this._mesh.dispose(),this._mesh=null,super.dispose()}get mesh(){return this._mesh}getForwardRay(e=100){if(!this.mesh)return new Yt.z(o.P.Zero(),new o.P(0,0,1),e);const t=this._pointingPoseNode?this._pointingPoseNode.getWorldMatrix():this.mesh.getWorldMatrix(),i=t.getTranslation(),n=new o.P(0,0,-1),s=o.P.TransformNormal(n,t),r=o.P.Normalize(s);return new Yt.z(i,r,e)}}Kt.POINTING_POSE="POINTING_POSE",function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Wt||(Wt={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Ht||(Ht={}));class $t extends tt{constructor(e,t,i,n=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new r.y$,this.onButtonUpObservable=new r.y$,this.onPadDownObservable=new r.y$,this.onPadUpObservable=new r.y$,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=tt.XBOX,this._isXboxOnePad=n}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,Wt.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,Wt.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,Wt.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,Wt.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Wt.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Wt.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Wt.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Wt.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Wt.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Wt.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Ht.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Ht.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Ht.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Ht.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}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Xt||(Xt={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(jt||(jt={}));class Qt extends tt{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 r.y$,this.onButtonUpObservable=new r.y$,this.onPadDownObservable=new r.y$,this.onPadUpObservable=new r.y$,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=tt.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,Xt.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Xt.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Xt.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Xt.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Xt.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Xt.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Xt.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Xt.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Xt.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Xt.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,jt.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,jt.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,jt.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,jt.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 Zt{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new r.y$,(0,fe.CG)()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new r.y$((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){const t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=tt.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach((e=>{e.dispose()})),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),n=-1!==e.id.search("Xbox One");return t=n||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new $t(e.id,e.index,e,n):i?new Qt(e.id,e.index,e):e.pose?qt.InitiateController(e):new it(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(e){-1===this._loggedErrors.indexOf(t.index)&&(de.w1.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&ue.D.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t<e.length;t++){const i=e[t];if(i)if(this._babylonGamepads[i.index])this._babylonGamepads[t].browserGamepad=i,this._babylonGamepads[t].isConnected||(this._babylonGamepads[t]._isConnected=!0,this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[t]));else{const e=this._addNewGamepad(i);this.onGamepadConnectedObservable.notifyObservers(e)}}}}Object.defineProperty(k.x.prototype,"gamepadManager",{get:function(){if(!this._gamepadManager){this._gamepadManager=new Zt(this);let e=this._getComponent(ve.l.NAME_GAMEPAD);e||(e=new Jt(this),this._addComponent(e))}return this._gamepadManager},enumerable:!0,configurable:!0}),vt.a.prototype.addGamepad=function(){return this.add(new xt),this},ut.prototype.addGamepad=function(){return this.add(new nt),this};class Jt{constructor(e){this.name=ve.l.NAME_GAMEPAD,this.scene=e}register(){this.scene._beforeCameraUpdateStage.registerStep(ve.l.STEP_BEFORECAMERAUPDATE_GAMEPAD,this,this._beforeCameraUpdate)}rebuild(){}dispose(){const e=this.scene._gamepadManager;e&&(e.dispose(),this.scene._gamepadManager=null)}_beforeCameraUpdate(){const e=this.scene._gamepadManager;e&&e._isMonitoring&&e._checkGamepadsStatus()}}Ot.N.AddNodeConstructor("FreeCamera",((e,t)=>()=>new ei(e,o.P.Zero(),t)));class ei extends wt{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"}}Mt.V._CreateDefaultParsedCamera=(e,t)=>new ei(e,o.P.Zero(),t),Ot.N.AddNodeConstructor("GamepadCamera",((e,t)=>()=>new ti(e,o.P.Zero(),t)));class ti extends ei{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}var ii=i(9525),ni=i(392),si=i(8104);si.v.ShadersStore.anaglyphPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}";class ri extends ni.D{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,n,s,r){super(e,"anaglyph",null,["leftSampler"],t,i[1],n,s,r),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)}))}}function oi(e){e._rigCameras[0]._rigPostProcess=new ii.Q(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new ri(e.name+"_anaglyph",1,e._rigCameras)}(0,l.H)("BABYLON.AnaglyphPostProcess",ri),Ot.N.AddNodeConstructor("AnaglyphArcRotateCamera",((e,t,i)=>()=>new ai(e,0,0,1,o.P.Zero(),i.interaxial_distance,t)));class ai extends Ft{constructor(e,t,i,n,s,r,o){super(e,t,i,n,s,o),this._setRigMode=oi.bind(null,this),this.interaxialDistance=r,this.setCameraRigMode(Mt.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:r})}getClassName(){return"AnaglyphArcRotateCamera"}}Ot.N.AddNodeConstructor("AnaglyphFreeCamera",((e,t,i)=>()=>new li(e,o.P.Zero(),i.interaxial_distance,t)));class li extends Dt.c{constructor(e,t,i,n){super(e,t,n),this._setRigMode=oi.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(Mt.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Ot.N.AddNodeConstructor("AnaglyphGamepadCamera",((e,t,i)=>()=>new hi(e,o.P.Zero(),i.interaxial_distance,t)));class hi extends ti{constructor(e,t,i,n){super(e,t,n),this._setRigMode=oi.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(Mt.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Ot.N.AddNodeConstructor("AnaglyphUniversalCamera",((e,t,i)=>()=>new ci(e,o.P.Zero(),i.interaxial_distance,t)));class ci extends ei{constructor(e,t,i,n){super(e,t,n),this._setRigMode=oi.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(Mt.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}var ui=i(4538);si.v.ShadersStore.stereoscopicInterlacePixelShader="const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nbool useCamA;\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\nuseCamA=!useCamB;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);\nuseCamA=mod(rowNum,2.0)==1.0;\nuseCamB=mod(rowNum,2.0)==0.0;\ntexCoord1=vec2(vUV.x,vUV.y);\ntexCoord2=vec2(vUV.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\nuseCamA=!useCamB;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n#endif\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else if (useCamA){\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}else {\ndiscard;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}\n";class di extends ni.D{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,n,s,r,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,r,a,n?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new o.FM(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new o.FM(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}class pi extends ni.D{getClassName(){return"StereoscopicInterlacePostProcess"}constructor(e,t,i,n,s,r){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],n,s,r,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new o.FM(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new o.FM(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}function fi(e){const t=e.cameraRigMode===Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===Mt.V.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new ii.Q(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new di(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new ui.l(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new ui.l(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}Ot.N.AddNodeConstructor("StereoscopicArcRotateCamera",((e,t,i)=>()=>new _i(e,0,0,1,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class _i extends Ft{constructor(e,t,i,n,s,r,o,a){super(e,t,i,n,s,a),this._setRigMode=fi.bind(null,this),this.interaxialDistance=r,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Mt.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:r})}getClassName(){return"StereoscopicArcRotateCamera"}}Ot.N.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new mi(e,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class mi extends Dt.c{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=fi.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Mt.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Ot.N.AddNodeConstructor("StereoscopicGamepadCamera",((e,t,i)=>()=>new gi(e,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class gi extends ti{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=fi.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Mt.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Ot.N.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new vi(e,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class vi extends ei{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=fi.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Mt.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}var yi=i(4674);class xi extends ei{set distanceBetweenEyes(e){this._distanceBetweenEyes=e}get distanceBetweenEyes(){return this._distanceBetweenEyes}set distanceToProjectionPlane(e){this._distanceToProjectionPlane=e}get distanceToProjectionPlane(){return this._distanceToProjectionPlane}constructor(e,t,i,n=1,s=.065){super(e,t,i),this._distanceBetweenEyes=s,this._distanceToProjectionPlane=n,this.setCameraRigMode(Mt.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),this._cameraRigParams.stereoHalfAngle=0,this._cameraRigParams.interaxialDistance=s}getClassName(){return"StereoscopicUniversalCamera"}createRigCamera(e){const t=new It.C(e,o.P.Zero(),this.getScene()),i=new yi.Y("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(o.y3.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++){const t=this._rigCameras[e];t.minZ=this.minZ,t.maxZ=this.maxZ,t.fov=this.fov,t.upVector.copyFrom(this.upVector),t.rotationQuaternion?t.rotationQuaternion.copyFrom(this.rotationQuaternion):t.rotation.copyFrom(this.rotation),this._updateCamera(this._rigCameras[e],e)}}_updateCamera(e,t){const i=this.distanceBetweenEyes/2,n=i/this.distanceToProjectionPlane;e.position.copyFrom(this.position),e.position.addInPlaceFromFloats(0===t?-i:i,0,-this._distanceToProjectionPlane);const s=e.parent,r=s.getPivotMatrix();r.setTranslationFromFloats(0===t?i:-i,0,0),r.setRowFromFloats(2,0===t?n:-n,0,1,0),s.setPivotMatrix(r,!1)}_setRigMode(){this._rigCameras[0].viewport=new ui.l(0,0,.5,1),this._rigCameras[1].viewport=new ui.l(.5,0,.5,1);for(let e=0;e<this._rigCameras.length;e++)this._updateCamera(this._rigCameras[e],e)}}Ot.N.AddNodeConstructor("VirtualJoysticksCamera",((e,t)=>()=>new bi(e,o.P.Zero(),t)));class bi extends Dt.c{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class Ti{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return o.y3.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return o.y3.Translation(-e,0,0)}get leftPreViewMatrix(){return o.y3.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return o.y3.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new Ti;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}}si.v.ShadersStore.vrDistortionCorrectionPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}";class Si extends ni.D{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,n){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,n.postProcessScaleFactor,t,Ce.x.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=n.distortionK,this._postProcessScaleFactor=n.postProcessScaleFactor,this._lensCenterOffset=n.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new o.FM(2,2/this.aspectRatio),this._scaleFactor=new o.FM(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new o.FM(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}}si.v.ShadersStore.vrMultiviewToSingleviewPixelShader="precision mediump sampler2DArray;\nvarying vec2 vUV;\nuniform sampler2DArray multiviewSampler;\nuniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ngl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));\n}";var Ei=i(6202),Ci=i(3743),Ai=i(4246);class Pi extends Ai._{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}}var Ri=i(1560);function Mi(e,t){const i=new Ci.M(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}ue.D.prototype.createMultiviewRenderTargetTexture=function(e,t){const i=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=i.createFramebuffer();const s=new Ei.l(this,Ei.S.Unknown,!0);return s.width=e,s.height=t,s.isMultiview=!0,n._colorTextureArray=i.createTexture(),i.bindTexture(i.TEXTURE_2D_ARRAY,n._colorTextureArray),i.texStorage3D(i.TEXTURE_2D_ARRAY,1,i.RGBA8,e,t,2),n._depthStencilTextureArray=i.createTexture(),i.bindTexture(i.TEXTURE_2D_ARRAY,n._depthStencilTextureArray),i.texStorage3D(i.TEXTURE_2D_ARRAY,1,i.DEPTH24_STENCIL8,e,t,2),s.isReady=!0,n.setTextures(s),n._depthStencilTexture=s,n},ue.D.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,n=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(n.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),n.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},Mt.V.prototype._useMultiviewToSingleView=!1,Mt.V.prototype._multiviewTexture=null,Mt.V.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new Pi(this.getScene(),{width:e,height:t})):this._multiviewTexture=new Pi(this.getScene(),{width:e,height:t})};const Ii=k.x.prototype.createSceneUniformBuffer;k.x.prototype._transformMatrixR=o.y3.Zero(),k.x.prototype._multiviewSceneUbo=null,k.x.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=Mi(this.getEngine(),"scene_multiview")},k.x.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?Mi(this.getEngine(),e):Ii.bind(this)(e)},k.x.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,o.jp.Matrix[0]),Ri.i.GetRightPlaneToRef(o.jp.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))},k.x.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t<e._rigCameras.length;t++){const i=this.getEngine();this._activeCamera=e._rigCameras[t],i.setViewport(this._activeCamera.viewport),this.postProcessManager&&(this.postProcessManager._prepareFrame(),this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate))}};class Di extends ni.D{getClassName(){return"VRMultiviewToSingleviewPostProcess"}constructor(e,t,i){super(e,"vrMultiviewToSingleview",["imageIndex"],["multiviewSampler"],i,t,Ce.x.BILINEAR_SAMPLINGMODE);const n=null!=t?t:this.getCamera();this.onSizeChangedObservable.add((()=>{})),this.onApplyObservable.add((e=>{n._scene.activeCamera&&n._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",n._multiviewTexture)}))}}function Oi(e,t){const i=t.vrCameraMetrics||Ti.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new ui.l(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new ui.l(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new Di("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(_.Y.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Si("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Si("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}Ot.N.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",((e,t)=>()=>new wi(e,0,0,1,o.P.Zero(),t)));class wi extends Ft{constructor(e,t,i,n,s,r,o=!0,a=Ti.GetDefault()){super(e,t,i,n,s,r),this._setRigMode=Oi.bind(null,this),a.compensateDistortion=o,this.setCameraRigMode(Mt.V.RIG_MODE_VR,{vrCameraMetrics:a}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Ot.N.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new Ni(e,o.P.Zero(),t)));class Ni extends Lt{constructor(e,t,i,n=!0,s=Ti.GetDefault()){super(e,t,i),this._setRigMode=Oi.bind(null,this),s.compensateDistortion=n,this.setCameraRigMode(Mt.V.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Ot.N.AddNodeConstructor("VRDeviceOrientationGamepadCamera",((e,t)=>()=>new Fi(e,o.P.Zero(),t)));class Fi extends Ni{constructor(e,t,i,n=!0,s=Ti.GetDefault()){super(e,t,i,n,s),this._setRigMode=Oi.bind(null,this),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}var Li=i(7616);function Bi(e,t){if(t.vrDisplay){const i=t.vrDisplay.getEyeParameters("left"),n=t.vrDisplay.getEyeParameters("right");e._rigCameras[0].viewport=new ui.l(0,0,.5,1),e._rigCameras[0].setCameraRigParameter("left",!0),e._rigCameras[0].setCameraRigParameter("specs",t.specs),e._rigCameras[0].setCameraRigParameter("eyeParameters",i),e._rigCameras[0].setCameraRigParameter("frameData",t.frameData),e._rigCameras[0].setCameraRigParameter("parentCamera",t.parentCamera),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[0].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[0].parent=e,e._rigCameras[0]._getViewMatrix=e._getWebVRViewMatrix,e._rigCameras[1].viewport=new ui.l(.5,0,.5,1),e._rigCameras[1].setCameraRigParameter("eyeParameters",n),e._rigCameras[1].setCameraRigParameter("specs",t.specs),e._rigCameras[1].setCameraRigParameter("frameData",t.frameData),e._rigCameras[1].setCameraRigParameter("parentCamera",t.parentCamera),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[1].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[1].parent=e,e._rigCameras[1]._getViewMatrix=e._getWebVRViewMatrix}}Object.defineProperty(ue.D.prototype,"isInVRExclusivePointerMode",{get:function(){return this._vrExclusivePointerMode},enumerable:!0,configurable:!0}),ue.D.prototype._prepareVRComponent=function(){this._vrSupported=!1,this._vrExclusivePointerMode=!1,this.onVRDisplayChangedObservable=new r.y$,this.onVRRequestPresentComplete=new r.y$,this.onVRRequestPresentStart=new r.y$},ue.D.prototype.isVRDevicePresent=function(){return!!this._vrDisplay},ue.D.prototype.getVRDevice=function(){return this._vrDisplay},ue.D.prototype.initWebVR=function(){return this.initWebVRAsync(),this.onVRDisplayChangedObservable},ue.D.prototype.initWebVRAsync=function(){const e=()=>{const e={vrDisplay:this._vrDisplay,vrSupported:this._vrSupported};this.onVRDisplayChangedObservable.notifyObservers(e),this._webVRInitPromise=new Promise((t=>{t(e)}))};if(!this._onVrDisplayConnect){this._onVrDisplayConnect=t=>{this._vrDisplay=t.display,e()},this._onVrDisplayDisconnect=()=>{this._vrDisplay.cancelAnimationFrame(this._frameHandler),this._vrDisplay=void 0,this._frameHandler=ue.D.QueueNewFrame(this._boundRenderFunction),e()},this._onVrDisplayPresentChange=()=>{this._vrExclusivePointerMode=this._vrDisplay&&this._vrDisplay.isPresenting};const t=this.getHostWindow();t&&(t.addEventListener("vrdisplayconnect",this._onVrDisplayConnect),t.addEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),t.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange))}return this._webVRInitPromise=this._webVRInitPromise||this._getVRDisplaysAsync(),this._webVRInitPromise.then(e),this._webVRInitPromise},ue.D.prototype._getVRDisplaysAsync=function(){return new Promise((e=>{navigator.getVRDisplays?navigator.getVRDisplays().then((t=>{this._vrSupported=!0,this._vrDisplay=t[0],e({vrDisplay:this._vrDisplay,vrSupported:this._vrSupported})})):(this._vrDisplay=void 0,this._vrSupported=!1,e({vrDisplay:this._vrDisplay,vrSupported:this._vrSupported}))}))},ue.D.prototype.enableVR=function(e){if(this._vrDisplay&&!this._vrDisplay.isPresenting){const t=()=>{this.onVRRequestPresentComplete.notifyObservers(!0),this._onVRFullScreenTriggered()},i=()=>{this.onVRRequestPresentComplete.notifyObservers(!1)};this.onVRRequestPresentStart.notifyObservers(this);const n={highRefreshRate:!!this.vrPresentationAttributes&&this.vrPresentationAttributes.highRefreshRate,foveationLevel:this.vrPresentationAttributes?this.vrPresentationAttributes.foveationLevel:1,multiview:(this.getCaps().multiview||this.getCaps().oculusMultiview)&&e.useMultiview};this._vrDisplay.requestPresent([{source:this.getRenderingCanvas(),attributes:n,...n}]).then(t).catch(i)}},ue.D.prototype._onVRFullScreenTriggered=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting){this._oldSize=new w.$(this.getRenderWidth(),this.getRenderHeight()),this._oldHardwareScaleFactor=this.getHardwareScalingLevel();const e=this._vrDisplay.getEyeParameters("left");this.setHardwareScalingLevel(1),this.setSize(2*e.renderWidth,e.renderHeight)}else this.setHardwareScalingLevel(this._oldHardwareScaleFactor),this.setSize(this._oldSize.width,this._oldSize.height)},ue.D.prototype.disableVR=function(){this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.exitPresent().then((()=>this._onVRFullScreenTriggered())).catch((()=>this._onVRFullScreenTriggered())),(0,fe.CG)()&&(window.removeEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted),window.removeEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted),this._onVrDisplayConnect&&(window.removeEventListener("vrdisplayconnect",this._onVrDisplayConnect),this._onVrDisplayDisconnect&&window.removeEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),this._onVrDisplayPresentChange&&window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._onVrDisplayConnect=null,this._onVrDisplayDisconnect=null))},ue.D.prototype._connectVREvents=function(e,t){if(this._onVRDisplayPointerRestricted=()=>{e&&e.requestPointerLock()},this._onVRDisplayPointerUnrestricted=()=>{if(t)t.exitPointerLock&&t.exitPointerLock();else{const e=this.getHostWindow();e.document&&e.document.exitPointerLock&&e.document.exitPointerLock()}},(0,fe.CG)()){const e=this.getHostWindow();e.addEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted,!1),e.addEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted,!1)}},ue.D.prototype._submitVRFrame=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting)try{this._vrDisplay.submitFrame()}catch(e){de.w1.Warn("webVR submitFrame has had an unexpected failure: "+e)}},ue.D.prototype.isVRPresenting=function(){return this._vrDisplay&&this._vrDisplay.isPresenting},ue.D.prototype._requestVRFrame=function(){this._frameHandler=ue.D.QueueNewFrame(this._boundRenderFunction,this._vrDisplay)},Ot.N.AddNodeConstructor("WebVRFreeCamera",((e,t)=>()=>new Ui(e,o.P.Zero(),t))),Ot.N.AddNodeConstructor("WebVRGamepadCamera",((e,t)=>()=>new Ui(e,o.P.Zero(),t)));class Ui extends Dt.c{constructor(e,t,i,n={}){super(e,t,i),this._webVROptions=n,this._vrDevice=null,this.rawPose=null,this._specsVersion="1.1",this._attached=!1,this._descendants=[],this._deviceRoomPosition=o.P.Zero(),this._deviceRoomRotationQuaternion=o._f.Identity(),this._standingMatrix=null,this.devicePosition=o.P.Zero(),this.deviceRotationQuaternion=o._f.Identity(),this.deviceScaleFactor=1,this._deviceToWorld=o.y3.Identity(),this._worldToDevice=o.y3.Identity(),this.controllers=[],this.onControllersAttachedObservable=new r.y$,this.onControllerMeshLoadedObservable=new r.y$,this.onPoseUpdatedFromDeviceObservable=new r.y$,this._poseSet=!1,this.rigParenting=!0,this._defaultHeight=void 0,this._setRigMode=Bi.bind(null,this),this._detachIfAttached=()=>{const e=this.getEngine().getVRDevice();e&&!e.isPresenting&&this.detachControl()},this._workingVector=o.P.Zero(),this._oneVector=o.P.One(),this._workingMatrix=o.y3.Identity(),this._tmpMatrix=new o.y3,this._cache.position=o.P.Zero(),n.defaultHeight&&(this._defaultHeight=n.defaultHeight,this.position.y=this._defaultHeight),this.minZ=.1,5===arguments.length&&(this._webVROptions=arguments[4]),null==this._webVROptions.trackPosition&&(this._webVROptions.trackPosition=!0),null==this._webVROptions.controllerMeshes&&(this._webVROptions.controllerMeshes=!0),null==this._webVROptions.defaultLightingOnControllers&&(this._webVROptions.defaultLightingOnControllers=!0),this.rotationQuaternion=new o._f,this._webVROptions&&this._webVROptions.positionScale&&(this.deviceScaleFactor=this._webVROptions.positionScale);const s=this.getEngine();this._onVREnabled=e=>{e&&this.initControllers()},s.onVRRequestPresentComplete.add(this._onVREnabled),s.initWebVR().add((e=>{e.vrDisplay&&this._vrDevice!==e.vrDisplay&&(this._vrDevice=e.vrDisplay,this.setCameraRigMode(Mt.V.RIG_MODE_WEBVR,{parentCamera:this,vrDisplay:this._vrDevice,frameData:this._frameData,specs:this._specsVersion}),this._attached&&this.getEngine().enableVR(this._webVROptions))})),"undefined"!=typeof VRFrameData&&(this._frameData=new VRFrameData),n.useMultiview&&(this.getScene().getEngine().getCaps().multiview?(this._useMultiviewToSingleView=!0,this._rigPostProcess=new Di("VRMultiviewToSingleview",this,1)):(_.Y.Warn("Multiview is not supported, falling back to standard rendering"),this._useMultiviewToSingleView=!1)),this.getScene().onBeforeCameraRenderObservable.add((e=>{e.parent===this&&this.rigParenting&&(this._descendants=this.getDescendants(!0,(e=>{const t=this.controllers.some((t=>t._mesh===e)),i=-1!==this._rigCameras.indexOf(e);return!t&&!i})),this._descendants.forEach((t=>{t.parent=e})))})),this.getScene().onAfterCameraRenderObservable.add((e=>{e.parent===this&&this.rigParenting&&this._descendants.forEach((e=>{e.parent=this}))}))}deviceDistanceToRoomGround(){return this._standingMatrix?(this._standingMatrix.getTranslationToRef(this._workingVector),this._deviceRoomPosition.y+this._workingVector.y):this._defaultHeight||0}useStandingMatrix(e=(e=>{})){this.getEngine().initWebVRAsync().then((t=>{t.vrDisplay&&t.vrDisplay.stageParameters&&t.vrDisplay.stageParameters.sittingToStandingTransform&&this._webVROptions.trackPosition?(this._standingMatrix=new o.y3,o.y3.FromFloat32ArrayToRefScaled(t.vrDisplay.stageParameters.sittingToStandingTransform,0,1,this._standingMatrix),this.getScene().useRightHandedSystem||this._standingMatrix&&this._standingMatrix.toggleModelMatrixHandInPlace(),e(!0)):e(!1)}))}useStandingMatrixAsync(){return new Promise((e=>{this.useStandingMatrix((t=>{e(t)}))}))}dispose(){this._detachIfAttached(),this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled),this._updateCacheWhenTrackingDisabledObserver&&this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver),super.dispose()}getControllerByName(e){for(const t of this.controllers)if(t.hand===e)return t;return null}get leftController(){return this._leftController||(this._leftController=this.getControllerByName("left")),this._leftController}get rightController(){return this._rightController||(this._rightController=this.getControllerByName("right")),this._rightController}getForwardRay(e=100){return this.leftCamera?super.getForwardRay(e,this.leftCamera.getWorldMatrix(),this.leftCamera.globalPosition):super.getForwardRay(e)}_checkInputs(){this._vrDevice&&this._vrDevice.isPresenting&&(this._vrDevice.getFrameData(this._frameData),this.updateFromDevice(this._frameData.pose)),super._checkInputs()}updateFromDevice(e){e&&e.orientation&&4===e.orientation.length&&(this.rawPose=e,this._deviceRoomRotationQuaternion.copyFromFloats(e.orientation[0],e.orientation[1],-e.orientation[2],-e.orientation[3]),this.getScene().useRightHandedSystem&&(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1),this._webVROptions.trackPosition&&this.rawPose.position&&(this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2]),this.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1)),this._poseSet=!0)}attachControl(e){e=de.w1.BackCompatCameraNoPreventDefault(arguments),super.attachControl(e),this._attached=!0,e=!Mt.V.ForceAttachControlToAlwaysPreventDefault&&e,this._vrDevice&&this.getEngine().enableVR(this._webVROptions);const t=this._scene.getEngine().getHostWindow();t&&t.addEventListener("vrdisplaypresentchange",this._detachIfAttached)}detachControl(){this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),super.detachControl(),this._attached=!1,this.getEngine().disableVR(),window.removeEventListener("vrdisplaypresentchange",this._detachIfAttached)}getClassName(){return"WebVRFreeCamera"}resetToCurrentRotation(){this._vrDevice.resetPose()}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];e.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),t.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),e.position.copyFrom(this._deviceRoomPosition),t.position.copyFrom(this._deviceRoomPosition)}_correctPositionIfNotTrackPosition(e,t=!1){this.rawPose&&this.rawPose.position&&!this._webVROptions.trackPosition&&(o.y3.TranslationToRef(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2],this._tmpMatrix),t||this._tmpMatrix.invert(),this._tmpMatrix.multiplyToRef(e,e))}_updateCache(e){this.rotationQuaternion.equals(this._cache.rotationQuaternion)&&this.position.equals(this._cache.position)||(this._updateCacheCalled||(this._updateCacheCalled=!0,this.update()),this.rotationQuaternion.toRotationMatrix(this._workingMatrix),o.P.TransformCoordinatesToRef(this._deviceRoomPosition,this._workingMatrix,this._workingVector),this.devicePosition.subtractToRef(this._workingVector,this._workingVector),o.y3.ComposeToRef(this._oneVector,this.rotationQuaternion,this._workingVector,this._deviceToWorld),this._deviceToWorld.getTranslationToRef(this._workingVector),this._workingVector.addInPlace(this.position),this._workingVector.subtractInPlace(this._cache.position),this._deviceToWorld.setTranslation(this._workingVector),this._deviceToWorld.invertToRef(this._worldToDevice),this.controllers.forEach((e=>{e._deviceToWorld.copyFrom(this._deviceToWorld),this._correctPositionIfNotTrackPosition(e._deviceToWorld),e.update()}))),e||super._updateCache(),this._updateCacheCalled=!1}_computeDevicePosition(){o.P.TransformCoordinatesToRef(this._deviceRoomPosition,this._deviceToWorld,this.devicePosition)}update(){this._computeDevicePosition(),o.y3.FromQuaternionToRef(this._deviceRoomRotationQuaternion,this._workingMatrix),this._workingMatrix.multiplyToRef(this._deviceToWorld,this._workingMatrix),o._f.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this._poseSet&&this.onPoseUpdatedFromDeviceObservable.notifyObservers(null),super.update()}_getViewMatrix(){return o.y3.Identity()}_getWebVRViewMatrix(){const e=this._cameraRigParams.parentCamera;e._updateCache();const t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftViewMatrix:this._cameraRigParams.frameData.rightViewMatrix;return o.y3.FromArrayToRef(t,0,this._webvrViewMatrix),this.getScene().useRightHandedSystem||this._webvrViewMatrix.toggleModelMatrixHandInPlace(),this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix),o.P.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),1!==e.deviceScaleFactor&&(this._webvrViewMatrix.invert(),e.deviceScaleFactor&&(this._webvrViewMatrix.multiplyAtIndex(12,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(13,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(14,e.deviceScaleFactor)),this._webvrViewMatrix.invert()),e._correctPositionIfNotTrackPosition(this._webvrViewMatrix,!0),e._worldToDevice.multiplyToRef(this._webvrViewMatrix,this._webvrViewMatrix),this._workingMatrix=this._workingMatrix||o.y3.Identity(),this._webvrViewMatrix.invertToRef(this._workingMatrix),this._workingMatrix.multiplyToRef(e.getWorldMatrix(),this._workingMatrix),this._workingMatrix.getTranslationToRef(this._globalPosition),this._markSyncedWithParent(),this._webvrViewMatrix}_getWebVRProjectionMatrix(){const e=this.parent;e._vrDevice.depthNear=e.minZ,e._vrDevice.depthFar=e.maxZ;const t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftProjectionMatrix:this._cameraRigParams.frameData.rightProjectionMatrix;return o.y3.FromArrayToRef(t,0,this._projectionMatrix),this.getScene().useRightHandedSystem||this._projectionMatrix.toggleProjectionMatrixHandInPlace(),this._projectionMatrix}initControllers(){this.controllers.length=0;const e=this.getScene().gamepadManager;this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{if(e.type===tt.POSE_ENABLED){const t=e;t.defaultModel&&t.defaultModel.setEnabled(!1),"right"===t.hand&&(this._rightController=null),"left"===t.hand&&(this._leftController=null);const i=this.controllers.indexOf(t);-1!==i&&this.controllers.splice(i,1)}})),this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{if(e.type===tt.POSE_ENABLED){const t=e;if(this._webVROptions.trackPosition||(t._disableTrackPosition(new o.P("left"==t.hand?-.15:.15,-.5,.25)),this._updateCacheWhenTrackingDisabledObserver||(this._updateCacheWhenTrackingDisabledObserver=this._scene.onBeforeRenderObservable.add((()=>{this._updateCache()})))),t.deviceScaleFactor=this.deviceScaleFactor,t._deviceToWorld.copyFrom(this._deviceToWorld),this._correctPositionIfNotTrackPosition(t._deviceToWorld),this._webVROptions.controllerMeshes&&(t.defaultModel?t.defaultModel.setEnabled(!0):t.initControllerMesh(this.getScene(),(e=>{if(e.scaling.scaleInPlace(this.deviceScaleFactor),this.onControllerMeshLoadedObservable.notifyObservers(t),this._webVROptions.defaultLightingOnControllers){this._lightOnControllers||(this._lightOnControllers=new Li.e("vrControllersLight",new o.P(0,1,0),this.getScene()));const t=function(e,i){const n=e.getChildren();n&&0!==n.length&&n.forEach((e=>{i.includedOnlyMeshes.push(e),t(e,i)}))};this._lightOnControllers.includedOnlyMeshes.push(e),t(e,this._lightOnControllers)}}))),t.attachToPoseControlledCamera(this),-1===this.controllers.indexOf(t)){this.controllers.push(t);let e=!1;for(let t=0;t<this.controllers.length;t++)this.controllers[t].controllerType===zt.VIVE&&(e?this.controllers[t].hand="right":(e=!0,this.controllers[t].hand="left"));this.controllers.length>=2&&this.onControllersAttachedObservable.notifyObservers(this.controllers)}}}))}}class Vi extends Kt{onButtonStateChange(e){this._onButtonStateChange=e}get defaultModel(){return this._defaultModel}constructor(e){super(e),this.onTriggerStateChangedObservable=new r.y$,this.onMainButtonStateChangedObservable=new r.y$,this.onSecondaryButtonStateChangedObservable=new r.y$,this.onPadStateChangedObservable=new r.y$,this.onPadValuesChangedObservable=new r.y$,this.pad={x:0,y:0},this._changes={pressChanged:!1,touchChanged:!1,valueChanged:!1,changed:!1},this._buttons=new Array(e.buttons.length),this.hand=e.hand}update(){super.update();for(let e=0;e<this._buttons.length;e++)this._setButtonValue(this.browserGamepad.buttons[e],this._buttons[e],e);this.leftStick.x===this.pad.x&&this.leftStick.y===this.pad.y||(this.pad.x=this.leftStick.x,this.pad.y=this.leftStick.y,this.onPadValuesChangedObservable.notifyObservers(this.pad))}_setButtonValue(e,t,i){e||(e={pressed:!1,touched:!1,value:0}),t?(this._checkChanges(e,t),this._changes.changed&&(this._onButtonStateChange&&this._onButtonStateChange(this.index,i,e),this._handleButtonChange(i,e,this._changes)),this._buttons[i].pressed=e.pressed,this._buttons[i].touched=e.touched,this._buttons[i].value=e.value<1e-8?0:e.value):this._buttons[i]={pressed:e.pressed,touched:e.touched,value:e.value}}_checkChanges(e,t){return this._changes.pressChanged=e.pressed!==t.pressed,this._changes.touchChanged=e.touched!==t.touched,this._changes.valueChanged=e.value!==t.value,this._changes.changed=this._changes.pressChanged||this._changes.touchChanged||this._changes.valueChanged,this._changes}dispose(){super.dispose(),this._defaultModel=null,this.onTriggerStateChangedObservable.clear(),this.onMainButtonStateChangedObservable.clear(),this.onSecondaryButtonStateChangedObservable.clear(),this.onPadStateChangedObservable.clear(),this.onPadValuesChangedObservable.clear()}}var ki=i(4475),Gi=i(252),zi=i(4160);i(5141),i(1423),i(3660);si.v.ShadersStore.imageProcessingPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}",i(8793);class Wi extends ni.D{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=A.l.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new ki.$}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,n,s,r,o=0,a){super(e,"imageProcessing",[],[],t,i,n,s,r,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},a?(a.applyByPostProcess=!0,this._attachImageProcessingConfiguration(a,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines)this._defines[t]&&(e+=`#define ${t};\r\n`);const t=["textureSampler"],i=["scale"];ki.$&&(ki.$.PrepareSamplers(t,this._defines),ki.$.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)}}(0,be.gn)([(0,Te.qC)()],Wi.prototype,"_fromLinearSpace",void 0);class Hi{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}constructor(e,t,i,n,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=n,this.createRenderTargetTextureProvider=s}}var Xi,ji,Yi=i(2200);class qi{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new Ei.l(this._engine,Ei.S.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new Yi.B(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,n,s,r){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},a=r?new Pi(this._scene,o):new Ai._("XR renderTargetTexture",o,this._scene),l=a.renderTarget;if(l._samples=a.samples,!i&&n||(l._framebuffer=i),n)if(r)l._colorTextureArray=n;else{const e=this._createInternalTexture(o,n);l.setTexture(e,0),a._texture=e}return s&&(r?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(o,s)),a.disableRescaling(),"undefined"!=typeof XRWebGLBinding&&(a.skipInitialClear=!0),this._renderTargetTextures.push(a),a}_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 Ki extends Hi{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new $i(e.scene,this))),this.layer=e}}class $i extends qi{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const n=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/n,e.y=i.y/s,e.width=i.width/n,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,n=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&n===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,n),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=n),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class Qi{static GetDefaults(e){const t=new Qi;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class Zi{constructor(e,t=Qi.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new r.y$,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()}))}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new Ki(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{}),(()=>{de.w1.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 Ji extends Hi{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new en(e,this))),this.layer=e}}class en extends qi{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 tn{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 nn{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new r.y$,this.onXRReferenceSpaceChanged=new r.y$,this.onXRSessionEnded=new r.y$,this.onXRSessionInit=new r.y$,this.inXRFrameLoop=!1,this.inXRSession=!1,this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),null===(e=this._engine)||void 0===e||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}exitXRAsync(){return this.session&&this.inXRSession?(this.inXRSession=!1,this.session.end().catch((()=>{_.Y.Warn("Could not end XR session.")}))):Promise.resolve()}trySetViewportForView(e,t){var i;return(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new tn(this):((e=e||Qi.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new Zi(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then((t=>(this.session=t,this._sessionMode=e,this.onXRSessionInit.notifyObservers(t),this.inXRSession=!0,this.session.addEventListener("end",(()=>{var e;this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&(null===(e=this._baseLayerRTTProvider)||void 0===e||e.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return nn.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:this.session.requestAnimationFrame.bind(this.session),renderFunction:(e,t)=>{var i;this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t&&(this.inXRFrameLoop=!0,this._engine.framebufferDimensionsObject=(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.getFramebufferDimensions())||null,this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1))}},this._engine.framebufferDimensionsObject=(null===(e=this._baseLayerRTTProvider)||void 0===e?void 0:e.getFramebufferDimensions())||null,"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(_.Y.Error("XR.requestReferenceSpace failed for the following reason: "),_.Y.Error(e),_.Y.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw _.Y.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&(null===(t=this._baseLayerRTTProvider)||void 0===t||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=(null===(i=this._baseLayerWrapper)||void 0===i?void 0:i.createRenderTargetTextureProvider(this))||null}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new Ji(e.baseLayer):new Ki(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(_.Y.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){var e;return null!==(e=this._xrNavigator.xr.native)&&void 0!==e&&e}get currentFrameRate(){var e;return null===(e=this.session)||void 0===e?void 0:e.frameRate}get supportedFrameRates(){var e;return null===(e=this.session)||void 0===e?void 0:e.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.fixedFoveation)||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}}!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(Xi||(Xi={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(ji||(ji={}));var sn=i(2101),rn=i(4892);function on(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,n=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,n=n||1e-5;const s=e.tessellation||24,r=e.subdivisions||1,l=!!e.hasRings,h=!!e.enclose,c=0===e.cap?0:e.cap||Nt.Kj.CAP_ALL,u=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,d=0===e.sideOrientation?0:e.sideOrientation||sn.x.DEFAULTSIDE,p=e.faceUV||new Array(3),f=e.faceColors,_=2+(1+(1!==u&&h?2:0))*(l?r:1);let m;for(m=0;m<_;m++)f&&void 0===f[m]&&(f[m]=new a.HE(1,1,1,1));for(m=0;m<_;m++)p&&void 0===p[m]&&(p[m]=new o.Lt(0,0,1,1));const g=new Array,v=new Array,y=new Array,x=new Array,b=new Array,T=2*Math.PI*u/s;let S,E,C;const A=(n-i)/2/t,P=o.P.Zero(),R=o.P.Zero(),M=o.P.Zero(),I=o.P.Zero(),D=o.P.Zero(),O=We.RD.Y;let w,N,F,L=1,B=1,U=0,V=0;for(w=0;w<=r;w++)for(E=w/r,C=(E*(i-n)+n)/2,L=l&&0!==w&&w!==r?2:1,F=0;F<L;F++){for(l&&(B+=F),h&&(B+=2*F),N=0;N<=s;N++)S=N*T,P.x=Math.cos(-S)*C,P.y=-t/2+E*t,P.z=Math.sin(-S)*C,0===i&&w===r?(R.x=y[y.length-3*(s+1)],R.y=y[y.length-3*(s+1)+1],R.z=y[y.length-3*(s+1)+2]):(R.x=P.x,R.z=P.z,R.y=Math.sqrt(R.x*R.x+R.z*R.z)*A,R.normalize()),0===N&&(M.copyFrom(P),I.copyFrom(R)),v.push(P.x,P.y,P.z),y.push(R.x,R.y,R.z),V=l?U!==B?p[B].y:p[B].w:p[B].y+(p[B].w-p[B].y)*E,x.push(p[B].x+(p[B].z-p[B].x)*N/s,rn.e.UseOpenGLOrientationForUV?1-V:V),f&&b.push(f[B].r,f[B].g,f[B].b,f[B].a);1!==u&&h&&(v.push(P.x,P.y,P.z),v.push(0,P.y,0),v.push(0,P.y,0),v.push(M.x,M.y,M.z),o.P.CrossToRef(O,R,D),D.normalize(),y.push(D.x,D.y,D.z,D.x,D.y,D.z),o.P.CrossToRef(I,O,D),D.normalize(),y.push(D.x,D.y,D.z,D.x,D.y,D.z),V=l?U!==B?p[B+1].y:p[B+1].w:p[B+1].y+(p[B+1].w-p[B+1].y)*E,x.push(p[B+1].x,rn.e.UseOpenGLOrientationForUV?1-V:V),x.push(p[B+1].z,rn.e.UseOpenGLOrientationForUV?1-V:V),V=l?U!==B?p[B+2].y:p[B+2].w:p[B+2].y+(p[B+2].w-p[B+2].y)*E,x.push(p[B+2].x,rn.e.UseOpenGLOrientationForUV?1-V:V),x.push(p[B+2].z,rn.e.UseOpenGLOrientationForUV?1-V:V),f&&(b.push(f[B+1].r,f[B+1].g,f[B+1].b,f[B+1].a),b.push(f[B+1].r,f[B+1].g,f[B+1].b,f[B+1].a),b.push(f[B+2].r,f[B+2].g,f[B+2].b,f[B+2].a),b.push(f[B+2].r,f[B+2].g,f[B+2].b,f[B+2].a))),U!==B&&(U=B)}const k=1!==u&&h?s+4:s;for(w=0,B=0;B<r;B++){let e=0,t=0,i=0,n=0;for(N=0;N<s;N++)e=w*(k+1)+N,t=(w+1)*(k+1)+N,i=w*(k+1)+(N+1),n=(w+1)*(k+1)+(N+1),g.push(e,t,i),g.push(n,i,t);1!==u&&h&&(g.push(e+2,t+2,i+2),g.push(n+2,i+2,t+2),g.push(e+4,t+4,i+4),g.push(n+4,i+4,t+4)),w=l?w+2:w+1}const G=e=>{const r=e?i/2:n/2;if(0===r)return;let a,l,h;const c=e?p[_-1]:p[0];let d=null;f&&(d=e?f[_-1]:f[0]);const m=v.length/3,T=e?t/2:-t/2,S=new o.P(0,T,0);v.push(S.x,S.y,S.z),y.push(0,e?1:-1,0);const E=c.y+.5*(c.w-c.y);x.push(c.x+.5*(c.z-c.x),rn.e.UseOpenGLOrientationForUV?1-E:E),d&&b.push(d.r,d.g,d.b,d.a);const C=new o.FM(.5,.5);for(h=0;h<=s;h++){a=2*Math.PI*h*u/s;const t=Math.cos(-a),i=Math.sin(-a);l=new o.P(t*r,T,i*r);const n=new o.FM(t*C.x+.5,i*C.y+.5);v.push(l.x,l.y,l.z),y.push(0,e?1:-1,0);const p=c.y+(c.w-c.y)*n.y;x.push(c.x+(c.z-c.x)*n.x,rn.e.UseOpenGLOrientationForUV?1-p:p),d&&b.push(d.r,d.g,d.b,d.a)}for(h=0;h<s;h++)e?(g.push(m),g.push(m+(h+2)),g.push(m+(h+1))):(g.push(m),g.push(m+(h+1)),g.push(m+(h+2)))};c!==Nt.Kj.CAP_START&&c!==Nt.Kj.CAP_ALL||G(!1),c!==Nt.Kj.CAP_END&&c!==Nt.Kj.CAP_ALL||G(!0),sn.x._ComputeSides(d,v,g,y,x,e.frontUVs,e.backUVs);const z=new sn.x;return z.indices=g,z.positions=v,z.normals=y,z.uvs=x,f&&(z.colors=b),z}function an(e,t={},i){const n=new Nt.Kj(e,i);return t.sideOrientation=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,on(t).applyToMesh(n,t.updatable),n}const ln={CreateCylinder:an};function hn(e){const t=[],i=[],n=[],s=[],r=e.diameter||1,a=e.thickness||.5,l=e.tessellation||16,h=0===e.sideOrientation?0:e.sideOrientation||sn.x.DEFAULTSIDE,c=l+1;for(let e=0;e<=l;e++){const h=e/l,u=e*Math.PI*2/l-Math.PI/2,d=o.y3.Translation(r/2,0,0).multiply(o.y3.RotationY(u));for(let r=0;r<=l;r++){const u=1-r/l,p=r*Math.PI*2/l+Math.PI,f=Math.cos(p),_=Math.sin(p);let m=new o.P(f,_,0),g=m.scale(a/2);const v=new o.FM(h,u);g=o.P.TransformCoordinates(g,d),m=o.P.TransformNormal(m,d),i.push(g.x,g.y,g.z),n.push(m.x,m.y,m.z),s.push(v.x,rn.e.UseOpenGLOrientationForUV?1-v.y:v.y);const y=(e+1)%c,x=(r+1)%c;t.push(e*c+r),t.push(e*c+x),t.push(y*c+r),t.push(e*c+x),t.push(y*c+x),t.push(y*c+r)}}sn.x._ComputeSides(h,i,t,n,s,e.frontUVs,e.backUVs);const u=new sn.x;return u.indices=t,u.positions=i,u.normals=n,u.uvs=s,u}function cn(e,t={},i){const n=new Nt.Kj(e,i);return t.sideOrientation=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,hn(t).applyToMesh(n,t.updatable),n}sn.x.CreateCylinder=on,Nt.Kj.CreateCylinder=(e,t,i,n,s,r,o,a,l)=>(void 0!==o&&o instanceof k.x||(void 0!==o&&(l=a||Nt.Kj.DEFAULTSIDE,a=o),o=r,r=1),an(e,{height:t,diameterTop:i,diameterBottom:n,tessellation:s,subdivisions:r,sideOrientation:l,updatable:a},o));const un={CreateTorus:cn};sn.x.CreateTorus=hn,Nt.Kj.CreateTorus=(e,t,i,n,s,r,o)=>cn(e,{diameter:t,thickness:i,tessellation:n,sideOrientation:o,updatable:r},s);var dn=i(8027);class pn{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=pn._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=cn("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new Gi.K("targetMat",e);t.specularColor=a.Wo.Black(),t.emissiveColor=new a.Wo(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new Yt.z(o.P.Zero(),new o.P(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()}}pn._IdCounter=0;class fn extends pn{constructor(e,t,i){super(t,i),this.webVRController=e,this._laserPointer=an("laserPointer",{updatable:!1,height:1,diameterTop:.004,diameterBottom:2e-4,tessellation:20,subdivisions:1},t);const n=new Gi.K("laserPointerMat",t);if(n.emissiveColor=new a.Wo(.7,.7,.7),n.alpha=.6,this._laserPointer.material=n,this._laserPointer.rotation.x=Math.PI/2,this._laserPointer.position.z=-.5,this._laserPointer.isVisible=!1,this._laserPointer.isPickable=!1,!e.mesh){const i=new Nt.Kj("preloadControllerMesh",t),n=new Nt.Kj(Kt.POINTING_POSE,t);n.rotation.x=-.7,i.addChild(n),e.attachToMesh(i)}this._setLaserPointerParent(e.mesh),this._meshAttachedObserver=e._meshAttachedObservable.add((e=>{this._setLaserPointerParent(e)}))}_getForwardRay(e){return this.webVRController.getForwardRay(e)}_activatePointer(){super._activatePointer(),this._laserPointer.isVisible=!0}_deactivatePointer(){super._deactivatePointer(),this._laserPointer.isVisible=!1}_setLaserPointerColor(e){this._laserPointer.material.emissiveColor=e}_setLaserPointerLightingDisabled(e){this._laserPointer.material.disableLighting=e}_setLaserPointerParent(e){const t=e=>{e.isPickable=!1,e.getChildMeshes().forEach((e=>{t(e)}))};t(e);const i=e.getChildren(void 0,!1);let n=e;this.webVRController._pointingPoseNode=null;for(let e=0;e<i.length;e++)if(i[e].name&&i[e].name.indexOf(Kt.POINTING_POSE)>=0){n=i[e],this.webVRController._pointingPoseNode=n;break}this._laserPointer.parent=n}_updatePointerDistance(e=100){this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2}dispose(){super.dispose(),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)}}class _n extends pn{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new Yt.z(o.P.Zero(),o.P.Forward())}}class mn{}class gn{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get onControllerMeshLoaded(){return this.onControllerMeshLoadedObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._leftController&&this._leftController._gazeTracker&&this._leftController._gazeTracker.dispose(),this._rightController&&this._rightController._gazeTracker&&this._rightController._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker",this._leftController&&(this._leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this._rightController&&(this._rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))}get leftControllerGazeTrackerMesh(){return this._leftController?this._leftController._gazeTracker:null}get rightControllerGazeTrackerMesh(){return this._rightController?this._rightController._gazeTracker:null}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1))}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e,e?(this._rightController&&this._rightController._activatePointer(),this._leftController&&this._leftController._activatePointer()):(this._rightController&&(this._rightController._deactivatePointer(),this._rightController._gazeTracker.isVisible=!1),this._leftController&&(this._leftController._deactivatePointer(),this._leftController._gazeTracker.isVisible=!1))}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._webVRready?this._webVRCamera:this._scene.activeCamera}get webVRCamera(){return this._webVRCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated||null!==this._leftController&&this._leftController._teleportationRequestInitiated||null!==this._rightController&&this._rightController._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new r.y$,this.onAfterEnteringVRObservable=new r.y$,this.onExitingVRObservable=new r.y$,this.onControllerMeshLoadedObservable=new r.y$,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=gn.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new o.P(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new o.P(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._leftController=null,this._rightController=null,this._gazeColor=new a.Wo(.7,.7,.7),this._laserColor=new a.Wo(.7,.7,.7),this._pickedLaserColor=new a.Wo(.2,.2,1),this._pickedGazeColor=new a.Wo(0,0,1),this.onNewMeshSelected=new r.y$,this.onMeshSelectedWithController=new r.y$,this.onNewMeshPicked=new r.y$,this.onBeforeCameraTeleport=new r.y$,this.onAfterCameraTeleport=new r.y$,this.onSelectedMeshUnselected=new r.y$,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._interactionsRequested=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight(),this._fullscreenVRpresenting&&this._webVRready&&this.exitVR()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._leftController&&this._leftController._activePointer&&this._castRayAndSelectObject(this._leftController),this._rightController&&this._rightController._activePointer&&this._castRayAndSelectObject(this._rightController),this._noControllerIsActive&&(this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock)?this._castRayAndSelectObject(this._cameraGazer):this._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=e=>{if(e.type!==tt.POSE_ENABLED)e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(!this._leftController&&!this._rightController||this._leftController&&!this._leftController._activePointer&&this._rightController&&!this._rightController._activePointer)&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===tt.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&e===Wt.A&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&e===Wt.A&&this._cameraGazer._selectionPointerUp()})));else{const t=e,i=new fn(t,this._scene,this._cameraGazer._gazeTracker);"right"===t.hand||this._leftController&&this._leftController.webVRController!=t?this._rightController=i:this._leftController=i,this._tryEnableInteractionOnController(i)}},this._tryEnableInteractionOnController=e=>{this._interactionsRequested&&!e._interactionsEnabled&&this._enableInteractionOnController(e),this._teleportationRequested&&!e._teleportationEnabled&&this._enableTeleportationOnController(e)},this._onNewGamepadDisconnected=e=>{e instanceof Vi&&("left"===e.hand&&null!=this._leftController&&(this._leftController.dispose(),this._leftController=null),"right"===e.hand&&null!=this._rightController&&(this._rightController.dispose(),this._rightController=null))},this._workingVector=o.P.Zero(),this._workingQuaternion=o._f.Identity(),this._workingMatrix=o.y3.Identity(),_.Y.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),"getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),void 0===t.defaultHeight&&(t.defaultHeight=1.7),t.useCustomVRButton&&(this._useCustomVRButton=!0,t.customVRButton&&(this._btnVR=t.customVRButton)),t.rayLength&&(this._rayLength=t.rayLength),this._defaultHeight=t.defaultHeight,t.positionScale&&(this._rayLength*=t.positionScale,this._defaultHeight*=t.positionScale),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new o.P(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new Lt("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 It.C&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(o._f.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?nn.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(_.Y.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new _n((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case Xi.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case Xi.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case Xi.IN_XR:this._hasEnteredVR=!0;break;case Xi.NOT_IN_XR:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(t.useMultiview&&(t.vrDeviceOrientationCameraMetrics||(t.vrDeviceOrientationCameraMetrics=Ti.GetDefault()),t.vrDeviceOrientationCameraMetrics.multiviewEnabled=!0),this._vrDeviceOrientationCamera=new Ni("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._webVRCamera=new Ui("WebVRHelper",this._position,this._scene,t),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new _n((()=>this.currentVRCamera),e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(()=>{this.isInVRMode?this._scene.getEngine().disableVR():this.enterVR()}));const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera?this._displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add((e=>{e.vrDisplay&&this._displayVRButton()})),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())}),Re.kD.POINTERDOUBLETAP,!1),this._onVRDisplayChangedBind=e=>this._onVRDisplayChanged(e),this._onVrDisplayPresentChangeBind=()=>this._onVrDisplayPresentChange(),this._onVRRequestPresentStart=()=>{this._webVRrequesting=!0,this._updateButtonVisibility()},this._onVRRequestPresentComplete=()=>{this._webVRrequesting=!1,this._updateButtonVisibility()},e.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChangedBind),e.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),e.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),i.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),e.onDisposeObservable.add((()=>{this.dispose()})),this._webVRCamera.onControllerMeshLoadedObservable.add((e=>this._onDefaultMeshLoaded(e))),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this._updateButtonVisibility(),this._circleEase=new Y,this._circleEase.setEasingMode(j.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===Re.kD.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===Re.kD.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}_onDefaultMeshLoaded(e){this._leftController&&this._leftController.webVRController==e&&e.mesh&&this._leftController._setLaserPointerParent(e.mesh),this._rightController&&this._rightController.webVRController==e&&e.mesh&&this._rightController._setLaserPointerParent(e.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(e)}catch(e){_.Y.Warn("Error in your custom logic onControllerMeshLoaded: "+e)}}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===Xi.IN_XR||this._webVRpresenting||this._fullscreenVRpresenting}_onVrDisplayPresentChange(){const e=this._scene.getEngine().getVRDevice();if(e){const t=this._webVRpresenting;this._webVRpresenting=e.isPresenting,t&&!this._webVRpresenting&&this.exitVR()}else _.Y.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this._updateButtonVisibility()}_onVRDisplayChanged(e){this._webVRsupported=e.vrSupported,this._webVRready=!!e.vrDisplay,this._webVRpresenting=e.vrDisplay&&e.vrDisplay.isPresenting,this._updateButtonVisibility()}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode?this._btnVR.className+=" vrdisplaypresenting":(this._webVRready&&(this._btnVR.className+=" vrdisplayready"),this._webVRsupported&&(this._btnVR.className+=" vrdisplaysupported"),this._webVRrequesting&&(this._btnVR.className+=" vrdisplayrequesting")))}enterVR(){if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){_.Y.Warn("Error in your custom logic onEnteringVR: "+e)}if(this._scene.activeCamera){if(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=o._f.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this.webVRCamera){const e=this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y,t=o._f.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y-e,i=this.webVRCamera.rotationQuaternion.toEulerAngles().y;this.webVRCamera.rotationQuaternion=o._f.FromEulerAngles(0,i+t,0)}this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)}this._webVRrequesting||(this._webVRready?this._webVRpresenting||(this._scene.getEngine().onVRRequestPresentComplete.addOnce((e=>{this.onAfterEnteringVRObservable.notifyObservers({success:e})})),this._webVRCamera.position=this._position,this._scene.activeCamera=this._webVRCamera):this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce((()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})}))),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._displayLaserPointer&&[this._leftController,this._rightController].forEach((e=>{e&&e._activatePointer()})),this._hasEnteredVR=!0)}}exitVR(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){_.Y.Warn("Error in your custom logic onExitingVR: "+e)}this._webVRpresenting&&this._scene.getEngine().disableVR(),this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1)),this._scene.getEngine().resize(),[this._leftController,this._rightController].forEach((e=>{e&&e._deactivatePointer()})),this._hasEnteredVR=!1;const e=this._scene.getEngine();e._onVrDisplayPresentChange&&e._onVrDisplayPresentChange()}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this._interactionsRequested=!0,this.xr)return void(this.xr.baseExperience.state===Xi.IN_XR&&this.xr.pointerSelection.attach());this._leftController&&this._enableInteractionOnController(this._leftController),this._rightController&&this._enableInteractionOnController(this._rightController),this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}get _noControllerIsActive(){return!(this._leftController&&this._leftController._activePointer||this._rightController&&this._rightController._activePointer)}_isTeleportationFloor(e){for(let t=0;t<this._floorMeshesCollection.length;t++)if(this._floorMeshesCollection[t].id===e.id)return!0;return!(!this._floorMeshName||e.name!==this._floorMeshName)}addFloorMesh(e){this._floorMeshesCollection&&(this._floorMeshesCollection.indexOf(e)>-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this._teleportationRequested=!0,this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction),null!=this._leftController&&this._enableTeleportationOnController(this._leftController),null!=this._rightController&&this._enableTeleportationOnController(this._rightController);const t=new ki.$;t.vignetteColor=new a.HE(0,0,0,0),t.vignetteEnabled=!0,this._postProcessMove=new Wi("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,t),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}}_enableInteractionOnController(e){e.webVRController.mesh&&(e._interactionsEnabled=!0,this.isInVRMode&&this._displayLaserPointer&&e._activatePointer(),this.webVROptions.laserToggle&&e.webVRController.onMainButtonStateChangedObservable.add((t=>{this._displayLaserPointer&&1===t.value&&(e._activePointer?e._deactivatePointer():e._activatePointer(),this.displayGaze&&(e._gazeTracker.isVisible=e._activePointer))})),e.webVRController.onTriggerStateChangedObservable.add((t=>{let i=e;this._noControllerIsActive&&(i=this._cameraGazer),i._pointerDownOnMeshAsked?t.value<this._padSensibilityDown&&i._selectionPointerUp():t.value>this._padSensibilityUp&&i._selectionPointerDown()})))}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)<this._padSensibilityDown&&(this._teleportActive&&this.teleportCamera(this._haloCenter),t._teleportationRequestInitiated=!1):e.y<-this._padSensibilityUp&&t._dpadPressed&&(t._activatePointer(),t._teleportationRequestInitiated=!0))}_checkRotate(e,t){t._teleportationRequestInitiated||(t._rotationLeftAsked?e.x>-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.x<this._padSensibilityDown&&(t._rotationRightAsked=!1):e.x>this._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;let e=o._f.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(e=this.currentVRCamera.deviceRotationQuaternion,i=this.currentVRCamera.devicePosition),e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,o._f.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),o.P.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const n=new Yt.z(i,this._workingVector),s=this._scene.pickWithRay(n,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_enableTeleportationOnController(e){e.webVRController.mesh&&(e._interactionsEnabled||this._enableInteractionOnController(e),e._interactionsEnabled=!0,e._teleportationEnabled=!0,e.webVRController.controllerType===zt.VIVE&&(e._dpadPressed=!1,e.webVRController.onPadStateChangedObservable.add((t=>{e._dpadPressed=t.pressed,e._dpadPressed||(e._rotationLeftAsked=!1,e._rotationRightAsked=!1,e._teleportationBackRequestInitiated=!1)}))),e.webVRController.onPadValuesChangedObservable.add((t=>{this.teleportationEnabled&&(this._checkTeleportBackwards(t,e),this._checkTeleportWithRay(t,e)),this._checkRotate(t,e)})))}_createTeleportationCircles(){this._teleportationTarget=(0,dn.$6)("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new zi.c("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new Gi.K("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const n=cn("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);n.isPickable=!1,n.parent=this._teleportationTarget;const s=new D.f("animationInnerCircle","position.y",30,D.f.ANIMATIONTYPE_FLOAT,D.f.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),s.setKeys(r);const o=new ne;o.setEasingMode(j.EASINGMODE_EASEINOUT),s.setEasingFunction(o),n.animations=[],n.animations.push(s),this._scene.beginAnimation(n,0,60,!0),this._hideTeleportationTarget()}_displayTeleportationTarget(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof Dt.c))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=o._f.FromRotationMatrix(o.y3.RotationY(Math.PI/4*this._rotationAngle)),i=new D.f("animationRotation","rotationQuaternion",90,D.f.ANIMATIONTYPE_QUATERNION,D.f.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),n.push({frame:6,value:t}),i.setKeys(n),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const s=new D.f("animationPP","vignetteWeight",90,D.f.ANIMATIONTYPE_FLOAT,D.f.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:0}),r.push({frame:3,value:4}),r.push({frame:6,value:0}),s.setKeys(r),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);const a=new D.f("animationPP2","vignetteStretch",90,D.f.ANIMATIONTYPE_FLOAT,D.f.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._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,6,!1,1,(()=>{this._webVRCamera.detachPostProcess(this._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}_moveTeleportationSelectorTo(e,t,i){if(e.pickedPoint){t._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(e.pickedPoint),this._teleportationTarget.position.copyFrom(e.pickedPoint));const n=this._convertNormalToDirectionOfRay(e.getNormal(!0,!1),i);if(n){const e=o.P.Cross(We.RD.Y,n),t=o.P.Cross(n,e);o.P.RotationFromAxisToRef(t,n,e,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}}teleportCamera(e){if(!(this.currentVRCamera instanceof Dt.c))return;let t,i;if(this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),e.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(e),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==gn.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=o.P.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const n=new D.f("animationCameraTeleportation","position",90,D.f.ANIMATIONTYPE_VECTOR3,D.f.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];n.setKeys(s),n.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(n),this._postProcessMove.animations=[];const r=Math.round(i/2),a=new D.f("animationPP","vignetteWeight",90,D.f.ANIMATIONTYPE_FLOAT,D.f.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:r,value:8}),l.push({frame:i,value:0}),a.setKeys(l),this._postProcessMove.animations.push(a);const h=new D.f("animationPP2","vignetteStretch",90,D.f.ANIMATIONTYPE_FLOAT,D.f.ANIMATIONLOOPMODE_CONSTANT),c=[];c.push({frame:0,value:0}),c.push({frame:r,value:10}),c.push({frame:i,value:0}),h.setKeys(c),this._postProcessMove.animations.push(h),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,i,!1,t,(()=>{this._webVRCamera.detachPostProcess(this._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)})),this._hideTeleportationTarget()}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(o.P.Dot(e,t.direction))<Math.PI/2&&e.scaleInPlace(-1),e}_castRayAndSelectObject(e){if(!(this.currentVRCamera instanceof Dt.c))return;const t=e._getForwardRay(this._rayLength),i=this._scene.pickWithRay(t,this._raySelectionPredicate);if(i&&this._scene.simulatePointerMove(i,{pointerId:e._id}),e._currentHit=i,i&&i.pickedPoint){if(this._displayGaze){let n=1;e._gazeTracker.isVisible=!0,e._isActionableMesh&&(n=3),this.updateGazeTrackerScale&&(e._gazeTracker.scaling.x=i.distance*n,e._gazeTracker.scaling.y=i.distance*n,e._gazeTracker.scaling.z=i.distance*n);const s=this._convertNormalToDirectionOfRay(i.getNormal(),t),r=.002;if(s){const t=o.P.Cross(We.RD.Y,s),i=o.P.Cross(s,t);o.P.RotationFromAxisToRef(i,s,t,e._gazeTracker.rotation)}e._gazeTracker.position.copyFrom(i.pickedPoint),e._gazeTracker.position.x<0?e._gazeTracker.position.x+=r:e._gazeTracker.position.x-=r,e._gazeTracker.position.y<0?e._gazeTracker.position.y+=r:e._gazeTracker.position.y-=r,e._gazeTracker.position.z<0?e._gazeTracker.position.z+=r:e._gazeTracker.position.z-=r}e._updatePointerDistance(i.distance)}else e._updatePointerDistance(),e._gazeTracker.isVisible=!1;if(i&&i.pickedMesh){if(this._teleportationInitialized&&this._isTeleportationFloor(i.pickedMesh)&&i.pickedPoint)return e._currentMeshSelected&&!this._isTeleportationFloor(e._currentMeshSelected)&&this._notifySelectedMeshUnselected(e._currentMeshSelected),e._currentMeshSelected=null,void(e._teleportationRequestInitiated&&this._moveTeleportationSelectorTo(i,e,t));if(i.pickedMesh!==e._currentMeshSelected)if(this.meshSelectionPredicate(i.pickedMesh)){this.onNewMeshPicked.notifyObservers(i),e._currentMeshSelected=i.pickedMesh,i.pickedMesh.isPickable&&i.pickedMesh.actionManager?(this.changeGazeColor(this._pickedGazeColor),this.changeLaserColor(this._pickedLaserColor),e._isActionableMesh=!0):(this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor),e._isActionableMesh=!1);try{this.onNewMeshSelected.notifyObservers(i.pickedMesh);const t=e;t.webVRController&&this.onMeshSelectedWithController.notifyObservers({mesh:i.pickedMesh,controller:t.webVRController})}catch(e){_.Y.Warn("Error while raising onNewMeshSelected or onMeshSelectedWithController: "+e)}}else this._notifySelectedMeshUnselected(e._currentMeshSelected),e._currentMeshSelected=null,this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor)}else this._notifySelectedMeshUnselected(e._currentMeshSelected),e._currentMeshSelected=null,this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor)}_notifySelectedMeshUnselected(e){e&&this.onSelectedMeshUnselected.notifyObservers(e)}setLaserColor(e,t=this._pickedLaserColor){this._laserColor=e,this._pickedLaserColor=t}setLaserLightingState(e=!0){this._leftController&&this._leftController._setLaserPointerLightingDisabled(!e),this._rightController&&this._rightController._setLaserPointerLightingDisabled(!e)}setGazeColor(e,t=this._pickedGazeColor){this._gazeColor=e,this._pickedGazeColor=t}changeLaserColor(e){this.updateControllerLaserColor&&(this._leftController&&this._leftController._setLaserPointerColor(e),this._rightController&&this._rightController._setLaserPointerColor(e))}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e,this._leftController&&(this._leftController._gazeTracker.material.emissiveColor=e),this._rightController&&(this._rightController._gazeTracker.material.emissiveColor=e))}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._webVRCamera&&this._webVRCamera.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._leftController&&this._leftController.dispose(),this._rightController&&this._rightController.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.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChangedBind),this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart),this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}gn.TELEPORTATIONMODE_CONSTANTTIME=0,gn.TELEPORTATIONMODE_CONSTANTSPEED=1;const vn=function(){const e={root:0,found:!1};return function(t,i,n,s){e.root=0,e.found=!1;const r=i*i-4*t*n;if(r<0)return e;const o=Math.sqrt(r);let a=(-i-o)/(2*t),l=(-i+o)/(2*t);if(a>l){const e=l;l=a,a=e}return a>0&&a<s?(e.root=a,e.found=!0,e):l>0&&l<s?(e.root=l,e.found=!0,e):e}}();class yn{constructor(){this._collisionPoint=o.P.Zero(),this._planeIntersectionPoint=o.P.Zero(),this._tempVector=o.P.Zero(),this._tempVector2=o.P.Zero(),this._tempVector3=o.P.Zero(),this._tempVector4=o.P.Zero(),this._edge=o.P.Zero(),this._baseToVertex=o.P.Zero(),this._destinationPoint=o.P.Zero(),this._slidePlaneNormal=o.P.Zero(),this._displacementVector=o.P.Zero(),this._radius=o.P.One(),this._retry=0,this._basePointWorld=o.P.Zero(),this._velocityWorld=o.P.Zero(),this._normalizedVelocity=o.P.Zero(),this._collisionMask=-1}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}get slidePlaneNormal(){return this._slidePlaneNormal}_initialize(e,t,i){this._velocity=t,this._velocitySquaredLength=this._velocity.lengthSquared();const n=Math.sqrt(this._velocitySquaredLength);0===n||1===n?this._normalizedVelocity.copyFromFloats(t._x,t._y,t._z):t.scaleToRef(1/n,this._normalizedVelocity),this._basePoint=e,e.multiplyToRef(this._radius,this._basePointWorld),t.multiplyToRef(this._radius,this._velocityWorld),this._velocityWorldLength=this._velocityWorld.length(),this._epsilon=i,this.collisionFound=!1}_checkPointInTriangle(e,t,i,n,s){t.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),o.P.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);let r=o.P.Dot(this._tempVector4,s);return!(r<0)&&(n.subtractToRef(e,this._tempVector3),o.P.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),r=o.P.Dot(this._tempVector4,s),!(r<0)&&(o.P.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),r=o.P.Dot(this._tempVector4,s),r>=0))}_canDoCollision(e,t,i,n){const s=o.P.Distance(this._basePointWorld,e),r=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+r+t||!((e,t,i,n)=>!(e.x>i.x+n||i.x-n>t.x||e.y>i.y+n||i.y-n>t.y||e.z>i.z+n||i.z-n>t.z))(i,n,this._basePointWorld,this._velocityWorldLength+r))}_testTriangle(e,t,i,n,s,r,a){let l,h=!1;t||(t=[]),t[e]||(t[e]=new ot.J(0,0,0,0),t[e].copyFromPoints(i,n,s));const c=t[e];if(!r&&!c.isFrontFacingTo(this._normalizedVelocity,0))return;const u=c.signedDistanceTo(this._basePoint),d=o.P.Dot(c.normal,this._velocity);if(yn.DoubleSidedCheck&&d>1e-4)return;if(0==d){if(Math.abs(u)>=1)return;h=!0,l=0}else{l=(-1-u)/d;let e=(1-u)/d;if(l>e){const t=e;e=l,l=t}if(l>1||e<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);let p=!1,f=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,n,s,c.normal)&&(p=!0,f=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!p){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*o.P.Dot(this._velocity,this._tempVector),r=this._tempVector.lengthSquared()-1,a=vn(e,t,r,f);a.found&&(f=a.root,p=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(n,this._tempVector),t=2*o.P.Dot(this._velocity,this._tempVector),r=this._tempVector.lengthSquared()-1,a=vn(e,t,r,f),a.found&&(f=a.root,p=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(s,this._tempVector),t=2*o.P.Dot(this._velocity,this._tempVector),r=this._tempVector.lengthSquared()-1,a=vn(e,t,r,f),a.found&&(f=a.root,p=!0,this._collisionPoint.copyFrom(s)),n.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let l=this._edge.lengthSquared(),h=o.P.Dot(this._edge,this._velocity),c=o.P.Dot(this._edge,this._baseToVertex);if(e=l*-this._velocitySquaredLength+h*h,t=2*(l*o.P.Dot(this._velocity,this._baseToVertex)-h*c),r=l*(1-this._baseToVertex.lengthSquared())+c*c,a=vn(e,t,r,f),a.found){const e=(h*a.root-c)/l;e>=0&&e<=1&&(f=a.root,p=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex),l=this._edge.lengthSquared(),h=o.P.Dot(this._edge,this._velocity),c=o.P.Dot(this._edge,this._baseToVertex),e=l*-this._velocitySquaredLength+h*h,t=2*(l*o.P.Dot(this._velocity,this._baseToVertex)-h*c),r=l*(1-this._baseToVertex.lengthSquared())+c*c,a=vn(e,t,r,f),a.found){const e=(h*a.root-c)/l;e>=0&&e<=1&&(f=a.root,p=!0,this._edge.scaleInPlace(e),n.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),l=this._edge.lengthSquared(),h=o.P.Dot(this._edge,this._velocity),c=o.P.Dot(this._edge,this._baseToVertex),e=l*-this._velocitySquaredLength+h*h,t=2*(l*o.P.Dot(this._velocity,this._baseToVertex)-h*c),r=l*(1-this._baseToVertex.lengthSquared())+c*c,a=vn(e,t,r,f),a.found){const e=(h*a.root-c)/l;e>=0&&e<=1&&(f=a.root,p=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(p){const e=f*f*this._velocitySquaredLength;(!this.collisionFound||e<this._nearestDistanceSquared)&&(a.collisionResponse&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this._nearestDistanceSquared=e,this._nearestDistance=Math.sqrt(e),this.collisionFound=!0),this.collidedMesh=a)}}_collide(e,t,i,n,s,r,o,a,l,h=!1){if(h)if(i&&0!==i.length)for(let r=n;r<s-2;r+=1){const n=i[r],s=i[r+1],h=i[r+2];if(4294967295===h){r+=2;continue}const c=t[n],u=t[s],d=t[h];c&&u&&d&&((l?1:0)^r%2?this._testTriangle(r,e,c,u,d,o,a):this._testTriangle(r,e,u,c,d,o,a))}else for(let i=0;i<t.length-2;i+=1){const n=t[i],s=t[i+1],r=t[i+2];n&&s&&r&&((l?1:0)^i%2?this._testTriangle(i,e,n,s,r,o,a):this._testTriangle(i,e,s,n,r,o,a))}else if(i&&0!==i.length)for(let h=n;h<s;h+=3){const n=t[i[h]-r],s=t[i[h+1]-r],c=t[i[h+2]-r];l?this._testTriangle(h,e,n,s,c,o,a):this._testTriangle(h,e,c,s,n,o,a)}else for(let i=0;i<t.length;i+=3){const n=t[i],s=t[i+1],r=t[i+2];l?this._testTriangle(i,e,n,s,r,o,a):this._testTriangle(i,e,r,s,n,o,a)}}_getResponse(e,t){e.addToRef(t,this._destinationPoint),t.scaleInPlace(this._nearestDistance/t.length()),this._basePoint.addToRef(t,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this._epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(ot.J.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,t)}}yn.DoubleSidedCheck=!1;class xn{constructor(){this._scaledPosition=o.P.Zero(),this._scaledVelocity=o.P.Zero(),this._finalPosition=o.P.Zero()}getNewPosition(e,t,i,n,s,r,o){e.divideToRef(i._radius,this._scaledPosition),t.divideToRef(i._radius,this._scaledVelocity),i.collidedMesh=null,i._retry=0,i._initialVelocity=this._scaledVelocity,i._initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,n,this._finalPosition,s),this._finalPosition.multiplyInPlace(i._radius),r(o,this._finalPosition,i.collidedMesh)}createCollider(){return new yn}init(e){this._scene=e}_collideWithWorld(e,t,i,n,s,r=null){const o=10*ue.D.CollisionsEpsilon;if(i._retry>=n)return void s.copyFrom(e);const a=r?r.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=r&&r.surroundingMeshes||this._scene.meshes;for(let e=0;e<l.length;e++){const t=l[e];t.isEnabled()&&t.checkCollisions&&t.subMeshes&&t!==r&&0!=(a&t.collisionGroup)&&t._checkCollision(i)}i.collisionFound?(0===t.x&&0===t.y&&0===t.z||i._getResponse(e,t),t.length()<=o?s.copyFrom(e):(i._retry++,this._collideWithWorld(e,t,i,n,s,r))):e.addToRef(t,s)}}k.x.CollisionCoordinatorFactory=()=>new xn;var bn=i(5670),Tn=i(2312),Sn=i(9356),En=i(8198),Cn=i(9131);class An{constructor(e,t,i,n=""){var s,o;let a;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new r.y$,this.onErrorObservable=new r.y$,this.onBindObservable=new r.y$,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=Cn.x.WGSL,this.name=e,this._key=n,this._engine=i,this.uniqueId=An._UniqueIdSeed++,this.defines=null!==(s=t.defines)&&void 0!==s?s:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=null!==(o=t.entryPoint)&&void 0!==o?o:"main",this._shaderStore=si.v.GetShadersStore(this._shaderLanguage),this._shaderRepository=si.v.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=si.v.GetIncludesShadersStore(this._shaderLanguage);const l=(0,fe.CG)()?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("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(a,"Compute","",(i=>{En.L.Initialize(h),En.L.PreProcess(i,h,(n=>{this._rawComputeSourceCode=i,t.processFinalCode&&(n=t.processFinalCode(n));const s=En.L.Finalize(n,"",h);this._useFinalCode(s.vertexCode,e)}),this._engine)}))}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void n((0,fe.v)(e));if("source:"===e.substr(0,7))return void n(e.substr(7));if("base64:"===e.substr(0,7))return void n(window.atob(e.substr(7)));if(this._shaderStore[e+t+"Shader"])return void n(this._shaderStore[e+t+"Shader"]);if(i&&this._shaderStore[e+i+"Shader"])return void n(this._shaderStore[e+i+"Shader"]);let s;s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",n)}get computeSourceCode(){var e,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getComputeShaderCode())&&void 0!==t?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(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t){const i=/COMPUTE SHADER ERROR: 0:(\d+?):/;let n=null;if(t&&e){const s=t.match(i);if(s&&2===s.length){const t=parseInt(s[1]),i=e.split("\n",-1);i.length>=t&&(n=`Offending line [${t}] in compute code: ${i[t-1]}`)}}return[e,n]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,_.Y.Error("Unable to compile compute effect:"),_.Y.Error("Defines:\r\n"+this.defines),An.LogShaderCodeOnCompilationError){let e=null,t=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getComputeShaderCode())&&([t,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),t&&(_.Y.Error("Compute code:"),_.Y.Error(t))),e&&_.Y.Error(e)}_.Y.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){si.v.GetShadersStore(Cn.x.WGSL)[`${e}ComputeShader`]=t}}An._UniqueIdSeed=0,An.LogShaderCodeOnCompilationError=!0;var Pn,Rn=i(3230);!function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler"}(Pn||(Pn={})),Rn.B.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},Rn.B.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},Rn.B.prototype.createComputeContext=function(){},Rn.B.prototype.computeDispatch=function(e,t,i,n,s,r,o){throw new Error("computeDispatch: This engine does not support compute shaders!")},Rn.B.prototype.areAllComputeEffectsReady=function(){return!0},Rn.B.prototype.releaseComputeEffects=function(){},Rn.B.prototype._prepareComputePipelineContext=function(e,t,i,n,s){},Rn.B.prototype._rebuildComputeEffects=function(){},Rn.B.prototype._executeWhenComputeStateIsCompiled=function(e,t){t()},Rn.B.prototype._releaseComputeEffect=function(e){},Rn.B.prototype._deleteComputePipelineContext=function(e){};var Mn=i(8718),In=i(3297);class Dn{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,n={}){this._bindings={},this._samplers={},this._contextIsDirty=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=Mn.K.UniqueId,this._engine.getCaps().supportComputeShaders?n.bindingsMapping?(this._context=t.createComputeContext(),this._shaderPath=i,this._options={bindingsMapping:{},defines:[],...n}):_.Y.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!"):_.Y.Error("This engine does not support compute shaders!")}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){const n=this._bindings[e];this._bindings[e]={type:i?Pn.Texture:Pn.TextureWithoutSampler,object:t,indexInGroupEntries:null==n?void 0:n.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!n||n.object!==t||n.type!==this._bindings[e].type)}setStorageTexture(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:Pn.StorageTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setUniformBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:Pn.UniformBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setStorageBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:Pn.StorageBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setTextureSampler(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:Pn.Sampler,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}isReady(){let e=this._effect;for(const e in this._bindings){const t=this._bindings[e],i=t.type,n=t.object;switch(i){case Pn.Texture:case Pn.TextureWithoutSampler:case Pn.StorageTexture:if(!n.isReady())return!1}}const t=[],i=this._shaderPath;if(this._options.defines)for(let e=0;e<this._options.defines.length;e++)t.push(this._options.defines[e]);const n=t.join("\n");return this._cachedDefines!==n&&(this._cachedDefines=n,e=this._engine.createComputeEffect(i,{defines:n,entryPoint:this._options.entryPoint,onCompiled:this.onCompiled,onError:this.onError}),this._effect=e),!!e.isReady()}dispatch(e,t,i){var n;if(!this.isReady())return!1;for(const e in this._bindings){const t=this._bindings[e];if(!this._options.bindingsMapping[e])throw new Error("ComputeShader ('"+this.name+"'): No binding mapping has been provided for the property '"+e+"'");switch(t.type){case Pn.Texture:{const i=this._samplers[e],s=t.object;i&&s._texture&&i.compareSampler(s._texture)||(this._samplers[e]=(new In.a).setParameters(s.wrapU,s.wrapV,s.wrapR,s.anisotropicFilteringLevel,s._texture.samplingMode,null===(n=s._texture)||void 0===n?void 0:n._comparisonFunction),this._contextIsDirty=!0);break}case Pn.UniformBuffer:{const e=t.object;e.getBuffer()!==t.buffer&&(t.buffer=e.getBuffer(),this._contextIsDirty=!0);break}}}return this._contextIsDirty&&(this._contextIsDirty=!1,this._context.clear()),this._engine.computeDispatch(this._effect,this._context,this._bindings,e,t,i,this._options.bindingsMapping),!0}dispatchWhenReady(e,t,i,n=10){return new Promise((s=>{const r=()=>{this.dispatch(e,t,i)?s():setTimeout(r,n)};r()}))}serialize(){const e=Te.p4.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],n=i.object;switch(i.type){case Pn.Texture:case Pn.TextureWithoutSampler:case Pn.StorageTexture:{const s=n.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type});break}case Pn.UniformBuffer:}}return e}static Parse(e,t,i){const n=Te.p4.Parse((()=>new Dn(e.name,t.getEngine(),e.shaderPath,e.options)),e,t,i);for(const s in e.textures){const r=e.bindings[s],o=Ce.x.Parse(e.textures[s],t,i);r.type===Pn.Texture?n.setTexture(s,o):r.type===Pn.TextureWithoutSampler?n.setTexture(s,o,!1):n.setStorageTexture(s,o)}return n}}(0,be.gn)([(0,Te.qC)()],Dn.prototype,"name",void 0),(0,l.H)("BABYLON.ComputeShader",Dn);var On=i(5237),wn=i(3722),Nn=i(6667),Fn=i(5363);class Ln{constructor(e,t,i,n,s,r){this.entries=new Array,this._boundingVectors=new Array,this._capacity=i,this._depth=n,this._maxDepth=s,this._creationFunc=r,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks)for(let t=0;t<this.blocks.length;t++)this.blocks[t].addEntry(e);else this._creationFunc(e,this),this.entries.length>this.capacity&&this._depth<this._maxDepth&&this.createInnerBlocks()}removeEntry(e){if(this.blocks){for(let t=0;t<this.blocks.length;t++)this.blocks[t].removeEntry(e);return}const t=this.entries.indexOf(e);t>-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t<e.length;t++){const i=e[t];this.addEntry(i)}}select(e,t,i){if(On.k.IsInFrustum(this._boundingVectors,e)){if(this.blocks){for(let n=0;n<this.blocks.length;n++)this.blocks[n].select(e,t,i);return}i?t.concat(this.entries):t.concatWithNoDuplicate(this.entries)}}intersects(e,t,i,n){if(On.k.IntersectsSphere(this._minPoint,this._maxPoint,e,t)){if(this.blocks){for(let s=0;s<this.blocks.length;s++)this.blocks[s].intersects(e,t,i,n);return}n?i.concat(this.entries):i.concatWithNoDuplicate(this.entries)}}intersectsRay(e,t){if(e.intersectsBoxMinMax(this._minPoint,this._maxPoint)){if(this.blocks){for(let i=0;i<this.blocks.length;i++)this.blocks[i].intersectsRay(e,t);return}t.concatWithNoDuplicate(this.entries)}}createInnerBlocks(){Ln._CreateBlocks(this._minPoint,this._maxPoint,this.entries,this._capacity,this._depth,this._maxDepth,this,this._creationFunc),this.entries.splice(0)}static _CreateBlocks(e,t,i,n,s,r,a,l){a.blocks=new Array;const h=new o.P((t.x-e.x)/2,(t.y-e.y)/2,(t.z-e.z)/2);for(let t=0;t<2;t++)for(let o=0;o<2;o++)for(let c=0;c<2;c++){const u=e.add(h.multiplyByFloats(t,o,c)),d=e.add(h.multiplyByFloats(t+1,o+1,c+1)),p=new Ln(u,d,n,s+1,r,l);p.addEntries(i),a.blocks.push(p)}}}class Bn{constructor(e,t,i=2){this.maxDepth=i,this.dynamicContent=new Array,this._maxBlockCapacity=t||64,this._selectionContent=new Fn.f(1024),this._creationFunc=e}update(e,t,i){Ln._CreateBlocks(e,t,i,this._maxBlockCapacity,0,this.maxDepth,this,this._creationFunc)}addMesh(e){for(let t=0;t<this.blocks.length;t++)this.blocks[t].addEntry(e)}removeMesh(e){for(let t=0;t<this.blocks.length;t++)this.blocks[t].removeEntry(e)}select(e,t){this._selectionContent.reset();for(let i=0;i<this.blocks.length;i++)this.blocks[i].select(e,this._selectionContent,t);return t?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}intersects(e,t,i){this._selectionContent.reset();for(let n=0;n<this.blocks.length;n++)this.blocks[n].intersects(e,t,this._selectionContent,i);return i?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}intersectsRay(e){this._selectionContent.reset();for(let t=0;t<this.blocks.length;t++)this.blocks[t].intersectsRay(e,this._selectionContent);return this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}}Bn.CreationFuncForMeshes=(e,t)=>{const i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},Bn.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)};var Un=i(1795);k.x.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(ve.l.NAME_OCTREE);i||(i=new Vn(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new Bn(Bn.CreationFuncForMeshes,e,t));const n=this.getWorldExtends();return this._selectionOctree.update(n.min,n.max,this.meshes),this._selectionOctree},Object.defineProperty(k.x.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Un.x.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){const i=this.getScene();let n=i._getComponent(ve.l.NAME_OCTREE);n||(n=new Vn(i),i._addComponent(n)),this._submeshesOctree||(this._submeshesOctree=new Bn(Bn.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);const s=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(s.minimumWorld,s.maximumWorld,this.subMeshes),this._submeshesOctree};class Vn{constructor(e){this.name=ve.l.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new Yt.z(o.P.Zero(),new o.P(1,1,1)),(e=e||A.l.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=this.getActiveMeshCandidates.bind(this),this.scene.getActiveSubMeshCandidates=this.getActiveSubMeshCandidates.bind(this),this.scene.getCollidingSubMeshCandidates=this.getCollidingSubMeshCandidates.bind(this),this.scene.getIntersectingSubMeshCandidates=this.getIntersectingSubMeshCandidates.bind(this))}register(){this.scene.onMeshRemovedObservable.add((e=>{const t=this.scene.selectionOctree;if(null!=t){const i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}})),this.scene.onMeshImportedObservable.add((e=>{const t=this.scene.selectionOctree;null!=t&&t.addMesh(e)}))}getActiveMeshCandidates(){var e;return(null===(e=this.scene._selectionOctree)||void 0===e?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?(Yt.z.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(){}}var kn,Gn=i(3322),zn=i(9803);class Wn extends Gn.t{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreateArrow(e,t,i=1,n=!1){const s=new yi.Y("arrow",e),r=an("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),o=an("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return r.parent=s,r.material=t,r.rotation.x=Math.PI/2,r.position.z+=.3,o.parent=s,o.material=t,o.position.z+=.1375,o.rotation.x=Math.PI/2,n&&(o.visibility=0,r.visibility=0),s}static _CreateArrowInstance(e,t){const i=new yi.Y("arrow",e);for(const e of t.getChildMeshes())e.createInstance(e.name).parent=i;return i}constructor(e,t=a.Wo.Gray(),i=zn.x.DefaultUtilityLayer,n=null,s=1){var l;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new r.y$,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._parent=n,this._coloredMaterial=new Gi.K("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new a.Wo(.1,.1,.1)),this._hoverMaterial=new Gi.K("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a.Wo.Yellow(),this._disableMaterial=new Gi.K("",i.utilityLayerScene),this._disableMaterial.diffuseColor=a.Wo.Gray(),this._disableMaterial.alpha=.4;const h=Wn._CreateArrow(i.utilityLayerScene,this._coloredMaterial,s),c=Wn._CreateArrow(i.utilityLayerScene,this._coloredMaterial,s+4,!0);this._gizmoMesh=new Nt.Kj("",i.utilityLayerScene),this._gizmoMesh.addChild(h),this._gizmoMesh.addChild(c),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let u=0;const d={snapDistance:0};this.dragBehavior=new Le.M({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){this._handlePivot();let t=!1;if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(o.jp.Vector3[2]),o.jp.Vector3[2].addInPlace(e.delta),this.dragBehavior.validateDrag(o.jp.Vector3[2])&&(this.attachedNode.position&&this.attachedNode.position.addInPlaceFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.updateCache(),t=!0);else if(u+=e.dragDistance,Math.abs(u)>this.snapDistance){const i=Math.floor(Math.abs(u)/this.snapDistance);u%=this.snapDistance,e.delta.normalizeToRef(o.jp.Vector3[1]),o.jp.Vector3[1].scaleInPlace(this.snapDistance*i),this.attachedNode.getWorldMatrix().getTranslationToRef(o.jp.Vector3[2]),o.jp.Vector3[2].addInPlace(o.jp.Vector3[1]),this.dragBehavior.validateDrag(o.jp.Vector3[2])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(o.jp.Vector3[1].x,o.jp.Vector3[1].y,o.jp.Vector3[1].z),this.attachedNode.updateCache(),d.snapDistance=this.snapDistance*i,this.onSnapObservable.notifyObservers(d),t=!0)}t&&this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const p=i._getSharedGizmoLight();p.includedOnlyMeshes=p.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const f={gizmoMeshes:h.getChildMeshes(),colliderMeshes:c.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(l=this._parent)||void 0===l||l.addToAxisCache(c,f),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{var t;if(!this._customMeshSet&&(this._isHovered=!(-1==f.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh)),!this._parent)){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(f.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(f.gizmoMeshes,e?f.material:f.disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}class Hn{get xAxis(){return this._xAxis}get yAxis(){return this._yAxis}get zAxis(){return this._zAxis}constructor(e,t=1,i=2,n,s,r,l=1){if(this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this.scaleLines=1,e=e||A.l.LastCreatedScene){if(this.scaleLines=t,!n){const t=new Gi.K("",e);t.disableLighting=!0,t.emissiveColor=a.Wo.Red().scale(.5),n=Wn._CreateArrow(e,t,l)}if(!s){const t=new Gi.K("",e);t.disableLighting=!0,t.emissiveColor=a.Wo.Green().scale(.5),s=Wn._CreateArrow(e,t,l)}if(!r){const t=new Gi.K("",e);t.disableLighting=!0,t.emissiveColor=a.Wo.Blue().scale(.5),r=Wn._CreateArrow(e,t,l)}this._xAxis=n,this._xAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._yAxis=s,this._yAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._zAxis=r,this._zAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),null!=i&&(Hn._SetRenderingGroupId(this._xAxis,i),Hn._SetRenderingGroupId(this._yAxis,i),Hn._SetRenderingGroupId(this._zAxis,i)),this.scene=e,this.update(new o.P,o.P.Right(),o.P.Up(),o.P.Forward())}}update(e,t,i,n){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._xAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._yAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(n),this._zAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor)}createInstance(){const e=Wn._CreateArrowInstance(this.scene,this._xAxis),t=Wn._CreateArrowInstance(this.scene,this._yAxis),i=Wn._CreateArrowInstance(this.scene,this._zAxis),n=new Hn(this.scene,this.scaleLines,null,e,t,i);return n._instanced=!0,n}dispose(){this._xAxis&&this._xAxis.dispose(!1,!this._instanced),this._yAxis&&this._yAxis.dispose(!1,!this._instanced),this._zAxis&&this._zAxis.dispose(!1,!this._instanced),this.scene=null}static _SetRenderingGroupId(e,t){e.getChildMeshes().forEach((e=>{e.renderingGroupId=t}))}}class Xn extends Hn{constructor(e,t,i,n=1){super(e,n),this.pos=o.P.Zero(),this.xaxis=o.P.Zero(),this.yaxis=o.P.Zero(),this.zaxis=o.P.Zero(),this.mesh=i,this.bone=t}update(){if(!this.mesh||!this.bone)return;const e=this.bone;e.getAbsolutePositionToRef(this.mesh,this.pos),e.getDirectionToRef(We.RD.X,this.mesh,this.xaxis),e.getDirectionToRef(We.RD.Y,this.mesh,this.yaxis),e.getDirectionToRef(We.RD.Z,this.mesh,this.zaxis),super.update(this.pos,this.xaxis,this.yaxis,this.zaxis)}dispose(){this.mesh&&(this.mesh=null,this.bone=null,super.dispose())}}Object.defineProperty(k.x.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new jn(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(kn||(kn={}));class jn{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new r.y$),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new r.y$),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||A.l.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 e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}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(void 0===this.BJSINSPECTOR){const i=e&&e.inspectorURL?e.inspectorURL:jn.InspectorURL;de.w1.LoadScript(i,(()=>{this._createInspector(e),t(this)}))}else this._createInspector(e),t(this)}))}}jn.InspectorURL=`https://unpkg.com/babylonjs-inspector@${ue.D.Version}/babylon.inspector.bundle.js`;var Yn=i(7422);function qn(e){const t=e.segments||32,i=e.diameterX||e.diameter||1,n=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,r=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,a=e.slice&&e.slice<=0?1:e.slice||1,l=0===e.sideOrientation?0:e.sideOrientation||sn.x.DEFAULTSIDE,h=!!e.dedupTopBottomIndices,c=new o.P(i/2,n/2,s/2),u=2+t,d=2*u,p=[],f=[],_=[],m=[];for(let e=0;e<=u;e++){const t=e/u,i=t*Math.PI*a;for(let e=0;e<=d;e++){const n=e/d,s=n*Math.PI*2*r,a=o.y3.RotationZ(-i),l=o.y3.RotationY(s),h=o.P.TransformCoordinates(o.P.Up(),a),u=o.P.TransformCoordinates(h,l),p=u.multiply(c),g=u.divide(c).normalize();f.push(p.x,p.y,p.z),_.push(g.x,g.y,g.z),m.push(n,rn.e.UseOpenGLOrientationForUV?1-t:t)}if(e>0){const t=f.length/3;for(let i=t-2*(d+1);i+d+2<t;i++)h?(e>1&&(p.push(i),p.push(i+1),p.push(i+d+1)),(e<u||a<1)&&(p.push(i+d+1),p.push(i+1),p.push(i+d+2))):(p.push(i),p.push(i+1),p.push(i+d+1),p.push(i+d+1),p.push(i+1),p.push(i+d+2))}}sn.x._ComputeSides(l,f,p,_,m,e.frontUVs,e.backUVs);const g=new sn.x;return g.indices=p,g.positions=f,g.normals=_,g.uvs=m,g}function Kn(e,t={},i=null){const n=new Nt.Kj(e,i);return t.sideOrientation=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,qn(t).applyToMesh(n,t.updatable),n}const $n={CreateSphere:Kn};sn.x.CreateSphere=qn,Nt.Kj.CreateSphere=(e,t,i,n,s,r)=>Kn(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:r,updatable:s},n);var Qn=i(4389);function Zn(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const t=Math.max(e.subdivisions?e.subdivisions:2,1),i=Math.max(e.tessellation?e.tessellation:16,3),n=Math.max(e.height?e.height:1,0),s=Math.max(e.radius?e.radius:.25,0),r=Math.max(e.capSubdivisions?e.capSubdivisions:6,1),a=i,l=t,h=Math.max(e.radiusTop?e.radiusTop:s,0),c=Math.max(e.radiusBottom?e.radiusBottom:s,0),u=n-(h+c),d=2*Math.PI,p=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:r,1),f=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:r,1),_=Math.acos((c-h)/n);let m=[];const g=[],v=[],y=[];let x=0;const b=[],T=.5*u,S=.5*Math.PI;let E,C;const A=o.P.Zero(),P=o.P.Zero(),R=Math.cos(_),M=Math.sin(_),I=new o.FM(h*M,T+h*R).subtract(new o.FM(c*M,c*R-T)).length(),D=h*_+I+c*(S-_);let O=0;for(C=0;C<=p;C++){const e=[],t=S-_*(C/p);O+=h*_/p;const i=Math.cos(t),n=Math.sin(t),s=i*h;for(E=0;E<=a;E++){const t=E/a,r=t*d+0,o=Math.sin(r),l=Math.cos(r);P.x=s*o,P.y=T+n*h,P.z=s*l,g.push(P.x,P.y,P.z),A.set(i*o,n,i*l),v.push(A.x,A.y,A.z),y.push(t,rn.e.UseOpenGLOrientationForUV?O/D:1-O/D),e.push(x),x++}b.push(e)}const w=n-h-c+R*h-R*c,N=M*(c-h)/w;for(C=1;C<=l;C++){const e=[];O+=I/l;const t=M*(C*(c-h)/l+h);for(E=0;E<=a;E++){const i=E/a,n=i*d+0,s=Math.sin(n),r=Math.cos(n);P.x=t*s,P.y=T+R*h-C*w/l,P.z=t*r,g.push(P.x,P.y,P.z),A.set(s,N,r).normalize(),v.push(A.x,A.y,A.z),y.push(i,rn.e.UseOpenGLOrientationForUV?O/D:1-O/D),e.push(x),x++}b.push(e)}for(C=1;C<=f;C++){const e=[],t=S-_-(Math.PI-_)*(C/f);O+=c*_/f;const i=Math.cos(t),n=Math.sin(t),s=i*c;for(E=0;E<=a;E++){const t=E/a,r=t*d+0,o=Math.sin(r),l=Math.cos(r);P.x=s*o,P.y=n*c-T,P.z=s*l,g.push(P.x,P.y,P.z),A.set(i*o,n,i*l),v.push(A.x,A.y,A.z),y.push(t,rn.e.UseOpenGLOrientationForUV?O/D:1-O/D),e.push(x),x++}b.push(e)}for(E=0;E<a;E++)for(C=0;C<p+l+f;C++){const e=b[C][E],t=b[C+1][E],i=b[C+1][E+1],n=b[C][E+1];m.push(e),m.push(t),m.push(n),m.push(t),m.push(i),m.push(n)}if(m=m.reverse(),e.orientation&&!e.orientation.equals(o.P.Up())){const t=new o.y3;e.orientation.clone().scale(.5*Math.PI).cross(o.P.Up()).toQuaternion().toRotationMatrix(t);const i=o.P.Zero();for(let e=0;e<g.length;e+=3)i.set(g[e],g[e+1],g[e+2]),o.P.TransformCoordinatesToRef(i.clone(),t,i),g[e]=i.x,g[e+1]=i.y,g[e+2]=i.z}const F=new sn.x;return F.positions=g,F.normals=v,F.uvs=y,F.indices=m,F}function Jn(e,t={orientation:o.P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1},i=null){const n=new Nt.Kj(e,i);return Zn(t).applyToMesh(n,t.updatable),n}const es={CreateCapsule:Jn};Nt.Kj.CreateCapsule=(e,t,i)=>Jn(e,t,i),sn.x.CreateCapsule=Zn;class ts{constructor(e){if(this._impostors=[],this._meshes=[],this._bodies=[],this._bodyMeshes=[],this._numMeshes=0,this._numBodies=0,this._debugMeshMeshes=new Array,this._scene=e||A.l.LastCreatedScene,!this._scene)return;const t=this._scene.getPhysicsEngine();t&&(this._physicsEnginePlugin=t.getPhysicsPlugin()),this._utilityLayer=new zn.x(this._scene,!1),this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!0}_updateDebugMeshes(){const e=this._physicsEnginePlugin;1===(null==e?void 0:e.getPluginVersion())?this._updateDebugMeshesV1():this._updateDebugMeshesV2()}_updateDebugMeshesV1(){const e=this._physicsEnginePlugin;for(let t=0;t<this._numMeshes;t++){const i=this._impostors[t];if(i)if(i.isDisposed)this.hideImpostor(this._impostors[t--]);else{if(i.type===Qn.Q.MeshImpostor)continue;const n=this._meshes[t];n&&e&&e.syncMeshWithImpostor(n,i)}}}_updateDebugMeshesV2(){const e=this._physicsEnginePlugin;for(let t=0;t<this._numBodies;t++){const i=this._bodies[t],n=this._bodyMeshes[t];i&&n&&e.syncTransform(i,n)}}showImpostor(e,t){if(!this._scene)return null;for(let t=0;t<this._numMeshes;t++)if(this._impostors[t]==e)return null;const i=this._getDebugMesh(e,t);return i&&(this._impostors[this._numMeshes]=e,this._meshes[this._numMeshes]=i,0===this._numMeshes&&(this._renderFunction=this._updateDebugMeshes.bind(this),this._scene.registerBeforeRender(this._renderFunction)),this._numMeshes++),i}showBody(e){if(!this._scene)return null;for(let t=0;t<this._numBodies;t++)if(this._bodies[t]==e)return null;const t=this._getDebugBodyMesh(e);return t&&(this._bodies[this._numBodies]=e,this._bodyMeshes[this._numBodies]=t,0===this._numBodies&&(this._renderFunction=this._updateDebugMeshes.bind(this),this._scene.registerBeforeRender(this._renderFunction)),this._numBodies++),t}hideImpostor(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let n=0;n<this._numMeshes;n++)if(this._impostors[n]==e){const e=this._meshes[n];if(!e)continue;i.removeMesh(e),e.dispose();const s=this._debugMeshMeshes.indexOf(e);s>-1&&this._debugMeshMeshes.splice(s,1),this._numMeshes--,this._numMeshes>0?(this._meshes[n]=this._meshes[this._numMeshes],this._impostors[n]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}hideBody(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let n=0;n<this._numBodies;n++)if(this._bodies[n]===e){const e=this._bodyMeshes[n];if(!e)continue;i.removeMesh(e),e.dispose(),this._numBodies--,this._numBodies>0?(this._bodyMeshes[n]=this._bodyMeshes[this._numBodies],this._bodies[n]=this._bodies[this._numBodies],this._bodyMeshes[this._numBodies]=null,this._bodies[this._numBodies]=null):(this._bodyMeshes[0]=null,this._bodies[0]=null),t=!0;break}t&&0===this._numBodies&&this._scene.unregisterBeforeRender(this._renderFunction)}_getDebugMaterial(e){return this._debugMaterial||(this._debugMaterial=new Gi.K("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=a.Wo.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial}_getDebugBoxMesh(e){return this._debugBoxMesh||(this._debugBoxMesh=(0,Yn.NR)("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=o._f.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")}_getDebugSphereMesh(e){return this._debugSphereMesh||(this._debugSphereMesh=Kn("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=o._f.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")}_getDebugCapsuleMesh(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=Jn("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=o._f.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")}_getDebugCylinderMesh(e){return this._debugCylinderMesh||(this._debugCylinderMesh=an("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=o._f.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")}_getDebugMeshMesh(e,t){const i=new Nt.Kj(e.name,t,null,e);return i.setParent(e),i.position=o.P.Zero(),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i}_getDebugMesh(e,t){if(!this._utilityLayer)return null;if(t&&t.parent&&t.parent.physicsImpostor)return null;let i=null;const n=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return _.Y.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case Qn.Q.BoxImpostor:i=this._getDebugBoxMesh(n),e.getBoxSizeToRef(i.scaling);break;case Qn.Q.SphereImpostor:{i=this._getDebugSphereMesh(n);const t=e.getRadius();i.scaling.x=2*t,i.scaling.y=2*t,i.scaling.z=2*t;break}case Qn.Q.CapsuleImpostor:{i=this._getDebugCapsuleMesh(n);const t=e.object.getBoundingInfo();i.scaling.x=2*(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=2*(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}case Qn.Q.MeshImpostor:t&&(i=this._getDebugMeshMesh(t,n));break;case Qn.Q.NoImpostor:t?t.getChildMeshes().filter((e=>e.physicsImpostor?1:0)).forEach((e=>{if(e.physicsImpostor&&"Mesh"===e.getClassName()){const t=e.getBoundingInfo(),s=t.boundingBox.minimum,r=t.boundingBox.maximum;switch(e.physicsImpostor.type){case Qn.Q.BoxImpostor:i=this._getDebugBoxMesh(n),i.position.copyFrom(s),i.position.addInPlace(r),i.position.scaleInPlace(.5);break;case Qn.Q.SphereImpostor:i=this._getDebugSphereMesh(n);break;case Qn.Q.CylinderImpostor:i=this._getDebugCylinderMesh(n);break;default:i=null}i&&(i.scaling.x=r.x-s.x,i.scaling.y=r.y-s.y,i.scaling.z=r.z-s.z,i.parent=e)}})):_.Y.Warn("No target mesh parameter provided for NoImpostor. Skipping."),i=null;break;case Qn.Q.CylinderImpostor:{i=this._getDebugCylinderMesh(n);const t=e.object.getBoundingInfo();i.scaling.x=(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}}return i}_getDebugBodyMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=new Nt.Kj("custom",t),n=new sn.x,s=e.getGeometry();if(n.positions=s.positions,n.indices=s.indices,n.applyToMesh(i),e._pluginDataInstances){const t=new Float32Array(16*e._pluginDataInstances.length);i.thinInstanceSetBuffer("matrix",t,16)}return i.material=this._getDebugMaterial(t),i}dispose(){for(let e=this._numMeshes-1;e>=0;e--)this.hideImpostor(this._impostors[0]);for(let e=this._numBodies-1;e>=0;e--)this.hideBody(this._bodies[0]);this._debugBoxMesh&&this._debugBoxMesh.dispose(),this._debugSphereMesh&&this._debugSphereMesh.dispose(),this._debugCylinderMesh&&this._debugCylinderMesh.dispose(),this._debugMaterial&&this._debugMaterial.dispose(),this._impostors.length=0,this._scene=null,this._physicsEnginePlugin=null,this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)}}var is=i(8591);function ns(e){const t=[],i=[],n=e.lines,s=e.colors,r=[];let o=0;for(let e=0;e<n.length;e++){const a=n[e];for(let n=0;n<a.length;n++){if(i.push(a[n].x,a[n].y,a[n].z),s){const t=s[e];r.push(t[n].r,t[n].g,t[n].b,t[n].a)}n>0&&(t.push(o-1),t.push(o)),o++}}const a=new sn.x;return a.indices=t,a.positions=i,s&&(a.colors=r),a}function ss(e){const t=e.dashSize||3,i=e.gapSize||1,n=e.dashNb||200,s=e.points,r=new Array,a=new Array,l=o.P.Zero();let h=0,c=0,u=0,d=0,p=0,f=0,_=0;for(_=0;_<s.length-1;_++)s[_+1].subtractToRef(s[_],l),h+=l.length();for(u=h/n,d=t*u/(t+i),_=0;_<s.length-1;_++){s[_+1].subtractToRef(s[_],l),c=Math.floor(l.length()/u),l.normalize();for(let e=0;e<c;e++)p=u*e,r.push(s[_].x+p*l.x,s[_].y+p*l.y,s[_].z+p*l.z),r.push(s[_].x+(p+d)*l.x,s[_].y+(p+d)*l.y,s[_].z+(p+d)*l.z),a.push(f,f+1),f+=2}const m=new sn.x;return m.positions=r,m.indices=a,m}function rs(e,t,i){const n=t.instance,s=t.lines,r=t.colors;if(n){const e=n.getVerticesData(qe.o.PositionKind);let t,i;r&&(t=n.getVerticesData(qe.o.ColorKind));let o=0,a=0;for(let n=0;n<s.length;n++){const l=s[n];for(let s=0;s<l.length;s++)e[o]=l[s].x,e[o+1]=l[s].y,e[o+2]=l[s].z,r&&t&&(i=r[n],t[a]=i[s].r,t[a+1]=i[s].g,t[a+2]=i[s].b,t[a+3]=i[s].a,a+=4),o+=3}return n.updateVerticesData(qe.o.PositionKind,e,!1,!1),r&&t&&n.updateVerticesData(qe.o.ColorKind,t,!1,!1),n}const o=!!r,a=new is._(e,i,null,void 0,void 0,o,t.useVertexAlpha,t.material);return ns(t).applyToMesh(a,t.updatable),a}function os(e,t,i=null){const n=t.colors?[t.colors]:null;return rs(e,{lines:[t.points],updatable:t.updatable,instance:t.instance,colors:n,useVertexAlpha:t.useVertexAlpha,material:t.material},i)}function as(e,t,i=null){const n=t.points,s=t.instance,r=t.gapSize||1,a=t.dashSize||3;if(s){const e=e=>{const t=o.P.Zero(),i=e.length/6;let r=0,a=0,l=0,h=0,c=0,u=0,d=0,p=0;for(d=0;d<n.length-1;d++)n[d+1].subtractToRef(n[d],t),r+=t.length();l=r/i;const f=s._creationDataStorage.dashSize;for(h=f*l/(f+s._creationDataStorage.gapSize),d=0;d<n.length-1;d++)for(n[d+1].subtractToRef(n[d],t),a=Math.floor(t.length()/l),t.normalize(),p=0;p<a&&u<e.length;)c=l*p,e[u]=n[d].x+c*t.x,e[u+1]=n[d].y+c*t.y,e[u+2]=n[d].z+c*t.z,e[u+3]=n[d].x+(c+h)*t.x,e[u+4]=n[d].y+(c+h)*t.y,e[u+5]=n[d].z+(c+h)*t.z,u+=6,p++;for(;u<e.length;)e[u]=n[d].x,e[u+1]=n[d].y,e[u+2]=n[d].z,u+=3};return(t.dashNb||t.dashSize||t.gapSize||t.useVertexAlpha||t.material)&&_.Y.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."),s.updateMeshPositions(e,!1),s}const l=new is._(e,i,null,void 0,void 0,void 0,t.useVertexAlpha,t.material);return ss(t).applyToMesh(l,t.updatable),l._creationDataStorage=new Nt.gW,l._creationDataStorage.dashSize=a,l._creationDataStorage.gapSize=r,l}const ls={CreateDashedLines:as,CreateLineSystem:rs,CreateLines:os};sn.x.CreateLineSystem=ns,sn.x.CreateDashedLines=ss,Nt.Kj.CreateLines=(e,t,i=null,n=!1,s=null)=>os(e,{points:t,updatable:n,instance:s},i),Nt.Kj.CreateDashedLines=(e,t,i,n,s,r=null,o,a)=>as(e,{points:t,dashSize:i,gapSize:n,dashNb:s,updatable:o,instance:a},r);class hs{static CreateAndShow(e,t,i){const n=new hs(e);return n.show(t,i),n}constructor(e){this.ray=e}show(e,t){if(!this._renderFunction&&this.ray){const t=this.ray;this._renderFunction=this._render.bind(this),this._scene=e,this._renderPoints=[t.origin,t.origin.add(t.direction.scale(t.length))],this._renderLine=os("ray",{points:this._renderPoints,updatable:!0},e),this._renderLine.isPickable=!1,this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}t&&this._renderLine&&this._renderLine.color.copyFrom(t)}hide(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])}_render(){var e;const t=this.ray;if(!t)return;const i=this._renderPoints[1],n=Math.min(t.length,1e6);i.copyFrom(t.direction),i.scaleInPlace(n),i.addInPlace(t.origin),this._renderPoints[0].copyFrom(t.origin),os("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),null===(e=this._renderLine)||void 0===e||e.refreshBoundingInfo()}attachToMesh(e,t,i,n){this._attachedToMesh=e;const s=this.ray;s&&(s.direction||(s.direction=o.P.Zero()),s.origin||(s.origin=o.P.Zero()),n&&(s.length=n),i||(i=o.P.Zero()),t||(t=new o.P(0,0,-1)),this._scene||(this._scene=e.getScene()),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(t),this._meshSpaceOrigin.copyFrom(i)):(this._meshSpaceDirection=t.clone(),this._meshSpaceOrigin=i.clone()),this._onAfterRenderObserver||(this._onAfterRenderObserver=this._scene.onBeforeRenderObservable.add((()=>this._updateToMesh())),this._onAfterStepObserver=this._scene.onAfterStepObservable.add((()=>this._updateToMesh()))),this._attachedToMesh.computeWorldMatrix(!0),this._updateToMesh())}detachFromMesh(){this._attachedToMesh&&this._scene&&(this._onAfterRenderObserver&&(this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver),this._scene.onAfterStepObservable.remove(this._onAfterStepObserver)),this._attachedToMesh=null,this._onAfterRenderObserver=null,this._onAfterStepObserver=null,this._scene=null)}_updateToMesh(){const e=this.ray;this._attachedToMesh&&e&&(this._attachedToMesh.isDisposed()?this.detachFromMesh():(this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,e.direction),o.P.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)))}dispose(){this.hide(),this.detachFromMesh(),this.ray=null}}var cs=i(7104),us=i(8097),ds=i(1979);function ps(e){let t=e.pathArray;const i=e.closeArray||!1,n=e.closePath||!1,s=e.invertUV||!1,r=Math.floor(t[0].length/2);let o=e.offset||r;o=o>r?r:Math.floor(o);const a=0===e.sideOrientation?0:e.sideOrientation||sn.x.DEFAULTSIDE,l=e.uvs,h=e.colors,c=[],u=[],d=[],p=[],f=[],_=[],m=[],g=[];let v;const y=[],x=[];let b,T,S;if(t.length<2){const e=[],i=[];for(T=0;T<t[0].length-o;T++)e.push(t[0][T]),i.push(t[0][T+o]);t=[e,i]}let E=0;const C=n?1:0;let A,P,R,M,I,D;for(v=t[0].length,b=0;b<t.length;b++){for(m[b]=0,f[b]=[0],A=t[b],P=A.length,v=v<P?v:P,S=0;S<P;)c.push(A[S].x,A[S].y,A[S].z),S>0&&(R=A[S].subtract(A[S-1]).length(),M=R+m[b],f[b].push(M),m[b]=M),S++;n&&(S--,c.push(A[0].x,A[0].y,A[0].z),R=A[S].subtract(A[0]).length(),M=R+m[b],f[b].push(M),m[b]=M),y[b]=P+C,x[b]=E,E+=P+C}let O,w,N=null,F=null;for(T=0;T<v+C;T++){for(g[T]=0,_[T]=[0],b=0;b<t.length-1;b++)I=t[b],D=t[b+1],T===v?(N=I[0],F=D[0]):(N=I[T],F=D[T]),R=F.subtract(N).length(),M=R+g[T],_[T].push(M),g[T]=M;i&&F&&N&&(I=t[b],D=t[0],T===v&&(F=D[0]),R=F.subtract(N).length(),M=R+g[T],g[T]=M)}if(l)for(b=0;b<l.length;b++)p.push(l[b].x,rn.e.UseOpenGLOrientationForUV?1-l[b].y:l[b].y);else for(b=0;b<t.length;b++)for(T=0;T<v+C;T++)O=0!=m[b]?f[b][T]/m[b]:0,w=0!=g[T]?_[T][b]/g[T]:0,s?p.push(w,O):p.push(O,rn.e.UseOpenGLOrientationForUV?1-w:w);b=0;let L=0,B=y[b]-1,U=y[b+1]-1,V=B<U?B:U,k=x[1]-x[0];const G=i?y.length:y.length-1;for(;L<=V&&b<G;)u.push(L,L+k,L+1),u.push(L+k+1,L+1,L+k),L+=1,L===V&&(b++,b===y.length-1?(k=x[0]-x[b],B=y[b]-1,U=y[0]-1):(k=x[b+1]-x[b],B=y[b]-1,U=y[b+1]-1),L=x[b],V=B<U?B+L:U+L);if(sn.x.ComputeNormals(c,u,d),n){let e=0,i=0;for(b=0;b<t.length;b++)e=3*x[b],i=b+1<t.length?3*(x[b+1]-1):d.length-3,d[e]=.5*(d[e]+d[i]),d[e+1]=.5*(d[e+1]+d[i+1]),d[e+2]=.5*(d[e+2]+d[i+2]),d[i]=d[e],d[i+1]=d[e+1],d[i+2]=d[e+2]}sn.x._ComputeSides(a,c,u,d,p,e.frontUVs,e.backUVs);let z=null;if(h){z=new Float32Array(4*h.length);for(let e=0;e<h.length;e++)z[4*e]=h[e].r,z[4*e+1]=h[e].g,z[4*e+2]=h[e].b,z[4*e+3]=h[e].a}const W=new sn.x,H=new Float32Array(c),X=new Float32Array(d),j=new Float32Array(p);return W.indices=u,W.positions=H,W.normals=X,W.uvs=j,z&&W.set(z,qe.o.ColorKind),n&&(W._idx=x),W}function fs(e,t,i=null){const n=t.pathArray,s=t.closeArray,r=t.closePath,a=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),l=t.instance,h=t.updatable;if(l){const e=o.jp.Vector3[0].setAll(Number.MAX_VALUE),i=o.jp.Vector3[1].setAll(-Number.MAX_VALUE),s=t=>{let s=n[0].length;const r=l;let o=0;const a=r._originalBuilderSideOrientation===Nt.Kj.DOUBLESIDE?2:1;for(let l=1;l<=a;++l)for(let a=0;a<n.length;++a){const l=n[a],h=l.length;s=s<h?s:h;for(let n=0;n<s;++n){const s=l[n];t[o]=s.x,t[o+1]=s.y,t[o+2]=s.z,e.minimizeInPlaceFromFloats(s.x,s.y,s.z),i.maximizeInPlaceFromFloats(s.x,s.y,s.z),o+=3}if(r._creationDataStorage&&r._creationDataStorage.closePath){const e=l[0];t[o]=e.x,t[o+1]=e.y,t[o+2]=e.z,o+=3}}},r=l.getVerticesData(qe.o.PositionKind);if(s(r),l.hasBoundingInfo?l.getBoundingInfo().reConstruct(e,i,l._worldMatrix):l.buildBoundingInfo(e,i,l._worldMatrix),l.updateVerticesData(qe.o.PositionKind,r,!1,!1),t.colors){const e=l.getVerticesData(qe.o.ColorKind);for(let i=0,n=0;i<t.colors.length;i++,n+=4){const s=t.colors[i];e[n]=s.r,e[n+1]=s.g,e[n+2]=s.b,e[n+3]=s.a}l.updateVerticesData(qe.o.ColorKind,e,!1,!1)}if(t.uvs){const e=l.getVerticesData(qe.o.UVKind);for(let i=0;i<t.uvs.length;i++)e[2*i]=t.uvs[i].x,e[2*i+1]=rn.e.UseOpenGLOrientationForUV?1-t.uvs[i].y:t.uvs[i].y;l.updateVerticesData(qe.o.UVKind,e,!1,!1)}if(!l.areNormalsFrozen||l.isFacetDataEnabled){const e=l.getIndices(),t=l.getVerticesData(qe.o.NormalKind),i=l.isFacetDataEnabled?l.getFacetDataParameters():null;if(sn.x.ComputeNormals(r,e,t,i),l._creationDataStorage&&l._creationDataStorage.closePath){let e=0,i=0;for(let s=0;s<n.length;s++)e=3*l._creationDataStorage.idx[s],i=s+1<n.length?3*(l._creationDataStorage.idx[s+1]-1):t.length-3,t[e]=.5*(t[e]+t[i]),t[e+1]=.5*(t[e+1]+t[i+1]),t[e+2]=.5*(t[e+2]+t[i+2]),t[i]=t[e],t[i+1]=t[e+1],t[i+2]=t[e+2]}l.areNormalsFrozen||l.updateVerticesData(qe.o.NormalKind,t,!1,!1)}return l}{const n=new Nt.Kj(e,i);n._originalBuilderSideOrientation=a,n._creationDataStorage=new Nt.gW;const o=ps(t);return r&&(n._creationDataStorage.idx=o._idx),n._creationDataStorage.closePath=r,n._creationDataStorage.closeArray=s,o.applyToMesh(n,h),n}}const _s={CreateRibbon:fs};function ms(e,t,i=null){const n=t.path,s=t.shape,r=t.scale||1,o=t.rotation||0,a=0===t.cap?0:t.cap||Nt.Kj.NO_CAP,l=t.updatable,h=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),c=t.instance||null,u=t.invertUV||!1,d=t.closeShape||!1;return vs(e,s,n,r,o,null,null,t.closePath||!1,d,a,!1,i,!!l,h,c,u,t.frontUVs||null,t.backUVs||null,t.firstNormal||null,!!t.adjustFrame)}function gs(e,t,i=null){const n=t.path,s=t.shape,r=t.scaleFunction||(()=>1),o=t.rotationFunction||(()=>0),a=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||Nt.Kj.NO_CAP,c=t.updatable,u=t.firstNormal||null,d=t.adjustFrame||!1;return vs(e,s,n,null,null,r,o,a,l,h,!0,i,!!c,Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,u,d)}function vs(e,t,i,n,s,r,a,l,h,c,u,d,p,f,_,m,g,v,y,x){const b=(e,t,i,n,s,r,a,l,h,c,u)=>{const d=i.getTangents(),p=i.getNormals(),f=i.getBinormals(),_=i.getDistances();if(u)for(let e=0;e<d.length;e++)if(0==d[e].x&&0==d[e].y&&0==d[e].z&&d[e].copyFrom(d[e-1]),0==p[e].x&&0==p[e].y&&0==p[e].z&&p[e].copyFrom(p[e-1]),0==f[e].x&&0==f[e].y&&0==f[e].z&&f[e].copyFrom(f[e-1]),e>0){let t=d[e-1];o.P.Dot(t,d[e])<0&&d[e].scaleInPlace(-1),t=p[e-1],o.P.Dot(t,p[e])<0&&p[e].scaleInPlace(-1),t=f[e-1],o.P.Dot(t,f[e])<0&&f[e].scaleInPlace(-1)}let m=0;const g=c&&l?l:()=>null!==r?r:0,v=c&&a?a:()=>null!==s?s:1;let y=h===Nt.Kj.NO_CAP||h===Nt.Kj.CAP_END?0:2;const x=o.jp.Matrix[0];for(let i=0;i<t.length;i++){const s=new Array,r=g(i,_[i]),a=v(i,_[i]);o.y3.RotationAxisToRef(d[i],m,x);for(let n=0;n<e.length;n++){const r=d[i].scale(e[n].z).add(p[i].scale(e[n].x)).add(f[i].scale(e[n].y)),l=o.P.Zero();o.P.TransformCoordinatesToRef(r,x,l),l.scaleInPlace(a).addInPlace(t[i]),s[n]=l}n[y]=s,m+=r,y++}const b=e=>{const t=Array(),i=o.P.Zero();let n;for(n=0;n<e.length;n++)i.addInPlace(e[n]);for(i.scaleInPlace(1/e.length),n=0;n<e.length;n++)t.push(i);return t};switch(h){case Nt.Kj.NO_CAP:break;case Nt.Kj.CAP_START:n[0]=b(n[2]),n[1]=n[2];break;case Nt.Kj.CAP_END:n[y]=n[y-1],n[y+1]=b(n[y-1]);break;case Nt.Kj.CAP_ALL:n[0]=b(n[2]),n[1]=n[2],n[y]=n[y-1],n[y+1]=b(n[y-1])}return n};let T,S;if(_){const e=_._creationDataStorage;return T=y?e.path3D.update(i,y):e.path3D.update(i),S=b(t,i,e.path3D,e.pathArray,n,s,r,a,e.cap,u,x),fs("",{pathArray:S,closeArray:!1,closePath:!1,offset:0,updatable:!1,sideOrientation:0,instance:_},d||void 0)}T=y?new X.$B(i,y):new X.$B(i),S=b(t,i,T,new Array,n,s,r,a,c=c<0||c>3?0:c,u,x);const E=fs(e,{pathArray:S,closeArray:l,closePath:h,updatable:p,sideOrientation:f,invertUV:m,frontUVs:g||void 0,backUVs:v||void 0},d);return E._creationDataStorage.pathArray=S,E._creationDataStorage.path3D=T,E._creationDataStorage.cap=c,E}sn.x.CreateRibbon=ps,Nt.Kj.CreateRibbon=(e,t,i=!1,n,s,r,o=!1,a,l)=>fs(e,{pathArray:t,closeArray:i,closePath:n,offset:s,updatable:o,sideOrientation:a,instance:l},r);const ys={ExtrudeShape:ms,ExtrudeShapeCustom:gs};Nt.Kj.ExtrudeShape=(e,t,i,n,s,r,o=null,a,l,h)=>ms(e,{shape:t,path:i,scale:n,rotation:s,cap:0===r?0:r||Nt.Kj.NO_CAP,sideOrientation:l,instance:h,updatable:a},o),Nt.Kj.ExtrudeShapeCustom=(e,t,i,n,s,r,o,a,l,h,c,u)=>gs(e,{shape:t,path:i,scaleFunction:n,rotationFunction:s,ribbonCloseArray:r,ribbonClosePath:o,cap:0===a?0:a||Nt.Kj.NO_CAP,sideOrientation:c,instance:u,updatable:h},l);class xs{static CreateBoneWeightShader(e,t){var i,n,s,r,o,l;const h=e.skeleton,c=null!==(i=e.colorBase)&&void 0!==i?i:a.Wo.Black(),u=null!==(n=e.colorZero)&&void 0!==n?n:a.Wo.Blue(),d=null!==(s=e.colorQuarter)&&void 0!==s?s:a.Wo.Green(),p=null!==(r=e.colorHalf)&&void 0!==r?r:a.Wo.Yellow(),f=null!==(o=e.colorFull)&&void 0!==o?o:a.Wo.Red(),_=null!==(l=e.targetBoneIndex)&&void 0!==l?l:0;ds.Q.ShadersStore["boneWeights:"+h.name+"VertexShader"]="precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n\n #include<bonesDeclaration>\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include<bakedVertexAnimationDeclaration>\n\n #include<instancesDeclaration>\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include<instancesVertex>\n #include<bonesVertex>\n #include<bakedVertexAnimation>\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",ds.Q.ShadersStore["boneWeights:"+h.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";const m=new us.j("boneWeight:"+h.name,t,{vertex:"boneWeights:"+h.name,fragment:"boneWeights:"+h.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return m.setColor3("colorBase",c),m.setColor3("colorZero",u),m.setColor3("colorQuarter",d),m.setColor3("colorHalf",p),m.setColor3("colorFull",f),m.setFloat("targetBoneIndex",_),m.getClassName=()=>"BoneWeightShader",m.transparencyMode=cs.F.MATERIAL_OPAQUE,m}static CreateSkeletonMapShader(e,t){var i;const n=e.skeleton,s=null!==(i=e.colorMap)&&void 0!==i?i:[{color:new a.Wo(1,.38,.18),location:0},{color:new a.Wo(.59,.18,1),location:.2},{color:new a.Wo(.59,1,.18),location:.4},{color:new a.Wo(1,.87,.17),location:.6},{color:new a.Wo(1,.17,.42),location:.8},{color:new a.Wo(.17,.68,1),location:1}],r=n.bones.length+1,o=xs._CreateBoneMapColorBuffer(r,s,t),l=new us.j("boneWeights:"+n.name,t,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*n.bones.length+"];\n\n #include<bonesDeclaration>\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include<bakedVertexAnimationDeclaration>\n #include<instancesDeclaration>\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include<instancesVertex>\n #include<bonesVertex>\n #include<bakedVertexAnimation>\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return l.setFloats("colorMap",o),l.getClassName=()=>"SkeletonMapShader",l.transparencyMode=cs.F.MATERIAL_OPAQUE,l}static _CreateBoneMapColorBuffer(e,t,i){const n=new zi.c("temp",{width:e,height:1},i,!1),s=n.getContext(),r=s.createLinearGradient(0,0,e,0);t.forEach((e=>{r.addColorStop(e.location,e.color.toHexString())})),s.fillStyle=r,s.fillRect(0,0,e,1),n.update();const o=[],a=s.getImageData(0,0,e,1).data;for(let e=0;e<a.length;e++)o.push(.00392156862745098*a[e]);return n.dispose(),o}get scene(){return this._scene}get utilityLayer(){return this._utilityLayer}get isReady(){return this._ready}set ready(e){this._ready=e}get debugMesh(){return this._debugMesh}set debugMesh(e){this._debugMesh=e}get displayMode(){return this.options.displayMode||xs.DISPLAY_LINES}set displayMode(e){e>xs.DISPLAY_SPHERE_AND_SPURS&&(e=xs.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,n=!0,s=3,r={}){var o,l,h,c,u,d,p,f,_,m,g,v,y,x;this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=n,this.renderingGroupId=s,this.options=r,this.color=a.Wo.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,r.pauseAnimations=null===(o=r.pauseAnimations)||void 0===o||o,r.returnToRest=null!==(l=r.returnToRest)&&void 0!==l&&l,r.displayMode=null!==(h=r.displayMode)&&void 0!==h?h:xs.DISPLAY_LINES,r.displayOptions=null!==(c=r.displayOptions)&&void 0!==c?c:{},r.displayOptions.midStep=null!==(u=r.displayOptions.midStep)&&void 0!==u?u:.235,r.displayOptions.midStepFactor=null!==(d=r.displayOptions.midStepFactor)&&void 0!==d?d:.155,r.displayOptions.sphereBaseSize=null!==(p=r.displayOptions.sphereBaseSize)&&void 0!==p?p:.15,r.displayOptions.sphereScaleUnit=null!==(f=r.displayOptions.sphereScaleUnit)&&void 0!==f?f:2,r.displayOptions.sphereFactor=null!==(_=r.displayOptions.sphereFactor)&&void 0!==_?_:.865,r.displayOptions.spurFollowsChild=null!==(m=r.displayOptions.spurFollowsChild)&&void 0!==m&&m,r.displayOptions.showLocalAxes=null!==(g=r.displayOptions.showLocalAxes)&&void 0!==g&&g,r.displayOptions.localAxesSize=null!==(v=r.displayOptions.localAxesSize)&&void 0!==v?v:.075,r.computeBonesUsingShaders=null===(y=r.computeBonesUsingShaders)||void 0===y||y,r.useAllBones=null===(x=r.useAllBones)||void 0===x||x;const b=t.getVerticesData(qe.o.MatricesIndicesKind),T=t.getVerticesData(qe.o.MatricesWeightsKind);if(this._boneIndices=new Set,!r.useAllBones&&b&&T)for(let e=0;e<b.length;++e){const t=b[e];0!==T[e]&&this._boneIndices.add(t)}this._utilityLayer=new zn.x(this._scene,!1),this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!0;let S=this.options.displayMode||0;S>xs.DISPLAY_SPHERE_AND_SPURS&&(S=xs.DISPLAY_LINES),this.displayMode=S,this.update(),this._bindObs()}_bindObs(){this.displayMode===xs.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add((()=>{this._displayLinesUpdate()})))}update(){switch(this.displayMode){case xs.DISPLAY_LINES:this._displayLinesUpdate();break;case xs.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case xs.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,n=0,s=0,r=0){const a=o.jp.Matrix[0],l=t.getParent();if(a.copyFrom(t.getLocalMatrix()),0!==n||0!==s||0!==r){const e=o.jp.Matrix[1];o.y3.IdentityToRef(e),e.setTranslationFromFloats(n,s,r),e.multiplyToRef(a,a)}l&&a.multiplyToRef(l.getAbsoluteTransform(),a),a.multiplyToRef(i,a),e.x=a.m[12],e.y=a.m[13],e.z=a.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length,n=this.mesh.position;let s=0;for(let r=0;r<i;r++){const i=e[r];let a=this._debugLines[s];-1!==i._index&&(this._boneIndices.has(i.getIndex())||this.options.useAllBones)&&(a||(a=[o.P.Zero(),o.P.Zero()],this._debugLines[s]=a),this._getBonePosition(a[0],i,t),this._getBonePosition(a[1],i,t,0,i.length,0),a[0].subtractInPlace(n),a[1].subtractInPlace(n),s++)}}_getLinesForBonesNoLength(e){const t=e.length;let i=0;const n=this.mesh,s=n.position;for(let r=t-1;r>=0;r--){const t=e[r],a=t.getParent();if(!a||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let l=this._debugLines[i];l||(l=[o.P.Zero(),o.P.Zero()],this._debugLines[i]=l),t.getAbsolutePositionToRef(n,l[0]),a.getAbsolutePositionToRef(n,l[1]),l[0].subtractInPlace(s),l[1].subtractInPlace(s),i++}}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBaseMatrix().multiplyToRef(t,t)):t.copyFrom(o.y3.Identity())}_buildSpheresAndSpurs(e=!0){var t,i;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const n=null===(t=this.utilityLayer)||void 0===t?void 0:t.utilityLayerScene,s=this.skeleton.bones,r=[],a=[],l=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,n.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteTransforms();let t=Number.NEGATIVE_INFINITY;const h=this.options.displayOptions||{};for(let i=0;i<s.length;i++){const l=s[i];if(-1===l._index||!this._boneIndices.has(l.getIndex())&&!this.options.useAllBones)continue;const c=new o.y3;this._getAbsoluteBindPoseToRef(l,c);const u=new o.P;c.decompose(void 0,void 0,u),l.children.forEach((i=>{const s=new o.y3;i.getBaseMatrix().multiplyToRef(c,s);const r=new o.P;s.decompose(void 0,void 0,r);const d=o.P.Distance(u,r);if(d>t&&(t=d),e)return;const p=r.clone().subtract(u.clone()),f=p.length(),_=p.normalize().scale(f),m=h.midStep||.165,g=h.midStepFactor||.215,v=_.scale(m),y=gs("skeletonViewer",{shape:[new o.P(1,-1,0),new o.P(1,1,0),new o.P(-1,1,0),new o.P(-1,-1,0),new o.P(1,-1,0)],path:[o.P.Zero(),v,_],scaleFunction:e=>{switch(e){case 0:case 2:return 0;case 1:return f*g}return 0},sideOrientation:Nt.Kj.DEFAULTSIDE,updatable:!1},n),x=y.getTotalVertices(),b=[],T=[];for(let e=0;e<x;e++)b.push(1,0,0,0),h.spurFollowsChild&&e>9?T.push(i.getIndex(),0,0,0):T.push(l.getIndex(),0,0,0);y.position=u.clone(),y.setVerticesData(qe.o.MatricesWeightsKind,b,!1),y.setVerticesData(qe.o.MatricesIndicesKind,T,!1),y.convertToFlatShadedMesh(),a.push(y)}));const d=Kn("skeletonViewer",{segments:6,diameter:h.sphereBaseSize||.2,updatable:!0},n),p=d.getTotalVertices(),f=[],_=[];for(let e=0;e<p;e++)f.push(1,0,0,0),_.push(l.getIndex(),0,0,0);d.setVerticesData(qe.o.MatricesWeightsKind,f,!1),d.setVerticesData(qe.o.MatricesIndicesKind,_,!1),d.position=u.clone(),r.push([d,l])}const c=h.sphereScaleUnit||2,u=h.sphereFactor||.85,d=[];for(let e=0;e<r.length;e++){const[i,n]=r[e],s=1/(c/t);let o=0,a=n;for(;a.getParent()&&-1!==a.getParent().getIndex();)o++,a=a.getParent();i.scaling.scaleInPlace(s*Math.pow(u,o)),d.push(i)}this.debugMesh=Nt.Kj.MergeMeshes(d.concat(a),!0,!0),this.debugMesh&&(this.debugMesh.renderingGroupId=this.renderingGroupId,this.debugMesh.skeleton=this.skeleton,this.debugMesh.parent=this.mesh,this.debugMesh.computeBonesUsingShaders=null===(i=this.options.computeBonesUsingShaders)||void 0===i||i,this.debugMesh.alwaysSelectAsActiveMesh=!0),this.utilityLayer._getSharedGizmoLight().intensity=.7,this._revert(l),this.ready=!0}catch(e){console.error(e),this._revert(l),this.dispose()}}_buildLocalAxes(){var e;this._localAxes&&this._localAxes.dispose(),this._localAxes=null;const t=this.options.displayOptions||{};if(!t.showLocalAxes)return;const i=this._utilityLayer.utilityLayerScene,n=t.localAxesSize||.075,s=[],r=[],l=new a.HE(1,0,0,1),h=new a.HE(0,1,0,1),c=new a.HE(0,0,1,1),u=[],d=[];for(const e in this.skeleton.bones){const t=this.skeleton.bones[e];if(-1===t._index||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;const i=new o.y3,a=new o.P;this._getAbsoluteBindPoseToRef(t,i),i.decompose(void 0,o.jp.Quaternion[0],a);const p=new o.y3;o.jp.Quaternion[0].toRotationMatrix(p);const f=o.P.TransformCoordinates(new o.P(0+n,0,0),p),_=o.P.TransformCoordinates(new o.P(0,0+n,0),p),m=o.P.TransformCoordinates(new o.P(0,0,0+n),p),g=[[a,a.add(f)],[a,a.add(_)],[a,a.add(m)]],v=[[l,l],[h,h],[c,c]];s.push(...g),r.push(...v);for(let e=0;e<6;e++)u.push(1,0,0,0),d.push(t.getIndex(),0,0,0)}this._localAxes=rs("localAxes",{lines:s,colors:r,updatable:!0},i),this._localAxes.setVerticesData(qe.o.MatricesWeightsKind,u,!1),this._localAxes.setVerticesData(qe.o.MatricesIndicesKind,d,!1),this._localAxes.skeleton=this.skeleton,this._localAxes.renderingGroupId=this.renderingGroupId+1,this._localAxes.parent=this.mesh,this._localAxes.computeBonesUsingShaders=null===(e=this.options.computeBonesUsingShaders)||void 0===e||e}_displayLinesUpdate(){if(!this._utilityLayer)return;this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteTransforms(),void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones):this._getLinesForBonesWithLength(this.skeleton.bones,this.mesh.getWorldMatrix());const e=this._utilityLayer.utilityLayerScene;e&&(this._debugMesh?rs("",{lines:this._debugLines,updatable:!0,instance:this._debugMesh},e):(this._debugMesh=rs("",{lines:this._debugLines,updatable:!0,instance:null},e),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.position.copyFrom(this.mesh.position),this._debugMesh.color=this.color)}changeDisplayMode(e){const t=!!this.isEnabled;this.displayMode!==e&&(this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this.displayMode=e,this.update(),this._bindObs(),this.isEnabled=t)}changeDisplayOptions(e,t){const i=!!this.isEnabled;this.options.displayOptions[e]=t,this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this.update(),this._bindObs(),this.isEnabled=i}dispose(){this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null),this.ready=!1}}xs.DISPLAY_LINES=0,xs.DISPLAY_SPHERES=1,xs.DISPLAY_SPHERE_AND_SPURS=2;class bs{get transparency(){return this._transparency}set transparency(e){this._transparency=e;for(let t=6;t<12;++t)this._lightHelperFrustumMeshes[t].material.alpha=e}get showLines(){return this._showLines}set showLines(e){if(this._showLines!==e){this._showLines=e;for(let t=0;t<6;++t)this._lightHelperFrustumMeshes[t].setEnabled(e)}}get showPlanes(){return this._showPlanes}set showPlanes(e){if(this._showPlanes!==e){this._showPlanes=e;for(let t=6;t<12;++t)this._lightHelperFrustumMeshes[t].setEnabled(e)}}constructor(e,t){this._oldPosition=new o.P(Number.NaN,Number.NaN,Number.NaN),this._oldDirection=new o.P(Number.NaN,Number.NaN,Number.NaN),this._transparency=.3,this._showLines=!0,this._showPlanes=!0,this._scene=e.getScene(),this._light=e,this._camera=t,this._inverseViewMatrix=o.y3.Identity(),this._lightHelperFrustumMeshes=[],this._createGeometry(),this.show(),this.update()}show(){this._lightHelperFrustumMeshes.forEach(((e,t)=>{e.setEnabled(t<6&&this._showLines||t>=6&&this._showPlanes)})),this._oldPosition.set(Number.NaN,Number.NaN,Number.NaN),this._visible=!0}hide(){this._lightHelperFrustumMeshes.forEach((e=>{e.setEnabled(!1)})),this._visible=!1}update(){var e,t,i,n,s,r;if(!this._visible)return;if(this._oldPosition.equals(this._light.position)&&this._oldDirection.equals(this._light.direction)&&this._oldAutoCalc===this._light.autoCalcShadowZBounds&&this._oldMinZ===this._light.shadowMinZ&&this._oldMaxZ===this._light.shadowMaxZ)return;this._oldPosition.copyFrom(this._light.position),this._oldDirection.copyFrom(this._light.direction),this._oldAutoCalc=this._light.autoCalcShadowZBounds,this._oldMinZ=this._light.shadowMinZ,this._oldMaxZ=this._light.shadowMaxZ,o.jp.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,void 0!==this._light.shadowMinZ?this._light.shadowMinZ:this._camera.minZ),o.jp.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,void 0!==this._light.shadowMaxZ?this._light.shadowMaxZ:this._camera.maxZ);const a=this._getInvertViewMatrix();o.jp.Vector3[2].copyFromFloats(o.jp.Vector3[1].x,o.jp.Vector3[1].y,o.jp.Vector3[0].z),o.jp.Vector3[3].copyFromFloats(o.jp.Vector3[1].x,o.jp.Vector3[0].y,o.jp.Vector3[0].z),o.jp.Vector3[4].copyFromFloats(o.jp.Vector3[0].x,o.jp.Vector3[0].y,o.jp.Vector3[0].z),o.jp.Vector3[5].copyFromFloats(o.jp.Vector3[0].x,o.jp.Vector3[1].y,o.jp.Vector3[0].z),o.P.TransformCoordinatesToRef(o.jp.Vector3[2],a,o.jp.Vector3[2]),o.P.TransformCoordinatesToRef(o.jp.Vector3[3],a,o.jp.Vector3[3]),o.P.TransformCoordinatesToRef(o.jp.Vector3[4],a,o.jp.Vector3[4]),o.P.TransformCoordinatesToRef(o.jp.Vector3[5],a,o.jp.Vector3[5]),o.jp.Vector3[6].copyFromFloats(o.jp.Vector3[1].x,o.jp.Vector3[1].y,o.jp.Vector3[1].z),o.jp.Vector3[7].copyFromFloats(o.jp.Vector3[1].x,o.jp.Vector3[0].y,o.jp.Vector3[1].z),o.jp.Vector3[8].copyFromFloats(o.jp.Vector3[0].x,o.jp.Vector3[0].y,o.jp.Vector3[1].z),o.jp.Vector3[9].copyFromFloats(o.jp.Vector3[0].x,o.jp.Vector3[1].y,o.jp.Vector3[1].z),o.P.TransformCoordinatesToRef(o.jp.Vector3[6],a,o.jp.Vector3[6]),o.P.TransformCoordinatesToRef(o.jp.Vector3[7],a,o.jp.Vector3[7]),o.P.TransformCoordinatesToRef(o.jp.Vector3[8],a,o.jp.Vector3[8]),o.P.TransformCoordinatesToRef(o.jp.Vector3[9],a,o.jp.Vector3[9]),os("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),os("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),os("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),os("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),os("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),os("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),o.jp.Vector3[2].toArray(this._nearPlaneVertices,0),o.jp.Vector3[3].toArray(this._nearPlaneVertices,3),o.jp.Vector3[4].toArray(this._nearPlaneVertices,6),o.jp.Vector3[5].toArray(this._nearPlaneVertices,9),null===(e=this._lightHelperFrustumMeshes[6].geometry)||void 0===e||e.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),o.jp.Vector3[6].toArray(this._farPlaneVertices,0),o.jp.Vector3[7].toArray(this._farPlaneVertices,3),o.jp.Vector3[8].toArray(this._farPlaneVertices,6),o.jp.Vector3[9].toArray(this._farPlaneVertices,9),null===(t=this._lightHelperFrustumMeshes[7].geometry)||void 0===t||t.updateVerticesDataDirectly("position",this._farPlaneVertices,0),o.jp.Vector3[2].toArray(this._rightPlaneVertices,0),o.jp.Vector3[6].toArray(this._rightPlaneVertices,3),o.jp.Vector3[7].toArray(this._rightPlaneVertices,6),o.jp.Vector3[3].toArray(this._rightPlaneVertices,9),null===(i=this._lightHelperFrustumMeshes[8].geometry)||void 0===i||i.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),o.jp.Vector3[5].toArray(this._leftPlaneVertices,0),o.jp.Vector3[9].toArray(this._leftPlaneVertices,3),o.jp.Vector3[8].toArray(this._leftPlaneVertices,6),o.jp.Vector3[4].toArray(this._leftPlaneVertices,9),null===(n=this._lightHelperFrustumMeshes[9].geometry)||void 0===n||n.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),o.jp.Vector3[2].toArray(this._topPlaneVertices,0),o.jp.Vector3[6].toArray(this._topPlaneVertices,3),o.jp.Vector3[9].toArray(this._topPlaneVertices,6),o.jp.Vector3[5].toArray(this._topPlaneVertices,9),null===(s=this._lightHelperFrustumMeshes[10].geometry)||void 0===s||s.updateVerticesDataDirectly("position",this._topPlaneVertices,0),o.jp.Vector3[3].toArray(this._bottomPlaneVertices,0),o.jp.Vector3[7].toArray(this._bottomPlaneVertices,3),o.jp.Vector3[8].toArray(this._bottomPlaneVertices,6),o.jp.Vector3[4].toArray(this._bottomPlaneVertices,9),null===(r=this._lightHelperFrustumMeshes[11].geometry)||void 0===r||r.updateVerticesDataDirectly("position",this._bottomPlaneVertices,0)}dispose(){this._lightHelperFrustumMeshes.forEach((e=>{var t;null===(t=e.material)||void 0===t||t.dispose(),e.dispose()})),this._rootNode.dispose()}_createGeometry(){this._rootNode=new yi.Y("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[o.P.ZeroReadOnly,o.P.ZeroReadOnly,o.P.ZeroReadOnly,o.P.ZeroReadOnly,o.P.ZeroReadOnly];const e=os("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);e.parent=this._rootNode,e.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[o.P.ZeroReadOnly,o.P.ZeroReadOnly,o.P.ZeroReadOnly,o.P.ZeroReadOnly,o.P.ZeroReadOnly];const t=os("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[o.P.ZeroReadOnly,o.P.ZeroReadOnly];const i=os("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[o.P.ZeroReadOnly,o.P.ZeroReadOnly];const n=os("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[o.P.ZeroReadOnly,o.P.ZeroReadOnly];const s=os("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[o.P.ZeroReadOnly,o.P.ZeroReadOnly];const r=os("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(e,t,i,n,s,r);const l=(e,t,i)=>{const n=new Nt.Kj(e+"plane",this._scene),s=new Gi.K(e+"PlaneMat",this._scene);n.material=s,n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,s.emissiveColor=t,s.alpha=this.transparency,s.backFaceCulling=!1,s.disableLighting=!0;const r=new sn.x;r.positions=i,r.indices=[0,1,2,0,2,3],r.applyToMesh(n,!0),this._lightHelperFrustumMeshes.push(n)};this._nearPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._farPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._rightPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._leftPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._topPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._bottomPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],l("near",new a.Wo(1,0,0),this._nearPlaneVertices),l("far",new a.Wo(.3,0,0),this._farPlaneVertices),l("right",new a.Wo(0,1,0),this._rightPlaneVertices),l("left",new a.Wo(0,.3,0),this._leftPlaneVertices),l("top",new a.Wo(0,0,1),this._topPlaneVertices),l("bottom",new a.Wo(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=o.jp.Vector3[2],this._nearLinesPoints[1]=o.jp.Vector3[3],this._nearLinesPoints[2]=o.jp.Vector3[4],this._nearLinesPoints[3]=o.jp.Vector3[5],this._nearLinesPoints[4]=o.jp.Vector3[2],this._farLinesPoints[0]=o.jp.Vector3[6],this._farLinesPoints[1]=o.jp.Vector3[7],this._farLinesPoints[2]=o.jp.Vector3[8],this._farLinesPoints[3]=o.jp.Vector3[9],this._farLinesPoints[4]=o.jp.Vector3[6],this._trLinesPoints[0]=o.jp.Vector3[2],this._trLinesPoints[1]=o.jp.Vector3[6],this._brLinesPoints[0]=o.jp.Vector3[3],this._brLinesPoints[1]=o.jp.Vector3[7],this._tlLinesPoints[0]=o.jp.Vector3[4],this._tlLinesPoints[1]=o.jp.Vector3[8],this._blLinesPoints[0]=o.jp.Vector3[5],this._blLinesPoints[1]=o.jp.Vector3[9]}_getInvertViewMatrix(){return o.y3.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),o.P.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix}}var Ts=i(3255),Ss=i(7967),Es=i(3739),Cs=i(7458),As=i(771),Ps=i(1345),Rs=i(7374);class Ms{constructor(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}class Is extends ue.D{isDeterministicLockStep(){return this._options.deterministicLockstep}getLockstepMaxSteps(){return this._options.lockstepMaxSteps}getHardwareScalingLevel(){return 1}constructor(e=new Ms){super(null),ue.D.Instances.push(this),void 0===e.deterministicLockstep&&(e.deterministicLockstep=!1),void 0===e.lockstepMaxSteps&&(e.lockstepMaxSteps=4),this._options=e,As.Z.SetMatrixPrecision(!!e.useHighPrecisionMatrix),this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1,canUseGLInstanceID:!1,canUseGLVertexID:!1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:128,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,_collectUbosUpdatedInFrame:!1},_.Y.Log(`Babylon.js v${ue.D.Version} - Null engine`);const t="undefined"!=typeof self?self:"undefined"!=typeof global?global:window;"undefined"==typeof URL&&(t.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(t.Blob=function(){})}createVertexBuffer(e){const t=new Ke.h;return t.references=1,t}createIndexBuffer(e){const t=new Ke.h;return t.references=1,t}clear(e,t,i,n=!1){}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight}setViewport(e,t,i){this._cachedViewport=e}createShaderProgram(e,t,i,n,s){return{__SPECTOR_rebuildProgram:null}}getUniforms(e,t){return[]}getAttributes(e,t){return[]}bindSamplers(e){this._currentEffect=null}enableEffect(e){e=null!==e&&Ps.q.IsWrapper(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setState(e,t=0,i,n=!1,s,r,o=0){}setIntArray(e,t){return!0}setIntArray2(e,t){return!0}setIntArray3(e,t){return!0}setIntArray4(e,t){return!0}setFloatArray(e,t){return!0}setFloatArray2(e,t){return!0}setFloatArray3(e,t){return!0}setFloatArray4(e,t){return!0}setArray(e,t){return!0}setArray2(e,t){return!0}setArray3(e,t){return!0}setArray4(e,t){return!0}setMatrices(e,t){return!0}setMatrix3x3(e,t){return!0}setMatrix2x2(e,t){return!0}setFloat(e,t){return!0}setFloat2(e,t,i){return!0}setFloat3(e,t,i,n){return!0}setBool(e,t){return!0}setFloat4(e,t,i,n,s){return!0}setAlphaMode(e,t=!1){this._alphaMode!==e&&(this.alphaState.alphaBlend=0!==e,t||this.setDepthWrite(0===e),this._alphaMode=e)}bindBuffers(e,t,i){}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)}draw(e,t,i,n){}drawElementsType(e,t,i,n){}drawArraysType(e,t,i,n){}_createTexture(){return{}}_releaseTexture(e){}createTexture(e,t,i,n,s=3,r=null,o=null,a=null,l=null,h=null,c=null,u){const d=new Ei.l(this,Ei.S.Url),p=String(e);return d.url=p,d.generateMipMaps=!t,d.samplingMode=s,d.invertY=i,d.baseWidth=this._options.textureSize,d.baseHeight=this._options.textureSize,d.width=this._options.textureSize,d.height=this._options.textureSize,h&&(d.format=h),d.isReady=!0,r&&setTimeout((()=>{r(d)})),this._internalTexturesCache.push(d),d}_createHardwareRenderTargetWrapper(e,t,i){const n=new Rs.r(e,t,i,this);return this._renderTargetWrapperCache.push(n),n}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),n={};void 0!==t&&"object"==typeof t?(n.generateMipMaps=t.generateMipMaps,n.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,n.generateStencilBuffer=n.generateDepthBuffer&&t.generateStencilBuffer,n.type=void 0===t.type?0:t.type,n.samplingMode=void 0===t.samplingMode?3:t.samplingMode):(n.generateMipMaps=t,n.generateDepthBuffer=!0,n.generateStencilBuffer=!1,n.type=0,n.samplingMode=3);const s=new Ei.l(this,Ei.S.RenderTarget),r=e.width||e,o=e.height||e;return i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=!!n.generateStencilBuffer,s.baseWidth=r,s.baseHeight=o,s.width=r,s.height=o,s.isReady=!0,s.samples=1,s.generateMipMaps=!!n.generateMipMaps,s.samplingMode=n.samplingMode,s.type=n.type,this._internalTexturesCache.push(s),i}createRenderTargetCubeTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),n={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,(1!==n.type||this._caps.textureFloatLinearFiltering)&&(2!==n.type||this._caps.textureHalfFloatLinearFiltering)||(n.samplingMode=1),i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=!!n.generateStencilBuffer;const s=new Ei.l(this,Ei.S.RenderTarget);return s.baseWidth=e,s.baseHeight=e,s.width=e,s.height=e,s.isReady=!0,s.isCube=!0,s.samples=1,s.generateMipMaps=!!n.generateMipMaps,s.samplingMode=n.samplingMode,s.type=n.type,this._internalTexturesCache.push(s),i}updateTextureSamplingMode(e,t){t.samplingMode=e}createRawTexture(e,t,i,n,s,r,o,a=null,l=0,h=0,c=!1){const u=new Ei.l(this,Ei.S.Raw);return u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=n,u.generateMipMaps=s,u.samplingMode=o,u.invertY=r,u._compression=a,u.type=l,u._useSRGBBuffer=c,this._doNotHandleContextLost||(u._bufferView=e),u}updateRawTexture(e,t,i,n,s=null,r=0,o=!1){e&&(e._bufferView=t,e.format=i,e.invertY=n,e._compression=s,e.type=r,e._useSRGBBuffer=o)}bindFramebuffer(e,t,i,n,s){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!s&&this.setViewport(this._cachedViewport,i,n)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null}createDynamicVertexBuffer(e){const t=new Ke.h;return t.references=1,t.capacity=1,t}updateDynamicTexture(e,t,i,n=!1,s){}areAllEffectsReady(){return!0}getError(){return 0}_getUnpackAlignement(){return 1}_unpackFlipY(e){}updateDynamicIndexBuffer(e,t,i=0){}updateDynamicVertexBuffer(e,t,i,n){}_bindTextureDirectly(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)}_bindTexture(e,t){e<0||this._bindTextureDirectly(0,t)}_deleteBuffer(e){}releaseEffects(){}displayLoadingUI(){}hideLoadingUI(){}set loadingUIText(e){}_uploadCompressedDataToTextureDirectly(e,t,i,n,s,r=0,o=0){}_uploadDataToTextureDirectly(e,t,i=0,n=0){}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){}_uploadImageToTexture(e,t,i=0,n=0){}}i(9347),Rn.B.prototype._debugPushGroup=function(e,t){},Rn.B.prototype._debugPopGroup=function(e){},Rn.B.prototype._debugInsertMarker=function(e,t){},Rn.B.prototype._debugFlushPendingCommands=function(){};class Ds{constructor(){this._timeElapsedQueryEnded=!1}}var Os=i(8215);class ws{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Un.x.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Un.x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}ue.D.prototype.createQuery=function(){const e=this._gl.createQuery();if(!e)throw new Error("Unable to create Occlusion Query");return e},ue.D.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},ue.D.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},ue.D.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},ue.D.prototype.beginOcclusionQuery=function(e,t){const i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},ue.D.prototype.endOcclusionQuery=function(e){const t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},ue.D.prototype._createTimeQuery=function(){const e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},ue.D.prototype._deleteTimeQuery=function(e){const t=this.getCaps().timerQuery;t.deleteQueryEXT?t.deleteQueryEXT(e):this.deleteQuery(e)},ue.D.prototype._getTimeQueryResult=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},ue.D.prototype._getTimeQueryAvailability=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},ue.D.prototype.startTimeQuery=function(){const e=this.getCaps(),t=e.timerQuery;if(!t)return null;const i=new Ds;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery),this._currentNonTimestampToken=i}return i},ue.D.prototype.endTimeQuery=function(e){const t=this.getCaps(),i=t.timerQuery;if(!i||!e)return-1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return-1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return-1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}const n=this._gl.getParameter(i.GPU_DISJOINT_EXT);let s=!1;if(e._endTimeQuery?s=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(s=this._getTimeQueryAvailability(e._timeElapsedQuery)),s&&!n){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return-1;const t=this._getTimeQueryResult(e._startTimeQuery);i=this._getTimeQueryResult(e._endTimeQuery)-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return-1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return-1},ue.D.prototype._captureGPUFrameTime=!1,ue.D.prototype._gpuFrameTime=new Os.z,ue.D.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},ue.D.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.onBeginFrameObservable.add((()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())})),this._onEndFrameObserver=this.onEndFrameObservable.add((()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))}))):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},ue.D.prototype._getGlAlgorithmType=function(e){return e===Un.x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(Un.x.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(Un.x.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new ws),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(Un.x.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(Un.x.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Un.x.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Un.x.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(Un.x.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),Un.x.prototype._checkOcclusionQuery=function(){const e=this._occlusionDataStorage;if(e.occlusionType===Un.x.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;const t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery)if(t.isQueryResultAvailable(this._occlusionQuery)){const i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==Un.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==Un.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}const i=this.getScene();if(i.getBoundingBoxRenderer){const n=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(n.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded};var Ns=!0;ue.D.prototype.createTransformFeedback=function(){const e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},ue.D.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},ue.D.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},ue.D.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},ue.D.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},ue.D.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},ue.D.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},i(6599),i(6914),Rn.B.prototype.createExternalTexture=function(e){return null},Rn.B.prototype.setExternalTexture=function(e,t){throw new Error("setExternalTexture: This engine does not support external textures!")},Rn.B.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const n=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),r=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,n,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,n,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,n,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},Rn.B.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},Rn.B.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},Rn.B.prototype.buildTextureLayout=function(e){const t=this._gl,i=[];for(let n=0;n<e.length;n++)e[n]?i.push(t["COLOR_ATTACHMENT"+n]):i.push(t.NONE);return i},Rn.B.prototype.bindAttachments=function(e){this._gl.drawBuffers(e)},Rn.B.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t=!1,i){this._currentRenderTarget=null;const n=this._gl,s=e._attachments,r=s.length;if(e._MSAAFramebuffer){n.bindFramebuffer(n.READ_FRAMEBUFFER,e._MSAAFramebuffer),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,e._framebuffer);for(let t=0;t<r;t++){const i=e.textures[t];for(let e=0;e<r;e++)s[e]=n.NONE;s[t]=n[this.webGLVersion>1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],n.readBuffer(s[t]),n.drawBuffers(s),n.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,n.COLOR_BUFFER_BIT,n.NEAREST)}for(let e=0;e<r;e++)s[e]=n[this.webGLVersion>1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];n.drawBuffers(s)}for(let i=0;i<r;i++){const s=e.textures[i];!(null==s?void 0:s.generateMipMaps)||t||s.isCube||(this._bindTextureDirectly(n.TEXTURE_2D,s,!0),n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null))}i&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),i()),this._bindUnboundFramebuffer(null)},Rn.B.prototype.createMultipleRenderTarget=function(e,t,i=!0){var n;let s=!1,r=!0,o=!1,a=!1,l=15,h=1,c=new Array,u=new Array,d=new Array,p=new Array,f=new Array,m=new Array,g=new Array,v=new Array;const y=this._createHardwareRenderTargetWrapper(!0,!1,e);void 0!==t&&(s=void 0!==t.generateMipMaps&&t.generateMipMaps,r=void 0===t.generateDepthBuffer||t.generateDepthBuffer,o=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,a=void 0!==t.generateDepthTexture&&t.generateDepthTexture,h=t.textureCount||1,t.types&&(c=t.types),t.samplingModes&&(u=t.samplingModes),t.useSRGBBuffers&&(d=t.useSRGBBuffers),t.formats&&(p=t.formats),t.targetTypes&&(f=t.targetTypes),t.faceIndex&&(m=t.faceIndex),t.layerIndex&&(g=t.layerIndex),t.layerCounts&&(v=t.layerCounts),this.webGLVersion>1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(l=t.depthTextureFormat));const x=this._gl,b=x.createFramebuffer();this._bindUnboundFramebuffer(b);const T=e.width||e,S=e.height||e,E=[],C=[],A=this.webGLVersion>1&&a&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),P=this._setupFramebufferDepthAttachments(!A&&o,!a&&r,T,S);y._framebuffer=b,y._depthStencilBuffer=P,y._generateDepthBuffer=!a&&r,y._generateStencilBuffer=!A&&o,y._attachments=C;for(let e=0;e<h;e++){let t=u[e]||3,i=c[e]||0,r=d[e]||!1;const o=p[e]||5,a=f[e]||3553,l=null!==(n=v[e])&&void 0!==n?n:1;(1!==i||this._caps.textureFloatLinearFiltering)&&(2!==i||this._caps.textureHalfFloatLinearFiltering)||(t=1);const h=this._getSamplingParameters(t,s);1!==i||this._caps.textureFloat||(i=0,_.Y.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),r=r&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU);const m=this.webGLVersion>1,g=x[m?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(C.push(g),-1===a)continue;const y=new Ei.l(this,Ei.S.MultiRenderTarget);E[e]=y,x.activeTexture(x["TEXTURE"+e]),x.bindTexture(a,y._hardwareTexture.underlyingResource),x.texParameteri(a,x.TEXTURE_MAG_FILTER,h.mag),x.texParameteri(a,x.TEXTURE_MIN_FILTER,h.min),x.texParameteri(a,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(a,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE);const b=this._getRGBABufferInternalSizedFormat(i,o,r),A=this._getInternalFormat(o),P=this._getWebGLTextureType(i);if(!m||35866!==a&&32879!==a)if(34067===a){for(let e=0;e<6;e++)x.texImage2D(x.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,b,T,S,0,A,P,null);y.isCube=!0}else x.texImage2D(x.TEXTURE_2D,0,b,T,S,0,A,P,null);else 35866===a?y.is2DArray=!0:y.is3D=!0,y.baseDepth=y.depth=l,x.texImage3D(a,0,b,T,S,l,0,A,P,null);s&&x.generateMipmap(a),this._bindTextureDirectly(a,null),y.baseWidth=T,y.baseHeight=S,y.width=T,y.height=S,y.isReady=!0,y.samples=1,y.generateMipMaps=s,y.samplingMode=t,y.type=i,y._useSRGBBuffer=r,y.format=o,this._internalTexturesCache.push(y)}if(a&&this._caps.depthTextureExtension){const e=new Ei.l(this,Ei.S.Depth);let t=5,i=x.DEPTH_COMPONENT16,n=x.DEPTH_COMPONENT,r=x.UNSIGNED_SHORT,o=x.DEPTH_ATTACHMENT;this.webGLVersion<2?i=x.DEPTH_COMPONENT:14===l?(t=1,r=x.FLOAT,i=x.DEPTH_COMPONENT32F):18===l?(t=0,r=x.FLOAT_32_UNSIGNED_INT_24_8_REV,i=x.DEPTH32F_STENCIL8,n=x.DEPTH_STENCIL,o=x.DEPTH_STENCIL_ATTACHMENT):16===l?(t=0,r=x.UNSIGNED_INT,i=x.DEPTH_COMPONENT24,o=x.DEPTH_ATTACHMENT):13!==l&&17!==l||(t=12,r=x.UNSIGNED_INT_24_8,i=x.DEPTH24_STENCIL8,n=x.DEPTH_STENCIL,o=x.DEPTH_STENCIL_ATTACHMENT),x.activeTexture(x.TEXTURE0),x.bindTexture(x.TEXTURE_2D,e._hardwareTexture.underlyingResource),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MAG_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MIN_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE),x.texImage2D(x.TEXTURE_2D,0,i,T,S,0,n,r,null),x.framebufferTexture2D(x.FRAMEBUFFER,o,x.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=T,e.baseHeight=S,e.width=T,e.height=S,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=l,e.type=t,E[h]=e,this._internalTexturesCache.push(e)}return y.setTextures(E),i&&x.drawBuffers(C),this._bindUnboundFramebuffer(null),y.setLayerAndFaceIndices(g,m),this.resetTextureCache(),y},Rn.B.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const n=e._attachments.length;if(0===n)return 1;const s=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);const r=!!e._depthStencilBuffer;if(r&&(s.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(s.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof s.renderbufferStorageMultisample){const r=s.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(r);const o=[];for(let t=0;t<n;t++)e.textures[t]._hardwareTexture.releaseMSAARenderBuffers();for(let i=0;i<n;i++){const n=e.textures[i],r=n._hardwareTexture,a=s[this.webGLVersion>1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(n.width,n.height,t,-1,this._getRGBAMultiSampleBufferFormat(n.type,n.format),a);if(!l)throw new Error("Unable to create multi sampled framebuffer");r.addMSAARenderBuffer(l),n.samples=t,o.push(a)}i&&s.drawBuffers(o)}else this._bindUnboundFramebuffer(e._framebuffer);return r&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},i(2477),i(7246),i(6697),Rn.B.prototype.setTextureSampler=function(e,t){throw new Error("setTextureSampler: This engine does not support separate texture sampler objects!")},i(4901),i(3742);class Fs{}const Ls=new r.y$,Bs=new r.y$;Object.defineProperty(ue.D.prototype,"onBeforeViewRenderObservable",{get:function(){return Ls}}),Object.defineProperty(ue.D.prototype,"onAfterViewRenderObservable",{get:function(){return Bs}}),Object.defineProperty(ue.D.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){var t;this._inputElement!==e&&(this._inputElement=e,null===(t=this._onEngineViewChanged)||void 0===t||t.call(this))}}),ue.D.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},ue.D.prototype.registerView=function(e,t,i){this.views||(this.views=[]);for(const t of this.views)if(t.target===e)return t;const n=this.getRenderingCanvas();n&&(e.width=n.width,e.height=n.height);const s={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(s),t&&t.onDisposeObservable.add((()=>{this.unRegisterView(e)})),s},ue.D.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(const t of this.views)if(t.target===e){const e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},ue.D.prototype._renderViewStep=function(e){const t=e.target,i=t.getContext("2d");if(!i)return!0;const n=this.getRenderingCanvas();Ls.notifyObservers(e);const s=e.camera;let r=null,o=null;if(s){if(o=s.getScene(),!o||o.activeCameras&&o.activeCameras.length)return!0;this.activeView=e,r=o.activeCamera,o.activeCamera=s}if(e.customResize)e.customResize(t);else{const e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||n.width!==t.width||i!==t.height||n.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!(!n.width||!n.height||(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,n.width,n.height),i.drawImage(n,0,0),r&&o&&(o.activeCamera=r),Bs.notifyObservers(e),0))},ue.D.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;if(!this.getRenderingCanvas())return!1;let e;for(const t of this.views)if(t.enabled)if(t.target!==this.inputElement){if(!this._renderViewStep(t))return!1}else e=t;return!(e&&!this._renderViewStep(e)||(this.activeView=null,0))};var Us=i(9075);function Vs(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some((t=>{const i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;const t=e.lastIndexOf("."),i=e.lastIndexOf("?"),n=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+n}Rn.B.prototype.createStorageBuffer=function(e,t){throw new Error("createStorageBuffer: Unsupported method in this engine!")},Rn.B.prototype.updateStorageBuffer=function(e,t,i,n){},Rn.B.prototype.readFromStorageBuffer=function(e,t,i,n){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")},Rn.B.prototype.setStorageBuffer=function(e,t){throw new Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(ue.D.prototype,"texturesSupported",{get:function(){const e=new Array;return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(ue.D.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),ue.D.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},ue.D.prototype.setTextureFormatToUse=function(e){const t=this.texturesSupported;for(let i=0,n=t.length;i<n;i++)for(let n=0,s=e.length;n<s;n++)if(t[i]===e[n].toLowerCase())return this._transformTextureUrl=Vs.bind(this),this._textureFormatInUse=t[i];return this._textureFormatInUse="",this._transformTextureUrl=null,null};class ks{constructor(){const e=new ArrayBuffer(ks.DEFAULT_BUFFER_SIZE);this._uint32s=new Uint32Array(e),this._int32s=new Int32Array(e),this._float32s=new Float32Array(e),this._length=ks.DEFAULT_BUFFER_SIZE/4,this._position=0,this._nativeDataStream=new _native.NativeDataStream((()=>{this._flush()}))}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}ks.DEFAULT_BUFFER_SIZE=65536;var Gs=i(4277),zs=i(6430),Ws=i(4001),Hs=i(1722);class Xs{get isAsync(){return this.isParallelCompiled}get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+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,n,s,r,o,a){const l=this._engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this._engine.getUniforms(this,i).forEach(((e,t)=>{n[i[t]]=e})),this._uniforms=n,h=0;h<s.length;h++)null==e.getUniform(s[h])&&(s.splice(h,1),h--);s.forEach(((e,t)=>{r[e]=t})),a.push(...l.getAttributes(this,o))}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],n=t.updateFlag;return(void 0===i||i!==n)&&(this._valueCache[e]=n,!0)}_cacheFloat2(e,t,i){let n=this._valueCache[e];if(!n)return n=[t,i],this._valueCache[e]=n,!0;let s=!1;return n[0]!==t&&(n[0]=t,s=!0),n[1]!==i&&(n[1]=i,s=!0),s}_cacheFloat3(e,t,i,n){let s=this._valueCache[e];if(!s)return s=[t,i,n],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),s[2]!==n&&(s[2]=n,r=!0),r}_cacheFloat4(e,t,i,n,s){let r=this._valueCache[e];if(!r)return r=[t,i,n,s],this._valueCache[e]=r,!0;let o=!1;return r[0]!==t&&(r[0]=t,o=!0),r[1]!==i&&(r[1]=i,o=!0),r[2]!==n&&(r[2]=n,o=!0),r[3]!==s&&(r[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&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,n){this._cacheFloat3(e,t,i,n)&&(this._engine.setInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setInt4(this._uniforms[e],t,i,n,s)||(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];void 0!==i&&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,n){this._cacheFloat3(e,t,i,n)&&(this._engine.setUInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setUInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setUInt4(this._uniforms[e],t,i,n,s)||(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];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];void 0!==i&&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,n){this._cacheFloat3(e,t,i,n)&&(this._engine.setFloat3(this._uniforms[e],t,i,n)||(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,n,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setFloat4(this._uniforms[e],t,i,n,s)||(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 js extends Rs.r{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,n){super(e,t,i,n),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=n}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class Ys{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()}}const qs=new r.y$;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{e=t,e&&qs.notifyObservers(e)}})}function Ks(){return new Promise((e=>{"undefined"==typeof _native?qs.addOnce((t=>e(t))):e(_native)}))}async function $s(e,t){(await Ks())[e]=t}class Qs extends Ke.h{}class Zs{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=Js._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 Js extends ue.D{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 Zs(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!==Js.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${Js.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,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:1,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:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,_collectUbosUpdatedInFrame:!1},de.w1.Log("Babylon Native (v"+ue.D.Version+") launched"),de.w1.LoadScript=function(e,t,i,n){de.w1.LoadFile(e,(e=>{Function(e).apply(null),t&&t()}),void 0,void 0,!1,((e,t)=>{i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){const t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,n){return Array.isArray(n)?i.push.apply(i,e.call(n,t-1)):i.push(n),i}),[]):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 Ws.C,this.onNewSceneAddedObservable.add((e=>{const t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}}))}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new ks}_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,n=!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(n?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t){const i=this._normalizeIndexData(e),n=new Qs;return n.references=1,n.is32Bits=4===i.BYTES_PER_ELEMENT,i.byteLength&&(n.nativeIndexBuffer=this._engine.createIndexBuffer(i.buffer,i.byteOffset,i.byteLength,n.is32Bits,null!=t&&t)),n}createVertexBuffer(e,t){const i=ArrayBuffer.isView(e)?e:new Float32Array(e),n=new Qs;return n.references=1,i.byteLength&&(n.nativeVertexBuffer=this._engine.createVertexBuffer(i.buffer,i.byteOffset,i.byteLength,null!=t&&t)),n}_recordVertexArrayObject(e,t,i,n,s){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const r=n.getAttributesNames();for(let i=0;i<r.length;i++){const o=n.getAttributeLocation(i);if(o>=0){const n=r[i];let a=null;if(s&&(a=s[n]),a||(a=t[n]),a){const t=a.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,o,a.byteOffset,a.byteStride,a.getSize(),this._getNativeAttribType(a.type),a.normalized,a.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,n){const s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,n),s}_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,n){this._drawCalls.addCount(1,!1),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,n){this._drawCalls.addCount(1,!1),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 Xs(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,n,s,r,o,a){e.nativeProgram=n?this.createRawShaderProgram():this.createShaderProgram(e,t,i,a)}isAsync(e){return!(!e.isAsync||!this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!this.isAsync(e))return void t();const n=i.onCompiled;i.onCompiled=n?()=>{n(),t()}:t}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,n){const s=e;if(s.nativeProgram)throw new Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=new zs.Z(t);r.processCode(),t=r.code;const o=new zs.Z(i);o.processCode(),i=o.code,t=Rn.B._ConcatenateShader(t,n),i=Rn.B._ConcatenateShader(i,n);const a=()=>{var e;s.isCompiled=!0,null===(e=s.onCompiled)||void 0===e||e.call(s),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,a,(e=>{s.compilationError=e}));try{const e=s.nativeProgram=this._engine.createProgram(t,i);return a(),e}catch(e){const t=null==e?void 0:e.message;throw new Error("SHADER ERROR"+("string"==typeof t?"\n"+t:""))}}inlineShaderCode(e){const t=new zs.Z(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 t=0;t<i.length;t++){const n=e.getUniform(i[t]);n&&(this._boundUniforms[t]=n)}this._currentEffect=null}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._engine.getRenderWidth()}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._engine.getRenderHeight()}setViewport(e,t,i){this._cachedViewport=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.x),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.y),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.width),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.height),this._commandBufferEncoder.finishEncodingCommand()}setState(e,t=0,i,n=!1,s,r,o=0){var a,l;this._zOffset=t,this._zOffsetUnits=o,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(o),this._commandBufferEncoder.encodeCommandArgAsUInt32(null===(l=null!==(a=this.cullBackFaces)&&void 0!==a?a:s)||void 0===l||l?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(n?1:0),this._commandBufferEncoder.finishEncodingCommand()}getInputElementClientRect(){return{bottom:this.getRenderHeight(),height:this.getRenderHeight(),left:0,right:this.getRenderWidth(),top:0,width:this.getRenderWidth(),x:0,y:0,toJSON:()=>{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}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,this._getStencilOpFail(this._stencilOpStencilFail),this._getStencilDepthFail(this._stencilOpDepthFail),this._getStencilDepthPass(this._stencilOpStencilDepthPass),this._getStencilFunc(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,n,s,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),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,n){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=this._getNativeAlphaMode(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),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)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}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)}setFloat3(e,t,i,n){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(n),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,n,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(n),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}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,n=!1,s){if(void 0===n&&(n=!1),e&&e._hardwareTexture){const i=t.getCanvasTexture(),n=e._hardwareTexture.underlyingResource;this._engine.copyTexture(n,i),e.isReady=!0}}createDynamicTexture(e,t,i,n){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,n)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const n=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(n,t,i)}}createRawTexture(e,t,i,n,s,r,o,a=null,l=0,h=0,c=!1){const u=new Ei.l(this,Ei.S.Raw);if(u.format=n,u.generateMipMaps=s,u.samplingMode=o,u.invertY=r,u.baseWidth=t,u.baseHeight=i,u.width=u.baseWidth,u.height=u.baseHeight,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this.updateRawTexture(u,e,n,r,a,l,u._useSRGBBuffer),u._hardwareTexture){const e=u._hardwareTexture.underlyingResource,t=this._getNativeSamplingMode(o);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(u),u}createRawTexture2DArray(e,t,i,n,s,r,o,a,l=null,h=0){const c=new Ei.l(this,Ei.S.Raw2DArray);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=n,c.width=t,c.height=i,c.depth=n,c.format=s,c.type=h,c.generateMipMaps=r,c.samplingMode=a,c.is2DArray=!0,c._hardwareTexture){const l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,n,this._getNativeTextureFormat(s,h),r,o);const u=this._getNativeSamplingMode(a);this._setTextureSampling(l,u)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,n,s=null,r=0,o=!1){if(e){if(t&&e._hardwareTexture){const n=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(n,t,e.width,e.height,this._getNativeTextureFormat(i,r),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,n,s=3,r=null,o=null,a=null,l=null,h=null,c=null,u,d,p,f=!1){const m="data:"===(e=e||"").substr(0,5),g=m&&-1!==e.indexOf(";base64,"),v=l||new Ei.l(this,Ei.S.Url),y=e;!this._transformTextureUrl||g||l||a||(e=this._transformTextureUrl(e));const x=e.lastIndexOf("."),b=c||(x>-1?e.substring(x).toLowerCase():"");let T=null;for(const e of ue.D._TextureLoaders)if(e.canLoad(b)){T=e;break}n&&n.addPendingData(v),v.url=e,v.generateMipMaps=!t,v.samplingMode=s,v.invertY=i,v._useSRGBBuffer=this._getUseSRGBBuffer(f,t),this.doNotHandleContextLost||(v._buffer=a);let S=null;r&&!l&&(S=v.onLoadedObservable.add(r)),l||this._internalTexturesCache.push(v);const E=(i,l)=>{n&&n.removePendingData(v),e===y?(S&&v.onLoadedObservable.remove(S),A.l.UseFallbackTexture&&this.createTexture(A.l.FallbackTexture,t,v.invertY,n,s,null,o,a,v),o&&o((i||"Unknown error")+(A.l.UseFallbackTexture?" - Fallback texture was used":""),l)):(_.Y.Warn(`Failed to load ${e}, falling back to ${y}`),this.createTexture(y,t,v.invertY,n,s,r,o,a,v,h,c,u,d))};if(T)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const r=e=>{if(!v._hardwareTexture)return void(n&&n.removePendingData(v));const r=v._hardwareTexture.underlyingResource;this._engine.loadTexture(r,e,!t,i,f,(()=>{v.baseWidth=this._engine.getTextureWidth(r),v.baseHeight=this._engine.getTextureHeight(r),v.width=v.baseWidth,v.height=v.baseHeight,v.isReady=!0;const e=this._getNativeSamplingMode(s);this._setTextureSampling(r,e),n&&n.removePendingData(v),v.onLoadedObservable.notifyObservers(v),v.onLoadedObservable.clear()}),(()=>{throw new Error("Could not load a native texture.")}))};if(m&&a)if(a instanceof ArrayBuffer)r(new Uint8Array(a));else if(ArrayBuffer.isView(a))r(a);else{if("string"!=typeof a)throw new Error("Unsupported buffer type");r(new Uint8Array(de.w1.DecodeBase64(a)))}else g?r(new Uint8Array(de.w1.DecodeBase64(e))):this._loadFile(e,(e=>r(new Uint8Array(e))),void 0,void 0,!0,((e,t)=>{E("Unable to load "+(e&&e.responseURL,t))}))}return v}wrapNativeTexture(e,t=!1,i=3){const n=new Ys(e,this._engine),s=new Ei.l(this,Ei.S.Unknown,!0);return s._hardwareTexture=n,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const n=i,s=new Ei.l(this,Ei.S.DepthStencil),r=e.width||e,o=e.height||e,a=this._engine.createFrameBuffer(s._hardwareTexture.underlyingResource,r,o,!0,!0);return n._framebufferDepthStencil=a,s}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){const i=new Promise(((t,i)=>{const n=this.createCanvasImage();n.onload=()=>{try{const e=this._engine.createImageBitmap(n);t(e)}catch(e){i(`Error loading image ${n.src} with exception: ${e}`)}},n.onerror=e=>{i(`Error loading image ${n.src} with exception: ${e}`)},n.src=e}));return i}createImageBitmap(e,t){return new Promise(((t,i)=>{if(Array.isArray(e)){const i=e;if(i.length){const e=this._engine.createImageBitmap(i[0]);if(e)return void t(e)}}i("Unsupported data for createImageBitmap.")}))}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,n,s=null,r=null,o,a=null,l=!1,h=0,c=0,u=null,d,p=!1){const f=u||new Ei.l(this,Ei.S.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!n,f._lodGenerationScale=h,f._lodGenerationOffset=c,this._doNotHandleContextLost||(f._extension=a,f._files=i);const _=e.lastIndexOf(".");if(".env"===(a||(_>-1?e.substring(_).toLowerCase():""))){const t=e=>{const t=(0,Gs.qJ)(e);f.width=t.width,f.height=t.width,(0,Gs.qC)(f,t);const i=t.specular;if(!i)throw new Error("Nothing else parsed so far");f._lodGenerationScale=i.lodGenerationScale;const n=(0,Gs.Do)(e,t);f.format=5,f.type=0,f.generateMipMaps=!0,f.getEngine().updateTextureSamplingMode(Ce.x.TRILINEAR_SAMPLINGMODE,f),f._isRGBD=!0,f.invertY=!0,this._engine.loadCubeTextureWithMips(f._hardwareTexture.underlyingResource,n,!1,p,(()=>{f.isReady=!0,s&&s()}),(()=>{throw new Error("Could not load a native cube texture.")}))};if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");{const i=(e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)};this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,void 0,!0,i)}}else{if(!i||6!==i.length)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((e=>de.w1.LoadFileAsync(e).then((e=>new Uint8Array(e)))))).then((e=>new Promise(((t,i)=>{this._engine.loadCubeTexture(f._hardwareTexture.underlyingResource,e,!n,!0,p,t,i)})))).then((()=>{f.isReady=!0,s&&s()}),(e=>{r&&r(`Failed to load cubemap: ${e.message}`,e)}))}return this._internalTexturesCache.push(f),f}_createHardwareTexture(){return new Ys(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const n=new js(e,t,i,this);return this._renderTargetWrapperCache.push(n),n}_createInternalTexture(e,t,i=!0,n=Ei.S.Unknown){var s;let r,o=!1,a=0,l=3,h=5,c=!1,u=1;void 0!==t&&"object"==typeof t?(o=!!t.generateMipMaps,a=void 0===t.type?0:t.type,l=void 0===t.samplingMode?3:t.samplingMode,h=void 0===t.format?5:t.format,c=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,u=null!==(s=t.samples)&&void 0!==s?s:1,r=t.label):o=!!t,c&&(c=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(1!==a||this._caps.textureFloatLinearFiltering)&&(2!==a||this._caps.textureHalfFloatLinearFiltering)||(l=1),1!==a||this._caps.textureFloat||(a=0,_.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=new Ei.l(this,n),p=e.width||e,f=e.height||e,m=e.layers||0;if(0!==m)throw new Error("Texture layers are not supported in Babylon Native");const g=d._hardwareTexture.underlyingResource,v=this._getNativeTextureFormat(h,a);return this._engine.initializeTexture(g,p,f,o,v,!0,c),this._setTextureSampling(g,this._getNativeSamplingMode(l)),d._useSRGBBuffer=c,d.baseWidth=p,d.baseHeight=f,d.width=p,d.height=f,d.depth=m,d.isReady=!0,d.samples=u,d.generateMipMaps=o,d.samplingMode=l,d.type=a,d.format=h,d.label=r,this._internalTexturesCache.push(d),d}createRenderTargetTexture(e,t){var i,n;const s=this._createHardwareRenderTargetWrapper(!1,!1,e);let r,o=!0,a=!1,l=!1,h=1;void 0!==t&&"object"==typeof t&&(o=null===(i=t.generateDepthBuffer)||void 0===i||i,a=!!t.generateStencilBuffer,l=!!t.noColorAttachment,r=t.colorAttachment,h=null!==(n=t.samples)&&void 0!==n?n:1);const c=r||(l?null:this._createInternalTexture(e,t,!0,Ei.S.RenderTarget)),u=e.width||e,d=e.height||e,p=this._engine.createFrameBuffer(c?c._hardwareTexture.underlyingResource:null,u,d,a,o);return s._framebuffer=p,s._generateDepthBuffer=o,s._generateStencilBuffer=a,s.setTextures(c),this.updateRenderTargetTextureSampleCount(s,h),s}updateRenderTargetTextureSampleCount(e,t){return 1}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=this._getNativeSamplingMode(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,n,s){const r=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||n)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");r._framebufferDepthStencil?this._bindUnboundFramebuffer(r._framebufferDepthStencil):this._bindUnboundFramebuffer(r._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 n=e,s=this._normalizeIndexData(t);n.is32Bits=4===s.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(n.nativeIndexBuffer,s.buffer,s.byteOffset,s.byteLength,i)}updateDynamicVertexBuffer(e,t,i,n){const s=e,r=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(s.nativeVertexBuffer,r.buffer,r.byteOffset+(null!=i?i:0),null!=n?n:r.byteLength)}_setTexture(e,t,i=!1,n=!1){const s=this._boundUniforms[e];if(!s)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let r;return r=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!r||!r._hardwareTexture||(this._setTextureWrapMode(r._hardwareTexture.underlyingResource,this._getAddressMode(t.wrapU),this._getAddressMode(t.wrapV),this._getAddressMode(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(s,r._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,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),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)}_getAddressMode(e){switch(e){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: "+e+".")}}_bindTexture(e,t){const i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){const e=t._hardwareTexture.underlyingResource;this._setTextureCore(i,e)}}_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,n,s,r,o=0,a=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,n,s,r=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,n=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,n=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_getNativeSamplingMode(e){switch(e){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: ${e}.`)}}_getStencilFunc(e){switch(e){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: ${e}.`)}}_getStencilOpFail(e){switch(e){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: ${e}.`)}}_getStencilDepthFail(e){switch(e){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: ${e}.`)}}_getStencilDepthPass(e){switch(e){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: ${e}.`)}}_getNativeTextureFormat(e,t){if(4==e&&0==t)return _native.Engine.TEXTURE_FORMAT_RGB8;if(5==e&&0==t)return _native.Engine.TEXTURE_FORMAT_RGBA8;if(5==e&&2==t)return _native.Engine.TEXTURE_FORMAT_RGBA16F;if(5==e&&1==t)return _native.Engine.TEXTURE_FORMAT_RGBA32F;throw new Hs.LH(`Unsupported texture format or type: format ${e}, type ${t}.`,Hs.SM.UnsupportedTextureError)}_getNativeAlphaMode(e){switch(e){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: ${e}.`)}}_getNativeAttribType(e){switch(e){case qe.o.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case qe.o.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case qe.o.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case qe.o.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case qe.o.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${e}.`)}}getFontOffset(e){return{ascent:0,height:0,descent:0}}_readTexturePixels(e,t,i,n,s,r,o,a,l,h){var c,u,d,p;if(void 0!==n&&-1!==n)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${n}.`);return this._engine.readTexture(null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,null!=s?s:0,null!=l?l:0,null!=h?h:0,t,i,null!==(u=null==r?void 0:r.buffer)&&void 0!==u?u:null,null!==(d=null==r?void 0:r.byteOffset)&&void 0!==d?d:0,null!==(p=null==r?void 0:r.byteLength)&&void 0!==p?p:0).then((e=>(r||(r=new Uint8Array(e)),r)))}}Js.PROTOCOL_VERSION=8,Js._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new er:new ks};class er extends ks{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 tr,ir,nr,sr,rr,or,ar,lr,hr,cr,ur,dr,pr,fr,_r,mr,gr,vr,yr,xr,br,Tr,Sr,Er,Cr,Ar,Pr,Rr,Mr,Ir,Dr,Or,wr,Nr,Fr,Lr,Br,Ur,Vr,kr,Gr=i(6913);!function(e){e.LowPower="low-power",e.HighPerformance="high-performance"}(tr||(tr={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(ir||(ir={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(nr||(nr={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(sr||(sr={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(rr||(rr={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(or||(or={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(ar||(ar={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(lr||(lr={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(hr||(hr={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth24UnormStencil8="depth24unorm-stencil8",e.Depth32FloatStencil8="depth32float-stencil8"}(cr||(cr={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(ur||(ur={})),function(e){e.Nearest="nearest",e.Linear="linear"}(dr||(dr={})),function(e){e.Nearest="nearest",e.Linear="linear"}(pr||(pr={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(fr||(fr={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(_r||(_r={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(mr||(mr={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(gr||(gr={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(vr||(vr={})),function(e){e.WriteOnly="write-only"}(yr||(yr={})),function(e){e.Error="error",e.Warning="warning",e.Info="info"}(xr||(xr={})),function(e){e.Validation="validation",e.Internal="internal"}(br||(br={})),function(e){e.Auto="auto"}(Tr||(Tr={})),function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(Sr||(Sr={})),function(e){e.CCW="ccw",e.CW="cw"}(Er||(Er={})),function(e){e.None="none",e.Front="front",e.Back="back"}(Cr||(Cr={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(Ar||(Ar={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(Pr||(Pr={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(Rr||(Rr={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(Mr||(Mr={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(Ir||(Ir={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4"}(Dr||(Dr={})),function(e){e.Vertex="vertex",e.Instance="instance"}(Or||(Or={})),function(e){e.Beginning="beginning",e.End="end"}(wr||(wr={})),function(e){e.Beginning="beginning",e.End="end"}(Nr||(Nr={})),function(e){e.Load="load",e.Clear="clear"}(Fr||(Fr={})),function(e){e.Store="store",e.Discard="discard"}(Lr||(Lr={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(Br||(Br={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(Ur||(Ur={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(Vr||(Vr={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(kr||(kr={}));class zr{constructor(){this.shaderLanguage=Cn.x.GLSL}_addUniformToLeftOverUBO(e,t,i){let n=0;[e,t,n]=this._getArraySize(e,t,i);for(let t=0;t<this._webgpuProcessingContext.leftOverUniforms.length;t++)if(this._webgpuProcessingContext.leftOverUniforms[t].name===e)return;this._webgpuProcessingContext.leftOverUniforms.push({name:e,type:t,length:n})}_buildLeftOverUBO(){if(!this._webgpuProcessingContext.leftOverUniforms.length)return"";const e=zr.LeftOvertUBOName;let t=this._webgpuProcessingContext.availableBuffers[e];return t||(t={binding:this._webgpuProcessingContext.getNextFreeUBOBinding()},this._webgpuProcessingContext.availableBuffers[e]=t,this._addBufferBindingDescription(e,t,mr.Uniform,!0),this._addBufferBindingDescription(e,t,mr.Uniform,!1)),this._generateLeftOverUBOCode(e,t)}_collectBindingNames(){for(let e=0;e<this._webgpuProcessingContext.bindGroupLayoutEntries.length;e++){const t=this._webgpuProcessingContext.bindGroupLayoutEntries[e];if(void 0!==t)for(let i=0;i<t.length;i++){const t=this._webgpuProcessingContext.bindGroupLayoutEntries[e][i],n=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][t.binding].name,s=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][t.binding].nameInArrayOfTexture;t&&(t.texture||t.externalTexture||t.storageTexture?this._webgpuProcessingContext.textureNames.push(s):t.sampler?this._webgpuProcessingContext.samplerNames.push(n):t.buffer&&this._webgpuProcessingContext.bufferNames.push(n))}else this._webgpuProcessingContext.bindGroupLayoutEntries[e]=[]}}_preCreateBindGroupEntries(){const e=this._webgpuProcessingContext.bindGroupEntries;for(let t=0;t<this._webgpuProcessingContext.bindGroupLayoutEntries.length;t++){const i=this._webgpuProcessingContext.bindGroupLayoutEntries[t],n=[];for(let e=0;e<i.length;e++){const i=this._webgpuProcessingContext.bindGroupLayoutEntries[t][e];i.sampler||i.texture||i.storageTexture||i.externalTexture?n.push({binding:i.binding,resource:void 0}):i.buffer&&n.push({binding:i.binding,resource:{buffer:void 0,offset:0,size:0}})}e[t]=n}}_addTextureBindingDescription(e,t,i,n,s,r){let{groupIndex:o,bindingIndex:a}=t.textures[i];if(this._webgpuProcessingContext.bindGroupLayoutEntries[o]||(this._webgpuProcessingContext.bindGroupLayoutEntries[o]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][a]){let r;r=null===n?this._webgpuProcessingContext.bindGroupLayoutEntries[o].push({binding:a,visibility:0,externalTexture:{}}):s?this._webgpuProcessingContext.bindGroupLayoutEntries[o].push({binding:a,visibility:0,storageTexture:{access:yr.WriteOnly,format:s,viewDimension:n}}):this._webgpuProcessingContext.bindGroupLayoutEntries[o].push({binding:a,visibility:0,texture:{sampleType:t.sampleType,viewDimension:n,multisampled:!1}});const l=t.isTextureArray?e+i:e;this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][a]={name:e,index:r-1,nameInArrayOfTexture:l}}a=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][a].index,this._webgpuProcessingContext.bindGroupLayoutEntries[o][a].visibility|=r?_r.Vertex:_r.Fragment}_addSamplerBindingDescription(e,t,i){let{groupIndex:n,bindingIndex:s}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[n]||(this._webgpuProcessingContext.bindGroupLayoutEntries[n]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][s]){const i=this._webgpuProcessingContext.bindGroupLayoutEntries[n].push({binding:s,visibility:0,sampler:{type:t.type}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][s]={name:e,index:i-1}}s=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][s].index,this._webgpuProcessingContext.bindGroupLayoutEntries[n][s].visibility|=i?_r.Vertex:_r.Fragment}_addBufferBindingDescription(e,t,i,n){let{groupIndex:s,bindingIndex:r}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[s]||(this._webgpuProcessingContext.bindGroupLayoutEntries[s]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][r]){const t=this._webgpuProcessingContext.bindGroupLayoutEntries[s].push({binding:r,visibility:0,buffer:{type:i}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][r]={name:e,index:t-1}}r=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][r].index,this._webgpuProcessingContext.bindGroupLayoutEntries[s][r].visibility|=n?_r.Vertex:_r.Fragment}_injectStartingAndEndingCode(e,t,i,n){let s=e.indexOf(t);if(s<0)return console.error('No "main" function found in shader code! Processing aborted.'),e;if(i){for(;s++<e.length&&"{"!=e.charAt(s););if(s<e.length){const t=e.substring(0,s+1),n=e.substring(s+1);e=t+i+n}}if(n){const t=e.lastIndexOf("}");e=e.substring(0,t),e+=n+"\n}"}return e}}zr.AutoSamplerSuffix="Sampler",zr.LeftOvertUBOName="LeftOver",zr.InternalsUBOName="Internals",zr.UniformSizes={bool:1,int:1,float:1,vec2:2,ivec2:2,vec3:3,ivec3:3,vec4:4,ivec4:4,mat2:4,mat3:12,mat4:16,i32:1,u32:1,f32:1,mat2x2:4,mat3x3:12,mat4x4:16},zr._SamplerFunctionByWebGLSamplerType={sampler2D:"sampler2D",sampler2DArray:"sampler2DArray",sampler2DShadow:"sampler2DShadow",sampler2DArrayShadow:"sampler2DArrayShadow",samplerCube:"samplerCube",sampler3D:"sampler3D"},zr._TextureTypeByWebGLSamplerType={sampler2D:"texture2D",sampler2DArray:"texture2DArray",sampler2DShadow:"texture2D",sampler2DArrayShadow:"texture2DArray",samplerCube:"textureCube",samplerCubeArray:"textureCubeArray",sampler3D:"texture3D"},zr._GpuTextureViewDimensionByWebGPUTextureType={textureCube:lr.Cube,textureCubeArray:lr.CubeArray,texture2D:lr.E2d,texture2DArray:lr.E2dArray,texture3D:lr.E3d},zr._SamplerTypeByWebGLSamplerType={sampler2DShadow:"samplerShadow",sampler2DArrayShadow:"samplerShadow"},zr._IsComparisonSamplerByWebGPUSamplerType={samplerShadow:!0,samplerArrayShadow:!0,sampler:!1};class Wr{get isAsync(){return!1}get isReady(){return!!this.stages}constructor(e,t){this._name="unnamed",this.shaderProcessingContext=e,this._leftOverUniformsByName={},this.engine=t}_handlesSpectorRebuildCallback(){}_fillEffectInformation(e,t,i,n,s,r,o,a){const l=this.engine;e._fragmentSourceCode="",e._vertexSourceCode="";const h=this.shaderProcessingContext.availableTextures;let c;for(c=0;c<s.length;c++){const e=s[c],t=h[s[c]];null==t||null==t?(s.splice(c,1),c--):r[e]=c}for(const e of l.getAttributes(this,o))a.push(e);this.buildUniformLayout();const u=[],d=[];for(c=0;c<o.length;c++){const e=a[c];e>=0&&(u.push(o[c]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=u,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new Ci.M(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=zr.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,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,n)}setInt4(e,t,i,n,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,n,s)}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,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,n)}setUInt4(e,t,i,n,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,n,s)}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,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,n)}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,n,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,n,s)}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 null===(e=this.sources)||void 0===e?void 0:e.vertex}_getFragmentShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.fragment}}const Hr={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Xr{static get KnownUBOs(){return Xr._SimplifiedKnownBindings?Xr._SimplifiedKnownUBOs:Xr._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=Xr.KnownUBOs,t=[];for(const i in e){const n=e[i].binding;-1!==n.groupIndex&&(void 0===t[n.groupIndex]?t[n.groupIndex]=n.bindingIndex:t[n.groupIndex]=Math.max(t[n.groupIndex],n.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;const n=this._attributeNextLocation;return this._attributeNextLocation+=(null!==(i=Hr[e])&&void 0!==i?i:1)*(t||1),n}getVaryingNextLocation(e,t=0){var i;const n=this._varyingNextLocation;return this._varyingNextLocation+=(null!==(i=Hr[e])&&void 0!==i?i:1)*(t||1),n}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)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}}Xr._SimplifiedKnownBindings=!0,Xr._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}}},Xr._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 jr extends zr{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=Cn.x.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let n=0;const s=e.indexOf("["),r=e.indexOf("]");if(s>0&&r>0){const t=e.substring(s+1,r);n=+t,isNaN(n)&&(n=+i[t.trim()]),e=e.substr(0,s)}return[e,t,n]}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\r\nuniform ${zr.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,n=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),n?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),n?e:i+e)}varyingProcessor(e,t,i){this._preProcessors=i;const n=(t&&this._fragmentIsGLES3?/\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==n){const s=n[1],r=n[2];let o;t?(o=this._webgpuProcessingContext.availableVaryings[r],this._missingVaryings[o]="",void 0===o&&_.Y.Warn(`Invalid fragment shader: The varying named "${r}" is not declared in the vertex shader! This declaration will be ignored.`)):(o=this._webgpuProcessingContext.getVaryingNextLocation(s,this._getArraySize(r,s,i)[2]),this._webgpuProcessingContext.availableVaryings[r]=o,this._missingVaryings[o]=`layout(location = ${o}) in ${s} ${r};`),e=e.replace(n[0],void 0===o?"":`layout(location = ${o}) ${t?"in":"out"} ${s} ${r};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){const n=i[1],s=i[2],r=this._webgpuProcessingContext.getAttributeNextLocation(n,this._getArraySize(s,n,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=r,this._webgpuProcessingContext.orderedAttributes[r]=s,e=e.replace(i[0],`layout(location = ${r}) in ${n} ${s};`)}return e}uniformProcessor(e,t,i){var n;this._preProcessors=i;const s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let r=s[1],o=s[2];if(0===r.indexOf("sampler")||1===r.indexOf("sampler")){let s=0;[o,r,s]=this._getArraySize(o,r,i);let a=this._webgpuProcessingContext.availableTextures[o];if(!a){a={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:vr.Float};for(let e=0;e<(s||1);++e)a.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const l=null!==(n=zr._SamplerTypeByWebGLSamplerType[r])&&void 0!==n?n:"sampler",h=!!zr._IsComparisonSamplerByWebGPUSamplerType[l],c=h?gr.Comparison:gr.Filtering,u=o+zr.AutoSamplerSuffix;let d=this._webgpuProcessingContext.availableSamplers[u];d||(d={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:c});const p="u"===r.charAt(0)?"u":"i"===r.charAt(0)?"i":"";p&&(r=r.substr(1));const f=h?vr.Depth:"u"===p?vr.Uint:"i"===p?vr.Sint:vr.Float;a.sampleType=f;const _=s>0,m=d.binding.groupIndex,g=d.binding.bindingIndex,v=zr._SamplerFunctionByWebGLSamplerType[r],y=zr._TextureTypeByWebGLSamplerType[r],x=zr._GpuTextureViewDimensionByWebGPUTextureType[y];if(_){const t=[];t.push(`layout(set = ${m}, binding = ${g}) uniform ${p}${l} ${u};`),e="\r\n";for(let i=0;i<s;++i){const n=a.textures[i].groupIndex,s=a.textures[i].bindingIndex;t.push(`layout(set = ${n}, binding = ${s}) uniform ${y} ${o}Texture${i};`),e+=`${i>0?"\r\n":""}#define ${o}${i} ${p}${v}(${o}Texture${i}, ${u})`}e=t.join("\r\n")+e,this._textureArrayProcessing.push(o)}else s=1,e=`layout(set = ${m}, binding = ${g}) uniform ${p}${l} ${u};\n layout(set = ${a.textures[0].groupIndex}, binding = ${a.textures[0].bindingIndex}) uniform ${y} ${o}Texture;\n #define ${o} ${p}${v}(${o}Texture, ${u})`;this._webgpuProcessingContext.availableTextures[o]=a,this._webgpuProcessingContext.availableSamplers[u]=d,this._addSamplerBindingDescription(u,d,!t);for(let e=0;e<s;++e)this._addTextureBindingDescription(o,a,e,x,null,!t)}else this._addUniformToLeftOverUBO(o,r,i),e=""}return e}uniformBufferProcessor(e,t){const i=/uniform\s+(\w+)/gm.exec(e);if(null!==i){const n=i[1];let s=this._webgpuProcessingContext.availableBuffers[n];if(!s){const e=Xr.KnownUBOs[n];let t;t=e&&-1!==e.binding.groupIndex?e.binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),s={binding:t},this._webgpuProcessingContext.availableBuffers[n]=s}this._addBufferBindingDescription(n,s,mr.Uniform,!t),e=e.replace("uniform",`layout(set = ${s.binding.groupIndex}, binding = ${s.binding.bindingIndex}) uniform`)}return e}postProcessor(e,t,i,n,s){const r=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=e.indexOf("gl_FragCoord")>=0,i="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",n=t?"vec4 glFragCoord_;\n":"";if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",n),t&&(e=this._injectStartingAndEndingCode(e,"void main",i))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",s.isNDCHalfZRange||(e+="gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n"),e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let n=i.exec(e);for(;null!==n;){const s=n[1];let r=+s;this._preProcessors&&isNaN(r)&&(r=+this._preProcessors[s.trim()]),e=e.replace(n[0],t+r),n=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}];\n`:i+=` ${e.type} ${e.name};\n`;return i+="};\n\n",i}finalizeShaders(e,t){for(let i=0;i<this._textureArrayProcessing.length;++i){const n=this._textureArrayProcessing[i];e=this._applyTextureArrayProcessing(e,n),t=this._applyTextureArrayProcessing(t,n)}for(let e=0;e<this._missingVaryings.length;++e){const i=this._missingVaryings[e];i&&i.length>0&&(t=i+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,{vertexCode:e,fragmentCode:t}}}var Yr=i(8985);si.v.IncludesShadersStoreWGSL.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4<f32>;\nattribute matricesWeights : vec4<f32>;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4<f32>;\nattribute matricesWeightsExtra : vec4<f32>;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d<f32>;\nuniform boneTextureWidth : f32;\n#else\nuniform mBones : array<mat4x4,BonesPerMesh>;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array<mat4x4,BonesPerMesh>;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32)->mat4x4<f32>\n{\nlet offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2<i32>(offset+0,0),0);\nlet m1=textureLoad(smp,vec2<i32>(offset+1,0),0);\nlet m2=textureLoad(smp,vec2<i32>(offset+2,0),0);\nlet m3=textureLoad(smp,vec2<i32>(offset+3,0),0);\nreturn mat4x4<f32>(m0,m1,m2,m3);\n}\n#endif\n#endif\n#endif\n";si.v.IncludesShadersStoreWGSL.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4<f32>;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";si.v.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;\nuniform bakedVertexAnimationTextureSizeInverted: vec2<f32>;\nuniform bakedVertexAnimationSettings: vec4<f32>;\nvar bakedVertexAnimationTexture : texture_2d<f32>;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4<f32>;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32)->mat4x4<f32>\n{\nlet offset=i32(index)*4;\nlet frameUV=i32(frame);\nlet m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);\nlet m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);\nlet m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);\nlet m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);\nreturn mat4x4<f32>(m0,m1,m2,m3);\n}\n#endif\n";si.v.IncludesShadersStoreWGSL.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;\nlet VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;\nlet VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;\nlet VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;\nlet VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;\nlet VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;\nlet VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;\nlet time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;\nlet frameCorrection: f32=select(1.0,0.0,time<1.0);\nlet numOfFrames: f32=totalFrames-frameCorrection;\nvar VATFrameNum: f32=fract(time)*numOfFrames;\nVATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;\nVATFrameNum=floor(VATFrameNum);\nVATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;\nvar VATInfluence : mat4x4<f32>;\nVATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;\n}\n#endif\n";si.v.IncludesShadersStoreWGSL.clipPlaneFragment="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{\ndiscard;\n}\n#endif\n";si.v.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";si.v.IncludesShadersStoreWGSL.clipPlaneVertex="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";si.v.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vClipPlane: vec4<f32>;\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4<f32>;\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4<f32>;\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4<f32>;\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4<f32>;\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4<f32>;\nvarying fClipDistance6: f32;\n#endif\n";si.v.IncludesShadersStoreWGSL.instancesDeclaration="#ifdef INSTANCES\nattribute world0 : vec4<f32>;\nattribute world1 : vec4<f32>;\nattribute world2 : vec4<f32>;\nattribute world3 : vec4<f32>;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4<f32>;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4<f32>;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4<f32>;\nattribute previousWorld1 : vec4<f32>;\nattribute previousWorld2 : vec4<f32>;\nattribute previousWorld3 : vec4<f32>;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4<f32>;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4<f32>;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4<f32>;\n#endif\n#endif\n";si.v.IncludesShadersStoreWGSL.instancesVertex="#ifdef INSTANCES\nvar finalWorld=mat4x4<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4<f32>(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\n#endif\n#endif\n";si.v.IncludesShadersStoreWGSL.meshUboDeclaration="struct Mesh {\nworld : mat4x4<f32>,\nvisibility : f32,\n};\nvar<uniform> mesh : Mesh;\n#define WORLD_UBO\n";si.v.IncludesShadersStoreWGSL.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE \nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;\npositionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";si.v.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3<f32>;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3<f32>;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3<f32>;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2<f32>;\n#endif\n#endif\n#endif\n";si.v.IncludesShadersStoreWGSL.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";si.v.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array<f32,NUM_MORPH_INFLUENCERS>;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;\nuniform morphTargetTextureInfo : vec3<f32>;\nvar morphTargets : texture_2d_array<f32>;\nvar morphTargetsSampler : sampler;\nfn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3<f32>\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);\nlet x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;\nlet textureUV=vec2<f32>((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);\nreturn textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;\n}\n#endif\n#endif\n";si.v.IncludesShadersStoreWGSL.sceneUboDeclaration="struct Scene {\nviewProjection : mat4x4<f32>,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4<f32>,\n#endif \nview : mat4x4<f32>,\nprojection : mat4x4<f32>,\nvEyePosition : vec4<f32>,\n};\nvar<uniform> scene : Scene;\n";const qr={texture_1d:lr.E1d,texture_2d:lr.E2d,texture_2d_array:lr.E2dArray,texture_3d:lr.E3d,texture_cube:lr.Cube,texture_cube_array:lr.CubeArray,texture_multisampled_2d:lr.E2d,texture_depth_2d:lr.E2d,texture_depth_2d_array:lr.E2dArray,texture_depth_cube:lr.Cube,texture_depth_cube_array:lr.CubeArray,texture_depth_multisampled_2d:lr.E2d,texture_storage_1d:lr.E1d,texture_storage_2d:lr.E2d,texture_storage_2d_array:lr.E2dArray,texture_storage_3d:lr.E3d,texture_external:null};class Kr extends zr{constructor(){super(...arguments),this.shaderLanguage=Cn.x.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 n=0;const s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const r=t.substring(e+1,s);for(n=+r,isNaN(n)&&(n=+i[r.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,n]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesWGSL=[],this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return`struct ${zr.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar<uniform> internals : ${zr.InternalsUBOName};\n`+(0,Yr.Kt)(e)}varyingProcessor(e,t,i){const n=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==n){const s=n[2],r=n[1];let o;t?(o=this._webgpuProcessingContext.availableVaryings[r],void 0===o&&_.Y.Warn(`Invalid fragment shader: The varying named "${r}" is not declared in the vertex shader! This declaration will be ignored.`)):(o=this._webgpuProcessingContext.getVaryingNextLocation(s,this._getArraySize(r,s,i)[2]),this._webgpuProcessingContext.availableVaryings[r]=o,this._varyingsWGSL.push(` @location(${o}) ${r} : ${s},`),this._varyingNamesWGSL.push(r)),e=""}return e}attributeProcessor(e,t){const i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){const n=i[2],s=i[1],r=this._webgpuProcessingContext.getAttributeNextLocation(n,this._getArraySize(s,n,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=r,this._webgpuProcessingContext.orderedAttributes[r]=s,this._attributesWGSL.push(`@location(${r}) ${s} : ${n},`),e=""}return e}uniformProcessor(e,t,i){const n=this.uniformRegexp.exec(e);if(null!==n){const t=n[2],s=n[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){const n=this.textureRegexp.exec(e);if(null!==n){const s=n[1],r=n[2],o=!!n[3],a=n[4],l=a.indexOf("storage")>0,h=n[6],c=l?h.substring(0,h.indexOf(",")).trim():null;let u=o?this._getArraySize(s,r,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[s];if(d)u=d.textures.length;else{d={isTextureArray:u>0,isStorageTexture:l,textures:[],sampleType:vr.Float},u=u||1;for(let e=0;e<u;++e)d.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}this._webgpuProcessingContext.availableTextures[s]=d;const p=a.indexOf("depth")>0,f=qr[a],_=p?vr.Depth:"u32"===h?vr.Uint:"i32"===h?vr.Sint:vr.Float;if(d.sampleType=_,void 0===f)throw`Can't get the texture dimension corresponding to the texture function "${a}"!`;for(let i=0;i<u;++i){const{groupIndex:n,bindingIndex:r}=d.textures[i];0===i&&(e=`@group(${n}) @binding(${r}) ${e}`),this._addTextureBindingDescription(s,d,i,f,c,!t)}}return e}postProcessor(e){return e}finalizeShaders(e,t){const i=t.indexOf("fragmentInputs.position")>=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const n=this._buildLeftOverUBO();t=n+t,e=(e=n+e).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let s="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesWGSL.length>0&&(s+=this._attributesWGSL.join("\n")),s+="\n};\nvar<private> vertexInputs : VertexInputs;\n";let r="struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n";this._varyingsWGSL.length>0&&(r+=this._varyingsWGSL.join("\n")),r+="\n};\nvar<private> vertexOutputs : FragmentInputs;\n",e=s+r+e,e=this._injectStartingAndEndingCode(e,"fn main","\n vertexInputs = input;\n"," vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;"),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let o="struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(o+=this._varyingsWGSL.join("\n")),o+="\n};\nvar<private> fragmentInputs : FragmentInputs;\n";let a="struct FragmentOutputs {\n @location(0) color : vec4<f32>,\n",l=!1,h=0;for(;!(l||(h=t.indexOf("fragmentOutputs.fragDepth",h),h<0));){const e=h;for(l=!0;h>1&&"\n"!==t.charAt(h);){if("/"===t.charAt(h)&&"/"===t.charAt(h-1)){l=!1;break}h--}h=e+25}l&&(a+=" @builtin(frag_depth) fragDepth: f32,\n"),a+="};\nvar<private> fragmentOutputs : FragmentOutputs;\n",t=o+a+t;const c=" fragmentInputs = input;\n "+i;return t=this._injectStartingAndEndingCode(t,"fn main",c," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",n=`struct ${e} {\n`;for(const t of this._webgpuProcessingContext.leftOverUniforms){const s=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),r=zr.UniformSizes[s];if(t.length>0)if(r<=2){const r=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${r} {\n @size(16)\n el: ${s},\n }`,this._stridedUniformArrays.push(t.name),n+=` @align(16) ${t.name} : array<${r}, ${t.length}>,\n`}else n+=` ${t.name} : array<${t.type}, ${t.length}>,\n`;else n+=` ${t.name} : ${t.type},\n`}return n+="};\n",n=`${i}\n${n}`,n+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var<uniform> uniforms : ${e};\n`,n}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const n=i.exec(e);if(null===n)break;const s=n[1],r=n[2],o=s.indexOf(zr.AutoSamplerSuffix)===s.length-zr.AutoSamplerSuffix.length?s.substring(0,s.indexOf(zr.AutoSamplerSuffix)):null,a="sampler_comparison"===r?gr.Comparison:gr.Filtering;if(o){const e=this._webgpuProcessingContext.availableTextures[o];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[s];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:a},this._webgpuProcessingContext.availableSamplers[s]=l),this._addSamplerBindingDescription(s,l,t);const h=e.substring(0,n.index),c=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,u=e.substring(n.index);e=h+c+u,i.lastIndex+=c.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 n=i.exec(e);if(null===n)break;const s=n[1],r=n[3];let o=n[4];const a=n[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const e="uniform"===s?Xr.KnownUBOs[a]:null;let t;e?(o=a,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.getNextFreeUBOBinding())):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:t},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],"read_write"===r?mr.Storage:"storage"===s?mr.ReadOnlyStorage:mr.Uniform,t);const h=l.binding.groupIndex,c=l.binding.bindingIndex,u=e.substring(0,n.index),d=`@group(${h}) @binding(${c}) `,p=e.substring(n.index);e=u+d+p,i.lastIndex+=d.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 $r{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t,i;return null!==(i=null===(t=this._webgpuMSAATexture)||void 0===t?void 0:t[e])&&void 0!==i?i:null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)null==e||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=cr.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,n,s){this.createView({format:this.format,dimension:i?lr.Cube:lr.E2d,mipLevelCount:t?lt.R.ILog2(Math.max(n,s))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:hr.All})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;null===(e=this._webgpuTexture)||void 0===e||e.destroy(),this.releaseMSAATexture(),null===(t=this._copyInvertYTempTexture)||void 0===t||t.destroy(),this.reset()}}const Qr="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",Zr=Qr;var Jr,eo;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(Jr||(Jr={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(eo||(eo={}));const to=[{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n "},{vertex:Qr,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "},{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n "},{vertex:Zr,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "}],io={"":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,rgb10a2unorm:22,rg32uint:23,rg32sint:24,rg32float:25,rgba16uint:26,rgba16sint:27,rgba16float:28,rgba32uint:29,rgba32sint:30,rgba32float:31,stencil8:32,depth16unorm:33,depth24plus:34,"depth24plus-stencil8":35,depth32float:36,"depth24unorm-stencil8":37,"depth32float-stencil8":38};class no{static ComputeNumMipmapLevels(e,t){return lt.R.ILog2(Math.max(e,t))+1}constructor(e,t,i,n){this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=n,this._mipmapSampler=e.createSampler({minFilter:dr.Linear}),this._videoSampler=e.createSampler({minFilter:dr.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,sr.Uniform|sr.CopyDst).underlyingResource,this._getPipeline(cr.RGBA8Unorm),this._getVideoPipeline(cr.RGBA8Unorm)}_getPipeline(e,t=Jr.MipMap,i){const n=t===Jr.MipMap?1:t===Jr.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Jr.Clear?8:t===Jr.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][n];if(!s){let r="#version 450\r\n";t!==Jr.InvertYPremultiplyAlpha&&t!==Jr.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(r+="#define INVERTY\r\n"),i.premultiplyAlpha&&(r+="#define PREMULTIPLYALPHA\r\n"));let o=this._compiledShaders[n];if(!o){let e=this._glslang.compileGLSL(r+to[t].vertex,"vertex"),i=this._glslang.compileGLSL(r+to[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));const s=this._device.createShaderModule({code:e}),a=this._device.createShaderModule({code:i});o=this._compiledShaders[n]=[s,a]}const a=this._device.createRenderPipeline({layout:Tr.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Sr.TriangleStrip,stripIndexFormat:Ir.Uint16}});s=this._pipelines[e][n]=[a,a.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=eo.DontInvertY){const i=t===eo.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let n=this._videoPipelines[e][i];if(!n){let t=this._videoCompiledShaders[i];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4<f32>,\n @location(0) fragUV : vec2<f32>\n }\n \n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array<vec2<f32>, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array<vec2<f32>, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),n=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2<f32>\n ) -> @location(0) vec4<f32> {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2<f32>\n ) -> @location(0) vec4<f32> {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2<f32>(fragUV.x, 1.0 - fragUV.y));\n }\n "});t=this._videoCompiledShaders[i]=[e,n]}const s=this._device.createRenderPipeline({label:`CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:Tr.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Sr.TriangleStrip,stripIndexFormat:Ir.Uint16}});n=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return n}static _GetTextureTypeFromFormat(e){switch(e){case cr.R8Unorm:case cr.R8Snorm:case cr.R8Uint:case cr.R8Sint:case cr.RG8Unorm:case cr.RG8Snorm:case cr.RG8Uint:case cr.RG8Sint:case cr.RGBA8Unorm:case cr.RGBA8UnormSRGB:case cr.RGBA8Snorm:case cr.RGBA8Uint:case cr.RGBA8Sint:case cr.BGRA8Unorm:case cr.BGRA8UnormSRGB:case cr.RGB10A2Unorm:case cr.RGB9E5UFloat:case cr.RG11B10UFloat:case cr.Depth24UnormStencil8:case cr.Depth32FloatStencil8:case cr.BC7RGBAUnorm:case cr.BC7RGBAUnormSRGB:case cr.BC6HRGBUFloat:case cr.BC6HRGBFloat:case cr.BC5RGUnorm:case cr.BC5RGSnorm:case cr.BC3RGBAUnorm:case cr.BC3RGBAUnormSRGB:case cr.BC2RGBAUnorm:case cr.BC2RGBAUnormSRGB:case cr.BC4RUnorm:case cr.BC4RSnorm:case cr.BC1RGBAUnorm:case cr.BC1RGBAUnormSRGB:case cr.ETC2RGB8Unorm:case cr.ETC2RGB8UnormSRGB:case cr.ETC2RGB8A1Unorm:case cr.ETC2RGB8A1UnormSRGB:case cr.ETC2RGBA8Unorm:case cr.ETC2RGBA8UnormSRGB:case cr.EACR11Unorm:case cr.EACR11Snorm:case cr.EACRG11Unorm:case cr.EACRG11Snorm:case cr.ASTC4x4Unorm:case cr.ASTC4x4UnormSRGB:case cr.ASTC5x4Unorm:case cr.ASTC5x4UnormSRGB:case cr.ASTC5x5Unorm:case cr.ASTC5x5UnormSRGB:case cr.ASTC6x5Unorm:case cr.ASTC6x5UnormSRGB:case cr.ASTC6x6Unorm:case cr.ASTC6x6UnormSRGB:case cr.ASTC8x5Unorm:case cr.ASTC8x5UnormSRGB:case cr.ASTC8x6Unorm:case cr.ASTC8x6UnormSRGB:case cr.ASTC8x8Unorm:case cr.ASTC8x8UnormSRGB:case cr.ASTC10x5Unorm:case cr.ASTC10x5UnormSRGB:case cr.ASTC10x6Unorm:case cr.ASTC10x6UnormSRGB:case cr.ASTC10x8Unorm:case cr.ASTC10x8UnormSRGB:case cr.ASTC10x10Unorm:case cr.ASTC10x10UnormSRGB:case cr.ASTC12x10Unorm:case cr.ASTC12x10UnormSRGB:case cr.ASTC12x12Unorm:case cr.ASTC12x12UnormSRGB:return 0;case cr.R16Uint:case cr.R16Sint:case cr.RG16Uint:case cr.RG16Sint:case cr.RGBA16Uint:case cr.RGBA16Sint:case cr.Depth16Unorm:return 5;case cr.R16Float:case cr.RG16Float:case cr.RGBA16Float:return 2;case cr.R32Uint:case cr.R32Sint:case cr.RG32Uint:case cr.RG32Sint:case cr.RGBA32Uint:case cr.RGBA32Sint:return 7;case cr.R32Float:case cr.RG32Float:case cr.RGBA32Float:case cr.Depth32Float:return 1;case cr.Stencil8:throw"No fixed size for Stencil8 format!";case cr.Depth24Plus:throw"No fixed size for Depth24Plus format!";case cr.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!"}return 0}static _GetBlockInformationFromFormat(e){switch(e){case cr.R8Unorm:case cr.R8Snorm:case cr.R8Uint:case cr.R8Sint:return{width:1,height:1,length:1};case cr.R16Uint:case cr.R16Sint:case cr.R16Float:case cr.RG8Unorm:case cr.RG8Snorm:case cr.RG8Uint:case cr.RG8Sint:return{width:1,height:1,length:2};case cr.R32Uint:case cr.R32Sint:case cr.R32Float:case cr.RG16Uint:case cr.RG16Sint:case cr.RG16Float:case cr.RGBA8Unorm:case cr.RGBA8UnormSRGB:case cr.RGBA8Snorm:case cr.RGBA8Uint:case cr.RGBA8Sint:case cr.BGRA8Unorm:case cr.BGRA8UnormSRGB:case cr.RGB9E5UFloat:case cr.RGB10A2Unorm:case cr.RG11B10UFloat:return{width:1,height:1,length:4};case cr.RG32Uint:case cr.RG32Sint:case cr.RG32Float:case cr.RGBA16Uint:case cr.RGBA16Sint:case cr.RGBA16Float:return{width:1,height:1,length:8};case cr.RGBA32Uint:case cr.RGBA32Sint:case cr.RGBA32Float:return{width:1,height:1,length:16};case cr.Stencil8:throw"No fixed size for Stencil8 format!";case cr.Depth16Unorm:return{width:1,height:1,length:2};case cr.Depth24Plus:throw"No fixed size for Depth24Plus format!";case cr.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case cr.Depth32Float:case cr.Depth24UnormStencil8:return{width:1,height:1,length:4};case cr.Depth32FloatStencil8:return{width:1,height:1,length:5};case cr.BC7RGBAUnorm:case cr.BC7RGBAUnormSRGB:case cr.BC6HRGBUFloat:case cr.BC6HRGBFloat:case cr.BC5RGUnorm:case cr.BC5RGSnorm:case cr.BC3RGBAUnorm:case cr.BC3RGBAUnormSRGB:case cr.BC2RGBAUnorm:case cr.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case cr.BC4RUnorm:case cr.BC4RSnorm:case cr.BC1RGBAUnorm:case cr.BC1RGBAUnormSRGB:case cr.ETC2RGB8Unorm:case cr.ETC2RGB8UnormSRGB:case cr.ETC2RGB8A1Unorm:case cr.ETC2RGB8A1UnormSRGB:case cr.EACR11Unorm:case cr.EACR11Snorm:return{width:4,height:4,length:8};case cr.ETC2RGBA8Unorm:case cr.ETC2RGBA8UnormSRGB:case cr.EACRG11Unorm:case cr.EACRG11Snorm:case cr.ASTC4x4Unorm:case cr.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case cr.ASTC5x4Unorm:case cr.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case cr.ASTC5x5Unorm:case cr.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case cr.ASTC6x5Unorm:case cr.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case cr.ASTC6x6Unorm:case cr.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case cr.ASTC8x5Unorm:case cr.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case cr.ASTC8x6Unorm:case cr.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case cr.ASTC8x8Unorm:case cr.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case cr.ASTC10x5Unorm:case cr.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case cr.ASTC10x6Unorm:case cr.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case cr.ASTC10x8Unorm:case cr.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case cr.ASTC10x10Unorm:case cr.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case cr.ASTC12x10Unorm:case cr.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case cr.ASTC12x12Unorm:case cr.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 void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}setCommandEncoder(e){this._commandEncoderForCreation=e}static IsCompressedFormat(e){switch(e){case cr.BC7RGBAUnormSRGB:case cr.BC7RGBAUnorm:case cr.BC6HRGBFloat:case cr.BC6HRGBUFloat:case cr.BC5RGSnorm:case cr.BC5RGUnorm:case cr.BC4RSnorm:case cr.BC4RUnorm:case cr.BC3RGBAUnormSRGB:case cr.BC3RGBAUnorm:case cr.BC2RGBAUnormSRGB:case cr.BC2RGBAUnorm:case cr.BC1RGBAUnormSRGB:case cr.BC1RGBAUnorm:case cr.ETC2RGB8Unorm:case cr.ETC2RGB8UnormSRGB:case cr.ETC2RGB8A1Unorm:case cr.ETC2RGB8A1UnormSRGB:case cr.ETC2RGBA8Unorm:case cr.ETC2RGBA8UnormSRGB:case cr.EACR11Unorm:case cr.EACR11Snorm:case cr.EACRG11Unorm:case cr.EACRG11Snorm:case cr.ASTC4x4Unorm:case cr.ASTC4x4UnormSRGB:case cr.ASTC5x4Unorm:case cr.ASTC5x4UnormSRGB:case cr.ASTC5x5Unorm:case cr.ASTC5x5UnormSRGB:case cr.ASTC6x5Unorm:case cr.ASTC6x5UnormSRGB:case cr.ASTC6x6Unorm:case cr.ASTC6x6UnormSRGB:case cr.ASTC8x5Unorm:case cr.ASTC8x5UnormSRGB:case cr.ASTC8x6Unorm:case cr.ASTC8x6UnormSRGB:case cr.ASTC8x8Unorm:case cr.ASTC8x8UnormSRGB:case cr.ASTC10x5Unorm:case cr.ASTC10x5UnormSRGB:case cr.ASTC10x6Unorm:case cr.ASTC10x6UnormSRGB:case cr.ASTC10x8Unorm:case cr.ASTC10x8UnormSRGB:case cr.ASTC10x10Unorm:case cr.ASTC10x10UnormSRGB:case cr.ASTC12x10Unorm:case cr.ASTC12x10UnormSRGB:case cr.ASTC12x12Unorm:case cr.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return cr.Depth16Unorm;case 16:return cr.Depth24Plus;case 13:return cr.Depth24PlusStencil8;case 14:return cr.Depth32Float;case 17:return cr.Depth24UnormStencil8;case 18:return cr.Depth32FloatStencil8;case 19:return cr.Stencil8;case 36492:return i?cr.BC7RGBAUnormSRGB:cr.BC7RGBAUnorm;case 36495:return cr.BC6HRGBUFloat;case 36494:return cr.BC6HRGBFloat;case 33779:return i?cr.BC3RGBAUnormSRGB:cr.BC3RGBAUnorm;case 33778:return i?cr.BC2RGBAUnormSRGB:cr.BC2RGBAUnorm;case 33777:case 33776:return i?cr.BC1RGBAUnormSRGB:cr.BC1RGBAUnorm;case 37808:return i?cr.ASTC4x4UnormSRGB:cr.ASTC4x4Unorm;case 36196:case 37492:return i?cr.ETC2RGB8UnormSRGB:cr.ETC2RGB8Unorm;case 37496:return i?cr.ETC2RGBA8UnormSRGB:cr.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return cr.R8Snorm;case 7:return cr.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return cr.R8Sint;case 9:return cr.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return cr.RGBA8Sint;default:return cr.RGBA8Snorm}case 0:switch(t){case 6:return cr.R8Unorm;case 7:return cr.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?cr.RGBA8UnormSRGB:cr.RGBA8Unorm;case 12:return i?cr.BGRA8UnormSRGB:cr.BGRA8Unorm;case 8:return cr.R8Uint;case 9:return cr.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return cr.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 cr.RGBA8Unorm}case 4:switch(t){case 8:return cr.R16Sint;case 9:return cr.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cr.RGBA16Sint}case 5:switch(t){case 8:return cr.R16Uint;case 9:return cr.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cr.RGBA16Uint}case 6:switch(t){case 8:return cr.R32Sint;case 9:return cr.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cr.RGBA32Sint}case 7:switch(t){case 8:return cr.R32Uint;case 9:return cr.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cr.RGBA32Uint}case 1:switch(t){case 6:return cr.R32Float;case 7:return cr.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return cr.RGBA32Float}case 2:switch(t){case 6:return cr.R16Float;case 7:return cr.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return cr.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:throw"TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV format not supported in WebGPU";case 14:throw"TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV format not supported in WebGPU";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:default:return cr.RGB10A2Unorm;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV"}}return i?cr.RGBA8UnormSRGB:cr.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case cr.R8Unorm:case cr.R8Snorm:case cr.R8Uint:case cr.R8Sint:case cr.BC4RUnorm:case cr.BC4RSnorm:case cr.R16Uint:case cr.R16Sint:case cr.Depth16Unorm:case cr.R16Float:case cr.R32Uint:case cr.R32Sint:case cr.R32Float:case cr.Depth32Float:case cr.Stencil8:case cr.Depth24Plus:case cr.EACR11Unorm:case cr.EACR11Snorm:return 1;case cr.RG8Unorm:case cr.RG8Snorm:case cr.RG8Uint:case cr.RG8Sint:case cr.Depth24UnormStencil8:case cr.Depth32FloatStencil8:case cr.BC5RGUnorm:case cr.BC5RGSnorm:case cr.RG16Uint:case cr.RG16Sint:case cr.RG16Float:case cr.RG32Uint:case cr.RG32Sint:case cr.RG32Float:case cr.Depth24PlusStencil8:case cr.EACRG11Unorm:case cr.EACRG11Snorm:return 2;case cr.RGB9E5UFloat:case cr.RG11B10UFloat:case cr.BC6HRGBUFloat:case cr.BC6HRGBFloat:case cr.ETC2RGB8Unorm:case cr.ETC2RGB8UnormSRGB:return 3;case cr.RGBA8Unorm:case cr.RGBA8UnormSRGB:case cr.RGBA8Snorm:case cr.RGBA8Uint:case cr.RGBA8Sint:case cr.BGRA8Unorm:case cr.BGRA8UnormSRGB:case cr.RGB10A2Unorm:case cr.BC7RGBAUnorm:case cr.BC7RGBAUnormSRGB:case cr.BC3RGBAUnorm:case cr.BC3RGBAUnormSRGB:case cr.BC2RGBAUnorm:case cr.BC2RGBAUnormSRGB:case cr.BC1RGBAUnorm:case cr.BC1RGBAUnormSRGB:case cr.RGBA16Uint:case cr.RGBA16Sint:case cr.RGBA16Float:case cr.RGBA32Uint:case cr.RGBA32Sint:case cr.RGBA32Float:case cr.ETC2RGB8A1Unorm:case cr.ETC2RGB8A1UnormSRGB:case cr.ETC2RGBA8Unorm:case cr.ETC2RGBA8UnormSRGB:case cr.ASTC4x4Unorm:case cr.ASTC4x4UnormSRGB:case cr.ASTC5x4Unorm:case cr.ASTC5x4UnormSRGB:case cr.ASTC5x5Unorm:case cr.ASTC5x5UnormSRGB:case cr.ASTC6x5Unorm:case cr.ASTC6x5UnormSRGB:case cr.ASTC6x6Unorm:case cr.ASTC6x6UnormSRGB:case cr.ASTC8x5Unorm:case cr.ASTC8x5UnormSRGB:case cr.ASTC8x6Unorm:case cr.ASTC8x6UnormSRGB:case cr.ASTC8x8Unorm:case cr.ASTC8x8UnormSRGB:case cr.ASTC10x5Unorm:case cr.ASTC10x5UnormSRGB:case cr.ASTC10x6Unorm:case cr.ASTC10x6UnormSRGB:case cr.ASTC10x8Unorm:case cr.ASTC10x8UnormSRGB:case cr.ASTC10x10Unorm:case cr.ASTC10x10UnormSRGB:case cr.ASTC12x10Unorm:case cr.ASTC12x10UnormSRGB:case cr.ASTC12x12Unorm:case cr.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case cr.Stencil8:case cr.Depth24UnormStencil8:case cr.Depth32FloatStencil8:case cr.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case cr.Depth24UnormStencil8:case cr.Depth32FloatStencil8:case cr.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case cr.Depth16Unorm:return cr.Depth16Unorm;case cr.Depth24Plus:case cr.Depth24PlusStencil8:case cr.Depth24UnormStencil8:return cr.Depth24Plus;case cr.Depth32Float:case cr.Depth32FloatStencil8:return cr.Depth32Float}return e}copyVideoToTexture(e,t,i,n=!1,s){var r,o,a,l;const h=void 0===s,[c,u]=this._getVideoPipeline(i,n?eo.InvertY:eo.DontInvertY);h&&(s=this._device.createCommandEncoder({})),null===(o=(r=s).pushDebugGroup)||void 0===o||o.call(r,`copy video to texture - invertY=${n}`);const d={colorAttachments:[{view:t._hardwareTexture.underlyingResource.createView({format:i,dimension:lr.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:hr.All}),loadOp:Fr.Load,storeOp:Lr.Store}]},p=s.beginRenderPass(d),f={layout:u,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},_=this._device.createBindGroup(f);p.setPipeline(c),p.setBindGroup(0,_),p.draw(4,1,0,0),p.end(),null===(l=(a=s).popDebugGroup)||void 0===l||l.call(a),h&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,n,s=!1,r=!1,o=0,a=0,l=1,h=0,c=0,u=0,d=0,p,f){var _,m,g,v,y,x;const b=0!==u,T=void 0===p,[S,E]=this._getPipeline(n,b?Jr.InvertYPremultiplyAlphaWithOfst:Jr.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:r});let C;if(o=Math.max(o,0),T&&(p=this._device.createCommandEncoder({})),null===(m=(_=p).pushDebugGroup)||void 0===m||m.call(_,`internal process texture - invertY=${s} premultiplyAlpha=${r}`),no._IsHardwareTexture(e)?(C=e.underlyingResource,s&&!r&&1===l&&0===o||(e=void 0)):(C=e,e=void 0),!C)return;b&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,u,d]),0,16);const A=e,P=null!==(g=null==A?void 0:A._copyInvertYTempTexture)&&void 0!==g?g:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,n,1,p,ar.CopySrc|ar.RenderAttachment|ar.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),R=null!==(v=null==A?void 0:A._copyInvertYRenderPassDescr)&&void 0!==v?v:{colorAttachments:[{view:P.createView({format:n,dimension:lr.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Fr.Load,storeOp:Lr.Store}]},M=p.beginRenderPass(R);let I=b?null==A?void 0:A._copyInvertYBindGroupWithOfst:null==A?void 0:A._copyInvertYBindGroup;if(!I){const e={layout:E,entries:[{binding:0,resource:C.createView({format:n,dimension:lr.E2d,baseMipLevel:a,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};b&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),I=this._device.createBindGroup(e)}M.setPipeline(S),M.setBindGroup(0,I),M.draw(4,1,0,0),M.end(),p.copyTextureToTexture({texture:P},{texture:C,mipLevel:a,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),A?(A._copyInvertYTempTexture=P,A._copyInvertYRenderPassDescr=R,b?A._copyInvertYBindGroupWithOfst=I:A._copyInvertYBindGroup=I):this._deferredReleaseTextures.push([P,null]),null===(x=(y=p).popDebugGroup)||void 0===x||x.call(y),T&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,n){var s,r,o,a;const l=void 0===n,[h,c]=this._getPipeline(t,Jr.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});l&&(n=this._device.createCommandEncoder({})),null===(r=(s=n).pushDebugGroup)||void 0===r||r.call(s,"internal copy texture with invertY");const u=n.beginRenderPass(i),d=this._device.createBindGroup({layout:c,entries:[{binding:0,resource:e}]});u.setPipeline(h),u.setBindGroup(0,d),u.draw(4,1,0,0),u.end(),null===(a=(o=n).popDebugGroup)||void 0===a||a.call(o),l&&(this._device.queue.submit([n.finish()]),n=null)}createTexture(e,t=!1,i=!1,n=!1,s=!1,r=!1,o=cr.RGBA8Unorm,a=1,l,h=-1,c=0,u){a>1&&(a=4);const d=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:d},f=no.IsCompressedFormat(o),_=t?no.ComputeNumMipmapLevels(e.width,e.height):1,m=h>=0?h:ar.CopySrc|ar.CopyDst|ar.TextureBinding;c|=t&&!f?ar.CopySrc|ar.RenderAttachment:0,f||r||(c|=ar.RenderAttachment|ar.CopyDst);const g=this._device.createTexture({label:`Texture${r?"3D":"2D"}_${u?u+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${a}`,size:p,dimension:r?or.E3d:or.E2d,format:o,usage:m|c,sampleCount:a,mipLevelCount:_});return no.IsImageBitmap(e)&&(this.updateTexture(e,g,e.width,e.height,d,o,0,0,n,s,0,0),t&&i&&this.generateMipmaps(g,o,_,0,l)),g}createCubeTexture(e,t=!1,i=!1,n=!1,s=!1,r=cr.RGBA8Unorm,o=1,a,l=-1,h=0,c){o>1&&(o=4);const u=no.IsImageBitmapArray(e)?e[0].width:e.width,d=no.IsImageBitmapArray(e)?e[0].height:e.height,p=no.IsCompressedFormat(r),f=t?no.ComputeNumMipmapLevels(u,d):1,_=l>=0?l:ar.CopySrc|ar.CopyDst|ar.TextureBinding;h|=t&&!p?ar.CopySrc|ar.RenderAttachment:0,p||(h|=ar.RenderAttachment|ar.CopyDst);const m=this._device.createTexture({label:`TextureCube_${c?c+"_":""}${u}x${d}x6_${t?"wmips":"womips"}_${r}_samples${o}`,size:{width:u,height:d,depthOrArrayLayers:6},dimension:or.E2d,format:r,usage:_|h,sampleCount:o,mipLevelCount:f});return no.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,m,u,d,r,n,s,0,0),t&&i&&this.generateCubeMipmaps(m,r,f,a)),m}generateCubeMipmaps(e,t,i,n){var s,r,o,a;const l=void 0===n;l&&(n=this._device.createCommandEncoder({})),null===(r=(s=n).pushDebugGroup)||void 0===r||r.call(s,`create cube mipmaps - ${i} levels`);for(let s=0;s<6;++s)this.generateMipmaps(e,t,i,s,n);null===(a=(o=n).popDebugGroup)||void 0===a||a.call(o),l&&(this._device.queue.submit([n.finish()]),n=null)}generateMipmaps(e,t,i,n=0,s){var r,o,a,l,h,c,u,d;const p=void 0===s,[f,_]=this._getPipeline(t);let m;if(n=Math.max(n,0),p&&(s=this._device.createCommandEncoder({})),null===(o=(r=s).pushDebugGroup)||void 0===o||o.call(r,`create mipmaps for face #${n} - ${i} levels`),no._IsHardwareTexture(e)?(m=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(m=e,e=void 0),!m)return;const g=e;for(let e=1;e<i;++e){const i=null!==(l=null===(a=null==g?void 0:g._mipmapGenRenderPassDescr[n])||void 0===a?void 0:a[e-1])&&void 0!==l?l:{colorAttachments:[{view:m.createView({format:t,dimension:lr.E2d,baseMipLevel:e,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:n}),loadOp:Fr.Load,storeOp:Lr.Store}]};g&&(g._mipmapGenRenderPassDescr[n]=g._mipmapGenRenderPassDescr[n]||[],g._mipmapGenRenderPassDescr[n][e-1]=i);const r=s.beginRenderPass(i),o=null!==(c=null===(h=null==g?void 0:g._mipmapGenBindGroup[n])||void 0===h?void 0:h[e-1])&&void 0!==c?c:this._device.createBindGroup({layout:_,entries:[{binding:0,resource:this._mipmapSampler},{binding:1,resource:m.createView({format:t,dimension:lr.E2d,baseMipLevel:e-1,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:n})}]});g&&(g._mipmapGenBindGroup[n]=g._mipmapGenBindGroup[n]||[],g._mipmapGenBindGroup[n][e-1]=o),r.setPipeline(f),r.setBindGroup(0,o),r.draw(4,1,0,0),r.end()}null===(d=(u=s).popDebugGroup)||void 0===d||d.call(u),p&&(this._device.queue.submit([s.finish()]),s=null)}createGPUTextureForInternalTexture(e,t,i,n,s){e._hardwareTexture||(e._hardwareTexture=new $r),void 0===t&&(t=e.width),void 0===i&&(i=e.height),void 0===n&&(n=e.depth);const r=e._hardwareTexture,o=0!=(1&(null!=s?s:0));r.format=no.GetWebGPUTextureFormat(e.type,e.format,e._useSRGBBuffer),r.textureUsages=e._source===Ei.S.RenderTarget||e.source===Ei.S.MultiRenderTarget?ar.TextureBinding|ar.CopySrc|ar.RenderAttachment:e._source===Ei.S.DepthStencil?ar.TextureBinding|ar.RenderAttachment:-1,r.textureAdditionalUsages=o?ar.StorageBinding:0;const a=e.generateMipMaps,l=n||1;let h;if(h=null!==e._maxLodLevel?e._maxLodLevel:a?no.ComputeNumMipmapLevels(t,i):1,e.isCube){const n=this.createCubeTexture({width:t,height:i},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,r.format,1,this._commandEncoderForCreation,r.textureUsages,r.textureAdditionalUsages,e.label);r.set(n),r.createView({format:no.GetDepthFormatOnly(r.format),dimension:lr.Cube,mipLevelCount:h,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:6,aspect:no.HasDepthAndStencilAspects(r.format)?hr.DepthOnly:hr.All},o)}else{const n=this.createTexture({width:t,height:i,layers:l},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,e.is3D,r.format,1,this._commandEncoderForCreation,r.textureUsages,r.textureAdditionalUsages,e.label);r.set(n),r.createView({format:no.GetDepthFormatOnly(r.format),dimension:e.is2DArray?lr.E2dArray:e.is3D?or.E3d:lr.E2d,mipLevelCount:h,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:e.is3D?1:l,aspect:no.HasDepthAndStencilAspects(r.format)?hr.DepthOnly:hr.All},o)}return e.width=e.baseWidth=t,e.height=e.baseHeight=i,e.depth=e.baseDepth=n,this.createMSAATexture(e,e.samples),r}createMSAATexture(e,t,i=!0,n=-1){const s=e._hardwareTexture;if(i&&(null==s||s.releaseMSAATexture()),!s||(null!=t?t:1)<=1)return;const r=e.width,o=e.height,a=this.createTexture({width:r,height:o,layers:1},!1,!1,!1,!1,!1,s.format,t,this._commandEncoderForCreation,ar.RenderAttachment,0,e.label?"MSAA"+e.label:void 0);s.setMSAATexture(a,n)}updateCubeTextures(e,t,i,n,s,r=!1,o=!1,a=0,l=0){const h=[0,3,1,4,2,5];for(let c=0;c<h.length;++c){const u=e[h[c]];this.updateTexture(u,t,i,n,1,s,c,0,r,o,a,l)}}updateTexture(e,t,i,n,s,r,o=0,a=0,l=!1,h=!1,c=0,u=0,d){const p=no._IsInternalTexture(t)?t._hardwareTexture.underlyingResource:t,f=no._GetBlockInformationFromFormat(r),_=no._IsInternalTexture(t)?t._hardwareTexture:t,m={texture:p,origin:{x:c,y:u,z:Math.max(o,0)},mipLevel:a,premultipliedAlpha:h},g={width:Math.ceil(i/f.width)*f.width,height:Math.ceil(n/f.height)*f.height,depthOrArrayLayers:s||1};if(void 0!==e.byteLength){const p=Math.ceil(i/f.width)*f.length;if(256*Math.ceil(p/256)===p){const t=this._device.createCommandEncoder({}),i=this._bufferManager.createRawBuffer(e.byteLength,sr.MapWrite|sr.CopySrc,!0),s=i.getMappedRange();new Uint8Array(s).set(e),i.unmap(),t.copyBufferToTexture({buffer:i,offset:0,bytesPerRow:p,rowsPerImage:n},m,g),this._device.queue.submit([t.finish()]),this._bufferManager.releaseBuffer(i)}else this._device.queue.writeTexture(m,e,{offset:0,bytesPerRow:p,rowsPerImage:n},g);if(l||h){if(!no._IsInternalTexture(t))throw"updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!";{const e=0===c&&0===u&&i===t.width&&n===t.height;this.invertYPreMultiplyAlpha(_,t.width,t.height,r,l,h,o,a,s||1,c,u,e?0:i,e?0:n,void 0,d)}}}else if(l)if(m.premultipliedAlpha=!1,no._IsInternalTexture(t)&&0===c&&0===u&&i===t.width&&n===t.height)this._device.queue.copyExternalImageToTexture({source:e},m,g),this.invertYPreMultiplyAlpha(_,i,n,r,l,h,o,a,s||1,0,0,0,0,void 0,d);else{const t=this._device.createCommandEncoder({}),c=this.createTexture({width:i,height:n,layers:1},!1,!1,!1,!1,!1,r,1,t,ar.CopySrc|ar.TextureBinding,void 0,"TempTextureForUpdateTexture");this._deferredReleaseTextures.push([c,null]),g.depthOrArrayLayers=1,this._device.queue.copyExternalImageToTexture({source:e},{texture:c},g),g.depthOrArrayLayers=s||1,this.invertYPreMultiplyAlpha(c,i,n,r,l,h,o,a,s||1,0,0,0,0,t,d),t.copyTextureToTexture({texture:c},m,g),this._device.queue.submit([t.finish()])}else this._device.queue.copyExternalImageToTexture({source:e},m,g)}readPixels(e,t,i,n,s,r,o=0,a=0,l=null,h=!1){const c=no._GetBlockInformationFromFormat(r),u=Math.ceil(n/c.width)*c.length,d=256*Math.ceil(u/256),p=d*s,f=this._bufferManager.createRawBuffer(p,sr.MapRead|sr.CopyDst),_=this._device.createCommandEncoder({});return _.copyTextureToBuffer({texture:e,mipLevel:a,origin:{x:t,y:i,z:Math.max(o,0)}},{buffer:f,offset:0,bytesPerRow:d},{width:n,height:s,depthOrArrayLayers:1}),this._device.queue.submit([_.finish()]),this._bufferManager.readDataFromBuffer(f,p,n,s,u,d,no._GetTextureTypeFromFormat(r),0,l,!0,h)}releaseTexture(e){if(no._IsInternalTexture(e)){const t=e._hardwareTexture,i=e._irradianceTexture;this._deferredReleaseTextures.push([t,i])}else this._deferredReleaseTextures.push([e,null])}destroyDeferredTextures(){for(let e=0;e<this._deferredReleaseTextures.length;++e){const[t,i]=this._deferredReleaseTextures[e];t&&(no._IsHardwareTexture(t)?t.release():t.destroy()),null==i||i.dispose()}this._deferredReleaseTextures.length=0}}class so extends Ke.h{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}var ro=i(806);class oo{static _IsGPUBuffer(e){return void 0===e.underlyingResource}constructor(e){this._deferredReleaseBuffers=[],this._device=e}createRawBuffer(e,t,i=!1){const n={mappedAtCreation:i,size:void 0!==e.byteLength?e.byteLength+3&-4:e+3&-4,usage:t};return this._device.createBuffer(n)}createBuffer(e,t){const i=void 0!==e.byteLength,n=this.createRawBuffer(e,t),s=new so(n);return s.references=1,s.capacity=i?e.byteLength:e,i&&this.setSubData(s,0,e),s}setRawData(e,t,i,n,s){this._device.queue.writeBuffer(e,t,i.buffer,n,s)}setSubData(e,t,i,n=0,s=0){const r=e.underlyingResource;s=s||i.byteLength,s=Math.min(s,e.capacity-t);let o=i.byteOffset+n,a=o+s;const l=s+3&-4;if(l!==s){const e=new Uint8Array(i.buffer.slice(o,a));(i=new Uint8Array(l)).set(e),n=0,o=0,a=l,s=l}const h=15728640;let c=0;for(;a-(o+c)>h;)this._device.queue.writeBuffer(r,t+c,i.buffer,o+c,h),c+=h;this._device.queue.writeBuffer(r,t+c,i.buffer,o+c,s-c)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const n=new Uint16Array(t);for(;e--;)i[e]=(0,ro.qZ)(n[e]);return i}readDataFromBuffer(e,t,i,n,s,r,o=0,a=0,l=null,h=!0,c=!1){const u=1===o?2:2===o?1:0;return new Promise(((i,d)=>{e.mapAsync(rr.Read,a,t).then((()=>{const d=e.getMappedRange(a,t);let p=l;if(c)p=null===p?(0,Us.A)(o,t,!0,d):(0,Us.A)(o,p.buffer,void 0,d);else if(null===p)switch(u){case 0:p=new Uint8Array(t),p.set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:p=new Float32Array(t/4),p.set(new Float32Array(d))}else switch(u){case 0:p=new Uint8Array(p.buffer),p.set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:p=new Float32Array(p.buffer),p.set(new Float32Array(d))}if(s!==r){1!==u||c||(s*=2,r*=2);const e=new Uint8Array(p.buffer);let t=s,i=0;for(let o=1;o<n;++o){i=o*r;for(let n=0;n<s;++n)e[t++]=e[i++]}p=0===u||c?new Uint8Array(e.buffer,0,t):new Float32Array(e.buffer,0,t/4)}e.unmap(),h&&this.releaseBuffer(e),i(p)}),(e=>d(e)))}))}releaseBuffer(e){return oo._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e<this._deferredReleaseBuffers.length;++e)this._deferredReleaseBuffers[e].destroy();this._deferredReleaseBuffers.length=0}}class ao{constructor(){this.colorAttachmentGPUTextures=[],this.reset()}reset(e=!1){this.renderPass=null,e&&(this.renderPassDescriptor=null,this.colorAttachmentViewDescriptor=null,this.depthAttachmentViewDescriptor=null,this.colorAttachmentGPUTextures=[],this.depthTextureFormat=void 0)}}const lo=[0,0,3,7,0,2,6,2,4,1,5,3,1],ho=[0,64,32,96,16,80,48,112,8],co=[0,128,128,0,0,0,0,128,0,0,0,0,128];class uo{constructor(e){this._samplers={},this._device=e,this.disabled=!1}static GetSamplerHashCode(e){var t,i,n;const s=e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1;return lo[e.samplingMode]+ho[(e._comparisonFunction||514)-512+1]+co[e.samplingMode]+((null!==(t=e._cachedWrapU)&&void 0!==t?t:1)<<8)+((null!==(i=e._cachedWrapV)&&void 0!==i?i:1)<<10)+((null!==(n=e._cachedWrapR)&&void 0!==n?n:1)<<12)+((e.useMipMaps?1:0)<<14)+(s<<15)}static _GetSamplerFilterDescriptor(e,t){let i,n,s,r,o;const a=e.useMipMaps;switch(e.samplingMode){case 11:i=dr.Linear,n=dr.Linear,s=dr.Nearest,a||(r=o=0);break;case 3:case 3:i=dr.Linear,n=dr.Linear,a?s=dr.Linear:(s=dr.Nearest,r=o=0);break;case 8:i=dr.Nearest,n=dr.Nearest,a?s=dr.Linear:(s=dr.Nearest,r=o=0);break;case 4:i=dr.Nearest,n=dr.Nearest,s=dr.Nearest,a||(r=o=0);break;case 5:i=dr.Nearest,n=dr.Linear,s=dr.Nearest,a||(r=o=0);break;case 6:i=dr.Nearest,n=dr.Linear,a?s=dr.Linear:(s=dr.Nearest,r=o=0);break;case 7:i=dr.Nearest,n=dr.Linear,s=dr.Nearest,r=o=0;break;case 1:case 1:default:i=dr.Nearest,n=dr.Nearest,s=dr.Nearest,r=o=0;break;case 9:i=dr.Linear,n=dr.Nearest,s=dr.Nearest,a||(r=o=0);break;case 10:i=dr.Linear,n=dr.Nearest,a?s=dr.Linear:(s=dr.Nearest,r=o=0);break;case 2:case 2:i=dr.Linear,n=dr.Linear,s=dr.Nearest,r=o=0;break;case 12:i=dr.Linear,n=dr.Nearest,s=dr.Nearest,r=o=0}return t>1&&(0!==r||0!==o)?{magFilter:dr.Linear,minFilter:dr.Linear,mipmapFilter:dr.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:n,mipmapFilter:s,lodMinClamp:r,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return ur.Repeat;case 0:return ur.ClampToEdge;case 2:return ur.MirrorRepeat}return ur.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e){const t=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,i=this._GetSamplerFilterDescriptor(e,t);return{...i,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?uo.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:i.anisotropyEnabled?t:1}}static GetCompareFunction(e){switch(e){case 519:return fr.Always;case 514:return fr.Equal;case 516:return fr.Greater;case 518:return fr.GreaterEqual;case 513:default:return fr.Less;case 515:return fr.LessEqual;case 512:return fr.Never;case 517:return fr.NotEqual}}getSampler(e,t=!1,i=0){if(this.disabled)return this._device.createSampler(uo._GetSamplerDescriptor(e));t?i=0:0===i&&(i=uo.GetSamplerHashCode(e));let n=t?void 0:this._samplers[i];return n||(n=this._device.createSampler(uo._GetSamplerDescriptor(e)),t||(this._samplers[i]=n)),n}}var po;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(po||(po={}));const fo={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},_o={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class mo{constructor(e,t,i){this.mrtTextureCount=0,this._device=e,this._useTextureStage=i,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=[cr.BGRA8Unorm],this.setColorFormat(cr.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(cr.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,n=0){if(i>1&&(i=4),this.disabled){const n=mo._GetTopology(e);return this._setVertexState(t),this._parameter.pipeline=this._createRenderPipeline(t,n,i),mo.NumCacheMiss++,mo._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(n),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,mo.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return mo.NumCacheHitWithHash++,this._parameter.pipeline;const s=mo._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),mo.NumCacheMiss++,mo._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){mo.NumPipelineCreationLastFrame=mo._NumPipelineCreationCurrentFrame,mo._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,n,s,r,o,a){this._depthWriteEnabled=o,this._depthTestEnabled=r,this._depthCompare=(null!=a?a:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(n),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[po.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[po.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=io[null!=e?e:""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i<e.length;++i)0!==e[i]&&(t+=1<<i);this._mrtEnabledMask!==t&&(this._mrtEnabledMask=t,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.MRTAttachments1))}setMRT(e,t){var i,n;if((t=null!=t?t:e.length)>10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const s=[0,0];let r=0,o=0,a=0;for(let l=0;l<t;++l){const t=e[l],h=null==t?void 0:t._hardwareTexture;this._mrtFormats[a]=null!==(i=null==h?void 0:h.format)&&void 0!==i?i:this._webgpuColorFormat[0],s[r]+=io[null!==(n=this._mrtFormats[a])&&void 0!==n?n:""]<<o,o+=6,a++,o>=32&&(o=0,r++)}this._mrtFormats.length=a,this._mrtAttachments1===s[0]&&this._mrtAttachments2===s[1]||(this._mrtAttachments1=s[0],this._mrtAttachments2=s[1],this._states[po.MRTAttachments1]=s[0],this._states[po.MRTAttachments2]=s[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.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=void 0===e?0:io[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(null!=e?e:519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(null!=e?e:519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:_o[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:_o[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:_o[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[po.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[po.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,n,s,r,o){this._stencilEnabled=e,this._stencilFrontCompare=(null!=t?t:519)-512,this._stencilFrontDepthFailOp=null===i?1:_o[i],this._stencilFrontPassOp=null===n?2:_o[n],this._stencilFrontFailOp=null===s?1:_o[s],this.setStencilReadMask(r),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return Sr.TriangleList;case 2:case 3:return Sr.PointList;case 1:case 4:return Sr.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return Sr.LineStrip;case 7:return Sr.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return Rr.Add;case 32778:return Rr.Subtract;case 32779:return Rr.ReverseSubtract;case 32775:return Rr.Min;case 32776:return Rr.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return Pr.Zero;case 1:default:return Pr.One;case 768:return Pr.Src;case 769:return Pr.OneMinusSrc;case 770:return Pr.SrcAlpha;case 771:return Pr.OneMinusSrcAlpha;case 772:return Pr.DstAlpha;case 773:return Pr.OneMinusDstAlpha;case 774:return Pr.Dst;case 775:return Pr.OneMinusDst;case 776:return Pr.SrcAlphaSaturated;case 32769:case 32771:return Pr.Constant;case 32770:case 32772:return Pr.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:return fr.Never;case 1:return fr.Less;case 2:return fr.Equal;case 3:return fr.LessEqual;case 4:return fr.Greater;case 5:return fr.NotEqual;case 6:return fr.GreaterEqual;case 7:return fr.Always}return fr.Never}static _GetStencilOpFunction(e){switch(e){case 0:return Mr.Zero;case 1:return Mr.Keep;case 2:return Mr.Replace;case 3:return Mr.IncrementClamp;case 4:return Mr.DecrementClamp;case 5:return Mr.Invert;case 6:return Mr.IncrementWrap;case 7:return Mr.DecrementWrap}return Mr.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,n=e.getSize();switch(t){case qe.o.BYTE:switch(n){case 1:case 2:return i?Dr.Snorm8x2:Dr.Sint8x2;case 3:case 4:return i?Dr.Snorm8x4:Dr.Sint8x4}break;case qe.o.UNSIGNED_BYTE:switch(n){case 1:case 2:return i?Dr.Unorm8x2:Dr.Uint8x2;case 3:case 4:return i?Dr.Unorm8x4:Dr.Uint8x4}break;case qe.o.SHORT:switch(n){case 1:case 2:return i?Dr.Snorm16x2:Dr.Sint16x2;case 3:case 4:return i?Dr.Snorm16x4:Dr.Sint16x4}break;case qe.o.UNSIGNED_SHORT:switch(n){case 1:case 2:return i?Dr.Unorm16x2:Dr.Uint16x2;case 3:case 4:return i?Dr.Unorm16x4:Dr.Uint16x4}break;case qe.o.INT:switch(n){case 1:return Dr.Sint32;case 2:return Dr.Sint32x2;case 3:return Dr.Sint32x3;case 4:return Dr.Sint32x4}break;case qe.o.UNSIGNED_INT:switch(n){case 1:return Dr.Uint32;case 2:return Dr.Uint32x2;case 3:return Dr.Uint32x3;case 4:return Dr.Uint32x4}break;case qe.o.FLOAT:switch(n){case 1:return Dr.Float32;case 2:return Dr.Float32x2;case 3:return Dr.Float32x3;case 4:return Dr.Float32x4}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${n}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:mo._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:mo._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:mo._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:mo._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:mo._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:mo._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[po.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[po.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=((null===this._alphaBlendFuncParams[0]?2:fo[this._alphaBlendFuncParams[0]])<<0)+((null===this._alphaBlendFuncParams[1]?2:fo[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:fo[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:fo[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[po.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.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[po.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.DepthStencilState))}_setVertexState(e){var t,i;const n=this._statesLength;let s=po.VertexState;const r=e._pipelineContext,o=r.shaderProcessingContext.attributeNamesFromEffect,a=r.shaderProcessingContext.attributeLocationsFromEffect;let l,h=0;for(let e=0;e<o.length;e++){const n=a[e];let r=null!==(t=this._overrideVertexBuffers&&this._overrideVertexBuffers[o[e]])&&void 0!==t?t:this._vertexBuffers[o[e]];r||(r=this._emptyVertexBuffer);const c=null===(i=r.getBuffer())||void 0===i?void 0:i.underlyingResource;if(void 0===r._validOffsetRange){const e=r.byteOffset,t=r.getSize(!0),i=r.byteStride;r._validOffsetRange=e<=this._kMaxVertexBufferStride-t&&(0===i||e+t<=i)}l&&l===c&&r._validOffsetRange||(this.vertexBuffers[h++]=r,l=r._validOffsetRange?c:null);const u=r.hashCode+(n<<7);this._isDirty=this._isDirty||this._states[s]!==u,this._states[s++]=u}this.vertexBuffers.length=h,this._statesLength=s,this._isDirty=this._isDirty||s!==n,this._isDirty&&(this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.VertexState))}_setTextureState(e){this._textureState!==e&&(this._textureState=e,this._states[po.TextureStage]=this._textureState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,po.TextureStage))}_createPipelineLayout(e){if(this._useTextureStage)return this._createPipelineLayoutWithTextureStage(e);const t=[],i=e.shaderProcessingContext.bindGroupLayoutEntries;for(let e=0;e<i.length;e++){const n=i[e];t[e]=this._device.createBindGroupLayout({entries:n})}return e.bindGroupLayouts=t,this._device.createPipelineLayout({bindGroupLayouts:t})}_createPipelineLayoutWithTextureStage(e){var t;const i=e.shaderProcessingContext,n=i.bindGroupLayoutEntries;let s=1;for(let e=0;e<n.length;e++){const r=n[e];for(let o=0;o<r.length;o++){const r=n[e][o];if(r.texture){const o=i.bindGroupLayoutEntryInfo[e][r.binding].name,a=i.availableTextures[o],l=a.autoBindSampler?i.availableSamplers[o+zr.AutoSamplerSuffix]:null;let h=a.sampleType,c=null!==(t=null==l?void 0:l.type)&&void 0!==t?t:gr.Filtering;if(this._textureState&s&&h!==vr.Depth&&(a.autoBindSampler&&(c=gr.NonFiltering),h=vr.UnfilterableFloat),r.texture.sampleType=h,l){const e=i.bindGroupLayoutEntryInfo[l.binding.groupIndex][l.binding.bindingIndex].index;n[l.binding.groupIndex][e].sampler.type=c}s<<=1}}}const r=[];for(let e=0;e<n.length;++e)r[e]=this._device.createBindGroupLayout({entries:n[e]});return e.bindGroupLayouts=r,this._device.createPipelineLayout({bindGroupLayouts:r})}_getVertexInputDescriptor(e){var t,i;const n=[],s=e._pipelineContext,r=s.shaderProcessingContext.attributeNamesFromEffect,o=s.shaderProcessingContext.attributeLocationsFromEffect;let a,l;for(let e=0;e<r.length;e++){const s=o[e];let h=null!==(t=this._overrideVertexBuffers&&this._overrideVertexBuffers[r[e]])&&void 0!==t?t:this._vertexBuffers[r[e]];h||(h=this._emptyVertexBuffer);let c=null===(i=h.getBuffer())||void 0===i?void 0:i.underlyingResource,u=h.byteOffset;const d=!h._validOffsetRange;if(!a||!l||a!==c||d){const e={arrayStride:h.byteStride,stepMode:h.getIsInstanced()?Or.Instance:Or.Vertex,attributes:[]};n.push(e),l=e.attributes,d&&(u=0,c=null)}l.push({shaderLocation:s,offset:u,format:mo._GetVertexInputDescriptorFormat(h)}),a=c}return n}_createRenderPipeline(e,t,i){var n,s,r;const o=e._pipelineContext,a=this._getVertexInputDescriptor(e),l=this._createPipelineLayout(o),h=[],c=this._getAphaBlendState(),u=this._getColorBlendState();if(this._mrtAttachments1>0)for(let e=0;e<this._mrtFormats.length;++e){const t=this._mrtFormats[e];if(t){const i={format:t,writeMask:0!=(this._mrtEnabledMask&1<<e)?this._writeMask:0};c&&u&&(i.blend={alpha:c,color:u}),h.push(i)}else h.push(null)}else if(this._webgpuColorFormat[0]){const e={format:this._webgpuColorFormat[0],writeMask:this._writeMask};c&&u&&(e.blend={alpha:c,color:u}),h.push(e)}else h.push(null);const d={compare:mo._GetCompareFunction(this._stencilEnabled?this._stencilFrontCompare:7),depthFailOp:mo._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontDepthFailOp:1),failOp:mo._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontFailOp:1),passOp:mo._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontPassOp:1)};let p;t!==Sr.LineStrip&&t!==Sr.TriangleStrip||(p=!this._indexBuffer||this._indexBuffer.is32Bits?Ir.Uint32:Ir.Uint16);const f=!!this._webgpuDepthStencilFormat&&no.HasStencilAspect(this._webgpuDepthStencilFormat);return this._device.createRenderPipeline({label:`RenderPipeline_${null!==(s=null===(n=h[0])||void 0===n?void 0:n.format)&&void 0!==s?s:"nooutput"}_${null!==(r=this._webgpuDepthStencilFormat)&&void 0!==r?r:"nodepth"}_samples${i}`,layout:l,vertex:{module:o.stages.vertexStage.module,entryPoint:o.stages.vertexStage.entryPoint,buffers:a},primitive:{topology:t,stripIndexFormat:p,frontFace:1===this._frontFace?Er.CCW:Er.CW,cullMode:this._cullEnabled?2===this._cullFace?Cr.Front:Cr.Back:Cr.None},fragment:o.stages.fragmentStage?{module:o.stages.fragmentStage.module,entryPoint:o.stages.fragmentStage.entryPoint,targets:h}:void 0,multisample:{count:i},depthStencil:void 0===this._webgpuDepthStencilFormat?void 0:{depthWriteEnabled:this._depthWriteEnabled,depthCompare:this._depthTestEnabled?mo._GetCompareFunction(this._depthCompare):fr.Always,format:this._webgpuDepthStencilFormat,stencilFront:this._stencilEnabled&&f?d:void 0,stencilBack:this._stencilEnabled&&f?d:void 0,stencilReadMask:this._stencilEnabled&&f?this._stencilReadMask:void 0,stencilWriteMask:this._stencilEnabled&&f?this._stencilWriteMask:void 0,depthBias:this._depthBias,depthBiasClamp:this._depthBiasClamp,depthBiasSlopeScale:this._depthBiasSlopeScale}})}}mo.NumCacheHitWithoutHash=0,mo.NumCacheHitWithHash=0,mo.NumCacheMiss=0,mo.NumPipelineCreationLastFrame=0,mo._NumPipelineCreationCurrentFrame=0;class go{constructor(){this.values={}}count(){let e=0,t=this.pipeline?1:0;for(const i in this.values){const n=this.values[i],[s,r]=n.count();e+=s,t+=r,e++}return[e,t]}}class vo extends mo{static GetNodeCounts(){const e=vo._Cache.count();return{nodeCount:e[0],pipelineCount:e[1]}}static _GetPipelines(e,t,i,n){if(e.pipeline){const e=i.slice();e.length=n,t.push(e)}for(const s in e.values){const r=e.values[s];i[n]=parseInt(s),vo._GetPipelines(r,t,i,n+1)}}static GetPipelines(){const e=[];return vo._GetPipelines(vo._Cache,e,[],0),e}constructor(e,t,i){super(e,t,i),this._nodeStack=[],this._nodeStack[0]=vo._Cache}_getRenderPipeline(e){let t=this._nodeStack[this._stateDirtyLowestIndex];for(let e=this._stateDirtyLowestIndex;e<this._statesLength;++e){let i=t.values[this._states[e]];i||(i=new go,t.values[this._states[e]]=i),t=i,this._nodeStack[e+1]=t}e.token=t,e.pipeline=t.pipeline}_setRenderPipeline(e){e.token.pipeline=e.pipeline}}vo._Cache=new go;var yo=i(9468);class xo extends yo.C{constructor(e){super(!1),this._cache=e,this.reset()}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._cache.setStencilCompare(e))}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._cache.setStencilReadMask(e))}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._cache.setStencilFailOp(e))}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._cache.setStencilDepthFailOp(e))}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._cache.setStencilPassOp(e))}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._cache.setStencilWriteMask(e))}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._cache.setStencilEnabled(e))}reset(){super.reset(),this._cache.resetStencilState()}apply(){var e;const t=null===(e=this.stencilMaterial)||void 0===e?void 0:e.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.enabled&&(this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask)}}var bo=i(6533);class To extends bo.k{constructor(e){super(!1),this._cache=e,this.reset()}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0,this._cache.setDepthBiasSlopeScale(e))}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0,this._cache.setDepthBias(e))}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0,this._cache.setCullFace(null!=e?e:1))}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0,this._cache.setCullEnabled(!!e))}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0,this._cache.setDepthCompare(e))}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0,this._cache.setDepthWriteEnabled(e))}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0,this._cache.setDepthTestEnabled(e))}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0,this._cache.setFrontFace(null!=e?e:2))}reset(){super.reset(),this._cache.resetDepthCullingState()}apply(){}}class So{static IsExternalTexture(e){return void 0!==e.underlyingResource}getClassName(){return"ExternalTexture"}get underlyingResource(){return this._video}constructor(e){this.useMipMaps=!1,this.type=16,this._video=e,this.uniqueId=Ei.l._Counter++}isReady(){return this._video.readyState>=this._video.HAVE_CURRENT_DATA}dispose(){}}class Eo{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatTextures(){return this._numFloatTextures>0}constructor(){this.uniqueId=Eo._Counter++,this.updateId=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],n=-1;i?n=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?uo.GetSamplerHashCode(t):0;const s=n!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var i,n,s;let r=this.textures[e],o=-1;r?o=null!==(n=null===(i=r.texture)||void 0===i?void 0:i.uniqueId)&&void 0!==n?n:-1:this.textures[e]=r={texture:t,isFloatTexture:!1,isExternalTexture:!1},r.isExternalTexture&&this._numExternalTextures--,r.isFloatTexture&&this._numFloatTextures--,t?(r.isFloatTexture=1===t.type,r.isExternalTexture=So.IsExternalTexture(t),r.isFloatTexture&&this._numFloatTextures++,r.isExternalTexture&&this._numExternalTextures++):(r.isFloatTexture=!1,r.isExternalTexture=!1),r.texture=t;const a=o!==(null!==(s=null==t?void 0:t.uniqueId)&&void 0!==s?s:-1);a&&this.updateId++,this.isDirty||(this.isDirty=a)}}Eo._Counter=0;class Co{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(40,sr.CopyDst|sr.Indirect),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=Co._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=(null==t?void 0:t.uniqueId)!==(null===(i=this.buffers[e])||void 0===i?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}}Co._Counter=0;class Ao{constructor(){this.values={}}}class Po{static get Statistics(){return{totalCreated:Po.NumBindGroupsCreatedTotal,lastFrameCreated:Po.NumBindGroupsCreatedLastFrame,lookupLastFrame:Po.NumBindGroupsLookupLastFrame,noLookupLastFrame:Po.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Po.NumBindGroupsCreatedLastFrame=Po._NumBindGroupsCreatedCurrentFrame,Po.NumBindGroupsLookupLastFrame=Po._NumBindGroupsLookupCurrentFrame,Po.NumBindGroupsNoLookupLastFrame=Po._NumBindGroupsNoLookupCurrentFrame,Po._NumBindGroupsCreatedCurrentFrame=0,Po._NumBindGroupsLookupCurrentFrame=0,Po._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var n,s,r,o,a,l,h,c,u,d;let p,f=Po._Cache;const m=this.disabled||i.forceBindGroupCreation;if(!m){if(!t.isDirty(i.updateId)&&!i.isDirty)return Po._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const i of e.shaderProcessingContext.bufferNames){const e=null!==(s=null===(n=t.buffers[i])||void 0===n?void 0:n.uniqueId)&&void 0!==s?s:0;let r=f.values[e];r||(r=new Ao,f.values[e]=r),f=r}for(const t of e.shaderProcessingContext.samplerNames){const e=null!==(o=null===(r=i.samplers[t])||void 0===r?void 0:r.hashCode)&&void 0!==o?o:0;let n=f.values[e];n||(n=new Ao,f.values[e]=n),f=n}for(const t of e.shaderProcessingContext.textureNames){const e=null!==(h=null===(l=null===(a=i.textures[t])||void 0===a?void 0:a.texture)||void 0===l?void 0:l.uniqueId)&&void 0!==h?h:0;let n=f.values[e];n||(n=new Ao,f.values[e]=n),f=n}p=f.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,p)return t.bindGroups=p,Po._NumBindGroupsLookupCurrentFrame++,p;p=[],t.bindGroups=p,m||(f.bindGroups=p),Po.NumBindGroupsCreatedTotal++,Po._NumBindGroupsCreatedCurrentFrame++;const g=e.bindGroupLayouts;for(let n=0;n<e.shaderProcessingContext.bindGroupLayoutEntries.length;n++){const s=e.shaderProcessingContext.bindGroupLayoutEntries[n],r=e.shaderProcessingContext.bindGroupEntries[n];for(let o=0;o<s.length;o++){const s=e.shaderProcessingContext.bindGroupLayoutEntries[n][o],a=e.shaderProcessingContext.bindGroupLayoutEntryInfo[n][s.binding],l=null!==(c=a.nameInArrayOfTexture)&&void 0!==c?c:a.name;if(s.sampler){const e=i.samplers[l];if(e){const t=e.sampler;if(!t){this._engine.dbgSanityChecks&&_.Y.Error(`Trying to bind a null sampler! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"<no dump>":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}r[o].resource=this._cacheSampler.getSampler(t,!1,e.hashCode)}else _.Y.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"<no dump>":t))}`,50)}else if(s.texture||s.storageTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){_.Y.Error(`Trying to bind a null texture! entry=${JSON.stringify(s)}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"<no dump>":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||s.texture&&!t.view||s.storageTexture&&!t.viewForWriting)){_.Y.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"<no dump>":t))}, isReady=${null===(u=e.texture)||void 0===u?void 0:u.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}r[o].resource=s.storageTexture?t.viewForWriting:t.view}else _.Y.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"<no dump>":t))}`,50)}else if(s.externalTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){_.Y.Error(`Trying to bind a null external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"<no dump>":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){_.Y.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"<no dump>":t))}, isReady=${null===(d=e.texture)||void 0===d?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}r[o].resource=this._device.importExternalTexture({source:t})}else _.Y.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"<no dump>":t))}`,50)}else if(s.buffer){const e=t.buffers[l];if(e){const t=e.underlyingResource;r[o].resource.buffer=t,r[o].resource.size=e.capacity}else _.Y.Error(`Can't find buffer "${l}". entry=${JSON.stringify(s)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const o=g[n];p[n]=this._device.createBindGroup({layout:o,entries:r})}return p}}Po.NumBindGroupsCreatedTotal=0,Po.NumBindGroupsCreatedLastFrame=0,Po.NumBindGroupsLookupLastFrame=0,Po.NumBindGroupsNoLookupLastFrame=0,Po._Cache=new Ao,Po._NumBindGroupsCreatedCurrentFrame=0,Po._NumBindGroupsLookupCurrentFrame=0,Po._NumBindGroupsNoLookupCurrentFrame=0;si.v.ShadersStore.clearQuadVertexShader="uniform float depthValue;\nconst vec2 pos[4]={\nvec2(-1.0,1.0),\nvec2(1.0,1.0),\nvec2(-1.0,-1.0),\nvec2(1.0,-1.0)\n};\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=vec4(pos[gl_VertexID],depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";si.v.ShadersStore.clearQuadPixelShader="uniform vec4 color;\nvoid main() {\ngl_FragColor=color;\n}\n";class Ro{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 vo(this._device,i,!t._caps.textureFloatLinearFiltering),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"])}clear(e,t,i,n,s=1){var r,o;let a,l,h=null;const c=!!this._engine._currentRenderTarget;if(e)a=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t<this._cacheRenderPipeline.colorFormats.length;++t)this._keyTemp[e++]=io[null!==(r=this._cacheRenderPipeline.colorFormats[t])&&void 0!==r?r:""];const u=io[null!==(o=this._depthTextureFormat)&&void 0!==o?o:0];if(this._keyTemp[e]=(t?t.r+256*t.g+256*t.b*256+256*t.a*256*256:0)+(i?2**32:0)+(n?2**33:0)+(this._engine.useReverseDepthBuffer?2**34:0)+(c?2**35:0)+(s>1?2**36:0)+u*2**37,l=this._keyTemp.join("_"),h=this._bundleCache[l],h)return h;a=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:s})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!n&&!!this._depthTextureFormat&&no.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(n?255:0),this._cacheRenderPipeline.setStencilCompare(n?519:512),this._cacheRenderPipeline.setStencilPassOp(n?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const u=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),d=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),d.uniformBuffer.update();const p=c?this._engine._ubInvertY:this._engine._ubDontInvertY,f=d.uniformBuffer.getBuffer(),_=f.uniqueId+"-"+p.uniqueId;let m=this._bindGroups[_];if(!m){const e=d.bindGroupLayouts;m=this._bindGroups[_]=[],m.push(this._device.createBindGroup({layout:e[0],entries:[]})),Xr._SimplifiedKnownBindings||m.push(this._device.createBindGroup({layout:e[1],entries:[]})),m.push(this._device.createBindGroup({layout:e[Xr._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:p.underlyingResource,size:p.capacity}},{binding:1,resource:{buffer:f.underlyingResource,size:f.capacity}}]}))}a.setPipeline(u);for(let e=0;e<m.length;++e)a.setBindGroup(e,m[e]);return a.draw(4,1,0,0),e||(h=a.finish(),this._bundleCache[l]=h),h}}class Mo{constructor(e,t,i,n){this.x=Math.floor(e),this.y=Math.floor(t),this.w=Math.floor(i),this.h=Math.floor(n)}run(e){e.setViewport(this.x,this.y,this.w,this.h,0,1)}clone(){return new Mo(this.x,this.y,this.w,this.h)}}class Io{constructor(e,t,i,n){this.x=e,this.y=t,this.w=i,this.h=n}run(e){e.setScissorRect(this.x,this.y,this.w,this.h)}clone(){return new Io(this.x,this.y,this.w,this.h)}}class Do{constructor(e){this.ref=e}run(e){e.setStencilReference(this.ref)}clone(){return new Do(this.ref)}}class Oo{constructor(e){this.color=e}run(e){e.setBlendConstant(this.color)}clone(){return new Oo(this.color)}}class wo{constructor(e){this.query=e}run(e){e.beginOcclusionQuery(this.query)}clone(){return new wo(this.query)}}class No{constructor(){}run(e){e.endOcclusionQuery()}clone(){return new No}}class Fo{constructor(){this.bundles=[]}run(e){e.executeBundles(this.bundles)}clone(){const e=new Fo;return e.bundles=this.bundles,e}}class Lo{constructor(e){this.numDrawCalls=0,this._device=e,this._list=new Array(10),this._listLength=0}addBundle(e){if(!this._currentItemIsBundle){const e=new Fo;this._list[this._listLength++]=e,this._currentBundleList=e.bundles,this._currentItemIsBundle=!0}e&&this._currentBundleList.push(e)}_finishBundle(){this._currentItemIsBundle&&this._bundleEncoder&&(this._currentBundleList.push(this._bundleEncoder.finish()),this._bundleEncoder=void 0,this._currentItemIsBundle=!1)}addItem(e){this._finishBundle(),this._list[this._listLength++]=e,this._currentItemIsBundle=!1}getBundleEncoder(e,t,i){return this._currentItemIsBundle||(this.addBundle(),this._bundleEncoder=this._device.createRenderBundleEncoder({colorFormats:e,depthStencilFormat:t,sampleCount:i})),this._bundleEncoder}close(){this._finishBundle()}run(e){this.close();for(let t=0;t<this._listLength;++t)this._list[t].run(e)}reset(){this._listLength=0,this._currentItemIsBundle=!1,this.numDrawCalls=0}clone(){this.close();const e=new Lo(this._device);e._list=new Array(this._listLength),e._listLength=this._listLength,e.numDrawCalls=this.numDrawCalls;for(let t=0;t<this._listLength;++t)e._list[t]=this._list[t].clone();return e}}class Bo{get querySet(){return this._querySet}constructor(e,t,i,n,s=!0){this._dstBuffers=[],this._device=i,this._bufferManager=n,this._count=e,this._canUseMultipleBuffers=s,this._querySet=i.createQuerySet({type:t,count:e}),this._queryBuffer=n.createRawBuffer(8*e,sr.QueryResolve|sr.CopySrc),s||this._dstBuffers.push(this._bufferManager.createRawBuffer(8*this._count,sr.MapRead|sr.CopyDst))}_getBuffer(e,t){if(!this._canUseMultipleBuffers&&0===this._dstBuffers.length)return null;const i=this._device.createCommandEncoder();let n;return 0===this._dstBuffers.length?n=this._bufferManager.createRawBuffer(8*this._count,sr.MapRead|sr.CopyDst):(n=this._dstBuffers[this._dstBuffers.length-1],this._dstBuffers.length--),i.resolveQuerySet(this._querySet,e,t,this._queryBuffer,0),i.copyBufferToBuffer(this._queryBuffer,0,n,0,8*t),this._device.queue.submit([i.finish()]),n}async readValues(e=0,t=1){const i=this._getBuffer(e,t);if(null===i)return null;await i.mapAsync(rr.Read);const n=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,n}async readValue(e=0){const t=this._getBuffer(e,1);if(null===t)return null;await t.mapAsync(rr.Read);const i=new BigUint64Array(t.getMappedRange()),n=Number(i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,n}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(null===t)return null;await t.mapAsync(rr.Read);const i=new BigUint64Array(t.getMappedRange()),n=Number(i[1]-i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,n}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e<this._dstBuffers.length;++e)this._bufferManager.releaseBuffer(this._dstBuffers[e])}}class Uo{get gpuFrameTimeCounter(){return this._gpuFrameTimeCounter}constructor(e,t){this._enabled=!1,this._gpuFrameTimeCounter=new Os.z,this._measureDurationState=0,this._device=e,this._bufferManager=t}get enable(){return this._enabled}set enable(e){this._enabled!==e&&(this._enabled=e,this._measureDurationState=0,e?this._measureDuration=new Vo(this._device,this._bufferManager):this._measureDuration.dispose())}startFrame(e){this._enabled&&0===this._measureDurationState&&(this._measureDuration.start(e),this._measureDurationState=1)}endFrame(e){1===this._measureDurationState&&(this._measureDurationState=2,this._measureDuration.stop(e).then((e=>{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0})))}}class Vo{constructor(e,t){this._querySet=new Bo(2,Br.Timestamp,e,t)}start(e){e.writeTimestamp(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp(this._querySet.querySet,1),this._querySet.readTwoValuesAndSubtract(0)}dispose(){this._querySet.dispose()}}class ko{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}get canBeginQuery(){switch(this._engine._getCurrentRenderPassIndex()){case 0:return void 0!==this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet;case 1:return void 0!==this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet}return!1}constructor(e,t,i,n=50,s=100){this._availableIndices=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(n)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length-1]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e<this._lastBuffer.length}getQueryResult(e){var t,i;return Number(null!==(i=null===(t=this._lastBuffer)||void 0===t?void 0:t[e])&&void 0!==i?i:-1)}_retrieveQueryBuffer(){this._lastBuffer&&this._frameLastBuffer===this._engine.frameId||this._frameLastBuffer!==this._engine.frameId&&(this._frameLastBuffer=this._engine.frameId,this._querySet.readValues(0,this._currentTotalIndices).then((e=>{this._lastBuffer=e})))}_allocateNewIndices(e){e=null!=e?e:this._countIncrement,this._delayQuerySetDispose();for(let t=0;t<e;++t)this._availableIndices.push(this._currentTotalIndices+t);this._currentTotalIndices+=e,this._querySet=new Bo(this._currentTotalIndices,Br.Occlusion,this._device,this._bufferManager,!1)}_delayQuerySetDispose(){const e=this._querySet;e&&setTimeout((()=>e.dispose),1e3)}dispose(){var e;null===(e=this._querySet)||void 0===e||e.dispose(),this._availableIndices.length=0}}class Go{async initTwgsl(e){if(!Go._twgsl)return e=e||{},(e={...Go._TWgslDefaultOptions,...e}).twgsl?(Go._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&((0,fe.CG)()?await de.w1.LoadScriptAsync(e.jsPath):importScripts(e.jsPath)),self.twgsl?(Go._twgsl=await self.twgsl(e.wasmPath),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=Go._twgsl.convertSpirV2WGSL(e);return Go.ShowWGSLShaderCode&&(console.log(i),console.log("***********************************************")),Go.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}Go._TWgslDefaultOptions={jsPath:"https://preview.babylonjs.com/twgsl/twgsl.js",wasmPath:"https://preview.babylonjs.com/twgsl/twgsl.wasm"},Go.ShowWGSLShaderCode=!1,Go.DisableUniformityAnalysis=!1,Go._twgsl=null;class zo{constructor(e,t,i,n){this._record=!1,this._play=!1,this._mainPassBundleList=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i,this._bundleListRenderTarget=n}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._mainPassBundleList.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}endMainRenderPass(){this._record&&this._mainPassBundleList.push(this._bundleList.clone())}endRenderTargetPass(e,t){var i,n,s,r;if(this._play)null===(n=null===(i=t._bundleLists)||void 0===i?void 0:i[t._currentLayer])||void 0===n||n.run(e),1===this._mode&&this._engine._reportDrawCall(null===(r=null===(s=t._bundleLists)||void 0===s?void 0:s[t._currentLayer])||void 0===r?void 0:r.numDrawCalls);else{if(!this._record)return!1;t._bundleLists||(t._bundleLists=[]),t._bundleLists[t._currentLayer]=this._bundleListRenderTarget.clone(),t._bundleLists[t._currentLayer].run(e),this._bundleListRenderTarget.reset()}return!0}endFrame(e){if(this._record&&(this._mainPassBundleList.push(this._bundleList.clone()),this._record=!1,this._play=!0,this._mode=this._modeSaved),null!==e&&this._play)for(let t=0;t<this._mainPassBundleList.length;++t)this._mainPassBundleList[t].run(e),1===this._mode&&this._engine._reportDrawCall(this._mainPassBundleList[t].numDrawCalls)}reset(){this.enabled=!1,this.enabled=!0}}const Wo={label:"TextureView_SwapChain_ResolveTarget",dimension:or.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Ho={label:"TextureView_SwapChain",dimension:or.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Xo="/* disable_uniformity_analysis */";class jo extends ue.D{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}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}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 _.Y.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 currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new jo(e,t);return new Promise((e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then((()=>e(i)))}))}constructor(e,t={}){var i,n;super(null,null===(i=t.antialias)||void 0===i||i,t),this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._renderTargetEncoderDescriptor={label:"renderTarget"},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._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,null],this._currentRenderPass=null,this._mainRenderPassWrapper=new ao,this._rttRenderPassWrapper=new ao,this._pendingDebugCommands=[],this._onAfterUnbindFrameBufferObservable=new r.y$,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},{x:0,y:0,w:0,h:0}],this._scissorsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=[-1,-1],this._blendColorsCurrent=[[null,null,null,null],[null,null,null,null]],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=null!==(n=t.enableGPUDebugMarkers)&&void 0!==n&&n,_.Y.Log(`Babylon.js v${ue.D.Version} - ${this.description} engine`),navigator.gpu?(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 jr,this._shaderProcessorWGSL=new Kr):_.Y.Error("WebGPU is not supported by your browser.")}initAsync(e,t){var i;return this._initGlslang(null!=e?e:null===(i=this._options)||void 0===i?void 0:i.glslangOptions).then((e=>{var i;return this._glslang=e,this._tintWASM=jo.UseTWGSL?new Go:null,this._tintWASM?this._tintWASM.initTwgsl(null!=t?t:null===(i=this._options)||void 0===i?void 0:i.twgslOptions).then((()=>navigator.gpu.requestAdapter(this._options)),(e=>{throw _.Y.Error("Can not initialize twgsl!"),_.Y.Error(e),Error("WebGPU initializations stopped.")})):navigator.gpu.requestAdapter(this._options)}),(e=>{throw _.Y.Error("Can not initialize glslang!"),_.Y.Error(e),Error("WebGPU initializations stopped.")})).then((e=>{var t,i,n;if(e){this._adapter=e,this._adapterSupportedExtensions=[],null===(t=this._adapter.features)||void 0===t||t.forEach((e=>this._adapterSupportedExtensions.push(e))),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then((e=>{this._adapterInfo=e}));const s=null!==(i=this._options.deviceDescriptor)&&void 0!==i?i:{},r=null!==(n=null==s?void 0:s.requiredFeatures)&&void 0!==n?n:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(r){const e=r,t=[];for(const i of e)-1!==this._adapterSupportedExtensions.indexOf(i)&&t.push(i);s.requiredFeatures=t}if(this._options.setMaximumLimits&&!s.requiredLimits){s.requiredLimits={};for(const e in this._adapterSupportedLimits)s.requiredLimits[e]=this._adapterSupportedLimits[e]}return this._adapter.requestDevice(s)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((e=>{var t,i;this._device=e,this._deviceEnabledExtensions=[],null===(t=this._device.features)||void 0===t||t.forEach((e=>this._deviceEnabledExtensions.push(e))),this._deviceLimits=e.limits;let n=-1;this._device.addEventListener("uncapturederror",(e=>{++n<this.numMaxUncapturedErrors?_.Y.Warn(`WebGPU uncaptured error (${n+1}): ${e.error} - ${e.error.message}`):n++===this.numMaxUncapturedErrors&&_.Y.Warn(`WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`)})),this._doNotHandleContextLost||null===(i=this._device.lost)||void 0===i||i.then((e=>{this._isDisposed||(this._contextWasLost=!0,_.Y.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(this.initAsync.bind(this)))}))}),(e=>{_.Y.Error("Could not retrieve a WebGPU device."),_.Y.Error(e)})).then((()=>{this._bufferManager=new oo(this._device),this._textureHelper=new no(this._device,this._glslang,this._tintWASM,this._bufferManager),this._cacheSampler=new uo(this._device),this._cacheBindGroups=new Po(this._device,this._cacheSampler,this),this._timestampQuery=new Uo(this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new ko(this,this._device,this._bufferManager):void 0,this._bundleList=new Lo(this._device),this._bundleListRenderTarget=new Lo(this._device),this._snapshotRendering=new zo(this,this._snapshotRenderingMode,this._bundleList,this._bundleListRenderTarget),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),sr.Uniform|sr.CopyDst),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),sr.Uniform|sr.CopyDst),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,console.log("%c frame #"+this._count+" - begin","background: #ffff00")),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._renderTargetEncoder=this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),this._emptyVertexBuffer=new qe.o(this,[0],"",!1,!1,1,!1,0,1),this._initializeLimits(),this._cacheRenderPipeline=new vo(this._device,this._emptyVertexBuffer,!this._caps.textureFloatLinearFiltering),this._depthCullingState=new To(this._cacheRenderPipeline),this._stencilStateComposer=new xo(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 Ro(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((e=>{_.Y.Error("Can not create WebGPU Device and/or context."),_.Y.Error(e),console.trace&&console.trace()}))}_initGlslang(e){return e=e||{},(e={...jo._GLSLslangDefaultOptions,...e}).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?(0,fe.CG)()?de.w1.LoadScriptAsync(e.jsPath).then((()=>self.glslang(e.wasmPath))):(importScripts(e.jsPath),self.glslang(e.wasmPath)):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,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(ir.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(ir.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(ir.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(ir.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(ir.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(ir.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,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,_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 $r],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(!1),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:or.E2d,format:this._options.swapChainFormat,usage:ar.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:or.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new Gr.HE(0,0,0,1),loadOp:Fr.Clear,storeOp:Lr.Store}]}else t=[{view:void 0,clearValue:new Gr.HE(0,0,0,1),loadOp:Fr.Clear,storeOp:Lr.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?cr.Depth24PlusStencil8:cr.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:or.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:ar.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const n={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:or.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Fr.Clear,depthStoreOp:Lr.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Fr.Clear:void 0,stencilStoreOp:this.isStencilEnable?Lr.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={colorAttachments:t,depthStencilAttachment:n}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:ar.RenderAttachment|ar.CopySrc,alphaMode:this.premultipliedAlpha?Ur.Premultiplied:Ur.Opaque})}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - setSize called -",e,t)),this._initializeMainAttachments(),this.snapshotRendering&&this.snapshotRenderingReset(),!0)}_getShaderProcessor(e){return e===Cn.x.WGSL?this._shaderProcessorWGSL:this._shaderProcessor}_getShaderProcessingContext(e){return new Xr(e)}applyStates(){this._stencilStateComposer.apply(),this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend)}wipeCaches(e){this.preventCacheWipeBetweenFrames&&!e||(this._forceEnableEffect=!0,this._currentIndexBuffer=null,this._currentOverrideVertexBuffers=null,this._cacheRenderPipeline.setBuffers(null,null,null),e&&(this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=515,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters),this._cacheRenderPipeline.setAlphaBlendEnabled(!1),this.setColorWrite(!0)),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}setColorWrite(e){this._colorWriteLocal=e,this._cacheRenderPipeline.setWriteMask(e?15:0)}getColorWrite(){return this._colorWriteLocal}_resetCurrentViewport(e){this._viewportsCurrent[e].x=0,this._viewportsCurrent[e].y=0,this._viewportsCurrent[e].w=0,this._viewportsCurrent[e].h=0}_mustUpdateViewport(e){const t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._viewportCached.x,n=this._viewportCached.y,s=this._viewportCached.z,r=this._viewportCached.w,o=this._viewportsCurrent[t].x!==i||this._viewportsCurrent[t].y!==n||this._viewportsCurrent[t].w!==s||this._viewportsCurrent[t].h!==r;return o&&(this._viewportsCurrent[t].x=this._viewportCached.x,this._viewportsCurrent[t].y=this._viewportCached.y,this._viewportsCurrent[t].w=this._viewportCached.z,this._viewportsCurrent[t].h=this._viewportCached.w),o}_applyViewport(e){let t=Math.floor(this._viewportCached.y);const i=Math.floor(this._viewportCached.w);this._currentRenderTarget||(t=this.getRenderHeight(!0)-t-i),e.setViewport(Math.floor(this._viewportCached.x),t,Math.floor(this._viewportCached.z),i,0,1),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - viewport applied - (",this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w,") current pass is main pass="+(e===this._mainRenderPassWrapper.renderPass)))}_viewport(e,t,i,n){this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=n}_resetCurrentScissor(e){this._scissorsCurrent[e].x=0,this._scissorsCurrent[e].y=0,this._scissorsCurrent[e].w=0,this._scissorsCurrent[e].h=0}_mustUpdateScissor(e){const t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._scissorCached.x,n=this._scissorCached.y,s=this._scissorCached.z,r=this._scissorCached.w,o=this._scissorsCurrent[t].x!==i||this._scissorsCurrent[t].y!==n||this._scissorsCurrent[t].w!==s||this._scissorsCurrent[t].h!==r;return o&&(this._scissorsCurrent[t].x=this._scissorCached.x,this._scissorsCurrent[t].y=this._scissorCached.y,this._scissorsCurrent[t].w=this._scissorCached.z,this._scissorsCurrent[t].h=this._scissorCached.w),o}_applyScissor(e){e.setScissorRect(this._scissorCached.x,this._currentRenderTarget?this._scissorCached.y:this.getRenderHeight()-this._scissorCached.w-this._scissorCached.y,this._scissorCached.z,this._scissorCached.w),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - scissor applied - (",this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w,") current pass is main pass="+(e===this._mainRenderPassWrapper.renderPass)))}_scissorIsActive(){return 0!==this._scissorCached.x||0!==this._scissorCached.y||0!==this._scissorCached.z||0!==this._scissorCached.w}enableScissor(e,t,i,n){this._scissorCached.x=e,this._scissorCached.y=t,this._scissorCached.z=i,this._scissorCached.w=n}disableScissor(){this._scissorCached.x=0,this._scissorCached.y=0,this._scissorCached.z=0,this._scissorCached.w=0,this._resetCurrentScissor(0),this._resetCurrentScissor(1)}_resetCurrentStencilRef(e){this._stencilRefsCurrent[e]=-1}_mustUpdateStencilRef(e){const t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._stencilStateComposer.funcRef!==this._stencilRefsCurrent[t];return i&&(this._stencilRefsCurrent[t]=this._stencilStateComposer.funcRef),i}_applyStencilRef(e){var t;e.setStencilReference(null!==(t=this._stencilStateComposer.funcRef)&&void 0!==t?t:0)}_resetCurrentColorBlend(e){this._blendColorsCurrent[e][0]=this._blendColorsCurrent[e][1]=this._blendColorsCurrent[e][2]=this._blendColorsCurrent[e][3]=null}_mustUpdateBlendColor(e){const t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._alphaState._blendConstants,n=i[0]!==this._blendColorsCurrent[t][0]||i[1]!==this._blendColorsCurrent[t][1]||i[2]!==this._blendColorsCurrent[t][2]||i[3]!==this._blendColorsCurrent[t][3];return n&&(this._blendColorsCurrent[t][0]=i[0],this._blendColorsCurrent[t][1]=i[1],this._blendColorsCurrent[t][2]=i[2],this._blendColorsCurrent[t][3]=i[3]),n}_applyBlendColor(e){e.setBlendConstant(this._alphaState._blendConstants)}clear(e,t,i,n=!1){e&&void 0===e.a&&(e.a=1);const s=this._scissorIsActive();this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - clear called - backBuffer=",t," depth=",i," stencil=",n," scissor is active=",s)),this._currentRenderTarget?s?(this._rttRenderPassWrapper.renderPass||this._startRenderTargetRenderPass(this._currentRenderTarget,!1,t?e:null,i,n),this.compatibilityMode?this._applyScissor(this._currentRenderPass):this._bundleListRenderTarget.addItem(new Io(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),this._clearFullQuad(t?e:null,i,n)):(this._currentRenderPass&&this._endRenderTargetRenderPass(),this._startRenderTargetRenderPass(this._currentRenderTarget,!0,t?e:null,i,n)):(this._mainRenderPassWrapper.renderPass&&s||this._startMainRenderPass(!s,t?e:null,i,n),s&&(this.compatibilityMode?this._applyScissor(this._currentRenderPass):this._bundleList.addItem(new Io(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),this._clearFullQuad(t?e:null,i,n)))}_clearFullQuad(e,t,i){var n,s,r;const o=this.compatibilityMode?this._getCurrentRenderPass():null,a=0===this._getCurrentRenderPassIndex()?this._bundleList:this._bundleListRenderTarget;this._clearQuad.setColorFormat(this._colorFormat),this._clearQuad.setDepthStencilFormat(this._depthTextureFormat),this._clearQuad.setMRTAttachments(null!==(n=this._cacheRenderPipeline.mrtAttachments)&&void 0!==n?n:[],null!==(s=this._cacheRenderPipeline.mrtTextureArray)&&void 0!==s?s:[],this._cacheRenderPipeline.mrtTextureCount),this.compatibilityMode?o.setStencilReference(this._clearStencilValue):a.addItem(new Do(this._clearStencilValue));const l=this._clearQuad.clear(o,e,t,i,this.currentSampleCount);this.compatibilityMode?this._applyStencilRef(o):(a.addBundle(l),a.addItem(new Do(null!==(r=this._stencilStateComposer.funcRef)&&void 0!==r?r:0)),this._reportDrawCall())}createVertexBuffer(e){let t;return t=e instanceof Array?new Float32Array(e):e instanceof ArrayBuffer?new Uint8Array(e):e,this._bufferManager.createBuffer(t,sr.Vertex|sr.CopyDst)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e)}createIndexBuffer(e){let t,i=!0;e instanceof Uint32Array||e instanceof Int32Array?t=e:e instanceof Uint16Array?(t=e,i=!1):e.length>65535?t=new Uint32Array(e):(t=new Uint16Array(e),i=!1);const n=this._bufferManager.createBuffer(t,sr.Index|sr.CopyDst);return n.is32Bits=i,n}_createBuffer(e,t){let i;i=e instanceof Array?new Float32Array(e):e instanceof ArrayBuffer?new Uint8Array(e):e;let n=0;return 1&t&&(n|=sr.CopySrc),2&t&&(n|=sr.CopyDst),4&t&&(n|=sr.Uniform),8&t&&(n|=sr.Vertex),16&t&&(n|=sr.Index),32&t&&(n|=sr.Storage),this._bufferManager.createBuffer(i,n)}bindBuffersDirectly(){throw"Not implemented on WebGPU"}updateAndBindInstancesBuffer(){throw"Not implemented on WebGPU"}bindBuffers(e,t,i,n){this._currentIndexBuffer=t,this._currentOverrideVertexBuffers=null!=n?n:null,this._cacheRenderPipeline.setBuffers(e,t,this._currentOverrideVertexBuffers)}_releaseBuffer(e){return this._bufferManager.releaseBuffer(e)}createEffect(e,t,i,n,s,r,o,a,l,h=Cn.x.GLSL){var c;const u=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,d=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,p=this._getGlobalDefines();let f=null!==(c=null!=s?s:t.defines)&&void 0!==c?c:"";p&&(f+="\n"+p);const _=u+"+"+d+"@"+f;if(this._compiledEffects[_]){const e=this._compiledEffects[_];return o&&e.isReady()&&o(e),e}const m=new ds.Q(e,t,i,n,this,s,r,o,a,l,_,h);return this._compiledEffects[_]=m,m}_compileRawShaderToSpirV(e,t){return this._glslang.compileGLSL(e,t)}_compileShaderToSpirV(e,t,i,n){return this._compileRawShaderToSpirV(n+(i?i+"\n":"")+e,t)}_getWGSLShader(e,t,i){return(i=i?"//"+i.split("\n").join("\n//")+"\n":"")+e}_createPipelineStageDescriptor(e,t,i,n,s){return this._tintWASM&&i===Cn.x.GLSL&&(e=this._tintWASM.convertSpirV2WGSL(e,n),t=this._tintWASM.convertSpirV2WGSL(t,s)),{vertexStage:{module:this._device.createShaderModule({code:e}),entryPoint:"main"},fragmentStage:{module:this._device.createShaderModule({code:t}),entryPoint:"main"}}}_compileRawPipelineStageDescriptor(e,t,i){const n=e.indexOf(Xo)>=0,s=t.indexOf(Xo)>=0,r=i===Cn.x.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===Cn.x.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(r,o,i,n,s)}_compilePipelineStageDescriptor(e,t,i,n){this.onBeforeShaderCompilationObservable.notifyObservers(this);const s=e.indexOf(Xo)>=0,r=t.indexOf(Xo)>=0,o="#version 450\n",a=n===Cn.x.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=n===Cn.x.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(a,l,n,s,r);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new zs.Z(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new Wr(e,this)}createMaterialContext(){return new Eo}createDrawContext(){return new Co(this._bufferManager)}_preparePipelineContext(e,t,i,n,s,r,o,a){const l=e,h=l.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(console.log(a),console.log(t),console.log(i),console.log("***********************************************")),l.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:r},l.stages=n?this._compileRawPipelineStageDescriptor(t,i,h):this._compilePipelineStageDescriptor(t,i,a,h)}getAttributes(e,t){const i=new Array(t.length),n=e;for(let e=0;e<t.length;e++){const s=t[e],r=n.shaderProcessingContext.availableAttributes[s];void 0!==r&&(i[e]=r)}return i}enableEffect(e){if(!e)return;let t=!0;if(Ps.q.IsWrapper(e)){if(!e.effect||e.effect===this._currentEffect&&e.materialContext===this._currentMaterialContext&&e.drawContext===this._currentDrawContext&&!this._forceEnableEffect){if(!e.effect&&this.dbgShowEmptyEnableEffectCalls)throw console.error("drawWrapper=",e),"Invalid call to enableEffect: the effect property is empty!";return}if(t=e.effect!==this._currentEffect,this._currentEffect=e.effect,this._currentMaterialContext=e.materialContext,this._currentDrawContext=e.drawContext,this._counters.numEnableDrawWrapper++,!this._currentMaterialContext)throw console.error("drawWrapper=",e),"Invalid call to enableEffect: the materialContext property is empty!"}else t=e!==this._currentEffect,this._currentEffect=e,this._currentMaterialContext=this._defaultMaterialContext,this._currentDrawContext=this._defaultDrawContext,this._counters.numEnableEffects++,this.dbgLogIfNotDrawWrapper&&_.Y.Warn(`enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=${e.uniqueId}, effect.name=${e.name}, effect.name.vertex=${e.name.vertex}, effect.name.fragment=${e.name.fragment}`,10);this._stencilStateComposer.stencilMaterial=void 0,this._forceEnableEffect=!t&&!this._forceEnableEffect&&this._forceEnableEffect,t&&(this._currentEffect.onBind&&this._currentEffect.onBind(this._currentEffect),this._currentEffect._onBindObservable&&this._currentEffect._onBindObservable.notifyObservers(this._currentEffect))}_releaseEffect(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],this._deletePipelineContext(e.getPipelineContext()))}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}_deletePipelineContext(e){e&&e.dispose()}get needPOTTextures(){return!1}_createHardwareTexture(){return new $r}_releaseTexture(e){const t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),this._textureHelper.releaseTexture(e)}_getRGBABufferInternalSizedFormat(){return 5}updateTextureComparisonFunction(e,t){e._comparisonFunction=t}_createInternalTexture(e,t,i=!0,n=Ei.S.Unknown){var s,r,o;const a={};void 0!==t&&"object"==typeof t?(a.generateMipMaps=t.generateMipMaps,a.type=void 0===t.type?0:t.type,a.samplingMode=void 0===t.samplingMode?3:t.samplingMode,a.format=void 0===t.format?5:t.format,a.samples=null!==(s=t.samples)&&void 0!==s?s:1,a.creationFlags=null!==(r=t.creationFlags)&&void 0!==r?r:0,a.useSRGBBuffer=null!==(o=t.useSRGBBuffer)&&void 0!==o&&o,a.label=t.label):(a.generateMipMaps=t,a.type=0,a.samplingMode=3,a.format=5,a.samples=1,a.creationFlags=0,a.useSRGBBuffer=!1),(1!==a.type||this._caps.textureFloatLinearFiltering)&&(2!==a.type||this._caps.textureHalfFloatLinearFiltering)||(a.samplingMode=1),1!==a.type||this._caps.textureFloat||(a.type=0,_.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const l=new Ei.l(this,n),h=e.width||e,c=e.height||e,u=e.layers||0;return l.baseWidth=h,l.baseHeight=c,l.width=h,l.height=c,l.depth=u,l.isReady=!0,l.samples=a.samples,l.generateMipMaps=!!a.generateMipMaps,l.samplingMode=a.samplingMode,l.type=a.type,l.format=a.format,l.is2DArray=u>0,l._cachedWrapU=0,l._cachedWrapV=0,l._useSRGBBuffer=a.useSRGBBuffer,l.label=a.label,this._internalTexturesCache.push(l),i||this._textureHelper.createGPUTextureForInternalTexture(l,h,c,u||1,a.creationFlags),l}createTexture(e,t,i,n,s=3,r=null,o=null,a=null,l=null,h=null,c=null,u,d,p,f){return this._createTextureBase(e,t,i,n,s,r,o,((e,t,i,n,s,r,o,a)=>{var l;const c=n;if(e.baseWidth=c.width,e.baseHeight=c.height,e.width=c.width,e.height=c.height,e.format=null!=h?h:-1,a(e.width,e.height,c,t,e,(()=>{})),null===(l=e._hardwareTexture)||void 0===l?void 0:l.underlyingResource)r||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,c.width,c.height,void 0,p);no.IsImageBitmap(c)&&(this._textureHelper.updateTexture(c,e,c.width,c.height,e.depth,t.format,0,0,s,!1,0,0),r||o||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(()=>!1),a,l,h,c,u,d,f)}wrapWebGPUTexture(e){const t=new $r(e),i=new Ei.l(this,Ei.S.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&&((null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource)||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e,e.source===Ei.S.RenderTarget||e.source===Ei.S.MultiRenderTarget?this._renderTargetEncoder:void 0))}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,n=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==n&&(e._cachedWrapR=n)}updateTextureDimensions(e,t,i,n=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===i&&e.depth===n)return;const s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,n,s)}_setInternalTexture(e,t,i){if(i=null!=i?i:e,this._currentEffect){const n=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),n&&n.autoBindSampler){const e=i+zr.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,n){this._setTexture(e,i,!1,!1,n,n)}setTextureArray(e,t,i,n){for(let e=0;e<i.length;e++)this._setTexture(-1,i[e],!0,!1,n+e.toString(),n)}_setTexture(e,t,i=!1,n=!1,s="",r){if(r=null!=r?r:s,this._currentEffect){if(!t)return this._currentMaterialContext.setTexture(s,null),!1;if(t.video)t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let e=null;if(e=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,e&&!e.isMultiview){if(e.isCube&&e._cachedCoordinatesMode!==t.coordinatesMode){e._cachedCoordinatesMode=t.coordinatesMode;const i=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=i,t.wrapV=i}e._cachedWrapU=t.wrapU,e._cachedWrapV=t.wrapV,e.is3D&&(e._cachedWrapR=t.wrapR),this._setAnisotropicLevel(0,e,t.anisotropicFilteringLevel)}this._setInternalTexture(s,e,r)}else this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - _setTexture called with a null _currentEffect! texture=",t));return!0}_setAnisotropicLevel(e,t,i){t._cachedAnisotropicFilteringLevel!==i&&(t._cachedAnisotropicFilteringLevel=Math.min(i,this._caps.maxAnisotropy))}_bindTexture(e,t,i){void 0!==e&&this._setInternalTexture(i,t)}generateMipmaps(e){this._generateMipmaps(e,this._renderTargetEncoder)}_generateMipmaps(e,t){const i=e._hardwareTexture;if(!i)return;t=null!=t?t:this._currentRenderTarget&&!this._currentRenderPass?this._renderTargetEncoder:this._currentRenderPass?this._uploadEncoder:this._renderEncoder;const n=e._hardwareTexture.format,s=no.ComputeNumMipmapLevels(e.width,e.height);this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - generate mipmaps called - width=",e.width,"height=",e.height,"isCube=",e.isCube)),e.isCube?this._textureHelper.generateCubeMipmaps(i,n,s,t):this._textureHelper.generateMipmaps(i,n,s,0,t)}updateTextureData(e,t,i,n,s,r,o=0,a=0,l=!1){var h;let c=e._hardwareTexture;(null===(h=e._hardwareTexture)||void 0===h?void 0:h.underlyingResource)||(c=this._textureHelper.createGPUTextureForInternalTexture(e));const u=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(u,e,s,r,e.depth,c.format,o,a,e.invertY,!1,i,n),l&&this._generateMipmaps(e,this._renderTargetEncoder)}_uploadCompressedDataToTextureDirectly(e,t,i,n,s,r=0,o=0){var a;let l=e._hardwareTexture;(null===(a=e._hardwareTexture)||void 0===a?void 0:a.underlyingResource)||(e.format=t,l=this._textureHelper.createGPUTextureForInternalTexture(e,i,n));const h=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);this._textureHelper.updateTexture(h,e,i,n,e.depth,l.format,r,o,!1,!1,0,0)}_uploadDataToTextureDirectly(e,t,i=0,n=0,s,r=!1){var o;const a=Math.round(Math.log(e.width)*Math.LOG2E),l=Math.round(Math.log(e.height)*Math.LOG2E),h=r?e.width:Math.pow(2,Math.max(a-n,0)),c=r?e.height:Math.pow(2,Math.max(l-n,0));let u=e._hardwareTexture;(null===(o=e._hardwareTexture)||void 0===o?void 0:o.underlyingResource)||(u=this._textureHelper.createGPUTextureForInternalTexture(e,h,c));const d=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(d,e,h,c,e.depth,u.format,i,n,e.invertY,!1,0,0)}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){this._uploadDataToTextureDirectly(e,t,i,n)}_uploadImageToTexture(e,t,i=0,n=0){var s;let r=e._hardwareTexture;if((null===(s=e._hardwareTexture)||void 0===s?void 0:s.underlyingResource)||(r=this._textureHelper.createGPUTextureForInternalTexture(e)),t instanceof HTMLImageElement)throw"WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!";const o=t,a=Math.ceil(e.width/(1<<n)),l=Math.ceil(e.height/(1<<n));this._textureHelper.updateTexture(o,e,a,l,e.depth,r.format,i,n,e.invertY,!1,0,0)}readPixels(e,t,i,n,s=!0,r=!0){const o=(this._rttRenderPassWrapper.renderPass?this._rttRenderPassWrapper:this._mainRenderPassWrapper).colorAttachmentGPUTextures[0];if(!o)return Promise.resolve(new Uint8Array(0));const a=o.underlyingResource,l=o.format;return a?(r&&this.flushFramebuffer(),this._textureHelper.readPixels(a,e,t,i,n,l)):Promise.resolve(new Uint8Array(0))}beginFrame(){super.beginFrame()}endFrame(){if(this._snapshotRendering.endFrame(this._mainRenderPassWrapper.renderPass),this._endMainRenderPass(),this._timestampQuery.endFrame(this._renderEncoder),this.flushFramebuffer(!1),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - counters")),this._textureHelper.destroyDeferredTextures(),this._bufferManager.destroyDeferredBuffers(),this._features._collectUbosUpdatedInFrame){if(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){const e=[];for(const t in Ci.M._UpdatedUbosInFrame)e.push(t+":"+Ci.M._UpdatedUbosInFrame[t]);console.log("frame #"+this._count+" - updated ubos -",e.join(", "))}Ci.M._UpdatedUbosInFrame={}}this.countersLastFrame.numEnableEffects=this._counters.numEnableEffects,this.countersLastFrame.numEnableDrawWrapper=this._counters.numEnableDrawWrapper,this.countersLastFrame.numBundleCreationNonCompatMode=this._counters.numBundleCreationNonCompatMode,this.countersLastFrame.numBundleReuseNonCompatMode=this._counters.numBundleReuseNonCompatMode,this._counters.numEnableEffects=0,this._counters.numEnableDrawWrapper=0,this._counters.numBundleCreationNonCompatMode=0,this._counters.numBundleReuseNonCompatMode=0,this._cacheRenderPipeline.endFrame(),this._cacheBindGroups.endFrame(),this._pendingDebugCommands.length=0,super.endFrame(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),this._count<this.dbgVerboseLogsNumFrames&&console.log("%c frame #"+this._count+" - end","background: #ffff00"),this._count<this.dbgVerboseLogsNumFrames&&(this._count++,this._count!==this.dbgVerboseLogsNumFrames&&console.log("%c frame #"+this._count+" - begin","background: #ffff00")))}flushFramebuffer(e=!0){const t=!this._currentRenderPass;let i=0;this._currentRenderPass&&this._currentRenderTarget&&(i|=1,this._endRenderTargetRenderPass()),this._mainRenderPassWrapper.renderPass&&(i|=2,this._endMainRenderPass()),this._commandBuffers[0]=this._uploadEncoder.finish(),this._commandBuffers[1]=this._renderTargetEncoder.finish(),this._commandBuffers[2]=this._renderEncoder.finish(),this._device.queue.submit(this._commandBuffers),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._renderTargetEncoder=this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),this._timestampQuery.startFrame(this._uploadEncoder),this._textureHelper.setCommandEncoder(this._uploadEncoder),this._bundleList.reset(),this._bundleListRenderTarget.reset(),e&&(2&i&&this._startMainRenderPass(!1),1&i&&this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1),t&&this._currentRenderTarget&&(this._currentRenderPass=null))}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentRenderTarget}_startRenderTargetRenderPass(e,t,i,n,s){var r,o,a,l,h,c,u;const d=e,p=d._depthStencilTexture,f=null==p?void 0:p._hardwareTexture,_=null==f?void 0:f.underlyingResource,m=null==f?void 0:f.getMSAATexture(),g=null==_?void 0:_.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),v=null==m?void 0:m.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),y=!!f&&no.HasStencilAspect(f.format),x=[];this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();const b=t&&i,T=t&&n,S=t&&s;if(d._attachments&&d.isMulti){this._mrtAttachments&&0!==this._mrtAttachments.length||(this._mrtAttachments=d._defaultAttachments);for(let e=0;e<this._mrtAttachments.length;++e){const t=this._mrtAttachments[e],n=d.textures[e],s=null==n?void 0:n._hardwareTexture,h=null==s?void 0:s.underlyingResource;if(s&&h){const c=s.getMSAATexture(e),u=null!==(o=null===(r=d.layerIndices)||void 0===r?void 0:r[e])&&void 0!==o?o:0,p=null!==(l=null===(a=d.faceIndices)||void 0===a?void 0:a[e])&&void 0!==l?l:0,f={...this._rttRenderPassWrapper.colorAttachmentViewDescriptor,format:s.format,baseArrayLayer:n.isCube?6*u+p:u},_={...this._rttRenderPassWrapper.colorAttachmentViewDescriptor,format:s.format,baseArrayLayer:0},m=h.createView(f),g=null==c?void 0:c.createView(_);x.push({view:g||m,resolveTarget:c?m:void 0,clearValue:0!==t&&b?i:void 0,loadOp:0!==t&&b?Fr.Clear:Fr.Load,storeOp:Lr.Store})}}this._cacheRenderPipeline.setMRT(d.textures,this._mrtAttachments.length),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)}else{const e=d.texture;if(e){const t=e._hardwareTexture,n=t.underlyingResource,s=t.getMSAATexture(),r=n.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),o=null==s?void 0:s.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor);x.push({view:o||r,resolveTarget:s?r:void 0,clearValue:b?i:void 0,loadOp:b?Fr.Clear:Fr.Load,storeOp:Lr.Store})}else x.push(null)}if(null===(h=this._debugPushGroup)||void 0===h||h.call(this,"render target pass",1),this._rttRenderPassWrapper.renderPassDescriptor={colorAttachments:x,depthStencilAttachment:p&&_?{view:v||g,depthClearValue:T?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,depthLoadOp:T?Fr.Clear:Fr.Load,depthStoreOp:Lr.Store,stencilClearValue:d._depthStencilTextureWithStencil&&S?this._clearStencilValue:void 0,stencilLoadOp:y?d._depthStencilTextureWithStencil&&S?Fr.Clear:Fr.Load:void 0,stencilStoreOp:y?Lr.Store:void 0}:void 0,occlusionQuerySet:(null===(c=this._occlusionQuery)||void 0===c?void 0:c.hasQueries)?this._occlusionQuery.querySet:void 0},this._rttRenderPassWrapper.renderPass=this._renderTargetEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){const e=d.texture;console.log("frame #"+this._count+" - render target begin pass - internalTexture.uniqueId=",e.uniqueId,"width=",e.width,"height=",e.height,this._rttRenderPassWrapper.renderPassDescriptor)}this._currentRenderPass=this._rttRenderPassWrapper.renderPass,null===(u=this._debugFlushPendingCommands)||void 0===u||u.call(this),this._resetCurrentViewport(1),this._resetCurrentScissor(1),this._resetCurrentStencilRef(1),this._resetCurrentColorBlend(1),f&&no.HasStencilAspect(f.format)||(this._stencilStateComposer.enabled=!1)}_endRenderTargetRenderPass(){var e,t,i,n;if(this._currentRenderPass){const s=null===(e=this._currentRenderTarget.texture)||void 0===e?void 0:e._hardwareTexture;!s||this._snapshotRendering.endRenderTargetPass(this._currentRenderPass,s)||this.compatibilityMode||(this._bundleListRenderTarget.run(this._currentRenderPass),this._bundleListRenderTarget.reset()),this._currentRenderPass.end(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - render target end pass - internalTexture.uniqueId=",null===(i=null===(t=this._currentRenderTarget)||void 0===t?void 0:t.texture)||void 0===i?void 0:i.uniqueId)),null===(n=this._debugPopGroup)||void 0===n||n.call(this,1),this._resetCurrentViewport(1),this._viewport(0,0,0,0),this._resetCurrentScissor(1),this._resetCurrentStencilRef(1),this._resetCurrentColorBlend(1),this._currentRenderPass=null,this._rttRenderPassWrapper.reset()}}_getCurrentRenderPass(){return this._currentRenderTarget&&!this._currentRenderPass?this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1):this._currentRenderPass||this._startMainRenderPass(!1),this._currentRenderPass}_getCurrentRenderPassIndex(){return null===this._currentRenderPass?-1:this._currentRenderPass===this._mainRenderPassWrapper.renderPass?0:1}_startMainRenderPass(e,t,i,n){var s,r,o;this._mainRenderPassWrapper.renderPass&&this.flushFramebuffer(!1),this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();const a=e&&t,l=e&&i,h=e&&n;this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue=a?t:void 0,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp=a?Fr.Clear:Fr.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue=l?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp=l?Fr.Clear:Fr.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue=h?this._clearStencilValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp=this.isStencilEnable?h?Fr.Clear:Fr.Load:void 0,this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet=(null===(s=this._occlusionQuery)||void 0===s?void 0:s.hasQueries)?this._occlusionQuery.querySet:void 0;const c=this._context.getCurrentTexture();this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(c),this._options.antialias?(Wo.format=c.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget=c.createView(Wo)):(Ho.format=c.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view=c.createView(Ho)),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - main begin pass - texture width="+this._mainTextureExtends.width," height="+this._mainTextureExtends.height,this._mainRenderPassWrapper.renderPassDescriptor)),null===(r=this._debugPushGroup)||void 0===r||r.call(this,"main pass",0),this._currentRenderPass=this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor),this._mainRenderPassWrapper.renderPass=this._currentRenderPass,null===(o=this._debugFlushPendingCommands)||void 0===o||o.call(this),this._resetCurrentViewport(0),this._resetCurrentScissor(0),this._resetCurrentStencilRef(0),this._resetCurrentColorBlend(0),this._isStencilEnable||(this._stencilStateComposer.enabled=!1)}_endMainRenderPass(){var e;null!==this._mainRenderPassWrapper.renderPass&&(this._snapshotRendering.endMainRenderPass(),this.compatibilityMode||this._snapshotRendering.play||(this._bundleList.run(this._mainRenderPassWrapper.renderPass),this._bundleList.reset()),this._mainRenderPassWrapper.renderPass.end(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - main end pass")),null===(e=this._debugPopGroup)||void 0===e||e.call(this,0),this._resetCurrentViewport(0),this._resetCurrentScissor(0),this._resetCurrentStencilRef(0),this._resetCurrentColorBlend(0),this._mainRenderPassWrapper.renderPass===this._currentRenderPass&&(this._currentRenderPass=null),this._mainRenderPassWrapper.reset(!1))}bindFramebuffer(e,t=0,i,n,s,r=0,o=0){var a,l;const h=null===(a=e.texture)||void 0===a?void 0:a._hardwareTexture;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,h&&(h._currentLayer=e.isCube?6*o+t:o),this._rttRenderPassWrapper.colorAttachmentGPUTextures[0]=h,this._rttRenderPassWrapper.depthTextureFormat=this._currentRenderTarget._depthStencilTexture?no.GetWebGPUTextureFormat(-1,this._currentRenderTarget._depthStencilTexture.format):void 0,this._setDepthTextureFormat(this._rttRenderPassWrapper),this._setColorFormat(this._rttRenderPassWrapper),this._rttRenderPassWrapper.colorAttachmentViewDescriptor={format:this._colorFormat,dimension:lr.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?6*o+t:o,baseMipLevel:r,arrayLayerCount:1,aspect:hr.All},this._rttRenderPassWrapper.depthAttachmentViewDescriptor={format:this._depthTextureFormat,dimension:lr.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?6*o+t:o,baseMipLevel:0,arrayLayerCount:1,aspect:hr.All},this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - bindFramebuffer called - internalTexture.uniqueId=",null===(l=e.texture)||void 0===l?void 0:l.uniqueId,"face=",t,"lodLevel=",r,"layer=",o,this._rttRenderPassWrapper.colorAttachmentViewDescriptor,this._rttRenderPassWrapper.depthAttachmentViewDescriptor)),this._currentRenderPass=null,this.snapshotRendering&&1===this.snapshotRenderingMode&&this._getCurrentRenderPass(),this._cachedViewport&&!s?this.setViewport(this._cachedViewport,i,n):(i||(i=e.width,r&&(i/=Math.pow(2,r))),n||(n=e.height,r&&(n/=Math.pow(2,r))),this._viewport(0,0,i,n)),this.wipeCaches()}unBindFramebuffer(e,t=!1,i){var n,s;const r=this._currentRenderTarget;this._currentRenderTarget=null,i&&i(),this._currentRenderTarget=r,this._currentRenderPass&&this._currentRenderPass!==this._mainRenderPassWrapper.renderPass&&this._endRenderTargetRenderPass(),!(null===(n=e.texture)||void 0===n?void 0:n.generateMipMaps)||t||e.isCube||this._generateMipmaps(e.texture),this._currentRenderTarget=null,this._onAfterUnbindFrameBufferObservable.notifyObservers(this),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - unBindFramebuffer called - internalTexture.uniqueId=",null===(s=e.texture)||void 0===s?void 0:s.uniqueId)),this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments),this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):(this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)),this._currentRenderPass&&this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_setColorFormat(e){var t,i;const n=null!==(i=null===(t=e.colorAttachmentGPUTextures[0])||void 0===t?void 0:t.format)&&void 0!==i?i:null;this._cacheRenderPipeline.setColorFormat(n),this._colorFormat!==n&&(this._colorFormat=n)}_setDepthTextureFormat(e){this._cacheRenderPipeline.setDepthStencilFormat(e.depthTextureFormat),this._depthTextureFormat!==e.depthTextureFormat&&(this._depthTextureFormat=e.depthTextureFormat)}setDitheringState(){}setRasterizerState(){}setState(e,t=0,i,n=!1,s,r,o=0){var a,l;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const h=null===(l=null!==(a=this.cullBackFaces)&&void 0!==a?a:s)||void 0===l||l?1:2;(this._depthCullingState.cullFace!==h||i)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(o);const c=n?this._currentRenderTarget?1:2:this._currentRenderTarget?2:1;(this._depthCullingState.frontFace!==c||i)&&(this._depthCullingState.frontFace=c),this._stencilStateComposer.stencilMaterial=r}_applyRenderPassChanges(e,t){var i;const n=this._mustUpdateViewport(e),s=this._mustUpdateScissor(e),r=!!this._stencilStateComposer.enabled&&this._mustUpdateStencilRef(e),o=!!this._alphaState.alphaBlend&&this._mustUpdateBlendColor(e);t?(n&&t.addItem(new Mo(this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w)),s&&t.addItem(new Io(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),r&&t.addItem(new Do(null!==(i=this._stencilStateComposer.funcRef)&&void 0!==i?i:0)),o&&t.addItem(new Oo(this._alphaState._blendConstants.slice()))):(n&&this._applyViewport(e),s&&this._applyScissor(e),r&&this._applyStencilRef(e),o&&this._applyBlendColor(e))}_draw(e,t,i,n,s){var r;const o=this._getCurrentRenderPass(),a=0===this._getCurrentRenderPassIndex()?this._bundleList:this._bundleListRenderTarget;this.applyStates();const l=this._currentEffect._pipelineContext;if(this.bindUniformBufferBase(this._currentRenderTarget?this._ubInvertY:this._ubDontInvertY,0,zr.InternalsUBOName),l.uniformBuffer&&(l.uniformBuffer.update(),this.bindUniformBufferBase(l.uniformBuffer.getBuffer(),0,zr.LeftOvertUBOName)),this._snapshotRendering.play)return void this._reportDrawCall();!this.compatibilityMode&&(this._currentDrawContext.isDirty(this._currentMaterialContext.updateId)||this._currentMaterialContext.isDirty||this._currentMaterialContext.forceBindGroupCreation)&&(this._currentDrawContext.fastBundle=void 0);let h=o;if(!this.compatibilityMode&&this._currentDrawContext.fastBundle||this._snapshotRendering.record){if(this._applyRenderPassChanges(o,a),!this._snapshotRendering.record)return this._counters.numBundleReuseNonCompatMode++,this._currentDrawContext.indirectDrawBuffer&&this._currentDrawContext.setIndirectData(n,s||1,i),a.addBundle(this._currentDrawContext.fastBundle),void this._reportDrawCall();h=a.getBundleEncoder(this._cacheRenderPipeline.colorFormats,this._depthTextureFormat,this.currentSampleCount),a.numDrawCalls++}let c=0;if(!this._caps.textureFloatLinearFiltering&&this._currentMaterialContext.hasFloatTextures){let e=1;for(let t=0;t<l.shaderProcessingContext.textureNames.length;++t){const i=l.shaderProcessingContext.textureNames[t],n=null===(r=this._currentMaterialContext.textures[i])||void 0===r?void 0:r.texture;1===(null==n?void 0:n.type)&&(c|=e),e<<=1}}const u=this._cacheRenderPipeline.getRenderPipeline(t,this._currentEffect,this.currentSampleCount,c),d=this._cacheBindGroups.getBindGroups(l,this._currentDrawContext,this._currentMaterialContext);this._snapshotRendering.record||(this._applyRenderPassChanges(o,this.compatibilityMode?null:a),this.compatibilityMode||(this._counters.numBundleCreationNonCompatMode++,h=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:this.currentSampleCount}))),h.setPipeline(u),this._currentIndexBuffer&&h.setIndexBuffer(this._currentIndexBuffer.underlyingResource,this._currentIndexBuffer.is32Bits?Ir.Uint32:Ir.Uint16,0);const p=this._cacheRenderPipeline.vertexBuffers;for(let e=0;e<p.length;e++){const t=p[e],i=t.getBuffer();i&&h.setVertexBuffer(e,i.underlyingResource,t._validOffsetRange?0:t.byteOffset)}for(let e=0;e<d.length;e++)h.setBindGroup(e,d[e]);const f=!this.compatibilityMode&&!this._snapshotRendering.record;f&&this._currentDrawContext.indirectDrawBuffer?(this._currentDrawContext.setIndirectData(n,s||1,i),0===e?h.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer,0):h.drawIndirect(this._currentDrawContext.indirectDrawBuffer,0)):0===e?h.drawIndexed(n,s||1,i,0,0):h.draw(n,s||1,i,0),f&&(this._currentDrawContext.fastBundle=h.finish(),a.addBundle(this._currentDrawContext.fastBundle)),this._reportDrawCall()}drawElementsType(e,t,i,n=1){this._draw(0,e,t,i,n)}drawArraysType(e,t,i,n=1){this._currentIndexBuffer=null,this._draw(1,e,t,i,n)}dispose(){var e,t;this._isDisposed=!0,null===(e=this._mainTexture)||void 0===e||e.destroy(),null===(t=this._depthTexture)||void 0===t||t.destroy(),this._device.destroy(),super.dispose()}getRenderWidth(e=!1){var t,i;return!e&&this._currentRenderTarget?this._currentRenderTarget.width:null!==(i=null===(t=this._renderingCanvas)||void 0===t?void 0:t.width)&&void 0!==i?i:0}getRenderHeight(e=!1){var t,i;return!e&&this._currentRenderTarget?this._currentRenderTarget.height:null!==(i=null===(t=this._renderingCanvas)||void 0===t?void 0:t.height)&&void 0!==i?i:0}getError(){return 0}bindSamplers(){}_bindTextureDirectly(){return!1}areAllEffectsReady(){return!0}_executeWhenRenderingStateIsCompiled(e,t){t()}_isRenderingStateCompiled(){return!0}_getUnpackAlignement(){return 1}_unpackFlipY(){}_bindUnboundFramebuffer(){throw"_bindUnboundFramebuffer is not implementedin WebGPU! You probably want to use restoreDefaultFramebuffer or unBindFramebuffer instead"}_getSamplingParameters(){throw"_getSamplingParameters is not available in WebGPU"}getUniforms(){return[]}setIntArray(){return!1}setIntArray2(){return!1}setIntArray3(){return!1}setIntArray4(){return!1}setArray(){return!1}setArray2(){return!1}setArray3(){return!1}setArray4(){return!1}setMatrices(){return!1}setMatrix3x3(){return!1}setMatrix2x2(){return!1}setFloat(){return!1}setFloat2(){return!1}setFloat3(){return!1}setFloat4(){return!1}}jo._GLSLslangDefaultOptions={jsPath:"https://preview.babylonjs.com/glslang/glslang.js",wasmPath:"https://preview.babylonjs.com/glslang/glslang.wasm"},jo.UseTWGSL=!0,jo.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e&&(0===e&&!this._alphaState.alphaBlend||0!==e&&this._alphaState.alphaBlend)){if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.setDepthWrite(t),this._cacheRenderPipeline.setDepthWriteEnabled(t))}}else{switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0}t||(this.setDepthWrite(e===ue.D.ALPHA_DISABLE),this._cacheRenderPipeline.setDepthWriteEnabled(e===ue.D.ALPHA_DISABLE)),this._alphaMode=e,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)}},jo.prototype.setAlphaEquation=function(e){ue.D.prototype.setAlphaEquation.call(this,e),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};class Yo{getBindGroups(e,t,i){if(!i)throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(0===this._bindGroups.length){const n=this._bindGroupEntries.length>0;for(const t in e){const s=e[t],r=i[t],o=r.group,a=r.binding,l=s.type,h=s.object;let c=s.indexInGroupEntries,u=this._bindGroupEntries[o];switch(u||(u=this._bindGroupEntries[o]=[]),l){case Pn.Sampler:{const e=h;void 0!==c&&n?u[c].resource=this._cacheSampler.getSampler(e):(s.indexInGroupEntries=u.length,u.push({binding:a,resource:this._cacheSampler.getSampler(e)}));break}case Pn.Texture:case Pn.TextureWithoutSampler:{const e=h,t=e._texture._hardwareTexture;void 0!==c&&n?(l===Pn.Texture&&(u[c++].resource=this._cacheSampler.getSampler(e._texture)),u[c].resource=t.view):(s.indexInGroupEntries=u.length,l===Pn.Texture&&u.push({binding:a-1,resource:this._cacheSampler.getSampler(e._texture)}),u.push({binding:a,resource:t.view}));break}case Pn.StorageTexture:{const e=h,t=e._texture._hardwareTexture;0==(t.textureAdditionalUsages&ar.StorageBinding)&&_.Y.Error(`computeDispatch: The texture (name=${e.name}, uniqueId=${e.uniqueId}) is not a storage texture!`,50),void 0!==c&&n?u[c].resource=t.viewForWriting:(s.indexInGroupEntries=u.length,u.push({binding:a,resource:t.viewForWriting}));break}case Pn.UniformBuffer:case Pn.StorageBuffer:{const e=(Pn.UniformBuffer,h).getBuffer(),t=e.underlyingResource;void 0!==c&&n?(u[c].resource.buffer=t,u[c].resource.size=e.capacity):(s.indexInGroupEntries=u.length,u.push({binding:a,resource:{buffer:t,offset:0,size:e.capacity}}));break}}}for(let e=0;e<this._bindGroupEntries.length;++e){const i=this._bindGroupEntries[e];this._bindGroups[e]=i?this._device.createBindGroup({layout:t.getBindGroupLayout(e),entries:i}):void 0}this._bindGroups.length=this._bindGroupEntries.length}return this._bindGroups}constructor(e,t){this._device=e,this._cacheSampler=t,this.uniqueId=Yo._Counter++,this._bindGroupEntries=[],this.clear()}clear(){this._bindGroups=[]}}Yo._Counter=0;class qo{get isAsync(){return!1}get isReady(){return!!this.stage}constructor(e){this._name="unnamed",this.engine=e}_getComputeShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.compute}dispose(){}}jo.prototype.createComputeContext=function(){return new Yo(this._device,this._cacheSampler)},jo.prototype.createComputeEffect=function(e,t){const i=(e.computeElement||e.compute||e.computeToken||e.computeSource||e)+"@"+t.defines;if(this._compiledComputeEffects[i]){const e=this._compiledComputeEffects[i];return t.onCompiled&&e.isReady()&&t.onCompiled(e),e}const n=new An(e,t,this,i);return this._compiledComputeEffects[i]=n,n},jo.prototype.createComputePipelineContext=function(){return new qo(this)},jo.prototype.areAllComputeEffectsReady=function(){for(const e in this._compiledComputeEffects)if(!this._compiledComputeEffects[e].isReady())return!1;return!0},jo.prototype.computeDispatch=function(e,t,i,n,s,r,o){if(this._currentRenderTarget)return void this._onAfterUnbindFrameBufferObservable.addOnce((()=>{this.computeDispatch(e,t,i,n,s,r,o)}));const a=e._pipelineContext,l=t;a.computePipeline||(a.computePipeline=this._device.createComputePipeline({layout:Tr.Auto,compute:a.stage}));const h=this._renderTargetEncoder.beginComputePass();h.setPipeline(a.computePipeline);const c=l.getBindGroups(i,a.computePipeline,o);for(let e=0;e<c.length;++e){const t=c[e];t&&h.setBindGroup(e,t)}h.dispatchWorkgroups(n,s,r),h.end()},jo.prototype.releaseComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},jo.prototype._prepareComputePipelineContext=function(e,t,i,n,s){const r=e;this.dbgShowShaderCode&&(console.log(n),console.log(t)),r.sources={compute:t,rawCompute:i},r.stage=this._createComputePipelineStageDescriptor(t,n,s)},jo.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},jo.prototype._rebuildComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},jo.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},jo.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},jo.prototype._createDepthStencilCubeTexture=function(e,t){const i=new Ei.l(this,Ei.S.DepthStencil);i.isCube=!0;const n={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,...t};return i.format=n.generateStencil?13:14,this._setupDepthStencilTexture(i,e,n.generateStencil,n.bilinearFiltering,n.comparisonFunction,n.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},jo.prototype.createCubeTexture=function(e,t,i,n,s=null,r=null,o,a=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(e,t,i,!!n,s,r,o,a,l,h,c,u,null,((e,t)=>{const i=t,r=i[0].width,a=r;this._setCubeMapTextureParams(e,!n),e.format=null!=o?o:-1;const l=this._textureHelper.createGPUTextureForInternalTexture(e,r,a);this._textureHelper.updateCubeTextures(i,l.underlyingResource,r,a,l.format,!1,!1,0,0),n||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()}),!!d)},jo.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},jo.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?(0===t?this._renderEncoder:this._renderTargetEncoder).pushDebugGroup(e):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e]))},jo.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?(0===e?this._renderEncoder:this._renderTargetEncoder).popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))},jo.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?(0===t?this._renderEncoder:this._renderTargetEncoder).insertDebugMarker(e):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e]))},jo.prototype._debugFlushPendingCommands=function(){for(let e=0;e<this._pendingDebugCommands.length;++e){const[t,i]=this._pendingDebugCommands[e];switch(t){case"push":this._debugPushGroup(i);break;case"pop":this._debugPopGroup();break;case"insert":this._debugInsertMarker(i)}}this._pendingDebugCommands.length=0},jo.prototype.updateDynamicIndexBuffer=function(e,t,i=0){const n=e;let s;s=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._bufferManager.setSubData(n,i,s)},jo.prototype.updateDynamicVertexBuffer=function(e,t,i,n){const s=e;let r;void 0===i&&(i=0),void 0===n?(r=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,n=r.byteLength):r=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(s,i,r,0,n)},jo.prototype.updateDynamicTexture=function(e,t,i,n=!1,s,r,o){var a;if(!e)return;const l=t.width,h=t.height;let c=e._hardwareTexture;(null===(a=e._hardwareTexture)||void 0===a?void 0:a.underlyingResource)||(c=this._textureHelper.createGPUTextureForInternalTexture(e,l,h)),this._textureHelper.updateTexture(t,e,l,h,e.depth,c.format,0,0,i,n,0,0,o),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0};class Ko extends So{constructor(e){super(e)}}function $o(e,t,i,n){let s,r=1;1===n?s=new Float32Array(t*i*4):2===n?(s=new Uint16Array(t*i*4),r=15360):s=7===n?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let n=0;n<t;n++)for(let o=0;o<i;o++){const i=3*(o*t+n),a=4*(o*t+n);s[a+0]=e[i+0],s[a+1]=e[i+1],s[a+2]=e[i+2],s[a+3]=r}return s}ds.Q.prototype.setExternalTexture=function(e,t){this._engine.setExternalTexture(e,t)},jo.prototype.createExternalTexture=function(e){return new Ko(e)},jo.prototype.setExternalTexture=function(e,t){t?this._setInternalTexture(e,t):this._currentMaterialContext.setTexture(e,null)},jo.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t=!1,i){i&&i();const n=e._attachments.length;this._currentRenderPass&&this._currentRenderPass!==this._mainRenderPassWrapper.renderPass&&this._endRenderTargetRenderPass();for(let i=0;i<n;i++){const n=e.textures[i];!n.generateMipMaps||t||n.isCube||this._generateMipmaps(n)}this._currentRenderTarget=null,this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments),this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)},jo.prototype.createMultipleRenderTarget=function(e,t,i){var n,s;let r=!1,o=!0,a=!1,l=!1,h=15,c=1,u=new Array,d=new Array,p=new Array,f=new Array,m=new Array,g=new Array,v=new Array,y=new Array;const x=this._createHardwareRenderTargetWrapper(!0,!1,e);void 0!==t&&(r=void 0!==t.generateMipMaps&&t.generateMipMaps,o=void 0===t.generateDepthBuffer||t.generateDepthBuffer,a=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,l=void 0!==t.generateDepthTexture&&t.generateDepthTexture,c=t.textureCount||1,h=null!==(n=t.depthTextureFormat)&&void 0!==n?n:15,t.types&&(u=t.types),t.samplingModes&&(d=t.samplingModes),t.useSRGBBuffers&&(p=t.useSRGBBuffers),t.formats&&(f=t.formats),t.targetTypes&&(m=t.targetTypes),t.faceIndex&&(g=t.faceIndex),t.layerIndex&&(v=t.layerIndex),t.layerCounts&&(y=t.layerCounts));const b=e.width||e,T=e.height||e;let S=null;(o||a||l)&&(l||(h=o&&a?13:o?14:19),S=x.createDepthStencilTexture(0,!1,a,1,h));const E=[],C=[],A=[];x._generateDepthBuffer=o,x._generateStencilBuffer=a,x._attachments=C,x._defaultAttachments=A;for(let e=0;e<c;e++){let t=d[e]||3,n=u[e]||0;const o=f[e]||5,a=!!p[e]&&this._caps.supportSRGBBuffers,l=m[e]||3553,h=null!==(s=y[e])&&void 0!==s?s:1;if((1!==n||this._caps.textureFloatLinearFiltering)&&(2!==n||this._caps.textureHalfFloatLinearFiltering)||(t=1),1!==n||this._caps.textureFloat||(n=0,_.Y.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),C.push(e+1),A.push(i?e+1:0===e?1:0),-1===l)continue;const c=new Ei.l(this,Ei.S.MultiRenderTarget);switch(E[e]=c,l){case 34067:c.isCube=!0;break;case 32879:c.is3D=!0,c.baseDepth=c.depth=h;break;case 35866:c.is2DArray=!0,c.baseDepth=c.depth=h}c.baseWidth=b,c.baseHeight=T,c.width=b,c.height=T,c.isReady=!0,c.samples=1,c.generateMipMaps=r,c.samplingMode=t,c.type=n,c._cachedWrapU=0,c._cachedWrapV=0,c._useSRGBBuffer=a,c.format=o,this._internalTexturesCache.push(c),this._textureHelper.createGPUTextureForInternalTexture(c)}return S&&(S.incrementReferences(),E[c]=S,this._internalTexturesCache.push(S)),x.setTextures(E),x.setLayerAndFaceIndices(v,g),x},jo.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t){if(!e||!e.textures||e.textures[0].samples===t)return t;const i=e.textures.length;if(0===i)return 1;t=Math.min(t,this.getCaps().maxMSAASamples);for(let t=0;t<i;++t){const i=e.textures[t]._hardwareTexture;null==i||i.releaseMSAATexture()}const n=e._depthStencilTexture===e.textures[i-1];for(let s=0;s<i;++s){const r=e.textures[s];this._textureHelper.createMSAATexture(r,t,!1,s===i-1&&n?0:s),r.samples=t}return e._depthStencilTexture&&!n&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),t},jo.prototype.bindAttachments=function(e){0!==e.length&&this._currentRenderTarget&&(this._mrtAttachments=e,this._currentRenderPass&&this._cacheRenderPipeline.setMRTAttachments(e))},jo.prototype.buildTextureLayout=function(e){const t=[];for(let i=0;i<e.length;i++)e[i]?t.push(i+1):t.push(0);return t},jo.prototype.restoreSingleAttachment=function(){},jo.prototype.restoreSingleAttachmentForRenderTarget=function(){},jo.prototype.getGPUFrameTimeCounter=function(){return this._timestampQuery.gpuFrameTimeCounter},jo.prototype.captureGPUFrameTime=function(e){this._timestampQuery.enable=e&&!!this._caps.timerQuery},jo.prototype.createQuery=function(){return this._occlusionQuery.createQuery()},jo.prototype.deleteQuery=function(e){return this._occlusionQuery.deleteQuery(e),this},jo.prototype.isQueryResultAvailable=function(e){return this._occlusionQuery.isQueryResultAvailable(e)},jo.prototype.getQueryResult=function(e){return this._occlusionQuery.getQueryResult(e)},jo.prototype.beginOcclusionQuery=function(e,t){var i;return this.compatibilityMode?!!this._occlusionQuery.canBeginQuery&&(null===(i=this._currentRenderPass)||void 0===i||i.beginOcclusionQuery(t),!0):((0===this._getCurrentRenderPassIndex()?this._bundleList:this._bundleListRenderTarget).addItem(new wo(t)),!0)},jo.prototype.endOcclusionQuery=function(){var e;return this.compatibilityMode?null===(e=this._currentRenderPass)||void 0===e||e.endOcclusionQuery():(0===this._getCurrentRenderPassIndex()?this._bundleList:this._bundleListRenderTarget).addItem(new No),this},jo.prototype.createRawTexture=function(e,t,i,n,s,r,o,a=null,l=0,h=0,c=!1){const u=new Ei.l(this,Ei.S.Raw);return u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=n,u.generateMipMaps=s,u.samplingMode=o,u.invertY=r,u._compression=a,u.type=l,u._useSRGBBuffer=c,this._doNotHandleContextLost||(u._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(u,t,i,void 0,h),this.updateRawTexture(u,e,n,r,a,l,c),this._internalTexturesCache.push(u),u},jo.prototype.updateRawTexture=function(e,t,i,n,s=null,r=0,o=!1){if(e){if(this._doNotHandleContextLost||(e._bufferView=t,e.invertY=n,e._compression=s,e._useSRGBBuffer=o),t){const s=e._hardwareTexture;4===i&&(t=$o(t,e.width,e.height,r));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,n,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0}},jo.prototype.createRawCubeTexture=function(e,t,i,n,s,r,o,a=null){const l=new Ei.l(this,Ei.S.CubeRaw);return 1!==n||this._caps.textureFloatLinearFiltering?2!==n||this._caps.textureHalfFloatLinearFiltering?1!==n||this._caps.textureFloatRender?2!==n||this._caps.colorBufferFloat||(s=!1,_.Y.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(s=!1,_.Y.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(s=!1,o=1,_.Y.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(s=!1,o=1,_.Y.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")),l.isCube=!0,l.format=4===i?5:i,l.type=n,l.generateMipMaps=s,l.width=t,l.height=t,l.samplingMode=o,this._doNotHandleContextLost||(l._bufferViewArray=e),l.invertY=r,l._compression=a,l._cachedWrapU=0,l._cachedWrapV=0,this._textureHelper.createGPUTextureForInternalTexture(l),e&&this.updateRawCubeTexture(l,e,i,n,r,a),l.isReady=!0,l},jo.prototype.updateRawCubeTexture=function(e,t,i,n,s,r=null){e._bufferViewArray=t,e.invertY=s,e._compression=r;const o=e._hardwareTexture,a=4===i,l=[];for(let i=0;i<t.length;++i){let s=t[i];a&&(s=$o(t[i],e.width,e.height,n)),l.push(new Uint8Array(s.buffer,s.byteOffset,s.byteLength))}this._textureHelper.updateCubeTextures(l,o.underlyingResource,e.width,e.height,o.format,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0},jo.prototype.createRawCubeTextureFromUrl=function(e,t,i,n,s,r,o,a,l=null,h=null,c=3,u=!1){const d=this.createRawCubeTexture(null,i,n,s,!r,u,c,null);null==t||t.addPendingData(d),d.url=e,this._internalTexturesCache.push(d);const p=e=>{const i=d.width,r=o(e);if(!r)return;const h=[0,2,4,1,3,5];if(a){const e=4===n,t=a(r),o=d._hardwareTexture,l=[0,1,2,3,4,5];for(let n=0;n<t.length;n++){const r=i>>n,a=[];for(let i=0;i<6;i++){let o=t[n][l[i]];e&&(o=$o(o,r,r,s)),a.push(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}this._textureHelper.updateCubeTextures(a,o.underlyingResource,r,r,o.format,u,!1,0,0)}}else{const e=[];for(let t=0;t<6;t++)e.push(r[h[t]]);this.updateRawCubeTexture(d,e,n,s,u)}d.isReady=!0,null==t||t.removePendingData(d),l&&l()};return this._loadFile(e,(e=>{p(e)}),void 0,null==t?void 0:t.offlineProvider,!0,((e,i)=>{null==t||t.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)})),d},jo.prototype.createRawTexture3D=function(e,t,i,n,s,r,o,a,l=null,h=0,c=0){const u=Ei.S.Raw3D,d=new Ei.l(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=n,d.width=t,d.height=i,d.depth=n,d.format=s,d.type=h,d.generateMipMaps=r,d.samplingMode=a,d.is3D=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,c),this.updateRawTexture3D(d,e,s,o,l,h),this._internalTexturesCache.push(d),d},jo.prototype.updateRawTexture3D=function(e,t,i,n,s=null,r=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=n,e._compression=s),t){const s=e._hardwareTexture;4===i&&(t=$o(t,e.width,e.height,r));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,n,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},jo.prototype.createRawTexture2DArray=function(e,t,i,n,s,r,o,a,l=null,h=0,c=0){const u=Ei.S.Raw2DArray,d=new Ei.l(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=n,d.width=t,d.height=i,d.depth=n,d.format=s,d.type=h,d.generateMipMaps=r,d.samplingMode=a,d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,n,c),this.updateRawTexture2DArray(d,e,s,o,l,h),this._internalTexturesCache.push(d),d},jo.prototype.updateRawTexture2DArray=function(e,t,i,n,s=null,r=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=n,e._compression=s),t){const s=e._hardwareTexture;4===i&&(t=$o(t,e.width,e.height,r));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,n,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},jo.prototype._readTexturePixels=function(e,t,i,n=-1,s=0,r=null,o=!0,a=!1,l=0,h=0){const c=e._hardwareTexture;return o&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,n,s,r,a)},jo.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class Qo extends Rs.r{}jo.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const n=new Qo(e,t,i,this);return this._renderTargetWrapperCache.push(n),n},jo.prototype.createRenderTargetTexture=function(e,t){var i,n;const s=this._createHardwareRenderTargetWrapper(!1,!1,e),r={};void 0!==t&&"object"==typeof t?(r.generateMipMaps=t.generateMipMaps,r.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&t.generateStencilBuffer,r.samplingMode=void 0===t.samplingMode?3:t.samplingMode,r.creationFlags=null!==(i=t.creationFlags)&&void 0!==i?i:0,r.noColorAttachment=!!t.noColorAttachment,r.samples=t.samples,r.label=t.label):(r.generateMipMaps=t,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.samplingMode=3,r.creationFlags=0,r.noColorAttachment=!1);const o=r.noColorAttachment?null:this._createInternalTexture(e,t,!0,Ei.S.RenderTarget);return s._samples=null!==(n=r.samples)&&void 0!==n?n:1,s._generateDepthBuffer=r.generateDepthBuffer,s._generateStencilBuffer=!!r.generateStencilBuffer,s.setTextures(o),(s._generateDepthBuffer||s._generateStencilBuffer)&&s.createDepthStencilTexture(0,this._caps.textureFloatLinearFiltering&&(void 0===r.samplingMode||2===r.samplingMode||2===r.samplingMode||3===r.samplingMode||3===r.samplingMode||5===r.samplingMode||6===r.samplingMode||7===r.samplingMode||11===r.samplingMode),s._generateStencilBuffer,s.samples,r.generateStencilBuffer?13:14,r.label?r.label+"-DepthStencil":void 0),o&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!r.generateMipMaps&&(o.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(o,void 0,void 0,void 0,r.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!r.generateMipMaps&&(o.generateMipMaps=!1)),s},jo.prototype._createDepthStencilTexture=function(e,t){const i=new Ei.l(this,Ei.S.DepthStencil);i.label=t.label;const n={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};return i.format=n.depthTextureFormat,this._setupDepthStencilTexture(i,e,n.generateStencil,n.bilinearFiltering,n.comparisonFunction,n.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},jo.prototype._setupDepthStencilTexture=function(e,t,i,n,s,r=1){const o=t.width||t,a=t.height||t,l=t.layers||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=r,e.generateMipMaps=!1,e.samplingMode=n?2:1,e.type=1,e._comparisonFunction=s,e._cachedWrapU=0,e._cachedWrapV=0},jo.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},jo.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),n={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...t};n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=n.generateStencilBuffer;const s=new Ei.l(this,Ei.S.RenderTarget);return s.width=e,s.height=e,s.depth=0,s.isReady=!0,s.isCube=!0,s.samples=n.samples,s.generateMipMaps=n.generateMipMaps,s.samplingMode=n.samplingMode,s.type=n.type,s.format=n.format,this._internalTexturesCache.push(s),i.setTextures(s),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===n.samplingMode||2===n.samplingMode||2===n.samplingMode||3===n.samplingMode||3===n.samplingMode||5===n.samplingMode||6===n.samplingMode||7===n.samplingMode||11===n.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!n.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s),t&&t.createMipMaps&&!n.generateMipMaps&&(s.generateMipMaps=!1),i},ds.Q.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},jo.prototype.setTextureSampler=function(e,t){var i;null===(i=this._currentMaterialContext)||void 0===i||i.setSampler(e,t)},ds.Q.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},jo.prototype.createStorageBuffer=function(e,t){return this._createBuffer(e,32|t)},jo.prototype.updateStorageBuffer=function(e,t,i,n){const s=e;let r;void 0===i&&(i=0),void 0===n?(r=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,n=r.byteLength):r=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(s,i,r,0,n)},jo.prototype.readFromStorageBuffer=function(e,t,i,n){i=i||e.capacity;const s=this._bufferManager.createRawBuffer(i,sr.MapRead|sr.CopyDst);return this._renderTargetEncoder.copyBufferToBuffer(e.underlyingResource,null!=t?t:0,s,0,i),new Promise(((e,t)=>{this.onEndFrameObservable.addOnce((()=>{s.mapAsync(rr.Read,0,i).then((()=>{const t=s.getMappedRange(0,i);let r=n;if(void 0===r)r=new Uint8Array(i),r.set(new Uint8Array(t));else{const e=r.constructor;r=new e(r.buffer),r.set(new e(t))}s.unmap(),this._bufferManager.releaseBuffer(s),e(r)}),(e=>t(e)))}))}))},jo.prototype.setStorageBuffer=function(e,t){var i,n;null===(i=this._currentDrawContext)||void 0===i||i.setBuffer(e,null!==(n=null==t?void 0:t.getBuffer())&&void 0!==n?n:null)},jo.prototype.createUniformBuffer=function(e){let t;return t=e instanceof Array?new Float32Array(e):e,this._bufferManager.createBuffer(t,sr.Uniform|sr.CopyDst)},jo.prototype.createDynamicUniformBuffer=function(e){return this.createUniformBuffer(e)},jo.prototype.updateUniformBuffer=function(e,t,i,n){void 0===i&&(i=0);const s=e;let r;void 0===n?(r=t instanceof Float32Array?t:new Float32Array(t),n=r.byteLength):r=t instanceof Float32Array?t:new Float32Array(t),this._bufferManager.setSubData(s,i,r,0,n)},jo.prototype.bindUniformBufferBase=function(e,t,i){this._currentDrawContext.setBuffer(i,e)},jo.prototype.bindUniformBlock=function(){},jo.prototype.updateVideoTexture=function(e,t,i){var n;if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;(null===(n=e._hardwareTexture)||void 0===n?void 0:n.underlyingResource)||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),function(e){return!(!e||void 0===e.underlyingResource)}(t)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0):t&&this.createImageBitmap(t).then((t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0})).catch((()=>{e.isReady=!0}))};var Zo=i(4238);class Jo{static CreateAsync(e,t){return jo.IsSupportedAsync.then((i=>i?jo.CreateAsync(e,t):ue.D.IsSupported?new Promise((i=>{i(new ue.D(e,void 0,t))})):new Promise((e=>{e(new Is(t))}))))}}var ea=i(9884),ta=i(9953);class ia extends Vi{constructor(e){super(e),this.controllerType=zt.DAYDREAM}initControllerMesh(e,t){ta.n.ImportMesh("",ia.MODEL_BASE_URL,ia.MODEL_FILENAME,e,(e=>{this._defaultModel=e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}_handleButtonChange(e,t){if(0===e){const e=this.onTriggerStateChangedObservable;e&&e.notifyObservers(t)}else _.Y.Warn(`Unrecognized Daydream button index: ${e}`)}}ia.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",ia.MODEL_FILENAME="generic.babylon",ia.GAMEPAD_ID_PREFIX="Daydream",qt._ControllerFactories.push({canCreate:e=>0===e.id.indexOf(ia.GAMEPAD_ID_PREFIX),create:e=>new ia(e)});class na extends Vi{constructor(e){super(e),this._buttonIndexToObservableNameMap=["onPadStateChangedObservable","onTriggerStateChangedObservable"],this.controllerType=zt.GEAR_VR,this._calculatedPosition=new o.P("left"==this.hand?-.15:.15,-.5,.25),this._disableTrackPosition(this._calculatedPosition)}initControllerMesh(e,t){ta.n.ImportMesh("",na.MODEL_BASE_URL,na.MODEL_FILENAME,e,(i=>{const n=new Nt.Kj("",e);i[1].parent=n,i[1].position.z=-.15,this._defaultModel=n,this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}_handleButtonChange(e,t){if(e<this._buttonIndexToObservableNameMap.length){const i=this[this._buttonIndexToObservableNameMap[e]];i&&i.notifyObservers(t)}}}na.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",na.MODEL_FILENAME="generic.babylon",na.GAMEPAD_ID_PREFIX="Gear VR",qt._ControllerFactories.push({canCreate:e=>0===e.id.indexOf(na.GAMEPAD_ID_PREFIX)||-1!==e.id.indexOf("Oculus Go")||-1!==e.id.indexOf("Vive Focus"),create:e=>new na(e)});class sa extends Vi{constructor(e){super(e)}initControllerMesh(e,t){ta.n.ImportMesh("",sa.MODEL_BASE_URL,sa.MODEL_FILENAME,e,(e=>{this._defaultModel=e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}_handleButtonChange(e,t){console.log("Button id: "+e+"state: "),console.dir(t)}}sa.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",sa.MODEL_FILENAME="generic.babylon",qt._DefaultControllerFactory=e=>new sa(e);class ra extends Vi{constructor(e){super(e),this.onSecondaryTriggerStateChangedObservable=new r.y$,this.onThumbRestChangedObservable=new r.y$,this.controllerType=zt.OCULUS}initControllerMesh(e,t){let i;i="left"===this.hand?ra.MODEL_LEFT_FILENAME:ra.MODEL_RIGHT_FILENAME,ta.n.ImportMesh("",ra._IsQuest?ra.QUEST_MODEL_BASE_URL:ra.MODEL_BASE_URL,i,e,(e=>{this._defaultModel=ra._IsQuest?e[0]:e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}get onAButtonStateChangedObservable(){if("right"===this.hand)return this.onMainButtonStateChangedObservable;throw new Error("No A button on left hand")}get onBButtonStateChangedObservable(){if("right"===this.hand)return this.onSecondaryButtonStateChangedObservable;throw new Error("No B button on left hand")}get onXButtonStateChangedObservable(){if("left"===this.hand)return this.onMainButtonStateChangedObservable;throw new Error("No X button on right hand")}get onYButtonStateChangedObservable(){if("left"===this.hand)return this.onSecondaryButtonStateChangedObservable;throw new Error("No Y button on right hand")}_handleButtonChange(e,t){const i=t,n="right"===this.hand?-1:1;switch(e){case 0:return void this.onPadStateChangedObservable.notifyObservers(i);case 1:return!ra._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[3].rotation.x=.2*-i.value,this._defaultModel.getChildren()[3].position.y=.005*-i.value,this._defaultModel.getChildren()[3].position.z=.005*-i.value),void this.onTriggerStateChangedObservable.notifyObservers(i);case 2:return!ra._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[4].position.x=n*i.value*.0035),void this.onSecondaryTriggerStateChangedObservable.notifyObservers(i);case 3:return!ra._IsQuest&&this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[1].position.y=-.001:this._defaultModel.getChildren()[1].position.y=0),void this.onMainButtonStateChangedObservable.notifyObservers(i);case 4:return!ra._IsQuest&&this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),void this.onSecondaryButtonStateChangedObservable.notifyObservers(i);case 5:return void this.onThumbRestChangedObservable.notifyObservers(i)}}}ra.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",ra.MODEL_LEFT_FILENAME="left.babylon",ra.MODEL_RIGHT_FILENAME="right.babylon",ra.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",ra._IsQuest=!1,qt._ControllerFactories.push({canCreate:e=>(A.l.LastCreatedEngine&&A.l.LastCreatedEngine._vrDisplay&&"Oculus Quest"===A.l.LastCreatedEngine._vrDisplay.displayName&&(ra._IsQuest=!0),-1!==e.id.indexOf("Oculus Touch")),create:e=>new ra(e)});class oa extends Vi{constructor(e){super(e),this.controllerType=zt.VIVE,this._invertLeftStickY=!0}initControllerMesh(e,t){ta.n.ImportMesh("",oa.MODEL_BASE_URL,oa.MODEL_FILENAME,e,(e=>{this._defaultModel=e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}get onLeftButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onRightButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onMenuButtonStateChangedObservable(){return this.onSecondaryButtonStateChangedObservable}_handleButtonChange(e,t){const i=t;switch(e){case 0:return void this.onPadStateChangedObservable.notifyObservers(i);case 1:return this._defaultModel&&(this._defaultModel.getChildren()[6].rotation.x=.15*-i.value),void this.onTriggerStateChangedObservable.notifyObservers(i);case 2:return void this.onMainButtonStateChangedObservable.notifyObservers(i);case 3:return this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),void this.onSecondaryButtonStateChangedObservable.notifyObservers(i)}}}oa.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",oa.MODEL_FILENAME="wand.babylon",qt._ControllerFactories.push({canCreate:e=>-1!==e.id.toLowerCase().indexOf("openvr"),create:e=>new oa(e)});class aa{constructor(){this.buttonMeshes={},this.axisMeshes={}}}class la extends Vi{constructor(e){super(e),this._mapping={buttons:["thumbstick","trigger","grip","menu","trackpad"],buttonMeshNames:{trigger:"SELECT",menu:"MENU",grip:"GRASP",thumbstick:"THUMBSTICK_PRESS",trackpad:"TOUCHPAD_PRESS"},buttonObservableNames:{trigger:"onTriggerStateChangedObservable",menu:"onSecondaryButtonStateChangedObservable",grip:"onMainButtonStateChangedObservable",thumbstick:"onPadStateChangedObservable",trackpad:"onTrackpadChangedObservable"},axisMeshNames:["THUMBSTICK_X","THUMBSTICK_Y","TOUCHPAD_TOUCH_X","TOUCHPAD_TOUCH_Y"],pointingPoseMeshName:Kt.POINTING_POSE},this.onTrackpadChangedObservable=new r.y$,this.onTrackpadValuesChangedObservable=new r.y$,this.trackpad={x:0,y:0},this.controllerType=zt.WINDOWS,this._loadedMeshInfo=null}get onTriggerButtonStateChangedObservable(){return this.onTriggerStateChangedObservable}get onMenuButtonStateChangedObservable(){return this.onSecondaryButtonStateChangedObservable}get onGripButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onThumbstickButtonStateChangedObservable(){return this.onPadStateChangedObservable}get onTouchpadButtonStateChangedObservable(){return this.onTrackpadChangedObservable}get onTouchpadValuesChangedObservable(){return this.onTrackpadValuesChangedObservable}_updateTrackpad(){!this.browserGamepad.axes||this.browserGamepad.axes[2]==this.trackpad.x&&this.browserGamepad.axes[3]==this.trackpad.y||(this.trackpad.x=this.browserGamepad.axes[this._mapping.axisMeshNames.indexOf("TOUCHPAD_TOUCH_X")],this.trackpad.y=this.browserGamepad.axes[this._mapping.axisMeshNames.indexOf("TOUCHPAD_TOUCH_Y")],this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad))}update(){if(super.update(),this.browserGamepad.axes&&(this._updateTrackpad(),this._loadedMeshInfo))for(let e=0;e<this._mapping.axisMeshNames.length;e++)this._lerpAxisTransform(e,this.browserGamepad.axes[e])}_handleButtonChange(e,t){const i=this._mapping.buttons[e];if(!i)return;this._updateTrackpad();const n=this[this._mapping.buttonObservableNames[i]];n&&n.notifyObservers(t),this._lerpButtonTransform(i,t.value)}_lerpButtonTransform(e,t){if(!this._loadedMeshInfo)return;const i=this._loadedMeshInfo.buttonMeshes[e];i&&i.unpressed.rotationQuaternion&&i.pressed.rotationQuaternion&&i.value.rotationQuaternion&&(o._f.SlerpToRef(i.unpressed.rotationQuaternion,i.pressed.rotationQuaternion,t,i.value.rotationQuaternion),o.P.LerpToRef(i.unpressed.position,i.pressed.position,t,i.value.position))}_lerpAxisTransform(e,t){if(!this._loadedMeshInfo)return;const i=this._loadedMeshInfo.axisMeshes[e];if(!i)return;if(!i.min.rotationQuaternion||!i.max.rotationQuaternion||!i.value.rotationQuaternion)return;const n=.5*t+.5;o._f.SlerpToRef(i.min.rotationQuaternion,i.max.rotationQuaternion,n,i.value.rotationQuaternion),o.P.LerpToRef(i.min.position,i.max.position,n,i.value.position)}initControllerMesh(e,t,i=!1){let n,s;if(ta.n.IsPluginForExtensionAvailable(".glb")){let e="default";if(this.id&&!i){const t=this.id.match(la.GAMEPAD_ID_PATTERN);e=t&&t[0]||e}s="left"===this.hand?la.MODEL_LEFT_FILENAME:la.MODEL_RIGHT_FILENAME,n=la.MODEL_BASE_URL+e+"/"}else _.Y.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models"),n=sa.MODEL_BASE_URL,s=sa.MODEL_FILENAME;ta.n.ImportMesh("",n,s,e,(i=>{this._loadedMeshInfo=this._processModel(e,i),this._loadedMeshInfo&&(this._defaultModel=this._loadedMeshInfo.rootNode,this.attachToMesh(this._defaultModel),t&&t(this._defaultModel))}),null,((e,r)=>{_.Y.Log(r),_.Y.Warn("Failed to retrieve controller model from the remote server: "+n+s),i||this.initControllerMesh(e,t,!0)}))}_processModel(e,t){let i=null;const n=new Nt.Kj(this.id+" "+this.hand,e);let s=null;for(let e=0;e<t.length;e++){const i=t[e];if(!i.parent){i.isPickable=!1,s=i;break}}return s?(s.setParent(n),i=this._createMeshInfo(n)):_.Y.Warn("Could not find root node in model file."),i}_createMeshInfo(e){const t=new aa;let i;for(t.rootNode=e,t.buttonMeshes={},t.axisMeshes={},i=0;i<this._mapping.buttons.length;i++){const r=this._mapping.buttonMeshNames[this._mapping.buttons[i]];if(!r){_.Y.Log("Skipping unknown button at index: "+i+" with mapped name: "+this._mapping.buttons[i]);continue}const o=n(e,r);if(!o){_.Y.Warn("Missing button mesh with name: "+r);continue}const a={index:i,value:s(o,"VALUE"),pressed:s(o,"PRESSED"),unpressed:s(o,"UNPRESSED")};a.value&&a.pressed&&a.unpressed?t.buttonMeshes[this._mapping.buttons[i]]=a:_.Y.Warn("Missing button submesh under mesh with name: "+r+"(VALUE: "+!!a.value+", PRESSED: "+!!a.pressed+", UNPRESSED:"+!!a.unpressed+")")}for(i=0;i<this._mapping.axisMeshNames.length;i++){const r=this._mapping.axisMeshNames[i];if(!r){_.Y.Log("Skipping unknown axis at index: "+i);continue}const o=n(e,r);if(!o){_.Y.Warn("Missing axis mesh with name: "+r);continue}const a={index:i,value:s(o,"VALUE"),min:s(o,"MIN"),max:s(o,"MAX")};a.value&&a.min&&a.max?t.axisMeshes[i]=a:_.Y.Warn("Missing axis submesh under mesh with name: "+r+"(VALUE: "+!!a.value+", MIN: "+!!a.min+", MAX:"+!!a.max+")")}return t.pointingPoseNode=n(e,this._mapping.pointingPoseMeshName),t.pointingPoseNode?this._pointingPoseNode=t.pointingPoseNode:_.Y.Warn("Missing pointing pose mesh with name: "+this._mapping.pointingPoseMeshName),t;function n(e,t){return e.getChildren((e=>e.name===t),!1)[0]}function s(e,t){return e.getChildren((e=>e.name==t),!0)[0]}}getForwardRay(e=100){if(!this._loadedMeshInfo||!this._loadedMeshInfo.pointingPoseNode)return super.getForwardRay(e);const t=this._loadedMeshInfo.pointingPoseNode.getWorldMatrix(),i=t.getTranslation(),n=new o.P(0,0,-1),s=o.P.TransformNormal(n,t),r=o.P.Normalize(s);return new Yt.z(i,r,e)}dispose(){super.dispose(),this.onTrackpadChangedObservable.clear(),this.onTrackpadValuesChangedObservable.clear()}}la.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/",la.MODEL_LEFT_FILENAME="left.glb",la.MODEL_RIGHT_FILENAME="right.glb",la.GAMEPAD_ID_PREFIX="Spatial Controller (Spatial Interaction Source) ",la.GAMEPAD_ID_PATTERN=/([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;class ha extends la{constructor(e){super(e),this._mapping={buttons:["trigger","grip","trackpad","thumbstick","menu"],buttonMeshNames:{trigger:"SELECT",menu:"MENU",grip:"GRASP",thumbstick:"THUMBSTICK_PRESS",trackpad:"TOUCHPAD_PRESS"},buttonObservableNames:{trigger:"onTriggerStateChangedObservable",menu:"onSecondaryButtonStateChangedObservable",grip:"onMainButtonStateChangedObservable",thumbstick:"onThumbstickStateChangedObservable",trackpad:"onTrackpadChangedObservable"},axisMeshNames:["TOUCHPAD_TOUCH_X","TOUCHPAD_TOUCH_Y","THUMBSTICK_X","THUMBSTICK_Y"],pointingPoseMeshName:Kt.POINTING_POSE},this.thumbstickValues={x:0,y:0},this.onThumbstickStateChangedObservable=new r.y$,this.onThumbstickValuesChangedObservable=new r.y$,this.onTrackpadChangedObservable=this.onPadStateChangedObservable,this.onTrackpadValuesChangedObservable=this.onPadValuesChangedObservable}get onThumbstickButtonStateChangedObservable(){return this.onThumbstickStateChangedObservable}_updateTrackpad(){!this.browserGamepad.axes||this.browserGamepad.axes[2]==this.thumbstickValues.x&&this.browserGamepad.axes[3]==this.thumbstickValues.y||(this.trackpad.x=this.browserGamepad.axes[2],this.trackpad.y=this.browserGamepad.axes[3],this.onThumbstickValuesChangedObservable.notifyObservers(this.trackpad))}dispose(){super.dispose(),this.onThumbstickStateChangedObservable.clear(),this.onThumbstickValuesChangedObservable.clear()}}qt._ControllerFactories.push({canCreate:e=>0===e.id.indexOf(la.GAMEPAD_ID_PREFIX),create:e=>new la(e)});class ca extends Gn.t{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=a.Wo.Gray(),i=zn.x.DefaultUtilityLayer,n=null,s=1){var l,h,c,u,d,p,f;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new r.y$,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new o.P(0,0,0),this._parent=n,this._coloredMaterial=new Gi.K("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new a.Wo(.1,.1,.1)),this._hoverMaterial=new Gi.K("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a.Wo.Yellow(),this._disableMaterial=new Gi.K("",i.utilityLayerScene),this._disableMaterial.diffuseColor=a.Wo.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=new Nt.Kj("axis",i.utilityLayerScene);const{arrowMesh:_,arrowTail:m}=this._createGizmoMesh(this._gizmoMesh,s),g=this._createGizmoMesh(this._gizmoMesh,s+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,Gn.t.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const v=_.position.clone(),y=m.position.clone(),x=m.scaling.clone(),b=e=>{const t=e*(3/this._rootMesh.scaling.length())*6;_.position.z+=t/3.5,m.scaling.y+=t,this.dragScale=m.scaling.y,m.position.z=_.position.z/2},T=()=>{_.position.set(v.x,v.y,v.z),m.position.set(y.x,y.y,y.z),m.scaling.set(x.x,x.y,x.z),this.dragScale=m.scaling.y,this._dragging=!1};this.dragBehavior=new Le.M({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let S=0;const E={snapDistance:0};this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){this._handlePivot();const i=this.sensitivity*t.dragDistance*(3*this.scaleRatio/this._rootMesh.scaling.length()),n=this._tmpVector;let s=!1,r=0;this.uniformScaling?n.setAll(.57735):n.copyFrom(e),0==this.snapDistance?n.scaleToRef(i,n):(S+=i,Math.abs(S)>this.snapDistance?(r=Math.floor(Math.abs(S)/this.snapDistance),S<0&&(r*=-1),S%=this.snapDistance,n.scaleToRef(this.snapDistance*r,n),s=!0):n.scaleInPlace(0)),o.y3.ScalingToRef(1+n.x,1+n.y,1+n.z,o.jp.Matrix[2]),o.jp.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),o.jp.Matrix[1]);const a=this.attachedNode._isMesh?this.attachedNode:void 0;o.jp.Matrix[1].decompose(o.jp.Vector3[1],void 0,void 0,Gn.t.PreserveScaling?a:void 0);const l=1e5;Math.abs(o.jp.Vector3[1].x)<l&&Math.abs(o.jp.Vector3[1].y)<l&&Math.abs(o.jp.Vector3[1].z)<l&&this.attachedNode.getWorldMatrix().copyFrom(o.jp.Matrix[1]),s&&(E.snapDistance=this.snapDistance*r,this.onSnapObservable.notifyObservers(E)),this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragObservable.add((e=>b(e.dragDistance))),this.dragBehavior.onDragEndObservable.add(T),null===(c=null===(h=null===(l=null==n?void 0:n.uniformScaleGizmo)||void 0===l?void 0:l.dragBehavior)||void 0===h?void 0:h.onDragObservable)||void 0===c||c.add((e=>b(e.delta.y))),null===(p=null===(d=null===(u=null==n?void 0:n.uniformScaleGizmo)||void 0===u?void 0:u.dragBehavior)||void 0===d?void 0:d.onDragEndObservable)||void 0===p||p.add(T);const C={gizmoMeshes:[_,m],colliderMeshes:[g.arrowMesh,g.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(f=this._parent)||void 0===f||f.addToAxisCache(this._gizmoMesh,C),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{var t;if(!this._customMeshSet&&(this._isHovered=!(-1==C.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh)),!this._parent)){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(C.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(C.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}));const A=i._getSharedGizmoLight();A.includedOnlyMeshes=A.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const n=(0,Yn.NR)("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),s=an("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return n.scaling.scaleInPlace(.1),n.material=this._coloredMaterial,n.rotation.x=Math.PI/2,n.position.z+=.3,s.material=this._coloredMaterial,s.position.z+=.1375,s.rotation.x=Math.PI/2,i&&(n.visibility=0,s.visibility=0),e.addChild(n),e.addChild(s),{arrowMesh:n,arrowTail:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach((e=>{e.material=this._coloredMaterial,e.color&&(e.color=this._coloredMaterial.diffuseColor)})),this._customMeshSet=!1)}}var ua=i(6746);class da extends Gn.t{set axisFactor(e){this._axisFactor=e;const t=this._scaleBoxesParent.getChildMeshes();let i=0;for(let e=0;e<3;e++)for(let n=0;n<3;n++)for(let s=0;s<3;s++){const r=(1===e?1:0)+(1===n?1:0)+(1===s?1:0);if(1!==r&&3!==r){if(t[i]){const r=new o.P(e-1,n-1,s-1);r.multiplyInPlace(this._axisFactor),t[i].setEnabled(r.lengthSquared()>Me.kn)}i++}}}get axisFactor(){return this._axisFactor}set scaleDragSpeed(e){this._scaleDragSpeed=e}get scaleDragSpeed(){return this._scaleDragSpeed}get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverColoredMaterial}get pointerDragBehavior(){return this._pointerDragBehavior}setColor(e){this._coloredMaterial.emissiveColor=e,this._hoverColoredMaterial.emissiveColor=e.clone().add(new a.Wo(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach((t=>{t.color&&(t.color=e)}))}constructor(e=a.Wo.Gray(),t=zn.x.DefaultKeepDepthUtilityLayer){super(t),this._boundingDimensions=new o.P(1,1,1),this._renderObserver=null,this._pointerObserver=null,this._scaleDragSpeed=.2,this._tmpQuaternion=new o._f,this._tmpVector=new o.P(0,0,0),this._tmpRotationMatrix=new o.y3,this.ignoreChildren=!1,this.includeChildPredicate=null,this.rotationSphereSize=.1,this.scaleBoxSize=.1,this.fixedDragMeshScreenSize=!1,this.fixedDragMeshBoundsSize=!1,this.fixedDragMeshScreenSizeDistanceFactor=10,this.onDragStartObservable=new r.y$,this.onScaleBoxDragObservable=new r.y$,this.onScaleBoxDragEndObservable=new r.y$,this.onRotationSphereDragObservable=new r.y$,this.onRotationSphereDragEndObservable=new r.y$,this.scalePivot=null,this._axisFactor=new o.P(1,1,1),this._existingMeshScale=new o.P,this._dragMesh=null,this._pointerDragBehavior=new Le.M,this.updateScale=!1,this._anchorMesh=new Un.x("anchor",t.utilityLayerScene),this._coloredMaterial=new Gi.K("",t.utilityLayerScene),this._coloredMaterial.disableLighting=!0,this._hoverColoredMaterial=new Gi.K("",t.utilityLayerScene),this._hoverColoredMaterial.disableLighting=!0,this._lineBoundingBox=new Un.x("",t.utilityLayerScene),this._lineBoundingBox.rotationQuaternion=new o._f;const i=[];i.push(os("lines",{points:[new o.P(0,0,0),new o.P(this._boundingDimensions.x,0,0)]},t.utilityLayerScene)),i.push(os("lines",{points:[new o.P(0,0,0),new o.P(0,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(os("lines",{points:[new o.P(0,0,0),new o.P(0,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(os("lines",{points:[new o.P(this._boundingDimensions.x,0,0),new o.P(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(os("lines",{points:[new o.P(this._boundingDimensions.x,0,0),new o.P(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(os("lines",{points:[new o.P(0,this._boundingDimensions.y,0),new o.P(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(os("lines",{points:[new o.P(0,this._boundingDimensions.y,0),new o.P(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(os("lines",{points:[new o.P(0,0,this._boundingDimensions.z),new o.P(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(os("lines",{points:[new o.P(0,0,this._boundingDimensions.z),new o.P(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(os("lines",{points:[new o.P(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new o.P(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(os("lines",{points:[new o.P(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new o.P(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(os("lines",{points:[new o.P(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new o.P(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.forEach((t=>{t.color=e,t.position.addInPlace(new o.P(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),t.isPickable=!1,this._lineBoundingBox.addChild(t)})),this._rootMesh.addChild(this._lineBoundingBox),this.setColor(e),this._rotateSpheresParent=new Un.x("",t.utilityLayerScene),this._rotateSpheresParent.rotationQuaternion=new o._f;for(let e=0;e<12;e++){const i=Kn("",{diameter:1},t.utilityLayerScene);i.rotationQuaternion=new o._f,i.material=this._coloredMaterial,i.isNearGrabbable=!0;const n=new Le.M({});n.moveAttached=!1,n.updateDragPlane=!1,i.addBehavior(n);const s=new o.P(1,0,0);let r=0;n.onDragStartObservable.add((()=>{s.copyFrom(i.forward),r=0})),n.onDragObservable.add((t=>{if(this.onRotationSphereDragObservable.notifyObservers({}),this.attachedMesh){const i=this.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void _.Y.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");ua.m._RemoveAndStorePivotPoint(this.attachedMesh);const n=s,a=t.dragPlaneNormal.scale(o.P.Dot(t.dragPlaneNormal,n)),l=n.subtract(a).normalizeToNew();let h=o.P.Dot(l,t.delta)<0?Math.abs(t.delta.length()):-Math.abs(t.delta.length());h=h/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=o._f.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=o._f.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),r+=h,Math.abs(r)<=2*Math.PI&&(e>=8?o._f.RotationYawPitchRollToRef(0,0,h,this._tmpQuaternion):e>=4?o._f.RotationYawPitchRollToRef(h,0,0,this._tmpQuaternion):o._f.RotationYawPitchRollToRef(0,h,0,this._tmpQuaternion),this._anchorMesh.addChild(this.attachedMesh,Gn.t.PreserveScaling),this._anchorMesh.getScene().useRightHandedSystem&&this._tmpQuaternion.conjugateInPlace(),this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion,this._anchorMesh.rotationQuaternion),this._anchorMesh.removeChild(this.attachedMesh,Gn.t.PreserveScaling),this.attachedMesh.setParent(i,Gn.t.PreserveScaling)),this.updateBoundingBox(),ua.m._RestorePivotPoint(this.attachedMesh)}this._updateDummy()})),n.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({}),this._selectNode(i)})),n.onDragEndObservable.add((e=>{this.onRotationSphereDragEndObservable.notifyObservers({}),this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,i)})),this._rotateSpheresParent.addChild(i)}this._rootMesh.addChild(this._rotateSpheresParent),this._scaleBoxesParent=new Un.x("",t.utilityLayerScene),this._scaleBoxesParent.rotationQuaternion=new o._f;for(let e=0;e<3;e++)for(let i=0;i<3;i++)for(let n=0;n<3;n++){const s=(1===e?1:0)+(1===i?1:0)+(1===n?1:0);if(1===s||3===s)continue;const r=(0,Yn.NR)("",{size:1},t.utilityLayerScene);r.material=this._coloredMaterial,r._internalMetadata=2===s,r.isNearGrabbable=!0;const a=new o.P(e-1,i-1,n-1).normalize(),l=new Le.M({dragAxis:a});l.updateDragPlane=!1,l.moveAttached=!1,r.addBehavior(l),l.onDragObservable.add((e=>{if(this.onScaleBoxDragObservable.notifyObservers({}),this.attachedMesh){const t=this.attachedMesh.parent;if(t&&t.scaling&&t.scaling.isNonUniformWithinEpsilon(.001))return void _.Y.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");ua.m._RemoveAndStorePivotPoint(this.attachedMesh);const i=e.dragDistance/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),n=new o.P(i,i,i);2===s&&(n.x*=Math.abs(a.x),n.y*=Math.abs(a.y),n.z*=Math.abs(a.z)),n.scaleInPlace(this._scaleDragSpeed),n.multiplyInPlace(this._axisFactor),this.updateBoundingBox(),this.scalePivot?(this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix),this._boundingDimensions.scaleToRef(.5,this._tmpVector),o.P.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this._boundingDimensions.multiplyToRef(this.scalePivot,this._tmpVector),o.P.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.addInPlace(this._tmpVector)):(r.absolutePosition.subtractToRef(this._anchorMesh.position,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector)),this._anchorMesh.addChild(this.attachedMesh,Gn.t.PreserveScaling),this._anchorMesh.scaling.addInPlace(n),(this._anchorMesh.scaling.x<0||this._anchorMesh.scaling.y<0||this._anchorMesh.scaling.z<0)&&this._anchorMesh.scaling.subtractInPlace(n),this._anchorMesh.removeChild(this.attachedMesh,Gn.t.PreserveScaling),this.attachedMesh.setParent(t,Gn.t.PreserveScaling),ua.m._RestorePivotPoint(this.attachedMesh)}this._updateDummy()})),l.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({}),this._selectNode(r)})),l.onDragEndObservable.add((e=>{this.onScaleBoxDragEndObservable.notifyObservers({}),this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,r)})),this._scaleBoxesParent.addChild(r)}this._rootMesh.addChild(this._scaleBoxesParent);const n=new Array;this._pointerObserver=t.utilityLayerScene.onPointerObservable.add((e=>{n[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=n[e.event.pointerId]&&(n[e.event.pointerId].material=this._coloredMaterial,delete n[e.event.pointerId]):this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{e.pickInfo&&e.pickInfo.pickedMesh==t&&(n[e.event.pointerId]=t,t.material=this._hoverColoredMaterial)}))})),this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingMeshScale.equals(this.attachedMesh.scaling)?this.updateBoundingBox():(this.fixedDragMeshScreenSize||this.fixedDragMeshBoundsSize)&&(this._updateRotationSpheres(),this._updateScaleBoxes()),this._dragMesh&&this.attachedMesh&&this._pointerDragBehavior.dragging&&(this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion,this._tmpVector),this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1))))})),this.updateBoundingBox()}_attachedNodeChanged(e){if(e){this._anchorMesh.scaling.setAll(1),ua.m._RemoveAndStorePivotPoint(e);const t=e.parent;this._anchorMesh.addChild(e,Gn.t.PreserveScaling),this._anchorMesh.removeChild(e,Gn.t.PreserveScaling),e.setParent(t,Gn.t.PreserveScaling),ua.m._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach((e=>{e.markAsDirty("scaling")})),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce((()=>{this._updateDummy()}))}}_selectNode(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{t.isVisible=!e||t==e}))}_unhoverMeshOnTouchUp(e,t){(null==e?void 0:e.event)instanceof PointerEvent&&"touch"===(null==e?void 0:e.event.pointerType)&&(t.material=this._coloredMaterial)}getScaleBoxes(){return this._scaleBoxesParent.getChildMeshes()}updateBoundingBox(){if(this.attachedMesh){ua.m._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null,Gn.t.PreserveScaling),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=o._f.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=o._f.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e,Gn.t.PreserveScaling)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),ua.m._RestorePivotPoint(this.attachedMesh))}_updateRotationSpheres(){const e=this._rotateSpheresParent.getChildMeshes();for(let t=0;t<3;t++)for(let i=0;i<2;i++)for(let n=0;n<2;n++){const s=4*t+2*i+n;if(0==t&&(e[s].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*i,this._boundingDimensions.z*n),e[s].position.addInPlace(new o.P(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[s].lookAt(o.P.Cross(e[s].position.normalizeToNew(),o.P.Right()).normalizeToNew().add(e[s].position))),1==t&&(e[s].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y/2,this._boundingDimensions.z*n),e[s].position.addInPlace(new o.P(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[s].lookAt(o.P.Cross(e[s].position.normalizeToNew(),o.P.Up()).normalizeToNew().add(e[s].position))),2==t&&(e[s].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y*n,this._boundingDimensions.z/2),e[s].position.addInPlace(new o.P(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[s].lookAt(o.P.Cross(e[s].position.normalizeToNew(),o.P.Forward()).normalizeToNew().add(e[s].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const t=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[s].scaling.set(t,t,t)}else this.fixedDragMeshBoundsSize?e[s].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[s].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}}_updateScaleBoxes(){const e=this._scaleBoxesParent.getChildMeshes();let t=0;for(let i=0;i<3;i++)for(let n=0;n<3;n++)for(let s=0;s<3;s++){const r=(1===i?1:0)+(1===n?1:0)+(1===s?1:0);if(1!==r&&3!==r){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(n/2),this._boundingDimensions.z*(s/2)),e[t].position.addInPlace(new o.P(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[t].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const i=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[t].scaling.set(i,i,i)}else this.fixedDragMeshBoundsSize?e[t].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[t].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);t++}}}setEnabledRotationAxis(e){this._rotateSpheresParent.getChildMeshes().forEach(((t,i)=>{i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))}setEnabledScaling(e,t=!1){this._scaleBoxesParent.getChildMeshes().forEach((i=>{let n=e;t&&!0===i._internalMetadata&&(n=!1),i.setEnabled(n)}))}_updateDummy(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))}enableDragBehavior(){this._dragMesh=(0,Yn.NR)("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new o._f,this._pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this._pointerDragBehavior)}dispose(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),super.dispose()}static MakeNotPickableAndWrapInBoundingBox(e){const t=e=>{e.isPickable=!1,e.getChildMeshes().forEach((e=>{t(e)}))};t(e),e.rotationQuaternion||(e.rotationQuaternion=o._f.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));const i=e.position.clone(),n=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);const s=(0,Yn.NR)("box",{size:1},e.getScene()),r=e.getHierarchyBoundingVectors();return r.max.subtractToRef(r.min,s.scaling),0===s.scaling.y&&(s.scaling.y=Me.kn),0===s.scaling.x&&(s.scaling.x=Me.kn),0===s.scaling.z&&(s.scaling.z=Me.kn),s.position.set((r.max.x+r.min.x)/2,(r.max.y+r.min.y)/2,(r.max.z+r.min.z)/2),e.addChild(s),e.rotationQuaternion.copyFrom(n),e.position.copyFrom(i),e.removeChild(s),s.addChild(e),s.visibility=0,s}setCustomMesh(){_.Y.Error("Custom meshes are not supported on this gizmo")}}var pa=i(3615);class fa extends Gn.t{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=a.Wo.Gray(),i=zn.x.DefaultUtilityLayer,n=32,s=null,l=!1,h=1){var c;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new r.y$,this.angle=0,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new o.P,this._parent=s,this._coloredMaterial=new Gi.K("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new a.Wo(.1,.1,.1)),this._hoverMaterial=new Gi.K("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a.Wo.Yellow(),this._disableMaterial=new Gi.K("",i.utilityLayerScene),this._disableMaterial.diffuseColor=a.Wo.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=new Nt.Kj("",i.utilityLayerScene);const{rotationMesh:u,collider:d}=this._createGizmoMesh(this._gizmoMesh,h,n);this._rotationDisplayPlane=(0,pa.pT)("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),ds.Q.ShadersStore.rotationGizmoVertexShader=fa._RotationGizmoVertexShader,ds.Q.ShadersStore.rotationGizmoFragmentShader=fa._RotationGizmoFragmentShader,this._rotationShaderMaterial=new us.j("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles"]}),this._rotationShaderMaterial.backFaceCulling=!1,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,Gn.t.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new Le.M({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=fa.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const p=new o.P,f=new o.y3,m=new o.P;let g=new o.P;this.dragBehavior.onDragStartObservable.add((e=>{this.attachedNode&&(p.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(f),o.P.TransformCoordinatesToRef(e.dragPlanePoint,f,p),this._angles.x=Math.atan2(p.y,p.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,p.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)}));const v={snapDistance:0};let y=0;const x=new o.y3,b=new o._f;this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const n=new o.P(1,1,1),s=new o._f(0,0,0,1),r=new o.P(0,0,0);if(this._handlePivot(),this.attachedNode.getWorldMatrix().decompose(n,s,r),!(Math.abs(Math.abs(n.x)-Math.abs(n.y))<=Me.kn&&Math.abs(Math.abs(n.x)-Math.abs(n.z))<=Me.kn)&&this.updateGizmoRotationToMatchAttachedMesh)return void _.Y.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");s.normalize();const a=this.updateGizmoPositionToMatchAttachedMesh?r:this._rootMesh.absolutePosition,l=t.dragPlanePoint.subtract(a).normalize(),h=p.subtract(a).normalize(),c=o.P.Cross(l,h),u=o.P.Dot(l,h);let d=Math.atan2(c.length(),u);m.copyFrom(e),g.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(f),g=o.P.TransformCoordinates(m,f));let T=!1;if(i.utilityLayerScene.activeCamera){const e=i.utilityLayerScene.activeCamera.position.subtract(a).normalize();o.P.Dot(e,g)>0&&(m.scaleInPlace(-1),g.scaleInPlace(-1),T=!0)}o.P.Dot(g,c)>0&&(d=-d);let S=!1;if(0!=this.snapDistance)if(y+=d,Math.abs(y)>this.snapDistance){let e=Math.floor(Math.abs(y)/this.snapDistance);y<0&&(e*=-1),y%=this.snapDistance,d=this.snapDistance*e,S=!0}else d=0;const E=Math.sin(d/2);if(b.set(m.x*E,m.y*E,m.z*E,Math.cos(d/2)),x.determinant()>0){const e=new o.P;b.toEulerAnglesToRef(e),o._f.RotationYawPitchRollToRef(e.y,-e.x,-e.z,b)}this.updateGizmoRotationToMatchAttachedMesh?(s.multiplyToRef(b,s),o.y3.ComposeToRef(n,s,r,this.attachedNode.getWorldMatrix())):(b.toRotationMatrix(o.jp.Matrix[0]),o.jp.Matrix[0].multiplyToRef(this.attachedNode.getWorldMatrix(),this.attachedNode.getWorldMatrix())),p.copyFrom(t.dragPlanePoint),S&&(v.snapDistance=d,this.onSnapObservable.notifyObservers(v)),this._angles.y+=d,this.angle+=T?-d:d,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}}));const T=i._getSharedGizmoLight();T.includedOnlyMeshes=T.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const S={colliderMeshes:[d],gizmoMeshes:[u],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(c=this._parent)||void 0===c||c.addToAxisCache(this._gizmoMesh,S),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{var t;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=fa.MaxDragAngle,this._isHovered=!(-1==S.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh)),!this._parent)){const e=S.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(S.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(S.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_createGizmoMesh(e,t,i){const n=cn("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);n.visibility=0;const s=cn("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,n.rotation.x=Math.PI/2,e.addChild(s,Gn.t.PreserveScaling),e.addChild(n,Gn.t.PreserveScaling),{rotationMesh:s,collider:n}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}fa.MaxDragAngle=9*Math.PI/20,fa._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",fa._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n #define twopi 6.283185307\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity;\n }";class _a extends Gn.t{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}_checkBillboardTransform(){this._nodeAttached&&this._nodeAttached.billboardMode&&console.log("Rotation Gizmo will not work with transforms in billboard mode.")}get isHovered(){let e=!1;return[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{e=e||t.isHovered})),e}constructor(e=zn.x.DefaultUtilityLayer,t=32,i=!1,n=1,s,l){super(e),this.onDragStartObservable=new r.y$,this.onDragEndObservable=new r.y$,this._observables=[],this._gizmoAxisCache=new Map;const h=l&&l.xOptions&&l.xOptions.color?l.xOptions.color:a.Wo.Red().scale(.5),c=l&&l.yOptions&&l.yOptions.color?l.yOptions.color:a.Wo.Green().scale(.5),u=l&&l.zOptions&&l.zOptions.color?l.zOptions.color:a.Wo.Blue().scale(.5);this.xGizmo=new fa(new o.P(1,0,0),h,e,t,this,i,n),this.yGizmo=new fa(new o.P(0,1,0),c,e,t,this,i,n),this.zGizmo=new fa(new o.P(0,0,1),u,e,t,this,i,n),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((e=>{l&&null!=l.updateScale&&(e.updateScale=l.updateScale),e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,s?s.addToAxisCache(this._gizmoAxisCache):Gn.t.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set updateGizmoRotationToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)}get updateGizmoRotationToMatchAttachedMesh(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.yGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.zGizmo.updateGizmoPositionToMatchAttachedMesh=e)}get updateGizmoPositionToMatchAttachedMesh(){return this.xGizmo.updateGizmoPositionToMatchAttachedMesh}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)}get snapDistance(){return this.xGizmo.snapDistance}set scaleRatio(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)}get scaleRatio(){return this.xGizmo.scaleRatio}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}dispose(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)}))}setCustomMesh(){_.Y.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")}}class ma extends Gn.t{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreatePlane(e,t){const i=new yi.Y("plane",e),n=(0,pa.pT)("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return n.material=t,n.parent=i,i}constructor(e,t=a.Wo.Gray(),i=zn.x.DefaultUtilityLayer,n=null){var s;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new r.y$,this._isEnabled=!1,this._parent=null,this._dragging=!1,this._parent=n,this._coloredMaterial=new Gi.K("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new a.Wo(.1,.1,.1)),this._hoverMaterial=new Gi.K("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a.Wo.Yellow(),this._disableMaterial=new Gi.K("",i.utilityLayerScene),this._disableMaterial.diffuseColor=a.Wo.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=ma._CreatePlane(i.utilityLayerScene,this._coloredMaterial),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let l=0;const h=new o.P,c={snapDistance:0};this.dragBehavior=new Le.M({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){if(this._handlePivot(),0==this.snapDistance)this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z);else if(l+=e.dragDistance,Math.abs(l)>this.snapDistance){const t=Math.floor(Math.abs(l)/this.snapDistance);l%=this.snapDistance,e.delta.normalizeToRef(h),h.scaleInPlace(this.snapDistance*t),this.attachedNode.getWorldMatrix().addTranslationFromFloats(h.x,h.y,h.z),c.snapDistance=this.snapDistance*t,this.onSnapObservable.notifyObservers(c)}this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const u=i._getSharedGizmoLight();u.includedOnlyMeshes=u.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const d={gizmoMeshes:this._gizmoMesh.getChildMeshes(),colliderMeshes:this._gizmoMesh.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(s=this._parent)||void 0===s||s.addToAxisCache(this._gizmoMesh,d),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{var t;if(!this._customMeshSet&&(this._isHovered=!(-1==d.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh)),!this._parent)){const e=d.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(d.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(d.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),super.dispose(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class ga extends Gn.t{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}get isHovered(){let e=!1;return[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{e=e||t.isHovered})),e}constructor(e=zn.x.DefaultUtilityLayer,t=1,i){super(e),this._meshAttached=null,this._nodeAttached=null,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new r.y$,this.onDragEndObservable=new r.y$,this._planarGizmoEnabled=!1,this.xGizmo=new Wn(new o.P(1,0,0),a.Wo.Red().scale(.5),e,this,t),this.yGizmo=new Wn(new o.P(0,1,0),a.Wo.Green().scale(.5),e,this,t),this.zGizmo=new Wn(new o.P(0,0,1),a.Wo.Blue().scale(.5),e,this,t),this.xPlaneGizmo=new ma(new o.P(1,0,0),a.Wo.Red().scale(.5),this.gizmoLayer,this),this.yPlaneGizmo=new ma(new o.P(0,1,0),a.Wo.Green().scale(.5),this.gizmoLayer,this),this.zPlaneGizmo=new ma(new o.P(0,0,1),a.Wo.Blue().scale(.5),this.gizmoLayer,this),[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,i?i.addToAxisCache(this._gizmoAxisCache):Gn.t.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set planarGizmoEnabled(e){this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.isEnabled=e,e&&(t.attachedMesh?t.attachedMesh=this.attachedMesh:t.attachedNode=this.attachedNode))}),this)}get planarGizmoEnabled(){return this._planarGizmoEnabled}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoPositionToMatchAttachedMesh=e)}))}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragEndObservable.clear()}setCustomMesh(){_.Y.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")}}function va(e){const t=[];t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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 i=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,n=e.size,s=e.sizeX||n||1,r=e.sizeY||n||1,l=e.sizeZ||n||1,h=e.custom||t[i],c=h.face.length,u=e.faceUV||new Array(c),d=e.faceColors,p=void 0===e.flat||e.flat,f=0===e.sideOrientation?0:e.sideOrientation||sn.x.DEFAULTSIDE,_=new Array,m=new Array,g=new Array,v=new Array,y=new Array;let x=0,b=0;const T=new Array;let S,E,C,A,P,R,M=0,I=0;if(p)for(I=0;I<c;I++)d&&void 0===d[I]&&(d[I]=new a.HE(1,1,1,1)),u&&void 0===u[I]&&(u[I]=new o.Lt(0,0,1,1));if(p)for(I=0;I<c;I++){const e=h.face[I].length;for(C=2*Math.PI/e,A=.5*Math.tan(C/2),P=.5,M=0;M<e;M++)_.push(h.vertex[h.face[I][M]][0]*s,h.vertex[h.face[I][M]][1]*r,h.vertex[h.face[I][M]][2]*l),T.push(x),x++,S=u[I].x+(u[I].z-u[I].x)*(.5+A),E=u[I].y+(u[I].w-u[I].y)*(P-.5),v.push(S,rn.e.UseOpenGLOrientationForUV?1-E:E),R=A*Math.cos(C)-P*Math.sin(C),P=A*Math.sin(C)+P*Math.cos(C),A=R,d&&y.push(d[I].r,d[I].g,d[I].b,d[I].a);for(M=0;M<e-2;M++)m.push(T[0+b],T[M+2+b],T[M+1+b]);b+=e}else{for(M=0;M<h.vertex.length;M++)_.push(h.vertex[M][0]*s,h.vertex[M][1]*r,h.vertex[M][2]*l),v.push(0,rn.e.UseOpenGLOrientationForUV?1:0);for(I=0;I<c;I++)for(M=0;M<h.face[I].length-2;M++)m.push(h.face[I][0],h.face[I][M+2],h.face[I][M+1])}sn.x.ComputeNormals(_,m,g),sn.x._ComputeSides(f,_,m,g,v,e.frontUVs,e.backUVs);const D=new sn.x;return D.positions=_,D.indices=m,D.normals=g,D.uvs=v,d&&p&&(D.colors=y),D}function ya(e,t={},i=null){const n=new Nt.Kj(e,i);return t.sideOrientation=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,va(t).applyToMesh(n,t.updatable),n}const xa={CreatePolyhedron:ya};sn.x.CreatePolyhedron=va,Nt.Kj.CreatePolyhedron=(e,t,i)=>ya(e,t,i);class ba extends Gn.t{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}get isHovered(){let e=!1;return[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{e=e||t.isHovered})),e}constructor(e=zn.x.DefaultUtilityLayer,t=1,i){super(e),this._meshAttached=null,this._nodeAttached=null,this._sensitivity=1,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new r.y$,this.onDragEndObservable=new r.y$,this.uniformScaleGizmo=this._createUniformScaleMesh(),this.xGizmo=new ca(new o.P(1,0,0),a.Wo.Red().scale(.5),e,this,t),this.yGizmo=new ca(new o.P(0,1,0),a.Wo.Green().scale(.5),e,this,t),this.zGizmo=new ca(new o.P(0,0,1),a.Wo.Blue().scale(.5),e,this,t),[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,i?i.addToAxisCache(this._gizmoAxisCache):Gn.t.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}_createUniformScaleMesh(){this._coloredMaterial=new Gi.K("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=a.Wo.Gray(),this._hoverMaterial=new Gi.K("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=a.Wo.Yellow(),this._disableMaterial=new Gi.K("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=a.Wo.Gray(),this._disableMaterial.alpha=.4;const e=new ca(new o.P(0,1,0),a.Wo.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=ya("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=ya("",{type:1},e.gizmoLayer.utilityLayerScene),this._octahedron.scaling.scaleInPlace(.007),this._uniformScalingMesh.addChild(this._octahedron),e.setCustomMesh(this._uniformScalingMesh,!0);const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._octahedron);const i={gizmoMeshes:[this._octahedron,this._uniformScalingMesh],colliderMeshes:[this._uniformScalingMesh],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:e.dragBehavior};return this.addToAxisCache(e._rootMesh,i),e}set updateGizmoRotationToMatchAttachedMesh(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))):_.Y.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach((e=>{e&&e.dispose()})),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class Ta{get keepDepthUtilityLayer(){return this._defaultKeepDepthUtilityLayer}get utilityLayer(){return this._defaultUtilityLayer}get isHovered(){let e=!1;for(const t in this.gizmos){const i=this.gizmos[t];if(i&&i.isHovered){e=!0;break}}return e}set scaleRatio(e){this._scaleRatio=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}constructor(e,t=1,i=zn.x.DefaultUtilityLayer,n=zn.x.DefaultKeepDepthUtilityLayer){this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new r.y$,this.onAttachedToNodeObservable=new r.y$,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=a.Wo.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new Ue.K,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=n,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};const s=this._attachToMeshPointerObserver(e),o=Gn.t.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[s,o]}_attachToMeshPointerObserver(e){const t=e.onPointerObservable.add((e=>{if(this.usePointerToAttachGizmos&&e.type==Re.kD.POINTERDOWN)if(e.pickInfo&&e.pickInfo.pickedMesh){if(this.enableAutoPicking){let t=e.pickInfo.pickedMesh;if(null==this.attachableMeshes)for(;t&&null!=t.parent;)t=t.parent;else{let e=!1;this.attachableMeshes.forEach((i=>{t&&(t==i||t.isDescendantOf(i))&&(t=i,e=!0)})),e||(t=null)}t instanceof Un.x?this._attachedMesh!=t&&this.attachToMesh(t):this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}}else this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}));return t}attachToMesh(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=e,this._attachedNode=null;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(e)}attachToNode(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=null,this._attachedNode=e;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedNode=e)}this.boundingBoxGizmoEnabled&&this._attachedNode&&this._attachedNode.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToNodeObservable.notifyObservers(e)}set positionGizmoEnabled(e){e?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new ga(this._defaultUtilityLayer,this._thickness,this)),this._attachedNode?this.gizmos.positionGizmo.attachedNode=this._attachedNode:this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedNode=null),this._gizmosEnabled.positionGizmo=e}get positionGizmoEnabled(){return this._gizmosEnabled.positionGizmo}set rotationGizmoEnabled(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new _a(this._defaultUtilityLayer,32,!1,this._thickness,this)),this._attachedNode?this.gizmos.rotationGizmo.attachedNode=this._attachedNode:this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedNode=null),this._gizmosEnabled.rotationGizmo=e}get rotationGizmoEnabled(){return this._gizmosEnabled.rotationGizmo}set scaleGizmoEnabled(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new ba(this._defaultUtilityLayer,this._thickness,this),this._attachedNode?this.gizmos.scaleGizmo.attachedNode=this._attachedNode:this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedNode=null),this._gizmosEnabled.scaleGizmo=e}get scaleGizmoEnabled(){return this._gizmosEnabled.scaleGizmo}set boundingBoxGizmoEnabled(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new da(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this._attachedMesh?this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh:this.gizmos.boundingBoxGizmo.attachedNode=this._attachedNode,this._attachedMesh?(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)):this._attachedNode&&(this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh?this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior):this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedNode=null),this._gizmosEnabled.boundingBoxGizmo=e}get boundingBoxGizmoEnabled(){return this._gizmosEnabled.boundingBoxGizmo}addToAxisCache(e){e.size>0&&e.forEach(((e,t)=>{this._gizmoAxisCache.set(t,e)}))}dispose(){var e,t;this._pointerObservers.forEach((e=>{this._scene.onPointerObservable.remove(e)}));for(const e in this.gizmos){const t=this.gizmos[e];t&&t.dispose()}this._defaultKeepDepthUtilityLayer!==zn.x._DefaultKeepDepthUtilityLayer&&(null===(e=this._defaultKeepDepthUtilityLayer)||void 0===e||e.dispose()),this._defaultUtilityLayer!==zn.x._DefaultUtilityLayer&&(null===(t=this._defaultUtilityLayer)||void 0===t||t.dispose()),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()}}var Sa=i(7951);function Ea(e){const t=new Array,i=new Array,n=new Array,s=new Array,r=e.radius||.5,o=e.tessellation||64,a=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||sn.x.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);const h=2*Math.PI*a,c=1===a?h/o:h/(o-1);let u=0;for(let e=0;e<o;e++){const e=Math.cos(u),i=Math.sin(u),n=(e+1)/2,o=(1-i)/2;t.push(r*e,r*i,0),s.push(n,rn.e.UseOpenGLOrientationForUV?1-o:o),u+=c}1===a&&(t.push(t[3],t[4],t[5]),s.push(s[2],rn.e.UseOpenGLOrientationForUV?1-s[3]:s[3]));const d=t.length/3;for(let e=1;e<d-1;e++)i.push(e+1,0,e);sn.x.ComputeNormals(t,i,n),sn.x._ComputeSides(l,t,i,n,s,e.frontUVs,e.backUVs);const p=new sn.x;return p.indices=i,p.positions=t,p.normals=n,p.uvs=s,p}function Ca(e,t={},i=null){const n=new Nt.Kj(e,i);return t.sideOrientation=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,Ea(t).applyToMesh(n,t.updatable),n}const Aa={CreateDisc:Ca};function Pa(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);const n=Kn("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=Ca("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=n;const r=Nt.Kj.MergeMeshes([s,n],!0);return r.name=e,r}sn.x.CreateDisc=Ea,Nt.Kj.CreateDisc=(e,t,i,n=null,s,r)=>Ca(e,{radius:t,tessellation:i,sideOrientation:r,updatable:s},n);const Ra={CreateHemisphere:Pa};Nt.Kj.CreateHemisphere=(e,t,i,n)=>Pa(e,{segments:t,diameter:i},n);var Ma=i(6317);class Ia extends Gn.t{constructor(e=zn.x.DefaultUtilityLayer){super(e),this._cachedPosition=new o.P,this._cachedForward=new o.P(0,0,1),this._pointerObserver=null,this.onClickedObservable=new r.y$,this._light=null,this.attachedMesh=new Un.x("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new yi.Y("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new Gi.K("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new a.Wo(.5,.5,.5),this._material.specularColor=new a.Wo(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._light&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))}),Re.kD.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){console.warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),e instanceof Li.e?this._lightMesh=Ia._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof Sa.O?this._lightMesh=Ia._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof Ma.P?this._lightMesh=Ia._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=Ia._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new o._f,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction&&(this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(this.attachedMesh.forward)),this._update()}}get light(){return this._light}get material(){return this._material}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new o.P(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction)if(o.P.DistanceSquared(this.attachedMesh.forward,this._cachedForward)>1e-4){const e=this.attachedMesh.forward;this._light.direction=new o.P(e.x,e.y,e.z),this._cachedForward.copyFrom(this.attachedMesh.forward)}else o.P.DistanceSquared(this.attachedMesh.forward,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(this.attachedMesh.forward))}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new Nt.Kj("hemisphereLight",e),i=Pa(t.name,{segments:10,diameter:1},e);return i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(Ia._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new Nt.Kj("pointLight",e),i=Kn(t.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(Ia._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new Nt.Kj("spotLight",e);Kn(t.name,{segments:10,diameter:1},e).parent=t;const i=Pa(t.name,{segments:10,diameter:2},e);return i.parent=t,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(Ia._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new Nt.Kj("directionalLight",e),i=new Nt.Kj(t.name,e);i.parent=t,Kn(t.name,{diameter:1.2,segments:10},e).parent=i;const n=an(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);n.parent=i;let s=n.clone(t.name);s.scaling.y=.5,s.position.x+=1.25;let r=n.clone(t.name);r.scaling.y=.5,r.position.x+=-1.25;const o=an(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,s=o.clone(t.name),s.position.y=1.5,s.position.x+=1.25,r=o.clone(t.name),r.position.y=1.5,r.position.x+=-1.25,i.scaling.scaleInPlace(Ia._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}Ia._Scale=.007,Ia._CreateLightLines=(e,t)=>{const i=new Nt.Kj("root",t);i.rotation.x=Math.PI/2;const n=new Nt.Kj("linePivot",t);n.parent=i;const s=an("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=n,e<2)return n;for(let e=0;e<4;e++){const t=n.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){const t=n.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){const t=n.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(n.clone("linePivotClone").rotation.z=Math.PI),i};class Da extends Gn.t{constructor(e=zn.x.DefaultUtilityLayer){super(e),this._pointerObserver=null,this.onClickedObservable=new r.y$,this._camera=null,this._invProjection=new Gr.y3,this._material=new Gi.K("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new a.Wo(.5,.5,.5),this._material.specularColor=new a.Wo(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._camera&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))}),Re.kD.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._cameraMesh=Da._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraLinesMesh=Da._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._cameraMesh.parent=this._rootMesh,this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){const t=new Nt.Kj("rootCameraGizmo",e),i=new Nt.Kj(t.name,e);i.parent=t,(0,Yn.NR)(t.name,{width:1,height:.8,depth:.5},e).parent=i;const n=an(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);n.parent=i,n.position.y=.3,n.position.x=-.6,n.rotation.x=.5*Math.PI;const s=an(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);s.parent=i,s.position.y=.5,s.position.x=.4,s.rotation.x=.5*Math.PI;const r=an(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return r.parent=i,r.position.y=0,r.position.x=.6,r.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(Da._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e){const t=new Nt.Kj("rootCameraGizmo",e),i=new Nt.Kj(t.name,e);i.parent=t;for(let t=0;t<4;t+=2)for(let n=0;n<4;n+=2){let s=os("lines",{points:[new o.P(-1+n,-1+t,-1),new o.P(-1+n,-1+t,1)]},e);s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,s=os("lines",{points:[new o.P(-1,-1+n,-1+t),new o.P(1,-1+n,-1+t)]},e),s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,s=os("lines",{points:[new o.P(-1+n,-1,-1+t),new o.P(-1+n,1,-1+t)]},e),s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1}return t}}Da._Scale=.05;var Oa=i(6702);si.v.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";si.v.IncludesShadersStore.packingFunctions="vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}";si.v.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";si.v.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";si.v.ShadersStore.kernelBlurPixelShader="uniform sampler2D textureSampler;\nuniform vec2 delta;\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nfloat sampleCoC(in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r;\nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include<packingFunctions>\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";si.v.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";si.v.ShadersStore.kernelBlurVertexShader="attribute vec2 position;\nuniform vec2 delta;\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class wa extends ni.D{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,n,s,r=Ce.x.BILINEAR_SAMPLINGMODE,o,a,l=0,h="",c=!1,u=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],n,s,r,o,a,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,u),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,n,s,r){this._updateParameters(s,r)}_updateParameters(e,t){const i=this._kernel,n=(i-1)/2;let s=[],r=[],o=0;for(let e=0;e<i;e++){const t=e/(i-1),a=this._gaussianWeight(2*t-1);s[e]=e-n,r[e]=a,o+=a}for(let e=0;e<r.length;e++)r[e]/=o;const a=[],l=[],h=[];for(let e=0;e<=n;e+=2){const t=Math.min(e+1,Math.floor(n));if(e===t)h.push({o:s[e],w:r[e]});else{const i=t===n,o=r[e]+r[t]*(i?.5:1),a=s[e]+1/(1+r[e]/r[t]);0===a?(h.push({o:s[e],w:r[e]}),h.push({o:s[e+1],w:r[e+1]})):(h.push({o:a,w:o}),h.push({o:-a,w:o}))}}for(let e=0;e<h.length;e++)l[e]=h[e].o,a[e]=h[e].w;s=l,r=a;const c=this.getEngine().getCaps().maxVaryingVectors,u=Math.max(c,0)-1;let d=Math.min(s.length,u),p="";p+=this._staticDefines,-1!=this._staticDefines.indexOf("DOF")&&(p+=`#define CENTER_WEIGHT ${this._glslFloat(r[d-1])}\r\n`,d--);for(let e=0;e<d;e++)p+=`#define KERNEL_OFFSET${e} ${this._glslFloat(s[e])}\r\n`,p+=`#define KERNEL_WEIGHT${e} ${this._glslFloat(r[e])}\r\n`;let f=0;for(let e=u;e<s.length;e++)p+=`#define KERNEL_DEP_OFFSET${f} ${this._glslFloat(s[e])}\r\n`,p+=`#define KERNEL_DEP_WEIGHT${f} ${this._glslFloat(r[e])}\r\n`,f++;this.packedFloat&&(p+="#define PACKEDFLOAT 1"),this._blockCompilation=!1,super.updateEffect(p,null,null,{varyingCount:d,depCount:f},e,t)}_nearestBestKernel(e){const t=Math.round(e);for(const e of[t,t-1,t+1,t-2,t+2])if(e%2!=0&&Math.floor(e/2)%2==0&&e>0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new wa(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,n)}}(0,be.gn)([(0,Te.qC)("kernel")],wa.prototype,"_kernel",void 0),(0,be.gn)([(0,Te.qC)("packedFloat")],wa.prototype,"_packedFloat",void 0),(0,be.gn)([(0,Te.QC)()],wa.prototype,"direction",void 0),(0,l.H)("BABYLON.BlurPostProcess",wa);class Na extends Ai._{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,n,s=0,r=Ce.x.BILINEAR_SAMPLINGMODE,a=!0){if(super(e,t,i,n,!0,s,!1,r,a),this.mirrorPlane=new ot.J(0,1,0,1),this._transformMatrix=o.y3.Zero(),this._mirrorMatrix=o.y3.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()}));const l=i.getEngine();let h;l.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add((()=>{var t;null===(t=l._debugPushGroup)||void 0===t||t.call(l,`mirror generation for ${e}`,1)})),this.onAfterUnbindObservable.add((()=>{var e;null===(e=l._debugPopGroup)||void 0===e||e.call(l,1)})),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),o.y3.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=o.P.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 wa("horizontal blur",new o.FM(1,0),this._blurKernelX,this._blurRatio,null,Ce.x.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new wa("vertical blur",new o.FM(0,1),this._blurKernelY,this._blurRatio,null,Ce.x.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Na(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();const t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(e=this._sceneUBO)||void 0===e||e.dispose()}}Ce.x._CreateMirror=(e,t,i,n)=>new Na(e,t,i,n);var Fa=i(4051),La=i(5346),Ba=i(1917),Ua=i(580),Va=i(85);si.v.IncludesShadersStore.backgroundFragmentDeclaration="uniform vec4 vEyePosition;\nuniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n",i(2963);si.v.IncludesShadersStore.backgroundUboDeclaration="layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\n#include<sceneUboDeclaration>\n",i(2132),i(2557),i(3756),i(6568),i(3996),i(6390),i(9519),i(5791),i(9490),i(6043);si.v.ShadersStore.backgroundPixelShader="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include<helperFunctions>\n#define RECIPROCAL_PI2 0.15915494\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\n}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition.xyz),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));\nconst float startAngle=0.1;\nfloat fadeFactor=saturate(viewAngleToFloor/startAngle);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";si.v.IncludesShadersStore.backgroundVertexDeclaration="uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n",i(7520),i(493),i(1063),i(6343),i(9042),i(1542),i(9935),i(6883),i(6655),i(3206),i(5215),i(962),i(1101);si.v.ShadersStore.backgroundVertexShader="precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n} else {\ngl_Position=viewProjectionR*finalWorld*vec4(position,1.0);\n}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";var ka=i(1434),Ga=i(99);class za extends Ba.H{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.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 Wa extends Ua.a{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=Wa.StandardReflectance0*t,this.reflectionReflectance90=Wa.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=Wa.StandardReflectance0+(1-Wa.StandardReflectance0)*t,this.reflectionReflectance90=Wa.StandardReflectance90+(1-Wa.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=a.Wo.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=o.P.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._renderTargets=new Fn.t(16),this._reflectionControls=o.Lt.Zero(),this._white=a.Wo.White(),this._primaryShadowColor=a.Wo.Black(),this._primaryHighlightColor=a.Wo.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||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new za);const n=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=n.getEngine();if(La.G.PrepareDefinesForLights(n,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,La.G.PrepareDefinesForMultiview(n,s),s._areTexturesDirty){if(s._needUVs=!1,n.texturesEnabled){if(n.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&Va.k.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;La.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE"),s.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,s.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,s.OPACITYFRESNEL=this._opacityFresnel}else s.DIFFUSE=!1,s.DIFFUSEDIRECTUV=0,s.DIFFUSEHASALPHA=!1,s.GAMMADIFFUSE=!1,s.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&Va.k.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(s.REFLECTION=!0,s.GAMMAREFLECTION=e.gammaSpace,s.RGBDREFLECTION=e.isRGBD,s.REFLECTIONBLUR=this._reflectionBlur>0,s.LODINREFLECTIONALPHA=e.lodLevelInAlpha,s.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,s.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===Ce.x.INVCUBIC_MODE&&(s.INVERTCUBICMAP=!0),s.REFLECTIONMAP_3D=e.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case Ce.x.EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case Ce.x.PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case Ce.x.PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case Ce.x.SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case Ce.x.SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case Ce.x.EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Ce.x.FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Ce.x.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Ce.x.CUBIC_MODE:case Ce.x.INVCUBIC_MODE:default:s.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(s.REFLECTIONFRESNEL=!0,s.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):(s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1)}else s.REFLECTION=!1,s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1,s.REFLECTIONBLUR=!1,s.REFLECTIONMAP_3D=!1,s.REFLECTIONMAP_SPHERICAL=!1,s.REFLECTIONMAP_PLANAR=!1,s.REFLECTIONMAP_CUBIC=!1,s.REFLECTIONMAP_PROJECTION=!1,s.REFLECTIONMAP_SKYBOX=!1,s.REFLECTIONMAP_EXPLICIT=!1,s.REFLECTIONMAP_EQUIRECTANGULAR=!1,s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,s.INVERTCUBICMAP=!1,s.REFLECTIONMAP_OPPOSITEZ=!1,s.LODINREFLECTIONALPHA=!1,s.GAMMAREFLECTION=!1,s.RGBDREFLECTION=!1}s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.USERGBCOLOR=this._useRGBColor,s.NOISE=this._enableNoise}if(s._areLightsDirty&&(s.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),s.BACKMAT_SHADOWONLY=this._shadowOnly),s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s)}if(La.G.PrepareDefinesForMisc(e,n,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),La.G.PrepareDefinesForFrameBoundValues(n,r,this,s,i,null,t.getRenderingMesh().hasThinInstances),La.G.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&(n.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(qe.o.NormalKind)||(e.createNormals(!0),_.Y.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new ka.L;s.FOG&&i.addFallback(0,"FOG"),s.POINTSIZE&&i.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),La.G.HandleFallbacksForShadows(s,i,this._maxSimultaneousLights);const o=[qe.o.PositionKind];s.NORMAL&&o.push(qe.o.NormalKind),s.UV1&&o.push(qe.o.UVKind),s.UV2&&o.push(qe.o.UV2Kind),La.G.PrepareAttributesForBones(o,e,s,i),La.G.PrepareAttributesForInstances(o,s);const a=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"];(0,Ga.qx)(a);const l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];ki.$&&(ki.$.PrepareUniforms(a,s),ki.$.PrepareSamplers(l,s)),La.G.PrepareUniformsAndSamplersList({uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});const c=s.toString(),u=n.getEngine().createEffect("background",{attributes:o,uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},r);t.setEffect(u,s,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.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(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e),La.G.BindBonesParameters(t,this._activeEffect);const o=this._mustRebind(n,r,t.visibility);if(o){this._uniformBuffer.bindToEffect(r,"Material"),this.bindViewProjection(r);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(n.texturesEnabled&&(this._diffuseTexture&&Va.k.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),La.G.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&Va.k.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),n.texturesEnabled&&(this._diffuseTexture&&Va.k.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&Va.k.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),s.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)))),(0,Ga.an)(this._activeEffect,this,n),n.bindEyePosition(r)}else n.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(r,"Material"),this._needToBindSceneUbo=!0);!o&&this.isFrozen||(n.lightsEnabled&&La.G.BindLights(n,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(r),La.G.BindFogParameters(n,t,this._activeEffect,!0),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return Te.p4.Clone((()=>new Wa(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return Te.p4.Parse((()=>new Wa(e.name,t)),e,t,i)}}Wa.StandardReflectance0=.05,Wa.StandardReflectance90=.5,(0,be.gn)([(0,Te.n9)()],Wa.prototype,"_primaryColor",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsLightsDirty")],Wa.prototype,"primaryColor",void 0),(0,be.gn)([(0,Te.n9)()],Wa.prototype,"__perceptualColor",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_primaryColorShadowLevel",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_primaryColorHighlightLevel",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsLightsDirty")],Wa.prototype,"primaryColorHighlightLevel",null),(0,be.gn)([(0,Te.oU)()],Wa.prototype,"_reflectionTexture",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"reflectionTexture",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_reflectionBlur",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"reflectionBlur",void 0),(0,be.gn)([(0,Te.oU)()],Wa.prototype,"_diffuseTexture",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"diffuseTexture",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"shadowLights",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_shadowLevel",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"shadowLevel",void 0),(0,be.gn)([(0,Te.hd)()],Wa.prototype,"_sceneCenter",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"sceneCenter",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_opacityFresnel",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"opacityFresnel",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_reflectionFresnel",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"reflectionFresnel",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_reflectionFalloffDistance",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"reflectionFalloffDistance",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_reflectionAmount",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"reflectionAmount",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_reflectionReflectance0",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"reflectionReflectance0",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_reflectionReflectance90",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"reflectionReflectance90",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_useRGBColor",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"useRGBColor",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_enableNoise",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"enableNoise",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_maxSimultaneousLights",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],Wa.prototype,"maxSimultaneousLights",void 0),(0,be.gn)([(0,Te.qC)()],Wa.prototype,"_shadowOnly",void 0),(0,be.gn)([(0,Te.wz)("_markAllSubMeshesAsLightsDirty")],Wa.prototype,"shadowOnly",void 0),(0,be.gn)([(0,Te.rX)()],Wa.prototype,"_imageProcessingConfiguration",void 0),(0,l.H)("BABYLON.BackgroundMaterial",Wa);class Ha{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new a.Wo(.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 a.Wo(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:o.P.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=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options={...Ha._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new r.y$,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t={...this._options,...e};this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new a.HE(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 Oa.V)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=Fa.B.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new Nt.Kj("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const n=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),s=n.max.subtract(n.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Ft&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const r=s.length();r>e&&(e=2*r,t=e),e*=1.1,t*=1.5,i=n.min.add(s.scale(.5)),i.y=n.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=(0,pa.pT)("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 Wa("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof Oa.V?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new Ce.x(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=Ce.x.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new Na("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Ce.x.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new ot.J(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e<this._scene.meshes.length;e++){const t=this._scene.meshes[e];t!==this._ground&&t!==this._skybox&&t!==this._rootMesh&&this._groundMirror.renderList.push(t)}const i=this._options.groundColor.toGammaSpace(this._scene.getEngine().useExactSrgbConversions);this._groundMirror.clearColor=new a.HE(i.r,i.g,i.b,1),this._groundMirror.adaptiveBlurKernel=this._options.groundMirrorBlurKernel}_setupMirrorInGroundMaterial(){this._groundMaterial&&(this._groundMaterial.reflectionTexture=this._groundMirror,this._groundMaterial.reflectionFresnel=!0,this._groundMaterial.reflectionAmount=this._options.groundMirrorAmount,this._groundMaterial.reflectionStandardFresnelWeight=this._options.groundMirrorFresnelWeight,this._groundMaterial.reflectionFalloffDistance=this._options.groundMirrorFallOffDistance)}_setupSkybox(e){this._skybox&&!this._skybox.isDisposed()||(this._skybox=(0,Yn.NR)("BackgroundSkybox",{size:e.skyboxSize,sideOrientation:Nt.Kj.BACKSIDE},this._scene),this._skybox.onDisposeObservable.add((()=>{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new Wa("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof Oa.V?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new Fa.B(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Ce.x.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)}}Ha._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",Ha._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",Ha._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class Xa extends yi.Y{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._texture.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Ce.x.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Ce.x.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,n,s=null){super(e,n),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=Xa.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new r.y$,this.onLoadObservable=new r.y$,n=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(n.activeCamera?.48*n.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=Kn(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:Nt.Kj.BACKSIDE},n);const a=this._material=new Wa(e+"_material",n);a.useEquirectangularFOV=!0,a.fovMultiplier=1,a.opacityFresnel=!1;const l=this._initTexture(t,n,i);if(this.texture=l,this._mesh.material=a,this._mesh.parent=this,this._halfDomeMask=Kn("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:Nt.Kj.BACKSIDE},n),this._halfDomeMask.rotate(Gr.RD.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&&n.activeCamera){const e=n.activeCamera,t=o.P.Forward(),i=o.P.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(o.P.Dot(t,i))}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 Xa.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case Xa.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let n=i.isRightCamera;this._crossEye&&(n=!n),this._texture.uOffset=n?e:t}));break}case Xa.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}Xa.MODE_MONOSCOPIC=0,Xa.MODE_TOPBOTTOM=1,Xa.MODE_SIDEBYSIDE=2;class ja extends Xa{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 Ce.x(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(()=>{this.onLoadObservable.notifyObservers()}),((e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)}))}}ja.MODE_MONOSCOPIC=Xa.MODE_MONOSCOPIC,ja.MODE_TOPBOTTOM=Xa.MODE_TOPBOTTOM,ja.MODE_SIDEBYSIDE=Xa.MODE_SIDEBYSIDE;var Ya=i(9500),qa=i(6113),Ka=i(123);const $a=131072,Qa=131072;function Za(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const Ja=Za("DXT1"),el=Za("DXT3"),tl=Za("DXT5"),il=Za("DX10");class nl{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35);let n=1;t[2]&$a&&(n=Math.max(1,t[7]));const s=t[21],r=s===il?i[32]:0;let o=0;switch(s){case 113:o=2;break;case 116:o=1;break;case il:if(10===r){o=2;break}if(2===r){o=1;break}}return{width:t[4],height:t[3],mipmapCount:n,isFourCC:4==(4&t[20]),isRGB:64==(64&t[20]),isLuminance:(t[20]&Qa)===Qa,isCube:512==(512&t[28]),isCompressed:s===Ja||s===el||s===tl,dxgiFormat:r,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,n,s,r){const o=new Float32Array(n),a=new Uint16Array(s,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);o[l]=(0,ro.qZ)(a[n]),o[l+1]=(0,ro.qZ)(a[n+1]),o[l+2]=(0,ro.qZ)(a[n+2]),nl.StoreLODInAlphaChannel?o[l+3]=r:o[l+3]=(0,ro.qZ)(a[n+3]),l+=4}return o}static _GetHalfFloatRGBAArrayBuffer(e,t,i,n,s,r){if(nl.StoreLODInAlphaChannel){const o=new Uint16Array(n),a=new Uint16Array(s,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);o[l]=a[n],o[l+1]=a[n+1],o[l+2]=a[n+2],o[l+3]=(0,ro.ay)(r),l+=4}return o}return new Uint16Array(s,i,n)}static _GetFloatRGBAArrayBuffer(e,t,i,n,s,r){if(nl.StoreLODInAlphaChannel){const o=new Float32Array(n),a=new Float32Array(s,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);o[l]=a[n],o[l+1]=a[n+1],o[l+2]=a[n+2],o[l+3]=r,l+=4}return o}return new Float32Array(s,i,n)}static _GetFloatAsHalfFloatRGBAArrayBuffer(e,t,i,n,s,r){const o=new Uint16Array(n),a=new Float32Array(s,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++)o[l]=(0,ro.ay)(a[l]),o[l+1]=(0,ro.ay)(a[l+1]),o[l+2]=(0,ro.ay)(a[l+2]),nl.StoreLODInAlphaChannel?o[l+3]=(0,ro.ay)(r):o[l+3]=(0,ro.ay)(a[l+3]),l+=4;return o}static _GetFloatAsUIntRGBAArrayBuffer(e,t,i,n,s,r){const o=new Uint8Array(n),a=new Float32Array(s,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);o[l]=255*lt.R.Clamp(a[n]),o[l+1]=255*lt.R.Clamp(a[n+1]),o[l+2]=255*lt.R.Clamp(a[n+2]),nl.StoreLODInAlphaChannel?o[l+3]=r:o[l+3]=255*lt.R.Clamp(a[n+3]),l+=4}return o}static _GetHalfFloatAsUIntRGBAArrayBuffer(e,t,i,n,s,r){const o=new Uint8Array(n),a=new Uint16Array(s,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);o[l]=255*lt.R.Clamp((0,ro.qZ)(a[n])),o[l+1]=255*lt.R.Clamp((0,ro.qZ)(a[n+1])),o[l+2]=255*lt.R.Clamp((0,ro.qZ)(a[n+2])),nl.StoreLODInAlphaChannel?o[l+3]=r:o[l+3]=255*lt.R.Clamp((0,ro.qZ)(a[n+3])),l+=4}return o}static _GetRGBAArrayBuffer(e,t,i,n,s,r,o,a,l){const h=new Uint8Array(n),c=new Uint8Array(s,i);let u=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);h[u]=c[n+r],h[u+1]=c[n+o],h[u+2]=c[n+a],h[u+3]=c[n+l],u+=4}return h}static _ExtractLongWordOrder(e){return 0===e||255===e||-16777216===e?0:1+nl._ExtractLongWordOrder(e>>8)}static _GetRGBArrayBuffer(e,t,i,n,s,r,o,a){const l=new Uint8Array(n),h=new Uint8Array(s,i);let c=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=3*(t+i*e);l[c]=h[n+r],l[c+1]=h[n+o],l[c+2]=h[n+a],c+=3}return l}static _GetLuminanceArrayBuffer(e,t,i,n,s){const r=new Uint8Array(n),o=new Uint8Array(s,i);let a=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=t+i*e;r[a]=o[n],a++}return r}static UploadDDSLevels(e,t,i,n,s,r,o=-1,a,l=!0){let h=null;n.sphericalPolynomial&&(h=new Array);const c=!!e.getCaps().s3tc;t.generateMipMaps=s;const u=new Int32Array(i.buffer,i.byteOffset,31);let d,p,f,m,g,v,y,x=0,b=0,T=1;if(542327876!==u[0])return void _.Y.Error("Invalid magic number in DDS header");if(!n.isFourCC&&!n.isRGB&&!n.isLuminance)return void _.Y.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");if(n.isCompressed&&!c)return void _.Y.Error("Compressed textures are not supported on this platform.");let S=u[22];m=u[1]+4;let E=!1;if(n.isFourCC)switch(d=u[21],d){case Ja:T=8,b=33777;break;case el:T=16,b=33778;break;case tl:T=16,b=33779;break;case 113:E=!0,S=64;break;case 116:E=!0,S=128;break;case il:{m+=20;let e=!1;switch(n.dxgiFormat){case 10:E=!0,S=64,e=!0;break;case 2:E=!0,S=128,e=!0;break;case 88:n.isRGB=!0,n.isFourCC=!1,S=32,e=!0}if(e)break}default:return void console.error("Unsupported FourCC code:",(C=d,String.fromCharCode(255&C,C>>8&255,C>>16&255,C>>24&255)))}var C;const A=nl._ExtractLongWordOrder(u[23]),P=nl._ExtractLongWordOrder(u[24]),R=nl._ExtractLongWordOrder(u[25]),M=nl._ExtractLongWordOrder(u[26]);E&&(b=e._getRGBABufferInternalSizedFormat(n.textureType)),v=1,u[2]&$a&&!1!==s&&(v=Math.max(1,u[7]));const I=a||0,D=e.getCaps();for(let s=I;s<r;s++){for(p=u[4],f=u[3],y=0;y<v;++y){if(-1===o||o===y){const r=-1===o?y:0;if(!n.isCompressed&&n.isFourCC){t.format=5,x=p*f*4;let n=null;if(e._badOS||e._badDesktopOS||!D.textureHalfFloat&&!D.textureFloat)128===S?(n=nl._GetFloatAsUIntRGBAArrayBuffer(p,f,i.byteOffset+m,x,i.buffer,r),h&&0==r&&h.push(nl._GetFloatRGBAArrayBuffer(p,f,i.byteOffset+m,x,i.buffer,r))):64===S&&(n=nl._GetHalfFloatAsUIntRGBAArrayBuffer(p,f,i.byteOffset+m,x,i.buffer,r),h&&0==r&&h.push(nl._GetHalfFloatAsFloatRGBAArrayBuffer(p,f,i.byteOffset+m,x,i.buffer,r))),t.type=0;else{const e=D.textureFloat&&(l&&D.textureFloatLinearFiltering||!l),s=D.textureHalfFloat&&(l&&D.textureHalfFloatLinearFiltering||!l),o=(128===S||64===S&&!s)&&e?1:(64===S||128===S&&!e)&&s?2:0;let a,c=null;if(128===S)switch(o){case 1:a=nl._GetFloatRGBAArrayBuffer,c=null;break;case 2:a=nl._GetFloatAsHalfFloatRGBAArrayBuffer,c=nl._GetFloatRGBAArrayBuffer;break;case 0:a=nl._GetFloatAsUIntRGBAArrayBuffer,c=nl._GetFloatRGBAArrayBuffer}else switch(o){case 1:a=nl._GetHalfFloatAsFloatRGBAArrayBuffer,c=null;break;case 2:a=nl._GetHalfFloatRGBAArrayBuffer,c=nl._GetHalfFloatAsFloatRGBAArrayBuffer;break;case 0:a=nl._GetHalfFloatAsUIntRGBAArrayBuffer,c=nl._GetHalfFloatAsFloatRGBAArrayBuffer}t.type=o,n=a(p,f,i.byteOffset+m,x,i.buffer,r),h&&0==r&&h.push(c?c(p,f,i.byteOffset+m,x,i.buffer,r):n)}n&&e._uploadDataToTextureDirectly(t,n,s,r)}else if(n.isRGB)t.type=0,24===S?(t.format=4,x=p*f*3,g=nl._GetRGBArrayBuffer(p,f,i.byteOffset+m,x,i.buffer,A,P,R),e._uploadDataToTextureDirectly(t,g,s,r)):(t.format=5,x=p*f*4,g=nl._GetRGBAArrayBuffer(p,f,i.byteOffset+m,x,i.buffer,A,P,R,M),e._uploadDataToTextureDirectly(t,g,s,r));else if(n.isLuminance){const n=e._getUnpackAlignement(),o=p;x=Math.floor((p+n-1)/n)*n*(f-1)+o,g=nl._GetLuminanceArrayBuffer(p,f,i.byteOffset+m,x,i.buffer),t.format=1,t.type=0,e._uploadDataToTextureDirectly(t,g,s,r)}else x=Math.max(4,p)/4*Math.max(4,f)/4*T,g=new Uint8Array(i.buffer,i.byteOffset+m,x),t.type=0,e._uploadCompressedDataToTextureDirectly(t,b,p,f,g,s,r)}m+=S?p*f*(S/8):x,p*=.5,f*=.5,p=Math.max(1,p),f=Math.max(1,f)}if(void 0!==a)break}h&&h.length>0?n.sphericalPolynomial=Ka.$.ConvertCubeMapToSphericalPolynomial({size:u[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):n.sphericalPolynomial=void 0}}nl.StoreLODInAlphaChannel=!1,Rn.B.prototype.createPrefilteredCubeTexture=function(e,t,i,n,s=null,r=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(s&&s(null));const r=e.texture;if(l?e.info.sphericalPolynomial&&(r._sphericalPolynomial=e.info.sphericalPolynomial):r._sphericalPolynomial=new qa.i,r._source=Ei.S.CubePrefiltered,this.getCaps().textureLOD)return void(s&&s(r));const o=this._gl,a=e.width;if(!a)return;const h=[];for(let s=0;s<3;s++){const l=1-s/2,c=n,u=lt.R.Log2(a)*i+n,d=c+(u-c)*l,p=Math.round(Math.min(Math.max(d,0),u)),f=new Ei.l(this,Ei.S.Temp);if(f.type=r.type,f.format=r.format,f.width=Math.pow(2,Math.max(lt.R.Log2(a)-p,0)),f.height=f.width,f.isCube=!0,f._cachedWrapU=0,f._cachedWrapV=0,this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,f,!0),f.samplingMode=2,o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),nl.UploadDDSLevels(this,f,i,t,!0,6,p)}else _.Y.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null);const m=new Oa.V(t);m._isCube=!0,m._texture=f,f.isReady=!0,h.push(m)}r._lodTextureHigh=h[2],r._lodTextureMid=h[1],r._lodTextureLow=h[0],s&&s(r)}),r,o,a,l,i,n)};class sl{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,n){const s=t.getEngine();let r,o=!1,a=1e3;if(Array.isArray(e))for(let i=0;i<e.length;i++){const n=e[i];r=nl.GetDDSInfo(n),t.width=r.width,t.height=r.height,o=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps,s._unpackFlipY(r.isCompressed),nl.UploadDDSLevels(s,t,n,r,o,6,-1,i),r.isFourCC||1!==r.mipmapCount?a=r.mipmapCount-1:s.generateMipMapsForCubemap(t)}else{const n=e;r=nl.GetDDSInfo(n),t.width=r.width,t.height=r.height,i&&(r.sphericalPolynomial=new qa.i),o=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps,s._unpackFlipY(r.isCompressed),nl.UploadDDSLevels(s,t,n,r,o,6),r.isFourCC||1!==r.mipmapCount?a=r.mipmapCount-1:s.generateMipMapsForCubemap(t,!1)}s._setCubeMapTextureParams(t,o,a),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n({isDDS:!0,width:t.width,info:r,data:e,texture:t})}loadData(e,t,i){const n=nl.GetDDSInfo(e),s=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps&&n.width>>n.mipmapCount-1==1;i(n.width,n.height,s,n.isFourCC,(()=>{nl.UploadDDSLevels(t.getEngine(),t,e,n,s,1)}))}}ue.D._TextureLoaders.push(new sl);class rl{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,n,s){if(Array.isArray(e))return;const r=(0,Gs.qJ)(e);if(r){t.width=r.width,t.height=r.width;try{(0,Gs.qC)(t,r),(0,Gs.Ro)(t,e,r).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}),(e=>{null==s||s("Can not upload environment levels",e)}))}catch(e){null==s||s("Can not upload environment file",e)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}ue.D._TextureLoaders.push(new rl);class ol{constructor(e,t){if(this.data=e,this.isInvalid=!1,!ol.IsValid(e))return this.isInvalid=!0,void _.Y.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,n=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),s=67305985===n.getUint32(0,!0);return this.glType=n.getUint32(1*i,s),this.glTypeSize=n.getUint32(2*i,s),this.glFormat=n.getUint32(3*i,s),this.glInternalFormat=n.getUint32(4*i,s),this.glBaseInternalFormat=n.getUint32(5*i,s),this.pixelWidth=n.getUint32(6*i,s),this.pixelHeight=n.getUint32(7*i,s),this.pixelDepth=n.getUint32(8*i,s),this.numberOfArrayElements=n.getUint32(9*i,s),this.numberOfFaces=n.getUint32(10*i,s),this.numberOfMipmapLevels=n.getUint32(11*i,s),this.bytesOfKeyValueData=n.getUint32(12*i,s),0!==this.glType?(_.Y.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(_.Y.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(_.Y.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(_.Y.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=ol.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case ol.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case ol.TEX_2D:case ol.COMPRESSED_3D:case ol.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=ol.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,s=this.pixelHeight;const r=t?this.numberOfMipmapLevels:1;for(let t=0;t<r;t++){const r=new Int32Array(this.data.buffer,this.data.byteOffset+i,1)[0];i+=4;for(let o=0;o<this.numberOfFaces;o++){const a=new Uint8Array(this.data.buffer,this.data.byteOffset+i,r);e.getEngine()._uploadCompressedDataToTextureDirectly(e,e.format,n,s,a,o,t),i+=r,i+=3-(r+3)%4}n=Math.max(1,.5*n),s=Math.max(1,.5*s)}}static IsValid(e){if(e.byteLength>=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}ol.HEADER_LEN=64,ol.COMPRESSED_2D=0,ol.COMPRESSED_3D=1,ol.TEX_2D=2,ol.TEX_3D=3;var al,ll,hl,cl=i(6250);function ul(e){return e?de.w1.GetAbsoluteUrl(e):null}function dl(e){null!==e.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),null!==e.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),null!==e.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),null!==e.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),null!==e.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),null!==e.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),null!==e.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),null!==e.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),null!==e.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)}!function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(al||(al={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(ll||(ll={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}(hl||(hl={}));class pl{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:[ll.BC1_RGB,ll.BC3_RGBA],yes:{transcodeFormat:ll.RGBA32,engineFormat:hl.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class fl{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(fl._WorkerPoolPromise||fl._DecoderModulePromise)return;const t={jsDecoderModule:de.w1.GetAbsoluteUrl(this.URLConfig.jsDecoderModule),wasmUASTCToASTC:ul(this.URLConfig.wasmUASTCToASTC),wasmUASTCToBC7:ul(this.URLConfig.wasmUASTCToBC7),wasmUASTCToRGBA_UNORM:ul(this.URLConfig.wasmUASTCToRGBA_UNORM),wasmUASTCToRGBA_SRGB:ul(this.URLConfig.wasmUASTCToRGBA_SRGB),wasmUASTCToR8_UNORM:ul(this.URLConfig.wasmUASTCToR8_UNORM),wasmUASTCToRG8_UNORM:ul(this.URLConfig.wasmUASTCToRG8_UNORM),jsMSCTranscoder:ul(this.URLConfig.jsMSCTranscoder),wasmMSCTranscoder:ul(this.URLConfig.wasmMSCTranscoder),wasmZSTDDecoder:ul(this.URLConfig.wasmZSTDDecoder)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?fl._WorkerPoolPromise=new Promise((i=>{const n=`${dl}(${_l})()`,s=URL.createObjectURL(new Blob([n],{type:"application/javascript"}));i(new cl.v(e,(()=>new Promise(((e,i)=>{const n=new Worker(s),r=e=>{n.removeEventListener("error",r),n.removeEventListener("message",o),i(e)},o=t=>{"init"===t.data.action&&(n.removeEventListener("error",r),n.removeEventListener("message",o),e(n))};n.addEventListener("error",r),n.addEventListener("message",o),n.postMessage({action:"init",urls:t})})))))})):"undefined"==typeof KTX2DECODER?fl._DecoderModulePromise=de.w1.LoadScriptAsync(t.jsDecoderModule).then((()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,dl(t),new KTX2DECODER.KTX2Decoder))):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,fl._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=fl.DefaultNumWorkers){this._engine=e,fl._Initialize(t)}uploadAsync(e,t,i){const n=this._engine.getCaps(),s={astc:!!n.astc,bptc:!!n.bptc,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,etc1:!!n.etc1};if(fl._WorkerPoolPromise)return fl._WorkerPoolPromise.then((n=>new Promise(((r,o)=>{n.push(((n,a)=>{const l=e=>{n.removeEventListener("error",l),n.removeEventListener("message",h),o(e),a()},h=e=>{if("decoded"===e.data.action){if(n.removeEventListener("error",l),n.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),r()}catch(e){o({message:e})}else o({message:e.data.msg});a()}};n.addEventListener("error",l),n.addEventListener("message",h),n.postMessage({action:"setDefaultDecoderOptions",options:fl.DefaultDecoderOptions._getKTX2DecoderOptions()});const c=new Uint8Array(e.byteLength);c.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),n.postMessage({action:"decode",data:c,caps:s,options:i},[c.buffer])}))}))));if(fl._DecoderModulePromise)return fl._DecoderModulePromise.then((i=>(fl.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=fl.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((s,r)=>{i.decode(e,n).then((e=>{this._createTexture(e,t),s()})).catch((e=>{r({message:e})}))})))));throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let n=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,n=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i<e.mipmaps.length;++i){const s=e.mipmaps[i];if(!s||!s.data)throw new Error("KTX2 container - could not transcode one of the image");n?(t.width=s.width,t.height=s.height,this._engine._uploadDataToTextureDirectly(t,s.data,0,i,void 0,!0)):this._engine._uploadCompressedDataToTextureDirectly(t,e.transcodedFormat,s.width,s.height,s.data,0,i)}t._extension=".ktx2",t.width=e.mipmaps[0].width,t.height=e.mipmaps[0].height,t.isReady=!0,this._engine._bindTextureDirectly(3553,null)}static IsValid(e){if(e.byteLength>=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}function _l(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{const i=t.data.urls;importScripts(i.jsDecoderModule),dl(i),e=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=t.data.options;break;case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then((e=>{const t=[];for(let i=0;i<e.mipmaps.length;++i){const n=e.mipmaps[i];n&&n.data&&t.push(n.data.buffer)}postMessage({action:"decoded",success:!0,decodedData:e},t)})).catch((e=>{postMessage({action:"decoded",success:!1,msg:e})}))}}}fl.URLConfig={jsDecoderModule:"https://preview.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},fl.DefaultNumWorkers=fl.GetDefaultNumWorkers(),fl.DefaultDecoderOptions=new pl;class ml{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,n){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const s=t.getEngine(),r=new ol(e,6),o=r.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),r.uploadLevels(t,t.generateMipMaps),t.width=r.pixelWidth,t.height=r.pixelHeight,s._setCubeMapTextureParams(t,o,r.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}loadData(e,t,i,n){if(ol.IsValid(e)){t._invertVScale=!t.invertY;const n=new ol(e,1),s=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(n.glInternalFormat);s?(t.format=s,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=n.glInternalFormat,i(n.pixelWidth,n.pixelHeight,t.generateMipMaps,!0,(()=>{n.uploadLevels(t,t.generateMipMaps)}),n.isInvalid)}else fl.IsValid(e)?new fl(t.getEngine()).uploadAsync(e,t,n).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{_.Y.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)})):(_.Y.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0))}}ue.D._TextureLoaders.unshift(new ml);class gl extends Dt.c{constructor(e,t,i){super(e,o.P.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=o._f.Identity(),this._referencedPosition=new o.P,this._trackingState=ji.NOT_TRACKING,this.onBeforeCameraTeleport=new r.y$,this.onAfterCameraTeleport=new r.y$,this.onTrackingStateChanged=new r.y$,this.compensateOnFirstFrame=!0,this._rotate180=new o._f(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new o._f,this.cameraRigMode=Mt.V.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._xrSessionManager.onXRSessionInit.add((()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame})),this._xrSessionManager.onXRFrameObservable.add((()=>{this._firstFrame&&this._updateFromXRSession(),this._updateReferenceSpace(),this._updateFromXRSession()}),void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new ui.l(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new ui.l(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,o._f.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}setTarget(e){const t=o.jp.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),o._f.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)return void this._setTrackingState(ji.NOT_TRACKING);const t=e.emulatedPosition?ji.TRACKING_LOST:ji.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){const e={depthFar:this.maxZ||1e4,depthNear:this.minZ};this._xrSessionManager.updateRenderState(e),this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ}if(e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach(((e,t)=>{var i;const n=this.rigCameras[t];n.isLeftCamera||n.isRightCamera||("right"===e.eye?n._isRightCamera=!0:"left"===e.eye&&(n._isLeftCamera=!0));const s=e.transform.position,r=e.transform.orientation;n.parent=this.parent,n.position.set(s.x,s.y,s.z),n.rotationQuaternion.set(r.x,r.y,r.z,r.w),this._scene.useRightHandedSystem?n.rotationQuaternion.multiplyInPlace(this._rotate180):(n.position.z*=-1,n.rotationQuaternion.z*=-1,n.rotationQuaternion.w*=-1),o.y3.FromFloat32ArrayToRefScaled(e.projectionMatrix,0,1,n._projectionMatrix),this._scene.useRightHandedSystem||n._projectionMatrix.toggleProjectionMatrixHandInPlace(),0===t&&this._projectionMatrix.copyFrom(n._projectionMatrix);const a=this._xrSessionManager.getRenderTargetTextureForView(e);this._renderingMultiview=(null===(i=null==a?void 0:a._texture)||void 0===i?void 0:i.isMultiview)||!1,this._renderingMultiview?0==t&&(this._xrSessionManager.trySetViewportForView(this.viewport,e),this.outputRenderTarget=a):(this._xrSessionManager.trySetViewportForView(n.viewport,e),n.outputRenderTarget=a||this._xrSessionManager.getRenderTargetTextureForView(e)),n.layerMask=this.layerMask}))}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.length<e;){const e=new It.C("XR-RigCamera: "+this.rigCameras.length,o.P.Zero(),this.getScene());e.minZ=.1,e.rotationQuaternion=new o._f,e.updateUpVectorFromRotation=!0,e.isRigCamera=!0,e.rigParent=this,e.freezeProjectionMatrix(),this.rigCameras.push(e)}for(;this.rigCameras.length>e;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=o.jp.Matrix[0],t=o.jp.Matrix[1],i=o.jp.Matrix[2];o.y3.ComposeToRef(gl._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),o.y3.ComposeToRef(gl._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const n=new XRRigidTransform({x:this._referencedPosition.x,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(n)}}}gl._ScaleReadOnly=o.P.One();var vl=i(4370);class yl{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 r.y$,this.onStateChangedObservable=new r.y$,this.state=Xi.NOT_IN_XR,this.sessionManager=new nn(e),this.camera=new gl("webxr",e,this.sessionManager),this.featuresManager=new vl.d(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new yl(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(Xi.NOT_IN_XR),t.dispose(),e}))}dispose(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),null===(e=this._spectatorCamera)||void 0===e||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),n={}){var s,r,o;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(Xi.ENTERING_XR),"viewer"!==t&&"local"!==t&&(n.optionalFeatures=n.optionalFeatures||[],n.optionalFeatures.push(t)),n=await this.featuresManager._extendXRSessionInitObject(n),"immersive-ar"===e&&"unbounded"!==t&&_.Y.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,n),await this.sessionManager.setReferenceSpaceTypeAsync(t);const a=await i.initializeXRLayerAsync(this.sessionManager.session),l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(vl.b.LAYERS)||(l.baseLayer=a),this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(r=null===(s=this._nonVRCamera)||void 0===s?void 0:s.inputs)||void 0===r?void 0:r.attachedToElement),null===(o=this._nonVRCamera)||void 0===o||o.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1)),this.sessionManager.onXRSessionEnded.addOnce((()=>{this.state!==Xi.EXITING_XR&&this._setState(Xi.EXITING_XR),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(Xi.NOT_IN_XR)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(Xi.IN_XR)})),this.sessionManager}catch(e){throw console.log(e),console.log(e.message),this._setState(Xi.NOT_IN_XR),e}}exitXRAsync(){return this.state!==Xi.IN_XR?Promise.resolve():(this._setState(Xi.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/((null==e?void 0:e.fps)?e.fps:1e3)*1e3,i=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,n=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{this.state===Xi.IN_XR?(this._spectatorCamera=new ei("webxr-spectator",o.P.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new o._f,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(n),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):this.state===Xi.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(n),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(n),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class xl{constructor(e,t,i=-1,n=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=n,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new r.y$,this.onButtonStateChangedObservable=new r.y$}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}xl.BUTTON_TYPE="button",xl.SQUEEZE_TYPE="squeeze",xl.THUMBSTICK_TYPE="thumbstick",xl.TOUCHPAD_TYPE="touchpad",xl.TRIGGER_TYPE="trigger";class bl{constructor(e,t,i,n,s=!1,o){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=n,this._doNotLoadControllerMesh=s,this._controllerCache=o,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,n=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new xl(e,i,n,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new r.y$,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach((e=>this.getComponent(e).dispose())),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach((e=>{e.setEnabled(!1)})),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).filter((t=>t.type===e))}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?_.Y.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,n)=>{const s=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void s(e[0].meshes)}ta.n.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push({...t,meshes:e}),s(e)}),null,((e,i)=>{_.Y.Log(i),_.Y.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),n(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).update(this.gamepadObject))),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const n=i?.5*t+.5:t;o._f.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,n,e.valueMesh.rotationQuaternion),o.P.LerpToRef(e.minMesh.position,e.maxMesh.position,n,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new Nt.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0)}}class Tl extends bl{constructor(e,t,i){super(e,Sl[i],t,i),this.profileId=Tl.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new Nt.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}Tl.ProfileId="generic-trigger";const Sl={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 El extends bl{constructor(e,t,i,n,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=n,this.controllerCache=s,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=ta.n.IsPluginForExtensionAvailable(".glb");return e||_.Y.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const n=t.visualResponses[i];if("transform"===n.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,n.valueNodeName),minMesh:this._getChildByName(this.rootMesh,n.minNodeName),maxMesh:this._getChildByName(this.rootMesh,n.maxNodeName)};else{const s=t.type===xl.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:n.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===xl.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=Kn(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new Gi.K(i+"mat",this.scene),t.material.diffuseColor=a.Wo.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new Nt.Kj(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i<e.length;i++){const n=e[i];n.isPickable=!1,n.parent||(t=n)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||this.rootMesh.rotate(We.RD.Y,Math.PI,We.T.WORLD)}_updateModel(e){this.disableAnimation||this.getComponentIds().forEach((e=>{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],n=this.layout.components[e];Object.keys(n.visualResponses).forEach((e=>{const s=n.visualResponses[e];let r=t.value;if("xAxis"===s.componentProperty?r=t.axes.x:"yAxis"===s.componentProperty&&(r=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],r,"button"!==s.componentProperty);else{const n=i.states[e].valueMesh;n&&(n.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const Cl=[];class Al{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const n=[];i&&n.push(i),n.push(...e.profiles||[]),n.length&&!n[0]&&n.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&n.push("oculus-touch-v2");const s=n.indexOf("windows-mixed-reality");if(-1!==s&&n.splice(s,0,"microsoft-mixed-reality"),n.length||n.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,n,e,t).catch((()=>s.call(this,n,e,t)))}return this._LoadProfilesFromAvailableControllers(n,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=de.w1.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e.toString()))),this._ProfilesList}static ClearControllerCache(){Cl.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),Cl.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i<e.length;++i)if(e[i]&&t[e[i]])return e[i];throw new Error(`neither controller ${e[0]} nor all fallbacks were found in the repository,`)})).then((e=>(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=de.w1.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new El(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:Cl)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let n=0;n<e.length;++n){if(!e[n])continue;const s=this.FindFallbackWithProfileId(e[n]);for(let e=0;e<s.length;++e){const n=this._AvailableControllers[s[e]];if(n)return Promise.resolve(n(t,i))}}throw new Error("no controller requested was found in the available controllers list")}}Al._AvailableControllers={},Al._Fallbacks={},Al._ProfileLoadingPromises={},Al.BaseRepositoryUrl="https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist",Al.PrioritizeOnlineRepository=!0,Al.UseOnlineRepository=!0,Al.DisableControllerCache=!0,Al.RegisterController(Tl.ProfileId,((e,t)=>new Tl(t,e.gamepad,e.handedness))),Al.DefaultFallbacks();let Pl=0;class Rl{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new o.P,this._disposed=!1,this.onDisposeObservable=new r.y$,this.onMeshLoadedObservable=new r.y$,this.onMotionControllerInitObservable=new r.y$,this._uniqueId=`controller-${Pl++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Un.x(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new o._f,this.inputSource.gripSpace&&(this.grip=new Un.x(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new o._f),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&Al.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{var t;e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.renderingGroupId=this._options.renderingGroupId))),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&(null===(t=this.motionController)||void 0===t||t.dispose())}))}),(()=>{de.w1.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;o.P.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){const n=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=n,n){const e=n.transform.position;this.pointer.position.set(e.x,e.y,e.z);const t=n.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent}if(this.inputSource.gripSpace&&this.grip){const n=e.getPose(this.inputSource.gripSpace,t);if(n){const e=n.transform.position,t=n.transform.orientation;this.grip.position.set(e.x,e.y,e.z),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent}this.motionController&&this.motionController.updateFromXRFrame(e)}}class Ml{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new r.y$,this.onControllerRemovedObservable=new r.y$,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera)}))})),this._options.customControllersRepositoryURL&&(Al.BaseRepositoryUrl=this._options.customControllersRepositoryURL),Al.UseOnlineRepository=!this._options.disableOnlineControllerRepository,Al.UseOnlineRepository)try{Al.UpdateProfilesList().catch((()=>{Al.UseOnlineRepository=!1}))}catch(e){Al.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const t of e)if(-1===i.indexOf(t)){const e=new Rl(this.xrSessionManager.scene,t,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const n=[],s=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?n.push(e):s.push(e)})),this.controllers=n,s.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()}))}dispose(){this.controllers.forEach((e=>{e.dispose()})),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),Al.ClearControllerCache()}}var Il=i(2844);class Dl extends Il.F{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Yt.z(new o.P,new o.P),disabledByNearInteraction:!1,id:Dl._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new o.P,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new a.Wo(.9,.9,.9),this.laserPointerDefaultColor=new a.Wo(.7,.7,.7),this.selectionMeshDefaultColor=new a.Wo(.8,.8,.8),this.selectionMeshPickedColor=new a.Wo(.3,.3,1),this._identityMatrix=o.y3.Identity(),this._screenCoordinatesRef=o.P.Zero(),this._viewportRef=new ui.l(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 Yt.z(new o.P,new o.P),disabledByNearInteraction:!1,id:Dl._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null}_getPointerSelectionDisabledByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].disabledByNearInteraction;return!0}_setPointerSelectionDisabledByPointerId(e,t){const i=Object.keys(this._controllers);for(let n=0;n<i.length;++n)if(this._controllers[i[n]].id===e)return void(this._controllers[i[n]].disabledByNearInteraction=t)}_onXRFrame(e){Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e];if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,n=this._options.xrInput.xrCamera;n&&(n.viewport.toGlobalToRef(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),this._viewportRef),o.P.ProjectToRef(i,this._identityMatrix,e.getTransformMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let n=null;this._utilityLayerScene&&(n=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const s=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);n&&n.hit?s&&s.hit?n.distance<s.distance?t.pick=n:t.pick=s:t.pick=n:t.pick=s,t.pick&&t.xrController&&(t.pick.aimTransform=t.xrController.pointer,t.pick.gripTransform=t.xrController.grip||null);const r=t.pick;if(r&&r.pickedPoint&&r.hit){this._updatePointerDistance(t.laserPointer,r.distance),t.selectionMesh.position.copyFrom(r.pickedPoint),t.selectionMesh.scaling.x=Math.sqrt(r.distance),t.selectionMesh.scaling.y=Math.sqrt(r.distance),t.selectionMesh.scaling.z=Math.sqrt(r.distance);const e=this._convertNormalToDirectionOfRay(r.getNormal(!0),t.tmpRay),i=.001;if(t.selectionMesh.position.copyFrom(r.pickedPoint),e){const n=o.P.Cross(We.RD.Y,e),s=o.P.Cross(e,n);o.P.RotationFromAxisToRef(s,e,n,t.selectionMesh.rotation),t.selectionMesh.position.addInPlace(e.scale(i))}t.selectionMesh.isVisible=this.displaySelectionMesh,t.meshUnderPointer=r.pickedMesh}else t.selectionMesh.isVisible=!1,this._updatePointerDistance(t.laserPointer,1),t.meshUnderPointer=null}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||zn.x.DefaultUtilityLayer.utilityLayerScene}_attachGazeMode(e){const t=this._controllers[e&&e.uniqueId||"camera"],i=this._options.timeToSelect||3e3,n=this._options.useUtilityLayer?this._utilityLayerScene:this._scene;let s=new bn.p;const r=cn("selection",{diameter:.0525,thickness:.015,tessellation:20},n);r.isVisible=!1,r.isPickable=!1,r.parent=t.selectionMesh;let o=0,a=!1;const l={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,r.isVisible=!1,t.pick.hit)if(this._pickingMoved(s,t.pick))a&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),a=!1,o=0;else if(o>i/10&&(r.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),a=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),r.isVisible=!1;else{const e=1-o/i;r.scaling.set(e,e,e)}else a=!1,o=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}})),void 0!==this._options.renderingGroupId&&(r.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&a&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),r.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const n={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(n,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,n):(this._scene.simulatePointerDown(t.pick,n),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,n)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(n,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,n),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const n=n=>{this._options.overrideButtonId&&(t.selectionComponent=n.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=n.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((n=>{if(n.changes.pressed){const s=n.changes.pressed.current;t.pick?(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),s?(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)):!s||this._options.enablePointerSelectionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)}}))};e.motionController?n(e.motionController):e.onMotionControllerInitObservable.add(n)}else{const e=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)},n=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)};t.eventListeners={selectend:n,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",n)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(o.P.Dot(e,t.direction))<Math.PI/2&&e.scaleInPlace(-1),e}_detachController(e){const t=this._controllers[e];if(t){if(t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new bn.p,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){de.w1.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||zn.x.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():an("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const n=new Gi.K("laserPointerMat",t);n.emissiveColor=this.laserPointerDefaultColor,n.alpha=.7,i.material=n,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():cn("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;const r=new Gi.K("targetMat",t);return r.specularColor=a.Wo.Black(),r.emissiveColor=this.selectionMeshDefaultColor,r.backFaceCulling=!1,s.material=r,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){var i;if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;null===(i=e.pickedPoint)||void 0===i||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const n=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>n}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}Dl._IdCounter=200,Dl.Name=vl.b.POINTER_SELECTION,Dl.Version=1,vl.d.AddWebXRFeature(Dl.Name,((e,t)=>()=>new Dl(e,t)),Dl.Version,!0);var Ol,wl,Nl,Fl=i(4834),Ll=i(9401);Ll.P.prototype._projectOnTrianglesToRef=function(e,t,i,n,s,r){const a=o.jp.Vector3[0],l=o.jp.Vector3[1];let h=1/0;for(let r=this.indexStart;r<this.indexStart+this.indexCount-(3-n);r+=n){const n=i[r],c=i[r+1],u=i[r+2];if(s&&4294967295===u){r+=2;continue}const d=t[n],p=t[c],f=t[u];if(!d||!p||!f)continue;const _=o.P.ProjectOnTriangleToRef(e,d,p,f,l);_<h&&(a.copyFrom(l),h=_)}return r.copyFrom(a),h},Ll.P.prototype._projectOnUnIndexedTrianglesToRef=function(e,t,i,n){const s=o.jp.Vector3[0],r=o.jp.Vector3[1];let a=1/0;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=3){const n=t[i],l=t[i+1],h=t[i+2],c=o.P.ProjectOnTriangleToRef(e,n,l,h,r);c<a&&(s.copyFrom(r),a=c)}return n.copyFrom(s),a},Ll.P.prototype.projectToRef=function(e,t,i,n){const s=this.getMaterial();if(!s)return-1;let r=3,o=!1;switch(s.fillMode){case 3:case 5:case 6:case 8:return-1;case 7:r=1,o=!0}return 4===s.fillMode?-1:!i.length&&this._mesh._unIndexed?this._projectOnUnIndexedTrianglesToRef(e,t,i,n):this._projectOnTrianglesToRef(e,t,i,r,o,n)},function(e){e[e.DEHYDRATED=0]="DEHYDRATED",e[e.HOVER=1]="HOVER",e[e.TOUCH=2]="TOUCH"}(Ol||(Ol={})),function(e){e[e.DISABLED=0]="DISABLED",e[e.CENTERED_ON_CONTROLLER=1]="CENTERED_ON_CONTROLLER",e[e.CENTERED_IN_FRONT=2]="CENTERED_IN_FRONT"}(wl||(wl={}));class Bl extends Il.F{constructor(e,t){super(e),this._options=t,this._tmpRay=new Yt.z(new o.P,new o.P),this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:n}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:n,currentAnimationState:Ol.DEHYDRATED,grabRay:new Yt.z(new o.P,new o.P),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:Bl._IdCounter++,pickedPointVisualCue:s},this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new a.Wo(.8,.8,.8),this.selectionMeshPickedColor=new a.Wo(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=wl.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null}setFarInteractionFeature(e){this._farInteractionFeature=e}_nearPickPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearPickable}_nearGrabPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearGrabbable}_nearInteractionPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&(e.isNearPickable||e.isNearGrabbable)}_controllerAvailablePredicate(e,t){let i=e;for(;i;){if(i.reservedDataStore&&i.reservedDataStore.nearInteraction&&i.reservedDataStore.nearInteraction.excludedControllerId===t)return!1;i=i.parent}return!0}_handleTransitionAnimation(e,t){var i;if(e.currentAnimationState!==t&&this._options.nearInteractionControllerMode===wl.CENTERED_IN_FRONT&&!(null===(i=e.xrController)||void 0===i?void 0:i.inputSource.hand)){if(t>e.currentAnimationState)switch(e.currentAnimationState){case Ol.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===Ol.HOVER)break;case Ol.HOVER:if(e.touchCollisionMeshFunction(!0),t===Ol.TOUCH)break}else switch(e.currentAnimationState){case Ol.TOUCH:if(e.touchCollisionMeshFunction(!1),t===Ol.HOVER)break;case Ol.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===Ol.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var n;const s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(o.jp.Vector3[0]),s.grabRay.direction.copyFrom(o.jp.Vector3[0]),this._options.nearInteractionControllerMode!==wl.CENTERED_IN_FRONT||(null===(n=s.xrController)||void 0===n?void 0:n.inputSource.hand)||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{var i;const n=this._controllers[t],s=null===(i=n.xrController)||void 0===i?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!n.xrController||!s&&(!this._options.nearInteractionControllerMode||!n.xrController.inputSource.gamepad))return void(n.pick=null);if(n.hoverInteraction=!1,n.nearInteraction=!1,!n.xrController)return;if(s){const i=s.get("index-finger-tip");if(i){const n=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(n&&n.transform){const e=this._scene.useRightHandedSystem?1:-1;o.jp.Vector3[0].set(n.transform.position.x,n.transform.position.y,n.transform.position.z*e),o.jp.Quaternion[0].set(n.transform.orientation.x,n.transform.orientation.y,n.transform.orientation.z*e,n.transform.orientation.w*e),this._processTouchPoint(t,o.jp.Vector3[0],o.jp.Quaternion[0])}}}else if(n.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==wl.DISABLED){let e=n.xrController.pointer;n.xrController.grip&&this._options.nearInteractionControllerMode===wl.CENTERED_ON_CONTROLLER&&(e=n.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const r=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance<e.distance?t:e:t:e,i},a=e=>{let t=new bn.p,i=!1;const n=e&&e.pickedPoint&&e.hit;return(null==e?void 0:e.pickedPoint)&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),n&&!i&&(t=e),t};if(!n.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(n,this._hoverRadius,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const i=r(this._pickWithSphere(n,this._hoverRadius,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(i&&i.hit&&(e=a(i),e.hit&&(n.hoverInteraction=!0)),n.hoverInteraction){let t=null;const i=s?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(n,i,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const o=a(r(this._pickWithSphere(n,i,this._scene,(e=>this._nearPickPredicate(e))),t));o.hit&&(e=o,n.nearInteraction=!0)}n.stalePick=n.pick,n.pick=e,n.pick&&n.pick.pickedPoint&&n.pick.hit?(n.meshUnderPointer=n.pick.pickedMesh,n.pickedPointVisualCue.position.copyFrom(n.pick.pickedPoint),n.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(n.id,!0)):(n.meshUnderPointer=null,n.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(n.id,!1))}let l=Ol.DEHYDRATED;n.grabInteraction||n.nearInteraction?l=Ol.TOUCH:n.hoverInteraction&&(l=Ol.HOVER),this._handleTransitionAnimation(n,l)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||zn.x.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||zn.x.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Kn("nearInteraction",{diameter:.0105},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=o._f.Identity();const i=new Gi.K("targetMat",e);return i.specularColor=a.Wo.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.nearInteractionTargetMesh=null))}));const n=n=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),n&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!n&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!n||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;n(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;n(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i))},n=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)};t.eventListeners={selectend:n,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",n)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new bn.p,e)})),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||zn.x.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Kn("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:Fl.O.ParseFromSnippetAsync("8RUNKL#3",e).then((e=>{t.material=e}));const i=new ee;i.setEasingMode(j.EASINGMODE_EASEINOUT);const n=new o.P(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),s=this._controllerPickRadius*(4/3),r=new o.P(s,s,s),a=this._controllerPickRadius*(7/6),l=new o.P(a,a,a),h=.8*this._controllerPickRadius,c=new o.P(h,h,h),u=1.5*this._controllerPickRadius,d=[{frame:0,value:n},{frame:10,value:new o.P(u,u,u)},{frame:18,value:r}],p=[{frame:0,value:r},{frame:10,value:c},{frame:18,value:n}],f=[{frame:0,value:o.P.ZeroReadOnly},{frame:12,value:l},{frame:15,value:n}],_=[{frame:0,value:n},{frame:10,value:o.P.ZeroReadOnly},{frame:15,value:o.P.ZeroReadOnly}],m=new D.f("touch","scaling",60,D.f.ANIMATIONTYPE_VECTOR3,D.f.ANIMATIONLOOPMODE_CONSTANT),g=new D.f("release","scaling",60,D.f.ANIMATIONTYPE_VECTOR3,D.f.ANIMATIONLOOPMODE_CONSTANT),v=new D.f("hydrate","scaling",60,D.f.ANIMATIONTYPE_VECTOR3,D.f.ANIMATIONLOOPMODE_CONSTANT),y=new D.f("dehydrate","scaling",60,D.f.ANIMATIONTYPE_VECTOR3,D.f.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(i),g.setEasingFunction(i),v.setEasingFunction(i),y.setEasingFunction(i),m.setKeys(d),g.setKeys(p),v.setKeys(f),y.setKeys(_),{touchCollisionMesh:t,touchCollisionMeshFunction:i=>{const n=i?m:g;e.beginDirectAnimation(t,[n],0,18,!1,1)},hydrateCollisionMeshFunction:i=>{const n=i?v:y;i&&(t.isVisible=!0),e.beginDirectAnimation(t,[n],0,15,!1,1,(()=>{i||(t.isVisible=!1)}))}}}_pickWithSphere(e,t,i,n){const s=new bn.p;if(s.distance=1/0,e.touchCollisionMesh&&e.xrController){const r=e.touchCollisionMesh.position,o=Nn.K.CreateFromCenterAndRadius(r,t);for(let t=0;t<i.meshes.length;t++){const r=i.meshes[t];if(!n(r)||!this._controllerAvailablePredicate(r,e.xrController.uniqueId))continue;const a=Bl.PickMeshWithSphere(r,o);a&&a.hit&&a.distance<s.distance&&(s.hit=a.hit,s.pickedMesh=r,s.pickedPoint=a.pickedPoint,s.aimTransform=e.xrController.pointer,s.gripTransform=e.xrController.grip||null,s.originMesh=e.touchCollisionMesh,s.distance=a.distance)}}return s}static PickMeshWithSphere(e,t,i=!1){const n=e.subMeshes,s=new bn.p,r=e.getBoundingInfo();if(!e._generatePointsArray())return s;if(!e.subMeshes||!r)return s;if(!i&&!Nn.K.Intersects(r.boundingSphere,t))return s;const a=o.jp.Vector3[0],l=o.jp.Vector3[1];let h,c,u,d=1/0;const p=o.jp.Vector3[2],f=o.jp.Matrix[0];f.copyFrom(e.getWorldMatrix()),f.invert(),o.P.TransformCoordinatesToRef(t.center,f,p);for(let i=0;i<n.length;i++)n[i].projectToRef(p,e._positions,e.getIndices(),l),o.P.TransformCoordinatesToRef(l,e.getWorldMatrix(),l),h=o.P.Distance(l,t.center),u=o.P.Distance(l,e.getAbsolutePosition()),c=o.P.Distance(t.center,e.getAbsolutePosition()),-1!==c&&-1!==u&&u>c&&(h=0,l.copyFrom(t.center)),-1!==h&&h<d&&(d=h,a.copyFrom(l));return d<t.radius&&(s.hit=!0,s.distance=d,s.pickedMesh=e,s.pickedPoint=a.clone()),s}}Bl._IdCounter=200,Bl.Name=vl.b.NEAR_INTERACTION,Bl.Version=1,vl.d.AddWebXRFeature(Bl.Name,((e,t)=>()=>new Bl(e,t)),Bl.Version,!0);class Ul{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class Vl{}class kl{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new r.y$,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw de.w1.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let n=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";n+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const s=document.createElement("style");s.appendChild(document.createTextNode(n)),document.getElementsByTagName("head")[0].appendChild(s);const r=document.createElement("button");r.className="babylonVRicon",r.title=`${e} - ${i}`,this._buttons.push(new Ul(r,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",r.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce((()=>{this.dispose()})))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{e==Xi.NOT_IN_XR&&this._updateButtons(null)})),(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):de.w1.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const n=new kl(e,i);return await n.setHelperAsync(t,i.renderTarget||void 0),n}async _enterXRWithButtonIndex(e=0){if(this._helper.state==Xi.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==Xi.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,n=i.title;i.title="Error entering XR session : "+n,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}function Gl(e){var t;let i=0;const n=Date.now();e.observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{};const s=e.contextObservable.add((t=>{const r=Date.now();i=r-n;const o={startTime:n,currentTime:r,deltaTime:i,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(o),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(o)),i>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(o))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(Nl||(Nl={}));class zl{constructor(e){var t,i;this.onEachCountObservable=new r.y$,this.onTimerAbortedObservable=new r.y$,this.onTimerEndedObservable=new r.y$,this.onStateChangedObservable=new r.y$,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{const t=Date.now();this._timer=t-this._startTime;const i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},n=this._breakOnNextTick||this._breakCondition(i);n||this._timer>=this._timeToEnd?this._stop(i,n):this.onEachCountObservable.notifyObservers(i)},this._setState(Nl.INIT),this._contextObservable=e.contextObservable,this._observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{},this._breakCondition=null!==(i=e.breakCondition)&&void 0!==i?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===Nl.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(Nl.STARTED)}stop(){this._state===Nl.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(Nl.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class Wl extends Il.F{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new a.HE(1,1,1,1),this._tmpRay=new Yt.z(new o.P,new o.P),this._tmpVector=new o.P,this._tmpQuaternion=new o._f,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 r.y$,this.teleportationEnabled=!0,this._rotationEnabled=!0,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(xl.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(xl.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{this.teleportationEnabled&&i.changes.pressed&&(i.changes.pressed.current?(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,Gl({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})):(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,o._f.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);o._f.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else this._xrSessionManager.scene.onPointerObservable.add((i=>{i.type===Re.kD.POINTERDOWN?(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,Gl({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})):i.type===Re.kD.POINTERUP&&(t.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 a.HE(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)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t)for(let i=0;i<this._snapToPositions.length;++i)if(this._snapToPositions[i].equals(e)){t=i;break}return-1!==t&&(this._snapToPositions.splice(t,1),!0)}setSelectionFeature(e){this._selectionFeature=e}_onXRFrame(e){const t=this._xrSessionManager.currentFrame,i=this._xrSessionManager.scene;if(!this.attach||!t)return;const n=this._options.teleportationTargetMesh;if(this._currentTeleportationControllerId){if(!n)return;n.rotationQuaternion=n.rotationQuaternion||new o._f;const e=this._controllers[this._currentTeleportationControllerId];if(e&&e.teleportationState.forward){o._f.RotationYawPitchRollToRef(e.teleportationState.currentRotation+e.teleportationState.baseRotation,0,0,n.rotationQuaternion);let t=!1;if(e.xrController.getWorldPointerRayToRef(this._tmpRay),this.straightRayEnabled){const n=i.pickWithRay(this._tmpRay,(e=>{if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y<this._options.xrInput.xrCamera.globalPosition.y}));if(n&&n.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(n.pickedMesh))return e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),void this._showParabolicPath(n);n&&n.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(n),this._setTargetMeshVisibility(!0),this._showParabolicPath(n))}if(this.parabolicRayEnabled&&!t){const n=e.xrController.pointer.rotationQuaternion.toEulerAngles().x,s=Math.PI/2-Math.abs(n)+1,r=this.parabolicCheckRadius*s;this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(2*r),this._tmpVector),this._tmpVector.y=this._tmpRay.origin.y,this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(r)),this._tmpVector.subtractToRef(this._tmpRay.origin,this._tmpRay.direction),this._tmpRay.direction.normalize();const o=i.pickWithRay(this._tmpRay,(e=>!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e)));if(o&&o.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(o.pickedMesh))return e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),void this._showParabolicPath(o);o&&o.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(o),this._setTargetMeshVisibility(!0),this._showParabolicPath(o))}this._setTargetMeshVisibility(t)}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||zn.x.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=(0,dn.$6)("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,n=new zi.c("teleportationPlaneDynamicTexture",i,e,!0);n.hasAlpha=!0;const s=n.getContext(),r=i/2,o=i/2,a=200;s.beginPath(),s.arc(r,o,a,0,2*Math.PI,!1),s.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",s.fill(),s.lineWidth=10,s.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",s.stroke(),s.closePath(),n.update();const l=new Gi.K("teleportationPlaneMaterial",e);l.diffuseTexture=n,t.material=l}const i=cn("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new D.f("animationInnerCircle","position.y",30,D.f.ANIMATIONTYPE_FLOAT,D.f.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),t.setKeys(n);const s=new ne;s.setEasingMode(j.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const n=an("rotationCone",{diameterTop:0,tessellation:4},e);if(n.isPickable=!1,n.scaling.set(.5,.12,.2),n.rotate(We.RD.X,Math.PI/2),n.position.z=.6,n.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,n.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new Gi.K("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new a.Wo(.3,.3,1):t.diffuseColor=new a.Wo(.3,.3,1),t.alpha=.9,i.material=t,n.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,n.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,n=Number.MAX_VALUE;if(this._snapToPositions.length){const s=t*t;this._snapToPositions.forEach((t=>{const r=o.P.DistanceSquared(t,e);r<=s&&r<n&&(n=r,i=t)}))}return i}_setTargetMeshPosition(e){const t=e.pickedPoint;if(!this._options.teleportationTargetMesh||!t)return;const i=this._findClosestSnapPointWithRadius(t);this._snappedToPoint=!!i,this.snapPointsOnly&&!this._snappedToPoint&&this._teleportationRingMaterial?this._teleportationRingMaterial.diffuseColor.set(1,.3,.3):this.snapPointsOnly&&this._snappedToPoint&&this._teleportationRingMaterial&&this._teleportationRingMaterial.diffuseColor.set(.3,.3,1),this._options.teleportationTargetMesh.position.copyFrom(i||t),this._options.teleportationTargetMesh.position.y+=.01,this.onTargetMeshPositionUpdatedObservable.notifyObservers(e)}_setTargetMeshVisibility(e,t){this._options.teleportationTargetMesh&&(this._options.teleportationTargetMesh.isVisible!==e||t)&&(this._options.teleportationTargetMesh.isVisible=e,this._options.teleportationTargetMesh.getChildren(void 0,!1).forEach((t=>{t.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||zn.x.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],n=X.j_.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,r=new Array(26).fill(s||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(n.getPoints(),e):this._quadraticBezierCurve=os("teleportation path line",{points:n.getPoints(),instance:this._quadraticBezierCurve,updatable:!0,colors:r},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint))if(this.skipNextTeleportation)this.skipNextTeleportation=!1;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=this._options.xrInput.xrCamera.realWorldHeight;this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,o._f.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)}}}Wl.Name=vl.b.TELEPORTATION,Wl.Version=1,vl.d.AddWebXRFeature(Wl.Name,((e,t)=>()=>new Wl(e,t)),Wl.Version,!0);class Hl{}class Xl{constructor(){}static CreateAsync(e,t={}){const i=new Xl;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const n={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?n.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:n.optionalFeatures=t.optionalFeatures),i.enterExitUI=new kl(e,n)}return yl.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new Ml(e.sessionManager,e.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const e={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(Dl.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(Wl.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(Bl.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0,...t.nearInteractionOptions})),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(_.Y.Error("Error initializing XR"),_.Y.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}var jl=!0;function Yl(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}k.x.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;e<this.lights.length;e++)this.lights[e].dispose();0===this.lights.length&&new Li.e("default light",o.P.Up(),this)},k.x.prototype.createDefaultCamera=function(e=!1,t=!1,i=!1){if(t&&this.activeCamera&&(this.activeCamera.dispose(),this.activeCamera=null),!this.activeCamera){const t=this.getWorldExtends((e=>e.isVisible&&e.isEnabled())),n=t.max.subtract(t.min),s=t.min.add(n.scale(.5));let r,a=1.5*n.length();if(isFinite(a)||(a=1,s.copyFromFloats(0,0,0)),e){const e=new Ft("default camera",-Math.PI/2,Math.PI/2,a,s,this);e.lowerRadiusLimit=.01*a,e.wheelPrecision=100/a,r=e}else{const e=new Dt.c("default camera",new o.P(s.x,s.y,-a),this);e.setTarget(s),r=e}r.minZ=.01*a,r.maxZ=1e3*a,r.speed=.2*a,this.activeCamera=r,i&&r.attachControl()}},k.x.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},k.x.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,n=0,s=!0){if(!e)return _.Y.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);const r=(0,Yn.NR)("hdrSkyBox",{size:i},this);if(t){const t=new Ya.Y("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Ce.x.SKYBOX_MODE),t.microSurface=1-n,t.disableLighting=!0,t.twoSidedLighting=!0,r.material=t}else{const t=new Gi.K("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Ce.x.SKYBOX_MODE),t.disableLighting=!0,r.material=t}return r.isPickable=!1,r.infiniteDistance=!0,r.ignoreCameraMaxZ=!0,r},k.x.prototype.createDefaultEnvironment=function(e){return Ha?new Ha(e,this):null},k.x.prototype.createDefaultVRExperience=function(e={}){return new gn(this,e)},k.x.prototype.createDefaultXRExperienceAsync=function(e={}){return Xl.CreateAsync(this,e).then((e=>e))};class ql extends Ce.x{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new r.y$),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):_.Y.Error(null==e?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===(null==e?void 0:e.name)){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return _.Y.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}constructor(e,t,i,n=!1,s=!1,r=Ce.x.TRILINEAR_SAMPLINGMODE,o={},a,l=5){var h,c;super(null,i,!n,s),this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this._resizeInternalTexture=()=>{var e;null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||de.w1.IsExponentOfTwo(this.video.videoWidth)&&de.w1.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=Ce.x.WRAP_ADDRESSMODE,this.wrapV=Ce.x.WRAP_ADDRESSMODE):(this.wrapU=Ce.x.CLAMP_ADDRESSMODE,this.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=null!==(e=this._format)&&void 0!==e?e:5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState<this.video.HAVE_CURRENT_DATA)return;if(this._displayingPosterTexture)return;const e=this.getScene().getFrameId();this._frameId!==e&&(this._frameId=e,this._getEngine().updateVideoTexture(this._texture,this._externalTexture?this._externalTexture:this.video,this._invertY))},this._settings={autoPlay:!0,loop:!0,autoUpdateTexture:!0,...o},this._onError=a,this._generateMipMaps=n,this._initialSamplingMode=r,this.autoUpdateTexture=this._settings.autoUpdateTexture,this._currentSrc=t,this.name=e||this._getName(t),this.video=this._getVideo(t),this._externalTexture=null!==(c=null===(h=this._engine)||void 0===h?void 0:h.createExternalTexture(this.video))&&void 0!==c?c:null,this._settings.independentVideoSource||(this._settings.poster&&(this.video.poster=this._settings.poster),void 0!==this._settings.autoPlay&&(this.video.autoplay=this._settings.autoPlay),void 0!==this._settings.loop&&(this.video.loop=this._settings.loop),void 0!==this._settings.muted&&(this.video.muted=this._settings.muted),this.video.setAttribute("playsinline",""),this.video.addEventListener("paused",this._updateInternalTexture),this.video.addEventListener("seeked",this._updateInternalTexture),this.video.addEventListener("emptied",this._reset),this._settings.autoPlay&&this._handlePlay()),this._createInternalTextureOnEvent=this._settings.poster&&!this._settings.autoPlay?"play":"canplay",this.video.addEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._format=l;const u=this.video.readyState>=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return de.w1.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(de.w1.SetCorsBehavior(e,t),t.src=e):(de.w1.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{Yl(t)})),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new ql(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()),null===(e=this._externalTexture)||void 0===e||e.dispose()}static CreateFromStreamAsync(e,t,i,n=!0){const s=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(s),s.style.transform="scale(0.0001, 0.0001)",s.style.opacity="0",s.style.position="fixed",s.style.bottom="0px",s.style.right="0px"),s.setAttribute("autoplay",""),s.setAttribute("muted","true"),s.setAttribute("playsinline",""),s.muted=!0,s.isNative||(void 0!==s.mozSrcObject?s.mozSrcObject=t:"object"==typeof s.srcObject?s.srcObject=t:s.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const r=new ql("video",s,e,!0,n,void 0,void 0,void 0,4);e.getEngine()._badOS&&r.onDisposeObservable.addOnce((()=>{s.remove()})),r.onDisposeObservable.addOnce((()=>{Yl(s)})),t(r),s.removeEventListener("playing",i)};s.addEventListener("playing",i),s.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,n=!0){if(navigator.mediaDevices){const s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),r=await this.CreateFromStreamAsync(e,s,t,n);return r.onDisposeObservable.addOnce((()=>{s.getTracks().forEach((e=>{e.stop()}))})),r}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,n=!1,s=!0){this.CreateFromWebCamAsync(e,i,n,s).then((function(e){t&&t(e)})).catch((function(e){_.Y.Error(e.name)}))}}class Kl extends Xa{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const n={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new ql((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Ce.x.TRILINEAR_SAMPLINGMODE,n);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{var t;(null===(t=e.pickInfo)||void 0===t?void 0:t.pickedMesh)===this.mesh&&this._texture.video.play()}),Re.kD.POINTERDOWN)),this._textureObserver=s.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),s}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}Kl.MODE_MONOSCOPIC=Xa.MODE_MONOSCOPIC,Kl.MODE_TOPBOTTOM=Xa.MODE_TOPBOTTOM,Kl.MODE_SIDEBYSIDE=Xa.MODE_SIDEBYSIDE;class $l{get gpuFrameTimeCounter(){return this.engine.getGPUFrameTimeCounter()}get captureGPUFrameTime(){return this._captureGPUFrameTime}set captureGPUFrameTime(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,this.engine.captureGPUFrameTime(e))}get shaderCompilationTimeCounter(){return this._shaderCompilationTime}get captureShaderCompilationTime(){return this._captureShaderCompilationTime}set captureShaderCompilationTime(e){e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((()=>{this._shaderCompilationTime.fetchNewFrame(),this._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((()=>{this._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))}constructor(e){this.engine=e,this._captureGPUFrameTime=!1,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new Os.z,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}dispose(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null}}class Ql{get activeMeshesEvaluationTimeCounter(){return this._activeMeshesEvaluationTime}get captureActiveMeshesEvaluationTime(){return this._captureActiveMeshesEvaluationTime}set captureActiveMeshesEvaluationTime(e){e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((()=>{de.w1.StartPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((()=>{de.w1.EndPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.endMonitoring()}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))}get renderTargetsRenderTimeCounter(){return this._renderTargetsRenderTime}get captureRenderTargetsRenderTime(){return this._captureRenderTargetsRenderTime}set captureRenderTargetsRenderTime(e){e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((()=>{de.w1.StartPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((()=>{de.w1.EndPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))}get particlesRenderTimeCounter(){return this._particlesRenderTime}get captureParticlesRenderTime(){return this._captureParticlesRenderTime}set captureParticlesRenderTime(e){e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((()=>{de.w1.StartPerformanceCounter("Particles"),this._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((()=>{de.w1.EndPerformanceCounter("Particles"),this._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))}get spritesRenderTimeCounter(){return this._spritesRenderTime}get captureSpritesRenderTime(){return this._captureSpritesRenderTime}set captureSpritesRenderTime(e){e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((()=>{de.w1.StartPerformanceCounter("Sprites"),this._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((()=>{de.w1.EndPerformanceCounter("Sprites"),this._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))}get physicsTimeCounter(){return this._physicsTime}get capturePhysicsTime(){return this._capturePhysicsTime}set capturePhysicsTime(e){e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((()=>{de.w1.StartPerformanceCounter("Physics"),this._physicsTime.beginMonitoring()})),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((()=>{de.w1.EndPerformanceCounter("Physics"),this._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))}get animationsTimeCounter(){return this._animationsTime}get captureAnimationsTime(){return this._captureAnimationsTime}set captureAnimationsTime(e){e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((()=>{this._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))}get frameTimeCounter(){return this._frameTime}get captureFrameTime(){return this._captureFrameTime}set captureFrameTime(e){this._captureFrameTime=e}get interFrameTimeCounter(){return this._interFrameTime}get captureInterFrameTime(){return this._captureInterFrameTime}set captureInterFrameTime(e){this._captureInterFrameTime=e}get renderTimeCounter(){return this._renderTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((()=>{this._renderTime.beginMonitoring(),de.w1.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((()=>{this._renderTime.endMonitoring(!1),de.w1.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))}get cameraRenderTimeCounter(){return this._cameraRenderTime}get captureCameraRenderTime(){return this._captureCameraRenderTime}set captureCameraRenderTime(e){e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((e=>{this._cameraRenderTime.beginMonitoring(),de.w1.StartPerformanceCounter(`Rendering camera ${e.name}`)})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((e=>{this._cameraRenderTime.endMonitoring(!1),de.w1.EndPerformanceCounter(`Rendering camera ${e.name}`)}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))}get drawCallsCounter(){return this.scene.getEngine()._drawCalls}constructor(e){this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new Os.z,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new Os.z,this._captureFrameTime=!1,this._frameTime=new Os.z,this._captureRenderTime=!1,this._renderTime=new Os.z,this._captureInterFrameTime=!1,this._interFrameTime=new Os.z,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new Os.z,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new Os.z,this._capturePhysicsTime=!1,this._physicsTime=new Os.z,this._captureAnimationsTime=!1,this._animationsTime=new Os.z,this._captureCameraRenderTime=!1,this._cameraRenderTime=new Os.z,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=e.onBeforeAnimationsObservable.add((()=>{this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.fetchNewFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.fetchNewFrame(),this._captureFrameTime&&(de.w1.StartPerformanceCounter("Scene rendering"),this._frameTime.beginMonitoring()),this._captureInterFrameTime&&this._interFrameTime.endMonitoring(),this._captureParticlesRenderTime&&this._particlesRenderTime.fetchNewFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.fetchNewFrame(),this._captureAnimationsTime&&this._animationsTime.beginMonitoring(),this.scene.getEngine()._drawCalls.fetchNewFrame()})),this._onAfterRenderObserver=e.onAfterRenderObservable.add((()=>{this._captureFrameTime&&(de.w1.EndPerformanceCounter("Scene rendering"),this._frameTime.endMonitoring()),this._captureRenderTime&&this._renderTime.endMonitoring(!1),this._captureInterFrameTime&&this._interFrameTime.beginMonitoring()}))}dispose(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null}}si.v.ShadersStore.glowMapGenerationPixelShader="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include<helperFunctions>\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\nuniform sampler2D opacitySampler;\nuniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;\nuniform float glowIntensity;\n#include<clipPlaneFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include<clipPlaneFragment>\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a<ALPHATESTVALUE)\ndiscard;\n#endif\n#ifdef EMISSIVE\nvec4 emissive=texture2D(emissiveSampler,vUVEmissive);\n#ifdef EMISSIVE_ISLINEAR\nemissive=toGammaSpace(emissive);\n#endif\ngl_FragColor=emissive*finalColor*glowIntensity;\n#else\ngl_FragColor=finalColor;\n#endif\n#ifdef HIGHLIGHT\ngl_FragColor.a=glowColor.a;\n#endif\n}",i(9901),i(8073),i(6757),i(9085);si.v.ShadersStore.glowMapGenerationVertexShader="attribute vec3 position;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<clipPlaneVertexDeclaration>\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\nuniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;\ngl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include<clipPlaneVertex>\n}";var Zl=i(4934);class Jl{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i<e.length;++i){const n=e[i];t?this._materialForRendering[n.uniqueId]=[n,t]:delete this._materialForRendering[n.uniqueId]}else t?this._materialForRendering[e.uniqueId]=[e,t]:delete this._materialForRendering[e.uniqueId]}getEffectIntensity(e){var t;return null!==(t=this._effectIntensity[e.uniqueId])&&void 0!==t?t:1}setEffectIntensity(e,t){this._effectIntensity[e.uniqueId]=t}constructor(e,t){this._vertexBuffers={},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._shouldRender=!0,this._postProcesses=[],this._textures=[],this._emissiveTextureAndColor={texture:null,color:new a.HE},this._effectIntensity={},this.neutralColor=new a.HE,this.isEnabled=!0,this.disableBoundingBoxesFromEffectLayer=!1,this.onDisposeObservable=new r.y$,this.onBeforeRenderMainTextureObservable=new r.y$,this.onBeforeComposeObservable=new r.y$,this.onBeforeRenderMeshToEffect=new r.y$,this.onAfterRenderMeshToEffect=new r.y$,this.onAfterComposeObservable=new r.y$,this.onSizeChangedObservable=new r.y$,this._materialForRendering={},this.name=e,this._scene=t||A.l.LastCreatedScene,Jl._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.effectLayers.push(this),this._mergeDrawWrapper=[],this._generateIndexBuffer(),this._generateVertexBuffer()}_numInternalDraws(){return 1}_init(e){this._effectLayerOptions={mainTextureRatio:.5,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...e},this._setMainTextureSize(),this._createMainTexture(),this._createTextureAndPostProcesses()}_generateIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._engine.createIndexBuffer(e)}_generateVertexBuffer(){const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1);const t=new qe.o(this._engine,e,qe.o.PositionKind,!1,!1,2);this._vertexBuffers[qe.o.PositionKind]=t}_setMainTextureSize(){this._effectLayerOptions.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._effectLayerOptions.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._effectLayerOptions.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderWidth()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderHeight()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.width=this._engine.needPOTTextures?ue.D.GetExponentOfTwo(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?ue.D.GetExponentOfTwo(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)}_createMainTexture(){this._mainTexture=new Ai._("EffectLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,!1,!0,this._effectLayerOptions.mainTextureType),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(Ce.x.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0;for(const e in this._materialForRendering){const[t,i]=this._materialForRendering[e];this._mainTexture.setMaterialForRendering(t,i)}if(this._mainTexture.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){const i=e.subMeshes[t],n=i.getMaterial(),s=i.getRenderingMesh();if(!n)continue;const r=s._getInstancesRenderList(i._id,!!i.getReplacementMesh()).hardwareInstancedRendering[i._id]||s.hasThinInstances;if(this._setEmissiveTextureAndColor(s,i,n),!this._isReady(i,r,this._emissiveTextureAndColor.texture))return!1}return!0},this._mainTexture.customRenderFunction=(e,t,i,n)=>{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const r=this._scene.getEngine();if(n.length){for(r.setColorWrite(!1),s=0;s<n.length;s++)this._renderSubMesh(n.data[s]);r.setColorWrite(!0)}for(s=0;s<e.length;s++)this._renderSubMesh(e.data[s]);for(s=0;s<t.length;s++)this._renderSubMesh(t.data[s]);const o=r.getAlphaMode();for(s=0;s<i.length;s++)this._renderSubMesh(i.data[s],!0);r.setAlphaMode(o)},this._mainTexture.onClearObservable.add((e=>{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){var n;const s=this._scene.getEngine(),r=e.getMesh(),o=null===(n=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===n?void 0:n[s.currentRenderPassId];if(o)return o.isReadyForSubMesh(r,e,t);const a=e.getMaterial();if(!a)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return a.isReadyForSubMesh(e.getMesh(),e,t);const l=[],h=[qe.o.PositionKind];let c=!1,u=!1;if(a){const e=a.needAlphaTesting(),t=a.getAlphaTestTexture(),i=t&&t.hasAlpha&&(a.useAlphaFromDiffuseTexture||a._useAlphaFromAlbedoTexture);t&&(e||i)&&(l.push("#define DIFFUSE"),r.isVerticesDataPresent(qe.o.UV2Kind)&&1===t.coordinatesIndex?(l.push("#define DIFFUSEUV2"),u=!0):r.isVerticesDataPresent(qe.o.UVKind)&&(l.push("#define DIFFUSEUV1"),c=!0),e&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));const n=a.opacityTexture;n&&(l.push("#define OPACITY"),r.isVerticesDataPresent(qe.o.UV2Kind)&&1===n.coordinatesIndex?(l.push("#define OPACITYUV2"),u=!0):r.isVerticesDataPresent(qe.o.UVKind)&&(l.push("#define OPACITYUV1"),c=!0))}i&&(l.push("#define EMISSIVE"),r.isVerticesDataPresent(qe.o.UV2Kind)&&1===i.coordinatesIndex?(l.push("#define EMISSIVEUV2"),u=!0):r.isVerticesDataPresent(qe.o.UVKind)&&(l.push("#define EMISSIVEUV1"),c=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(qe.o.ColorKind)&&r.hasVertexAlpha&&a.transparencyMode!==cs.F.MATERIAL_OPAQUE&&(h.push(qe.o.ColorKind),l.push("#define VERTEXALPHA")),c&&(h.push(qe.o.UVKind),l.push("#define UV1")),u&&(h.push(qe.o.UV2Kind),l.push("#define UV2"));const d=new ka.L;if(r.useBones&&r.computeBonesUsingShaders){h.push(qe.o.MatricesIndicesKind),h.push(qe.o.MatricesWeightsKind),r.numBoneInfluencers>4&&(h.push(qe.o.MatricesIndicesExtraKind),h.push(qe.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const e=r.skeleton;e&&e.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),r.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,r)}else l.push("#define NUM_BONE_INFLUENCERS 0");const p=r.morphTargetManager;let f=0;p&&p.numInfluencers>0&&(l.push("#define MORPHTARGETS"),f=p.numInfluencers,l.push("#define NUM_MORPH_INFLUENCERS "+f),p.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),La.G.PrepareAttributesForMorphTargetsInfluencers(h,r,f)),t&&(l.push("#define INSTANCES"),La.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),(0,Ga.lK)(a,this._scene,l),this._addCustomEffectDefines(l);const _=e._getDrawWrapper(void 0,!0),m=_.defines,g=l.join("\n");if(m!==g){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];(0,Ga.qx)(e),_.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,d,void 0,void 0,{maxSimultaneousMorphTargets:f}),g)}return _.effect.isReady()}render(){for(let e=0;e<this._postProcesses.length;e++)if(!this._postProcesses[e].isReady())return;const e=this._scene.getEngine(),t=this._numInternalDraws();let i=!0;for(let e=0;e<t;++e){let t=this._mergeDrawWrapper[e];t||(t=this._mergeDrawWrapper[e]=new Ps.q(this._engine),t.setEffect(this._createMergeEffect())),i=i&&t.effect.isReady()}if(!i)return;this.onBeforeComposeObservable.notifyObservers(this);const n=e.getAlphaMode();for(let i=0;i<t;++i){const t=this._mergeDrawWrapper[i];e.enableEffect(t),e.setState(!1),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t.effect),e.setAlphaMode(this._effectLayerOptions.alphaBlendingMode),this._internalRender(t.effect,i)}e.setAlphaMode(n),this.onAfterComposeObservable.notifyObservers(this);const s=this._mainTexture.getSize();this._setMainTextureSize(),s.width===this._mainTextureDesiredSize.width&&s.height===this._mainTextureDesiredSize.height||0===this._mainTextureDesiredSize.width||0===this._mainTextureDesiredSize.height||(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses())}hasMesh(e){return-1===this.renderingGroupId||e.renderingGroupId===this.renderingGroupId}shouldRender(){return this.isEnabled&&this._shouldRender}_shouldRenderMesh(e){return!0}_canRenderMesh(e,t){return!t.needAlphaBlendingForMesh(e)}_shouldRenderEmissiveTextureForMesh(){return!0}_renderSubMesh(e,t=!1){var i,n;if(!this.shouldRender())return;const s=e.getMaterial(),r=e.getMesh(),o=e.getReplacementMesh(),a=e.getRenderingMesh(),l=e.getEffectiveMesh(),h=this._scene,c=h.getEngine();if(l._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!s)return;if(!this._canRenderMesh(a,s))return;let u=null!==(i=a.overrideMaterialSideOrientation)&&void 0!==i?i:s.sideOrientation;l._getWorldMatrixDeterminant()<0&&(u=u===cs.F.ClockWiseSideOrientation?cs.F.CounterClockWiseSideOrientation:cs.F.ClockWiseSideOrientation);const d=u===cs.F.ClockWiseSideOrientation;c.setState(s.backFaceCulling,s.zOffset,void 0,d,s.cullBackFaces,void 0,s.zOffsetUnits);const p=a._getInstancesRenderList(e._id,!!o);if(p.mustReturn)return;if(!this._shouldRenderMesh(a))return;const f=p.hardwareInstancedRendering[e._id]||a.hasThinInstances;if(this._setEmissiveTextureAndColor(a,e,s),this.onBeforeRenderMeshToEffect.notifyObservers(r),this._useMeshMaterial(a))a.render(e,t,o||void 0);else if(this._isReady(e,f,this._emissiveTextureAndColor.texture)){const i=null===(n=l._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===n?void 0:n[c.currentRenderPassId];let r=e._getDrawWrapper();if(!r&&i&&(r=i._getDrawWrapper()),!r)return;const o=r.effect;if(c.enableEffect(r),f||a._bind(e,o,s.fillMode),i?i.bindForSubMesh(l.getWorldMatrix(),l,e):(o.setMatrix("viewProjection",h.getTransformMatrix()),o.setMatrix("world",l.getWorldMatrix()),o.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a)),!i){const e=s.needAlphaTesting(),i=s.getAlphaTestTexture(),n=i&&i.hasAlpha&&(s.useAlphaFromDiffuseTexture||s._useAlphaFromAlbedoTexture);if(i&&(e||n)){o.setTexture("diffuseSampler",i);const e=i.getTextureMatrix();e&&o.setMatrix("diffuseMatrix",e)}const r=s.opacityTexture;if(r){o.setTexture("opacitySampler",r),o.setFloat("opacityIntensity",r.level);const e=r.getTextureMatrix();e&&o.setMatrix("opacityMatrix",e)}if(this._emissiveTextureAndColor.texture&&(o.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),o.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),a.useBones&&a.computeBonesUsingShaders&&a.skeleton){const e=a.skeleton;if(e.isUsingTextureForMatrices){const t=e.getTransformMatrixTexture(a);if(!t)return;o.setTexture("boneSampler",t),o.setFloat("boneTextureWidth",4*(e.bones.length+1))}else o.setMatrices("mBones",e.getTransformMatrices(a))}La.G.BindMorphTargetParameters(a,o),a.morphTargetManager&&a.morphTargetManager.isUsingTextureForTargets&&a.morphTargetManager._bind(o),t&&c.setAlphaMode(s.alphaMode),o.setFloat("glowIntensity",this.getEffectIntensity(a)),(0,Ga.an)(o,s,h)}a._processRendering(l,e,o,s.fillMode,p,f,((e,t)=>o.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[qe.o.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e<this._postProcesses.length;e++)this._postProcesses[e]&&this._postProcesses[e].dispose();this._postProcesses=[];for(let e=0;e<this._textures.length;e++)this._textures[e]&&this._textures[e].dispose();this._textures=[]}dispose(){const e=this._vertexBuffers[qe.o.PositionKind];e&&(e.dispose(),this._vertexBuffers[qe.o.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);for(const e of this._mergeDrawWrapper)e.dispose();this._mergeDrawWrapper=[],this._disposeTextureAndPostProcesses();const t=this._scene.effectLayers.indexOf(this,0);t>-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return de.w1.Instantiate(e.customType).Parse(e,t,i)}}Jl._SceneComponentInitialization=e=>{throw(0,Zl.S)("EffectLayerSceneComponent")},(0,be.gn)([(0,Te.qC)()],Jl.prototype,"name",void 0),(0,be.gn)([(0,Te.XX)()],Jl.prototype,"neutralColor",void 0),(0,be.gn)([(0,Te.qC)()],Jl.prototype,"isEnabled",void 0),(0,be.gn)([(0,Te.VE)()],Jl.prototype,"camera",null),(0,be.gn)([(0,Te.qC)()],Jl.prototype,"renderingGroupId",null),(0,be.gn)([(0,Te.qC)()],Jl.prototype,"disableBoundingBoxesFromEffectLayer",void 0),n.p.AddParser(ve.l.NAME_EFFECTLAYER,((e,t,i,n)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=new Array);for(let s=0;s<e.effectLayers.length;s++){const r=Jl.Parse(e.effectLayers[s],t,n);i.effectLayers.push(r)}}})),n.p.prototype.removeEffectLayer=function(e){const t=this.effectLayers.indexOf(e);return-1!==t&&this.effectLayers.splice(t,1),t},n.p.prototype.addEffectLayer=function(e){this.effectLayers.push(e)};class eh{constructor(e){this.name=ve.l.NAME_EFFECTLAYER,this._renderEffects=!1,this._needStencil=!1,this._previousStencilState=!1,this.scene=e||A.l.LastCreatedScene,this.scene&&(this._engine=this.scene.getEngine(),this.scene.effectLayers=new Array)}register(){this.scene._isReadyForMeshStage.registerStep(ve.l.STEP_ISREADYFORMESH_EFFECTLAYER,this,this._isReadyForMesh),this.scene._cameraDrawRenderTargetStage.registerStep(ve.l.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER,this,this._renderMainTexture),this.scene._beforeCameraDrawStage.registerStep(ve.l.STEP_BEFORECAMERADRAW_EFFECTLAYER,this,this._setStencil),this.scene._afterRenderingGroupDrawStage.registerStep(ve.l.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW,this,this._drawRenderingGroup),this.scene._afterCameraDrawStage.registerStep(ve.l.STEP_AFTERCAMERADRAW_EFFECTLAYER,this,this._setStencilBack),this.scene._afterCameraDrawStage.registerStep(ve.l.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW,this,this._drawCamera)}rebuild(){const e=this.scene.effectLayers;for(const t of e)t._rebuild()}serialize(e){e.effectLayers=[];const t=this.scene.effectLayers;for(const i of t)i.serialize&&e.effectLayers.push(i.serialize())}addFromContainer(e){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,n=this.scene.effectLayers;for(const s of n){if(!s.hasMesh(e))continue;const n=s._mainTexture;this._engine.currentRenderPassId=n.renderPassId;for(const n of e.subMeshes)if(!s.isReady(n,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 n of i)if(n.shouldRender()&&(!n.camera||n.camera.cameraRigMode===Mt.V.RIG_MODE_NONE&&e===n.camera||n.camera.cameraRigMode!==Mt.V.RIG_MODE_NONE&&n.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||n.needStencil();const e=n._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i<t.length;i++){const n=t[i];n.renderingGroupId===e&&n.shouldRender()&&n.render()}this._engine.setDepthBuffer(!0)}}_drawCamera(){this._renderEffects&&this._draw(-1)}_drawRenderingGroup(e){!this.scene._isInIntermediateRendering()&&this._renderEffects&&this._draw(e)}}Jl._SceneComponentInitialization=e=>{let t=e._getComponent(ve.l.NAME_EFFECTLAYER);t||(t=new eh(e),e._addComponent(t))};si.v.ShadersStore.glowMapMergePixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";si.v.ShadersStore.glowMapMergeVertexShader="attribute vec2 position;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}",n.p.prototype.getGlowLayerByName=function(e){var t;for(let i=0;i<(null===(t=this.effectLayers)||void 0===t?void 0:t.length);i++)if(this.effectLayers[i].name===e&&this.effectLayers[i].getEffectName()===th.EffectName)return this.effectLayers[i];return null};class th extends Jl{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 a.HE(0,0,0,1),this._options={mainTextureRatio:th.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode: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})}getEffectName(){return th.EffectName}_createMergeEffect(){let e="#define EMISSIVE \n";return this._options.ldrMerge&&(e+="#define LDR \n"),this._engine.createEffect("glowMapMerge",[qe.o.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?ue.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?ue.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new Ai._("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(Ce.x.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const n=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new Ai._("GlowLayerBlurRTT2",{width:n,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(Ce.x.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const r=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new wa("GlowLayerHBP1",new o.FM(1,0),r,{width:e,height:t},null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new wa("GlowLayerVBP1",new o.FM(0,1),r,{width:e,height:t},null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new wa("GlowLayerHBP2",new o.FM(1,0),r,{width:n,height:s},null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=n,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new wa("GlowLayerVBP2",new o.FM(0,1),r,{width:n,height:s},null,Ce.x.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 e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(null!=t?t:e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),n=e.getRenderingMesh();if(!i||!n)return!1;const s=i.emissiveTexture;return super._isReady(e,t,s)}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(cs.F.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var n;let s=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(s*=null!==(n=i.emissiveIntensity)&&void 0!==n?n:1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)):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){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&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=Te.p4.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;t<this._includedOnlyMeshes.length;t++){const i=this._scene.getMeshByUniqueId(this._includedOnlyMeshes[t]);i&&e.includedMeshes.push(i.id)}if(e.excludedMeshes=[],this._excludedMeshes.length)for(t=0;t<this._excludedMeshes.length;t++){const i=this._scene.getMeshByUniqueId(this._excludedMeshes[t]);i&&e.excludedMeshes.push(i.id)}return e}static Parse(e,t,i){const n=Te.p4.Parse((()=>new th(e.name,t,e.options)),e,t,i);let s;for(s=0;s<e.excludedMeshes.length;s++){const i=t.getMeshById(e.excludedMeshes[s]);i&&n.addExcludedMesh(i)}for(s=0;s<e.includedMeshes.length;s++){const i=t.getMeshById(e.includedMeshes[s]);i&&n.addIncludedOnlyMesh(i)}return n}}th.EffectName="GlowLayer",th.DefaultBlurKernelSize=32,th.DefaultTextureRatio=.5,(0,be.gn)([(0,Te.qC)()],th.prototype,"blurKernelSize",null),(0,be.gn)([(0,Te.qC)()],th.prototype,"intensity",null),(0,be.gn)([(0,Te.qC)("options")],th.prototype,"_options",void 0),(0,l.H)("BABYLON.GlowLayer",th);si.v.ShadersStore.glowBlurPostProcessPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}",n.p.prototype.getHighlightLayerByName=function(e){var t;for(let i=0;i<(null===(t=this.effectLayers)||void 0===t?void 0:t.length);i++)if(this.effectLayers[i].name===e&&this.effectLayers[i].getEffectName()===nh.EffectName)return this.effectLayers[i];return null};class ih extends ni.D{constructor(e,t,i,n,s,r=Ce.x.BILINEAR_SAMPLINGMODE,o,a){super(e,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,n,s,r,o,a),this.direction=t,this.kernel=i,this.onApplyObservable.add((e=>{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)}))}}class nh extends Jl{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 r.y$,this.onAfterBlurObservable=new r.y$,this._instanceGlowingMeshStencilReference=nh.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=nh.NeutralColor,this._engine.isStencilEnable||_.Y.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return nh.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[qe.o.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?ue.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?ue.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new Ai._("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Ce.x.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new ii.Q("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._horizontalBlurPostprocess=new ih("HighlightLayerHBP",new o.FM(1,0),this._options.blurHorizontalSize,1,null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._verticalBlurPostprocess=new ih("HighlightLayerVBP",new o.FM(0,1),this._options.blurVerticalSize,1,null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new wa("HighlightLayerHBP",new o.FM(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess=new wa("HighlightLayerVBP",new o.FM(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add((()=>{this.onBeforeBlurObservable.notifyObservers(this);const e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)})),this._postProcesses.map((e=>{e.autoClear=!1}))}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),n=e.getRenderingMesh();if(!i||!n||!this._meshes)return!1;let s=null;const r=this._meshes[n.uniqueId];return r&&r.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_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&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(cs.F.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(cs.F.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_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 n=this._meshes[e.uniqueId];n?this._emissiveTextureAndColor.color.set(n.color.r,n.color.g,n.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),n&&n.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){const t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((e=>{e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}}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)&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;const n=this._meshes[e.uniqueId];n?n.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((e=>{this.isEnabled&&this._defaultStencilReference(e)})),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 e in this._meshes)if(this._meshes[e]){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(nh.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=Te.p4.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 n=Te.p4.Parse((()=>new nh(e.name,t,e.options)),e,t,i);let s;for(s=0;s<e.excludedMeshes.length;s++){const i=t.getMeshById(e.excludedMeshes[s]);i&&n.addExcludedMesh(i)}for(s=0;s<e.meshes.length;s++){const i=e.meshes[s],r=t.getMeshById(i.meshId);r&&n.addMesh(r,a.Wo.FromArray(i.color),i.glowEmissiveOnly)}return n}}nh.EffectName="HighlightLayer",nh.NeutralColor=new a.HE(0,0,0,0),nh.GlowingMeshStencilReference=2,nh.NormalMeshStencilReference=1,(0,be.gn)([(0,Te.qC)()],nh.prototype,"innerGlow",void 0),(0,be.gn)([(0,Te.qC)()],nh.prototype,"outerGlow",void 0),(0,be.gn)([(0,Te.qC)()],nh.prototype,"blurHorizontalSize",null),(0,be.gn)([(0,Te.qC)()],nh.prototype,"blurVerticalSize",null),(0,be.gn)([(0,Te.qC)("options")],nh.prototype,"_options",void 0),(0,l.H)("BABYLON.HighlightLayer",nh);var sh=i(4380),rh=i(8513);class oh{static AddFlare(e,t,i,n,s){return new oh(e,t,i,n,s)}constructor(e,t,i,n,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new a.Wo(1,1,1),this.texture=n?new Ce.x(n,s.getScene(),!0):null,this._system=s;const r=s.scene.getEngine();this._drawWrapper=new Ps.q(r),this._drawWrapper.effect=r.createEffect("lensFlare",[qe.o.PositionKind],["color","viewportMatrix"],["textureSampler"],""),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}si.v.ShadersStore.lensFlarePixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";si.v.ShadersStore.lensFlareVertexShader="attribute vec2 position;\nuniform mat4 viewportMatrix;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class ah{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=new Array,this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||A.l.LastCreatedScene,ah._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&0!=(e.layerMask&i.activeCamera.layerMask);const n=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[qe.o.PositionKind]=new qe.o(n,s,qe.o.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=o.P.Project(t,o.y3.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=o.P.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return!!(t.z>0&&!i||t.z<0&&i)&&(this._positionX>e.x&&this._positionX<e.x+e.width&&this._positionY>e.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();const i=new Yt.z(this._scene.activeCamera.globalPosition,e),n=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!n||!n.hit||n.distance>t}render(){if(!this._scene.activeCamera)return!1;const e=this._scene.getEngine(),t=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(t))return!1;if(!this._isVisible())return!1;let i,n;i=this._positionX<this.borderLimit+t.x?this.borderLimit+t.x-this._positionX:this._positionX>t.x+t.width-this.borderLimit?this._positionX-t.x-t.width+this.borderLimit:0,n=this._positionY<this.borderLimit+t.y?this.borderLimit+t.y-this._positionY:this._positionY>t.y+t.height-this.borderLimit?this._positionY-t.y-t.height+this.borderLimit:0;let s=i>n?i:n;s-=this.viewportBorder,s>this.borderLimit&&(s=this.borderLimit);let r=1-lt.R.Clamp(s/this.borderLimit,0,1);if(r<0)return!1;r>1&&(r=1),this.viewportBorder>0&&(t.x+=this.viewportBorder,t.y+=this.viewportBorder,t.width-=2*this.viewportBorder,t.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const a=t.x+t.width/2,l=t.y+t.height/2,h=a-this._positionX,c=l-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let i=0;i<this.lensFlares.length;i++){const n=this.lensFlares[i];if(!n._drawWrapper.effect.isReady()||n.texture&&!n.texture.isReady())continue;e.enableEffect(n._drawWrapper),e.bindBuffers(this._vertexBuffers,this._indexBuffer,n._drawWrapper.effect),e.setAlphaMode(n.alphaMode);const s=a-h*n.position,u=l-c*n.position,d=n.size,p=n.size*e.getAspectRatio(this._scene.activeCamera,!0),f=s/(t.width+2*t.x)*2-1,_=1-u/(t.height+2*t.y)*2,m=o.y3.FromValues(d/2,0,0,0,0,p/2,0,0,0,0,1,0,f,_,0,1);n._drawWrapper.effect.setMatrix("viewportMatrix",m),n._drawWrapper.effect.setTexture("textureSampler",n.texture),n._drawWrapper.effect.setFloat4("color",n.color.r*r,n.color.g*r,n.color.b*r,1),e.drawElementsType(cs.F.TriangleFillMode,0,6)}return e.setDepthBuffer(!0),e.setAlphaMode(0),!0}rebuild(){var e;this._createIndexBuffer();for(const t in this._vertexBuffers)null===(e=this._vertexBuffers[t])||void 0===e||e._rebuild()}dispose(){const e=this._vertexBuffers[qe.o.PositionKind];for(e&&(e.dispose(),this._vertexBuffers[qe.o.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);this.lensFlares.length;)this.lensFlares[0].dispose();const t=this._scene.lensFlareSystems.indexOf(this);this._scene.lensFlareSystems.splice(t,1)}static Parse(e,t,i){const n=t.getLastEntryById(e.emitterId),s=e.name||"lensFlareSystem#"+e.emitterId,r=new ah(s,n,t);r.id=e.id||s,r.borderLimit=e.borderLimit;for(let t=0;t<e.flares.length;t++){const n=e.flares[t];oh.AddFlare(n.size,n.position,a.Wo.FromArray(n.color),n.textureName?i+n.textureName:"",r)}return r}serialize(){const e={};e.id=this.id,e.name=this.name,e.emitterId=this.getEmitter().id,e.borderLimit=this.borderLimit,e.flares=[];for(let t=0;t<this.lensFlares.length;t++){const i=this.lensFlares[t];e.flares.push({size:i.size,position:i.position,color:i.color.asArray(),textureName:de.w1.GetFilename(i.texture?i.texture.name:"")})}return e}}ah._SceneComponentInitialization=e=>{throw(0,Zl.S)("LensFlareSystemSceneComponent")},n.p.AddParser(ve.l.NAME_LENSFLARESYSTEM,((e,t,i,n)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=new Array);for(let s=0,r=e.lensFlareSystems.length;s<r;s++){const r=e.lensFlareSystems[s],o=ah.Parse(r,t,n);i.lensFlareSystems.push(o)}}})),n.p.prototype.getLensFlareSystemByName=function(e){for(let t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].name===e)return this.lensFlareSystems[t];return null},n.p.prototype.getLensFlareSystemById=function(e){for(let t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].id===e)return this.lensFlareSystems[t];return null},n.p.prototype.getLensFlareSystemByID=function(e){return this.getLensFlareSystemById(e)},n.p.prototype.removeLensFlareSystem=function(e){const t=this.lensFlareSystems.indexOf(e);return-1!==t&&this.lensFlareSystems.splice(t,1),t},n.p.prototype.addLensFlareSystem=function(e){this.lensFlareSystems.push(e)};class lh{constructor(e){this.name=ve.l.NAME_LENSFLARESYSTEM,this.scene=e,e.lensFlareSystems=new Array}register(){this.scene._afterCameraDrawStage.registerStep(ve.l.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM,this,this._draw)}rebuild(){for(let e=0;e<this.scene.lensFlareSystems.length;e++)this.scene.lensFlareSystems[e].rebuild()}addFromContainer(e){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.addLensFlareSystem(e)}))}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.removeLensFlareSystem(e),t&&e.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;de.w1.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)0!=(e.layerMask&i.layerMask)&&i.render();de.w1.EndPerformanceCounter("Lens flares",t.length>0)}}}ah._SceneComponentInitialization=e=>{let t=e._getComponent(ve.l.NAME_LENSFLARESYSTEM);t||(t=new lh(e),e._addComponent(t))};var hh=i(9311),ch=i(6792),uh=i(4221);si.v.IncludesShadersStore.bayerDitherFunctions="float bayerDither2(vec2 _P) {\nreturn mod(2.0*_P.y+_P.x+1.0,4.0);\n}\nfloat bayerDither4(vec2 _P) {\nvec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);\n}\nfloat bayerDither8(vec2 _P) {\nvec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);\n}\n";si.v.IncludesShadersStore.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include<packingFunctions>\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include<bayerDitherFunctions>\nuniform float softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;\nvarying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;\nuniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";si.v.IncludesShadersStore.shadowMapFragment="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";si.v.ShadersStore.shadowMapPixelShader="#include<shadowMapFragmentExtraDeclaration>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include<clipPlaneFragment>\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture<ALPHATESTVALUE)\ndiscard;\n#endif\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#ifdef ALPHATEXTURE\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\n#endif\n#endif\n#include<shadowMapFragment>\n}";si.v.IncludesShadersStore.sceneVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec4 vEyePosition;\n";si.v.IncludesShadersStore.meshVertexDeclaration="uniform mat4 world;\nuniform float visibility;\n";si.v.IncludesShadersStore.shadowMapVertexDeclaration="#include<sceneVertexDeclaration>\n#include<meshVertexDeclaration>\n",i(4804);si.v.IncludesShadersStore.shadowMapUboDeclaration="layout(std140,column_major) uniform;\n#include<sceneUboDeclaration>\n#include<meshUboDeclaration>\n";si.v.IncludesShadersStore.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;\nuniform vec2 depthValuesSM;\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";si.v.IncludesShadersStore.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;\nvec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);\nfloat sinNLSM=sqrt(1.0-ndlSM*ndlSM);\nfloat normalBiasSM=biasAndScaleSM.y*sinNLSM;\nworldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n";si.v.IncludesShadersStore.shadowMapVertexMetric="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;\ngl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";si.v.ShadersStore.shadowMapVertexShader="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#endif\n#include<helperFunctions>\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<shadowMapVertexExtraDeclaration>\n#include<clipPlaneVertexDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));\nvNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include<shadowMapVertexNormalBias>\ngl_Position=viewProjection*worldPos;\n#include<shadowMapVertexMetric>\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<clipPlaneVertex>\n}";si.v.ShadersStore.depthBoxBlurPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}";si.v.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\n#endif\n";class dh{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 void 0!==this._depthScale?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===dh.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===dh.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===dh.FILTER_PCF||e===dh.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==dh.FILTER_PCF&&e!==dh.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===dh.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(dh.FILTER_POISSONSAMPLING);(e||this.filter===dh.FILTER_POISSONSAMPLING)&&(this.filter=e?t:dh.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===dh.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(dh.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===dh.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:dh.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===dh.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(dh.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===dh.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:dh.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===dh.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(dh.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===dh.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:dh.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===dh.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(dh.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===dh.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:dh.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===dh.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(dh.FILTER_PCF);(e||this.filter===dh.FILTER_PCF)&&(this.filter=e?t:dh.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===dh.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(dh.FILTER_PCSS);(e||this.filter===dh.FILTER_PCSS)&&(this.filter=e?t:dh.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 this._darkness=e>=1?1:e<=0?0: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 dh.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){var e;return null!==(e=this._camera)&&void 0!==e?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,n){this.onBeforeShadowMapRenderObservable=new r.y$,this.onAfterShadowMapRenderObservable=new r.y$,this.onBeforeShadowMapRenderMeshObservable=new r.y$,this.onAfterShadowMapRenderMeshObservable=new r.y$,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=dh.FILTER_NONE,this._filteringQuality=dh.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=o.P.Zero(),this._viewMatrix=o.y3.Zero(),this._projectionMatrix=o.y3.Zero(),this._transformMatrix=o.y3.Zero(),this._cachedPosition=new o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=o.y3.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=null!=n?n:null;let s=t._shadowGenerators;s||(s=t._shadowGenerators=new Map),s.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}")`))),dh._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 Ai._(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new Ai._(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube())}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Ce.x.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===dh.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 t,i;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===dh.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void(null===(t=e._debugPopGroup)||void 0===t||t.call(e,1));const n=this.getShadowMapForRendering();n&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,n.renderTarget,!0),e.unBindFramebuffer(n.renderTarget,!0),null===(i=e._debugPopGroup)||void 0===i||i.call(e,1))}));const t=new a.HE(0,0,0,0),i=new a.HE(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===dh.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=uh.$.MIN_RENDERINGGROUPS;e<uh.$.MAX_RENDERINGGROUPS;e++)this._shadowMap.setRenderingAutoClearDepthStencil(e,!1)}_initializeBlurRTTAndPostProcesses(){const e=this._scene.getEngine(),t=this._mapSize/this.blurScale;this.useKernelBlur&&1===this.blurScale||(this._shadowMap2=new Ai._(this._light.name+"_shadowMap2",t,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(Ce.x.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new wa(this._light.name+"KernelBlurX",new o.FM(1,0),this.blurKernel,1,null,Ce.x.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=t,this._kernelBlurXPostprocess.height=t,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new wa(this._light.name+"KernelBlurY",new o.FM(0,1),this.blurKernel,1,null,Ce.x.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new ni.D(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Ce.x.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,n){let s;if(n.length)for(s=0;s<n.length;s++)this._renderSubMeshForShadowMap(n.data[s]);for(s=0;s<e.length;s++)this._renderSubMeshForShadowMap(e.data[s]);for(s=0;s<t.length;s++)this._renderSubMeshForShadowMap(t.data[s]);if(this._transparencyShadow)for(s=0;s<i.length;s++)this._renderSubMeshForShadowMap(i.data[s],!0);else for(s=0;s<i.length;s++)i.data[s].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}_bindCustomEffectForRenderSubMeshForShadowMap(e,t,i){t.setMatrix("viewProjection",this.getTransformMatrix())}_renderSubMeshForShadowMap(e,t=!1){var i,n;const s=e.getRenderingMesh(),r=e.getEffectiveMesh(),o=this._scene,a=o.getEngine(),l=e.getMaterial();if(r._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!l||0===e.verticesCount||e._renderId===o.getRenderId())return;const h=r._getWorldMatrixDeterminant()<0;let c=null!==(i=s.overrideMaterialSideOrientation)&&void 0!==i?i:l.sideOrientation;h&&(c=0===c?1:0);const u=0===c;a.setState(l.backFaceCulling,void 0,void 0,u,l.cullBackFaces);const d=s._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(d.mustReturn)return;const p=a.getCaps().instancedArrays&&(null!==d.visibleInstances[e._id]&&void 0!==d.visibleInstances[e._id]||s.hasThinInstances);if(!this.customAllowRendering||this.customAllowRendering(e))if(this.isReady(e,p,t)){e._renderId=o.getRenderId();const i=l.shadowDepthWrapper,h=null!==(n=null==i?void 0:i.getEffect(e,this,a.currentRenderPassId))&&void 0!==n?n:e._getDrawWrapper(),c=Ps.q.GetEffect(h);a.enableEffect(h),p||s._bind(e,c,l.fillMode),this.getTransformMatrix(),c.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===hh._.LIGHTTYPEID_DIRECTIONALLIGHT?c.setVector3("lightDataSM",this._cachedDirection):c.setVector3("lightDataSM",this._cachedPosition);const u=this._getCamera();if(u&&c.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(u),this.getLight().getDepthMinZ(u)+this.getLight().getDepthMaxZ(u)),t&&this.enableSoftTransparentShadow&&c.setFloat("softTransparentShadowSM",r.visibility*l.alpha),i)e._setMainDrawWrapperOverride(h),i.standalone?i.baseMaterial.bindForSubMesh(r.getWorldMatrix(),s,e):l.bindForSubMesh(r.getWorldMatrix(),s,e),e._setMainDrawWrapperOverride(null);else{if(this._opacityTexture&&(c.setTexture("diffuseSampler",this._opacityTexture),c.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),s.useBones&&s.computeBonesUsingShaders&&s.skeleton){const e=s.skeleton;if(e.isUsingTextureForMatrices){const t=e.getTransformMatrixTexture(s);if(!t)return;c.setTexture("boneSampler",t),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",e.getTransformMatrices(s))}La.G.BindMorphTargetParameters(s,c),s.morphTargetManager&&s.morphTargetManager.isUsingTextureForTargets&&s.morphTargetManager._bind(c),(0,Ga.an)(c,l,o)}this._useUBO||i||this._bindCustomEffectForRenderSubMeshForShadowMap(e,c,r),La.G.BindSceneUniformBuffer(c,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();const f=r.getWorldMatrix();p&&(r.getMeshUniformBuffer().bindToEffect(c,"Mesh"),r.transferToEffect(f)),this.forceBackFacesOnly&&a.setState(!0,0,!1,!0,l.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(s),this.onBeforeShadowMapRenderObservable.notifyObservers(c),s._processRendering(r,e,c,l.fillMode,d,p,((e,t)=>{r===s||e?(r.getMeshUniformBuffer().bindToEffect(c,"Mesh"),r.transferToEffect(e?t:f)):(s.getMeshUniformBuffer().bindToEffect(c,"Mesh"),s.transferToEffect(t))})),this.forceBackFacesOnly&&a.setState(!0,0,!1,!1,l.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(c),this.onAfterShadowMapRenderMeshObservable.notifyObservers(s)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===dh.FILTER_NONE||this.filter===dh.FILTER_PCSS?this._shadowMap.updateSamplingMode(Ce.x.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Ce.x.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},n=this.getShadowMap();if(!n)return void(e&&e(this));const s=n.renderList;if(!s)return void(e&&e(this));const r=new Array;for(const e of s)r.push(...e.subMeshes);if(0===r.length)return void(e&&e(this));let o=0;const a=()=>{var t,n;if(this._scene&&this._scene.getEngine()){for(;this.isReady(r[o],i.useInstances,null!==(n=null===(t=r[o].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(r[o].getMesh()))&&void 0!==n&&n);)if(o++,o>=r.length)return void(e&&e(this));setTimeout(a,16)}};a()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,n){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"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 s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(qe.o.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===hh._.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&n?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var n;const s=e.getMaterial(),r=null==s?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const o=[];if(this._prepareShadowDefines(e,t,o,i),r){if(!r.isReadyForSubMesh(e,o,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,a=i.defines;const l=[qe.o.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(qe.o.NormalKind)&&(l.push(qe.o.NormalKind),o.push("#define NORMAL"),h.nonUniformScaling&&o.push("#define NONUNIFORMSCALING"));const c=s.needAlphaTesting();if((c||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=null!==(n=s.alphaCutOff)&&void 0!==n?n:dh.DEFAULT_ALPHA_CUTOFF;o.push("#define ALPHATEXTURE"),c&&o.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(qe.o.UVKind)&&(l.push(qe.o.UVKind),o.push("#define UV1")),h.isVerticesDataPresent(qe.o.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(l.push(qe.o.UV2Kind),o.push("#define UV2"))}const u=new ka.L;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){l.push(qe.o.MatricesIndicesKind),l.push(qe.o.MatricesWeightsKind),h.numBoneInfluencers>4&&(l.push(qe.o.MatricesIndicesExtraKind),l.push(qe.o.MatricesWeightsExtraKind));const e=h.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?o.push("#define BONETEXTURE"):o.push("#define BonesPerMesh "+(e.bones.length+1))}else o.push("#define NUM_BONE_INFLUENCERS 0");const d=h.morphTargetManager;let p=0;if(d&&d.numInfluencers>0&&(o.push("#define MORPHTARGETS"),p=d.numInfluencers,o.push("#define NUM_MORPH_INFLUENCERS "+p),d.isUsingTextureForTargets&&o.push("#define MORPHTARGETS_TEXTURE"),La.G.PrepareAttributesForMorphTargetsInfluencers(l,h,p)),(0,Ga.lK)(s,this._scene,o),t&&(o.push("#define INSTANCES"),La.G.PushAttributesForInstances(l),e.getRenderingMesh().hasThinInstances&&o.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===o.indexOf(e)&&o.push(e);const f=o.join("\n");if(a!==f){a=f;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],n=["diffuseSampler","boneSampler","morphTargets"],s=["Scene","Mesh"];if((0,Ga.qx)(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===l.indexOf(e)&&l.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===n.indexOf(e)&&n.push(e)}const o=this._scene.getEngine();r=o.createEffect(e,{attributes:l,uniformsNames:t,uniformBuffersNames:s,samplers:n,defines:f,fallbacks:u,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:p}},o),i.setEffect(r,a)}if(!r.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,n=this._light;i.shadowsEnabled&&n.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===dh.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===dh.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===dh.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===dh.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),n.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const n=this._getCamera();if(!n)return;const s=this.getShadowMap();s&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===dh.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===dh.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(n),this.getLight().getDepthMinZ(n)+this.getLight().getDepthMaxZ(n),e))}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),o.P.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(o.P.Dot(this._lightDirection,o.P.Up()))&&(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),o.y3.LookAtLHToRef(t,t.add(this._lightDirection),o.P.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}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 e of t)this._shadowMap.renderList.push(e)}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();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(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=null===(e=this._camera)||void 0===e?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 e=0;e<i.renderList.length;e++){const n=i.renderList[e];t.renderList.push(n.id)}return t}static Parse(e,t,i){const n=t.getLightById(e.lightId),s=void 0!==e.cameraId?t.getCameraById(e.cameraId):null,r=i?i(e.mapSize,n,s):new dh(e.mapSize,n,void 0,s),o=r.getShadowMap();for(let i=0;i<e.renderList.length;i++)t.getMeshesById(e.renderList[i]).forEach((function(e){o&&(o.renderList||(o.renderList=[]),o.renderList.push(e))}));return void 0!==e.id&&(r.id=e.id),r.forceBackFacesOnly=!!e.forceBackFacesOnly,void 0!==e.darkness&&r.setDarkness(e.darkness),e.transparencyShadow&&r.setTransparencyShadow(!0),void 0!==e.frustumEdgeFalloff&&(r.frustumEdgeFalloff=e.frustumEdgeFalloff),void 0!==e.bias&&(r.bias=e.bias),void 0!==e.normalBias&&(r.normalBias=e.normalBias),e.usePercentageCloserFiltering?r.usePercentageCloserFiltering=!0:e.useContactHardeningShadow?r.useContactHardeningShadow=!0:e.usePoissonSampling?r.usePoissonSampling=!0:e.useExponentialShadowMap?r.useExponentialShadowMap=!0:e.useBlurExponentialShadowMap?r.useBlurExponentialShadowMap=!0:e.useCloseExponentialShadowMap?r.useCloseExponentialShadowMap=!0:e.useBlurCloseExponentialShadowMap?r.useBlurCloseExponentialShadowMap=!0:e.useVarianceShadowMap?r.useExponentialShadowMap=!0:e.useBlurVarianceShadowMap&&(r.useBlurExponentialShadowMap=!0),void 0!==e.contactHardeningLightSizeUVRatio&&(r.contactHardeningLightSizeUVRatio=e.contactHardeningLightSizeUVRatio),void 0!==e.filteringQuality&&(r.filteringQuality=e.filteringQuality),e.depthScale&&(r.depthScale=e.depthScale),e.blurScale&&(r.blurScale=e.blurScale),e.blurBoxOffset&&(r.blurBoxOffset=e.blurBoxOffset),e.useKernelBlur&&(r.useKernelBlur=e.useKernelBlur),e.blurKernel&&(r.blurKernel=e.blurKernel),r}}dh.CLASSNAME="ShadowGenerator",dh.FILTER_NONE=0,dh.FILTER_EXPONENTIALSHADOWMAP=1,dh.FILTER_POISSONSAMPLING=2,dh.FILTER_BLUREXPONENTIALSHADOWMAP=3,dh.FILTER_CLOSEEXPONENTIALSHADOWMAP=4,dh.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP=5,dh.FILTER_PCF=6,dh.FILTER_PCSS=7,dh.QUALITY_HIGH=0,dh.QUALITY_MEDIUM=1,dh.QUALITY_LOW=2,dh.DEFAULT_ALPHA_CUTOFF=.5,dh._SceneComponentInitialization=e=>{throw(0,Zl.S)("ShadowGeneratorSceneComponent")};si.v.ShadersStore.depthPixelShader="#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\nvarying float vDepthMetric;\n#ifdef PACKED\n#include<packingFunctions>\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include<clipPlaneFragment>\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";si.v.ShadersStore.depthVertexShader="attribute vec3 position;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<clipPlaneVertexDeclaration>\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;\nvarying vec4 vViewPos;\n#endif\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include<clipPlaneVertex>\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n";class ph{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,n=!1,s=Ce.x.TRILINEAR_SAMPLINGMODE,r=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=n,this._storeCameraSpaceZ=r,this.isPacked=0===t,this.isPacked?this.clearColor=new a.HE(1,1,1,1):this.clearColor=new a.HE(r?1e8:1,0,0,1),ph._SceneComponentInitialization(this._scene);const l=e.getEngine();this._camera=i,s!==Ce.x.NEAREST_SAMPLINGMODE&&(1!==t||l._caps.textureFloatLinearFiltering||(s=Ce.x.NEAREST_SAMPLINGMODE),2!==t||l._caps.textureHalfFloatLinearFiltering||(s=Ce.x.NEAREST_SAMPLINGMODE));const h=this.isPacked||!l._features.supportExtendedTextureFormats?5:6;this._depthMap=new Ai._(null!=o?o:"DepthRenderer",{width:l.getRenderWidth(),height:l.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,h),this._depthMap.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{var e;null===(e=l._debugPushGroup)||void 0===e||e.call(l,"depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{var e;null===(e=l._debugPopGroup)||void 0===e||e.call(l,1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){const i=e.subMeshes[t],n=i.getRenderingMesh(),s=n._getInstancesRenderList(i._id,!!i.getReplacementMesh()),r=l.getCaps().instancedArrays&&(null!==s.visibleInstances[i._id]&&void 0!==s.visibleInstances[i._id]||n.hasThinInstances);if(!this.isReady(i,r))return!1}return!0};const c=e=>{var t,i;const n=e.getRenderingMesh(),s=e.getEffectiveMesh(),r=this._scene,o=r.getEngine(),a=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!a||s.infiniteDistance||a.disableDepthWrite||0===e.verticesCount||e._renderId===r.getRenderId())return;const l=s._getWorldMatrixDeterminant()<0;let h=null!==(t=n.overrideMaterialSideOrientation)&&void 0!==t?t:a.sideOrientation;l&&(h=0===h?1:0);const c=0===h;o.setState(a.backFaceCulling,0,!1,c,this.reverseCulling?!a.cullBackFaces:a.cullBackFaces);const u=n._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(u.mustReturn)return;const d=o.getCaps().instancedArrays&&(null!==u.visibleInstances[e._id]&&void 0!==u.visibleInstances[e._id]||n.hasThinInstances),p=this._camera||r.activeCamera;if(this.isReady(e,d)&&p){e._renderId=r.getRenderId();const t=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[o.currentRenderPassId];let l=e._getDrawWrapper();!l&&t&&(l=t._getDrawWrapper());const h=p.mode===Mt.V.ORTHOGRAPHIC_CAMERA;if(!l)return;const c=l.effect;let f,_;if(o.enableEffect(l),d||n._bind(e,c,a.fillMode),t?t.bindForSubMesh(s.getWorldMatrix(),s,e):(c.setMatrix("viewProjection",r.getTransformMatrix()),c.setMatrix("world",s.getWorldMatrix()),this._storeCameraSpaceZ&&c.setMatrix("view",r.getViewMatrix())),h?(f=!o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:1,_=o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:1):(f=o.useReverseDepthBuffer&&o.isNDCHalfZRange?p.minZ:o.isNDCHalfZRange?0:p.minZ,_=o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:p.maxZ),c.setFloat2("depthValues",f,f+_),!t){if(a.needAlphaTesting()){const e=a.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.useBones&&n.computeBonesUsingShaders&&n.skeleton){const e=n.skeleton;if(e.isUsingTextureForMatrices){const t=e.getTransformMatrixTexture(n);if(!t)return;c.setTexture("boneSampler",t),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",e.getTransformMatrices(n))}(0,Ga.an)(c,a,r),La.G.BindMorphTargetParameters(n,c),n.morphTargetManager&&n.morphTargetManager.isUsingTextureForTargets&&n.morphTargetManager._bind(c)}n._processRendering(s,e,c,a.fillMode,u,d,((e,t)=>c.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,n)=>{let s;if(n.length)for(s=0;s<n.length;s++)c(n.data[s]);for(s=0;s<e.length;s++)c(e.data[s]);for(s=0;s<t.length;s++)c(t.data[s]);if(this.forceDepthWriteTransparentMeshes)for(s=0;s<i.length;s++)c(i.data[s]);else for(s=0;s<i.length;s++)i.data[s].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}}isReady(e,t){var i;const n=this._scene.getEngine(),s=e.getMesh(),r=s.getScene(),o=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[n.currentRenderPassId];if(o)return o.isReadyForSubMesh(s,e,t);const a=e.getMaterial();if(!a||a.disableDepthWrite)return!1;const l=[],h=[qe.o.PositionKind];if(a&&a.needAlphaTesting()&&a.getAlphaTestTexture()&&(l.push("#define ALPHATEST"),s.isVerticesDataPresent(qe.o.UVKind)&&(h.push(qe.o.UVKind),l.push("#define UV1")),s.isVerticesDataPresent(qe.o.UV2Kind)&&(h.push(qe.o.UV2Kind),l.push("#define UV2"))),s.useBones&&s.computeBonesUsingShaders){h.push(qe.o.MatricesIndicesKind),h.push(qe.o.MatricesWeightsKind),s.numBoneInfluencers>4&&(h.push(qe.o.MatricesIndicesExtraKind),h.push(qe.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;(null==t?void 0:t.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");const c=s.morphTargetManager;let u=0;c&&c.numInfluencers>0&&(u=c.numInfluencers,l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+u),c.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),La.G.PrepareAttributesForMorphTargetsInfluencers(h,s,u)),t&&(l.push("#define INSTANCES"),La.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),(0,Ga.lK)(a,r,l);const d=e._getDrawWrapper(void 0,!0),p=d.defines,f=l.join("\n");if(p!==f){const e=["world","mBones","boneTextureWidth","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,Ga.qx)(e),d.setEffect(n.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],f,void 0,void 0,void 0,{maxSimultaneousMorphTargets:u}),f)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}ph._SceneComponentInitialization=e=>{throw(0,Zl.S)("DepthRendererSceneComponent")};var fh=i(727);si.v.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;\nuniform vec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*(texSize-1.0));\nfloat f1=texelFetch(sourceTexture,coord,0).r;\nfloat f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;\nfloat f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;\nfloat f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;\nfloat minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(MAIN)\nuniform vec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*(texSize-1.0));\nvec2 f1=texelFetch(textureSampler,coord,0).rg;\nvec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;\nvec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;\nvec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;\nfloat minz=min(min(min(f1.x,f2.x),f3.x),f4.x);\nfloat maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*vec2(texSize-1));\nvec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;\nvec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;\nvec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;\nvec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;\nfloat minz=min(f1.x,f2.x);\nfloat maxz=max(f1.y,f2.y);\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(LAST)\nvoid main(void)\n{\nglFragColor=vec4(0.);\nif (true) { \ndiscard;\n}\n}\n#endif\n";class _h{constructor(e){this.onAfterReductionPerformed=new r.y$,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new fh.O(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,n=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=n;const s=this._camera.getScene(),r=new ni.D("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,s.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);r.autoClear=!1,r.forceFullscreenViewport=n;let o=this._sourceTexture.getRenderWidth(),a=this._sourceTexture.getRenderHeight();r.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(r);let l=1;for(;o>1||a>1;){o=Math.max(Math.round(o/2),1),a=Math.max(Math.round(a/2),1);const e=new ni.D("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:a},null,1,s.getEngine(),!1,"#define "+(1==o&&1==a?"LAST":1==o||1==a?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=n,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(e),l++,1==o&&1==a){const t=(e,t,i)=>{const n=new Float32Array(4*e*t),r={min:0,max:0};return()=>{s.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,n,!1),r.min=n[0],r.max=n[1],this.onAfterReductionPerformed.notifyObservers(r)}};e.onAfterRenderObservable.add(t(o,a,e))}}}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();null===(e=i._debugPushGroup)||void 0===e||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),null===(t=i._debugPopGroup)||void 0===t||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 e=0;e<this._reductionSteps.length;++e)this._reductionSteps[e].dispose();this._reductionSteps=null}this._postProcessManager&&e&&this._postProcessManager.dispose(),this._sourceTexture=null}}class mh extends _h{get depthRenderer(){return this._depthRenderer}constructor(e){super(e)}setDepthRenderer(e=null,t=2,i=!0){const n=this._camera.getScene();this._depthRenderer&&(delete n._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),null===e&&(n._depthRenderer||(n._depthRenderer={}),(e=this._depthRenderer=new ph(n,t,this._camera,!1,1)).enabled=!1,this._depthRendererId="minmax"+this._camera.id,n._depthRenderer[this._depthRendererId]=e),super.setSourceTexture(e.getDepthMap(),!0,t,i)}setSourceTexture(e,t,i=2,n=!0){super.setSourceTexture(e,t,i,n)}activate(){this._depthRenderer&&(this._depthRenderer.enabled=!0),super.activate()}deactivate(){super.deactivate(),this._depthRenderer&&(this._depthRenderer.enabled=!1)}dispose(e=!0){if(super.dispose(e),this._depthRenderer&&e){const e=this._depthRenderer.getDepthMap().getScene();e&&delete e._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null}}}const gh=o.P.Up(),vh=o.P.Zero(),yh=new o.P,xh=new o.P,bh=new o.y3;class Th extends dh{_validateFilter(e){return e===dh.FILTER_NONE||e===dh.FILTER_PCF||e===dh.FILTER_PCSS?e:(console.error('Unsupported filter "'+e+'"!'),dh.FILTER_NONE)}get numCascades(){return this._numCascades}set numCascades(e){(e=Math.min(Math.max(e,Th.MIN_CASCADES_COUNT),Th.MAX_CASCADES_COUNT))!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())}get freezeShadowCastersBoundingInfo(){return this._freezeShadowCastersBoundingInfo}set freezeShadowCastersBoundingInfo(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._freezeShadowCastersBoundingInfoObservable||e||(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(this._computeShadowCastersBoundingInfo.bind(this))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(Number.MIN_VALUE,Number.MIN_VALUE,Number.MIN_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let t=0;t<e.length;t++){const i=e[t];if(!i)continue;const n=i.getBoundingInfo().boundingBox;this._scbiMin.minimizeInPlace(n.minimumWorld),this._scbiMax.maximizeInPlace(n.maximumWorld)}const t=this._scene.meshes;for(let e=0;e<t.length;e++){const i=t[e];if(!(i&&i.isVisible&&i.isEnabled&&i.receiveShadows))continue;const n=i.getBoundingInfo().boundingBox;this._scbiMin.minimizeInPlace(n.minimumWorld),this._scbiMax.maximizeInPlace(n.maximumWorld)}}this._shadowCastersBoundingInfo.reConstruct(this._scbiMin,this._scbiMax)}get shadowCastersBoundingInfo(){return this._shadowCastersBoundingInfo}set shadowCastersBoundingInfo(e){this._shadowCastersBoundingInfo=e}setMinMaxDistance(e,t){this._minDistance===e&&this._maxDistance===t||(e>t&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return Th.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e<this._numCascades?this._cascadeMinExtents[e]:null}getCascadeMaxExtents(e){return e>=0&&e<this._numCascades?this._cascadeMaxExtents[e]:null}get shadowMaxZ(){return this._getCamera()?this._shadowMaxZ:0}set shadowMaxZ(e){const t=this._getCamera();t?this._shadowMaxZ===e||e<t.minZ||e>t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e<this._numCascades?this._viewMatrices[e]:null}getCascadeProjectionMatrix(e){return e>=0&&e<this._numCascades?this._projectionMatrices[e]:null}getCascadeTransformMatrix(e){return e>=0&&e<this._numCascades?this._transformMatrices[e]:null}setDepthRenderer(e){this._depthRenderer=e,this._depthReducer&&this._depthReducer.setDepthRenderer(this._depthRenderer)}get autoCalcDepthBounds(){return this._autoCalcDepthBounds}set autoCalcDepthBounds(e){const t=this._getCamera();if(t){if(this._autoCalcDepthBounds=e,!e)return this._depthReducer&&this._depthReducer.deactivate(),void this.setMinMaxDistance(0,1);this._depthReducer||(this._depthReducer=new mh(t),this._depthReducer.onAfterReductionPerformed.add((e=>{let t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t,i;return null!==(i=null===(t=null===(e=this._depthReducer)||void 0===e?void 0:e.depthRenderer)||void 0===t?void 0:t.getDepthMap().refreshRate)&&void 0!==i?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;(null===(t=this._depthReducer)||void 0===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,n=i-t,s=this._minDistance,r=t+s*n,o=t+(this._shadowMaxZ<i&&this._shadowMaxZ>=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*n,a=o-r,l=o/r;for(let e=0;e<this._cascades.length;++e){const i=(e+1)/this._numCascades,o=r*l**i,h=r+a*i,c=this._lambda*(o-h)+h;this._cascades[e].prevBreakDistance=0===e?s:this._cascades[e-1].breakDistance,this._cascades[e].breakDistance=(c-t)/n,this._viewSpaceFrustumsZ[e]=c,this._frustumLengths[e]=(this._cascades[e].breakDistance-this._cascades[e].prevBreakDistance)*n}this._breaksAreDirty=!1}_computeMatrices(){const e=this._scene;if(!this._getCamera())return;o.P.NormalizeToRef(this._light.getShadowDirection(0),this._lightDirection),1===Math.abs(o.P.Dot(this._lightDirection,o.P.Up()))&&(this._lightDirection.z=1e-13),this._cachedDirection.copyFrom(this._lightDirection);const t=e.getEngine().useReverseDepthBuffer;for(let i=0;i<this._numCascades;++i){this._computeFrustumInWorldSpace(i),this._computeCascadeFrustum(i),this._cascadeMaxExtents[i].subtractToRef(this._cascadeMinExtents[i],yh),this._frustumCenter[i].addToRef(this._lightDirection.scale(this._cascadeMinExtents[i].z),this._shadowCameraPos[i]),o.y3.LookAtLHToRef(this._shadowCameraPos[i],this._frustumCenter[i],gh,this._viewMatrices[i]);let n=0,s=yh.z;const r=this._shadowCastersBoundingInfo;r.update(this._viewMatrices[i]),s=Math.min(s,r.boundingBox.maximumWorld.z),n=this._depthClamp&&this.filter!==dh.FILTER_PCSS?Math.max(n,r.boundingBox.minimumWorld.z):Math.min(n,r.boundingBox.minimumWorld.z),o.y3.OrthoOffCenterLHToRef(this._cascadeMinExtents[i].x,this._cascadeMaxExtents[i].x,this._cascadeMinExtents[i].y,this._cascadeMaxExtents[i].y,t?s:n,t?n:s,this._projectionMatrices[i],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[i].z=n,this._cascadeMaxExtents[i].z=s,this._viewMatrices[i].multiplyToRef(this._projectionMatrices[i],this._transformMatrices[i]),o.P.TransformCoordinatesToRef(vh,this._transformMatrices[i],yh),yh.scaleInPlace(this._mapSize/2),xh.copyFromFloats(Math.round(yh.x),Math.round(yh.y),Math.round(yh.z)),xh.subtractInPlace(yh).scaleInPlace(2/this._mapSize),o.y3.TranslationToRef(xh.x,xh.y,0,bh),this._projectionMatrices[i].multiplyToRef(bh,this._projectionMatrices[i]),this._viewMatrices[i].multiplyToRef(this._projectionMatrices[i],this._transformMatrices[i]),this._transformMatrices[i].copyToArray(this._transformMatricesAsArray,16*i)}}_computeFrustumInWorldSpace(e){const t=this._getCamera();if(!t)return;const i=this._cascades[e].prevBreakDistance,n=this._cascades[e].breakDistance,s=this._scene.getEngine().isNDCHalfZRange;t.getViewMatrix();const r=o.y3.Invert(t.getTransformationMatrix()),a=this._scene.getEngine().useReverseDepthBuffer?4:0;for(let t=0;t<Th._FrustumCornersNDCSpace.length;++t)yh.copyFrom(Th._FrustumCornersNDCSpace[(t+a)%Th._FrustumCornersNDCSpace.length]),s&&-1===yh.z&&(yh.z=0),o.P.TransformCoordinatesToRef(yh,r,this._frustumCornersWorldSpace[e][t]);for(let t=0;t<Th._FrustumCornersNDCSpace.length/2;++t)yh.copyFrom(this._frustumCornersWorldSpace[e][t+4]).subtractInPlace(this._frustumCornersWorldSpace[e][t]),xh.copyFrom(yh).scaleInPlace(i),yh.scaleInPlace(n),yh.addInPlace(this._frustumCornersWorldSpace[e][t]),this._frustumCornersWorldSpace[e][t+4].copyFrom(yh),this._frustumCornersWorldSpace[e][t].addInPlace(xh)}_computeCascadeFrustum(e){if(this._cascadeMinExtents[e].copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cascadeMaxExtents[e].copyFromFloats(Number.MIN_VALUE,Number.MIN_VALUE,Number.MIN_VALUE),this._frustumCenter[e].copyFromFloats(0,0,0),this._getCamera()){for(let t=0;t<this._frustumCornersWorldSpace[e].length;++t)this._frustumCenter[e].addInPlace(this._frustumCornersWorldSpace[e][t]);if(this._frustumCenter[e].scaleInPlace(1/this._frustumCornersWorldSpace[e].length),this.stabilizeCascades){let t=0;for(let i=0;i<this._frustumCornersWorldSpace[e].length;++i){const n=this._frustumCornersWorldSpace[e][i].subtractToRef(this._frustumCenter[e],yh).length();t=Math.max(t,n)}t=Math.ceil(16*t)/16,this._cascadeMaxExtents[e].copyFromFloats(t,t,t),this._cascadeMinExtents[e].copyFromFloats(-t,-t,-t)}else{const t=this._frustumCenter[e];this._frustumCenter[e].addToRef(this._lightDirection,yh),o.y3.LookAtLHToRef(t,yh,gh,bh);for(let t=0;t<this._frustumCornersWorldSpace[e].length;++t)o.P.TransformCoordinatesToRef(this._frustumCornersWorldSpace[e][t],bh,yh),this._cascadeMinExtents[e].minimizeInPlace(yh),this._cascadeMaxExtents[e].maximizeInPlace(yh)}}}_recreateSceneUBOs(){if(this._disposeSceneUBOs(),this._sceneUBOs)for(let e=0;e<this._numCascades;++e)this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${e})`))}static get IsSupported(){const e=A.l.LastCreatedEngine;return!!e&&e._features.supportCSM}constructor(e,t,i,n){Th.IsSupported?(super(e,t,i,n),this.usePercentageCloserFiltering=!0):_.Y.Error("CascadedShadowMap is not supported by the current engine.")}_initializeGenerator(){var e,t,i,n,s,r,a,l,h,c,u,d,p,f,_,m,g,v,y,x;this.penumbraDarkness=null!==(e=this.penumbraDarkness)&&void 0!==e?e:1,this._numCascades=null!==(t=this._numCascades)&&void 0!==t?t:Th.DEFAULT_CASCADES_COUNT,this.stabilizeCascades=null!==(i=this.stabilizeCascades)&&void 0!==i&&i,this._freezeShadowCastersBoundingInfoObservable=null!==(n=this._freezeShadowCastersBoundingInfoObservable)&&void 0!==n?n:null,this.freezeShadowCastersBoundingInfo=null!==(s=this.freezeShadowCastersBoundingInfo)&&void 0!==s&&s,this._scbiMin=null!==(r=this._scbiMin)&&void 0!==r?r:new o.P(0,0,0),this._scbiMax=null!==(a=this._scbiMax)&&void 0!==a?a:new o.P(0,0,0),this._shadowCastersBoundingInfo=null!==(l=this._shadowCastersBoundingInfo)&&void 0!==l?l:new wn.j(new o.P(0,0,0),new o.P(0,0,0)),this._breaksAreDirty=null===(h=this._breaksAreDirty)||void 0===h||h,this._minDistance=null!==(c=this._minDistance)&&void 0!==c?c:0,this._maxDistance=null!==(u=this._maxDistance)&&void 0!==u?u:1,this._currentLayer=null!==(d=this._currentLayer)&&void 0!==d?d:0,this._shadowMaxZ=null!==(_=null!==(p=this._shadowMaxZ)&&void 0!==p?p:null===(f=this._getCamera())||void 0===f?void 0:f.maxZ)&&void 0!==_?_:1e4,this._debug=null!==(m=this._debug)&&void 0!==m&&m,this._depthClamp=null===(g=this._depthClamp)||void 0===g||g,this._cascadeBlendPercentage=null!==(v=this._cascadeBlendPercentage)&&void 0!==v?v:.1,this._lambda=null!==(y=this._lambda)&&void 0!==y?y:.5,this._autoCalcDepthBounds=null!==(x=this._autoCalcDepthBounds)&&void 0!==x&&x,this._recreateSceneUBOs(),super._initializeGenerator()}_createTargetRenderTexture(){const e=this._scene.getEngine(),t={width:this._mapSize,height:this._mapSize,layers:this.numCascades};this._shadowMap=new Ai._(this._light.name+"_CSMShadowMap",t,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)}_initializeShadowMap(){if(super._initializeShadowMap(),null===this._shadowMap)return;this._transformMatricesAsArray=new Float32Array(16*this._numCascades),this._viewSpaceFrustumsZ=new Array(this._numCascades),this._frustumLengths=new Array(this._numCascades),this._lightSizeUVCorrection=new Array(2*this._numCascades),this._depthCorrection=new Array(this._numCascades),this._cascades=[],this._viewMatrices=[],this._projectionMatrices=[],this._transformMatrices=[],this._cascadeMinExtents=[],this._cascadeMaxExtents=[],this._frustumCenter=[],this._shadowCameraPos=[],this._frustumCornersWorldSpace=[];for(let e=0;e<this._numCascades;++e){this._cascades[e]={prevBreakDistance:0,breakDistance:0},this._viewMatrices[e]=o.y3.Zero(),this._projectionMatrices[e]=o.y3.Zero(),this._transformMatrices[e]=o.y3.Zero(),this._cascadeMinExtents[e]=new o.P,this._cascadeMaxExtents[e]=new o.P,this._frustumCenter[e]=new o.P,this._shadowCameraPos[e]=new o.P,this._frustumCornersWorldSpace[e]=new Array(Th._FrustumCornersNDCSpace.length);for(let t=0;t<Th._FrustumCornersNDCSpace.length;++t)this._frustumCornersWorldSpace[e][t]=new o.P}const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.clear(),this._shadowMap.onBeforeRenderObservable.clear(),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===dh.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(),null===(t=e._debugPushGroup)||void 0===t||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!==dh.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,n=this._light;if(!i.shadowsEnabled||!n.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const s=this._getCamera();s&&this._shadowMaxZ<s.maxZ&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const n=this._getCamera();if(!n)return;const s=this.getShadowMap();if(!s)return;const r=s.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===dh.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,s),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r,1/r,this.frustumEdgeFalloff,e);else if(this._filter===dh.FILTER_PCSS){for(let e=0;e<this._numCascades;++e)this._lightSizeUVCorrection[2*e+0]=0===e?1:(this._cascadeMaxExtents[0].x-this._cascadeMinExtents[0].x)/(this._cascadeMaxExtents[e].x-this._cascadeMinExtents[e].x),this._lightSizeUVCorrection[2*e+1]=0===e?1:(this._cascadeMaxExtents[0].y-this._cascadeMinExtents[0].y)/(this._cascadeMaxExtents[e].y-this._cascadeMinExtents[e].y),this._depthCorrection[e]=0===e?1:(this._cascadeMaxExtents[e].z-this._cascadeMinExtents[e].z)/(this._cascadeMaxExtents[0].z-this._cascadeMinExtents[0].z);t.setDepthStencilTexture("shadowSampler"+e,s),t.setTexture("depthSampler"+e,s),t.setArray2("lightSizeUVCorrection"+e,this._lightSizeUVCorrection),t.setArray("depthCorrection"+e,this._depthCorrection),t.setFloat("penumbraDarkness"+e,this.penumbraDarkness),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/r,this._contactHardeningLightSizeUVRatio*r,this.frustumEdgeFalloff,e)}else t.setTexture("shadowSampler"+e,s),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r,1/r,this.frustumEdgeFalloff,e);i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(n),this.getLight().getDepthMinZ(n)+this.getLight().getDepthMaxZ(n),e)}getTransformMatrix(){return this.getCascadeTransformMatrix(0)}dispose(){super.dispose(),this._freezeShadowCastersBoundingInfoObservable&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._depthReducer&&(this._depthReducer.dispose(),this._depthReducer=null)}serialize(){const e=super.serialize(),t=this.getShadowMap();if(!t)return e;if(e.numCascades=this._numCascades,e.debug=this._debug,e.stabilizeCascades=this.stabilizeCascades,e.lambda=this._lambda,e.cascadeBlendPercentage=this.cascadeBlendPercentage,e.depthClamp=this._depthClamp,e.autoCalcDepthBounds=this.autoCalcDepthBounds,e.shadowMaxZ=this._shadowMaxZ,e.penumbraDarkness=this.penumbraDarkness,e.freezeShadowCastersBoundingInfo=this._freezeShadowCastersBoundingInfo,e.minDistance=this.minDistance,e.maxDistance=this.maxDistance,e.renderList=[],t.renderList)for(let i=0;i<t.renderList.length;i++){const n=t.renderList[i];e.renderList.push(n.id)}return e}static Parse(e,t){const i=dh.Parse(e,t,((e,t,i)=>new Th(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}Th._FrustumCornersNDCSpace=[new o.P(-1,1,-1),new o.P(1,1,-1),new o.P(1,-1,-1),new o.P(-1,-1,-1),new o.P(-1,1,1),new o.P(1,1,1),new o.P(1,-1,1),new o.P(-1,-1,1)],Th.CLASSNAME="CascadedShadowGenerator",Th.DEFAULT_CASCADES_COUNT=4,Th.MIN_CASCADES_COUNT=2,Th.MAX_CASCADES_COUNT=4,Th._SceneComponentInitialization=e=>{throw(0,Zl.S)("ShadowGeneratorSceneComponent")},n.p.AddParser(ve.l.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,n=e.shadowGenerators.length;i<n;i++){const n=e.shadowGenerators[i];n.className===Th.CLASSNAME?Th.Parse(n,t):dh.Parse(n,t)}}));class Sh{constructor(e){this.name=ve.l.NAME_SHADOWGENERATOR,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ve.l.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR,this,this._gatherRenderTargets)}rebuild(){}serialize(e){e.shadowGenerators=[];const t=this.scene.lights;for(const i of t){const t=i.getShadowGenerators();if(t){const i=t.values();for(let t=i.next();!0!==t.done;t=i.next()){const i=t.value;e.shadowGenerators.push(i.serialize())}}}}addFromContainer(e){}removeFromContainer(e,t){}dispose(){}_gatherRenderTargets(e){const t=this.scene;if(this.scene.shadowsEnabled)for(let i=0;i<t.lights.length;i++){const n=t.lights[i],s=n.getShadowGenerators();if(n.isEnabled()&&n.shadowEnabled&&s){const i=s.values();for(let n=i.next();!0!==n.done;n=i.next()){const i=n.value.getShadowMap();-1!==t.textures.indexOf(i)&&e.push(i)}}}}}dh._SceneComponentInitialization=e=>{let t=e._getComponent(ve.l.NAME_SHADOWGENERATOR);t||(t=new Sh(e),e._addComponent(t))};var Eh=i(5520);class Ch{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.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",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;Ch.DefaultLogoUrl?t.src=Ch.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",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 n=new Image;if(Ch.DefaultSpinnerUrl?n.src=Ch.DefaultSpinnerUrl:n.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",n.style.animation="spin1 0.75s infinite linear",n.style.webkitAnimation="spin1 0.75s infinite linear",n.style.transformOrigin="50% 50%",n.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,n.style.width=`${i.w}vh`,n.style.height=`${i.h}vh`,n.style.left=`calc(50% - ${i.w/2}vh)`,n.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(n),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{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)})))}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)}}Ch.DefaultLogoUrl="",Ch.DefaultSpinnerUrl="",ue.D.DefaultLoadingScreenFactory=e=>new Ch(e);var Ah=i(7321),Ph=i(9828);class Rh{static ConvertPanoramaToCubemap(e,t,i,n,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(n,this.FACE_FRONT,e,t,i,s),back:this.CreateCubemapTexture(n,this.FACE_BACK,e,t,i,s),left:this.CreateCubemapTexture(n,this.FACE_LEFT,e,t,i,s),right:this.CreateCubemapTexture(n,this.FACE_RIGHT,e,t,i,s),up:this.CreateCubemapTexture(n,this.FACE_UP,e,t,i,s),down:this.CreateCubemapTexture(n,this.FACE_DOWN,e,t,i,s),size:n,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,n,s,r=!1){const o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),l=r?Math.max(1,Math.round(n/4/e)):1,h=1/l,c=h*h,u=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),p=1/e;let f=0;for(let r=0;r<e;r++)for(let o=0;o<l;o++){let o=t[0],_=t[2];for(let t=0;t<e;t++)for(let h=0;h<l;h++){const l=_.subtract(o).scale(f).add(o);l.normalize();const h=this.CalcProjectionSpherical(l,i,n,s);a[r*e*3+3*t+0]+=h.r*c,a[r*e*3+3*t+1]+=h.g*c,a[r*e*3+3*t+2]+=h.b*c,o=o.add(u),_=_.add(d)}f+=p*h}return a}static CalcProjectionSpherical(e,t,i,n){let s=Math.atan2(e.z,e.x);const r=Math.acos(e.y);for(;s<-Math.PI;)s+=2*Math.PI;for(;s>Math.PI;)s-=2*Math.PI;let o=s/Math.PI;const a=r/Math.PI;o=.5*o+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(a*n);h<0?h=0:h>=n&&(h=n-1);const c=n-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}Rh.FACE_LEFT=[new o.P(-1,-1,-1),new o.P(1,-1,-1),new o.P(-1,1,-1),new o.P(1,1,-1)],Rh.FACE_RIGHT=[new o.P(1,-1,1),new o.P(-1,-1,1),new o.P(1,1,1),new o.P(-1,1,1)],Rh.FACE_FRONT=[new o.P(1,-1,-1),new o.P(1,-1,1),new o.P(1,1,-1),new o.P(1,1,1)],Rh.FACE_BACK=[new o.P(-1,-1,1),new o.P(-1,-1,-1),new o.P(-1,1,1),new o.P(-1,1,-1)],Rh.FACE_DOWN=[new o.P(1,1,-1),new o.P(1,1,1),new o.P(-1,1,-1),new o.P(-1,1,1)],Rh.FACE_UP=[new o.P(-1,-1,-1),new o.P(-1,-1,1),new o.P(1,-1,-1),new o.P(1,-1,1)];class Mh{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,n,s,r){s>0?(s=this._Ldexp(1,s-136),e[r+0]=t*s,e[r+1]=i*s,e[r+2]=n*s):(e[r+0]=0,e[r+1]=0,e[r+2]=0)}static _ReadStringLine(e,t){let i="",n="";for(let s=t;s<e.length-t&&(n=String.fromCharCode(e[s]),"\n"!=n);s++)i+=n;return i}static RGBE_ReadHeader(e){let t=0,i=0,n=this._ReadStringLine(e,0);if("#"!=n[0]||"?"!=n[1])throw"Bad HDR Format.";let s=!1,r=!1,o=0;do{o+=n.length+1,n=this._ReadStringLine(e,o),"FORMAT=32-bit_rle_rgbe"==n?r=!0:0==n.length&&(s=!0)}while(!s);if(!r)throw"HDR Bad header format, unsupported FORMAT";o+=n.length+1,n=this._ReadStringLine(e,o);const a=/^-Y (.*) \+X (.*)$/g.exec(n);if(!a||a.length<3)throw"HDR Bad header format, no size";if(i=parseInt(a[2]),t=parseInt(a[1]),i<8||i>32767)throw"HDR Bad header format, unsupported size";return o+=n.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const n=new Uint8Array(e),s=this.RGBE_ReadHeader(n),r=this.RGBE_ReadPixels(n,s);return Rh.ConvertPanoramaToCubemap(r,s.width,s.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const n=t.width;let s,r,o,a,l,h=t.dataPosition,c=0,u=0,d=0;const p=new ArrayBuffer(4*n),f=new Uint8Array(p),_=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(_);for(;i>0;){if(s=e[h++],r=e[h++],o=e[h++],a=e[h++],2!=s||2!=r||128&o||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|a)!=n)throw"HDR Bad header format, wrong scan line width";for(c=0,d=0;d<4;d++)for(u=(d+1)*n;c<u;)if(s=e[h++],r=e[h++],s>128){if(l=s-128,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)f[c++]=r}else{if(l=s,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (non-run)";if(f[c++]=r,--l>0)for(let t=0;t<l;t++)f[c++]=e[h++]}for(d=0;d<n;d++)s=f[d],r=f[d+n],o=f[d+2*n],a=f[d+3*n],this._Rgbe2float(m,s,r,o,a,(t.height-i)*n*3+3*d);i--}return m}static _RGBEReadPixelsNOTRLE(e,t){let i=t.height;const n=t.width;let s,r,o,a,l,h=t.dataPosition;const c=new ArrayBuffer(t.width*t.height*4*3),u=new Float32Array(c);for(;i>0;){for(l=0;l<t.width;l++)s=e[h++],r=e[h++],o=e[h++],a=e[h++],this._Rgbe2float(u,s,r,o,a,(t.height-i)*n*3+3*l);i--}return u}}var Ih=i(7218);si.v.ShadersStore.hdrFilteringVertexShader="attribute vec2 position;\nvarying vec3 direction;\nuniform vec3 up;\nuniform vec3 right;\nuniform vec3 front;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nmat3 view=mat3(up,right,front);\ndirection=view*vec3(position,1.0);\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}",i(3897),i(3154),i(4115);si.v.ShadersStore.hdrFilteringPixelShader="#include<helperFunctions>\n#include<importanceSampling>\n#include<pbrBRDFFunctions>\n#include<hdrFilteringFunctions>\nuniform float alphaG;\nuniform samplerCube inputTexture;\nuniform vec2 vFilteringInfo;\nuniform float hdrScale;\nvarying vec3 direction;\nvoid main() {\nvec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);\ngl_FragColor=vec4(color*hdrScale,1.0);\n}";class Dh{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=lt.R.ILog2(t)+1,n=this._effectWrapper.effect,s=this._createRenderTarget(t);this._effectRenderer.setViewport();const r=e.getInternalTexture();r&&this._engine.updateTextureSamplingMode(3,r,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);const o=[[new Gr.P(0,0,-1),new Gr.P(0,-1,0),new Gr.P(1,0,0)],[new Gr.P(0,0,1),new Gr.P(0,-1,0),new Gr.P(-1,0,0)],[new Gr.P(1,0,0),new Gr.P(0,0,1),new Gr.P(0,1,0)],[new Gr.P(1,0,0),new Gr.P(0,0,-1),new Gr.P(0,-1,0)],[new Gr.P(1,0,0),new Gr.P(0,-1,0),new Gr.P(0,0,1)],[new Gr.P(-1,0,0),new Gr.P(0,-1,0),new Gr.P(0,0,-1)]];n.setFloat("hdrScale",this.hdrScale),n.setFloat2("vFilteringInfo",e.getSize().width,i),n.setTexture("inputTexture",e);for(let e=0;e<6;e++){n.setVector3("up",o[e][0]),n.setVector3("right",o[e][1]),n.setVector3("front",o[e][2]);for(let r=0;r<i;r++){this._engine.bindFramebuffer(s,e,void 0,void 0,!0,r),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let i=Math.pow(2,(r-this._lodGenerationOffset)/this._lodGenerationScale)/t;0===r&&(i=0),n.setFloat("alphaG",i),this._effectRenderer.draw()}}this._effectRenderer.restoreStates(),this._engine.restoreDefaultFramebuffer(),this._engine._releaseTexture(e._texture);const a=s.texture.type,l=s.texture.format;return s._swapAndDie(e._texture),e._texture.type=a,e._texture.format=l,e.gammaSpace=!1,e.lodGenerationOffset=this._lodGenerationOffset,e.lodGenerationScale=this._lodGenerationScale,e._prefiltered=!0,e}_createEffect(e,t){const i=[];return e.gammaSpace&&i.push("#define GAMMA_INPUT"),i.push("#define NUM_SAMPLES "+this.quality+"u"),new Ih.H({engine:this._engine,name:"hdrFiltering",vertexShader:"hdrFiltering",fragmentShader:"hdrFiltering",samplerNames:["inputTexture"],uniformNames:["vSampleDirections","vWeights","up","right","front","vFilteringInfo","hdrScale","alphaG"],useShaderStore:!0,defines:i,onCompiled:t})}isReady(e){return e.isReady()&&this._effectWrapper.effect.isReady()}prefilter(e,t=null){return this._engine._features.allowTexturePrefiltering?new Promise((i=>{this._effectRenderer=new Ih.I(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(_.Y.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."))}}i(452);class Oh extends Oa.V{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(o.y3.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,n=!1,s=!0,a=!1,l=!1,h=null,c=null,u=!1){var d;super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=o.P.Zero(),this.onLoadObservable=new r.y$,e&&(this._coordinatesMode=Ce.x.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=o.y3.Identity(),this._prefilterOnLoad=l,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),h&&h()},this._onError=c,this.gammaSpace=a,this._noMipmap=n,this._size=i,this._supersample=u,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?de.w1.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):(null===(d=this.getScene())||void 0===d?void 0:d.useDelayedTextureLoading)?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new Dh(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=Mh.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){const e=Ka.$.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const n=[];let s=null,r=null;for(let e=0;e<6;e++){2===i?r=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));const o=t[Oh._FacesMapping[e]];if(this.gammaSpace||r||s)for(let e=0;e<this._size*this._size;e++)if(this.gammaSpace&&(o[3*e+0]=Math.pow(o[3*e+0],Me.zp),o[3*e+1]=Math.pow(o[3*e+1],Me.zp),o[3*e+2]=Math.pow(o[3*e+2],Me.zp)),r&&(r[3*e+0]=(0,ro.ay)(o[3*e+0]),r[3*e+1]=(0,ro.ay)(o[3*e+1]),r[3*e+2]=(0,ro.ay)(o[3*e+2])),s){let t=Math.max(255*o[3*e+0],0),i=Math.max(255*o[3*e+1],0),n=Math.max(255*o[3*e+2],0);const r=Math.max(Math.max(t,i),n);if(r>255){const e=255/r;t*=e,i*=e,n*=e}s[3*e+0]=t,s[3*e+1]=i,s[3*e+2]=n}r?n.push(r):s?n.push(s):n.push(o)}return n}),null,this._onLoad,this._onError)}clone(){const e=new Oh(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(){4===this.delayLoadState&&(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()&&(null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this))))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let n=null;return e.name&&!e.isRenderTarget&&(n=new Oh(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),n.name=e.name,n.hasAlpha=e.hasAlpha,n.level=e.level,n.coordinatesMode=e.coordinatesMode,n.isBlocking=e.isBlocking),n&&(e.boundingBoxPosition&&(n.boundingBoxPosition=o.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=o.P.FromArray(e.boundingBoxSize)),e.rotationY&&(n.rotationY=e.rotationY)),n}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}}Oh._FacesMapping=["right","left","up","down","front","back"],(0,l.H)("BABYLON.HDRCubeTexture",Oh);var wh=i(4702),Nh=i(58),Fh=i(4453),Lh=i(934);class Bh{constructor(e=!0,t=10,i=CANNON){this._useDeltaForWorldStep=e,this.name="CannonJSPlugin",this._physicsMaterials=new Array,this._fixedTimeStep=1/60,this._physicsBodiesToRemoveAfterStep=new Array,this._firstFrame=!0,this._tmpQuaternion=new o._f,this._minus90X=new o._f(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new o._f(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=o.P.Zero(),this._tmpDeltaPosition=o.P.Zero(),this._tmpUnityRotation=new o._f,this.BJSCANNON=i,this.isSupported()?(this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=t,this._cannonRaycastResult=new this.BJSCANNON.RaycastResult,this._raycastResult=new Fh.d):_.Y.Error("CannonJS is not available. Please make sure you included the js file.")}getPluginVersion(){return 1}setGravity(e){const t=e;this.world.gravity.set(t.x,t.y,t.z)}setTimeStep(e){this._fixedTimeStep=e}getTimeStep(){return this._fixedTimeStep}executeStep(e,t){if(this._firstFrame){this._firstFrame=!1;for(const e of t)e.type!=Qn.Q.HeightmapImpostor&&e.type!==Qn.Q.PlaneImpostor&&e.beforeStep()}this.world.step(this._useDeltaForWorldStep?e:this._fixedTimeStep),this._removeMarkedPhysicsBodiesFromWorld()}_removeMarkedPhysicsBodiesFromWorld(){this._physicsBodiesToRemoveAfterStep.length>0&&(this._physicsBodiesToRemoveAfterStep.forEach((e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)})),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,n)}applyForce(e,t,i){const n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,n)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t)return void _.Y.Warn("It was not possible to create a physics body for this object.");const i=e.physicsBody;i&&this.removePhysicsBody(e);const n=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:n},r=e.getParam("nativeOptions");for(const e in r)Object.prototype.hasOwnProperty.call(r,e)&&(s[e]=r[e]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){const n=i[t];e.physicsBody[t].set(n.x,n.y,n.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 i=t=>{if(!t.rotationQuaternion)return;const n=t.getPhysicsImpostor();if(n&&n.parent!==e&&t.parent){const i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.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(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=n.getParam("mass")}t.getChildMeshes(!0).filter((e=>!!e.physicsImpostor)).forEach(i)};t.filter((e=>!!e.physicsImpostor)).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let n;const s=e.joint.jointData,r={pivotA:s.mainPivot?(new this.BJSCANNON.Vec3).set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?(new this.BJSCANNON.Vec3).set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?(new this.BJSCANNON.Vec3).set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?(new this.BJSCANNON.Vec3).set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case Nh.q7.HingeJoint:case Nh.q7.Hinge2Joint:n=new this.BJSCANNON.HingeConstraint(t,i,r);break;case Nh.q7.DistanceJoint:n=new this.BJSCANNON.DistanceConstraint(t,i,s.maxDistance||2);break;case Nh.q7.SpringJoint:{const e=s;n=new this.BJSCANNON.Spring(t,i,{restLength:e.length,stiffness:e.stiffness,damping:e.damping,localAnchorA:r.pivotA,localAnchorB:r.pivotB});break}case Nh.q7.LockJoint:n=new this.BJSCANNON.LockConstraint(t,i,r);break;case Nh.q7.PointToPointJoint:case Nh.q7.BallAndSocketJoint:default:n=new this.BJSCANNON.PointToPointConstraint(t,r.pivotA,i,r.pivotB,r.maxForce)}n.collideConnected=!!s.collision,e.joint.physicsJoint=n,e.joint.type!==Nh.q7.SpringJoint?this.world.addConstraint(n):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){n.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==Nh.q7.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let n,s;for(n=0;n<this._physicsMaterials.length;n++)if(s=this._physicsMaterials[n],s.friction===t&&s.restitution===i)return s;const r=new this.BJSCANNON.Material(e);return r.friction=t,r.restitution=i,this._physicsMaterials.push(r),r}_checkWithEpsilon(e){return e<Me.kn?Me.kn:e}_createShape(e){const t=e.object;let i;const n=e.getObjectExtents();switch(e.type){case Qn.Q.SphereImpostor:{const e=n.x,t=n.y,s=n.z;i=new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(e),this._checkWithEpsilon(t),this._checkWithEpsilon(s))/2);break}case Qn.Q.CylinderImpostor:{let t=e.getParam("nativeOptions");t||(t={});const s=void 0!==t.radiusTop?t.radiusTop:this._checkWithEpsilon(n.x)/2,r=void 0!==t.radiusBottom?t.radiusBottom:this._checkWithEpsilon(n.x)/2,o=void 0!==t.height?t.height:this._checkWithEpsilon(n.y),a=void 0!==t.numSegments?t.numSegments:16;i=new this.BJSCANNON.Cylinder(s,r,o,a);const l=new this.BJSCANNON.Quaternion;l.setFromAxisAngle(new this.BJSCANNON.Vec3(1,0,0),-Math.PI/2);const h=new this.BJSCANNON.Vec3(0,0,0);i.transformAllPoints(h,l);break}case Qn.Q.BoxImpostor:{const e=n.scale(.5);i=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(e.x),this._checkWithEpsilon(e.y),this._checkWithEpsilon(e.z)));break}case Qn.Q.PlaneImpostor:_.Y.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),i=new this.BJSCANNON.Plane;break;case Qn.Q.MeshImpostor:{const n=t.getVerticesData?t.getVerticesData(qe.o.PositionKind):[],s=t.getIndices?t.getIndices():[];if(!n)return void _.Y.Warn("Tried to create a MeshImpostor for an object without vertices. This will fail.");const r=t.position.clone(),a=t.rotation&&t.rotation.clone(),l=t.rotationQuaternion&&t.rotationQuaternion.clone();t.position.copyFromFloats(0,0,0),t.rotation&&t.rotation.copyFromFloats(0,0,0),t.rotationQuaternion&&t.rotationQuaternion.copyFrom(e.getParentsRotation()),t.rotationQuaternion&&t.parent&&t.rotationQuaternion.conjugateInPlace();const h=t.computeWorldMatrix(!0),c=new Array;let u;for(u=0;u<n.length;u+=3)o.P.TransformCoordinates(o.P.FromArray(n,u),h).toArray(c,u);_.Y.Warn("MeshImpostor only collides against spheres."),i=new this.BJSCANNON.Trimesh(c,s),t.position.copyFrom(r),a&&t.rotation&&t.rotation.copyFrom(a),l&&t.rotationQuaternion&&t.rotationQuaternion.copyFrom(l);break}case Qn.Q.HeightmapImpostor:{const n=t.position.clone(),s=t.rotation&&t.rotation.clone(),r=t.rotationQuaternion&&t.rotationQuaternion.clone();t.position.copyFromFloats(0,0,0),t.rotation&&t.rotation.copyFromFloats(0,0,0),t.rotationQuaternion&&t.rotationQuaternion.copyFrom(e.getParentsRotation()),t.rotationQuaternion&&t.parent&&t.rotationQuaternion.conjugateInPlace(),t.rotationQuaternion&&t.rotationQuaternion.multiplyInPlace(this._minus90X),i=this._createHeightmap(t),t.position.copyFrom(n),s&&t.rotation&&t.rotation.copyFrom(s),r&&t.rotationQuaternion&&t.rotationQuaternion.copyFrom(r),t.computeWorldMatrix(!0);break}case Qn.Q.ParticleImpostor:i=new this.BJSCANNON.Particle;break;case Qn.Q.NoImpostor:i=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0,0,0))}return i}_createHeightmap(e,t){let i=e.getVerticesData(qe.o.PositionKind);const n=e.computeWorldMatrix(!0),s=new Array;let r;for(r=0;r<i.length;r+=3)o.P.TransformCoordinates(o.P.FromArray(i,r),n).toArray(s,r);i=s;const a=new Array,l=t||~~(Math.sqrt(i.length/3)-1),h=e.getBoundingInfo(),c=Math.min(h.boundingBox.extendSizeWorld.x,h.boundingBox.extendSizeWorld.y),u=h.boundingBox.extendSizeWorld.z,d=2*c/l;for(let e=0;e<i.length;e+=3){const t=Math.round(i[e+0]/d+l/2),n=Math.round(-1*(i[e+1]/d-l/2)),s=-i[e+2]+u;a[t]||(a[t]=[]),a[t][n]||(a[t][n]=s),a[t][n]=Math.max(s,a[t][n])}for(let e=0;e<=l;++e){if(!a[e]){let t=1;for(;!a[(e+t)%l];)t++;a[e]=a[(e+t)%l].slice()}for(let t=0;t<=l;++t)if(!a[e][t]){let i,n=1;for(;void 0===i;)i=a[e][(t+n++)%l];a[e][t]=i}}const p=new this.BJSCANNON.Heightfield(a,{elementSize:d});return p.minY=u,p}_updatePhysicsBodyTransformation(e){const t=e.object;if(t.computeWorldMatrix&&t.computeWorldMatrix(!0),!t.getBoundingInfo())return;const i=e.getObjectCenter();this._tmpDeltaPosition.copyFrom(t.getAbsolutePivotPoint().subtract(i)),this._tmpDeltaPosition.divideInPlace(e.object.scaling),this._tmpPosition.copyFrom(i);let n=t.rotationQuaternion;if(n){if(e.type!==Qn.Q.PlaneImpostor&&e.type!==Qn.Q.HeightmapImpostor||(n=n.multiply(this._minus90X),e.setDeltaRotation(this._plus90X)),e.type===Qn.Q.HeightmapImpostor){const e=t;let n=e.getBoundingInfo();const s=e.rotationQuaternion;e.rotationQuaternion=this._tmpUnityRotation,e.computeWorldMatrix(!0);const r=i.clone();let a=e.getPivotMatrix();a=a?a.clone():o.y3.Identity();const l=o.y3.Translation(n.boundingBox.extendSizeWorld.x,0,-n.boundingBox.extendSizeWorld.z);e.setPreTransformMatrix(l),e.computeWorldMatrix(!0),n=e.getBoundingInfo();const h=n.boundingBox.centerWorld.subtract(i).subtract(e.position).negate();this._tmpPosition.copyFromFloats(h.x,h.y-n.boundingBox.extendSizeWorld.y,h.z),this._tmpDeltaPosition.copyFrom(n.boundingBox.centerWorld.subtract(r)),this._tmpDeltaPosition.y+=n.boundingBox.extendSizeWorld.y,e.rotationQuaternion=s,e.setPreTransformMatrix(a),e.computeWorldMatrix(!0)}else e.type===Qn.Q.MeshImpostor&&this._tmpDeltaPosition.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpDeltaPosition),e.physicsBody.position.set(this._tmpPosition.x,this._tmpPosition.y,this._tmpPosition.z),e.physicsBody.quaternion.set(n.x,n.y,n.z,n.w)}}setTransformationFromPhysicsBody(e){if(e.object.position.set(e.physicsBody.position.x,e.physicsBody.position.y,e.physicsBody.position.z),e.object.rotationQuaternion){const t=e.physicsBody.quaternion;e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}setPhysicsBodyTransformation(e,t,i){e.physicsBody.position.set(t.x,t.y,t.z),e.physicsBody.quaternion.set(i.x,i.y,i.z,i.w)}isSupported(){return void 0!==this.BJSCANNON}setLinearVelocity(e,t){e.physicsBody.velocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.velocity;return t?new o.P(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new o.P(t.x,t.y,t.z):null}setBodyMass(e,t){e.physicsBody.mass=t,e.physicsBody.updateMassProperties()}getBodyMass(e){return e.physicsBody.mass}getBodyFriction(e){return e.physicsBody.material.friction}setBodyFriction(e,t){e.physicsBody.material.friction=t}getBodyRestitution(e){return e.physicsBody.material.restitution}setBodyRestitution(e,t){e.physicsBody.material.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.wakeUp()}updateDistanceJoint(e,t){e.physicsJoint.distance=t}setMotor(e,t,i,n){n||(e.physicsJoint.enableMotor(),e.physicsJoint.setMotorSpeed(t),i&&this.setLimit(e,i))}setLimit(e,t,i){e.physicsJoint.motorEquation.maxForce=i,e.physicsJoint.motorEquation.minForce=void 0===t?-t:t}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.quaternion.x,e.rotationQuaternion.y=i.quaternion.y,e.rotationQuaternion.z=i.quaternion.z,e.rotationQuaternion.w=i.quaternion.w)}getRadius(e){return e.physicsBody.shapes[0].boundingSphereRadius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes[0];t.x=2*i.halfExtents.x,t.y=2*i.halfExtents.y,t.z=2*i.halfExtents.z}dispose(){}_extendNamespace(){const e=new this.BJSCANNON.Vec3,t=this.BJSCANNON;this.BJSCANNON.World.prototype.step=function(i,n,s){if(s=s||10,0===(n=n||0))this.internalStep(i),this.time+=i;else{let r=Math.floor((this.time+n)/i)-Math.floor(this.time/i);r=Math.min(r,s)||1;const o=performance.now();for(let e=0;e!==r&&(this.internalStep(i),!(performance.now()-o>1e3*i));e++);this.time+=n;const a=this.time%i/i,l=e,h=this.bodies;for(let e=0;e!==h.length;e++){const i=h[e];i.type!==t.Body.STATIC&&i.sleepState!==t.Body.SLEEPING?(i.position.vsub(i.previousPosition,l),l.scale(a,l),i.position.vadd(l,i.interpolatedPosition)):(i.interpolatedPosition.set(i.position.x,i.position.y,i.position.z),i.interpolatedQuaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.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))}}Lh.T.DefaultPluginFactory=()=>new Bh;class Uh{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=o.P.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new Fh.d}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(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e}));let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];e&&t?(e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next):i=i.next}}applyImpulse(e,t,i){const n=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*n))}applyForce(e,t,i){_.Y.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());else{if(e.isBodyInitRequired()){const i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},n=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach((function(e){e.physicsImpostor&&n.push(e.physicsImpostor)}));const s=e=>Math.max(e,Me.kn),r=new o._f;n.forEach((t=>{if(!t.object.rotationQuaternion)return;const n=t.object.rotationQuaternion;r.copyFrom(n),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);const o=r.toEulerAngles(),a=t.getObjectExtents(),l=57.29577951308232;if(t===e){const t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{const e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(o.x*l,o.y*l,o.z*l)}switch(t.object.rotationQuaternion.copyFrom(r),t.type){case Qn.Q.ParticleImpostor:_.Y.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case Qn.Q.SphereImpostor:{const e=a.x,t=a.y,n=a.z,r=Math.max(s(e),s(t),s(n))/2;i.type.push("sphere"),i.size.push(r),i.size.push(r),i.size.push(r);break}case Qn.Q.CylinderImpostor:{const e=s(a.x)/2,t=s(a.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case Qn.Q.PlaneImpostor:case Qn.Q.BoxImpostor:default:{const e=s(a.x),t=s(a.y),n=s(a.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(n);break}}t.object.rotationQuaternion=n})),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(r),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}var t}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const n=e.joint.jointData,s=n.nativeParams||{};let r;const o={body1:t,body2:i,axe1:s.axe1||(n.mainAxis?n.mainAxis.asArray():null),axe2:s.axe2||(n.connectedAxis?n.connectedAxis.asArray():null),pos1:s.pos1||(n.mainPivot?n.mainPivot.asArray():null),pos2:s.pos2||(n.connectedPivot?n.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||n.collision,spring:s.spring,world:this.world};switch(e.joint.type){case Nh.q7.BallAndSocketJoint:r="jointBall";break;case Nh.q7.SpringJoint:{_.Y.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const e=n;o.min=e.length||o.min,o.max=Math.max(o.min,o.max)}case Nh.q7.DistanceJoint:r="jointDistance",o.max=n.maxDistance;break;case Nh.q7.PrismaticJoint:r="jointPrisme";break;case Nh.q7.SliderJoint:r="jointSlide";break;case Nh.q7.WheelJoint:r="jointWheel";break;case Nh.q7.HingeJoint:default:r="jointHinge"}o.type=r,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){_.Y.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}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 n=e.physicsBody;e.physicsBody.shapes.next||(n.position.set(t.x,t.y,t.z),n.orientation.set(i.x,i.y,i.z,i.w),n.syncShapes(),n.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 o.P(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new o.P(t.x,t.y,t.z):null}setBodyMass(e,t){const i=0===t;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,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,n){void 0!==i?_.Y.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const s=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,n){const s=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-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=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return _.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){_.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class Vh{constructor(e=!0,t=Ammo,i=null){this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new o._f,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new o.P,this._tmpContactNormal=new o.P,this._tmpVec3=new o.P,this._tmpMatrix=new o.y3,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(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=e=>{const t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new Fh.d,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)):_.Y.Error("AmmoJS is not available. Please make sure you included the js file.")):_.Y.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}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(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i<i?(this.world.stepSimulation(e,0),e=0):(e-=i,this.world.stepSimulation(i,0)),t--}executeStep(e,t){for(const e of t)e.soft||e.beforeStep();this._stepSimulation(this._useDeltaForWorldStep?e:this._timeStep,this._maxSteps,this._fixedTimeStep);for(const e of t)if(e.soft?this._afterSoftStep(e):e.afterStep(),e._onPhysicsCollideCallbacks.length>0&&this._isImpostorInContact(e))for(const t of e._onPhysicsCollideCallbacks)for(const i of t.otherImpostors)(e.physicsBody.isActive()||i.physicsBody.isActive())&&this._isImpostorPairInContact(e,i)&&(e.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),i.onCollide({body:e.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===Qn.Q.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let n,s,r,a,l;const h=new Array;for(let e=0;e<i;e++)n=t.at(e),s=n.get_m_x(),r=s.x(),a=s.y(),l=s.z(),h.push(new o.P(r,a,l));const c=e.object,u=e.getParam("shape");e._isFromLine?e.object=os("lines",{points:h,instance:c}):e.object=ms("ext",{shape:u,path:h,instance:c})}_softbodyOrClothStep(e){const t=e.type===Qn.Q.ClothImpostor?1:-1,i=e.object;let n=i.getVerticesData(qe.o.PositionKind);n||(n=[]);let s=i.getVerticesData(qe.o.NormalKind);s||(s=[]);const r=n.length/3,o=e.physicsBody.get_m_nodes();let a,l,h,c,u,d,p,f;for(let e=0;e<r;e++){a=o.at(e),l=a.get_m_x(),h=l.x(),c=l.y(),u=l.z()*t;const i=a.get_m_n();d=i.x(),p=i.y(),f=i.z()*t,n[3*e]=h,n[3*e+1]=c,n[3*e+2]=u,s[3*e]=d,s[3*e+1]=p,s[3*e+2]=f}const _=new sn.x;_.positions=n,_.normals=s,_.uvs=i.getVerticesData(qe.o.UVKind),_.colors=i.getVerticesData(qe.o.ColorKind),i&&i.getIndices&&(_.indices=i.getIndices()),_.applyToMesh(i)}applyImpulse(e,t,i){if(e.soft)_.Y.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();const n=this._tmpAmmoVectorA,s=this._tmpAmmoVectorB;e.object&&e.object.getWorldMatrix&&i.subtractInPlace(e.object.getWorldMatrix().getTranslation()),n.setValue(i.x,i.y,i.z),s.setValue(t.x,t.y,t.z),e.physicsBody.applyImpulse(s,n)}}applyForce(e,t,i){if(e.soft)_.Y.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();const n=this._tmpAmmoVectorA,s=this._tmpAmmoVectorB;if(e.object&&e.object.getWorldMatrix){const t=e.object.getWorldMatrix().getTranslation();n.setValue(i.x-t.x,i.y-t.y,i.z-t.z)}else n.setValue(i.x,i.y,i.z);s.setValue(t.x,t.y,t.z),e.physicsBody.applyForce(s,n)}}generatePhysicsBody(e){if(e._pluginData.toDispose=[],e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else if(e.isBodyInitRequired()){const t=this._createShape(e),i=e.getParam("mass");if(e._pluginData.mass=i,e.soft)t.get_m_cfg().set_collisions(17),t.get_m_cfg().set_kDP(e.getParam("damping")),this.bjsAMMO.castObject(t,this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(e.getParam("margin")),t.setActivationState(Vh._DISABLE_DEACTIVATION_FLAG),this.world.addSoftBody(t,1,-1),e.physicsBody=t,e._pluginData.toDispose.push(t),this.setBodyPressure(e,0),e.type===Qn.Q.SoftbodyImpostor&&this.setBodyPressure(e,e.getParam("pressure")),this.setBodyStiffness(e,e.getParam("stiffness")),this.setBodyVelocityIterations(e,e.getParam("velocityIterations")),this.setBodyPositionIterations(e,e.getParam("positionIterations"));else{const n=new this.bjsAMMO.btVector3(0,0,0),s=new this.bjsAMMO.btTransform;e.object.computeWorldMatrix(!0),s.setIdentity(),0!==i&&t.calculateLocalInertia(i,n),this._tmpAmmoVectorA.setValue(e.object.position.x,e.object.position.y,e.object.position.z),this._tmpAmmoQuaternion.setValue(e.object.rotationQuaternion.x,e.object.rotationQuaternion.y,e.object.rotationQuaternion.z,e.object.rotationQuaternion.w),s.setOrigin(this._tmpAmmoVectorA),s.setRotation(this._tmpAmmoQuaternion);const r=new this.bjsAMMO.btDefaultMotionState(s),o=new this.bjsAMMO.btRigidBodyConstructionInfo(i,r,t,n),a=new this.bjsAMMO.btRigidBody(o);if(0===i&&(a.setCollisionFlags(a.getCollisionFlags()|Vh._KINEMATIC_FLAG),a.setActivationState(Vh._DISABLE_DEACTIVATION_FLAG)),e.type!=Qn.Q.NoImpostor||t.getChildShape||a.setCollisionFlags(a.getCollisionFlags()|Vh._DISABLE_COLLISION_FLAG),e.type!==Qn.Q.MeshImpostor&&e.type!==Qn.Q.NoImpostor){const t=e.object.getBoundingInfo();this._tmpVec3.copyFrom(e.object.getAbsolutePosition()),this._tmpVec3.subtractInPlace(t.boundingBox.centerWorld),this._tmpVec3.x/=e.object.scaling.x,this._tmpVec3.y/=e.object.scaling.y,this._tmpVec3.z/=e.object.scaling.z,e.setDeltaPosition(this._tmpVec3)}const l=e.getParam("group"),h=e.getParam("mask");l&&h?this.world.addRigidBody(a,l,h):this.world.addRigidBody(a),e.physicsBody=a,e._pluginData.toDispose=e._pluginData.toDispose.concat([a,o,r,s,n,t])}this.setBodyRestitution(e,e.getParam("restitution")),this.setBodyFriction(e,e.getParam("friction"))}}removePhysicsBody(e){this.world&&(e.soft?this.world.removeSoftBody(e.physicsBody):this.world.removeRigidBody(e.physicsBody),e._pluginData&&(e._pluginData.toDispose.forEach((e=>{this.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const n=e.joint.jointData;let s;switch(n.mainPivot||(n.mainPivot=new o.P(0,0,0)),n.connectedPivot||(n.connectedPivot=new o.P(0,0,0)),e.joint.type){case Nh.q7.DistanceJoint:{const e=n.maxDistance;e&&(n.mainPivot=new o.P(0,-e/2,0),n.connectedPivot=new o.P(0,e/2,0)),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z));break}case Nh.q7.HingeJoint:{n.mainAxis||(n.mainAxis=new o.P(0,0,0)),n.connectedAxis||(n.connectedAxis=new o.P(0,0,0));const e=new this.bjsAMMO.btVector3(n.mainAxis.x,n.mainAxis.y,n.mainAxis.z),r=new this.bjsAMMO.btVector3(n.connectedAxis.x,n.connectedAxis.y,n.connectedAxis.z);s=new this.bjsAMMO.btHingeConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z),e,r);break}case Nh.q7.BallAndSocketJoint:s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z));break;default:_.Y.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z))}this.world.addConstraint(s,!e.joint.jointData.collision),e.joint.physicsJoint=s}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let n=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let r,a=i.getVerticesData(qe.o.PositionKind);if(a||(a=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?o._f.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):o._f.Identity(),o.y3.Compose(o.P.One(),e,t.position).invertToRef(this._tmpMatrix),r=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else o.y3.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),r=this._tmpMatrix;const l=s.length/3;for(let t=0;t<l;t++){const i=[];for(let e=0;e<3;e++){let n,l=new o.P(a[3*s[3*t+e]+0],a[3*s[3*t+e]+1],a[3*s[3*t+e]+2]);l=o.P.TransformCoordinates(l,r),n=0==e?this._tmpAmmoVectorA:1==e?this._tmpAmmoVectorB:this._tmpAmmoVectorC,n.setValue(l.x,l.y,l.z),i.push(n)}e.addTriangle(i[0],i[1],i[2]),n++}i.getChildMeshes().forEach((i=>{n+=this._addMeshVerts(e,t,i)}))}return n}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(qe.o.PositionKind);i||(i=[]);let n=t.getVerticesData(qe.o.NormalKind);n||(n=[]),t.computeWorldMatrix(!1);const s=[],r=[];for(let e=0;e<i.length;e+=3){let a=new o.P(i[e],i[e+1],i[e+2]),l=new o.P(n[e],n[e+1],n[e+2]);a=o.P.TransformCoordinates(a,t.getWorldMatrix()),l=o.P.TransformNormal(l,t.getWorldMatrix()),s.push(a.x,a.y,a.z),r.push(l.x,l.y,l.z)}const a=new sn.x;return a.positions=s,a.normals=r,a.uvs=t.getVerticesData(qe.o.UVKind),a.colors=t.getVerticesData(qe.o.ColorKind),t&&t.getIndices&&(a.indices=t.getIndices()),a.applyToMesh(t),t.position=o.P.Zero(),t.rotationQuaternion=null,t.rotation=o.P.Zero(),t.computeWorldMatrix(!0),a}return sn.x.ExtractFromMesh(t)}_createSoftbody(e){const t=e.object;if(t&&t.getIndices){let i=t.getIndices();i||(i=[]);const n=this._softVertexData(e),s=n.positions,r=n.normals;if(null===s||null===r)return new this.bjsAMMO.btCompoundShape;{const e=[],n=[];for(let t=0;t<s.length;t+=3){const i=new o.P(s[t],s[t+1],s[t+2]),a=new o.P(r[t],r[t+1],r[t+2]);e.push(i.x,i.y,-i.z),n.push(a.x,a.y,-a.z)}const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateFromTriMesh(this.world.getWorldInfo(),e,t.getIndices(),i.length/3,!0),l=s.length/3,h=a.get_m_nodes();let c,u;for(let e=0;e<l;e++)c=h.at(e),u=c.get_m_n(),u.setX(n[3*e]),u.setY(n[3*e+1]),u.setZ(n[3*e+2]);return a}}}_createCloth(e){const t=e.object;if(t&&t.getIndices){let i=t.getIndices();i||(i=[]);const n=this._softVertexData(e),s=n.positions,r=n.normals;if(null===s||null===r)return new this.bjsAMMO.btCompoundShape;{const t=s.length,i=Math.sqrt(t/3);e.segments=i;const n=i-1;return this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[3*n],s[3*n+1],s[3*n+2]),this._tmpAmmoVectorD.setValue(s[t-3],s[t-2],s[t-1]),this._tmpAmmoVectorC.setValue(s[t-3-3*n],s[t-2-3*n],s[t-1-3*n]),(new this.bjsAMMO.btSoftBodyHelpers).CreatePatch(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,this._tmpAmmoVectorC,this._tmpAmmoVectorD,i,i,e.getParam("fixedPoints"),!0)}}}_createRope(e){let t,i;const n=this._softVertexData(e),s=n.positions,r=n.normals;if(null===s||null===r)return new this.bjsAMMO.btCompoundShape;if(n.applyToMesh(e.object,!0),e._isFromLine=!0,0===r.map((e=>e*e)).reduce(((e,t)=>e+t)))t=s.length,i=t/3-1,this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[t-3],s[t-2],s[t-1]);else{e._isFromLine=!1;const n=e.getParam("path");if(null===e.getParam("shape"))return _.Y.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=n.length,i=t-1,this._tmpAmmoVectorA.setValue(n[0].x,n[0].y,n[0].z),this._tmpAmmoVectorB.setValue(n[t-1].x,n[t-1].y,n[t-1].z)}e.segments=i;let o=e.getParam("fixedPoints");o=o>3?3:o;const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,o);return a.get_m_cfg().set_collisions(17),a}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let n=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let r=i.getVerticesData(qe.o.PositionKind);r||(r=[]),i.computeWorldMatrix(!1);const a=s.length/3;for(let t=0;t<a;t++){const a=[];for(let e=0;e<3;e++){let n,l=new o.P(r[3*s[3*t+e]+0],r[3*s[3*t+e]+1],r[3*s[3*t+e]+2]);o.y3.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),l=o.P.TransformCoordinates(l,this._tmpMatrix),n=0==e?this._tmpAmmoVectorA:1==e?this._tmpAmmoVectorB:this._tmpAmmoVectorC,n.setValue(l.x,l.y,l.z),a.push(n)}e.addPoint(a[0],!0),e.addPoint(a[1],!0),e.addPoint(a[2],!0),n++}i.getChildMeshes().forEach((i=>{n+=this._addHullVerts(e,t,i)}))}return n}_createShape(e,t=!1){const i=e.object;let n;const s=e.getObjectExtents();if(!t){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];n=new this.bjsAMMO.btCompoundShape;let i=0;if(t.forEach((e=>{const t=e.getPhysicsImpostor();if(t){if(t.type==Qn.Q.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const s=this._createShape(t),r=e.parent.getWorldMatrix().clone(),a=new o.P;r.decompose(a),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*a.x,e.position.y*a.y,e.position.z*a.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),n.addChildShape(this._tmpAmmoTransform,s),t.dispose(),i++}})),i>0){if(e.type!=Qn.Q.NoImpostor){const t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),n.addChildShape(this._tmpAmmoTransform,t))}return n}this.bjsAMMO.destroy(n),n=null}switch(e.type){case Qn.Q.SphereImpostor:if(lt.R.WithinEpsilon(s.x,s.y,1e-4)&&lt.R.WithinEpsilon(s.x,s.z,1e-4))n=new this.bjsAMMO.btSphereShape(s.x/2);else{const e=[new this.bjsAMMO.btVector3(0,0,0)],t=[1];n=new this.bjsAMMO.btMultiSphereShape(e,t,1),n.setLocalScaling(new this.bjsAMMO.btVector3(s.x/2,s.y/2,s.z/2))}break;case Qn.Q.CapsuleImpostor:{const e=s.x/2;n=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case Qn.Q.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),n=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case Qn.Q.PlaneImpostor:case Qn.Q.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),n=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case Qn.Q.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)n=this.onCreateCustomMeshImpostor(e);else{const t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);const s=this._addMeshVerts(t,i,i);n=0==s?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case Qn.Q.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)n=this.onCreateCustomConvexHullImpostor(e);else{const t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,i,i)?(e._pluginData.toDispose.push(t),n=new this.bjsAMMO.btCompoundShape):n=t}break;case Qn.Q.NoImpostor:n=new this.bjsAMMO.btSphereShape(s.x/2);break;case Qn.Q.CustomImpostor:n=this._createCustom(e);break;case Qn.Q.SoftbodyImpostor:n=this._createSoftbody(e);break;case Qn.Q.ClothImpostor:n=this._createCloth(e);break;case Qn.Q.RopeImpostor:n=this._createRope(e);break;default:_.Y.Warn("The impostor type is not currently supported by the ammo plugin.")}return n}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 n=e.physicsBody.getWorldTransform();if(Math.abs(n.getOrigin().x()-t.x)>Me.kn||Math.abs(n.getOrigin().y()-t.y)>Me.kn||Math.abs(n.getOrigin().z()-t.z)>Me.kn||Math.abs(n.getRotation().x()-i.x)>Me.kn||Math.abs(n.getRotation().y()-i.y)>Me.kn||Math.abs(n.getRotation().z()-i.z)>Me.kn||Math.abs(n.getRotation().w()-i.w)>Me.kn)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),n.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),n.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(n),0==e.mass){const t=e.physicsBody.getMotionState();t&&t.setWorldTransform(n)}else e.physicsBody.activate()}isSupported(){return void 0!==this.bjsAMMO}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(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity(),!t)return null;const i=new o.P(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity(),!t)return null;const i=new o.P(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:(_.Y.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===Qn.Q.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):_.Y.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(_.Y.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):_.Y.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(_.Y.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):_.Y.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(_.Y.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):_.Y.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,n,s=1,r=!1){const o=e.segments,a=Math.round((o-1)*i)+o*(o-1-Math.round((o-1)*n));e.physicsBody.appendAnchor(a,t.physicsBody,r,s)}appendHook(e,t,i,n=1,s=!1){const r=Math.round(e.segments*i);e.physicsBody.appendAnchor(r,t.physicsBody,s,n)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){_.Y.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){_.Y.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 n=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,n),i.reset(e,t),n.hasHit()&&(i.setHitData({x:n.get_m_hitNormalWorld().x(),y:n.get_m_hitNormalWorld().y(),z:n.get_m_hitNormalWorld().z()},{x:n.get_m_hitPointWorld().x(),y:n.get_m_hitPointWorld().y(),z:n.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(n),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}Vh._DISABLE_COLLISION_FLAG=4,Vh._KINEMATIC_FLAG=2,Vh._DISABLE_DEACTIVATION_FLAG=4,n.p.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;const t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},n.p.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class kh{constructor(e,t,i,n=!0,s=!1,r=!1){if(this.name=e,this._viewMatrix=o.y3.Identity(),this._target=o.P.Zero(),this._add=o.P.Zero(),this._invertYAxis=!1,this.position=o.P.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=new Array),this._scene.reflectionProbes.push(this);let a=0;if(s){const e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?a=2:e.textureFloatRender&&(a=1)}this._renderTargetTexture=new Ai._(e,t,i,n,!0,a,!0),this._renderTargetTexture.gammaSpace=!r,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const l=i.getEngine().useReverseDepthBuffer;let h;this._renderTargetTexture.onBeforeRenderObservable.add((e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){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)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const t=i.useRightHandedSystem?o.y3.LookAtRHToRef:o.y3.LookAtLHToRef,n=i.useRightHandedSystem?o.y3.PerspectiveFovRH:o.y3.PerspectiveFovLH;t(this.position,this._target,o.P.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=n(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})),this._renderTargetTexture.onBeforeBindObservable.add((()=>{var t,n;this._currentSceneUBO=i.getSceneUniformBuffer(),null===(n=(t=i.getEngine())._debugPushGroup)||void 0===n||n.call(t,`reflection probe generation for ${e}`,1),h=this._scene.imageProcessingConfiguration.applyByPostProcess,r&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((()=>{var e,t;i.imageProcessingConfiguration.applyByPostProcess=h,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),null===(t=(e=i.getEngine())._debugPopGroup)||void 0===t||t.call(e,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}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const e of this._sceneUBOs)e.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=Te.p4.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let n=null;if(t.reflectionProbes)for(let i=0;i<t.reflectionProbes.length;i++){const s=t.reflectionProbes[i];if(s.name===e.name){n=s;break}}return n=Te.p4.Parse((()=>n||new kh(e.name,e.renderTargetSize,t,e._generateMipMaps)),e,t,i),n.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&n.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(n.metadata=e.metadata),n}}(0,be.gn)([(0,Te.RR)()],kh.prototype,"_attachedMesh",void 0),(0,be.gn)([(0,Te.hd)()],kh.prototype,"position",void 0);var Gh=!0;class zh{}zh.LoaderInjectedPhysicsEngine=void 0;let Wh={},Hh={};const Xh=(e,t,i,n)=>{if(!t.materials)return null;for(let s=0,r=t.materials.length;s<r;s++){const r=t.materials[s];if(e(r))return{parsedMaterial:r,material:cs.F.Parse(r,i,n)}}return null},jh=(e,t,i)=>{for(const n in t)if(e.name===t[n])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},Yh=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),qh=(e,t)=>{const i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){const n=t._waitingData.lods.ids,s=i.isEnabled(!1);if(t._waitingData.lods.distances){const r=t._waitingData.lods.distances;if(r.length>=n.length){const t=r.length>n.length?r[r.length-1]:0;i.setEnabled(!1);for(let t=0;t<n.length;t++){const s=n[t],o=e.getMeshById(s);null!=o&&i.addLODLevel(r[t],o)}t>0&&i.addLODLevel(t,null),!0===s&&i.setEnabled(!0)}else de.w1.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},Kh=(e,t,i)=>{if("number"!=typeof e){const n=i.getLastEntryById(e);return n&&null!=t?n.instances[parseInt(t)]:n}const n=Wh[e];return n&&null!=t?n.instances[parseInt(t)]:n},$h=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):Hh[e],Qh=(e,t,i,s,r=!1)=>{const o=new ce.TJ(e);let a="importScene has failed JSON parse";try{var h=JSON.parse(t);a="";const s=ta.n.loggingLevel===ta.n.DETAILED_LOGGING;let r,c;if(void 0!==h.environmentTexture&&null!==h.environmentTexture){const t=void 0===h.isPBR||h.isPBR;if(h.environmentTextureType&&"BABYLON.HDRCubeTexture"===h.environmentTextureType){const n=h.environmentTextureSize?h.environmentTextureSize:128,s=new Oh((h.environmentTexture.match(/https?:\/\//g)?"":i)+h.environmentTexture,e,n,!0,!t,void 0,h.environmentTexturePrefilterOnLoad);h.environmentTextureRotationY&&(s.rotationY=h.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof h.environmentTexture){const t=Fa.B.Parse(h.environmentTexture,e,i);e.environmentTexture=t}else if(h.environmentTexture.endsWith(".env")){const t=new Fa.B((h.environmentTexture.match(/https?:\/\//g)?"":i)+h.environmentTexture,e,h.environmentTextureForcedExtension);h.environmentTextureRotationY&&(t.rotationY=h.environmentTextureRotationY),e.environmentTexture=t}else{const t=Fa.B.CreateFromPrefilteredData((h.environmentTexture.match(/https?:\/\//g)?"":i)+h.environmentTexture,e,h.environmentTextureForcedExtension);h.environmentTextureRotationY&&(t.rotationY=h.environmentTextureRotationY),e.environmentTexture=t}if(!0===h.createDefaultSkybox){const i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,n=h.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,n)}o.environmentTexture=e.environmentTexture}if(void 0!==h.environmentIntensity&&null!==h.environmentIntensity&&(e.environmentIntensity=h.environmentIntensity),void 0!==h.lights&&null!==h.lights)for(r=0,c=h.lights.length;r<c;r++){const t=h.lights[r],i=hh._.Parse(t,e);i&&(Wh[t.uniqueId]=i,o.lights.push(i),i._parentContainer=o,a+=0===r?"\n\tLights:":"",a+="\n\t\t"+i.toString(s))}if(void 0!==h.reflectionProbes&&null!==h.reflectionProbes)for(r=0,c=h.reflectionProbes.length;r<c;r++){const t=h.reflectionProbes[r],n=kh.Parse(t,e,i);n&&(o.reflectionProbes.push(n),n._parentContainer=o,a+=0===r?"\n\tReflection Probes:":"",a+="\n\t\t"+n.toString(s))}if(void 0!==h.animations&&null!==h.animations)for(r=0,c=h.animations.length;r<c;r++){const t=h.animations[r],i=(0,l.q)("BABYLON.Animation");if(i){const n=i.Parse(t);e.animations.push(n),o.animations.push(n),a+=0===r?"\n\tAnimations:":"",a+="\n\t\t"+n.toString(s)}}if(void 0!==h.materials&&null!==h.materials)for(r=0,c=h.materials.length;r<c;r++){const t=h.materials[r],n=cs.F.Parse(t,e,i);n&&(Hh[t.uniqueId||t.id]=n,o.materials.push(n),n._parentContainer=o,a+=0===r?"\n\tMaterials:":"",a+="\n\t\t"+n.toString(s),n.getActiveTextures().forEach((e=>{-1==o.textures.indexOf(e)&&(o.textures.push(e),e._parentContainer=o)})))}if(void 0!==h.multiMaterials&&null!==h.multiMaterials)for(r=0,c=h.multiMaterials.length;r<c;r++){const t=h.multiMaterials[r],i=Ph.G.ParseMultiMaterial(t,e);Hh[t.uniqueId||t.id]=i,o.multiMaterials.push(i),i._parentContainer=o,a+=0===r?"\n\tMultiMaterials:":"",a+="\n\t\t"+i.toString(s),i.getActiveTextures().forEach((e=>{-1==o.textures.indexOf(e)&&(o.textures.push(e),e._parentContainer=o)}))}if(void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers)for(const t of h.morphTargetManagers){const i=wh.O.Parse(t,e);o.morphTargetManagers.push(i),i._parentContainer=o}if(void 0!==h.skeletons&&null!==h.skeletons)for(r=0,c=h.skeletons.length;r<c;r++){const t=h.skeletons[r],i=Ye.O.Parse(t,e);o.skeletons.push(i),i._parentContainer=o,a+=0===r?"\n\tSkeletons:":"",a+="\n\t\t"+i.toString(s)}const u=h.geometries;if(null!=u){const t=new Array,n=u.vertexData;if(null!=n)for(r=0,c=n.length;r<c;r++){const s=n[r];t.push(Ah.Z.Parse(s,e,i))}t.forEach((e=>{e&&(o.geometries.push(e),e._parentContainer=o)}))}if(void 0!==h.transformNodes&&null!==h.transformNodes)for(r=0,c=h.transformNodes.length;r<c;r++){const t=h.transformNodes[r],n=yi.Y.Parse(t,e,i);Wh[t.uniqueId]=n,o.transformNodes.push(n),n._parentContainer=o}if(void 0!==h.meshes&&null!==h.meshes)for(r=0,c=h.meshes.length;r<c;r++){const t=h.meshes[r],n=Nt.Kj.Parse(t,e,i);if(Wh[t.uniqueId]=n,o.meshes.push(n),n._parentContainer=o,n.hasInstances)for(const e of n.instances)o.meshes.push(e),e._parentContainer=o;a+=0===r?"\n\tMeshes:":"",a+="\n\t\t"+n.toString(s)}if(void 0!==h.cameras&&null!==h.cameras)for(r=0,c=h.cameras.length;r<c;r++){const t=h.cameras[r],i=Mt.V.Parse(t,e);Wh[t.uniqueId]=i,o.cameras.push(i),i._parentContainer=o,a+=0===r?"\n\tCameras:":"",a+="\n\t\t"+i.toString(s)}if(void 0!==h.postProcesses&&null!==h.postProcesses)for(r=0,c=h.postProcesses.length;r<c;r++){const t=h.postProcesses[r],n=ni.D.Parse(t,e,i);n&&(o.postProcesses.push(n),n._parentContainer=o,a+=0===r?"\nPostprocesses:":"",a+="\n\t\t"+n.toString())}if(void 0!==h.animationGroups&&null!==h.animationGroups)for(r=0,c=h.animationGroups.length;r<c;r++){const t=h.animationGroups[r],i=oe.O.Parse(t,e);o.animationGroups.push(i),i._parentContainer=o,a+=0===r?"\n\tAnimationGroups:":"",a+="\n\t\t"+i.toString(s)}for(r=0,c=e.cameras.length;r<c;r++){const t=e.cameras[r];null!==t._waitingParentId&&(t.parent=Kh(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,c=e.lights.length;r<c;r++){const t=e.lights[r];t&&null!==t._waitingParentId&&(t.parent=Kh(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,c=e.transformNodes.length;r<c;r++){const t=e.transformNodes[r];null!==t._waitingParentId&&(t.parent=Kh(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,c=e.meshes.length;r<c;r++){const t=e.meshes[r];null!==t._waitingParentId&&(t.parent=Kh(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null),t._waitingData.lods&&qh(e,t)}for(e.multiMaterials.forEach((t=>{t._waitingSubMaterialsUniqueIds.forEach((i=>{t.subMaterials.push($h(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((t=>{null!==t._waitingMaterialId&&(t.material=$h(t._waitingMaterialId,e),t._waitingMaterialId=null)})),r=0,c=e.skeletons.length;r<c;r++){const t=e.skeletons[r];t._hasWaitingData&&(null!=t.bones&&t.bones.forEach((t=>{if(t._waitingTransformNodeId){const i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),t._hasWaitingData=null)}for(r=0,c=e.meshes.length;r<c;r++){const t=e.meshes[r];t._waitingData.freezeWorldMatrix?(t.freezeWorldMatrix(),t._waitingData.freezeWorldMatrix=null):t.computeWorldMatrix(!0)}for(r=0,c=e.lights.length;r<c;r++){const t=e.lights[r];if(t._excludedMeshesIds.length>0){for(let i=0;i<t._excludedMeshesIds.length;i++){const n=e.getMeshById(t._excludedMeshesIds[i]);n&&t.excludedMeshes.push(n)}t._excludedMeshesIds=[]}if(t._includedOnlyMeshesIds.length>0){for(let i=0;i<t._includedOnlyMeshesIds.length;i++){const n=e.getMeshById(t._includedOnlyMeshesIds[i]);n&&t.includedOnlyMeshes.push(n)}t._includedOnlyMeshesIds=[]}}for(e.geometries.forEach((e=>{e._loadedUniqueId=""})),n.p.Parse(h,e,o,i),r=0,c=e.meshes.length;r<c;r++){const t=e.meshes[r];t._waitingData.actions&&(R.Parse(t._waitingData.actions,t,e),t._waitingData.actions=null)}void 0!==h.actions&&null!==h.actions&&R.Parse(h.actions,null,e)}catch(e){const t=Yh("loadAssets",h?h.producer:"Unknown")+a;if(!s)throw _.Y.Log(t),e;s(t,e)}finally{Wh={},Hh={},r||o.removeAllFromScene(),null!==a&&ta.n.loggingLevel!==ta.n.NO_LOGGING&&_.Y.Log(Yh("loadAssets",h?h.producer:"Unknown")+(ta.n.loggingLevel!==ta.n.MINIMAL_LOGGING?a:""))}return o};ta.n.RegisterPlugin({name:"babylon.js",extensions:".babylon",canDirectLoad:e=>-1!==e.indexOf("babylon"),importMesh:(e,t,i,s,r,o,a,l)=>{var h;let c="importMesh has failed JSON parse";try{var u=JSON.parse(i);c="";const l=ta.n.loggingLevel===ta.n.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;const d=new Array,p=new Map,f=[];if(void 0!==u.transformNodes&&null!==u.transformNodes)for(let e=0,i=u.transformNodes.length;e<i;e++){const i=u.transformNodes[e],n=yi.Y.Parse(i,t,s);f.push(n),p.set(n._waitingParsedUniqueId,n),n._waitingParsedUniqueId=null}if(void 0!==u.meshes&&null!==u.meshes){const i=[],n=[],o=[],m=[];for(let h=0,f=u.meshes.length;h<f;h++){const f=u.meshes[h];if(null===e||jh(f,e,d)){if(null!==e&&delete e[e.indexOf(f.name)],void 0!==f.geometryId&&null!==f.geometryId&&void 0!==u.geometries&&null!==u.geometries){let e=!1;["boxes","spheres","cylinders","toruses","grounds","planes","torusKnots","vertexData"].forEach((i=>{!0!==e&&u.geometries[i]&&Array.isArray(u.geometries[i])&&u.geometries[i].forEach((n=>{n.id===f.geometryId&&("vertexData"===i&&Ah.Z.Parse(n,t,s),e=!0)}))})),!1===e&&_.Y.Warn("Geometry not found for mesh "+f.id)}if(f.materialUniqueId||f.materialId){const e=f.materialUniqueId?o:n;let i=-1!==e.indexOf(f.materialUniqueId||f.materialId);if(!1===i&&void 0!==u.multiMaterials&&null!==u.multiMaterials){const n=(i,n)=>{e.push(i);const r=Xh(n,u,t,s);r&&r.material&&(Hh[r.parsedMaterial.uniqueId||r.parsedMaterial.id]=r.material,c+="\n\tMaterial "+r.material.toString(l))};for(let s=0,r=u.multiMaterials.length;s<r;s++){const r=u.multiMaterials[s];if(f.materialUniqueId&&r.uniqueId===f.materialUniqueId||r.id===f.materialId){r.materialsUniqueIds?r.materialsUniqueIds.forEach((e=>n(e,(t=>t.uniqueId===e)))):r.materials.forEach((e=>n(e,(t=>t.id===e)))),e.push(r.uniqueId||r.id);const s=Ph.G.ParseMultiMaterial(r,t);Hh[r.uniqueId||r.id]=s,s&&(i=!0,c+="\n\tMulti-Material "+s.toString(l));break}}}if(!1===i){e.push(f.materialUniqueId||f.materialId);const i=Xh((e=>f.materialUniqueId&&e.uniqueId===f.materialUniqueId||e.id===f.materialId),u,t,s);i&&i.material?(Hh[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,c+="\n\tMaterial "+i.material.toString(l)):_.Y.Warn("Material not found for mesh "+f.id)}}if(f.skeletonId>-1&&void 0!==u.skeletons&&null!==u.skeletons&&!(i.indexOf(f.skeletonId)>-1))for(let e=0,n=u.skeletons.length;e<n;e++){const n=u.skeletons[e];if(n.id===f.skeletonId){const e=Ye.O.Parse(n,t);a.push(e),i.push(n.id),c+="\n\tSkeleton "+e.toString(l)}}if(f.morphTargetManagerId>-1&&void 0!==u.morphTargetManagers&&null!==u.morphTargetManagers&&!(m.indexOf(f.morphTargetManagerId)>-1))for(let e=0,i=u.morphTargetManagers.length;e<i;e++){const i=u.morphTargetManagers[e];if(i.id===f.morphTargetManagerId){const e=wh.O.Parse(i,t);m.push(e.uniqueId),c+="\nMorph target "+e.toString()}}const h=Nt.Kj.Parse(f,t,s);r.push(h),p.set(h._waitingParsedUniqueId,h),h._waitingParsedUniqueId=null,c+="\n\tMesh "+h.toString(l)}}t.multiMaterials.forEach((e=>{e._waitingSubMaterialsUniqueIds.forEach((i=>{e.subMaterials.push($h(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((e=>{null!==e._waitingMaterialId&&(e.material=$h(e._waitingMaterialId,t),e._waitingMaterialId=null)}));for(let e=0,i=t.transformNodes.length;e<i;e++){const i=t.transformNodes[e];if(null!==i._waitingParentId){let e=p.get(parseInt(i._waitingParentId))||null;null===e&&(e=t.getLastEntryById(i._waitingParentId));let n=e;i._waitingParentInstanceIndex&&(n=e.instances[parseInt(i._waitingParentInstanceIndex)],i._waitingParentInstanceIndex=null),i.parent=n,i._waitingParentId=null}}let g;for(let e=0,i=t.meshes.length;e<i;e++){if(g=t.meshes[e],g._waitingParentId){let e=p.get(parseInt(g._waitingParentId))||null;null===e&&(e=t.getLastEntryById(g._waitingParentId));let i=e;if(g._waitingParentInstanceIndex&&(i=e.instances[parseInt(g._waitingParentInstanceIndex)],g._waitingParentInstanceIndex=null),g.parent=i,"TransformNode"===(null===(h=g.parent)||void 0===h?void 0:h.getClassName())){const e=f.indexOf(g.parent);e>-1&&f.splice(e,1)}g._waitingParentId=null}g._waitingData.lods&&qh(t,g)}for(const e of f)e.dispose();for(let e=0,i=t.skeletons.length;e<i;e++){const i=t.skeletons[e];i._hasWaitingData&&(null!=i.bones&&i.bones.forEach((e=>{if(e._waitingTransformNodeId){const i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),i._hasWaitingData=null)}for(let e=0,i=t.meshes.length;e<i;e++)g=t.meshes[e],g._waitingData.freezeWorldMatrix?(g.freezeWorldMatrix(),g._waitingData.freezeWorldMatrix=null):g.computeWorldMatrix(!0)}if(void 0!==u.particleSystems&&null!==u.particleSystems){const e=n.p.GetIndividualParser(ve.l.NAME_PARTICLESYSTEM);if(e)for(let i=0,n=u.particleSystems.length;i<n;i++){const n=u.particleSystems[i];-1!==d.indexOf(n.emitterId)&&o.push(e(n,t,s))}}return t.geometries.forEach((e=>{e._loadedUniqueId=""})),!0}catch(e){const t=Yh("importMesh",u?u.producer:"Unknown")+c;if(!l)throw _.Y.Log(t),e;l(t,e)}finally{null!==c&&ta.n.loggingLevel!==ta.n.NO_LOGGING&&_.Y.Log(Yh("importMesh",u?u.producer:"Unknown")+(ta.n.loggingLevel!==ta.n.MINIMAL_LOGGING?c:"")),Hh={}}return!1},load:(e,t,i,n)=>{let s="importScene has failed JSON parse";try{var r=JSON.parse(t);if(s="",void 0!==r.useDelayedTextureLoading&&null!==r.useDelayedTextureLoading&&(e.useDelayedTextureLoading=r.useDelayedTextureLoading&&!ta.n.ForceFullSceneLoadingForIncremental),void 0!==r.autoClear&&null!==r.autoClear&&(e.autoClear=r.autoClear),void 0!==r.clearColor&&null!==r.clearColor&&(e.clearColor=a.HE.FromArray(r.clearColor)),void 0!==r.ambientColor&&null!==r.ambientColor&&(e.ambientColor=a.Wo.FromArray(r.ambientColor)),void 0!==r.gravity&&null!==r.gravity&&(e.gravity=o.P.FromArray(r.gravity)),void 0!==r.useRightHandedSystem&&(e.useRightHandedSystem=!!r.useRightHandedSystem),r.fogMode&&0!==r.fogMode)switch(e.fogMode=r.fogMode,e.fogColor=a.Wo.FromArray(r.fogColor),e.fogStart=r.fogStart,e.fogEnd=r.fogEnd,e.fogDensity=r.fogDensity,s+="\tFog mode for scene: ",e.fogMode){case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(r.physicsEnabled){let t;"cannon"===r.physicsEngine||r.physicsEngine===Bh.name?t=new Bh(void 0,void 0,zh.LoaderInjectedPhysicsEngine):"oimo"===r.physicsEngine||r.physicsEngine===Uh.name?t=new Uh(void 0,zh.LoaderInjectedPhysicsEngine):"ammo"!==r.physicsEngine&&r.physicsEngine!==Vh.name||(t=new Vh(void 0,zh.LoaderInjectedPhysicsEngine,void 0)),s="\tPhysics engine "+(r.physicsEngine?r.physicsEngine:"oimo")+" enabled\n";const i=r.physicsGravity?o.P.FromArray(r.physicsGravity):null;e.enablePhysics(i,t)}return void 0!==r.metadata&&null!==r.metadata&&(e.metadata=r.metadata),void 0!==r.collisionsEnabled&&null!==r.collisionsEnabled&&(e.collisionsEnabled=r.collisionsEnabled),!!Qh(e,t,i,n,!0)&&(r.autoAnimate&&e.beginAnimation(e,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1),void 0!==r.activeCameraID&&null!==r.activeCameraID&&e.setActiveCameraById(r.activeCameraID),!0)}catch(e){const t=Yh("importScene",r?r.producer:"Unknown")+s;if(!n)throw _.Y.Log(t),e;n(t,e)}finally{null!==s&&ta.n.loggingLevel!==ta.n.NO_LOGGING&&_.Y.Log(Yh("importScene",r?r.producer:"Unknown")+(ta.n.loggingLevel!==ta.n.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,n)=>Qh(e,t,i,n)});var Zh=i(1376),Jh=i(8237);class ec{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,ue.D.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||a.Wo.White(),this.rightColor=e.rightColor||a.Wo.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){const e=new ec;return P.j.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 ec({isEnabled:e.isEnabled,leftColor:a.Wo.FromArray(e.leftColor),rightColor:a.Wo.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}Te.p4._FresnelParametersParser=ec.Parse,i(6980),i(9753);class tc extends us.j{constructor(e,t){super(e,t,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]}),this.disableColorWrite=!0,this.forceDepthWrite=!0,this.setColor4("color",new a.HE(0,0,0,1))}}var ic=i(9482),nc=i(5843);class sc extends nc.m{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 a.Wo(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsLightsDirty")],sc.prototype,"maxSimultaneousLights",void 0),(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsLightsDirty")],sc.prototype,"disableLighting",void 0),(0,be.gn)([(0,Te.oU)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],sc.prototype,"environmentTexture",void 0),(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],sc.prototype,"invertNormalMapX",void 0),(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],sc.prototype,"invertNormalMapY",void 0),(0,be.gn)([(0,Te.oU)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],sc.prototype,"normalTexture",void 0),(0,be.gn)([(0,Te.n9)("emissive"),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],sc.prototype,"emissiveColor",void 0),(0,be.gn)([(0,Te.oU)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],sc.prototype,"emissiveTexture",void 0),(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],sc.prototype,"occlusionStrength",void 0),(0,be.gn)([(0,Te.oU)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],sc.prototype,"occlusionTexture",void 0),(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],sc.prototype,"alphaCutOff",void 0),(0,be.gn)([(0,Te.qC)()],sc.prototype,"doubleSided",null),(0,be.gn)([(0,Te.oU)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty",null)],sc.prototype,"lightmapTexture",void 0),(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],sc.prototype,"useLightmapAsShadowmap",void 0);var rc=i(3077),oc=i(3949);class ac extends sc{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=Te.p4.Clone((()=>new ac(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=Te.p4.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 n=Te.p4.Parse((()=>new ac(e.name,t)),e,t,i);return e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}(0,be.gn)([(0,Te.n9)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],ac.prototype,"baseColor",void 0),(0,be.gn)([(0,Te.oU)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],ac.prototype,"baseTexture",void 0),(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],ac.prototype,"metallic",void 0),(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],ac.prototype,"roughness",void 0),(0,be.gn)([(0,Te.oU)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],ac.prototype,"metallicRoughnessTexture",void 0),(0,l.H)("BABYLON.PBRMetallicRoughnessMaterial",ac);class lc extends sc{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=Te.p4.Clone((()=>new lc(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=Te.p4.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 n=Te.p4.Parse((()=>new lc(e.name,t)),e,t,i);return e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}(0,be.gn)([(0,Te.n9)("diffuse"),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],lc.prototype,"diffuseColor",void 0),(0,be.gn)([(0,Te.oU)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],lc.prototype,"diffuseTexture",void 0),(0,be.gn)([(0,Te.n9)("specular"),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],lc.prototype,"specularColor",void 0),(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_microSurface")],lc.prototype,"glossiness",void 0),(0,be.gn)([(0,Te.oU)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],lc.prototype,"specularGlossinessTexture",void 0),(0,l.H)("BABYLON.PBRSpecularGlossinessMaterial",lc);var hc=i(4783),cc=i(3808);class uc extends Oa.V{constructor(e,t,i=null){if(super(t),e)if(this._textureMatrix=o.y3.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;t=e._features.support3DTextures?e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):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=i=>{if("string"!=typeof i)return;let n,s=null,r=null;const o=i.split("\n");let a=0,l=0,h=0,c=0,u=0;for(let e=0;e<o.length;e++){if(n=o[e],!uc._NoneEmptyLineRegex.test(n))continue;if(0===n.indexOf("#"))continue;const t=n.split(" ");if(0!==a){if(0!=a){const e=Math.max(parseInt(t[0]),0),i=Math.max(parseInt(t[1]),0),n=Math.max(parseInt(t[2]),0);u=Math.max(e,u),u=Math.max(i,u),u=Math.max(n,u);const s=4*(l+c*a+h*a*a);r&&(r[s+0]=e,r[s+1]=i,r[s+2]=n),h++,h%a==0&&(c++,h=0,c%a==0&&(l++,c=0))}}else a=t.length,s=new Uint8Array(a*a*a*4),r=new Float32Array(a*a*a*4)}if(r&&s)for(let e=0;e<r.length;e++)if(e>0&&(e+1)%4==0)s[e]=255;else{const t=r[e];s[e]=t/u*255}t.is3D?(t.updateSize(a,a,a),e.updateRawTexture3D(t,s,5,!1)):(t.updateSize(a*a,a),e.updateRawTexture(t,s,5,!1)),t.isReady=!0,this._triggerOnLoad()},n=this.getScene();return n?n._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 uc(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(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 uc(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}}uc._NoneEmptyLineRegex=/\S+/,(0,l.H)("BABYLON.ColorGradingTexture",uc);var dc=i(5661);class pc extends Oa.V{constructor(e,t,i,n=!1,s=!0,r=null,o=null,a=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=Ce.x.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=a,this._noMipmap=n,this.gammaSpace=s,this._onLoad=r,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?r&&(this._texture.isReady?de.w1.SetImmediate((()=>r())):this._texture.onLoadedObservable.add(r)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(this._loadTexture.bind(this),this._onError)}_loadImage(e,t){const i=document.createElement("canvas");(0,dc.r6)(this.url,(t=>{this._width=t.width,this._height=t.height,i.width=this._width,i.height=this._height;const n=i.getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,i.remove(),e()}),((e,i)=>{t&&t(`${this.getClassName()} could not be loaded`,i)}),null)}_loadTexture(){const e=this.getScene();e&&(this._texture=e.getEngine().createRawCubeTextureFromUrl(this.url,e,this._size,4,e.getEngine().getCaps().textureFloat?1:7,this._noMipmap,(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=Rh.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){const n=t[pc._FacesMapping[e]];i.push(n)}return i}),null,this._onLoad,this._onError))}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let n=0;for(let s=0;s<e.byteLength;s++)(s+1)%4!=0&&(i[n++]=t.getUint8(s)/255);return i}getClassName(){return"EquiRectangularCubeTexture"}clone(){const e=this.getScene();if(!e)return this;const t=new pc(this.url,e,this._size,this._noMipmap,this.gammaSpace);return t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t.coordinatesIndex=this.coordinatesIndex,t.coordinatesMode=this.coordinatesMode,t}}pc._FacesMapping=["right","left","up","down","front","back"];class fc extends Oa.V{constructor(e,t,i){var n,s;super(i.scene||i.engine),this.onLoadObservable=new r.y$,t&&(i.engine||i.scene)&&(i={...fc._DefaultOptions,...i},this._generateMipMaps=i.generateMipMaps,this._samplingMode=i.samplingMode,this._textureMatrix=o.y3.Identity(),this._format=i.format,this.name=e,this.element=t,this._isVideo=!!t.getVideoPlaybackQuality,this._externalTexture=this._isVideo&&null!==(s=null===(n=this._engine)||void 0===n?void 0:n.createExternalTexture(t))&&void 0!==s?s:null,this.anisotropicFilteringLevel=1,this._createInternalTexture())}_createInternalTexture(){let e=0,t=0;this._isVideo?(e=this.element.videoWidth,t=this.element.videoHeight):(e=this.element.width,t=this.element.height);const i=this._getEngine();i&&(this._texture=i.createDynamicTexture(e,t,this._generateMipMaps,this._samplingMode),this._texture.format=this._format),this.update()}getTextureMatrix(){return this._textureMatrix}update(e=null){const t=this._getEngine();if(null==this._texture||null==t)return;const i=this.isReady();if(this._isVideo){const i=this.element;if(i.readyState<i.HAVE_CURRENT_DATA)return;t.updateVideoTexture(this._texture,this._externalTexture?this._externalTexture:i,null===e||e)}else{const i=this.element;t.updateDynamicTexture(this._texture,i,null===e||e,!1,this._format)}!i&&this.isReady()&&this.onLoadObservable.notifyObservers(this)}dispose(){this.onLoadObservable.clear(),super.dispose()}}fc._DefaultOptions={generateMipMaps:!1,samplingMode:2,format:5,engine:null,scene:null};const _c=1,mc=2,gc=3,vc=9,yc=10,xc=11,bc=48,Tc=4,Sc=0,Ec=1,Cc=2,Ac=3;function Pc(e){let t=0;return{id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]}}function Rc(e,t){if(t.length<19)return void _.Y.Error("Unable to load TGA file - Not enough data to contain header");let i=18;const n=Pc(t);if(n.id_length+i>t.length)return void _.Y.Error("Unable to load TGA file - Not enough data");i+=n.id_length;let s,r=!1,o=!1,a=!1;switch(n.image_type){case vc:r=!0;case _c:o=!0;break;case yc:r=!0;case mc:break;case xc:r=!0;case gc:a=!0}const l=n.pixel_size>>3,h=n.width*n.height*l;let c,u,d,p,f,m,g;if(o&&(c=t.subarray(i,i+=n.colormap_length*(n.colormap_size>>3))),r){let e,n,r;s=new Uint8Array(h);let o=0;const a=new Uint8Array(l);for(;i<h&&o<h;)if(e=t[i++],n=1+(127&e),128&e){for(r=0;r<l;++r)a[r]=t[i++];for(r=0;r<n;++r)s.set(a,o+r*l);o+=l*n}else{for(n*=l,r=0;r<n;++r)s[o+r]=t[i++];o+=n}}else s=t.subarray(i,i+=o?n.width*n.height:h);switch((n.flags&bc)>>Tc){default:case Cc:u=0,p=1,g=n.width,d=0,f=1,m=n.height;break;case Sc:u=0,p=1,g=n.width,d=n.height-1,f=-1,m=-1;break;case Ac:u=n.width-1,p=-1,g=-1,d=0,f=1,m=n.height;break;case Ec:u=n.width-1,p=-1,g=-1,d=n.height-1,f=-1,m=-1}const v="_getImageData"+(a?"Grey":"")+n.pixel_size+"bits",y=Mc[v](n,c,s,d,f,m,u,p,g);e.getEngine()._uploadDataToTextureDirectly(e,y)}const Mc={GetTGAHeader:Pc,UploadContent:Rc,_getImageData8bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=t,u=e.width,d=e.height;let p,f,_,m=0;const g=new Uint8Array(u*d*4);for(_=n;_!==r;_+=s)for(f=o;f!==l;f+=a,m++)p=h[m],g[4*(f+u*_)+3]=255,g[4*(f+u*_)+2]=c[3*p+0],g[4*(f+u*_)+1]=c[3*p+1],g[4*(f+u*_)+0]=c[3*p+2];return g},_getImageData16bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f,_=0;const m=new Uint8Array(c*u*4);for(f=n;f!==r;f+=s)for(p=o;p!==l;p+=a,_+=2){d=h[_+0]+(h[_+1]<<8);const e=255*((31744&d)>>10)/31|0,t=255*((992&d)>>5)/31|0,i=255*(31&d)/31|0;m[4*(p+c*f)+0]=e,m[4*(p+c*f)+1]=t,m[4*(p+c*f)+2]=i,m[4*(p+c*f)+3]=32768&d?0:255}return m},_getImageData24bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f=0;const _=new Uint8Array(c*u*4);for(p=n;p!==r;p+=s)for(d=o;d!==l;d+=a,f+=3)_[4*(d+c*p)+3]=255,_[4*(d+c*p)+2]=h[f+0],_[4*(d+c*p)+1]=h[f+1],_[4*(d+c*p)+0]=h[f+2];return _},_getImageData32bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f=0;const _=new Uint8Array(c*u*4);for(p=n;p!==r;p+=s)for(d=o;d!==l;d+=a,f+=4)_[4*(d+c*p)+2]=h[f+0],_[4*(d+c*p)+1]=h[f+1],_[4*(d+c*p)+0]=h[f+2],_[4*(d+c*p)+3]=h[f+3];return _},_getImageDataGrey8bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f,_=0;const m=new Uint8Array(c*u*4);for(f=n;f!==r;f+=s)for(p=o;p!==l;p+=a,_++)d=h[_],m[4*(p+c*f)+0]=d,m[4*(p+c*f)+1]=d,m[4*(p+c*f)+2]=d,m[4*(p+c*f)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f=0;const _=new Uint8Array(c*u*4);for(p=n;p!==r;p+=s)for(d=o;d!==l;d+=a,f+=2)_[4*(d+c*p)+0]=h[f+0],_[4*(d+c*p)+1]=h[f+0],_[4*(d+c*p)+2]=h[f+0],_[4*(d+c*p)+3]=h[f+1];return _}};class Ic{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=Pc(n);i(s.width,s.height,t.generateMipMaps,!1,(()=>{Rc(t,n)}))}}ue.D._TextureLoaders.push(new Ic);class Dc{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=Mh.RGBE_ReadHeader(n),r=Mh.RGBE_ReadPixels(n,s),o=s.width*s.height,a=new Float32Array(4*o);for(let e=0;e<o;e+=1)a[4*e]=r[3*e],a[4*e+1]=r[3*e+1],a[4*e+2]=r[3*e+2],a[4*e+3]=1;i(s.width,s.height,t.generateMipMaps,!1,(()=>{const e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,a)}))}}ue.D._TextureLoaders.push(new Dc);class Oc{}var wc;!function(e){e[e.cTFETC1=0]="cTFETC1",e[e.cTFETC2=1]="cTFETC2",e[e.cTFBC1=2]="cTFBC1",e[e.cTFBC3=3]="cTFBC3",e[e.cTFBC4=4]="cTFBC4",e[e.cTFBC5=5]="cTFBC5",e[e.cTFBC7=6]="cTFBC7",e[e.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",e[e.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",e[e.cTFASTC_4x4=10]="cTFASTC_4x4",e[e.cTFATC_RGB=11]="cTFATC_RGB",e[e.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",e[e.cTFRGBA32=13]="cTFRGBA32",e[e.cTFRGB565=14]="cTFRGB565",e[e.cTFBGR565=15]="cTFBGR565",e[e.cTFRGBA4444=16]="cTFRGBA4444",e[e.cTFFXT1_RGB=17]="cTFFXT1_RGB",e[e.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",e[e.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",e[e.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",e[e.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"}(wc||(wc={}));const Nc={JSModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.js",WasmModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.wasm"},Fc=(e,t)=>{let i;switch(e){case wc.cTFETC1:i=36196;break;case wc.cTFBC1:i=33776;break;case wc.cTFBC4:i=33779;break;case wc.cTFASTC_4x4:i=37808;break;case wc.cTFETC2:i=37496;break;case wc.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i};let Lc=null,Bc=null,Uc=0;const Vc=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,n)=>{(Lc||(Lc=new Promise(((e,t)=>{Bc?e(Bc):de.w1.LoadFileAsync(Nc.WasmModuleURL).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const n=URL.createObjectURL(new Blob([`(${Wc})()`],{type:"application/javascript"}));Bc=new Worker(n);const s=i=>{"init"===i.data.action?(Bc.removeEventListener("message",s),e(Bc)):"error"===i.data.action&&t(i.data.error||"error initializing worker")};Bc.addEventListener("message",s),Bc.postMessage({action:"init",url:Nc.JSModuleURL,wasmBinary:i})})).catch(t)}))),Lc).then((()=>{const s=Uc++,r=t=>{"transcode"===t.data.action&&t.data.id===s&&(Bc.removeEventListener("message",r),t.data.success?e(t.data):n("Transcode is not supported on this device"))};Bc.addEventListener("message",r);const o=new Uint8Array(i.byteLength);o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),Bc.postMessage({action:"transcode",id:s,imageData:o,config:t,ignoreSupportedFormats:!1},[o.buffer])}),(e=>{n(e)}))}))},kc=(e,t)=>{var i,n;let s=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(s=null===(n=t._gl)||void 0===n?void 0:n.TEXTURE_CUBE_MAP),t._bindTextureDirectly(s,e,!0)},Gc=(e,t)=>{const i=e.getEngine();for(let n=0;n<t.fileInfo.images.length;n++){const s=t.fileInfo.images[n].levels[0];if(e._invertVScale=e.invertY,-1===t.format||t.format===wc.cTFRGB565)if(e.type=10,e.format=4,!i._features.basisNeedsPOT||lt.R.Log2(s.width)%1==0&&lt.R.Log2(s.height)%1==0)e._invertVScale=!e.invertY,e.width=s.width+3&-4,e.height=s.height+3&-4,e.samplingMode=2,kc(e,i),i._uploadDataToTextureDirectly(e,new Uint16Array(s.transcodedPixels.buffer),n,0,4,!0);else{const t=new Ei.l(i,Ei.S.Temp);e._invertVScale=e.invertY,t.type=10,t.format=4,t.width=s.width+3&-4,t.height=s.height+3&-4,kc(t,i),i._uploadDataToTextureDirectly(t,new Uint16Array(s.transcodedPixels.buffer),n,0,4,!0),i._rescaleTexture(t,e,i.scenes[0],i._getInternalFormat(4),(()=>{i._releaseTexture(t),kc(e,i)}))}else{e.width=s.width,e.height=s.height,e.generateMipMaps=t.fileInfo.images[n].levels.length>1;const r=zc.GetInternalFormatFromBasisFormat(t.format,i);e.format=r,kc(e,i),t.fileInfo.images[n].levels.forEach(((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,r,t.width,t.height,t.transcodedPixels,n,s)})),!i._features.basisNeedsPOT||lt.R.Log2(e.width)%1==0&&lt.R.Log2(e.height)%1==0||(de.w1.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."),e._cachedWrapU=Ce.x.CLAMP_ADDRESSMODE,e._cachedWrapV=Ce.x.CLAMP_ADDRESSMODE)}}},zc={JSModuleURL:Nc.JSModuleURL,WasmModuleURL:Nc.WasmModuleURL,GetInternalFormatFromBasisFormat:Fc,TranscodeAsync:Vc,LoadTextureFromTranscodeResult:Gc};function Wc(){let e=null;function t(e,t,i,n,s){const r=e.getImageTranscodedSizeInBytes(t,i,n);let o=new Uint8Array(r);return e.transcodeImage(o,t,i,n,1,0)?(s&&(o=function(e,t,i,n){const s=new Uint16Array(4),r=new Uint16Array(i*n),o=i/4,a=n/4;for(let t=0;t<a;t++)for(let n=0;n<o;n++){const a=0+8*(t*o+n);s[0]=e[a]|e[a+1]<<8,s[1]=e[a+2]|e[a+3]<<8,s[2]=(2*(31&s[0])+1*(31&s[1]))/3|(2*(2016&s[0])+1*(2016&s[1]))/3&2016|(2*(63488&s[0])+1*(63488&s[1]))/3&63488,s[3]=(2*(31&s[1])+1*(31&s[0]))/3|(2*(2016&s[1])+1*(2016&s[0]))/3&2016|(2*(63488&s[1])+1*(63488&s[0]))/3&63488;for(let o=0;o<4;o++){const l=e[a+4+o];let h=(4*t+o)*i+4*n;r[h++]=s[3&l],r[h++]=s[l>>2&3],r[h++]=s[l>>4&3],r[h++]=s[l>>6&3]}}return r}(o,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),o):null}onmessage=i=>{if("init"===i.data.action){if(!e){try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}e=BASIS({wasmBinary:i.data.wasmBinary})}null!==e&&e.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===i.data.action){const e=i.data.config,n=i.data.imageData,s=new BASIS.BasisFile(n),r=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),n=[];for(let t=0;t<i;t++){const i={levels:[]},s=e.getNumLevels(t);for(let n=0;n<s;n++){const s={width:e.getImageWidth(t,n),height:e.getImageHeight(t,n)};i.levels.push(s)}n.push(i)}return{hasAlpha:t,images:n}}(s);let o=i.data.ignoreSupportedFormats?null:function(e,t){let i=null;return e.supportedCompressionFormats&&(i=e.supportedCompressionFormats.astc?10:e.supportedCompressionFormats.bc7?6:e.supportedCompressionFormats.s3tc?t.hasAlpha?3:2:e.supportedCompressionFormats.pvrtc?t.hasAlpha?9:8:e.supportedCompressionFormats.etc2?1:e.supportedCompressionFormats.etc1?0:14),i}(i.data.config,r),a=!1;null===o&&(a=!0,o=r.hasAlpha?3:2);let l=!0;s.startTranscoding()||(l=!1);const h=[];for(let i=0;i<r.images.length&&l;i++){const n=r.images[i];if(void 0===e.loadSingleImage||e.loadSingleImage===i){let r=n.levels.length;!1===e.loadMipmapLevels&&(r=1);for(let e=0;e<r;e++){const r=n.levels[e],c=t(s,i,e,o,a);if(!c){l=!1;break}r.transcodedPixels=c,h.push(r.transcodedPixels.buffer)}}}s.close(),s.delete(),a&&(o=-1),l?postMessage({action:"transcode",success:l,id:i.data.id,fileInfo:r,format:o},h):postMessage({action:"transcode",success:l,id:i.data.id})}}}Object.defineProperty(zc,"JSModuleURL",{get:function(){return Nc.JSModuleURL},set:function(e){Nc.JSModuleURL=e}}),Object.defineProperty(zc,"WasmModuleURL",{get:function(){return Nc.WasmModuleURL},set:function(e){Nc.WasmModuleURL=e}});class Hc{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,n,s){if(Array.isArray(e))return;const r=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};Vc(e,o).then((e=>{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;Gc(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()})).catch((e=>{de.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(e)}))}loadData(e,t,i){const n=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};Vc(e,s).then((e=>{const n=e.fileInfo.images[0].levels[0],s=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(n.width,n.height,s,-1!==e.format,(()=>{Gc(t,e)}))})).catch((e=>{de.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),de.w1.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}}ue.D._TextureLoaders.push(new Hc);class Xc extends Ai._{get isSupported(){var e,t;return null!==(t=null===(e=this._engine)||void 0===e?void 0:e.getCaps().drawBuffersExtension)&&void 0!==t&&t}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t<this._textures.length;t++)this._textures[t].wrapU=e}set wrapV(e){if(this._textures)for(let t=0;t<this._textures.length;t++)this._textures[t].wrapV=e}constructor(e,t,i,n,s,r){const o=!(!s||!s.generateMipMaps)&&s.generateMipMaps,a=!(!s||!s.generateDepthTexture)&&s.generateDepthTexture,l=s&&s.depthTextureFormat?s.depthTextureFormat:15,h=!s||void 0===s.doNotChangeAspectRatio||s.doNotChangeAspectRatio,c=!(!s||!s.drawOnlyOnFirstAttachmentByDefault)&&s.drawOnlyOnFirstAttachmentByDefault;if(super(e,t,n,o,h,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0),!this.isSupported)return void this.dispose();this._textureNames=r;const u=[],d=[],p=[],f=[],_=[],m=[],g=[],v=[];this._initTypes(i,u,d,p,f,_,m,g,v,s);const y=!s||void 0===s.generateDepthBuffer||s.generateDepthBuffer,x=!(!s||void 0===s.generateStencilBuffer)&&s.generateStencilBuffer;this._size=t,this._multiRenderTargetOptions={samplingModes:d,generateMipMaps:o,generateDepthBuffer:y,generateStencilBuffer:x,generateDepthTexture:a,depthTextureFormat:l,types:u,textureCount:i,useSRGBBuffers:p,formats:f,targetTypes:_,faceIndex:m,layerIndex:g,layerCounts:v},this._count=i,this._drawOnlyOnFirstAttachmentByDefault=c,i>0&&(this._createInternalTextures(),this._createTextures(r))}_initTypes(e,t,i,n,s,r,o,a,l,h){for(let c=0;c<e;c++)h&&h.types&&void 0!==h.types[c]?t.push(h.types[c]):t.push(h&&h.defaultType?h.defaultType:0),h&&h.samplingModes&&void 0!==h.samplingModes[c]?i.push(h.samplingModes[c]):i.push(Ce.x.BILINEAR_SAMPLINGMODE),h&&h.useSRGBBuffers&&void 0!==h.useSRGBBuffers[c]?n.push(h.useSRGBBuffers[c]):n.push(!1),h&&h.formats&&void 0!==h.formats[c]?s.push(h.formats[c]):s.push(5),h&&h.targetTypes&&void 0!==h.targetTypes[c]?r.push(h.targetTypes[c]):r.push(3553),h&&h.faceIndex&&void 0!==h.faceIndex[c]?o.push(h.faceIndex[c]):o.push(0),h&&h.layerIndex&&void 0!==h.layerIndex[c]?a.push(h.layerIndex[c]):a.push(0),h&&h.layerCounts&&void 0!==h.layerCounts[c]?l.push(h.layerCounts[c]):l.push(1)}_createInternaTextureIndexMapping(){const e={},t=[];if(!this._renderTarget)return t;const i=this._renderTarget.textures;for(let n=0;n<i.length;n++){const s=i[n];if(!s)continue;const r=e[s.uniqueId];void 0!==r?t[n]=r:e[s.uniqueId]=n}return t}_rebuild(e=!1,t){if(this._count<1)return;const i=this._createInternaTextureIndexMapping();this.releaseInternalTextures(),this._createInternalTextures(),e&&(this._releaseTextures(),this._createTextures(t));const n=this._renderTarget.textures;for(let e=0;e<n.length;e++){const t=this._textures[e];void 0!==i[e]&&this._renderTarget.setTexture(n[i[e]],e),t._texture=n[e],t._texture&&(t._noMipmap=!t._texture.useMipMaps,t._useSRGBBuffer=t._texture._useSRGBBuffer)}1!==this.samples&&this._renderTarget.setSamples(this.samples,!this._drawOnlyOnFirstAttachmentByDefault,!0)}_createInternalTextures(){this._renderTarget=this._getEngine().createMultipleRenderTarget(this._size,this._multiRenderTargetOptions,!this._drawOnlyOnFirstAttachmentByDefault),this._texture=this._renderTarget.texture}_releaseTextures(){if(this._textures)for(let e=0;e<this._textures.length;e++)this._textures[e]._texture=null,this._textures[e].dispose()}_createTextures(e){const t=this._renderTarget.textures;this._textures=[];for(let i=0;i<t.length;i++){const n=new Ce.x(null,this.getScene());(null==e?void 0:e[i])&&(n.name=e[i]),n._texture=t[i],n._texture&&(n._noMipmap=!n._texture.useMipMaps,n._useSRGBBuffer=n._texture._useSRGBBuffer),this._textures.push(n)}}setInternalTexture(e,t,i=!0){var n,s;if(this.renderTarget&&(0===t&&(this._texture=e),this.renderTarget.setTexture(e,t,i),this.textures[t]||(this.textures[t]=new Ce.x(null,this.getScene()),this.textures[t].name=null!==(s=null===(n=this._textureNames)||void 0===n?void 0:n[t])&&void 0!==s?s:this.textures[t].name),this.textures[t]._texture=e,this.textures[t]._noMipmap=!e.useMipMaps,this.textures[t]._useSRGBBuffer=e._useSRGBBuffer,this._count=this.renderTarget.textures?this.renderTarget.textures.length:0,this._multiRenderTargetOptions.types&&(this._multiRenderTargetOptions.types[t]=e.type),this._multiRenderTargetOptions.samplingModes&&(this._multiRenderTargetOptions.samplingModes[t]=e.samplingMode),this._multiRenderTargetOptions.useSRGBBuffers&&(this._multiRenderTargetOptions.useSRGBBuffers[t]=e._useSRGBBuffer),this._multiRenderTargetOptions.targetTypes&&-1!==this._multiRenderTargetOptions.targetTypes[t])){let i=0;i=e.is2DArray?35866:e.isCube?34067:e.is3D?32879:3553,this._multiRenderTargetOptions.targetTypes[t]=i}}setLayerAndFaceIndex(e,t=-1,i=-1){this.textures[e]&&this.renderTarget&&(this._multiRenderTargetOptions.layerIndex&&(this._multiRenderTargetOptions.layerIndex[e]=t),this._multiRenderTargetOptions.faceIndex&&(this._multiRenderTargetOptions.faceIndex[e]=i),this.renderTarget.setLayerAndFaceIndex(e,t,i))}setLayerAndFaceIndices(e,t){this.renderTarget&&(this._multiRenderTargetOptions.layerIndex=e,this._multiRenderTargetOptions.faceIndex=t,this.renderTarget.setLayerAndFaceIndices(e,t))}get samples(){return this._samples}set samples(e){this._renderTarget?this._samples=this._renderTarget.setSamples(e):this._samples=e}resize(e){this._size=e,this._rebuild(void 0,this._textureNames)}updateCount(e,t,i){this._multiRenderTargetOptions.textureCount=e,this._count=e;const n=[],s=[],r=[],o=[],a=[],l=[],h=[],c=[];this._textureNames=i,this._initTypes(e,n,s,r,o,a,l,h,c,t),this._multiRenderTargetOptions.types=n,this._multiRenderTargetOptions.samplingModes=s,this._multiRenderTargetOptions.useSRGBBuffers=r,this._multiRenderTargetOptions.formats=o,this._multiRenderTargetOptions.targetTypes=a,this._multiRenderTargetOptions.faceIndex=l,this._multiRenderTargetOptions.layerIndex=h,this._multiRenderTargetOptions.layerCounts=c,this._rebuild(!0,i)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindMultiColorAttachmentFramebuffer(this._renderTarget,this.isCube,(()=>{this.onAfterRenderObservable.notifyObservers(t)}))}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;const i=null===(e=this._renderTarget)||void 0===e?void 0:e.textures;if(i){for(let e=i.length-1;e>=0;e--)this._textures[e]._texture=null;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null}}}class jc{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Yc{constructor(e,t,i,n){var s,r,o,l,h,c,u,d,p,f,_,m,g;return this.name=e,this.meshes=t,this.scene=n,this.options=i,this.options.map=null!==(s=this.options.map)&&void 0!==s?s:["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=null!==(r=this.options.uvsIn)&&void 0!==r?r:qe.o.UVKind,this.options.uvsOut=null!==(o=this.options.uvsOut)&&void 0!==o?o:qe.o.UVKind,this.options.layout=null!==(l=this.options.layout)&&void 0!==l?l:Yc.LAYOUT_STRIP,this.options.layout===Yc.LAYOUT_COLNUM&&(this.options.colnum=null!==(h=this.options.colnum)&&void 0!==h?h:8),this.options.updateInputMeshes=null===(c=this.options.updateInputMeshes)||void 0===c||c,this.options.disposeSources=null===(u=this.options.disposeSources)||void 0===u||u,this._expecting=0,this.options.fillBlanks=null===(d=this.options.fillBlanks)||void 0===d||d,!0===this.options.fillBlanks&&(this.options.customFillColor=null!==(p=this.options.customFillColor)&&void 0!==p?p:"black"),this.options.frameSize=null!==(f=this.options.frameSize)&&void 0!==f?f:256,this.options.paddingRatio=null!==(_=this.options.paddingRatio)&&void 0!==_?_:.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=null!==(m=this.options.paddingMode)&&void 0!==m?m:Yc.SUBUV_WRAP,this.options.paddingMode===Yc.SUBUV_COLOR&&(this.options.paddingColor=null!==(g=this.options.paddingColor)&&void 0!==g?g:new a.HE(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new o.FM(1,1).divide(t);let n=0;const s=this._expecting,r=this.meshes.length,l=Object.keys(this.sets);for(let e=0;e<l.length;e++){const i=l[e],n=new zi.c(this.name+".TexturePack."+i+"Set",{width:t.x,height:t.y},this.scene,!0,Ce.x.TRILINEAR_SAMPLINGMODE,ue.D.TEXTUREFORMAT_RGBA),s=n.getContext();s.fillStyle="rgba(0,0,0,0)",s.fillRect(0,0,t.x,t.y),n.update(!1),this.sets[i]=n}const h=this.options.frameSize||256,c=this._paddingValue,u=h+2*c,d=()=>{this._calculateMeshUVFrames(h,c,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i<r;i++){const r=this.meshes[i].material;for(let o=0;o<l.length;o++){const p=new zi.c("temp",u,this.scene,!0),f=p.getContext(),_=this._getFrameOffset(i),m=()=>{n++,p.update(!1);const i=f.getImageData(0,0,u,u),r=this.sets[g];if(r.getContext().putImageData(i,t.x*_.x,t.y*_.y),p.dispose(),r.update(!1),n==s)return d(),void e()},g=l[o]||"_blank";if(r&&null!==r[g]){const e=r[g],t=new Image;e instanceof zi.c?t.src=e.getContext().canvas.toDataURL("image/png"):t.src=e.url,de.w1.SetCorsBehavior(t.src,t),t.onload=()=>{f.fillStyle="rgba(0,0,0,0)",f.fillRect(0,0,u,u),p.update(!1),f.setTransform(1,0,0,-1,0,0);const e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)f.drawImage(t,0,0,t.width,t.height,c+h*e[i],c+h*e[i+1]-u,h,h);break;case 1:for(let i=0;i<c;i++)f.drawImage(t,0,0,t.width,t.height,i+h*e[0],c-u,h,h),f.drawImage(t,0,0,t.width,t.height,2*c-i,c-u,h,h),f.drawImage(t,0,0,t.width,t.height,c,i-u,h,h),f.drawImage(t,0,0,t.width,t.height,c,2*c-i-u,h,h);f.drawImage(t,0,0,t.width,t.height,c+h*e[0],c+h*e[1]-u,h,h);break;case 2:f.fillStyle=(this.options.paddingColor||a.Wo.Black()).toHexString(),f.fillRect(0,0,u,-u),f.clearRect(c,c,h,h),f.drawImage(t,0,0,t.width,t.height,c+h*e[0],c+h*e[1]-u,h,h)}f.setTransform(1,0,0,1,0,0),m()}}else f.fillStyle="rgba(0,0,0,0)",this.options.fillBlanks&&(f.fillStyle=this.options.customFillColor),f.fillRect(0,0,u,u),m()}}}_calculateSize(){const e=this.meshes.length||0,t=this.options.frameSize||0,i=this._paddingValue||0;switch(this.options.layout){case 0:return new o.FM(t*e+2*i*e,t+2*i);case 1:{const n=Math.max(2,Math.ceil(Math.sqrt(e))),s=t*n+2*i*n;return new o.FM(s,s)}case 2:{const n=this.options.colnum||1,s=Math.max(1,Math.ceil(e/n));return new o.FM(t*n+2*i*n,t*s+2*i*s)}}return o.FM.Zero()}_calculateMeshUVFrames(e,t,i,n,s){const r=this.meshes.length;for(let a=0;a<r;a++){const r=this.meshes[a],l=new o.FM(e/i.x,e/i.y),h=n.clone().scale(t),c=this._getFrameOffset(a).add(h),u=new jc(a,l,c);this.frames.push(u),s&&(this._updateMeshUV(r,a),this._updateTextureReferences(r))}}_getFrameOffset(e){const t=this.meshes.length;let i,n,s;switch(this.options.layout){case 0:return i=1/t,new o.FM(e*i,0);case 1:{const r=Math.max(2,Math.ceil(Math.sqrt(t)));return n=Math.floor(e/r),s=e-n*r,i=1/r,new o.FM(s*i,n*i)}case 2:{const r=this.options.colnum||1,a=Math.max(1,Math.ceil(t/r));return s=Math.floor(e/a),n=e-s*a,i=new o.FM(1/r,1/a),new o.FM(s*i.x,n*i.y)}}return o.FM.Zero()}_updateMeshUV(e,t){const i=this.frames[t],n=e.getVerticesData(this.options.uvsIn||qe.o.UVKind),s=[];let r=0;n.length&&(r=n.length||0);for(let e=0;e<r;e+=2)s.push(n[e]*i.scale.x+i.offset.x,n[e+1]*i.scale.y+i.offset.y);e.setVerticesData(this.options.uvsOut||qe.o.UVKind,s)}_updateTextureReferences(e,t=!1){const i=e.material,n=Object.keys(this.sets),s=e=>{e.dispose&&e.dispose()};for(let e=0;e<n.length;e++){const r=n[e];if(t)null!==i[r]&&s(i[r]),i[r]=this.sets[r];else{if(!i)return;null!==i[r]&&(s(i[r]),i[r]=this.sets[r])}}}setMeshToFrame(e,t,i=!1){this._updateMeshUV(e,t),i&&this._updateTextureReferences(e,!0)}processAsync(){return new Promise(((e,t)=>{try{if(0===this.meshes.length)return void e();let t=0;const i=i=>{if(t++,this.options.map){for(let e=0;e<this.options.map.length;e++)null!==i[this.options.map[e]]&&(this.sets[this.options.map[e]]||(this.sets[this.options.map[e]]=!0),this._expecting++);t===this.meshes.length&&this._createFrames(e)}};for(let n=0;n<this.meshes.length;n++){const s=this.meshes[n],r=s.material;if(r)r.forceCompilationAsync(s).then((()=>{i(r)}));else if(t++,t===this.meshes.length)return this._createFrames(e)}}catch(e){return t(e)}}))}dispose(){const e=Object.keys(this.sets);for(let t=0;t<e.length;t++){const i=e[t];this.sets[i].dispose()}}download(e="png",t=1){setTimeout((()=>{const i={name:this.name,sets:{},options:{},frames:[]},n=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;s<n.length;s++){const r=n[s],o=this.sets[r];i.sets[r]=o.getContext().canvas.toDataURL("image/"+e,t)}for(let e=0;e<s.length;e++){const t=s[e];i.options[t]=this.options[t]}for(let e=0;e<this.frames.length;e++){const t=this.frames[e];i.frames.push(t.scale.x,t.scale.y,t.offset.x,t.offset.y)}}catch(e){return void _.Y.Warn("Unable to download: "+e)}const r="data:text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(i,null,4)),o=document.createElement("a");o.setAttribute("href",r),o.setAttribute("download",this.name+"_texurePackage.json"),document.body.appendChild(o),o.click(),o.remove()}),0)}updateFromJSON(e){try{const t=JSON.parse(e);this.name=t.name;const i=Object.keys(t.options);for(let e=0;e<i.length;e++)this.options[i[e]]=t.options[i[e]];for(let e=0;e<t.frames.length;e+=4){const i=new jc(e/4,new o.FM(t.frames[e],t.frames[e+1]),new o.FM(t.frames[e+2],t.frames[e+3]));this.frames.push(i)}const n=Object.keys(t.sets);for(let e=0;e<n.length;e++){const i=new Ce.x(t.sets[n[e]],this.scene,!1,!1);this.sets[n[e]]=i}}catch(e){_.Y.Warn("Unable to update from JSON: "+e)}}}Yc.LAYOUT_STRIP=0,Yc.LAYOUT_POWER2=1,Yc.LAYOUT_COLNUM=2,Yc.SUBUV_WRAP=0,Yc.SUBUV_EXTEND=1,Yc.SUBUV_COLOR=2;var qc=i(7902),Kc=i(6662);class $c extends qc.g{constructor(e,t,i,n,s,r,o){super(e,i,null,n,s,r),this._animate=!0,this._time=0,this._texturePath=t,o?this.setFragment(this._texturePath):this._loadJson(t),this.refreshRate=1}_loadJson(e){const t=()=>{try{this.setFragment(this._texturePath)}catch(e){_.Y.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},i=e+"/config.json",n=new Kc.g;n.open("GET",i),n.addEventListener("load",(()=>{if(200===n.status||n.responseText&&n.responseText.length>0)try{this._config=JSON.parse(n.response),this.updateShaderUniforms(),this.updateTextures(),this.setFragment(this._texturePath+"/custom"),this._animate=this._config.animate,this.refreshRate=this._config.refreshrate}catch(e){t()}else t()}),!1),n.addEventListener("error",(()=>{t()}),!1);try{n.send()}catch(e){_.Y.Error("CustomProceduralTexture: Error on XHR send request.")}}isReady(){if(!super.isReady())return!1;for(const e in this._textures)if(!this._textures[e].isReady())return!1;return!0}render(e){const t=this.getScene();this._animate&&t&&(this._time+=.03*t.getAnimationRatio(),this.updateShaderUniforms()),super.render(e)}updateTextures(){for(let e=0;e<this._config.sampler2Ds.length;e++)this.setTexture(this._config.sampler2Ds[e].sample2Dname,new Ce.x(this._texturePath+"/"+this._config.sampler2Ds[e].textureRelativeUrl,this.getScene()))}updateShaderUniforms(){if(this._config)for(let e=0;e<this._config.uniforms.length;e++){const t=this._config.uniforms[e];switch(t.type){case"float":this.setFloat(t.name,t.value);break;case"color3":this.setColor3(t.name,new a.Wo(t.r,t.g,t.b));break;case"color4":this.setColor4(t.name,new a.HE(t.r,t.g,t.b,t.a));break;case"vector2":this.setVector2(t.name,new o.FM(t.x,t.y));break;case"vector3":this.setVector3(t.name,new o.P(t.x,t.y,t.z))}}this.setFloat("time",this._time)}get animate(){return this._animate}set animate(e){this._animate=e}}si.v.ShadersStore.noisePixelShader="uniform float brightness;\nuniform float persistence;\nuniform float timeScale;\nvarying vec2 vUV;\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n";class Qc extends qc.g{constructor(e,t=256,i=A.l.LastCreatedScene,n,s){super(e,t,"noise",i,n,s),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 "+(0|this.octaves)}render(e){this._updateShaderUniforms(),super.render(e)}serialize(){const e={customType:"BABYLON.NoiseProceduralTexture"};return 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 Qc(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 n=new Qc(e.name,e.size,t,void 0,e.generateMipMaps);return n.brightness=e.brightness,n.octaves=e.octaves,n.persistence=e.persistence,n.animationSpeedFactor=e.animationSpeedFactor,n.time=null!==(i=e.time)&&void 0!==i?i:0,n}}(0,l.H)("BABYLON.NoiseProceduralTexture",Qc);var Zc=i(8517),Jc=i(9630),eu=i(3324);class tu extends Ce.x{constructor(e,t,i,n,s,r,o=!0,a=!1,l=Ce.x.TRILINEAR_SAMPLINGMODE,h=0){super(null,r,!o,a),this.format=s,this._texture=r.getEngine().createRawTexture3D(e,t,i,n,s,o,a,l,null,h),this.is3D=!0}update(e){this._texture&&this._getEngine().updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}}class iu extends Ai._{constructor(e,t,i,n){super(e,t,i,n,!0),this.refractionPlane=new ot.J(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add((()=>{this.getScene().clipPlane=this.refractionPlane})),this.onAfterRenderObservable.add((()=>{this.getScene().clipPlane=null}))}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new iu(this.name,t.width,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.refractionPlane=this.refractionPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i.depth=this.depth,i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e}}var nu=i(2035);class su extends nu.g{get renderTarget(){return this._renderTarget}constructor(e,t,i){super(null),this._renderTarget=null,this._engine=e,this._renderTargetOptions=i,this.resize(t)}resize(e){var t;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null,this._texture=null,this._size=e,this._engine&&(this._renderTarget=this._engine.createRenderTargetTexture(this._size,this._renderTargetOptions)),this._texture=this.renderTarget.texture}getInternalTexture(){return this._texture}getClassName(){return"ThinRenderTargetTexture"}dispose(e=!1){var t;null===(t=this._renderTarget)||void 0===t||t.dispose(!0),this._renderTarget=null,e||super.dispose()}}var ru=i(4767),ou=i(3837),au=i(8832),lu=i(9135),hu=i(2904),cu=i(8660);class uu extends cu.VT{constructor(e,t,i,n,s){super(e,t,i),this._blockType=n,this._blockName=s,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof uu&&e._blockName===this._blockName?cu.WS.Compatible:cu.WS.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}var du=i(468),pu=i(7123),fu=i(363);class _u extends du.k{constructor(e){super(e,ru.u.Vertex),this.registerInput("matricesIndices",ou.E.Vector4),this.registerInput("matricesWeights",ou.E.Vector4),this.registerInput("matricesIndicesExtra",ou.E.Vector4,!0),this.registerInput("matricesWeightsExtra",ou.E.Vector4,!0),this.registerInput("world",ou.E.Matrix),this.registerOutput("output",ou.E.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){if(!this.matricesIndices.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesIndices"===e.name));t||(t=new fu.S("matricesIndices"),t.setAsAttribute("matricesIndices")),t.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesWeights"===e.name));t||(t=new fu.S("matricesWeights"),t.setAsAttribute("matricesWeights")),t.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.World));t||(t=new fu.S("world"),t.setAsSystemValue(lu.$.World)),t.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){La.G.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&La.G.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 n=this._outputs[0],s=this.world;return e.compilationString+="#if NUM_BONE_INFLUENCERS>0\r\n",e.compilationString+=this._declareOutput(n,e)+` = ${s.associatedVariableName} * ${i};\r\n`,e.compilationString+="#else\r\n",e.compilationString+=this._declareOutput(n,e)+` = ${s.associatedVariableName};\r\n`,e.compilationString+="#endif\r\n",this}}(0,l.H)("BABYLON.BonesBlock",_u);class mu extends du.k{constructor(e){super(e,ru.u.Vertex),this.registerInput("world0",ou.E.Vector4),this.registerInput("world1",ou.E.Vector4),this.registerInput("world2",ou.E.Vector4),this.registerInput("world3",ou.E.Vector4),this.registerInput("world",ou.E.Matrix,!0),this.registerOutput("output",ou.E.Matrix),this.registerOutput("instanceID",ou.E.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){if(!this.world0.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world0"===e.name));t||(t=new fu.S("world0"),t.setAsAttribute("world0")),t.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world1"===e.name));t||(t=new fu.S("world1"),t.setAsAttribute("world1")),t.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world2"===e.name));t||(t=new fu.S("world2"),t.setAsAttribute("world2")),t.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world3"===e.name));t||(t=new fu.S("world3"),t.setAsAttribute("world3")),t.output.connectTo(this.world3)}if(!this.world.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world"===e.name));t||(t=new fu.S("world"),t.setAsSystemValue(lu.$.World)),t.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,n=!1,s){let r=!1;i.INSTANCES!==n&&(i.setValue("INSTANCES",n),r=!0),s&&i.THIN_INSTANCES!==!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)&&(i.setValue("THIN_INSTANCES",!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)),r=!0),r&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],n=this._outputs[1],s=this.world0,r=this.world1,o=this.world2,a=this.world3;return e.compilationString+="#ifdef INSTANCES\r\n",e.compilationString+=this._declareOutput(i,e)+` = mat4(${s.associatedVariableName}, ${r.associatedVariableName}, ${o.associatedVariableName}, ${a.associatedVariableName});\r\n`,e.compilationString+="#ifdef THIN_INSTANCES\r\n",e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};\r\n`,e.compilationString+="#endif\r\n",t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(n,e)+" = float(gl_InstanceID);\r\n":e.compilationString+=this._declareOutput(n,e)+" = 0.0;\r\n",e.compilationString+="#else\r\n",e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName};\r\n`,e.compilationString+=this._declareOutput(n,e)+" = 0.0;\r\n",e.compilationString+="#endif\r\n",this}}(0,l.H)("BABYLON.InstancesBlock",mu);class gu extends du.k{constructor(e){super(e,ru.u.Vertex),this.registerInput("position",ou.E.Vector3),this.registerInput("normal",ou.E.Vector3),this.registerInput("tangent",ou.E.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(ou.E.Color4|ou.E.Vector4|ou.E.Vector3),this.registerInput("uv",ou.E.Vector2),this.registerOutput("positionOutput",ou.E.Vector3),this.registerOutput("normalOutput",ou.E.Vector3),this.registerOutput("tangentOutput",ou.E.Vector4),this.registerOutput("uvOutput",ou.E.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){if(!this.position.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name));t||(t=new fu.S("position"),t.setAsAttribute()),t.output.connectTo(this.position)}if(!this.normal.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name));t||(t=new fu.S("normal"),t.setAsAttribute("normal")),t.output.connectTo(this.normal)}if(!this.tangent.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name));t||(t=new fu.S("tangent"),t.setAsAttribute("tangent")),t.output.connectTo(this.tangent)}if(!this.uv.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name));t||(t=new fu.S("uv"),t.setAsAttribute("uv")),t.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const t=e.morphTargetManager;(null==t?void 0:t.isUsingTextureForTargets)&&t.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&La.G.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(La.G.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,n){const s=this.position,r=this.normal,o=this.tangent,a=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,u=this.uvOutput,d=e,p=n.NUM_MORPH_INFLUENCERS,f=i.morphTargetManager,_=f&&f.supportsNormals&&n.NORMAL,m=f&&f.supportsTangents&&n.TANGENT,g=f&&f.supportsUVs&&n.UV1;let v="";(null==f?void 0:f.isUsingTextureForTargets)&&p>0&&(v+="float vertexID;\r\n");for(let e=0;e<p;e++)v+="#ifdef MORPHTARGETS\r\n",(null==f?void 0:f.isUsingTextureForTargets)?(v+="vertexID = float(gl_VertexID) * morphTargetTextureInfo.x;\r\n",v+=`${l.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID) - ${s.associatedVariableName}) * morphTargetInfluences[${e}];\r\n`,v+="vertexID += 1.0;\r\n"):v+=`${l.associatedVariableName} += (position${e} - ${s.associatedVariableName}) * morphTargetInfluences[${e}];\r\n`,_&&(v+="#ifdef MORPHTARGETS_NORMAL\r\n",(null==f?void 0:f.isUsingTextureForTargets)?(v+=`${h.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID) - ${r.associatedVariableName}) * morphTargetInfluences[${e}];\r\n`,v+="vertexID += 1.0;\r\n"):v+=`${h.associatedVariableName} += (normal${e} - ${r.associatedVariableName}) * morphTargetInfluences[${e}];\r\n`,v+="#endif\r\n"),g&&(v+="#ifdef MORPHTARGETS_UV\r\n",(null==f?void 0:f.isUsingTextureForTargets)?(v+=`${u.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID).xy - ${a.associatedVariableName}) * morphTargetInfluences[${e}];\r\n`,v+="vertexID += 1.0;\r\n"):v+=`${u.associatedVariableName}.xy += (uv_${e} - ${a.associatedVariableName}.xy) * morphTargetInfluences[${e}];\r\n`,v+="#endif\r\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\r\n",(null==f?void 0:f.isUsingTextureForTargets)?v+=`${c.associatedVariableName}.xyz += (readVector3FromRawSampler(${e}, vertexID) - ${o.associatedVariableName}.xyz) * morphTargetInfluences[${e}];\r\n`:v+=`${c.associatedVariableName}.xyz += (tangent${e} - ${o.associatedVariableName}.xyz) * morphTargetInfluences[${e}];\r\n`,o.type===ou.E.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\r\n`:v+=`${c.associatedVariableName}.w = 1.;\r\n`,v+="#endif\r\n"),v+="#endif\r\n";if(d.compilationString=d.compilationString.replace(this._repeatableContentAnchor,v),p>0)for(let e=0;e<p;e++)d.attributes.push(qe.o.PositionKind+e),_&&d.attributes.push(qe.o.NormalKind+e),m&&d.attributes.push(qe.o.TangentKind+e),g&&d.attributes.push(qe.o.UVKind+"_"+e)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.repeatableContentBlocks.push(this);const t=this.position,i=this.normal,n=this.tangent,s=this.uv,r=this.positionOutput,o=this.normalOutput,a=this.tangentOutput,l=this.uvOutput,h=`//${this.name}`;return e.uniforms.push("morphTargetInfluences"),e.uniforms.push("morphTargetTextureInfo"),e.uniforms.push("morphTargetTextureIndices"),e.samplers.push("morphTargets"),e._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",h),e._emitFunctionFromInclude("morphTargetsVertexDeclaration",h,{repeatKey:"maxSimultaneousMorphTargets"}),e.compilationString+=`${this._declareOutput(r,e)} = ${t.associatedVariableName};\r\n`,e.compilationString+="#ifdef NORMAL\r\n",e.compilationString+=`${this._declareOutput(o,e)} = ${i.associatedVariableName};\r\n`,e.compilationString+="#else\r\n",e.compilationString+=`${this._declareOutput(o,e)} = vec3(0., 0., 0.);\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#ifdef TANGENT\r\n",e.compilationString+=`${this._declareOutput(a,e)} = ${n.associatedVariableName};\r\n`,e.compilationString+="#else\r\n",e.compilationString+=`${this._declareOutput(a,e)} = vec4(0., 0., 0., 0.);\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#ifdef UV1\r\n",e.compilationString+=`${this._declareOutput(l,e)} = ${s.associatedVariableName};\r\n`,e.compilationString+="#else\r\n",e.compilationString+=`${this._declareOutput(l,e)} = vec2(0., 0.);\r\n`,e.compilationString+="#endif\r\n",this._repeatableContentAnchor=e._repeatableContentAnchor,e.compilationString+=this._repeatableContentAnchor,this}}(0,l.H)("BABYLON.MorphTargetsBlock",gu);class vu extends du.k{constructor(e){super(e,ru.u.Vertex),this.registerInput("worldPosition",ou.E.Vector4,!1,ru.u.Vertex),this.registerOutput("direction",ou.E.Vector3),this.registerOutput("color",ou.E.Color3),this.registerOutput("intensity",ou.E.Float),this.registerOutput("shadowBias",ou.E.Float),this.registerOutput("shadowNormalBias",ou.E.Float),this.registerOutput("shadowDepthScale",ou.E.Float),this.registerOutput("shadowDepthRange",ou.E.Vector2)}getClassName(){return"LightInformationBlock"}get worldPosition(){return this._inputs[0]}get direction(){return this._outputs[0]}get color(){return this._outputs[1]}get intensity(){return this._outputs[2]}get shadowBias(){return this._outputs[3]}get shadowNormalBias(){return this._outputs[4]}get shadowDepthScale(){return this._outputs[5]}get shadowDepthRange(){return this._outputs[6]}bind(e,t,i){if(!i)return;this.light&&this.light.isDisposed()&&(this.light=null);let n=this.light;const s=t.getScene();if(!n&&s.lights.length&&(n=this.light=s.lights[0],this._forcePrepareDefines=!0),!n||!n.isEnabled)return e.setFloat3(this._lightDataUniformName,0,0,0),void e.setFloat4(this._lightColorUniformName,0,0,0,0);n.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,n.diffuse,n.intensity);const r=n.getShadowGenerator();if((this.shadowBias.hasEndpoints||this.shadowNormalBias.hasEndpoints||this.shadowDepthScale.hasEndpoints)&&(r?e.setFloat3(this._lightShadowUniformName,r.bias,r.normalBias,r.depthScale):e.setFloat3(this._lightShadowUniformName,0,0,0)),this.shadowDepthRange)if(r&&s.activeCamera){const t=n;e.setFloat2(this._lightShadowExtraUniformName,t.getDepthMinZ(s.activeCamera),t.getDepthMinZ(s.activeCamera)+t.getDepthMaxZ(s.activeCamera))}else e.setFloat2(this._lightShadowExtraUniformName,0,0)}prepareDefines(e,t,i){if(!i._areLightsDirty&&!this._forcePrepareDefines)return;this._forcePrepareDefines=!1;const n=this.light;i.setValue(this._lightTypeDefineName,!!(n&&n instanceof Eh.c),!0)}_buildBlock(e){super._buildBlock(e),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=this.direction,i=this.color,n=this.intensity,s=this.shadowBias,r=this.shadowNormalBias,o=this.shadowDepthScale,a=this.shadowDepthRange;return this._lightDataUniformName=e._getFreeVariableName("lightData"),this._lightColorUniformName=e._getFreeVariableName("lightColor"),this._lightShadowUniformName=e._getFreeVariableName("shadowData"),this._lightShadowExtraUniformName=e._getFreeVariableName("shadowExtraData"),this._lightTypeDefineName=e._getFreeDefineName("LIGHTPOINTTYPE"),e._emitUniformFromString(this._lightDataUniformName,"vec3"),e._emitUniformFromString(this._lightColorUniformName,"vec4"),e.compilationString+=`#ifdef ${this._lightTypeDefineName}\r\n`,e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName});\r\n`,e.compilationString+="#else\r\n",e.compilationString+=this._declareOutput(t,e)+` = ${this._lightDataUniformName};\r\n`,e.compilationString+="#endif\r\n",e.compilationString+=this._declareOutput(i,e)+` = ${this._lightColorUniformName}.rgb;\r\n`,e.compilationString+=this._declareOutput(n,e)+` = ${this._lightColorUniformName}.a;\r\n`,(s.hasEndpoints||r.hasEndpoints||o.hasEndpoints)&&(e._emitUniformFromString(this._lightShadowUniformName,"vec3"),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${this._lightShadowUniformName}.x;\r\n`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${this._lightShadowUniformName}.y;\r\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${this._lightShadowUniformName}.z;\r\n`)),a.hasEndpoints&&(e._emitUniformFromString(this._lightShadowExtraUniformName,"vec2"),e.compilationString+=this._declareOutput(a,e)+` = ${this._lightShadowUniformName};\r\n`),this}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId))}}(0,l.H)("BABYLON.LightInformationBlock",vu);var yu=i(9709),xu=i(9749);class bu extends du.k{constructor(e){super(e,ru.u.Fragment),this.convertInputToLinearSpace=!0,this.registerInput("color",ou.E.AutoDetect),this.registerOutput("output",ou.E.Color4),this.registerOutput("rgb",ou.E.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Color4|ou.E.Vector3|ou.E.Vector4)}getClassName(){return"ImageProcessingBlock"}get color(){return this._inputs[0]}get output(){return this._outputs[0]}get rgb(){return this._outputs[1]}initialize(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings"),e._excludeVariableName("ditherIntensity")}isReady(e,t,i){return!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}prepareDefines(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)}bind(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_buildBlock(e){var t;super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity");const i=this.color,n=this._outputs[0],s=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("imageProcessingDeclaration",s),e._emitFunctionFromInclude("imageProcessingFunctions",s),(null===(t=i.connectedPoint)||void 0===t?void 0:t.isConnected)&&(i.connectedPoint.type===ou.E.Color4||i.connectedPoint.type===ou.E.Vector4?e.compilationString+=`${this._declareOutput(n,e)} = ${i.associatedVariableName};\r\n`:e.compilationString+=`${this._declareOutput(n,e)} = vec4(${i.associatedVariableName}, 1.0);\r\n`,e.compilationString+="#ifdef IMAGEPROCESSINGPOSTPROCESS\r\n",this.convertInputToLinearSpace&&(e.compilationString+=`${n.associatedVariableName}.rgb = toLinearSpace(${i.associatedVariableName}.rgb);\r\n`),e.compilationString+="#else\r\n",e.compilationString+="#ifdef IMAGEPROCESSING\r\n",this.convertInputToLinearSpace&&(e.compilationString+=`${n.associatedVariableName}.rgb = toLinearSpace(${i.associatedVariableName}.rgb);\r\n`),e.compilationString+=`${n.associatedVariableName} = applyImageProcessing(${n.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#endif\r\n",this.rgb.hasEndpoints&&(e.compilationString+=this._declareOutput(this.rgb,e)+` = ${this.output.associatedVariableName}.xyz;\r\n`)),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace};\r\n`,e}serialize(){const e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){var n;super._deserialize(e,t,i),this.convertInputToLinearSpace=null===(n=e.convertInputToLinearSpace)||void 0===n||n}}(0,be.gn)([(0,xu.p)("Convert input to linear space",xu.U.Boolean,"ADVANCED")],bu.prototype,"convertInputToLinearSpace",void 0),(0,l.H)("BABYLON.ImageProcessingBlock",bu);class Tu extends du.k{constructor(e){super(e,ru.u.Fragment,!0),this.registerInput("normal",ou.E.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(ou.E.Color4|ou.E.Vector4|ou.E.Vector3),this.registerInput("tangent",ou.E.Vector4,!1),this.registerInput("world",ou.E.Matrix,!1),this.registerOutput("TBN",ou.E.Object,ru.u.Fragment,new uu("TBN",this,cu.Ab.Output,Tu,"TBNBlock")),this.registerOutput("row0",ou.E.Vector3,ru.u.Fragment),this.registerOutput("row1",ou.E.Vector3,ru.u.Fragment),this.registerOutput("row2",ou.E.Vector3,ru.u.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 ru.u.Fragment}set target(e){}autoConfigure(e){if(!this.world.isConnected){let t=e.getInputBlockByPredicate((e=>e.isSystemValue&&e.systemValue===lu.$.World));t||(t=new fu.S("world"),t.setAsSystemValue(lu.$.World)),t.output.connectTo(this.world)}if(!this.normal.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name));t||(t=new fu.S("normal"),t.setAsAttribute("normal")),t.output.connectTo(this.normal)}if(!this.tangent.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&e.type===ou.E.Vector4));t||(t=new fu.S("tangent"),t.setAsAttribute("tangent")),t.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var n,s,r,o;const a=this.normal,l=this.tangent;let h=a.isConnected;(null===(n=a.connectInputBlock)||void 0===n?void 0:n.isAttribute)&&!e.isVerticesDataPresent(null===(s=a.connectInputBlock)||void 0===s?void 0:s.name)&&(h=!1);let c=l.isConnected;(null===(r=l.connectInputBlock)||void 0===r?void 0:r.isAttribute)&&!e.isVerticesDataPresent(null===(o=l.connectInputBlock)||void 0===o?void 0:o.name)&&(c=!1);const u=h&&c;i.setValue("TBNBLOCK",u,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,n=this.world,s=this.TBN,r=this.row0,o=this.row1,a=this.row2;return e.target===ru.u.Fragment&&(e.compilationString+=`\n // ${this.name}\n vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz;\n vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz);\n vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;\n mat3 ${s.associatedVariableName} = mat3(${n.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal);\n `,r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = vec3(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]);\r\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]);\r\n`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]);\r\n`),e.sharedData.blocksWithDefines.push(this)),this}}(0,l.H)("BABYLON.TBNBlock",Tu),i(8882),i(7441),i(2321);class Su extends du.k{constructor(e){super(e,ru.u.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",ou.E.Vector4,!1),this.registerInput("worldNormal",ou.E.Vector4,!1),this.registerInput("worldTangent",ou.E.Vector4,!0),this.registerInput("uv",ou.E.Vector2,!1),this.registerInput("normalMapColor",ou.E.Color3,!1),this.registerInput("strength",ou.E.Float,!1),this.registerInput("viewDirection",ou.E.Vector3,!0),this.registerInput("parallaxScale",ou.E.Float,!0),this.registerInput("parallaxHeight",ou.E.Float,!0),this.registerInput("TBN",ou.E.Object,!0,ru.u.VertexAndFragment,new uu("TBN",this,cu.Ab.Input,Tu,"TBNBlock")),this.registerInput("world",ou.E.Matrix,!0),this.registerOutput("output",ou.E.Vector4),this.registerOutput("uvOffset",ou.E.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 n=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&n||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!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){if(!this.uv.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name));t||(t=new fu.S("uv"),t.setAsAttribute()),t.output.connectTo(this.uv)}if(!this.strength.isConnected){const e=new fu.S("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,n=this.worldPosition,s=this.worldNormal,r=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2"),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float"),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,"mat4");let o=null;this.normalMapColor.connectedPoint&&(o=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const a=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&o||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),l=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",h=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\r\n#if !defined(NORMALXYSCALE)\r\n1.0/\r\n#endif\r\n${e._emitFloat(this.strength.connectInputBlock.value)}`:`\r\n#if !defined(NORMALXYSCALE)\r\n1.0/\r\n#endif\r\n${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const c={search:/defined\(TANGENT\)/g,replace:r.isConnected?"defined(TANGENT)":"defined(IGNORE)"},u=this.TBN;u.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n mat3 vTBN = ${u.associatedVariableName};\n #endif\n `:r.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${s.associatedVariableName}.xyz);\r\n`,e.compilationString+=`vec3 tbnTangent = normalize(${r.associatedVariableName}.xyz);\r\n`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\r\n`,e.compilationString+="mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n"),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[c,{search:/varying mat3 vTBN/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include<samplerFragmentDeclaration>\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:"#define inline\r\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)"},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const d=a&&o?`texture2D(${o}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\r\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${d}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${d}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${a&&this.useParallaxOcclusion?o:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${a?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:h},{search:/vBumpInfos.z/g,replace:l},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:n.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:s.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:a?this.viewDirection.associatedVariableName:"vec3(0.)"},c]}),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};\r\n`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};\r\n`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\r\n`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\r\n`,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}}(0,be.gn)([(0,xu.p)("Invert X axis",xu.U.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Su.prototype,"invertX",void 0),(0,be.gn)([(0,xu.p)("Invert Y axis",xu.U.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Su.prototype,"invertY",void 0),(0,be.gn)([(0,xu.p)("Use parallax occlusion",xu.U.Boolean)],Su.prototype,"useParallaxOcclusion",void 0),(0,be.gn)([(0,xu.p)("Object Space Mode",xu.U.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Su.prototype,"useObjectSpaceNormalMap",void 0),(0,l.H)("BABYLON.PerturbNormalBlock",Su);class Eu extends du.k{constructor(e){super(e,ru.u.Fragment,!0),this.registerInput("value",ou.E.Float,!0),this.registerInput("cutoff",ou.E.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;\r\n`,this}}(0,l.H)("BABYLON.DiscardBlock",Eu);class Cu extends du.k{constructor(e){super(e,ru.u.Fragment),this.registerOutput("output",ou.E.Float,ru.u.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===ru.u.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;\r\n",this}}(0,l.H)("BABYLON.FrontFacingBlock",Cu);class Au extends du.k{constructor(e){super(e,ru.u.Fragment),this.registerInput("input",ou.E.AutoDetect,!1),this.registerOutput("dx",ou.E.BasedOnInput),this.registerOutput("dy",ou.E.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});\r\n`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName});\r\n`),this}}(0,l.H)("BABYLON.DerivativeBlock",Au);class Pu extends du.k{constructor(e){super(e,ru.u.Fragment),this.registerOutput("xy",ou.E.Vector2,ru.u.Fragment),this.registerOutput("xyz",ou.E.Vector3,ru.u.Fragment),this.registerOutput("xyzw",ou.E.Vector4,ru.u.Fragment),this.registerOutput("x",ou.E.Float,ru.u.Fragment),this.registerOutput("y",ou.E.Float,ru.u.Fragment),this.registerOutput("z",ou.E.Float,ru.u.Fragment),this.registerOutput("w",ou.E.Float,ru.u.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};\r\n`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===ru.u.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}(0,l.H)("BABYLON.FragCoordBlock",Pu);class Ru extends du.k{constructor(e){super(e,ru.u.Fragment),this.registerOutput("xy",ou.E.Vector2,ru.u.Fragment),this.registerOutput("x",ou.E.Float,ru.u.Fragment),this.registerOutput("y",ou.E.Float,ru.u.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 n of this._outputs)n.hasEndpoints&&(i+=`${this._declareOutput(n,e)} = ${t}.${n.name};\r\n`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===ru.u.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}}(0,l.H)("BABYLON.ScreenSizeBlock",Ru);class Mu extends du.k{constructor(e){super(e,ru.u.Fragment),this.registerInput("vector",ou.E.AutoDetect),this.registerInput("worldViewProjection",ou.E.Matrix),this.registerOutput("output",ou.E.Vector2),this.registerOutput("x",ou.E.Float),this.registerOutput("y",ou.E.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Vector3|ou.E.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){if(!this.worldViewProjection.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.WorldViewProjection));t||(t=new fu.S("worldViewProjection"),t.setAsSystemValue(lu.$.WorldViewProjection)),t.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const n=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case ou.E.Vector3:e.compilationString+=`vec4 ${s} = ${n} * vec4(${t.associatedVariableName}, 1.0);\r\n`;break;case ou.E.Vector4:e.compilationString+=`vec4 ${s} = ${n} * ${t.associatedVariableName};\r\n`}return e.compilationString+=`${s}.xy /= ${s}.w;`,e.compilationString+=`${s}.xy = ${s}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${s}.xy;\r\n`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${s}.x;\r\n`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${s}.y;\r\n`),this}}(0,l.H)("BABYLON.ScreenSpaceBlock",Mu);class Iu extends du.k{constructor(e){super(e,ru.u.Fragment),this.registerInput("input",ou.E.Vector2),this.registerInput("strength",ou.E.Float),this.registerInput("center",ou.E.Vector2),this.registerInput("offset",ou.E.Vector2),this.registerOutput("output",ou.E.Vector2),this.registerOutput("x",ou.E.Float),this.registerOutput("y",ou.E.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 fu.S("center");e.value=new o.FM(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new fu.S("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new fu.S("offset");e.value=new o.FM(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),n=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),r=e._getFreeVariableName("result");return e.compilationString+=`\n vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\n float ${i} = ${this.strength.associatedVariableName} * length(${t});\n float ${n} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;\n float ${s} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;\n vec2 ${r} = vec2(${n} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\n `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${r};\r\n`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${r}.x;\r\n`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${r}.y;\r\n`),this}}(0,l.H)("BABYLON.TwirlBlock",Iu);class Du extends du.k{constructor(e){super(e,ru.u.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",ou.E.Float),this.registerInput("worldPosition",ou.E.Vector3),this.registerInput("worldNormal",ou.E.Vector3),this.registerInput("worldTangent",ou.E.AutoDetect,!0),this.registerOutput("output",ou.E.Vector4),this.registerOutput("xyz",ou.E.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Vector3|ou.E.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||console.error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const i=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(normal, tangent);\n mat3 TBN = mat3(tangent, biTangent, normal);\n ",n=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ",s=`\n vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) {\n ${i}\n ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""}\n ${this.automaticNormalizationNormal?"normal = normalize(normal);":""}\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(normal, worlddX);\n vec3 crossY = cross(normal, worlddY);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * normal) - inToNormal);\n ${n}\n return vec4(result, 0.);\n }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",s,"// heightToNormal"),e.compilationString+=this._declareOutput(t,e)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName});\r\n`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;\r\n`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\r\n`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\r\n`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\r\n`,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}}(0,be.gn)([(0,xu.p)("Generate in world space instead of tangent space",xu.U.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Du.prototype,"generateInWorldSpace",void 0),(0,be.gn)([(0,xu.p)("Force normalization for the worldNormal input",xu.U.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Du.prototype,"automaticNormalizationNormal",void 0),(0,be.gn)([(0,xu.p)("Force normalization for the worldTangent input",xu.U.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Du.prototype,"automaticNormalizationTangent",void 0),(0,l.H)("BABYLON.HeightToNormalBlock",Du);class Ou extends du.k{constructor(e){super(e,ru.u.Fragment,!0),this.registerInput("depth",ou.E.Float,!0),this.registerInput("worldPos",ou.E.Vector4,!0),this.registerInput("viewProjection",ou.E.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};\r\n`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`\n vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\n float v = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n gl_FragDepth = v;\n \n `:console.warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}(0,l.H)("BABYLON.FragDepthBlock",Ou);class wu extends du.k{constructor(e){super(e,ru.u.Fragment),this.registerInput("worldPosition",ou.E.Vector4,!1),this.registerInput("viewProjection",ou.E.Matrix,!1),this.registerInput("worldNormal",ou.E.AutoDetect,!0),this.registerOutput("depth",ou.E.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Vector3|ou.E.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};\r\n`,e.compilationString+="vec3 vPositionWSM;\r\n",e.compilationString+="float vDepthMetricSM = 0.0;\r\n",e.compilationString+="float zSM;\r\n",this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+="\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n gl_FragDepth = (clipPos.z / clipPos.w);\n #else\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n ",e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.);\r\n`,this}}(0,l.H)("BABYLON.ShadowMapBlock",wu);class Nu extends du.k{constructor(e){super(e,ru.u.VertexAndFragment,!1),this.registerInput("worldPosition",ou.E.Vector4,!1,ru.u.Vertex),this.registerInput("view",ou.E.Matrix,!1,ru.u.Vertex),this.registerInput("input",ou.E.AutoDetect,!1,ru.u.Fragment),this.registerInput("fogColor",ou.E.AutoDetect,!1,ru.u.Fragment),this.registerOutput("output",ou.E.Color3,ru.u.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Vector3|ou.E.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Vector3|ou.E.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){if(!this.view.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.View));t||(t=new fu.S("view"),t.setAsSystemValue(lu.$.View)),t.output.connectTo(this.view)}if(!this.fogColor.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.FogColor));t||(t=new fu.S("fogColor",void 0,ou.E.Color3),t.setAsSystemValue(lu.$.FogColor)),t.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const n=e.getScene();i.setValue("FOG",t.fogEnabled&&La.G.GetFogState(e,n))}bind(e,t,i){if(!i)return;const n=i.getScene();e.setFloat4(this._fogParameters,n.fogMode,n.fogStart,n.fogEnd,n.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===ru.u.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,n=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const s=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+="#ifdef FOG\r\n",e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters});\r\n`,e.compilationString+=this._declareOutput(s,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${n.associatedVariableName}.rgb;\r\n`,e.compilationString+=`#else\r\n${this._declareOutput(s,e)} = ${i.associatedVariableName}.rgb;\r\n`,e.compilationString+="#endif\r\n"}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;\r\n`}return this}}(0,l.H)("BABYLON.FogBlock",Nu);class Fu extends du.k{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ru.u.Fragment:ru.u.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ru.u.Fragment:ru.u.Vertex}constructor(e){super(e,ru.u.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",ou.E.Vector4,!1,ru.u.Vertex),this.registerInput("worldNormal",ou.E.Vector4,!1,ru.u.Fragment),this.registerInput("cameraPosition",ou.E.Vector3,!1,ru.u.Fragment),this.registerInput("glossiness",ou.E.Float,!0,ru.u.Fragment),this.registerInput("glossPower",ou.E.Float,!0,ru.u.Fragment),this.registerInput("diffuseColor",ou.E.Color3,!0,ru.u.Fragment),this.registerInput("specularColor",ou.E.Color3,!0,ru.u.Fragment),this.registerInput("view",ou.E.Matrix,!0),this.registerOutput("diffuseOutput",ou.E.Color3,ru.u.Fragment),this.registerOutput("specularOutput",ou.E.Color3,ru.u.Fragment),this.registerOutput("shadow",ou.E.Float,ru.u.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){if(!this.cameraPosition.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.CameraPosition));t||(t=new fu.S("cameraPosition"),t.setAsSystemValue(lu.$.CameraPosition)),t.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const n=e.getScene();if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};La.G.PrepareDefinesForLight(n,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else La.G.PrepareDefinesForLights(n,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,n){for(let s=0;s<t.maxSimultaneousLights&&i["LIGHT"+s];s++){const t=e.uniforms.indexOf("vLightData"+s)>=0;La.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],n,t)}}bind(e,t,i){if(!i)return;const n=i.getScene();this.light?La.G.BindLight(this.light,this._lightId,n,e,!0):La.G.BindLights(n,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?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 n="v_"+t.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=`${n} = ${t.associatedVariableName};\r\n`),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};\r\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\r\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==ru.u.Fragment)return void this._injectVertexCode(e);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 n=i.associatedVariableName;this.generateOnlyFragmentCode?(n=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${n};\r\n`,t),e.compilationString+=`${n} = ${i.associatedVariableName}.xyz;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):n="v_"+n+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:n}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:n}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${n});\r\n`),e.compilationString+="lightingInfo info;\r\n",e.compilationString+="float shadow = 1.;\r\n",e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};\r\n`,e.compilationString+="vec3 diffuseBase = vec3(0., 0., 0.);\r\n",e.compilationString+="vec3 specularBase = vec3(0., 0., 0.);\r\n",e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz;\r\n`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights"});const s=this.diffuseOutput,r=this.specularOutput;return e.compilationString+=this._declareOutput(s,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};\r\n`,r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};\r\n`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+" = shadow;\r\n"),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()}}(0,be.gn)([(0,xu.p)("Generate only fragment code",xu.U.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Fu._OnGenerateOnlyFragmentCodeChanged}})],Fu.prototype,"generateOnlyFragmentCode",void 0),(0,l.H)("BABYLON.LightBlock",Fu);class Lu extends du.k{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:A.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._samplerName}constructor(e){super(e,ru.u.VertexAndFragment),this.registerOutput("source",ou.E.Object,ru.u.VertexAndFragment,new uu("source",this,cu.Ab.Output,Lu,"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===ru.u.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});\r\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,e):e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Fl.O.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Ce.x.Parse(e.texture,t,i))}}(0,l.H)("BABYLON.ImageSourceBlock",Lu);class Bu extends du.k{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:A.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._imageSource?this._imageSource.samplerName:this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:A.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:A.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?ru.u.Fragment:ru.u.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",ou.E.AutoDetect,!1,ru.u.VertexAndFragment),this.registerInput("source",ou.E.Object,!0,ru.u.VertexAndFragment,new uu("source",this,cu.Ab.Input,Lu,"ImageSourceBlock")),this.registerInput("layer",ou.E.Float,!0),this.registerOutput("rgba",ou.E.Color4,ru.u.Neutral),this.registerOutput("rgb",ou.E.Color3,ru.u.Neutral),this.registerOutput("r",ou.E.Float,ru.u.Neutral),this.registerOutput("g",ou.E.Float,ru.u.Neutral),this.registerOutput("b",ou.E.Float,ru.u.Neutral),this.registerOutput("a",ou.E.Float,ru.u.Neutral),this.registerOutput("level",ou.E.Float,ru.u.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ou.E.Vector2|ou.E.Vector3|ou.E.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 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 ru.u.Fragment;if(!this.uv.isConnected)return ru.u.VertexAndFragment;if(this.uv.sourceBlock.isInput)return ru.u.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===ru.u.Fragment)return ru.u.Fragment;if(e.target===ru.u.Vertex)return ru.u.VertexAndFragment;if(e.target===ru.u.Neutral||e.target===ru.u.VertexAndFragment){const t=e.ownerBlock;if(t.target===ru.u.Fragment)return ru.u.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return ru.u.VertexAndFragment}set target(e){}autoConfigure(e){if(!this.uv.isConnected)if(e.mode===hu.a.PostProcess){const t=e.getBlockByPredicate((e=>"uv"===e.name));t&&t.connectTo(this)}else{const t=e.mode===hu.a.Particle?"particle_uv":"uv";let i=e.getInputBlockByPredicate((e=>e.isAttribute&&e.name===t));i||(i=new fu.S("uv"),i.setAsAttribute(t)),i.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix)return void(this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)));const n=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,n,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){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!==ru.u.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}\r\n`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0));\r\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\r\n`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\r\n`,e.compilationString+="#endif\r\n",this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}}_getUVW(e){var t,i,n;let s=e;return null!==(n=null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)&&void 0!==n&&n&&(s=`vec3(${e}, ${this.layer.isConnected?this.layer.associatedVariableName:"0"})`),s}_generateTextureLookup(e){const t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName}\r\n`,e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${t}, ${this._getUVW(this._transformedUVName)});\r\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\r\n`,e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)});\r\n`,e.compilationString+="#endif\r\n"}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ru.u.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==ru.u.Fragment?this._generateTextureLookup(e):e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this.samplerName}, ${this._getUVW(i.associatedVariableName)});\r\n`}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i,n=!1){if(n){if(e.target===ru.u.Fragment)return;return e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===ru.u.Fragment)return e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,void this._generateConversionCode(e,t,i);let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s};\r\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){var t,i,n,s;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===ru.u.Vertex||this._fragmentOnly||e.target===ru.u.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===ru.u.Fragment||this._isMixed&&e.target===ru.u.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),(null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==ru.u.Fragment)return void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;this._isMixed&&!this._imageSource&&((null===(s=null===(n=this._texture)||void 0===n?void 0:n._texture)||void 0===s?void 0:s.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\r\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\r\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\r\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\r\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,e):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||"VideoTexture"===this.texture.getClassName()||(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&&!Fl.O.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Ce.x.Parse(e.texture,t,i))}}(0,l.H)("BABYLON.TextureBlock",Bu);class Uu extends du.k{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:A.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ru.u.Fragment:ru.u.VertexAndFragment)}constructor(e){super(e,ru.u.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e){if(!this.position.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name));t||(t=new fu.S("position"),t.setAsAttribute()),t.output.connectTo(this.position)}if(!this.world.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.World));t||(t=new fu.S("world"),t.setAsSystemValue(lu.$.World)),t.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.View));t||(t=new fu.S("view"),t.setAsSystemValue(lu.$.View)),t.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const n=this._getTexture();n&&n.getTextureMatrix&&(i.setValue(this._define3DName,n.isCube,!0),i.setValue(this._defineLocalCubicName,!!n.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===n.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===n.coordinatesMode,!0),i.setValue(this._defineCubicName,3===n.coordinatesMode||6===n.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===n.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===n.coordinatesMode,!0),i.setValue(this._definePlanarName,2===n.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===n.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===n.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===n.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===n.coordinatesMode,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){const n=this._getTexture();if(i&&n&&(e.setMatrix(this._reflectionMatrixName,n.getReflectionTextureMatrix()),n.isCube?e.setTexture(this._cubeSamplerName,n):e.setTexture(this._2DSamplerName,n),n.boundingBoxSize)){const t=n;e.setVector3(this._reflectionPositionName,t.boundingBoxPosition),e.setVector3(this._reflectionSizeName,t.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===ru.u.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};\r\n`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName}\r\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\r\n`,t+="#endif\r\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\r\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\r\n`,t+="#endif\r\n"),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}\r\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\r\n`,e._samplerDeclaration+="#else\r\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\r\n`,e._samplerDeclaration+="#endif\r\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunction("ReciprocalPI","#define RECIPROCAL_PI2 0.15915494",""),e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,n=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const s=this._reflectionMatrixName,r=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,a=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=`\n #ifdef ${this._defineMirroredEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${r});\n #endif\n\n #ifdef ${this._defineEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${r});\n #endif\n\n #ifdef ${this._defineEquirectangularName}\n vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${a}.xyz, ${s});\n #endif\n\n #ifdef ${this._defineSphericalName}\n vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${s});\n #endif\n\n #ifdef ${this._definePlanarName}\n vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${a}.xyz, ${s});\n #endif\n\n #ifdef ${this._defineCubicName}\n #ifdef ${this._defineLocalCubicName}\n vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${a}.xyz, ${s}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\n #else\n vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${a}.xyz, ${s});\n #endif\n #endif\n\n #ifdef ${this._defineProjectionName}\n vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${s});\n #endif\n\n #ifdef ${this._defineSkyboxName}\n vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${s});\n #endif\n\n #ifdef ${this._defineExplicitName}\n vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);\n #endif\r\n`;return n||(h+=`#ifdef ${this._defineOppositeZ}\n ${this._reflectionVectorName}.z *= -1.0;\n #endif\r\n`),i||(h+=`\n #ifdef ${this._define3DName}\n vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};\n #else\n vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;\n #ifdef ${this._defineProjectionName}\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\n #endif\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\n #endif\r\n`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i=`${"vec"+(0===t.length?"4":t.length-1)} ${this._reflectionColorName};\n #ifdef ${this._define3DName}\r\n`;return i+=e?`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t};\r\n`:`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t};\r\n`,i+="\n #else\r\n",i+=e?`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t};\r\n`:`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t};\r\n`,i+="#endif\r\n",i}writeOutputs(e,t){let i="";if(e.target===ru.u.Fragment)for(const n of this._outputs)n.hasEndpoints&&(i+=`${this._declareOutput(n,e)} = ${t}.${n.name};\r\n`);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"});\r\n`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\r\n`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,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&&!Fl.O.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=Fa.B.Parse(e.texture,t,i):this.texture=Ce.x.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}(0,be.gn)([(0,xu.p)("Generate only fragment code",xu.U.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Uu._OnGenerateOnlyFragmentCodeChanged}})],Uu.prototype,"generateOnlyFragmentCode",void 0),(0,l.H)("BABYLON.ReflectionTextureBaseBlock",Uu);class Vu extends Uu{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.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?ru.u.Fragment:ru.u.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ru.u.Fragment:ru.u.Vertex}constructor(e){super(e),this.registerInput("position",ou.E.AutoDetect,!1,ru.u.Vertex),this.registerInput("worldPosition",ou.E.Vector4,!1,ru.u.Vertex),this.registerInput("worldNormal",ou.E.Vector4,!1,ru.u.Fragment),this.registerInput("world",ou.E.Matrix,!1,ru.u.Vertex),this.registerInput("cameraPosition",ou.E.Vector3,!1,ru.u.Fragment),this.registerInput("view",ou.E.Matrix,!1,ru.u.Fragment),this.registerOutput("rgb",ou.E.Color3,ru.u.Fragment),this.registerOutput("rgba",ou.E.Color4,ru.u.Fragment),this.registerOutput("r",ou.E.Float,ru.u.Fragment),this.registerOutput("g",ou.E.Float,ru.u.Fragment),this.registerOutput("b",ou.E.Float,ru.u.Fragment),this.registerOutput("a",ou.E.Float,ru.u.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Vector3|ou.E.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){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.CameraPosition));t||(t=new fu.S("cameraPosition"),t.setAsSystemValue(lu.$.CameraPosition)),t.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==ru.u.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});\r\n`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}(0,l.H)("BABYLON.ReflectionTextureBlock",Vu);var ku=i(6653);class Gu extends du.k{constructor(e){super(e,ru.u.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",ou.E.AutoDetect,!1,ru.u.VertexAndFragment),this.registerOutput("depth",ou.E.Float,ru.u.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ou.E.Vector2|ou.E.Vector3|ou.E.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?ru.u.VertexAndFragment:ru.u.Fragment:ru.u.VertexAndFragment}_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===ou.E.Vector3?"3":t.type===ou.E.Vector4?"4":"2"))),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\r\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ru.u.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\r\n`}else this.uv.ownerBlock.target!==ru.u.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\r\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\r\n`}_writeOutput(e,t,i,n=!1){if(n){if(e.target===ru.u.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}else this.uv.ownerBlock.target,ru.u.Fragment,e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}_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!==ru.u.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(this._outputs.some((e=>e.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}}(0,be.gn)([(0,xu.p)("Use non linear depth",xu.U.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let n=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,n=!0),e.disableDepthRenderer(),n}}})],Gu.prototype,"useNonLinearDepth",void 0),(0,be.gn)([(0,xu.p)("Store Camera space Z",xu.U.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let n=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,n=!0),e.disableDepthRenderer(),n}}})],Gu.prototype,"storeCameraSpaceZ",void 0),(0,be.gn)([(0,xu.p)("Force 32 bits float",xu.U.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>e.disableDepthRenderer()}})],Gu.prototype,"force32itsFloat",void 0),(0,l.H)("BABYLON.SceneDepthBlock",Gu);class zu extends du.k{constructor(e){super(e,ru.u.VertexAndFragment,!0),this.registerInput("worldPosition",ou.E.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 ru.u.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var n,s,r,o,a,l;const h=e.getScene(),c=!!(null!==(n=t.clipPlane)&&void 0!==n?n:h.clipPlane),u=!!(null!==(s=t.clipPlane2)&&void 0!==s?s:h.clipPlane2),d=!!(null!==(r=t.clipPlane3)&&void 0!==r?r:h.clipPlane3),p=!!(null!==(o=t.clipPlane4)&&void 0!==o?o:h.clipPlane4),f=!!(null!==(a=t.clipPlane5)&&void 0!==a?a:h.clipPlane5),_=!!(null!==(l=t.clipPlane6)&&void 0!==l?l:h.clipPlane6);i.setValue("CLIPPLANE",c,!0),i.setValue("CLIPPLANE2",u,!0),i.setValue("CLIPPLANE3",d,!0),i.setValue("CLIPPLANE4",p,!0),i.setValue("CLIPPLANE5",f,!0),i.setValue("CLIPPLANE6",_,!0)}bind(e,t,i){if(!i)return;const n=i.getScene();(0,Ga.an)(e,t,n)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==ru.u.Fragment){const i=this.worldPosition;return 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"),void e._emitUniformFromString("vClipPlane6","vec4")}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}(0,l.H)("BABYLON.ClipPlanesBlock",zu);var Wu=i(3426),Hu=i(3841);class Xu extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("left",ou.E.AutoDetect),this.registerInput("right",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}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};\r\n`,this}}(0,l.H)("BABYLON.AddBlock",Xu);class ju extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("input",ou.E.AutoDetect),this.registerInput("factor",ou.E.Float),this.registerOutput("output",ou.E.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};\r\n`,this}}(0,l.H)("BABYLON.ScaleBlock",ju);class Yu extends du.k{constructor(e){super(e,ru.u.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",ou.E.AutoDetect),this.registerOutput("output",ou.E.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)});\r\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\r\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\r\n`,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}}(0,be.gn)([(0,xu.p)("Minimum",xu.U.Float)],Yu.prototype,"minimum",void 0),(0,be.gn)([(0,xu.p)("Maximum",xu.U.Float)],Yu.prototype,"maximum",void 0),(0,l.H)("BABYLON.ClampBlock",Yu);class qu extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("left",ou.E.AutoDetect),this.registerInput("right",ou.E.AutoDetect),this.registerOutput("output",ou.E.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Float),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Matrix),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Vector2),this._inputs[1].excludedConnectionPointTypes.push(ou.E.Float),this._inputs[1].excludedConnectionPointTypes.push(ou.E.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ou.E.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);\r\n`,this}}(0,l.H)("BABYLON.CrossBlock",qu);class Ku extends du.k{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((n=>{const s=new RegExp("\\{TYPE_"+n.name+"\\}","gm"),r=e._getGLType(n.type);t=t.replace(s,r),i=i.replace(s,r)})),this._outputs.forEach((n=>{const s=new RegExp("\\{TYPE_"+n.name+"\\}","gm"),r=e._getGLType(n.type);t=t.replace(s,r),i=i.replace(s,r)})),e._emitFunction(i,t,""),this._outputs.forEach((t=>{e.compilationString+=this._declareOutput(t,e)+";\r\n"})),e.compilationString+=i+"(";let n=!1;return this._inputs.forEach(((t,i)=>{i>0&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName,n=!0})),this._outputs.forEach(((t,i)=>{(i>0||n)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName})),e.compilationString+=");\r\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};\r\n`,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,n;this._options=e,this._code=e.code.join("\r\n")+"\r\n",this.name=this.name||e.name,this.target=ru.u[e.target],null===(t=e.inParameters)||void 0===t||t.forEach(((e,t)=>{const i=ou.E[e.type];this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),null===(i=e.outParameters)||void 0===i||i.forEach(((e,t)=>{this.registerOutput(e.name,ou.E[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])})),null===(n=e.inLinkedConnectionTypes)||void 0===n||n.forEach((e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])}))}_findInputByName(e){if(!e)return null;for(let t=0;t<this._inputs.length;t++)if(this._inputs[t].name===e)return[this._inputs[t],t];return null}}(0,l.H)("BABYLON.CustomBlock",Ku);class $u extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("left",ou.E.AutoDetect),this.registerInput("right",ou.E.AutoDetect),this.registerOutput("output",ou.E.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Float),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ou.E.Float),this._inputs[1].excludedConnectionPointTypes.push(ou.E.Matrix)}getClassName(){return"DotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = dot(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\r\n`,this}}(0,l.H)("BABYLON.DotBlock",$u);var Qu=i(7238),Zu=i(2864);class Ju extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("input",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ou.E.Float),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Matrix)}getClassName(){return"NormalizeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${i.associatedVariableName});\r\n`,this}}(0,l.H)("BABYLON.NormalizeBlock",Ju);var ed=i(3069);class td extends du.k{constructor(e){super(e,ru.u.Neutral),this.rSwizzle="r",this.gSwizzle="g",this.bSwizzle="b",this.aSwizzle="a",this.registerInput("rgb ",ou.E.Color3,!0),this.registerInput("r",ou.E.Float,!0),this.registerInput("g",ou.E.Float,!0),this.registerInput("b",ou.E.Float,!0),this.registerInput("a",ou.E.Float,!0),this.registerOutput("rgba",ou.E.Color4),this.registerOutput("rgb",ou.E.Color3)}getClassName(){return"ColorMergerBlock"}get rgbIn(){return this._inputs[0]}get r(){return this._inputs[1]}get g(){return this._inputs[2]}get b(){return this._inputs[3]}get a(){return this._inputs[4]}get rgba(){return this._outputs[0]}get rgbOut(){return this._outputs[1]}get rgb(){return this.rgbOut}_inputRename(e){return"rgb "===e?"rgbIn":e}_buildSwizzle(e){return"."+(this.rSwizzle+this.gSwizzle+this.bSwizzle+this.aSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.r,i=this.g,n=this.b,s=this.a,r=this.rgbIn,o=this._outputs[0],a=this._outputs[1];return r.isConnected?(o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec4(${r.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\r\n`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${r.associatedVariableName}${this._buildSwizzle(3)};\r\n`)):(o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\r\n`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(3)};\r\n`)),this}serialize(){const e=super.serialize();return e.rSwizzle=this.rSwizzle,e.gSwizzle=this.gSwizzle,e.bSwizzle=this.bSwizzle,e.aSwizzle=this.aSwizzle,e}_deserialize(e,t,i){var n,s,r,o;super._deserialize(e,t,i),this.rSwizzle=null!==(n=e.rSwizzle)&&void 0!==n?n:"r",this.gSwizzle=null!==(s=e.gSwizzle)&&void 0!==s?s:"g",this.bSwizzle=null!==(r=e.bSwizzle)&&void 0!==r?r:"b",this.aSwizzle=null!==(o=e.aSwizzle)&&void 0!==o?o:"a"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.rSwizzle = "${this.rSwizzle}";\r\n`,e+=`${this._codeVariableName}.gSwizzle = "${this.gSwizzle}";\r\n`,e+=`${this._codeVariableName}.bSwizzle = "${this.bSwizzle}";\r\n`,e+=`${this._codeVariableName}.aSwizzle = "${this.aSwizzle}";\r\n`,e}}(0,l.H)("BABYLON.ColorMergerBlock",td);var id,nd=i(8982),sd=i(8022);class rd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("xyzw",ou.E.Vector4,!0),this.registerInput("xyz ",ou.E.Vector3,!0),this.registerInput("xy ",ou.E.Vector2,!0),this.registerOutput("xyz",ou.E.Vector3),this.registerOutput("xy",ou.E.Vector2),this.registerOutput("zw",ou.E.Vector2),this.registerOutput("x",ou.E.Float),this.registerOutput("y",ou.E.Float),this.registerOutput("z",ou.E.Float),this.registerOutput("w",ou.E.Float),this.inputsAreExclusive=!0}getClassName(){return"VectorSplitterBlock"}get xyzw(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get xyzOut(){return this._outputs[0]}get xyOut(){return this._outputs[1]}get zw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get w(){return this._outputs[6]}_inputRename(e){switch(e){case"xy ":return"xyIn";case"xyz ":return"xyzIn";default:return e}}_outputRename(e){switch(e){case"xy":return"xyOut";case"xyz":return"xyzOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xyzw.isConnected?this.xyzw:this.xyzIn.isConnected?this.xyzIn:this.xyIn,i=this._outputs[0],n=this._outputs[1],s=this._outputs[2],r=this._outputs[3],o=this._outputs[4],a=this._outputs[5],l=this._outputs[6];return i.hasEndpoints&&(t===this.xyIn?e.compilationString+=this._declareOutput(i,e)+` = vec3(${t.associatedVariableName}, 0.0);\r\n`:e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.xyz;\r\n`),s.hasEndpoints&&this.xyzw.isConnected&&(e.compilationString+=this._declareOutput(s,e)+` = ${this.xyzw.associatedVariableName}.zw;\r\n`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.xy;\r\n`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.x;\r\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.y;\r\n`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.z;\r\n`),l.hasEndpoints&&(e.compilationString+=this._declareOutput(l,e)+` = ${t.associatedVariableName}.w;\r\n`),this}}(0,l.H)("BABYLON.VectorSplitterBlock",rd);class od extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("left",ou.E.AutoDetect),this.registerInput("right",ou.E.AutoDetect),this.registerInput("gradient",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(1,2,!0),this._inputs[2].acceptedConnectionPointTypes.push(ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.LerpBlock",od);class ad extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("left",ou.E.AutoDetect),this.registerInput("right",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}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};\r\n`,this}}(0,l.H)("BABYLON.DivideBlock",ad);class ld extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("left",ou.E.AutoDetect),this.registerInput("right",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}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};\r\n`,this}}(0,l.H)("BABYLON.SubtractBlock",ld);class hd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("value",ou.E.Float),this.registerInput("edge",ou.E.Float),this.registerOutput("output",ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.StepBlock",hd);class cd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("input",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[0].excludedConnectionPointTypes.push(ou.E.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};\r\n`,this}}(0,l.H)("BABYLON.OneMinusBlock",cd),(0,l.H)("BABYLON.OppositeBlock",cd);class ud extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("worldPosition",ou.E.Vector4),this.registerInput("cameraPosition",ou.E.Vector3),this.registerOutput("output",ou.E.Vector3)}getClassName(){return"ViewDirectionBlock"}get worldPosition(){return this._inputs[0]}get cameraPosition(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(e){if(!this.cameraPosition.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.CameraPosition));t||(t=new fu.S("cameraPosition"),t.setAsSystemValue(lu.$.CameraPosition)),t.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);\r\n`,this}}(0,l.H)("BABYLON.ViewDirectionBlock",ud),i(8491);class dd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("worldNormal",ou.E.Vector4),this.registerInput("viewDirection",ou.E.Vector3),this.registerInput("bias",ou.E.Float),this.registerInput("power",ou.E.Float),this.registerOutput("fresnel",ou.E.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 ud("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const e=new fu.S("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){const e=new fu.S("power");e.value=1,e.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});\r\n`,this}}(0,l.H)("BABYLON.FresnelBlock",dd);class pd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("left",ou.E.AutoDetect),this.registerInput("right",ou.E.AutoDetect),this.registerOutput("output",ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.MaxBlock",pd);class fd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("left",ou.E.AutoDetect),this.registerInput("right",ou.E.AutoDetect),this.registerOutput("output",ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.MinBlock",fd);class _d extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("left",ou.E.AutoDetect),this.registerInput("right",ou.E.AutoDetect),this.registerOutput("output",ou.E.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Float),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ou.E.Float),this._inputs[1].excludedConnectionPointTypes.push(ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.DistanceBlock",_d);class md extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("value",ou.E.AutoDetect),this.registerOutput("output",ou.E.Float),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Float),this._inputs[0].excludedConnectionPointTypes.push(ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.LengthBlock",md);class gd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("value",ou.E.AutoDetect),this.registerOutput("output",ou.E.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};\r\n`,this}}(0,l.H)("BABYLON.NegateBlock",gd);class vd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("value",ou.E.AutoDetect),this.registerInput("power",ou.E.AutoDetect),this.registerOutput("output",ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.PowBlock",vd);class yd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("seed",ou.E.AutoDetect),this.registerOutput("output",ou.E.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ou.E.Vector2|ou.E.Vector3|ou.E.Vector4|ou.E.Color3|ou.E.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);\r\n`,this}}(0,l.H)("BABYLON.RandomNumberBlock",yd);class xd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("x",ou.E.Float),this.registerInput("y",ou.E.Float),this.registerOutput("output",ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.ArcTan2Block",xd);class bd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("value",ou.E.AutoDetect),this.registerInput("edge0",ou.E.Float),this.registerInput("edge1",ou.E.Float),this.registerOutput("output",ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.SmoothStepBlock",bd);class Td extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("input",ou.E.AutoDetect),this.registerOutput("output",ou.E.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===ou.E.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName});\r\n`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName};\r\n`,this}}(0,l.H)("BABYLON.ReciprocalBlock",Td);class Sd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("value",ou.E.AutoDetect),this.registerInput("reference",ou.E.AutoDetect),this.registerInput("distance",ou.E.Float),this.registerInput("replacement",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Float),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ou.E.Float),this._inputs[1].excludedConnectionPointTypes.push(ou.E.Matrix),this._inputs[3].excludedConnectionPointTypes.push(ou.E.Float),this._inputs[3].excludedConnectionPointTypes.push(ou.E.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)+";\r\n",e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\r\n`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};\r\n`,e.compilationString+="} else {\r\n",e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};\r\n`,e.compilationString+="}\r\n",this}}(0,l.H)("BABYLON.ReplaceColorBlock",Sd);class Ed extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("value",ou.E.AutoDetect),this.registerInput("steps",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ou.E.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.PosterizeBlock",Ed),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(id||(id={}));class Cd extends du.k{constructor(e){super(e,ru.u.Neutral),this.kind=id.SawTooth,this.registerInput("input",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ou.E.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 id.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\r\n`;break;case id.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\r\n`;break;case id.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\r\n`}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}}(0,l.H)("BABYLON.WaveBlock",Cd);class Ad{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 Pd extends du.k{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,ru.u.Neutral),this.colorSteps=[new Ad(0,a.Wo.Black()),new Ad(1,a.Wo.White())],this.onValueChangedObservable=new r.y$,this.registerInput("gradient",ou.E.AutoDetect),this.registerOutput("output",ou.E.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ou.E.Float|ou.E.Vector2|ou.E.Vector3|ou.E.Vector4|ou.E.Color3|ou.E.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)return void(e.compilationString+=this._declareOutput(t,e)+" = vec3(0., 0., 0.);\r\n");const i=e._getFreeVariableName("gradientTempColor"),n=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)};\r\n`,e.compilationString+=`float ${n};\r\n`;let s=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==ou.E.Float&&(s+=".x");for(let t=1;t<this.colorSteps.length;t++){const r=this.colorSteps[t],o=this.colorSteps[t-1];e.compilationString+=`${n} = clamp((${s} - ${e._emitFloat(o.step)}) / (${e._emitFloat(r.step)} - ${e._emitFloat(o.step)}), 0.0, 1.0) * step(${e._emitFloat(t)}, ${e._emitFloat(this.colorSteps.length-1)});\r\n`,e.compilationString+=`${i} = mix(${i}, ${this._writeColorConstant(t)}, ${n});\r\n`}return e.compilationString+=this._declareOutput(t,e)+` = ${i};\r\n`,this}serialize(){const e=super.serialize();e.colorSteps=[];for(const t of this.colorSteps)e.colorSteps.push({step:t.step,color:{r:t.color.r,g:t.color.g,b:t.color.b}});return e}_deserialize(e,t,i){super._deserialize(e,t,i),this.colorSteps.length=0;for(const t of e.colorSteps)this.colorSteps.push(new Ad(t.step,new a.Wo(t.color.r,t.color.g,t.color.b)))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();e+=`${this._codeVariableName}.colorSteps = [];\r\n`;for(const t of this.colorSteps)e+=`${this._codeVariableName}.colorSteps.push(new BABYLON.GradientBlockColorStep(${t.step}, new BABYLON.Color3(${t.color.r}, ${t.color.g}, ${t.color.b})));\r\n`;return e}}(0,l.H)("BABYLON.GradientBlock",Pd);class Rd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("left",ou.E.AutoDetect),this.registerInput("right",ou.E.AutoDetect),this.registerInput("gradient",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(1,2,!0),this._inputs[2].acceptedConnectionPointTypes.push(ou.E.Float)}getClassName(){return"NLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName}));\r\n`,this}}(0,l.H)("BABYLON.NLerpBlock",Rd);class Md extends du.k{constructor(e){super(e,ru.u.Neutral),this.manhattanDistance=!1,this.registerInput("seed",ou.E.Vector3),this.registerInput("jitter",ou.E.Float),this.registerOutput("output",ou.E.Vector2),this.registerOutput("x",ou.E.Float),this.registerOutput("y",ou.E.Float)}getClassName(){return"WorleyNoise3DBlock"}get seed(){return this._inputs[0]}get jitter(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;if(!this.output.hasEndpoints&&!this.x.hasEndpoints&&!this.y.hasEndpoints)return;let t="vec3 permute(vec3 x){\r\n";t+=" return mod((34.0 * x + 1.0) * x, 289.0);\r\n",t+="}\r\n\r\n",t+="vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){\r\n",t+=" return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z);\r\n",t+="}\r\n\r\n",t+="vec2 worley(vec3 P, float jitter, bool manhattanDistance){\r\n",t+=" float K = 0.142857142857; // 1/7\r\n",t+=" float Ko = 0.428571428571; // 1/2-K/2\r\n",t+=" float K2 = 0.020408163265306; // 1/(7*7)\r\n",t+=" float Kz = 0.166666666667; // 1/6\r\n",t+=" float Kzo = 0.416666666667; // 1/2-1/6*2\r\n",t+="\r\n",t+=" vec3 Pi = mod(floor(P), 289.0);\r\n",t+=" vec3 Pf = fract(P) - 0.5;\r\n",t+="\r\n",t+=" vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\r\n",t+=" vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\r\n",t+=" vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\r\n",t+="\r\n",t+=" vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\r\n",t+=" vec3 p1 = permute(p + Pi.y - 1.0);\r\n",t+=" vec3 p2 = permute(p + Pi.y);\r\n",t+=" vec3 p3 = permute(p + Pi.y + 1.0);\r\n",t+="\r\n",t+=" vec3 p11 = permute(p1 + Pi.z - 1.0);\r\n",t+=" vec3 p12 = permute(p1 + Pi.z);\r\n",t+=" vec3 p13 = permute(p1 + Pi.z + 1.0);\r\n",t+="\r\n",t+=" vec3 p21 = permute(p2 + Pi.z - 1.0);\r\n",t+=" vec3 p22 = permute(p2 + Pi.z);\r\n",t+=" vec3 p23 = permute(p2 + Pi.z + 1.0);\r\n",t+="\r\n",t+=" vec3 p31 = permute(p3 + Pi.z - 1.0);\r\n",t+=" vec3 p32 = permute(p3 + Pi.z);\r\n",t+=" vec3 p33 = permute(p3 + Pi.z + 1.0);\r\n",t+="\r\n",t+=" vec3 ox11 = fract(p11*K) - Ko;\r\n",t+=" vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\r\n",t+=" vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\r\n",t+="\r\n",t+=" vec3 ox12 = fract(p12*K) - Ko;\r\n",t+=" vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\r\n",t+=" vec3 oz12 = floor(p12*K2)*Kz - Kzo;\r\n",t+="\r\n",t+=" vec3 ox13 = fract(p13*K) - Ko;\r\n",t+=" vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\r\n",t+=" vec3 oz13 = floor(p13*K2)*Kz - Kzo;\r\n",t+="\r\n",t+=" vec3 ox21 = fract(p21*K) - Ko;\r\n",t+=" vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\r\n",t+=" vec3 oz21 = floor(p21*K2)*Kz - Kzo;\r\n",t+="\r\n",t+=" vec3 ox22 = fract(p22*K) - Ko;\r\n",t+=" vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\r\n",t+=" vec3 oz22 = floor(p22*K2)*Kz - Kzo;\r\n",t+="\r\n",t+=" vec3 ox23 = fract(p23*K) - Ko;\r\n",t+=" vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\r\n",t+=" vec3 oz23 = floor(p23*K2)*Kz - Kzo;\r\n",t+="\r\n",t+=" vec3 ox31 = fract(p31*K) - Ko;\r\n",t+=" vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\r\n",t+=" vec3 oz31 = floor(p31*K2)*Kz - Kzo;\r\n",t+="\r\n",t+=" vec3 ox32 = fract(p32*K) - Ko;\r\n",t+=" vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\r\n",t+=" vec3 oz32 = floor(p32*K2)*Kz - Kzo;\r\n",t+="\r\n",t+=" vec3 ox33 = fract(p33*K) - Ko;\r\n",t+=" vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\r\n",t+=" vec3 oz33 = floor(p33*K2)*Kz - Kzo;\r\n",t+="\r\n",t+=" vec3 dx11 = Pfx + jitter*ox11;\r\n",t+=" vec3 dy11 = Pfy.x + jitter*oy11;\r\n",t+=" vec3 dz11 = Pfz.x + jitter*oz11;\r\n",t+="\r\n",t+=" vec3 dx12 = Pfx + jitter*ox12;\r\n",t+=" vec3 dy12 = Pfy.x + jitter*oy12;\r\n",t+=" vec3 dz12 = Pfz.y + jitter*oz12;\r\n",t+="\r\n",t+=" vec3 dx13 = Pfx + jitter*ox13;\r\n",t+=" vec3 dy13 = Pfy.x + jitter*oy13;\r\n",t+=" vec3 dz13 = Pfz.z + jitter*oz13;\r\n",t+="\r\n",t+=" vec3 dx21 = Pfx + jitter*ox21;\r\n",t+=" vec3 dy21 = Pfy.y + jitter*oy21;\r\n",t+=" vec3 dz21 = Pfz.x + jitter*oz21;\r\n",t+="\r\n",t+=" vec3 dx22 = Pfx + jitter*ox22;\r\n",t+=" vec3 dy22 = Pfy.y + jitter*oy22;\r\n",t+=" vec3 dz22 = Pfz.y + jitter*oz22;\r\n",t+="\r\n",t+=" vec3 dx23 = Pfx + jitter*ox23;\r\n",t+=" vec3 dy23 = Pfy.y + jitter*oy23;\r\n",t+=" vec3 dz23 = Pfz.z + jitter*oz23;\r\n",t+="\r\n",t+=" vec3 dx31 = Pfx + jitter*ox31;\r\n",t+=" vec3 dy31 = Pfy.z + jitter*oy31;\r\n",t+=" vec3 dz31 = Pfz.x + jitter*oz31;\r\n",t+="\r\n",t+=" vec3 dx32 = Pfx + jitter*ox32;\r\n",t+=" vec3 dy32 = Pfy.z + jitter*oy32;\r\n",t+=" vec3 dz32 = Pfz.y + jitter*oz32;\r\n",t+="\r\n",t+=" vec3 dx33 = Pfx + jitter*ox33;\r\n",t+=" vec3 dy33 = Pfy.z + jitter*oy33;\r\n",t+=" vec3 dz33 = Pfz.z + jitter*oz33;\r\n",t+="\r\n",t+=" vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\r\n",t+=" vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\r\n",t+=" vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\r\n",t+=" vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\r\n",t+=" vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\r\n",t+=" vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\r\n",t+=" vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\r\n",t+=" vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\r\n",t+=" vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\r\n",t+="\r\n",t+=" vec3 d1a = min(d11, d12);\r\n",t+=" d12 = max(d11, d12);\r\n",t+=" d11 = min(d1a, d13); // Smallest now not in d12 or d13\r\n",t+=" d13 = max(d1a, d13);\r\n",t+=" d12 = min(d12, d13); // 2nd smallest now not in d13\r\n",t+=" vec3 d2a = min(d21, d22);\r\n",t+=" d22 = max(d21, d22);\r\n",t+=" d21 = min(d2a, d23); // Smallest now not in d22 or d23\r\n",t+=" d23 = max(d2a, d23);\r\n",t+=" d22 = min(d22, d23); // 2nd smallest now not in d23\r\n",t+=" vec3 d3a = min(d31, d32);\r\n",t+=" d32 = max(d31, d32);\r\n",t+=" d31 = min(d3a, d33); // Smallest now not in d32 or d33\r\n",t+=" d33 = max(d3a, d33);\r\n",t+=" d32 = min(d32, d33); // 2nd smallest now not in d33\r\n",t+=" vec3 da = min(d11, d21);\r\n",t+=" d21 = max(d11, d21);\r\n",t+=" d11 = min(da, d31); // Smallest now in d11\r\n",t+=" d31 = max(da, d31); // 2nd smallest now not in d31\r\n",t+=" d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\r\n",t+=" d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\r\n",t+=" d12 = min(d12, d21); // 2nd smallest now not in d21\r\n",t+=" d12 = min(d12, d22); // nor in d22\r\n",t+=" d12 = min(d12, d31); // nor in d31\r\n",t+=" d12 = min(d12, d32); // nor in d32\r\n",t+=" d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\r\n",t+=" d11.y = min(d11.y,d12.z); // Only two more to go\r\n",t+=" d11.y = min(d11.y,d11.z); // Done! (Phew!)\r\n",t+=" return sqrt(d11.xy); // F1, F2\r\n",t+="}\r\n\r\n",e._emitFunction("worley3D","vec3 permute(vec3 x){\r\n return mod((34.0 * x + 1.0) * x, 289.0);\r\n}\r\n\r\nvec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){\r\n return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z);\r\n}\r\n\r\nvec2 worley(vec3 P, float jitter, bool manhattanDistance){\r\n float K = 0.142857142857; // 1/7\r\n float Ko = 0.428571428571; // 1/2-K/2\r\n float K2 = 0.020408163265306; // 1/(7*7)\r\n float Kz = 0.166666666667; // 1/6\r\n float Kzo = 0.416666666667; // 1/2-1/6*2\r\n\r\n vec3 Pi = mod(floor(P), 289.0);\r\n vec3 Pf = fract(P) - 0.5;\r\n\r\n vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\r\n vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\r\n vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\r\n\r\n vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\r\n vec3 p1 = permute(p + Pi.y - 1.0);\r\n vec3 p2 = permute(p + Pi.y);\r\n vec3 p3 = permute(p + Pi.y + 1.0);\r\n\r\n vec3 p11 = permute(p1 + Pi.z - 1.0);\r\n vec3 p12 = permute(p1 + Pi.z);\r\n vec3 p13 = permute(p1 + Pi.z + 1.0);\r\n\r\n vec3 p21 = permute(p2 + Pi.z - 1.0);\r\n vec3 p22 = permute(p2 + Pi.z);\r\n vec3 p23 = permute(p2 + Pi.z + 1.0);\r\n\r\n vec3 p31 = permute(p3 + Pi.z - 1.0);\r\n vec3 p32 = permute(p3 + Pi.z);\r\n vec3 p33 = permute(p3 + Pi.z + 1.0);\r\n\r\n vec3 ox11 = fract(p11*K) - Ko;\r\n vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\r\n vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\r\n\r\n vec3 ox12 = fract(p12*K) - Ko;\r\n vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\r\n vec3 oz12 = floor(p12*K2)*Kz - Kzo;\r\n\r\n vec3 ox13 = fract(p13*K) - Ko;\r\n vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\r\n vec3 oz13 = floor(p13*K2)*Kz - Kzo;\r\n\r\n vec3 ox21 = fract(p21*K) - Ko;\r\n vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\r\n vec3 oz21 = floor(p21*K2)*Kz - Kzo;\r\n\r\n vec3 ox22 = fract(p22*K) - Ko;\r\n vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\r\n vec3 oz22 = floor(p22*K2)*Kz - Kzo;\r\n\r\n vec3 ox23 = fract(p23*K) - Ko;\r\n vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\r\n vec3 oz23 = floor(p23*K2)*Kz - Kzo;\r\n\r\n vec3 ox31 = fract(p31*K) - Ko;\r\n vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\r\n vec3 oz31 = floor(p31*K2)*Kz - Kzo;\r\n\r\n vec3 ox32 = fract(p32*K) - Ko;\r\n vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\r\n vec3 oz32 = floor(p32*K2)*Kz - Kzo;\r\n\r\n vec3 ox33 = fract(p33*K) - Ko;\r\n vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\r\n vec3 oz33 = floor(p33*K2)*Kz - Kzo;\r\n\r\n vec3 dx11 = Pfx + jitter*ox11;\r\n vec3 dy11 = Pfy.x + jitter*oy11;\r\n vec3 dz11 = Pfz.x + jitter*oz11;\r\n\r\n vec3 dx12 = Pfx + jitter*ox12;\r\n vec3 dy12 = Pfy.x + jitter*oy12;\r\n vec3 dz12 = Pfz.y + jitter*oz12;\r\n\r\n vec3 dx13 = Pfx + jitter*ox13;\r\n vec3 dy13 = Pfy.x + jitter*oy13;\r\n vec3 dz13 = Pfz.z + jitter*oz13;\r\n\r\n vec3 dx21 = Pfx + jitter*ox21;\r\n vec3 dy21 = Pfy.y + jitter*oy21;\r\n vec3 dz21 = Pfz.x + jitter*oz21;\r\n\r\n vec3 dx22 = Pfx + jitter*ox22;\r\n vec3 dy22 = Pfy.y + jitter*oy22;\r\n vec3 dz22 = Pfz.y + jitter*oz22;\r\n\r\n vec3 dx23 = Pfx + jitter*ox23;\r\n vec3 dy23 = Pfy.y + jitter*oy23;\r\n vec3 dz23 = Pfz.z + jitter*oz23;\r\n\r\n vec3 dx31 = Pfx + jitter*ox31;\r\n vec3 dy31 = Pfy.z + jitter*oy31;\r\n vec3 dz31 = Pfz.x + jitter*oz31;\r\n\r\n vec3 dx32 = Pfx + jitter*ox32;\r\n vec3 dy32 = Pfy.z + jitter*oy32;\r\n vec3 dz32 = Pfz.y + jitter*oz32;\r\n\r\n vec3 dx33 = Pfx + jitter*ox33;\r\n vec3 dy33 = Pfy.z + jitter*oy33;\r\n vec3 dz33 = Pfz.z + jitter*oz33;\r\n\r\n vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\r\n vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\r\n vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\r\n vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\r\n vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\r\n vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\r\n vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\r\n vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\r\n vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\r\n\r\n vec3 d1a = min(d11, d12);\r\n d12 = max(d11, d12);\r\n d11 = min(d1a, d13); // Smallest now not in d12 or d13\r\n d13 = max(d1a, d13);\r\n d12 = min(d12, d13); // 2nd smallest now not in d13\r\n vec3 d2a = min(d21, d22);\r\n d22 = max(d21, d22);\r\n d21 = min(d2a, d23); // Smallest now not in d22 or d23\r\n d23 = max(d2a, d23);\r\n d22 = min(d22, d23); // 2nd smallest now not in d23\r\n vec3 d3a = min(d31, d32);\r\n d32 = max(d31, d32);\r\n d31 = min(d3a, d33); // Smallest now not in d32 or d33\r\n d33 = max(d3a, d33);\r\n d32 = min(d32, d33); // 2nd smallest now not in d33\r\n vec3 da = min(d11, d21);\r\n d21 = max(d11, d21);\r\n d11 = min(da, d31); // Smallest now in d11\r\n d31 = max(da, d31); // 2nd smallest now not in d31\r\n d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\r\n d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\r\n d12 = min(d12, d21); // 2nd smallest now not in d21\r\n d12 = min(d12, d22); // nor in d22\r\n d12 = min(d12, d31); // nor in d31\r\n d12 = min(d12, d32); // nor in d32\r\n d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\r\n d11.y = min(d11.y,d12.z); // Only two more to go\r\n d11.y = min(d11.y,d11.z); // Done! (Phew!)\r\n return sqrt(d11.xy); // F1, F2\r\n}\r\n\r\n","// Worley3D");const i=e._getFreeVariableName("worleyTemp");return e.compilationString+=`vec2 ${i} = worley(${this.seed.associatedVariableName}, ${this.jitter.associatedVariableName}, ${this.manhattanDistance});\r\n`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i};\r\n`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${i}.x;\r\n`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${i}.y;\r\n`),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.manhattanDistance = ${this.manhattanDistance};\r\n`}serialize(){const e=super.serialize();return e.manhattanDistance=this.manhattanDistance,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.manhattanDistance=e.manhattanDistance}}(0,be.gn)([(0,xu.p)("Use Manhattan Distance",xu.U.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Md.prototype,"manhattanDistance",void 0),(0,l.H)("BABYLON.WorleyNoise3DBlock",Md);class Id extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("seed",ou.E.Vector3),this.registerOutput("output",ou.E.Float)}getClassName(){return"SimplexPerlin3DBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;if(!this._outputs[0].hasEndpoints)return;let t="const float SKEWFACTOR = 1.0/3.0;\r\n";return t+="const float UNSKEWFACTOR = 1.0/6.0;\r\n",t+="const float SIMPLEX_CORNER_POS = 0.5;\r\n",t+="const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\r\n",t+="float SimplexPerlin3D( vec3 P ){\r\n",t+=" P.x = P == vec3(0., 0., 0.) ? 0.00001 : P.x;\r\n",t+=" P *= SIMPLEX_TETRAHADRON_HEIGHT;\r\n",t+=" vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );",t+=" vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\r\n",t+=" vec3 g = step(x0.yzx, x0.xyz);\r\n",t+=" vec3 l = 1.0 - g;\r\n",t+=" vec3 Pi_1 = min( g.xyz, l.zxy );\r\n",t+=" vec3 Pi_2 = max( g.xyz, l.zxy );\r\n",t+=" vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\r\n",t+=" vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\r\n",t+=" vec3 x3 = x0 - SIMPLEX_CORNER_POS;\r\n",t+=" vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\r\n",t+=" vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\r\n",t+=" vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\r\n",t+=" Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\r\n",t+=" vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\r\n",t+=" vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\r\n",t+=" Pt *= Pt;\r\n",t+=" vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\r\n",t+=" Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\r\n",t+=" const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\r\n",t+=" const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\r\n",t+=" vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\r\n",t+=" vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\r\n",t+=" Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\r\n",t+=" Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\r\n",t+=" vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\r\n",t+=" vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\r\n",t+=" vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\r\n",t+=" vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );\r\n",t+=" const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\r\n",t+=" vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\r\n",t+=" kernel_weights = max(0.5 - kernel_weights, 0.0);\r\n",t+=" kernel_weights = kernel_weights*kernel_weights*kernel_weights;\r\n",t+=" return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\r\n",t+="}\r\n",e._emitFunction("SimplexPerlin3D","const float SKEWFACTOR = 1.0/3.0;\r\nconst float UNSKEWFACTOR = 1.0/6.0;\r\nconst float SIMPLEX_CORNER_POS = 0.5;\r\nconst float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\r\nfloat SimplexPerlin3D( vec3 P ){\r\n P.x = P == vec3(0., 0., 0.) ? 0.00001 : P.x;\r\n P *= SIMPLEX_TETRAHADRON_HEIGHT;\r\n vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) ); vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\r\n vec3 g = step(x0.yzx, x0.xyz);\r\n vec3 l = 1.0 - g;\r\n vec3 Pi_1 = min( g.xyz, l.zxy );\r\n vec3 Pi_2 = max( g.xyz, l.zxy );\r\n vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\r\n vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\r\n vec3 x3 = x0 - SIMPLEX_CORNER_POS;\r\n vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\r\n vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\r\n vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\r\n Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\r\n vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\r\n vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\r\n Pt *= Pt;\r\n vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\r\n Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\r\n const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\r\n const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\r\n vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\r\n vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\r\n Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\r\n Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\r\n vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\r\n vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\r\n vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\r\n vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );\r\n const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\r\n vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\r\n kernel_weights = max(0.5 - kernel_weights, 0.0);\r\n kernel_weights = kernel_weights*kernel_weights*kernel_weights;\r\n return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\r\n}\r\n","// SimplexPerlin3D"),e.compilationString+=this._declareOutput(this._outputs[0],e)+` = SimplexPerlin3D(${this.seed.associatedVariableName});\r\n`,this}}(0,l.H)("BABYLON.SimplexPerlin3DBlock",Id);class Dd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("normalMap0",ou.E.AutoDetect),this.registerInput("normalMap1",ou.E.AutoDetect),this.registerOutput("output",ou.E.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Color4|ou.E.Vector3|ou.E.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Color4|ou.E.Vector3|ou.E.Vector4)}getClassName(){return"NormalBlendBlock"}get normalMap0(){return this._inputs[0]}get normalMap1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0],n=this._inputs[1],s=e._getFreeVariableName("stepR"),r=e._getFreeVariableName("stepG");return e.compilationString+=`float ${s} = step(0.5, ${i.associatedVariableName}.r);\r\n`,e.compilationString+=`float ${r} = step(0.5, ${i.associatedVariableName}.g);\r\n`,e.compilationString+=this._declareOutput(t,e)+";\r\n",e.compilationString+=`${t.associatedVariableName}.r = (1.0 - ${s}) * ${i.associatedVariableName}.r * ${n.associatedVariableName}.r * 2.0 + ${s} * (1.0 - (1.0 - ${i.associatedVariableName}.r) * (1.0 - ${n.associatedVariableName}.r) * 2.0);\r\n`,e.compilationString+=`${t.associatedVariableName}.g = (1.0 - ${r}) * ${i.associatedVariableName}.g * ${n.associatedVariableName}.g * 2.0 + ${r} * (1.0 - (1.0 - ${i.associatedVariableName}.g) * (1.0 - ${n.associatedVariableName}.g) * 2.0);\r\n`,e.compilationString+=`${t.associatedVariableName}.b = ${i.associatedVariableName}.b * ${n.associatedVariableName}.b;\r\n`,this}}(0,l.H)("BABYLON.NormalBlendBlock",Dd);class Od extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("input",ou.E.Vector2),this.registerInput("angle",ou.E.Float),this.registerOutput("output",ou.E.Vector2)}getClassName(){return"Rotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new fu.S("angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.angle,n=this.input;return e.compilationString+=this._declareOutput(t,e)+` = vec2(cos(${i.associatedVariableName}) * ${n.associatedVariableName}.x - sin(${i.associatedVariableName}) * ${n.associatedVariableName}.y, sin(${i.associatedVariableName}) * ${n.associatedVariableName}.x + cos(${i.associatedVariableName}) * ${n.associatedVariableName}.y);\r\n`,this}}(0,l.H)("BABYLON.Rotate2dBlock",Od);class wd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("incident",ou.E.AutoDetect),this.registerInput("normal",ou.E.AutoDetect),this.registerOutput("output",ou.E.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ou.E.Vector3|ou.E.Vector4|ou.E.Color3|ou.E.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ou.E.Vector3|ou.E.Vector4|ou.E.Color3|ou.E.Color4)}getClassName(){return"ReflectBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = reflect(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz);\r\n`,this}}(0,l.H)("BABYLON.ReflectBlock",wd);class Nd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("incident",ou.E.AutoDetect),this.registerInput("normal",ou.E.AutoDetect),this.registerInput("ior",ou.E.Float),this.registerOutput("output",ou.E.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ou.E.Vector3|ou.E.Vector4|ou.E.Color3|ou.E.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ou.E.Vector3|ou.E.Vector4|ou.E.Color3|ou.E.Color4)}getClassName(){return"RefractBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get ior(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = refract(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz, ${this.ior.associatedVariableName});\r\n`,this}}(0,l.H)("BABYLON.RefractBlock",Nd);class Fd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("color",ou.E.Color3),this.registerInput("level",ou.E.Float),this.registerOutput("output",ou.E.Color3)}getClassName(){return"DesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.color.associatedVariableName,n=e._getFreeVariableName("colorMin"),s=e._getFreeVariableName("colorMax"),r=e._getFreeVariableName("colorMerge");return e.compilationString+=`float ${n} = min(min(${i}.x, ${i}.y), ${i}.z);\r\n`,e.compilationString+=`float ${s} = max(max(${i}.x, ${i}.y), ${i}.z);\r\n`,e.compilationString+=`float ${r} = 0.5 * (${n} + ${s});\r\n`,e.compilationString+=this._declareOutput(t,e)+` = mix(${i}, vec3(${r}, ${r}, ${r}), ${this.level.associatedVariableName});\r\n`,this}}(0,l.H)("BABYLON.DesaturateBlock",Fd);class Ld extends du.k{constructor(e){super(e,ru.u.Fragment),this.albedoScaling=!1,this.linkSheenWithAlbedo=!1,this._isUnique=!0,this.registerInput("intensity",ou.E.Float,!0,ru.u.Fragment),this.registerInput("color",ou.E.Color3,!0,ru.u.Fragment),this.registerInput("roughness",ou.E.Float,!0,ru.u.Fragment),this.registerOutput("sheen",ou.E.Object,ru.u.Fragment,new uu("sheen",this,cu.Ab.Output,Ld,"SheenBlock"))}initialize(e){e._excludeVariableName("sheenOut"),e._excludeVariableName("sheenMapData"),e._excludeVariableName("vSheenColor"),e._excludeVariableName("vSheenRoughness")}getClassName(){return"SheenBlock"}get intensity(){return this._inputs[0]}get color(){return this._inputs[1]}get roughness(){return this._inputs[2]}get sheen(){return this._outputs[0]}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("SHEEN",!0),i.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("SHEEN_LINKWITHALBEDO",this.linkSheenWithAlbedo,!0),i.setValue("SHEEN_ROUGHNESS",this.roughness.isConnected,!0),i.setValue("SHEEN_ALBEDOSCALING",this.albedoScaling,!0)}getCode(e){let t="";return t=`#ifdef SHEEN\n sheenOutParams sheenOut;\n\n vec4 vSheenColor = vec4(${this.color.isConnected?this.color.associatedVariableName:"vec3(1.)"}, ${this.intensity.isConnected?this.intensity.associatedVariableName:"1."});\n\n sheenBlock(\n vSheenColor,\n #ifdef SHEEN_ROUGHNESS\n ${this.roughness.isConnected?this.roughness.associatedVariableName:"0."},\n #endif\n roughness,\n #ifdef SHEEN_TEXTURE\n vec4(0.),\n 1.0,\n #endif\n reflectance,\n #ifdef SHEEN_LINKWITHALBEDO\n baseColor,\n surfaceAlbedo,\n #endif\n #ifdef ENVIRONMENTBRDF\n NdotV,\n environmentBrdf,\n #endif\n #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\n AARoughnessFactors,\n ${null==e?void 0:e._vReflectionMicrosurfaceInfosName},\n ${null==e?void 0:e._vReflectionInfosName},\n ${null==e?void 0:e.reflectionColor},\n vLightingIntensity,\n #ifdef ${null==e?void 0:e._define3DName}\n ${null==e?void 0:e._cubeSamplerName},\n #else\n ${null==e?void 0:e._2DSamplerName},\n #endif\n reflectionOut.reflectionCoords,\n NdotVUnclamped,\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${null==e?void 0:e._define3DName}\n ${null==e?void 0:e._cubeSamplerName},\n ${null==e?void 0:e._cubeSamplerName},\n #else\n ${null==e?void 0:e._2DSamplerName},\n ${null==e?void 0:e._2DSamplerName},\n #endif\n #endif\n #if !defined(${null==e?void 0:e._defineSkyboxName}) && defined(RADIANCEOCCLUSION)\n seo,\n #endif\n #if !defined(${null==e?void 0:e._defineSkyboxName}) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(${null==e?void 0:e._define3DName})\n eho,\n #endif\n #endif\n sheenOut\n );\n\n #ifdef SHEEN_LINKWITHALBEDO\n surfaceAlbedo = sheenOut.surfaceAlbedo;\n #endif\n #endif\r\n`,t}_buildBlock(e){return e.target===ru.u.Fragment&&e.sharedData.blocksWithDefines.push(this),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.albedoScaling = ${this.albedoScaling};\r\n`,e+=`${this._codeVariableName}.linkSheenWithAlbedo = ${this.linkSheenWithAlbedo};\r\n`,e}serialize(){const e=super.serialize();return e.albedoScaling=this.albedoScaling,e.linkSheenWithAlbedo=this.linkSheenWithAlbedo,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.albedoScaling=e.albedoScaling,this.linkSheenWithAlbedo=e.linkSheenWithAlbedo}}(0,be.gn)([(0,xu.p)("Albedo scaling",xu.U.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Ld.prototype,"albedoScaling",void 0),(0,be.gn)([(0,xu.p)("Link sheen with albedo",xu.U.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Ld.prototype,"linkSheenWithAlbedo",void 0),(0,l.H)("BABYLON.SheenBlock",Ld);var Bd=i(6344);class Ud extends du.k{constructor(e){super(e,ru.u.Fragment),this._tangentCorrectionFactorName="",this._isUnique=!0,this.registerInput("intensity",ou.E.Float,!0,ru.u.Fragment),this.registerInput("direction",ou.E.Vector2,!0,ru.u.Fragment),this.registerInput("uv",ou.E.Vector2,!0),this.registerInput("worldTangent",ou.E.Vector4,!0),this.registerInput("TBN",ou.E.Object,!0,ru.u.VertexAndFragment,new uu("TBN",this,cu.Ab.Input,Tu,"TBNBlock")),this.registerOutput("anisotropy",ou.E.Object,ru.u.Fragment,new uu("anisotropy",this,cu.Ab.Output,Ud,"AnisotropyBlock"))}initialize(e){e._excludeVariableName("anisotropicOut"),e._excludeVariableName("TBN")}getClassName(){return"AnisotropyBlock"}get intensity(){return this._inputs[0]}get direction(){return this._inputs[1]}get uv(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get TBN(){return this._inputs[4]}get anisotropy(){return this._outputs[0]}_generateTBNSpace(e){let t="";const i=`//${this.name}`,n=this.uv,s=this.worldPositionConnectionPoint,r=this.worldNormalConnectionPoint,o=this.worldTangent;n.isConnected||console.error("You must connect the 'uv' input of the Anisotropy block!"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const a={search:/defined\(TANGENT\)/g,replace:o.isConnected?"defined(TANGENT)":"defined(IGNORE)"},l=this.TBN;return l.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n mat3 vTBN = ${l.associatedVariableName};\n #endif\n `:o.isConnected&&(t+=`vec3 tbnNormal = normalize(${r.associatedVariableName}.xyz);\r\n`,t+=`vec3 tbnTangent = normalize(${o.associatedVariableName}.xyz);\r\n`,t+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\r\n`,t+="mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n"),t+=`\n #if defined(${o.isConnected?"TANGENT":"IGNORE"}) && defined(NORMAL)\n mat3 TBN = vTBN;\n #else\n mat3 TBN = cotangent_frame(${r.associatedVariableName+".xyz"}, ${"v_"+s.associatedVariableName+".xyz"}, ${n.isConnected?n.associatedVariableName:"vec2(0.)"}, vec2(1., 1.));\n #endif\r\n`,e._emitFunctionFromInclude("bumpFragmentMainFunctions",i,{replaceStrings:[a]}),t}getCode(e,t=!1){let i="";t&&(i+=this._generateTBNSpace(e));const n=this.intensity.isConnected?this.intensity.associatedVariableName:"1.0";return i+=`anisotropicOutParams anisotropicOut;\n anisotropicBlock(\n vec3(${this.direction.isConnected?this.direction.associatedVariableName:"vec2(1., 0.)"}, ${n}),\n #ifdef ANISOTROPIC_TEXTURE\n vec3(0.),\n #endif\n TBN,\n normalW,\n viewDirectionW,\n anisotropicOut\n );\r\n`,i}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("ANISOTROPIC",!0),i.setValue("ANISOTROPIC_TEXTURE",!1,!0)}bind(e,t,i){super.bind(e,t,i),i&&e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1)}_buildBlock(e){return e.target===ru.u.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}}(0,l.H)("BABYLON.AnisotropyBlock",Ud);class Vd extends Uu{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The position input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?ru.u.Fragment:ru.u.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)}constructor(e){super(e),this.useSphericalHarmonics=!0,this.forceIrradianceInFragment=!1,this._isUnique=!0,this.registerInput("position",ou.E.AutoDetect,!1,ru.u.Vertex),this.registerInput("world",ou.E.Matrix,!1,ru.u.Vertex),this.registerInput("color",ou.E.Color3,!0,ru.u.Fragment),this.registerOutput("reflection",ou.E.Object,ru.u.Fragment,new uu("reflection",this,cu.Ab.Output,Vd,"ReflectionBlock")),this.position.addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Vector3|ou.E.Vector4)}getClassName(){return"ReflectionBlock"}get position(){return this._inputs[0]}get worldPosition(){return this.worldPositionConnectionPoint}get worldNormal(){return this.worldNormalConnectionPoint}get world(){return this._inputs[1]}get cameraPosition(){return this.cameraPositionConnectionPoint}get view(){return this.viewConnectionPoint}get color(){return this._inputs[2]}get reflection(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}get reflectionColor(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const n=this._getTexture(),s=n&&n.getTextureMatrix;i.setValue("REFLECTION",s,!0),s&&(i.setValue(this._defineLODReflectionAlpha,n.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularReflection,n.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!n.invertZ:n.invertZ,!0),i.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),i.setValue("GAMMAREFLECTION",n.gammaSpace,!0),i.setValue("RGBDREFLECTION",n.isRGBD,!0),n&&n.coordinatesMode!==Ce.x.SKYBOX_MODE&&n.isCube&&(i.setValue("USESPHERICALFROMREFLECTIONMAP",!0),i.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?i.setValue("USESPHERICALINVERTEX",!1):i.setValue("USESPHERICALINVERTEX",!0)))}bind(e,t,i,n){super.bind(e,t,i);const s=this._getTexture();if(!s||!n)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s);const r=s.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,r,s.lodGenerationScale,s.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,r,lt.R.Log2(r));const o=n.materialDefines,a=s.sphericalPolynomial;if(o.USESPHERICALFROMREFLECTIONMAP&&a)if(o.SPHERICAL_HARMONICS){const t=a.preScaledHarmonics;e.setVector3("vSphericalL00",t.l00),e.setVector3("vSphericalL1_1",t.l1_1),e.setVector3("vSphericalL10",t.l10),e.setVector3("vSphericalL11",t.l11),e.setVector3("vSphericalL2_2",t.l2_2),e.setVector3("vSphericalL2_1",t.l2_1),e.setVector3("vSphericalL20",t.l20),e.setVector3("vSphericalL21",t.l21),e.setVector3("vSphericalL22",t.l22)}else e.setFloat3("vSphericalX",a.x.x,a.x.y,a.x.z),e.setFloat3("vSphericalY",a.y.x,a.y.y,a.y.z),e.setFloat3("vSphericalZ",a.z.x,a.z.y,a.z.z),e.setFloat3("vSphericalXX_ZZ",a.xx.x-a.zz.x,a.xx.y-a.zz.y,a.xx.z-a.zz.z),e.setFloat3("vSphericalYY_ZZ",a.yy.x-a.zz.x,a.yy.y-a.zz.y,a.yy.z-a.zz.z),e.setFloat3("vSphericalZZ",a.zz.x,a.zz.y,a.zz.z),e.setFloat3("vSphericalXY",a.xy.x,a.xy.y,a.xy.z),e.setFloat3("vSphericalYZ",a.yz.x,a.yz.y,a.yz.z),e.setFloat3("vSphericalZX",a.zx.x,a.zx.y,a.zx.z)}handleVertexSide(e){let t=super.handleVertexSide(e);e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});const i=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,"vec3","defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX","vec3","SPHERICAL_HARMONICS",!0),t+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\n vec3 ${i} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz;\n #ifdef ${this._defineOppositeZ}\n ${i}.z *= -1.0;\n #endif\n ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${i});\n #endif\r\n`,t}getCode(e,t){let i="";this.handleFragmentSideInits(e),e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),e._emitFunction("sampleReflection",`\n #ifdef ${this._define3DName}\n #define sampleReflection(s, c) textureCube(s, c)\n #else\n #define sampleReflection(s, c) texture2D(s, c)\n #endif\r\n`,`//${this.name}`),e._emitFunction("sampleReflectionLod",`\n #ifdef ${this._define3DName}\n #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\r\n`,`//${this.name}`);const n=`\n vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {\n ${this.handleFragmentSideCodeReflectionCoords("worldNormal","worldPos",!0,!0)}\n return ${this._reflectionVectorName};\n }\r\n`;return e._emitFunction("computeReflectionCoordsPBR",n,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,"vec3"),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,"vec2"),i+=`#ifdef REFLECTION\n vec2 ${this._vReflectionInfosName} = vec2(1., 0.);\n\n reflectionOutParams reflectionOut;\n\n reflectionBlock(\n ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName}.xyz,\n ${t},\n alphaG,\n ${this._vReflectionMicrosurfaceInfosName},\n ${this._vReflectionInfosName},\n ${this.reflectionColor},\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName})\n NdotVUnclamped,\n #endif\n #ifdef ${this._defineLinearSpecularReflection}\n roughness,\n #endif\n #ifdef ${this._define3DName}\n ${this._cubeSamplerName},\n #else\n ${this._2DSamplerName},\n #endif\n #if defined(NORMAL) && defined(USESPHERICALINVERTEX)\n ${this._vEnvironmentIrradianceName},\n #endif\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n ${this._reflectionMatrixName},\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler, // ** not handled **\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${this._define3DName}\n ${this._cubeSamplerName},\n ${this._cubeSamplerName},\n #else\n ${this._2DSamplerName},\n ${this._2DSamplerName},\n #endif\n #endif\n #ifdef REALTIME_FILTERING\n ${this._vReflectionFilteringInfoName},\n #endif\n reflectionOut\n );\n #endif\r\n`,i}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==ru.u.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace};\r\n`),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics};\r\n`,e+=`${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment};\r\n`,e}serialize(){var e,t;const i=super.serialize();return i.useSphericalHarmonics=this.useSphericalHarmonics,i.forceIrradianceInFragment=this.forceIrradianceInFragment,i.gammaSpace=null===(t=null===(e=this.texture)||void 0===e?void 0:e.gammaSpace)||void 0===t||t,i}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}}(0,be.gn)([(0,xu.p)("Spherical Harmonics",xu.U.Boolean,"ADVANCED",{notifiers:{update:!0}})],Vd.prototype,"useSphericalHarmonics",void 0),(0,be.gn)([(0,xu.p)("Force irradiance in fragment",xu.U.Boolean,"ADVANCED",{notifiers:{update:!0}})],Vd.prototype,"forceIrradianceInFragment",void 0),(0,l.H)("BABYLON.ReflectionBlock",Vd);class kd extends du.k{constructor(e){super(e,ru.u.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",ou.E.Float,!1,ru.u.Fragment),this.registerInput("roughness",ou.E.Float,!0,ru.u.Fragment),this.registerInput("indexOfRefraction",ou.E.Float,!0,ru.u.Fragment),this.registerInput("normalMapColor",ou.E.Color3,!0,ru.u.Fragment),this.registerInput("uv",ou.E.Vector2,!0,ru.u.Fragment),this.registerInput("tintColor",ou.E.Color3,!0,ru.u.Fragment),this.registerInput("tintAtDistance",ou.E.Float,!0,ru.u.Fragment),this.registerInput("tintThickness",ou.E.Float,!0,ru.u.Fragment),this.registerInput("worldTangent",ou.E.Vector4,!0),this.registerInput("worldNormal",ou.E.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(ou.E.Color4|ou.E.Vector4|ou.E.Vector3),this.registerInput("TBN",ou.E.Object,!0,ru.u.VertexAndFragment,new uu("TBN",this,cu.Ab.Input,Tu,"TBNBlock")),this.registerOutput("clearcoat",ou.E.Object,ru.u.Fragment,new uu("clearcoat",this,cu.Ab.Output,kd,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){const e=new fu.S("ClearCoat intensity",ru.u.Fragment,ou.E.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",!this.indexOfRefraction.isConnected||this.indexOfRefraction.connectInputBlock.value===rc.Y._DefaultIndexOfRefraction,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){var n,s;super.bind(e,t,i);const r=null!==(s=null===(n=this.indexOfRefraction.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==s?s:rc.Y._DefaultIndexOfRefraction,o=1-r,a=1+r,l=Math.pow(-o/a,2),h=1/r;e.setFloat4("vClearCoatRefractionParams",l,h,o,a);const c=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,u=(null==c?void 0:c.perturbedNormal.isConnected)?c.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",(null==u?void 0:u.invertX)?1:-1,(null==u?void 0:u.invertY)?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",(null==u?void 0:u.invertX)?-1:1,(null==u?void 0:u.invertY)?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1)}_generateTBNSpace(e,t,i){let n="";const s=`//${this.name}`,r=this.worldTangent;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const o={search:/defined\(TANGENT\)/g,replace:r.isConnected?"defined(TANGENT)":"defined(IGNORE)"},a=this.TBN;return a.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n mat3 vTBN = ${a.associatedVariableName};\n #endif\n `:r.isConnected&&(n+=`vec3 tbnNormal = normalize(${i}.xyz);\r\n`,n+=`vec3 tbnTangent = normalize(${r.associatedVariableName}.xyz);\r\n`,n+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\r\n`,n+="mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n"),e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[o]}),n}static GetCode(e,t,i,n,s,r,o){let a="";const l=(null==t?void 0:t.intensity.isConnected)?t.intensity.associatedVariableName:"1.",h=(null==t?void 0:t.roughness.isConnected)?t.roughness.associatedVariableName:"0.",c=(null==t?void 0:t.normalMapColor.isConnected)?t.normalMapColor.associatedVariableName:"vec3(0.)",u=(null==t?void 0:t.uv.isConnected)?t.uv.associatedVariableName:"vec2(0.)",d=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",p=(null==t?void 0:t.tintThickness.isConnected)?t.tintThickness.associatedVariableName:"1.",f=(null==t?void 0:t.tintAtDistance.isConnected)?t.tintAtDistance.associatedVariableName:"1.";if(t){e._emitUniformFromString("vClearCoatRefractionParams","vec4"),e._emitUniformFromString("vClearCoatTangentSpaceParams","vec2");const i=t.worldNormal;a+=`vec3 vGeometricNormaClearCoatW = ${i.isConnected?"normalize("+i.associatedVariableName+".xyz)":"geometricNormalW"};\r\n`}else a+="vec3 vGeometricNormaClearCoatW = geometricNormalW;\r\n";return s&&t&&(a+=t._generateTBNSpace(e,n,o),r=t.worldTangent.isConnected),a+=`clearcoatOutParams clearcoatOut;\n\n #ifdef CLEARCOAT\n vec2 vClearCoatParams = vec2(${l}, ${h});\n vec4 vClearCoatTintParams = vec4(${d}, ${p});\n\n clearcoatBlock(\n ${n}.xyz,\n vGeometricNormaClearCoatW,\n viewDirectionW,\n vClearCoatParams,\n specularEnvironmentR0,\n #ifdef CLEARCOAT_TEXTURE\n vec2(0.),\n #endif\n #ifdef CLEARCOAT_TINT\n vClearCoatTintParams,\n ${f},\n vClearCoatRefractionParams,\n #ifdef CLEARCOAT_TINT_TEXTURE\n vec4(0.),\n #endif\n #endif\n #ifdef CLEARCOAT_BUMP\n vec2(0., 1.),\n vec4(${c}, 0.),\n ${u},\n #if defined(${r?"TANGENT":"IGNORE"}) && defined(NORMAL)\n vTBN,\n #else\n vClearCoatTangentSpaceParams,\n #endif\n #ifdef OBJECTSPACE_NORMALMAP\n normalMatrix,\n #endif\n #endif\n #if defined(FORCENORMALFORWARD) && defined(NORMAL)\n faceNormal,\n #endif\n #ifdef REFLECTION\n ${null==i?void 0:i._vReflectionMicrosurfaceInfosName},\n ${null==i?void 0:i._vReflectionInfosName},\n ${null==i?void 0:i.reflectionColor},\n vLightingIntensity,\n #ifdef ${null==i?void 0:i._define3DName}\n ${null==i?void 0:i._cubeSamplerName},\n #else\n ${null==i?void 0:i._2DSamplerName},\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${null==i?void 0:i._define3DName}\n ${null==i?void 0:i._cubeSamplerName},\n ${null==i?void 0:i._cubeSamplerName},\n #else\n ${null==i?void 0:i._2DSamplerName},\n ${null==i?void 0:i._2DSamplerName},\n #endif\n #endif\n #endif\n #if defined(ENVIRONMENTBRDF) && !defined(${null==i?void 0:i._defineSkyboxName})\n #ifdef RADIANCEOCCLUSION\n ambientMonochrome,\n #endif\n #endif\n #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n (gl_FrontFacing ? 1. : -1.),\n #endif\n clearcoatOut\n );\n #else\n clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;\n #endif\r\n`,a}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===ru.u.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange};\r\n`,e}serialize(){const e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){var n;super._deserialize(e,t,i),this.remapF0OnInterfaceChange=null===(n=e.remapF0OnInterfaceChange)||void 0===n||n}}(0,be.gn)([(0,xu.p)("Remap F0 on interface change",xu.U.Boolean,"ADVANCED")],kd.prototype,"remapF0OnInterfaceChange",void 0),(0,l.H)("BABYLON.ClearCoatBlock",kd);class Gd extends du.k{constructor(e){super(e,ru.u.Fragment),this._isUnique=!0,this.registerInput("intensity",ou.E.Float,!0,ru.u.Fragment),this.registerInput("indexOfRefraction",ou.E.Float,!0,ru.u.Fragment),this.registerInput("thickness",ou.E.Float,!0,ru.u.Fragment),this.registerOutput("iridescence",ou.E.Object,ru.u.Fragment,new uu("iridescence",this,cu.Ab.Output,Gd,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){const e=new fu.S("Iridescence intensity",ru.u.Fragment,ou.E.Float);e.value=1,e.output.connectTo(this.intensity);const t=new fu.S("Iridescence ior",ru.u.Fragment,ou.E.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);const i=new fu.S("Iridescence thickness",ru.u.Fragment,ou.E.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e){let t="";return t+=`iridescenceOutParams iridescenceOut;\n\n #ifdef IRIDESCENCE\n iridescenceBlock(\n vec4(${(null==e?void 0:e.intensity.isConnected)?e.intensity.associatedVariableName:"1."}, ${(null==e?void 0:e.indexOfRefraction.isConnected)?e.indexOfRefraction.associatedVariableName:oc.B._DefaultIndexOfRefraction}, 1., ${(null==e?void 0:e.thickness.isConnected)?e.thickness.associatedVariableName:oc.B._DefaultMaximumThickness}),\n NdotV,\n specularEnvironmentR0,\n #ifdef CLEARCOAT\n NdotVUnclamped,\n #endif\n iridescenceOut\n );\n\n float iridescenceIntensity = iridescenceOut.iridescenceIntensity;\n specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0;\n #endif\r\n`,t}_buildBlock(e){return e.target===ru.u.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)}}(0,l.H)("BABYLON.IridescenceBlock",Gd);class zd extends du.k{constructor(e){super(e,ru.u.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",ou.E.Float,!1,ru.u.Fragment),this.registerInput("tintAtDistance",ou.E.Float,!0,ru.u.Fragment),this.registerInput("volumeIndexOfRefraction",ou.E.Float,!0,ru.u.Fragment),this.registerOutput("refraction",ou.E.Object,ru.u.Fragment,new uu("refraction",this,cu.Ab.Output,zd,"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){if(!this.intensity.isConnected){const e=new fu.S("Refraction intensity",ru.u.Fragment,ou.E.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.View));t||(t=new fu.S("view"),t.setAsSystemValue(lu.$.View)),t.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const n=this._getTexture(),s=n&&n.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,n.isCube,!0),i.setValue(this._defineLODRefractionAlpha,n.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,n.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&n.isCube?!n.invertZ:n.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",n.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",n.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!n.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 n,s,r,o;super.bind(e,t,i);const a=this._getTexture();if(!a)return;a.isCube?e.setTexture(this._cubeSamplerName,a):e.setTexture(this._2DSamplerName,a),e.setMatrix(this._refractionMatrixName,a.getRefractionTextureMatrix());let l=1;a.isCube||a.depth&&(l=a.depth);const h=null!==(o=null!==(s=null===(n=this.volumeIndexOfRefraction.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==s?s:null===(r=this.indexOfRefractionConnectionPoint.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==o?o:1.5;e.setFloat4(this._vRefractionInfosName,a.level,1/h,l,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,a.getSize().width,a.lodGenerationScale,a.lodGenerationOffset,1/h);const c=a.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,c,lt.R.Log2(c)),a.boundingBoxSize){const t=a;e.setVector3("vRefractionPosition",t.boundingBoxPosition),e.setVector3("vRefractionSize",t.boundingBoxSize)}}getCode(e){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}\r\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\r\n`,e._samplerDeclaration+="#else\r\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\r\n`,e._samplerDeclaration+="#endif\r\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",`\n #ifdef ${this._define3DName}\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\r\n`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`\n #ifdef ${this._define3DName}\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\r\n`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\r\n`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\r\n`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\r\n`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\r\n`,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=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=Fa.B.Parse(e.texture,t,i):this.texture=Ce.x.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}(0,be.gn)([(0,xu.p)("Link refraction to transparency",xu.U.Boolean,"ADVANCED",{notifiers:{update:!0}})],zd.prototype,"linkRefractionWithTransparency",void 0),(0,be.gn)([(0,xu.p)("Invert refraction Y",xu.U.Boolean,"ADVANCED",{notifiers:{update:!0}})],zd.prototype,"invertRefractionY",void 0),(0,be.gn)([(0,xu.p)("Use thickness as depth",xu.U.Boolean,"ADVANCED",{notifiers:{update:!0}})],zd.prototype,"useThicknessAsDepth",void 0),(0,l.H)("BABYLON.RefractionBlock",zd);class Wd extends du.k{constructor(e){super(e,ru.u.Fragment),this._isUnique=!0,this.registerInput("thickness",ou.E.Float,!1,ru.u.Fragment),this.registerInput("tintColor",ou.E.Color3,!0,ru.u.Fragment),this.registerInput("translucencyIntensity",ou.E.Float,!0,ru.u.Fragment),this.registerInput("translucencyDiffusionDist",ou.E.Color3,!0,ru.u.Fragment),this.registerInput("refraction",ou.E.Object,!0,ru.u.Fragment,new uu("refraction",this,cu.Ab.Input,zd,"RefractionBlock")),this.registerOutput("subsurface",ou.E.Object,ru.u.Fragment,new uu("subsurface",this,cu.Ab.Output,Wd,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity")}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 subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new fu.S("SubSurface thickness",ru.u.Fragment,ou.E.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const n=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",n||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",n,!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)}static GetCode(e,t,i,n){var s,r,o,a,l,h,c,u,d,p,f,_,m,g,v,y;let x="";const b=(null==t?void 0:t.thickness.isConnected)?t.thickness.associatedVariableName:"0.",T=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",S=(null==t?void 0:t.translucencyIntensity.isConnected)?null==t?void 0:t.translucencyIntensity.associatedVariableName:"1.",E=(null==t?void 0:t.translucencyDiffusionDist.isConnected)?null==t?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",C=(null==t?void 0:t.refraction.isConnected)?null===(s=null==t?void 0:t.refraction.connectedPoint)||void 0===s?void 0:s.ownerBlock:null,A=(null==C?void 0:C.tintAtDistance.isConnected)?C.tintAtDistance.associatedVariableName:"1.",P=(null==C?void 0:C.intensity.isConnected)?C.intensity.associatedVariableName:"1.",R=(null==C?void 0:C.view.isConnected)?C.view.associatedVariableName:"";return x+=null!==(r=null==C?void 0:C.getCode(e))&&void 0!==r?r:"",x+=`subSurfaceOutParams subSurfaceOut;\n\n #ifdef SUBSURFACE\n vec2 vThicknessParam = vec2(0., ${b});\n vec4 vTintColor = vec4(${T}, ${A});\n vec3 vSubSurfaceIntensity = vec3(${P}, ${S}, 0.);\n\n subSurfaceBlock(\n vSubSurfaceIntensity,\n vThicknessParam,\n vTintColor,\n normalW,\n specularEnvironmentReflectance,\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n vec4(0.),\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n ${null==i?void 0:i._reflectionMatrixName},\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n reflectionOut.irradianceVector,\n #endif\n #if defined(REALTIME_FILTERING)\n ${null==i?void 0:i._cubeSamplerName},\n ${null==i?void 0:i._vReflectionFilteringInfoName},\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler,\n #endif\n #endif\n #endif\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n surfaceAlbedo,\n #endif\n #ifdef SS_REFRACTION\n ${n}.xyz,\n viewDirectionW,\n ${R},\n ${null!==(o=null==C?void 0:C._vRefractionInfosName)&&void 0!==o?o:""},\n ${null!==(a=null==C?void 0:C._refractionMatrixName)&&void 0!==a?a:""},\n ${null!==(l=null==C?void 0:C._vRefractionMicrosurfaceInfosName)&&void 0!==l?l:""},\n vLightingIntensity,\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha,\n #endif\n #ifdef ${null!==(h=null==C?void 0:C._defineLODRefractionAlpha)&&void 0!==h?h:"IGNORE"}\n NdotVUnclamped,\n #endif\n #ifdef ${null!==(c=null==C?void 0:C._defineLinearSpecularRefraction)&&void 0!==c?c:"IGNORE"}\n roughness,\n #endif\n alphaG,\n #ifdef ${null!==(u=null==C?void 0:C._define3DName)&&void 0!==u?u:"IGNORE"}\n ${null!==(d=null==C?void 0:C._cubeSamplerName)&&void 0!==d?d:""},\n #else\n ${null!==(p=null==C?void 0:C._2DSamplerName)&&void 0!==p?p:""},\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${null!==(f=null==C?void 0:C._define3DName)&&void 0!==f?f:"IGNORE"}\n ${null!==(_=null==C?void 0:C._cubeSamplerName)&&void 0!==_?_:""},\n ${null!==(m=null==C?void 0:C._cubeSamplerName)&&void 0!==m?m:""},\n #else\n ${null!==(g=null==C?void 0:C._2DSamplerName)&&void 0!==g?g:""},\n ${null!==(v=null==C?void 0:C._2DSamplerName)&&void 0!==v?v:""},\n #endif\n #endif\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #ifdef REALTIME_FILTERING\n ${null!==(y=null==C?void 0:C._vRefractionFilteringInfoName)&&void 0!==y?y:""},\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n vRefractionPosition,\n vRefractionSize,\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n ${E},\n #endif\n subSurfaceOut\n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\r\n`,x}_buildBlock(e){return e.target===ru.u.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}(0,l.H)("BABYLON.SubSurfaceBlock",Wd);const Hd={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:["shadow",""],alpha:["alpha",""]};class Xd extends du.k{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ru.u.Fragment:ru.u.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ru.u.Fragment:ru.u.Vertex}constructor(e){super(e,ru.u.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=a.Wo.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",ou.E.Vector4,!1,ru.u.Vertex),this.registerInput("worldNormal",ou.E.Vector4,!1,ru.u.Fragment),this.registerInput("view",ou.E.Matrix,!1),this.registerInput("cameraPosition",ou.E.Vector3,!1,ru.u.Fragment),this.registerInput("perturbedNormal",ou.E.Vector4,!0,ru.u.Fragment),this.registerInput("baseColor",ou.E.Color3,!0,ru.u.Fragment),this.registerInput("metallic",ou.E.Float,!1,ru.u.Fragment),this.registerInput("roughness",ou.E.Float,!1,ru.u.Fragment),this.registerInput("ambientOcc",ou.E.Float,!0,ru.u.Fragment),this.registerInput("opacity",ou.E.Float,!0,ru.u.Fragment),this.registerInput("indexOfRefraction",ou.E.Float,!0,ru.u.Fragment),this.registerInput("ambientColor",ou.E.Color3,!0,ru.u.Fragment),this.registerInput("reflection",ou.E.Object,!0,ru.u.Fragment,new uu("reflection",this,cu.Ab.Input,Vd,"ReflectionBlock")),this.registerInput("clearcoat",ou.E.Object,!0,ru.u.Fragment,new uu("clearcoat",this,cu.Ab.Input,kd,"ClearCoatBlock")),this.registerInput("sheen",ou.E.Object,!0,ru.u.Fragment,new uu("sheen",this,cu.Ab.Input,Ld,"SheenBlock")),this.registerInput("subsurface",ou.E.Object,!0,ru.u.Fragment,new uu("subsurface",this,cu.Ab.Input,Wd,"SubSurfaceBlock")),this.registerInput("anisotropy",ou.E.Object,!0,ru.u.Fragment,new uu("anisotropy",this,cu.Ab.Input,Ud,"AnisotropyBlock")),this.registerInput("iridescence",ou.E.Object,!0,ru.u.Fragment,new uu("iridescence",this,cu.Ab.Input,Gd,"IridescenceBlock")),this.registerOutput("ambientClr",ou.E.Color3,ru.u.Fragment),this.registerOutput("diffuseDir",ou.E.Color3,ru.u.Fragment),this.registerOutput("specularDir",ou.E.Color3,ru.u.Fragment),this.registerOutput("clearcoatDir",ou.E.Color3,ru.u.Fragment),this.registerOutput("sheenDir",ou.E.Color3,ru.u.Fragment),this.registerOutput("diffuseInd",ou.E.Color3,ru.u.Fragment),this.registerOutput("specularInd",ou.E.Color3,ru.u.Fragment),this.registerOutput("clearcoatInd",ou.E.Color3,ru.u.Fragment),this.registerOutput("sheenInd",ou.E.Color3,ru.u.Fragment),this.registerOutput("refraction",ou.E.Color3,ru.u.Fragment),this.registerOutput("lighting",ou.E.Color3,ru.u.Fragment),this.registerOutput("shadow",ou.E.Float,ru.u.Fragment),this.registerOutput("alpha",ou.E.Float,ru.u.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){if(!this.cameraPosition.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.CameraPosition));t||(t=new fu.S("cameraPosition"),t.setAsSystemValue(lu.$.CameraPosition)),t.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===lu.$.View));t||(t=new fu.S("view"),t.setAsSystemValue(lu.$.View)),t.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!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===nc.m.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===nc.m.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const n=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",n.indexOf(".")<0?n+".":n,!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 s=e.getScene();if(s.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&&Va.k.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){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};La.G.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else La.G.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,La.G.PrepareDefinesForMultiview(s,i)}updateUniformsAndSamples(e,t,i,n){for(let s=0;s<t.maxSimultaneousLights&&i["LIGHT"+s];s++){const t=e.uniforms.indexOf("vLightData"+s)>=0;La.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],n,t)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var n,s;if(!i)return;const r=i.getScene();this.light?La.G.BindLight(this.light,this._lightId,r,e,!0):La.G.BindLights(r,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const o=this._scene.ambientColor;o&&e.setColor3("ambientFromScene",o);const l=r.useRightHandedSystem===(null!=r._mirroredCameraPosition);e.setFloat(this._invertNormalName,l?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const h=null!==(s=null===(n=this.indexOfRefraction.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==s?s:1.5,c=Math.pow((h-1)/(h+1),2);this._metallicReflectanceColor.scaleToRef(c*this._metallicF0Factor,a.zZ.Color3[0]);const u=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,a.zZ.Color3[0],u),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;const n=this.worldPosition,s=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const r="v_"+n.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${n.associatedVariableName};\r\n`);const o=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;o&&(o.viewConnectionPoint=this.view),e.compilationString+=null!==(i=null==o?void 0:o.handleVertexSide(e))&&void 0!==i?i:"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\r\n",e._injectAtEnd+="vClipSpacePosition = gl_Position;\r\n",e._injectAtEnd+="#endif\r\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:n.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${n.associatedVariableName};\r\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\r\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e="albedoOpacityOutParams albedoOpacityOut;\r\n";return e+=`albedoOpacityBlock(\n vec4(${this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)"}, 1.),\n #ifdef ALBEDO\n vec4(1.),\n vec2(1., 1.),\n #endif\n #ifdef OPACITY\n vec4(${this.opacity.isConnected?this.opacity.associatedVariableName:"1."}),\n vec2(1., 1.),\n #endif\n albedoOpacityOut\n );\n\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\n float alpha = albedoOpacityOut.alpha;\r\n`,e}_getAmbientOcclusionCode(){let e="ambientOcclusionOutParams aoOut;\r\n";return e+=`ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3(${this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1."}),\n vec4(0., 1.0, 1.0, 0.),\n #endif\n aoOut\n );\r\n`,e}_getReflectivityCode(e){let t="reflectivityOutParams reflectivityOut;\r\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo;\n\n reflectivityBlock(\n vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),\n #ifdef METALLICWORKFLOW\n surfaceAlbedo,\n ${this._vMetallicReflectanceFactorsName},\n #endif\n #ifdef REFLECTIVITY\n vec3(0., 0., 1.),\n vec4(1.),\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor,\n #endif\n #ifdef MICROSURFACEMAP\n microSurfaceTexel, <== not handled!\n #endif\n reflectivityOut\n );\n\n float microSurface = reflectivityOut.microSurface;\n float roughness = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\r\n`,t}_buildBlock(e){var t,i,n,s,r,o,a,l,h,c,u,d,p,f,_,m,g,v,y,x,b,T,S,E,C,A,P,R,M,I,D,O,w,N,F,L,B,U,V,k,G;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=(0,Bd.$)(this._scene));const z=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;if(z&&(z.worldPositionConnectionPoint=this.worldPosition,z.cameraPositionConnectionPoint=this.cameraPosition,z.worldNormalConnectionPoint=this.worldNormal,z.viewConnectionPoint=this.view),e.target!==ru.u.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 W=`//${this.name}`,H=this.perturbedNormal;let X=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(X=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${X};\r\n`,W),e.compilationString+=`${X} = ${this.worldPosition.associatedVariableName}.xyz;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+="#if DEBUGMODE > 0\r\n",e.compilationString+="vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\r\n",e.compilationString+="#endif\r\n"):X="v_"+X,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",W),e._emitFunctionFromInclude("importanceSampling",W),e._emitFunctionFromInclude("pbrHelperFunctions",W),e._emitFunctionFromInclude("imageProcessingDeclaration",W),e._emitFunctionFromInclude("imageProcessingFunctions",W),e._emitFunctionFromInclude("shadowsFragmentFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",W),e._emitFunctionFromInclude("pbrBRDFFunctions",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(i=null==z?void 0:z._defineSkyboxName)&&void 0!==i?i:"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",W),e._emitFunctionFromInclude("pbrDirectLightingFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",W),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",W),e._emitFunctionFromInclude("pbrBlockReflectivity",W),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",W),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",W),e._emitFunctionFromInclude("pbrBlockAnisotropic",W),e._emitUniformFromString("vLightingIntensity","vec4"),(null==z?void 0:z.generateOnlyFragmentCode)&&(e.compilationString+=z.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\r\n`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${X}.xyz);\r\n`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz;\r\n`,e.compilationString+=`vec3 normalW = ${H.isConnected?"normalize("+H.associatedVariableName+".xyz)":"geometricNormalW"};\r\n`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",W),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",W),e.compilationString+="#ifdef UNLIT\n vec3 diffuseBase = vec3(1., 1., 1.);\n #else\r\n",e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(n=null==z?void 0:z._defineSkyboxName)&&void 0!==n?n:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(s=null==z?void 0:z._define3DName)&&void 0!==s?s:"REFLECTIONMAP_3D"}]});const j=this.anisotropy.isConnected?null===(r=this.anisotropy.connectedPoint)||void 0===r?void 0:r.ownerBlock:null;j&&(j.worldPositionConnectionPoint=this.worldPosition,j.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=j.getCode(e,!this.perturbedNormal.isConnected)),z&&z.hasTexture&&(e.compilationString+=z.getCode(e,j?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(o=null==z?void 0:z._define3DName)&&void 0!==o?o:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(a=null==z?void 0:z._defineOppositeZ)&&void 0!==a?a:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(l=null==z?void 0:z._defineProjectionName)&&void 0!==l?l:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(h=null==z?void 0:z._defineSkyboxName)&&void 0!==h?h:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(c=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==c?c:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(u=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==u?u:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:null!==(d=null==z?void 0:z._vReflectionFilteringInfoName)&&void 0!==d?d:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",W,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const Y=this.sheen.isConnected?null===(p=this.sheen.connectedPoint)||void 0===p?void 0:p.ownerBlock:null;Y&&(e.compilationString+=Y.getCode(z)),e._emitFunctionFromInclude("pbrBlockSheen",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(f=null==z?void 0:z._define3DName)&&void 0!==f?f:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(_=null==z?void 0:z._defineSkyboxName)&&void 0!==_?_:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(m=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==m?m:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(g=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==g?g:"LINEARSPECULARREFLECTION"}]});const q=this.iridescence.isConnected?null===(v=this.iridescence.connectedPoint)||void 0===v?void 0:v.ownerBlock:null;e.compilationString+=Gd.GetCode(q),e._emitFunctionFromInclude("pbrBlockIridescence",W,{replaceStrings:[]});const K=this.clearcoat.isConnected?null===(y=this.clearcoat.connectedPoint)||void 0===y?void 0:y.ownerBlock:null,$=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Q=this.perturbedNormal.isConnected&&(null===(b=(null===(x=this.perturbedNormal.connectedPoint)||void 0===x?void 0:x.ownerBlock).worldTangent)||void 0===b?void 0:b.isConnected),Z=this.anisotropy.isConnected&&(null===(T=this.anisotropy.connectedPoint)||void 0===T?void 0:T.ownerBlock).worldTangent.isConnected;let J=Q||!this.perturbedNormal.isConnected&&Z;e.compilationString+=kd.GetCode(e,K,z,X,$,J,this.worldNormal.associatedVariableName),$&&(J=null!==(S=null==K?void 0:K.worldTangent.isConnected)&&void 0!==S&&S),e._emitFunctionFromInclude("pbrBlockClearcoat",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(E=null==z?void 0:z._define3DName)&&void 0!==E?E:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(C=null==z?void 0:z._defineOppositeZ)&&void 0!==C?C:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(A=null==z?void 0:z._defineProjectionName)&&void 0!==A?A:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(P=null==z?void 0:z._defineSkyboxName)&&void 0!==P?P:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(R=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==R?R:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(M=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==M?M:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:J?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(I=null==z?void 0:z._defineSkyboxName)&&void 0!==I?I:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(D=null==z?void 0:z._define3DName)&&void 0!==D?D:"REFLECTIONMAP_3D"}]});const ee=this.subsurface.isConnected?null===(O=this.subsurface.connectedPoint)||void 0===O?void 0:O.ownerBlock:null,te=this.subsurface.isConnected?null===(N=(null===(w=this.subsurface.connectedPoint)||void 0===w?void 0:w.ownerBlock).refraction.connectedPoint)||void 0===N?void 0:N.ownerBlock:null;te&&(te.viewConnectionPoint=this.view,te.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=Wd.GetCode(e,ee,z,X),e._emitFunctionFromInclude("pbrBlockSubSurface",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(F=null==z?void 0:z._define3DName)&&void 0!==F?F:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(L=null==z?void 0:z._defineOppositeZ)&&void 0!==L?L:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(B=null==z?void 0:z._defineProjectionName)&&void 0!==B?B:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:null!==(U=null==te?void 0:te._define3DName)&&void 0!==U?U:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:null!==(V=null==te?void 0:te._defineLODRefractionAlpha)&&void 0!==V?V:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:null!==(k=null==te?void 0:te._defineLinearSpecularRefraction)&&void 0!==k?k:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:null!==(G=null==te?void 0:te._defineOppositeZ)&&void 0!==G?G:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",W),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{repeatKey:"maxSimultaneousLights"}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",W),e.compilationString+="#endif\r\n";const ie=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let ne=nc.m.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===ne.indexOf(".")&&(ne+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",W,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:ie+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:ne}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",W,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",W,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",W,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:X},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\r\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\r\n"}]});for(const t of this._outputs)if(t.hasEndpoints){const i=Hd[t.name];if(i){const[n,s]=i;s&&(e.compilationString+=`#if ${s}\r\n`),e.compilationString+=`${this._declareOutput(t,e)} = ${n};\r\n`,s&&(e.compilationString+="#else\r\n",e.compilationString+=`${this._declareOutput(t,e)} = vec3(0.);\r\n`,e.compilationString+="#endif\r\n")}else console.error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\r\n`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\r\n`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\r\n`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\r\n`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\r\n`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\r\n`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\r\n`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\r\n`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\r\n`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\r\n`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\r\n`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\r\n`,e+=`${this._codeVariableName}.unlit = ${this.unlit};\r\n`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\r\n`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};\r\n`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};\r\n`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};\r\n`,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 n,s;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=null!==(n=e.lightFalloff)&&void 0!==n?n: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=null!==(s=e.realTimeFilteringQuality)&&void 0!==s?s: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()}}(0,be.gn)([(0,xu.p)("Direct lights",xu.U.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Xd.prototype,"directIntensity",void 0),(0,be.gn)([(0,xu.p)("Environment lights",xu.U.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Xd.prototype,"environmentIntensity",void 0),(0,be.gn)([(0,xu.p)("Specular highlights",xu.U.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Xd.prototype,"specularIntensity",void 0),(0,be.gn)([(0,xu.p)("Light falloff",xu.U.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:nc.m.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:nc.m.LIGHTFALLOFF_GLTF},{label:"Standard",value:nc.m.LIGHTFALLOFF_STANDARD}]})],Xd.prototype,"lightFalloff",void 0),(0,be.gn)([(0,xu.p)("Alpha Testing",xu.U.Boolean,"OPACITY")],Xd.prototype,"useAlphaTest",void 0),(0,be.gn)([(0,xu.p)("Alpha CutOff",xu.U.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],Xd.prototype,"alphaTestCutoff",void 0),(0,be.gn)([(0,xu.p)("Alpha blending",xu.U.Boolean,"OPACITY")],Xd.prototype,"useAlphaBlending",void 0),(0,be.gn)([(0,xu.p)("Radiance over alpha",xu.U.Boolean,"RENDERING",{notifiers:{update:!0}})],Xd.prototype,"useRadianceOverAlpha",void 0),(0,be.gn)([(0,xu.p)("Specular over alpha",xu.U.Boolean,"RENDERING",{notifiers:{update:!0}})],Xd.prototype,"useSpecularOverAlpha",void 0),(0,be.gn)([(0,xu.p)("Specular anti-aliasing",xu.U.Boolean,"RENDERING",{notifiers:{update:!0}})],Xd.prototype,"enableSpecularAntiAliasing",void 0),(0,be.gn)([(0,xu.p)("Realtime filtering",xu.U.Boolean,"RENDERING",{notifiers:{update:!0}})],Xd.prototype,"realTimeFiltering",void 0),(0,be.gn)([(0,xu.p)("Realtime filtering quality",xu.U.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],Xd.prototype,"realTimeFilteringQuality",void 0),(0,be.gn)([(0,xu.p)("Energy Conservation",xu.U.Boolean,"ADVANCED",{notifiers:{update:!0}})],Xd.prototype,"useEnergyConservation",void 0),(0,be.gn)([(0,xu.p)("Radiance occlusion",xu.U.Boolean,"ADVANCED",{notifiers:{update:!0}})],Xd.prototype,"useRadianceOcclusion",void 0),(0,be.gn)([(0,xu.p)("Horizon occlusion",xu.U.Boolean,"ADVANCED",{notifiers:{update:!0}})],Xd.prototype,"useHorizonOcclusion",void 0),(0,be.gn)([(0,xu.p)("Unlit",xu.U.Boolean,"ADVANCED",{notifiers:{update:!0}})],Xd.prototype,"unlit",void 0),(0,be.gn)([(0,xu.p)("Force normal forward",xu.U.Boolean,"ADVANCED",{notifiers:{update:!0}})],Xd.prototype,"forceNormalForward",void 0),(0,be.gn)([(0,xu.p)("Generate only fragment code",xu.U.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Xd._OnGenerateOnlyFragmentCodeChanged}})],Xd.prototype,"generateOnlyFragmentCode",void 0),(0,be.gn)([(0,xu.p)("Debug mode",xu.U.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}]})],Xd.prototype,"debugMode",void 0),(0,be.gn)([(0,xu.p)("Split position",xu.U.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],Xd.prototype,"debugLimit",void 0),(0,be.gn)([(0,xu.p)("Output factor",xu.U.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],Xd.prototype,"debugFactor",void 0),(0,l.H)("BABYLON.PBRMetallicRoughnessBlock",Xd);var jd,Yd,qd=i(7010),Kd=i(8560),$d=i(1320);class Qd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("left",ou.E.AutoDetect),this.registerInput("right",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}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});\r\n`,this}}(0,l.H)("BABYLON.ModBlock",Qd);class Zd extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("row0",ou.E.Vector4),this.registerInput("row1",ou.E.Vector4),this.registerInput("row2",ou.E.Vector4),this.registerInput("row3",ou.E.Vector4),this.registerOutput("output",ou.E.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 fu.S("row0");e.value=new o.Lt(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new fu.S("row1");e.value=new o.Lt(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new fu.S("row2");e.value=new o.Lt(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new fu.S("row3");e.value=new o.Lt(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,n=this.row1,s=this.row2,r=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${n.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName});\r\n`,this}}(0,l.H)("BABYLON.MatrixBuilder",Zd),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(jd||(jd={}));class Jd extends du.k{constructor(e){super(e,ru.u.Neutral),this.condition=jd.LessThan,this.registerInput("a",ou.E.Float),this.registerInput("b",ou.E.Float),this.registerInput("true",ou.E.AutoDetect,!0),this.registerInput("false",ou.E.AutoDetect,!0),this.registerOutput("output",ou.E.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=ou.E.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",n=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case jd.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case jd.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case jd.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case jd.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case jd.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case jd.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case jd.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${n};\r\n`;break;case jd.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${n};\r\n`;break;case jd.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${n};\r\n`}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.${jd[this.condition]};\r\n`}}(0,l.H)("BABYLON.ConditionalBlock",Jd);class ep extends du.k{constructor(e){super(e,ru.u.Neutral),this.octaves=6,this.registerInput("seed",ou.E.AutoDetect),this.registerInput("chaos",ou.E.AutoDetect,!0),this.registerInput("offsetX",ou.E.Float,!0),this.registerInput("offsetY",ou.E.Float,!0),this.registerInput("offsetZ",ou.E.Float,!0),this.registerOutput("output",ou.E.Float),this._inputs[0].acceptedConnectionPointTypes.push(ou.E.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(ou.E.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)return;if(!this._outputs[0].hasEndpoints)return;const n=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode","\n\n float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise(in vec2 x, in vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise(in vec3 x, in vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }","// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,"\n float fbm(in vec2 st, in vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise(st, chaos);\n st *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm(in vec3 x, in vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n for (int i = 0; i < OCTAVES; ++i) {\n value += amplitude * cloudNoise(x, chaos);\n x = x * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }".replace(/fbm/gi,n).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");const s=e._getFreeVariableName("st"),r=(null===(t=this.seed.connectedPoint)||void 0===t?void 0:t.type)===ou.E.Vector2?"vec2":"vec3";e.compilationString+=`${r} ${s} = ${this.seed.associatedVariableName};\r\n`,this.offsetX.isConnected&&(e.compilationString+=`${s}.x += 0.1 * ${this.offsetX.associatedVariableName};\r\n`),this.offsetY.isConnected&&(e.compilationString+=`${s}.y += 0.1 * ${this.offsetY.associatedVariableName};\r\n`),this.offsetZ.isConnected&&"vec3"===r&&(e.compilationString+=`${s}.z += 0.1 * ${this.offsetZ.associatedVariableName};\r\n`);let o="";return o=this.chaos.isConnected?this.chaos.associatedVariableName:(null===(i=this.seed.connectedPoint)||void 0===i?void 0:i.type)===ou.E.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${n}(${s}, ${o});\r\n`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};\r\n`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}(0,be.gn)([(0,xu.p)("Octaves",xu.U.Int)],ep.prototype,"octaves",void 0),(0,l.H)("BABYLON.CloudBlock",ep);class tp extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("seed",ou.E.Vector2),this.registerInput("offset",ou.E.Float),this.registerInput("density",ou.E.Float),this.registerOutput("output",ou.E.Float),this.registerOutput("cells",ou.E.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){\n mat2 m = mat2(15.27, 47.63, 99.41, 89.98);\n vec2 uv = fract(sin(m * seed) * 46839.32);\n return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5);\n }\n ";e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t="void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\n vec2 g = floor(seed * density);\n vec2 f = fract(seed * density);\n float t = 8.0;\n vec3 res = vec3(8.0, 0.0, 0.0);\n\n for(int y=-1; y<=1; y++)\n {\n for(int x=-1; x<=1; x++)\n {\n vec2 lattice = vec2(x,y);\n vec2 randomOffset = voronoiRandom(lattice + g, offset);\n float d = distance(lattice + randomOffset, f);\n if(d < res.x)\n {\n res = vec3(d, randomOffset.x, randomOffset.y);\n outValue = res.x;\n cells = res.y;\n }\n }\n }\n }\n ",e._emitFunction("voronoi",t,"// Voronoi");const i=e._getFreeVariableName("tempOutput"),n=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0;\r\n`,e.compilationString+=`float ${n} = 0.0;\r\n`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${n});\r\n`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i};\r\n`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${n};\r\n`),this}}(0,l.H)("BABYLON.VoronoiNoiseBlock",tp);class ip extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("input",ou.E.AutoDetect),this.registerOutput("output",ou.E.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!==ru.u.VertexAndFragment)return t.target;if(e.connectedPoint.target!==ru.u.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){0==(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};\r\n`,this}}(0,l.H)("BABYLON.ElbowBlock",ip);class np extends du.k{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:A.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get textureY(){var e;return this.sourceY.isConnected?(null===(e=this.sourceY.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return(null===(e=this.sourceZ)||void 0===e?void 0:e.isConnected)?(null===(t=this.sourceY.connectedPoint)||void 0===t?void 0:t.ownerBlock).texture:null}_getImageSourceBlock(e){return(null==e?void 0: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 null!==(t=null===(e=this._getImageSourceBlock(this.sourceY))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get samplerZName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceZ))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:A.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:A.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,ru.u.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",ou.E.AutoDetect,!1),this.registerInput("normal",ou.E.AutoDetect,!1),this.registerInput("sharpness",ou.E.Float,!0),this.registerInput("source",ou.E.Object,!0,ru.u.VertexAndFragment,new uu("source",this,cu.Ab.Input,Lu,"ImageSourceBlock")),this.registerInput("sourceY",ou.E.Object,!0,ru.u.VertexAndFragment,new uu("sourceY",this,cu.Ab.Input,Lu,"ImageSourceBlock")),t||this.registerInput("sourceZ",ou.E.Object,!0,ru.u.VertexAndFragment,new uu("sourceZ",this,cu.Ab.Input,Lu,"ImageSourceBlock")),this.registerOutput("rgba",ou.E.Color4,ru.u.Neutral),this.registerOutput("rgb",ou.E.Color3,ru.u.Neutral),this.registerOutput("r",ou.E.Float,ru.u.Neutral),this.registerOutput("g",ou.E.Float,ru.u.Neutral),this.registerOutput("b",ou.E.Float,ru.u.Neutral),this.registerOutput("a",ou.E.Float,ru.u.Neutral),this.registerOutput("level",ou.E.Float,ru.u.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Vector3|ou.E.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ou.E.Color3|ou.E.Vector3|ou.E.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 n=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,n,!0),i.setValue(this._gammaDefineName,s,!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 n=this.samplerName,s=null!==(t=this.samplerYName)&&void 0!==t?t:n,r=null!==(i=this.samplerZName)&&void 0!==i?i:n,o=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",a=e._getFreeVariableName("x"),l=e._getFreeVariableName("y"),h=e._getFreeVariableName("z"),c=e._getFreeVariableName("w"),u=e._getFreeVariableName("n"),d=e._getFreeVariableName("uvx"),p=e._getFreeVariableName("uvy"),f=e._getFreeVariableName("uvz");e.compilationString+=`\n vec3 ${u} = ${this.normal.associatedVariableName}.xyz;\n\n vec2 ${d} = ${this.position.associatedVariableName}.yz;\n vec2 ${p} = ${this.position.associatedVariableName}.zx;\n vec2 ${f} = ${this.position.associatedVariableName}.xy;\n `,this.projectAsCube&&(e.compilationString+=`\n ${d}.xy = ${d}.yx;\n\n if (${u}.x >= 0.0) {\n ${d}.x = -${d}.x;\n }\n if (${u}.y < 0.0) {\n ${p}.y = -${p}.y;\n }\n if (${u}.z < 0.0) {\n ${f}.x = -${f}.x;\n }\n `),e.compilationString+=`\n vec4 ${a} = texture2D(${n}, ${d});\n vec4 ${l} = texture2D(${s}, ${p});\n vec4 ${h} = texture2D(${r}, ${f});\n \n // blend weights\n vec3 ${c} = pow(abs(${u}), vec3(${o}));\n\n // blend and return\n vec4 ${this._tempTextureRead} = (${a}*${c}.x + ${l}*${c}.y + ${h}*${c}.z) / (${c}.x + ${c}.y + ${c}.z); \n `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i){let n="";this.disableLevelMultiplication||(n=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${n};\r\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\r\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\r\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\r\n`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\r\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\r\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,e):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||"VideoTexture"===this.texture.getClassName()||(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&&!Fl.O.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Ce.x.Parse(e.texture,t,i))}}(0,be.gn)([(0,xu.p)("Project as cube",xu.U.Boolean,"ADVANCED",{notifiers:{update:!0}})],np.prototype,"projectAsCube",void 0),(0,l.H)("BABYLON.TriPlanarBlock",np);class sp extends np{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;const i=this.samplerName,n=null!==(t=this.samplerYName)&&void 0!==t?t:this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",r=e._getFreeVariableName("dpdx"),o=e._getFreeVariableName("dpdy"),a=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),c=e._getFreeVariableName("me"),u=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),p=e._getFreeVariableName("y");e.compilationString+=`\n // grab coord derivatives for texturing\n vec3 ${r} = dFdx(${this.position.associatedVariableName}.xyz);\n vec3 ${o} = dFdy(${this.position.associatedVariableName}.xyz);\n vec3 ${a} = abs(${this.normal.associatedVariableName}.xyz);\n \n // determine major axis (in x; yz are following axis)\n ivec3 ${l} = (${a}.x>${a}.y && ${a}.x>${a}.z) ? ivec3(0,1,2) :\n (${a}.y>${a}.z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine minor axis (in x; yz are following axis)\n ivec3 ${h} = (${a}.x<${a}.y && ${a}.x<${a}.z) ? ivec3(0,1,2) :\n (${a}.y<${a}.z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine median axis (in x; yz are following axis)\n ivec3 ${c} = ivec3(3) - ${h} - ${l};\n \n // project+fetch\n vec4 ${u} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), \n vec2(${r}[${l}.y],${r}[${l}.z]), \n vec2(${o}[${l}.y],${o}[${l}.z]) );\n vec4 ${d} = textureGrad( ${n}, vec2( ${this.position.associatedVariableName}[${c}.y], ${this.position.associatedVariableName}[${c}.z]), \n vec2(${r}[${c}.y],${r}[${c}.z]),\n vec2(${o}[${c}.y],${o}[${c}.z]) );\n \n // blend factors\n vec2 ${p} = vec2(${a}[${l}.x],${a}[${c}.x]);\n // make local support\n ${p} = clamp( (${p}-0.5773)/(1.0-0.5773), 0.0, 1.0 );\n // shape transition\n ${p} = pow( ${p}, vec2(${s}/8.0) );\n // blend and return\n vec4 ${this._tempTextureRead} = (${u}*${p}.x + ${d}*${p}.y) / (${p}.x + ${p}.y);\n `}}(0,l.H)("BABYLON.BiPlanarBlock",sp);class rp extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("input",ou.E.Matrix),this.registerOutput("output",ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.MatrixDeterminantBlock",rp);class op extends du.k{constructor(e){super(e,ru.u.Neutral),this.registerInput("input",ou.E.Matrix),this.registerOutput("output",ou.E.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});\r\n`,this}}(0,l.H)("BABYLON.MatrixTransposeBlock",op),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(Yd||(Yd={}));class ap extends du.k{constructor(e){super(e,ru.u.Neutral),this.attributeType=Yd.None,this.registerInput("input",ou.E.AutoDetect),this.registerInput("fallback",ou.E.AutoDetect),this.registerOutput("output",ou.E.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add((e=>{var t;if(this.attributeType)return;const i=e.ownerBlock;if(i instanceof fu.S&&i.isAttribute)switch(i.name){case"color":this.attributeType=Yd.VertexColor;break;case"normal":this.attributeType=Yd.Normal;break;case"tangent":this.attributeType=Yd.Tangent;break;case"uv":this.attributeType=Yd.UV1;break;case"uv2":this.attributeType=Yd.UV2;break;case"uv3":this.attributeType=Yd.UV3;break;case"uv4":this.attributeType=Yd.UV4;break;case"uv5":this.attributeType=Yd.UV5;break;case"uv6":this.attributeType=Yd.UV6}else if(i instanceof gu)switch(null===(t=this.input.connectedPoint)||void 0===t?void 0:t.name){case"normalOutput":this.attributeType=Yd.Normal;break;case"tangentOutput":this.attributeType=Yd.Tangent;break;case"uvOutput":this.attributeType=Yd.UV1}}))}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 Yd.VertexColor:t="VERTEXCOLOR_NME";break;case Yd.Normal:t="NORMAL";break;case Yd.Tangent:t="TANGENT";break;case Yd.UV1:t="UV1";break;case Yd.UV2:t="UV2";break;case Yd.UV3:t="UV3";break;case Yd.UV4:t="UV4";break;case Yd.UV5:t="UV5";break;case Yd.UV6:t="UV6"}const i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t}\r\n`),e.compilationString+=`${i} = ${this.input.associatedVariableName};\r\n`,t&&(e.compilationString+="#else\r\n",e.compilationString+=`${i} = ${this.fallback.associatedVariableName};\r\n`,e.compilationString+="#endif\r\n"),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){var n;super._deserialize(e,t,i),this.attributeType=null!==(n=e.attributeType)&&void 0!==n?n:Yd.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};\r\n`,e}}(0,be.gn)([(0,xu.p)("Attribute lookup",xu.U.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:Yd.None},{label:"Normal",value:Yd.Normal},{label:"Tangent",value:Yd.Tangent},{label:"Vertex Color",value:Yd.VertexColor},{label:"UV1",value:Yd.UV1},{label:"UV2",value:Yd.UV2},{label:"UV3",value:Yd.UV3},{label:"UV4",value:Yd.UV4},{label:"UV5",value:Yd.UV5},{label:"UV6",value:Yd.UV6}]})],ap.prototype,"attributeType",void 0),(0,l.H)("BABYLON.MeshAttributeExistsBlock",ap);class lp{optimize(e,t){}}var hp=i(1983);class cp{constructor(){this.mm=new Map}get(e,t){const i=this.mm.get(e);if(void 0!==i)return i.get(t)}set(e,t,i){let n=this.mm.get(e);void 0===n&&this.mm.set(e,n=new Map),n.set(t,i)}}class up{get standalone(){var e,t;return null!==(t=null===(e=this._options)||void 0===e?void 0:e.standalone)&&void 0!==t&&t}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){var e,t;return null!==(t=null===(e=this._options)||void 0===e?void 0:e.doNotInjectCode)&&void 0!==t&&t}constructor(e,t,i){this._baseMaterial=e,this._scene=null!=t?t:A.l.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new cp,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add((e=>{var t;const i=null===(t=e.subMesh)||void 0===t?void 0:t.getMesh();i&&!this._meshes.has(i)&&this._meshes.set(i,i.onDisposeObservable.add((e=>{const t=this._subMeshToEffect.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value;(null==t?void 0:t.getMesh())===e&&(this._subMeshToEffect.delete(t),this._subMeshToDepthWrapper.mm.delete(t))}}))),this._subMeshToEffect.set(e.subMesh,[e.effect,this._scene.getEngine().currentRenderPassId]),this._subMeshToDepthWrapper.mm.delete(e.subMesh)}))}getEffect(e,t,i){var n;const s=null===(n=this._subMeshToDepthWrapper.mm.get(e))||void 0===n?void 0:n.get(t);if(!s)return null;let r=s.drawWrapper[i];return r||(r=s.drawWrapper[i]=new Ps.q(this._scene.getEngine()),r.setEffect(s.mainDrawWrapper.effect,s.mainDrawWrapper.defines)),r}isReadyForSubMesh(e,t,i,n,s){var r,o;return!(this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,n))&&null!==(o=null===(r=this._makeEffect(e,t,i,s))||void 0===r?void 0:r.isReady())&&void 0!==o&&o}dispose(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;const e=this._meshes.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;e.onDisposeObservable.remove(i)}}_makeEffect(e,t,i,n){var s,r,o;const a=this._scene.getEngine(),l=this._subMeshToEffect.get(e);if(!l)return null;const[h,c]=l;let u=this._subMeshToDepthWrapper.get(e,i);if(!u){const t=new Ps.q(a);t.defines=null!==(r=null===(s=e._getDrawWrapper(c))||void 0===s?void 0:s.defines)&&void 0!==r?r:null,u={drawWrapper:[],mainDrawWrapper:t,depthDefines:"",token:(0,hp.f)()},u.drawWrapper[n]=t,this._subMeshToDepthWrapper.set(e,i,u)}const d=t.join("\n");if(u.mainDrawWrapper.effect&&d===u.depthDefines)return u.mainDrawWrapper.effect;u.depthDefines=d;const p=h.getUniformNames().slice();let f=h.vertexSourceCodeBeforeMigration,_=h.fragmentSourceCodeBeforeMigration;if(!this.doNotInjectCode){const e=this._options&&this._options.remappedVariables?`#include<shadowMapVertexNormalBias>(${this._options.remappedVariables.join(",")})`:ds.Q.IncludesShadersStore.shadowMapVertexNormalBias,t=this._options&&this._options.remappedVariables?`#include<shadowMapVertexMetric>(${this._options.remappedVariables.join(",")})`:ds.Q.IncludesShadersStore.shadowMapVertexMetric,i=this._options&&this._options.remappedVariables?`#include<shadowMapFragmentSoftTransparentShadow>(${this._options.remappedVariables.join(",")})`:ds.Q.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow,n=ds.Q.IncludesShadersStore.shadowMapFragment;f=f.replace(/void\s+?main/g,ds.Q.IncludesShadersStore.shadowMapVertexExtraDeclaration+"\r\nvoid main"),f=f.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,e),f=-1!==f.indexOf("#define SHADOWDEPTH_METRIC")?f.replace(/#define SHADOWDEPTH_METRIC/g,t):f.replace(/}\s*$/g,t+"\r\n}"),f=f.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const s=_.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||_.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,r=-1!==_.indexOf("#define SHADOWDEPTH_FRAGMENT");let o="";s?_=_.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,i):o=i+"\r\n",_=_.replace(/void\s+?main/g,ds.Q.IncludesShadersStore.shadowMapFragmentExtraDeclaration+"\r\nvoid main"),r?_=_.replace(/#define SHADOWDEPTH_FRAGMENT/g,n):o+=n+"\r\n",o&&(_=_.replace(/}\s*$/g,o+"}")),p.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}u.mainDrawWrapper.effect=a.createEffect({vertexSource:f,fragmentSource:_,vertexToken:u.token,fragmentToken:u.token},{attributes:h.getAttributesNames(),uniformsNames:p,uniformBuffersNames:h.getUniformBuffersNames(),samplers:h.getSamplers(),defines:d+"\n"+h.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:h.getIndexParameters()},a);for(let e=0;e<u.drawWrapper.length;++e)e!==n&&(null===(o=u.drawWrapper[e])||void 0===o||o.setEffect(u.mainDrawWrapper.effect,u.mainDrawWrapper.defines));return u.mainDrawWrapper.effect}}var dp=i(8449),pp=i(9249),fp=i(1698),_p=i(6150);class mp extends Ba.H{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class gp extends dp.n{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new mp,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,n){const s=n.getMesh().decalMap;return!(this._isEnabled&&(null==s?void 0:s.texture)&&Va.k.DecalMapEnabled&&t.texturesEnabled)||s.isReady()}prepareDefines(e,t,i){const n=i.decalMap;this._isEnabled&&(null==n?void 0:n.texture)&&Va.k.DecalMapEnabled&&t.texturesEnabled?((!e.DECAL||e.GAMMADECAL!==n.texture.gammaSpace)&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=n.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,La.G.PrepareDefinesForMergedUV(n.texture,e,"DECAL")):(e.DECAL&&e.markAsTexturesDirty(),e.DECAL=!1)}hardBindForSubMesh(e,t,i,n){const s=n.getMesh().decalMap;if(!(this._isEnabled&&(null==s?void 0:s.texture)&&Va.k.DecalMapEnabled&&t.texturesEnabled))return;const r=this._material.isFrozen,o=s.texture;e.useUbo&&r&&e.isSync||(e.updateFloat4("vDecalInfos",o.coordinatesIndex,0,0,0),La.G.BindTextureMatrix(o,e,"decal")),e.setTexture("decalSampler",o)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],gp.prototype,"isEnabled",void 0),(0,be.gn)([(0,Te.qC)(),(0,Te.wz)("_markAllSubMeshesAsTexturesDirty")],gp.prototype,"smoothAlpha",void 0);var vp=i(1444);function yp(e){return e instanceof nc.m?new ic.u(e):null}function xp(e){return e instanceof nc.m?new vp.d(e):null}function bp(e){return e instanceof nc.m?new rc.Y(e):null}function Tp(e){return e instanceof nc.m?new oc.B(e):null}function Sp(e){return e instanceof nc.m?new hc.B(e):null}function Ep(e){return e instanceof nc.m?new cc.u(e):null}function Cp(e){return e instanceof nc.m||e instanceof Gi.K?new _p.p(e):null}Object.defineProperty(Gi.K.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new gp(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(nc.m.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new gp(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Un.x.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});var Ap=i(1372);class Pp{constructor(e,t){this.radius=e,this.theta=t}getClassName(){return"Polar"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t}add(e){const t=new Pp(0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t){return this.radius+=e,this.theta+=t,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t}subtract(e){const t=new Pp(0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i){return i.radius=this.radius-e,i.theta=this.theta-t,i}subtractFromFloats(e,t){const i=new Pp(0,0);return this.subtractFromFloatsToRef(e,t,i),i}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t}multiply(e){const t=new Pp(0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t}divide(e){const t=new Pp(0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new Pp(this.radius,this.theta)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this}copyFromFloats(e,t){return this.radius=e,this.theta=t,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t}scale(e){const t=new Pp(0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t){return this.radius=e,this.theta=t,this}setAll(e){return this.set(e,e),this}toVector2ToRef(e){const t=this.radius*Math.cos(this.theta),i=this.radius*Math.sin(this.theta);return e.set(t,i),e}toVector2(){const e=new o.FM(0,0);return this.toVector2ToRef(e)}static FromVector2ToRef(e,t){const i=Math.sign(e.y)*Math.acos(e.x/e.length());return t.radius=e.length(),t.theta=i,t}static FromVector2(e){const t=new Pp(0,0);return Pp.FromVector2ToRef(e,t),t}static FromArray(e){return new Pp(e[0],e[1])}}class Rp{constructor(e,t,i){this.radius=e,this.theta=t,this.phi=i}getClassName(){return"Spherical"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta,this.phi]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t.phi=this.phi+e.phi,t}add(e){const t=new Rp(0,0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t,i){return this.radius+=e,this.theta+=t,this.phi+=i,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t.phi=this.phi-e.phi,t}subtract(e){const t=new Rp(0,0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i,n){return n.radius=this.radius-e,n.theta=this.theta-t,n.phi=this.phi-i,n}subtractFromFloats(e,t,i){const n=new Rp(0,0,0);return this.subtractFromFloatsToRef(e,t,i,n),n}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t.phi=this.phi*e.phi,t}multiply(e){const t=new Rp(0,0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t.phi=this.phi/e.phi,t}divide(e){const t=new Rp(0,0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new Rp(this.radius,this.theta,this.phi)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this.phi=e.phi,this}copyFromFloats(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t.phi=this.phi*e,t}scale(e){const t=new Rp(0,0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}setAll(e){return this.set(e,e,e),this}toVector3ToRef(e){const t=this.radius*Math.sin(this.theta)*Math.cos(this.phi),i=this.radius*Math.cos(this.theta),n=this.radius*Math.sin(this.theta)*Math.sin(this.phi);return e.set(t,i,n),e}toVector3(){const e=new o.P(0,0,0);return this.toVector3ToRef(e)}static FromVector3ToRef(e,t){return t.radius=e.length(),t.theta=Math.acos(e.y/t.radius),t.phi=Math.atan2(e.z,e.x),t}static FromVector3(e){const t=new Rp(0,0,0);return Rp.FromVector3ToRef(e,t),t}static FromArray(e){return new Rp(e[0],e[1],e[2])}}var Mp=i(1500),Ip=i(9481);let Dp=0;class Op{constructor(e,t,i,n){this.pos=e,this.normal=t,this.uv=i,this.vertColor=n}clone(){var e,t;return new Op(this.pos.clone(),this.normal.clone(),null===(e=this.uv)||void 0===e?void 0:e.clone(),null===(t=this.vertColor)||void 0===t?void 0:t.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new Op(o.P.Lerp(this.pos,e.pos,t),o.P.Lerp(this.normal,e.normal,t),this.uv&&e.uv?o.FM.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?a.HE.Lerp(this.vertColor,e.vertColor,t):void 0)}}class wp{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const n=i.subtract(e),s=t.subtract(e);if(0===n.lengthSquared()||0===s.lengthSquared())return null;const r=o.P.Normalize(o.P.Cross(n,s));return new wp(r,o.P.Dot(r,e))}clone(){return new wp(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,n,s){let r=0;const a=[];let l,h;for(l=0;l<e.vertices.length;l++){h=o.P.Dot(this.normal,e.vertices[l].pos)-this.w;const t=h<-wp.EPSILON?2:h>wp.EPSILON?1:0;r|=t,a.push(t)}switch(r){case 0:(o.P.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:n.push(e);break;case 2:s.push(e);break;case 3:{const t=[],i=[];for(l=0;l<e.vertices.length;l++){const n=(l+1)%e.vertices.length,s=a[l],r=a[n],c=e.vertices[l],u=e.vertices[n];if(2!==s&&t.push(c),1!==s&&i.push(2!==s?c.clone():c),3==(s|r)){h=(this.w-o.P.Dot(this.normal,c.pos))/o.P.Dot(this.normal,u.pos.subtract(c.pos));const e=c.interpolate(u,h);t.push(e),i.push(e.clone())}}let r;t.length>=3&&(r=new Np(t,e.shared),r.plane&&n.push(r)),i.length>=3&&(r=new Np(i,e.shared),r.plane&&s.push(r));break}}}}wp.EPSILON=1e-5;class Np{constructor(e,t){this.vertices=e,this.shared=t,this.plane=wp.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map((e=>e.clone()));return new Np(e,this.shared)}flip(){this.vertices.reverse().map((e=>{e.flip()})),this.plane.flip()}}class Fp{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new Fp;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((e=>e.clone())),e}invert(){for(let e=0;e<this._polygons.length;e++)this._polygons[e].flip();this._plane&&this._plane.flip(),this._front&&this._front.invert(),this._back&&this._back.invert();const e=this._front;this._front=this._back,this._back=e}clipPolygons(e){if(!this._plane)return e.slice();let t=new Array,i=new Array;for(let n=0;n<e.length;n++)this._plane.splitPolygon(e[n],t,i,t,i);return this._front&&(t=this._front.clipPolygons(t)),i=this._back?this._back.clipPolygons(i):[],t.concat(i)}clipTo(e){this._polygons=e.clipPolygons(this._polygons),this._front&&this._front.clipTo(e),this._back&&this._back.clipTo(e)}allPolygons(){let e=this._polygons.slice();return this._front&&(e=e.concat(this._front.allPolygons())),this._back&&(e=e.concat(this._back.allPolygons())),e}build(e){if(!e.length)return;this._plane||(this._plane=e[0].plane.clone());const t=new Array,i=new Array;for(let n=0;n<e.length;n++)this._plane.splitPolygon(e[n],this._polygons,this._polygons,t,i);t.length&&(this._front||(this._front=new Fp),this._front.build(t)),i.length&&(this._back||(this._back=new Fp),this._back.build(i))}}class Lp{constructor(){this._polygons=new Array}static FromMesh(e,t=!1){let i,n,s,r,l,h,c;const u=new Array;let d,p,f,_,m=null,g=!1;if(!(e instanceof Nt.Kj))throw"BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh";e.computeWorldMatrix(!0),d=e.getWorldMatrix(),p=e.position.clone(),f=e.rotation.clone(),e.rotationQuaternion&&(m=e.rotationQuaternion.clone()),_=e.scaling.clone(),e.material&&t&&(g=0===e.material.sideOrientation);const v=e.getIndices(),y=e.getVerticesData(qe.o.PositionKind),x=e.getVerticesData(qe.o.NormalKind),b=e.getVerticesData(qe.o.UVKind),T=e.getVerticesData(qe.o.ColorKind),S=e.subMeshes;for(let e=0,t=S.length;e<t;e++)for(let t=S[e].indexStart,p=S[e].indexCount+S[e].indexStart;t<p;t+=3){c=[];for(let e=0;e<3;e++){const h=0===e?t+e:g?t+3-e:t+e,u=new o.P(x[3*v[h]],x[3*v[h]+1],x[3*v[h]+2]);b&&(s=new o.FM(b[2*v[h]],b[2*v[h]+1])),T&&(l=new a.HE(T[4*v[h]],T[4*v[h]+1],T[4*v[h]+2],T[4*v[h]+3]));const p=new o.P(y[3*v[h]],y[3*v[h]+1],y[3*v[h]+2]);r=o.P.TransformCoordinates(p,d),n=o.P.TransformNormal(u,d),i=new Op(r,n,s,l),c.push(i)}h=new Np(c,{subMeshId:e,meshId:Dp,materialIndex:S[e].materialIndex}),h.plane&&u.push(h)}const E=Lp._FromPolygons(u);return E.matrix=t?o.y3.Identity():d,E.position=t?o.P.Zero():p,E.rotation=t?o.P.Zero():f,E.scaling=t?o.P.One():_,E.rotationQuaternion=t&&m?o._f.Identity():m,Dp++,E}static _FromPolygons(e){const t=new Lp;return t._polygons=e,t}clone(){const e=new Lp;return e._polygons=this._polygons.map((e=>e.clone())),e.copyTransformAttributes(this),e}union(e){const t=new Fp(this.clone()._polygons),i=new Fp(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),Lp._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new Fp(this._polygons),i=new Fp(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 Fp(this.clone()._polygons),i=new Fp(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(),Lp._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new Fp(this._polygons),i=new Fp(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 Fp(this.clone()._polygons),i=new Fp(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),Lp._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new Fp(this._polygons),i=new Fp(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}buildMeshGeometry(e,t,i){const n=this.matrix.clone();n.invert();const s=new Nt.Kj(e,t),r=[],l=[],h=[];let c=null,u=null;const d=o.P.Zero(),p=o.P.Zero(),f=o.FM.Zero(),_=new a.HE(0,0,0,0),m=this._polygons,g=[0,0,0];let v;const y={};let x,b=0;const T={};let S;i&&m.sort(((e,t)=>e.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId));for(let e=0,t=m.length;e<t;e++){v=m[e],T[v.shared.meshId]||(T[v.shared.meshId]={}),T[v.shared.meshId][v.shared.subMeshId]||(T[v.shared.meshId][v.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:v.shared.materialIndex}),S=T[v.shared.meshId][v.shared.subMeshId];for(let e=2,t=v.vertices.length;e<t;e++){g[0]=0,g[1]=e-1,g[2]=e;for(let e=0;e<3;e++){d.copyFrom(v.vertices[g[e]].pos),p.copyFrom(v.vertices[g[e]].normal),v.vertices[g[e]].uv&&(c||(c=[]),f.copyFrom(v.vertices[g[e]].uv)),v.vertices[g[e]].vertColor&&(u||(u=[]),_.copyFrom(v.vertices[g[e]].vertColor));const t=o.P.TransformCoordinates(d,n),i=o.P.TransformNormal(p,n);x=y[t.x+","+t.y+","+t.z];let s=!1;c&&c[2*x]!==f.x&&c[2*x+1]!==f.y&&(s=!0);let a=!1;u&&u[4*x]!==_.r&&u[4*x+1]!==_.g&&u[4*x+2]!==_.b&&u[4*x+3]!==_.a&&(a=!0),(void 0===x||h[3*x]!==i.x||h[3*x+1]!==i.y||h[3*x+2]!==i.z||s||a)&&(r.push(t.x,t.y,t.z),c&&c.push(f.x,f.y),h.push(p.x,p.y,p.z),u&&u.push(_.r,_.g,_.b,_.a),x=y[t.x+","+t.y+","+t.z]=r.length/3-1),l.push(x),S.indexStart=Math.min(b,S.indexStart),S.indexEnd=Math.max(b,S.indexEnd),b++}}}if(s.setVerticesData(qe.o.PositionKind,r),s.setVerticesData(qe.o.NormalKind,h),c&&s.setVerticesData(qe.o.UVKind,c),u&&s.setVerticesData(qe.o.ColorKind,u),s.setIndices(l,null),i){let e,t=0;s.subMeshes=new Array;for(const i in T){e=-1;for(const n in T[i])S=T[i][n],Ll.P.CreateFromIndices(S.materialIndex+t,S.indexStart,S.indexEnd-S.indexStart+1,s),e=Math.max(S.materialIndex,e);t+=++e}}return s}toMesh(e,t=null,i,n){const s=this.buildMeshGeometry(e,i,n);return s.material=t,s.position.copyFrom(this.position),s.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(s.rotationQuaternion=this.rotationQuaternion.clone()),s.scaling.copyFrom(this.scaling),s.computeWorldMatrix(!0),s}}si.v.ShadersStore.meshUVSpaceRendererVertexShader="precision highp float;\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\nuniform mat4 projMatrix;\nvarying vec2 vDecalTC;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<instancesDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\nvec3 normalUpdated=normal;\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nmat3 normWorldSM=mat3(finalWorld);\nvec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));\nvNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);\nvec3 decalTC=(projMatrix*worldPos).xyz;\nvDecalTC=decalTC.xy;\ngl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);\n}\n";si.v.ShadersStore.meshUVSpaceRendererPixelShader="precision highp float;\nvarying vec2 vDecalTC;\nuniform sampler2D textureSampler;\nvoid main(void) {\nif (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {\ndiscard;\n}\ngl_FragColor=texture2D(textureSampler,vDecalTC);\n}\n";class Bp{static _GetShader(e){if(!e._meshUVSpaceRendererShader){const t=new us.j("meshUVSpaceRendererShader",e,{vertex:"meshUVSpaceRenderer",fragment:"meshUVSpaceRenderer"},{attributes:["position","normal","uv"],uniforms:["world","worldView","worldViewProjection","view","projection"],needAlphaBlending:!0});t.backFaceCulling=!1,t.alphaMode=2,e.onDisposeObservable.add((()=>{var t;null===(t=e._meshUVSpaceRendererShader)||void 0===t||t.dispose(),e._meshUVSpaceRendererShader=null})),e._meshUVSpaceRendererShader=t}return e._meshUVSpaceRendererShader}static _IsRenderTargetTexture(e){return void 0!==e.renderList}constructor(e,t,i){this._textureCreatedInternally=!1,this.clearColor=new a.HE(0,0,0,0),this._mesh=e,this._scene=t,this._options={width:1024,height:1024,textureType:0,generateMipMaps:!0,optimizeUVAllocation:!0,...i}}isReady(){var e,t;return Bp._GetShader(this._scene).isReady()&&(null===(t=null===(e=this.texture)||void 0===e?void 0:e.isReady())||void 0===t||t)}renderTexture(e,t,i,n,s=0){if(this.texture||this._createDiffuseRTT(),Bp._IsRenderTargetTexture(this.texture)){const r=this._createProjectionMatrix(t,i,n,s),o=Bp._GetShader(this._scene);o.setTexture("textureSampler",e),o.setMatrix("projMatrix",r),this.texture.render()}}clear(){if(Bp._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget){const e=this._scene.getEngine();e.bindFramebuffer(this.texture.renderTarget),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this.texture.renderTarget)}}dispose(){this._textureCreatedInternally&&(this.texture.dispose(),this._textureCreatedInternally=!1)}_createDiffuseRTT(){this._textureCreatedInternally=!0;const e=this._createRenderTargetTexture(this._options.width,this._options.height);e.setMaterialForRendering(this._mesh,Bp._GetShader(this._scene)),this.texture=e}_createRenderTargetTexture(e,t){const i=new Ai._(this._mesh.name+"_uvspaceTexture",{width:e,height:t},this._scene,this._options.generateMipMaps,!0,this._options.textureType,!1,this._options.generateMipMaps?3:2,!1,!1,!1,5);return i.optimizeUVAllocation=!!this._options.optimizeUVAllocation,i.onClearObservable.addOnce((()=>{this._scene.getEngine().clear(this.clearColor,!0,!0,!0),i.onClearObservable.add((()=>{}))})),i.renderList=[this._mesh],i}_createProjectionMatrix(e,t,i,n=0){const s=-Math.atan2(t.z,t.x)-Math.PI/2,r=Math.sqrt(t.x*t.x+t.z*t.z),a=Math.atan2(t.y,r),l=e.add(t.scale(.5*i.z)),h=o.y3.RotationYawPitchRoll(s,a,n).multiply(o.y3.Translation(l.x,l.y,l.z)),c=o.y3.Invert(h),u=o.y3.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),d=o.y3.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return c.multiply(u).multiply(d)}}var Up=i(8475);Nt.Kj._GoldbergMeshParser=(e,t)=>Vp.Parse(e,t);class Vp extends Nt.Kj{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(_.Y.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(_.Y.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(_.Y.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t<e.length;t++){const i=e[t][0],n=e[t][1],s=e[t][2];for(let e=i;e<n+1;e++)this.goldbergData.faceColors[e]=s}const t=[];for(let e=0;e<12;e++)for(let i=0;i<5;i++)t.push(this.goldbergData.faceColors[e].r,this.goldbergData.faceColors[e].g,this.goldbergData.faceColors[e].b,this.goldbergData.faceColors[e].a);for(let e=12;e<this.goldbergData.faceColors.length;e++)for(let i=0;i<6;i++)t.push(this.goldbergData.faceColors[e].r,this.goldbergData.faceColors[e].g,this.goldbergData.faceColors[e].b,this.goldbergData.faceColors[e].a);return t}setGoldbergFaceColors(e){const t=this._changeGoldbergFaceColors(e);this.setVerticesData(qe.o.ColorKind,t)}updateGoldbergFaceColors(e){const t=this._changeGoldbergFaceColors(e);this.updateVerticesData(qe.o.ColorKind,t)}_changeGoldbergFaceUVs(e){const t=this.getVerticesData(qe.o.UVKind);for(let i=0;i<e.length;i++){const n=e[i][0],s=e[i][1],r=e[i][2],o=e[i][3],a=e[i][4],l=[],h=[];let c,u;for(let e=0;e<5;e++)c=r.x+o*Math.cos(a+e*Math.PI/2.5),u=r.y+o*Math.sin(a+e*Math.PI/2.5),c<0&&(c=0),c>1&&(c=1),l.push(c,u);for(let e=0;e<6;e++)c=r.x+o*Math.cos(a+e*Math.PI/3),u=r.y+o*Math.sin(a+e*Math.PI/3),c<0&&(c=0),c>1&&(c=1),h.push(c,u);for(let e=n;e<Math.min(12,s+1);e++)for(let i=0;i<5;i++)t[10*e+2*i]=l[2*i],t[10*e+2*i+1]=l[2*i+1];for(let e=Math.max(12,n);e<s+1;e++)for(let i=0;i<6;i++)t[12*e-24+2*i]=h[2*i],t[12*e-23+2*i]=h[2*i+1]}return t}setGoldbergFaceUVs(e){const t=this._changeGoldbergFaceUVs(e);this.setVerticesData(qe.o.UVKind,t)}updateGoldbergFaceUVs(e){const t=this._changeGoldbergFaceUVs(e);this.updateVerticesData(qe.o.UVKind,t)}placeOnGoldbergFaceAt(e,t,i){const n=o.P.RotationFromAxis(this.goldbergData.faceXaxis[t],this.goldbergData.faceYaxis[t],this.goldbergData.faceZaxis[t]);e.rotation=n,e.position=this.goldbergData.faceCenters[t].add(this.goldbergData.faceXaxis[t].scale(i.x)).add(this.goldbergData.faceYaxis[t].scale(i.y)).add(this.goldbergData.faceZaxis[t].scale(i.z))}serialize(e){super.serialize(e),e.type="GoldbergMesh";const t={};if(t.adjacentFaces=this.goldbergData.adjacentFaces,t.nbSharedFaces=this.goldbergData.nbSharedFaces,t.nbUnsharedFaces=this.goldbergData.nbUnsharedFaces,t.nbFaces=this.goldbergData.nbFaces,t.nbFacesAtPole=this.goldbergData.nbFacesAtPole,this.goldbergData.faceColors){t.faceColors=[];for(const e of this.goldbergData.faceColors)t.faceColors.push(e.asArray())}if(this.goldbergData.faceCenters){t.faceCenters=[];for(const e of this.goldbergData.faceCenters)t.faceCenters.push(e.asArray())}if(this.goldbergData.faceZaxis){t.faceZaxis=[];for(const e of this.goldbergData.faceZaxis)t.faceZaxis.push(e.asArray())}if(this.goldbergData.faceYaxis){t.faceYaxis=[];for(const e of this.goldbergData.faceYaxis)t.faceYaxis.push(e.asArray())}if(this.goldbergData.faceXaxis){t.faceXaxis=[];for(const e of this.goldbergData.faceXaxis)t.faceXaxis.push(e.asArray())}e.goldbergData=t}static Parse(e,t){const i=e.goldbergData;i.faceColors=i.faceColors.map((e=>a.HE.FromArray(e))),i.faceCenters=i.faceCenters.map((e=>o.P.FromArray(e))),i.faceZaxis=i.faceZaxis.map((e=>o.P.FromArray(e))),i.faceXaxis=i.faceXaxis.map((e=>o.P.FromArray(e))),i.faceYaxis=i.faceYaxis.map((e=>o.P.FromArray(e)));const n=new Vp(e.name,t);return n.goldbergData=i,n}}class kp extends Nt.Kj{constructor(e,t,i,n=1,s=60,r=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=r,this._generator=t,this.diameter=n,this._length=s,this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=o.P.Zero(),this._sectionNormalVectors[e]=o.P.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new sn.x,t=[],i=[],n=[];let s=o.P.Zero();s=this._generator instanceof Un.x&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.position;const r=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<this._sectionPolygonPointsCount;e++)t.push(s.x+Math.cos(e*r)*this.diameter,s.y+Math.sin(e*r)*this.diameter,s.z);for(let e=1;e<=this._length;e++){for(let e=0;e<this._sectionPolygonPointsCount;e++)t.push(s.x+Math.cos(e*r)*this.diameter,s.y+Math.sin(e*r)*this.diameter,s.z);const e=t.length/3-2*this._sectionPolygonPointsCount;for(let t=0;t<this._sectionPolygonPointsCount-1;t++)n.push(e+t,e+t+this._sectionPolygonPointsCount,e+t+this._sectionPolygonPointsCount+1),n.push(e+t,e+t+this._sectionPolygonPointsCount+1,e+t+1);n.push(e+this._sectionPolygonPointsCount-1,e+this._sectionPolygonPointsCount-1+this._sectionPolygonPointsCount,e+this._sectionPolygonPointsCount),n.push(e+this._sectionPolygonPointsCount-1,e+this._sectionPolygonPointsCount,e)}sn.x.ComputeNormals(t,n,i),e.positions=t,e.normals=i,e.indices=n,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add((()=>{this.update()})))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(qe.o.PositionKind),t=this.getVerticesData(qe.o.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let i=3*this._sectionPolygonPointsCount;i<e.length;i++)e[i-3*this._sectionPolygonPointsCount]=e[i]-t[i]/this._length*this.diameter;for(let e=3*this._sectionPolygonPointsCount;e<t.length;e++)t[e-3*this._sectionPolygonPointsCount]=t[e];const n=e.length-3*this._sectionPolygonPointsCount,s=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<this._sectionPolygonPointsCount;e++)this._sectionVectors[e].copyFromFloats(Math.cos(e*s)*this.diameter,Math.sin(e*s)*this.diameter,0),this._sectionNormalVectors[e].copyFromFloats(Math.cos(e*s),Math.sin(e*s),0),o.P.TransformCoordinatesToRef(this._sectionVectors[e],i,this._sectionVectors[e]),o.P.TransformNormalToRef(this._sectionNormalVectors[e],i,this._sectionNormalVectors[e]);for(let i=0;i<this._sectionPolygonPointsCount;i++)e[n+3*i]=this._sectionVectors[i].x,e[n+3*i+1]=this._sectionVectors[i].y,e[n+3*i+2]=this._sectionVectors[i].z,t[n+3*i]=this._sectionNormalVectors[i].x,t[n+3*i+1]=this._sectionNormalVectors[i].y,t[n+3*i+2]=this._sectionNormalVectors[i].z;this.updateVerticesData(qe.o.PositionKind,e,!0,!1),this.updateVerticesData(qe.o.NormalKind,t,!0,!1)}}clone(e="",t){return new kp(e,void 0===t?this._generator:t,this.getScene(),this.diameter,this._length,this._autoStart)}serialize(e){super.serialize(e)}static Parse(e,t){var i;return new kp(e.name,e._generator,t,null!==(i=e.diameter)&&void 0!==i?i:e._diameter,e._length,e._autoStart)}}var Gp=i(7338);function zp(e){const t=e.pattern||Nt.Kj.NO_FLIP,i=e.tileWidth||e.tileSize||1,n=e.tileHeight||e.tileSize||1,s=e.alignHorizontal||0,r=e.alignVertical||0,o=e.width||e.size||1,a=Math.floor(o/i);let l=o-a*i;const h=e.height||e.size||1,c=Math.floor(h/n);let u=h-c*n;const d=i*a/2,p=n*c/2;let f=0,_=0,m=0,g=0,v=0,y=0;if(l>0||u>0){switch(m=-d,g=-p,v=d,y=p,s){case Nt.Kj.CENTER:l/=2,m-=l,v+=l;break;case Nt.Kj.LEFT:v+=l,f=-l/2;break;case Nt.Kj.RIGHT:m-=l,f=l/2}switch(r){case Nt.Kj.CENTER:u/=2,g-=u,y+=u;break;case Nt.Kj.BOTTOM:y+=u,_=-u/2;break;case Nt.Kj.TOP:g-=u,_=u/2}}const x=[],b=[],T=[];T[0]=[0,0,1,0,1,1,0,1],T[1]=[0,0,1,0,1,1,0,1],t!==Nt.Kj.ROTATE_TILE&&t!==Nt.Kj.ROTATE_ROW||(T[1]=[1,1,0,1,0,0,1,0]),t!==Nt.Kj.FLIP_TILE&&t!==Nt.Kj.FLIP_ROW||(T[1]=[1,0,0,0,0,1,1,1]),t!==Nt.Kj.FLIP_N_ROTATE_TILE&&t!==Nt.Kj.FLIP_N_ROTATE_ROW||(T[1]=[0,1,1,1,1,0,0,0]);let S=[];const E=[],C=[];let A=0;for(let e=0;e<c;e++)for(let s=0;s<a;s++)x.push(s*i-d+f,e*n-p+_,0),x.push((s+1)*i-d+f,e*n-p+_,0),x.push((s+1)*i-d+f,(e+1)*n-p+_,0),x.push(s*i-d+f,(e+1)*n-p+_,0),C.push(A,A+1,A+3,A+1,A+2,A+3),S=t===Nt.Kj.FLIP_TILE||t===Nt.Kj.ROTATE_TILE||t===Nt.Kj.FLIP_N_ROTATE_TILE?S.concat(T[(s%2+e%2)%2]):t===Nt.Kj.FLIP_ROW||t===Nt.Kj.ROTATE_ROW||t===Nt.Kj.FLIP_N_ROTATE_ROW?S.concat(T[e%2]):S.concat(T[0]),E.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),A+=4;if(l>0||u>0){const e=u>0&&(r===Nt.Kj.CENTER||r===Nt.Kj.TOP),o=u>0&&(r===Nt.Kj.CENTER||r===Nt.Kj.BOTTOM),h=l>0&&(s===Nt.Kj.CENTER||s===Nt.Kj.RIGHT),T=l>0&&(s===Nt.Kj.CENTER||s===Nt.Kj.LEFT);let P,R,M,I,D=[];if(e&&h&&(x.push(m+f,g+_,0),x.push(-d+f,g+_,0),x.push(-d+f,g+u+_,0),x.push(m+f,g+u+_,0),C.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=1-l/i,R=1-u/n,M=1,I=1,D=[P,R,M,R,M,I,P,I],t===Nt.Kj.ROTATE_ROW&&(D=[1-P,1-R,1-M,1-R,1-M,1-I,1-P,1-I]),t===Nt.Kj.FLIP_ROW&&(D=[1-P,R,1-M,R,1-M,I,1-P,I]),t===Nt.Kj.FLIP_N_ROTATE_ROW&&(D=[P,1-R,M,1-R,M,1-I,P,1-I]),S=S.concat(D),E.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)),e&&T&&(x.push(d+f,g+_,0),x.push(v+f,g+_,0),x.push(v+f,g+u+_,0),x.push(d+f,g+u+_,0),C.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=0,R=1-u/n,M=l/i,I=1,D=[P,R,M,R,M,I,P,I],(t===Nt.Kj.ROTATE_ROW||t===Nt.Kj.ROTATE_TILE&&a%2==0)&&(D=[1-P,1-R,1-M,1-R,1-M,1-I,1-P,1-I]),(t===Nt.Kj.FLIP_ROW||t===Nt.Kj.FLIP_TILE&&a%2==0)&&(D=[1-P,R,1-M,R,1-M,I,1-P,I]),(t===Nt.Kj.FLIP_N_ROTATE_ROW||t===Nt.Kj.FLIP_N_ROTATE_TILE&&a%2==0)&&(D=[P,1-R,M,1-R,M,1-I,P,1-I]),S=S.concat(D),E.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)),o&&h&&(x.push(m+f,p+_,0),x.push(-d+f,p+_,0),x.push(-d+f,y+_,0),x.push(m+f,y+_,0),C.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=1-l/i,R=0,M=1,I=u/n,D=[P,R,M,R,M,I,P,I],(t===Nt.Kj.ROTATE_ROW&&c%2==1||t===Nt.Kj.ROTATE_TILE&&c%1==0)&&(D=[1-P,1-R,1-M,1-R,1-M,1-I,1-P,1-I]),(t===Nt.Kj.FLIP_ROW&&c%2==1||t===Nt.Kj.FLIP_TILE&&c%2==0)&&(D=[1-P,R,1-M,R,1-M,I,1-P,I]),(t===Nt.Kj.FLIP_N_ROTATE_ROW&&c%2==1||t===Nt.Kj.FLIP_N_ROTATE_TILE&&c%2==0)&&(D=[P,1-R,M,1-R,M,1-I,P,1-I]),S=S.concat(D),E.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)),o&&T&&(x.push(d+f,p+_,0),x.push(v+f,p+_,0),x.push(v+f,y+_,0),x.push(d+f,y+_,0),C.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=0,R=0,M=l/i,I=u/n,D=[P,R,M,R,M,I,P,I],(t===Nt.Kj.ROTATE_ROW&&c%2==1||t===Nt.Kj.ROTATE_TILE&&(c+a)%2==1)&&(D=[1-P,1-R,1-M,1-R,1-M,1-I,1-P,1-I]),(t===Nt.Kj.FLIP_ROW&&c%2==1||t===Nt.Kj.FLIP_TILE&&(c+a)%2==1)&&(D=[1-P,R,1-M,R,1-M,I,1-P,I]),(t===Nt.Kj.FLIP_N_ROTATE_ROW&&c%2==1||t===Nt.Kj.FLIP_N_ROTATE_TILE&&(c+a)%2==1)&&(D=[P,1-R,M,1-R,M,1-I,P,1-I]),S=S.concat(D),E.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)),e){const e=[];P=0,R=1-u/n,M=1,I=1,e[0]=[P,R,M,R,M,I,P,I],e[1]=[P,R,M,R,M,I,P,I],t!==Nt.Kj.ROTATE_TILE&&t!==Nt.Kj.ROTATE_ROW||(e[1]=[1-P,1-R,1-M,1-R,1-M,1-I,1-P,1-I]),t!==Nt.Kj.FLIP_TILE&&t!==Nt.Kj.FLIP_ROW||(e[1]=[1-P,R,1-M,R,1-M,I,1-P,I]),t!==Nt.Kj.FLIP_N_ROTATE_TILE&&t!==Nt.Kj.FLIP_N_ROTATE_ROW||(e[1]=[P,1-R,M,1-R,M,1-I,P,1-I]);for(let n=0;n<a;n++)x.push(n*i-d+f,g+_,0),x.push((n+1)*i-d+f,g+_,0),x.push((n+1)*i-d+f,g+u+_,0),x.push(n*i-d+f,g+u+_,0),C.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,S=t===Nt.Kj.FLIP_TILE||t===Nt.Kj.ROTATE_TILE||t===Nt.Kj.FLIP_N_ROTATE_TILE?S.concat(e[(n+1)%2]):t===Nt.Kj.FLIP_ROW||t===Nt.Kj.ROTATE_ROW||t===Nt.Kj.FLIP_N_ROTATE_ROW?S.concat(e[1]):S.concat(e[0]),E.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)}if(o){const e=[];P=0,R=0,M=1,I=u/n,e[0]=[P,R,M,R,M,I,P,I],e[1]=[P,R,M,R,M,I,P,I],t!==Nt.Kj.ROTATE_TILE&&t!==Nt.Kj.ROTATE_ROW||(e[1]=[1-P,1-R,1-M,1-R,1-M,1-I,1-P,1-I]),t!==Nt.Kj.FLIP_TILE&&t!==Nt.Kj.FLIP_ROW||(e[1]=[1-P,R,1-M,R,1-M,I,1-P,I]),t!==Nt.Kj.FLIP_N_ROTATE_TILE&&t!==Nt.Kj.FLIP_N_ROTATE_ROW||(e[1]=[P,1-R,M,1-R,M,1-I,P,1-I]);for(let n=0;n<a;n++)x.push(n*i-d+f,y-u+_,0),x.push((n+1)*i-d+f,y-u+_,0),x.push((n+1)*i-d+f,y+_,0),x.push(n*i-d+f,y+_,0),C.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,S=t===Nt.Kj.FLIP_TILE||t===Nt.Kj.ROTATE_TILE||t===Nt.Kj.FLIP_N_ROTATE_TILE?S.concat(e[(n+c)%2]):t===Nt.Kj.FLIP_ROW||t===Nt.Kj.ROTATE_ROW||t===Nt.Kj.FLIP_N_ROTATE_ROW?S.concat(e[c%2]):S.concat(e[0]),E.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)}if(h){const e=[];P=1-l/i,R=0,M=1,I=1,e[0]=[P,R,M,R,M,I,P,I],e[1]=[P,R,M,R,M,I,P,I],t!==Nt.Kj.ROTATE_TILE&&t!==Nt.Kj.ROTATE_ROW||(e[1]=[1-P,1-R,1-M,1-R,1-M,1-I,1-P,1-I]),t!==Nt.Kj.FLIP_TILE&&t!==Nt.Kj.FLIP_ROW||(e[1]=[1-P,R,1-M,R,1-M,I,1-P,I]),t!==Nt.Kj.FLIP_N_ROTATE_TILE&&t!==Nt.Kj.FLIP_N_ROTATE_ROW||(e[1]=[P,1-R,M,1-R,M,1-I,P,1-I]);for(let i=0;i<c;i++)x.push(m+f,i*n-p+_,0),x.push(m+l+f,i*n-p+_,0),x.push(m+l+f,(i+1)*n-p+_,0),x.push(m+f,(i+1)*n-p+_,0),C.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,S=t===Nt.Kj.FLIP_TILE||t===Nt.Kj.ROTATE_TILE||t===Nt.Kj.FLIP_N_ROTATE_TILE?S.concat(e[(i+1)%2]):t===Nt.Kj.FLIP_ROW||t===Nt.Kj.ROTATE_ROW||t===Nt.Kj.FLIP_N_ROTATE_ROW?S.concat(e[i%2]):S.concat(e[0]),E.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)}if(T){const e=[];P=0,R=0,M=l/n,I=1,e[0]=[P,R,M,R,M,I,P,I],e[1]=[P,R,M,R,M,I,P,I],t!==Nt.Kj.ROTATE_TILE&&t!==Nt.Kj.ROTATE_ROW||(e[1]=[1-P,1-R,1-M,1-R,1-M,1-I,1-P,1-I]),t!==Nt.Kj.FLIP_TILE&&t!==Nt.Kj.FLIP_ROW||(e[1]=[1-P,R,1-M,R,1-M,I,1-P,I]),t!==Nt.Kj.FLIP_N_ROTATE_TILE&&t!==Nt.Kj.FLIP_N_ROTATE_ROW||(e[1]=[P,1-R,M,1-R,M,1-I,P,1-I]);for(let i=0;i<c;i++)x.push(v-l+f,i*n-p+_,0),x.push(v+f,i*n-p+_,0),x.push(v+f,(i+1)*n-p+_,0),x.push(v-l+f,(i+1)*n-p+_,0),C.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,S=t===Nt.Kj.FLIP_TILE||t===Nt.Kj.ROTATE_TILE||t===Nt.Kj.FLIP_N_ROTATE_TILE?S.concat(e[(i+a)%2]):t===Nt.Kj.FLIP_ROW||t===Nt.Kj.ROTATE_ROW||t===Nt.Kj.FLIP_N_ROTATE_ROW?S.concat(e[i%2]):S.concat(e[0]),E.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)}}const P=0===e.sideOrientation?0:e.sideOrientation||sn.x.DEFAULTSIDE;sn.x._ComputeSides(P,x,C,b,S,e.frontUVs,e.backUVs);const R=new sn.x;R.indices=C,R.positions=x,R.normals=b,R.uvs=S;const M=P===sn.x.DOUBLESIDE?E.concat(E):E;return R.colors=M,R}function Wp(e,t,i=null){const n=new Nt.Kj(e,i);return t.sideOrientation=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,zp(t).applyToMesh(n,t.updatable),n}const Hp={CreateTiledPlane:Wp};function Xp(e){const t=e.faceUV||new Array(6),i=e.faceColors,n=e.pattern||Nt.Kj.NO_FLIP,s=e.width||e.size||1,r=e.height||e.size||1,l=e.depth||e.size||1,h=e.tileWidth||e.tileSize||1,c=e.tileHeight||e.tileSize||1,u=e.alignHorizontal||0,d=e.alignVertical||0,p=0===e.sideOrientation?0:e.sideOrientation||sn.x.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new o.Lt(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new a.HE(1,1,1,1));const f=s/2,_=r/2,m=l/2,g=[];for(let e=0;e<2;e++)g[e]=zp({pattern:n,tileWidth:h,tileHeight:c,width:s,height:r,alignVertical:d,alignHorizontal:u,sideOrientation:p});for(let e=2;e<4;e++)g[e]=zp({pattern:n,tileWidth:h,tileHeight:c,width:l,height:r,alignVertical:d,alignHorizontal:u,sideOrientation:p});let v=d;d===Nt.Kj.BOTTOM?v=Nt.Kj.TOP:d===Nt.Kj.TOP&&(v=Nt.Kj.BOTTOM);for(let e=4;e<6;e++)g[e]=zp({pattern:n,tileWidth:h,tileHeight:c,width:s,height:l,alignVertical:v,alignHorizontal:u,sideOrientation:p});let y=[],x=[],b=[],T=[];const S=[],E=[],C=[],A=[];let P=0,R=0;for(let e=0;e<6;e++){const n=g[e].positions.length;E[e]=[],C[e]=[];for(let t=0;t<n/3;t++)E[e].push(new o.P(g[e].positions[3*t],g[e].positions[3*t+1],g[e].positions[3*t+2])),C[e].push(new o.P(g[e].normals[3*t],g[e].normals[3*t+1],g[e].normals[3*t+2]));P=g[e].uvs.length,A[e]=[];for(let i=0;i<P;i+=2)A[e][i]=t[e].x+(t[e].z-t[e].x)*g[e].uvs[i],A[e][i+1]=t[e].y+(t[e].w-t[e].y)*g[e].uvs[i+1],rn.e.UseOpenGLOrientationForUV&&(A[e][i+1]=1-A[e][i+1]);if(b=b.concat(A[e]),T=T.concat(g[e].indices.map((e=>e+R))),R+=E[e].length,i)for(let t=0;t<4;t++)S.push(i[e].r,i[e].g,i[e].b,i[e].a)}const M=new o.P(0,0,m),I=o.y3.RotationY(Math.PI);y=E[0].map((e=>o.P.TransformNormal(e,I).add(M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),x=C[0].map((e=>o.P.TransformNormal(e,I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),y=y.concat(E[1].map((e=>e.subtract(M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),x=x.concat(C[1].map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const D=new o.P(f,0,0),O=o.y3.RotationY(-Math.PI/2);y=y.concat(E[2].map((e=>o.P.TransformNormal(e,O).add(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),x=x.concat(C[2].map((e=>o.P.TransformNormal(e,O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const w=o.y3.RotationY(Math.PI/2);y=y.concat(E[3].map((e=>o.P.TransformNormal(e,w).subtract(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),x=x.concat(C[3].map((e=>o.P.TransformNormal(e,w))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const N=new o.P(0,_,0),F=o.y3.RotationX(Math.PI/2);y=y.concat(E[4].map((e=>o.P.TransformNormal(e,F).add(N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),x=x.concat(C[4].map((e=>o.P.TransformNormal(e,F))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const L=o.y3.RotationX(-Math.PI/2);y=y.concat(E[5].map((e=>o.P.TransformNormal(e,L).subtract(N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),x=x.concat(C[5].map((e=>o.P.TransformNormal(e,L))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),sn.x._ComputeSides(p,y,T,x,b);const B=new sn.x;if(B.indices=T,B.positions=y,B.normals=x,B.uvs=b,i){const e=p===sn.x.DOUBLESIDE?S.concat(S):S;B.colors=e}return B}function jp(e,t,i=null){const n=new Nt.Kj(e,i);return t.sideOrientation=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,Xp(t).applyToMesh(n,t.updatable),n}sn.x.CreateTiledPlane=zp;const Yp={CreateTiledBox:jp};function qp(e){const t=new Array,i=new Array,n=new Array,s=new Array,r=e.radius||2,a=e.tube||.5,l=e.radialSegments||32,h=e.tubularSegments||32,c=e.p||2,u=e.q||3,d=0===e.sideOrientation?0:e.sideOrientation||sn.x.DEFAULTSIDE,p=e=>{const t=Math.cos(e),i=Math.sin(e),n=u/c*e,s=Math.cos(n),a=r*(2+s)*.5*t,l=r*(2+s)*i*.5,h=r*Math.sin(n)*.5;return new o.P(a,l,h)};let f,_;for(f=0;f<=l;f++){const e=f%l/l*2*c*Math.PI,t=p(e),n=p(e+.01),r=n.subtract(t);let u=n.add(t);const d=o.P.Cross(r,u);for(u=o.P.Cross(d,r),d.normalize(),u.normalize(),_=0;_<h;_++){const e=_%h/h*2*Math.PI,n=-a*Math.cos(e),r=a*Math.sin(e);i.push(t.x+n*u.x+r*d.x),i.push(t.y+n*u.y+r*d.y),i.push(t.z+n*u.z+r*d.z),s.push(f/l),s.push(rn.e.UseOpenGLOrientationForUV?1-_/h:_/h)}}for(f=0;f<l;f++)for(_=0;_<h;_++){const e=(_+1)%h,i=f*h+_,n=(f+1)*h+_,s=(f+1)*h+e,r=f*h+e;t.push(r),t.push(n),t.push(i),t.push(r),t.push(s),t.push(n)}sn.x.ComputeNormals(i,t,n),sn.x._ComputeSides(d,i,t,n,s,e.frontUVs,e.backUVs);const m=new sn.x;return m.indices=t,m.positions=i,m.normals=n,m.uvs=s,m}function Kp(e,t={},i){const n=new Nt.Kj(e,i);return t.sideOrientation=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,qp(t).applyToMesh(n,t.updatable),n}sn.x.CreateTiledBox=Xp;const $p={CreateTorusKnot:Kp};sn.x.CreateTorusKnot=qp,Nt.Kj.CreateTorusKnot=(e,t,i,n,s,r,o,a,l,h)=>Kp(e,{radius:t,tube:i,radialSegments:n,tubularSegments:s,p:r,q:o,sideOrientation:h,updatable:l},a);class Qp extends o.FM{constructor(e,t){super(e.x,e.y),this.index=t}}class Zp{constructor(){this.elements=new Array}add(e){const t=new Array;return e.forEach((e=>{const i=new Qp(e,this.elements.length);t.push(i),this.elements.push(i)})),t}computeBounds(){const e=new o.FM(this.elements[0].x,this.elements[0].y),t=new o.FM(this.elements[0].x,this.elements[0].y);return this.elements.forEach((i=>{i.x<e.x?e.x=i.x:i.x>t.x&&(t.x=i.x),i.y<e.y?e.y=i.y:i.y>t.y&&(t.y=i.y)})),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class Jp{static Rectangle(e,t,i,n){return[new o.FM(e,t),new o.FM(i,t),new o.FM(i,n),new o.FM(e,n)]}static Circle(e,t=0,i=0,n=32){const s=new Array;let r=0;const a=2*Math.PI/n;for(let l=0;l<n;l++)s.push(new o.FM(t+Math.cos(r)*e,i+Math.sin(r)*e)),r-=a;return s}static Parse(e){const t=e.split(/[^-+eE.\d]+/).map(parseFloat).filter((e=>!isNaN(e)));let i;const n=[];for(i=0;i<(2147483646&t.length);i+=2)n.push(new o.FM(t[i],t[i+1]));return n}static StartingAt(e,t){return X.ZZ.StartingAt(e,t)}}class ef{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,n=earcut){let s;this._points=new Zp,this._outlinepoints=new Zp,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=n,this._name=e,this._scene=i||A.l.LastCreatedScene,s=t instanceof X.ZZ?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&_.Y.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new Zp;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 n=new Nt.Kj(this._name,this._scene),s=this.buildVertexData(t,i);return n.setVerticesData(qe.o.PositionKind,s.positions,e),n.setVerticesData(qe.o.NormalKind,s.normals,e),n.setVerticesData(qe.o.UVKind,s.uvs,e),n.setIndices(s.indices),n}buildVertexData(e=0,t=2){const i=new sn.x,n=new Array,s=new Array,r=new Array,o=this._points.computeBounds();this._points.elements.forEach((e=>{n.push(0,1,0),s.push(e.x,0,e.y),r.push((e.x-o.min.x)/o.width,(e.y-o.min.y)/o.height)}));const a=new Array,l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e<l.length;e++)a.push(l[e]);if(e>0){const i=s.length/3;this._points.elements.forEach((t=>{n.push(0,-1,0),s.push(t.x,-e,t.y),r.push(1-(t.x-o.min.x)/o.width,1-(t.y-o.min.y)/o.height)}));const l=a.length;for(let e=0;e<l;e+=3){const t=a[e+0],n=a[e+1],s=a[e+2];a.push(s+i),a.push(n+i),a.push(t+i)}this._addSide(s,n,r,a,o,this._outlinepoints,e,!1,t),this._holes.forEach((i=>{this._addSide(s,n,r,a,o,i,e,!0,t)}))}return i.indices=a,i.positions=s,i.normals=n,i.uvs=r,i}_addSide(e,t,i,n,s,r,a,l,h){let c=e.length/3,u=0;for(let d=0;d<r.elements.length;d++){const p=r.elements[d],f=r.elements[(d+1)%r.elements.length];e.push(p.x,0,p.y),e.push(p.x,-a,p.y),e.push(f.x,0,f.y),e.push(f.x,-a,f.y);const _=r.elements[(d+r.elements.length-1)%r.elements.length],m=r.elements[(d+2)%r.elements.length];let g=new o.P(-(f.y-p.y),0,f.x-p.x),v=new o.P(-(p.y-_.y),0,p.x-_.x),y=new o.P(-(m.y-f.y),0,m.x-f.x);l||(g=g.scale(-1),v=v.scale(-1),y=y.scale(-1));const x=g.normalizeToNew();let b=v.normalizeToNew(),T=y.normalizeToNew();const S=o.P.Dot(b,x);b=S>h?S<Me.kn-1?new o.P(p.x,0,p.y).subtract(new o.P(f.x,0,f.y)).normalize():v.add(g).normalize():x;const E=o.P.Dot(y,g);T=E>h?E<Me.kn-1?new o.P(f.x,0,f.y).subtract(new o.P(p.x,0,p.y)).normalize():y.add(g).normalize():x,i.push(u/s.width,0),i.push(u/s.width,1),u+=g.length(),i.push(u/s.width,0),i.push(u/s.width,1),t.push(b.x,b.y,b.z),t.push(b.x,b.y,b.z),t.push(T.x,T.y,T.z),t.push(T.x,T.y,T.z),l?(n.push(c),n.push(c+2),n.push(c+1),n.push(c+1),n.push(c+2),n.push(c+3)):(n.push(c),n.push(c+1),n.push(c+2),n.push(c+1),n.push(c+3),n.push(c+2)),c+=4}}}function tf(e,t,i,n,s,r,l){const h=i||new Array(3),c=n,u=[],d=l||!1;for(let e=0;e<3;e++)void 0===h[e]&&(h[e]=new o.Lt(0,0,1,1)),c&&void 0===c[e]&&(c[e]=new a.HE(1,1,1,1));const p=e.getVerticesData(qe.o.PositionKind),f=e.getVerticesData(qe.o.NormalKind),_=e.getVerticesData(qe.o.UVKind),m=e.getIndices(),g=p.length/9;let v=0,y=0,x=0,b=0,T=0;const S=[0];if(d)for(let e=g;e<p.length/3;e+=4)y=p[3*(e+2)]-p[3*e],x=p[3*(e+2)+2]-p[3*e+2],b=Math.sqrt(y*y+x*x),T+=b,S.push(T);let E=0,C=0;for(let e=0;e<f.length;e+=3)Math.abs(f[e+1])<.001&&(C=1),Math.abs(f[e+1]-1)<.001&&(C=0),Math.abs(f[e+1]+1)<.001&&(C=2),E=e/3,1===C?(v=E-g,_[2*E]=v%4<1.5?d?h[C].x+(h[C].z-h[C].x)*S[Math.floor(v/4)]/T:h[C].x:d?h[C].x+(h[C].z-h[C].x)*S[Math.floor(v/4)+1]/T:h[C].z,_[2*E+1]=v%2==0?rn.e.UseOpenGLOrientationForUV?1-h[C].w:h[C].w:rn.e.UseOpenGLOrientationForUV?1-h[C].y:h[C].y):(_[2*E]=(1-_[2*E])*h[C].x+_[2*E]*h[C].z,_[2*E+1]=(1-_[2*E+1])*h[C].y+_[2*E+1]*h[C].w,rn.e.UseOpenGLOrientationForUV&&(_[2*E+1]=1-_[2*E+1])),c&&u.push(c[C].r,c[C].g,c[C].b,c[C].a);sn.x._ComputeSides(t,p,m,f,_,s,r);const A=new sn.x;if(A.indices=m,A.positions=p,A.normals=f,A.uvs=_,c){const e=t===sn.x.DOUBLESIDE?u.concat(u):u;A.colors=e}return A}function nf(e,t,i=null,n=earcut){t.sideOrientation=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation);const s=t.shape,r=t.holes||[],a=t.depth||0,l=t.smoothingThreshold||2,h=[];let c=[];for(let e=0;e<s.length;e++)h[e]=new o.FM(s[e].x,s[e].z);h[0].equalsWithEpsilon(h[h.length-1],1e-8)&&h.pop();const u=new ef(e,h,i||A.l.LastCreatedScene,n);for(let e=0;e<r.length;e++){c=[];for(let t=0;t<r[e].length;t++)c.push(new o.FM(r[e][t].x,r[e][t].z));u.addHole(c)}const d=u.build(!1,a,l);return d._originalBuilderSideOrientation=t.sideOrientation,tf(d,t.sideOrientation,t.faceUV,t.faceColors,t.frontUVs,t.backUVs,t.wrap).applyToMesh(d,t.updatable),d}function sf(e,t,i=null,n=earcut){return nf(e,t,i,n)}const rf={ExtrudePolygon:sf,CreatePolygon:nf};function of(e,t,i=null){const n=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,s=void 0===t.closed||t.closed,r=t.shape,a=t.radius||1,l=t.tessellation||64,h=t.clip||0,c=t.updatable,u=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),d=t.cap||Nt.Kj.NO_CAP,p=2*Math.PI,f=new Array,_=t.invertUV||!1;let m=0,g=0;const v=p/l*n;let y,x;for(m=0;m<=l-h;m++){for(x=[],d!=Nt.Kj.CAP_START&&d!=Nt.Kj.CAP_ALL||(x.push(new o.P(0,r[0].y,0)),x.push(new o.P(Math.cos(m*v)*r[0].x*a,r[0].y,Math.sin(m*v)*r[0].x*a))),g=0;g<r.length;g++)y=new o.P(Math.cos(m*v)*r[g].x*a,r[g].y,Math.sin(m*v)*r[g].x*a),x.push(y);d!=Nt.Kj.CAP_END&&d!=Nt.Kj.CAP_ALL||(x.push(new o.P(Math.cos(m*v)*r[r.length-1].x*a,r[r.length-1].y,Math.sin(m*v)*r[r.length-1].x*a)),x.push(new o.P(0,r[r.length-1].y,0))),f.push(x)}return fs(e,{pathArray:f,closeArray:s,sideOrientation:u,updatable:c,invertUV:_,frontUVs:t.frontUVs,backUVs:t.backUVs},i)}sn.x.CreatePolygon=tf,Nt.Kj.CreatePolygon=(e,t,i,n,s,r,o=earcut)=>nf(e,{shape:t,holes:n,updatable:s,sideOrientation:r},i,o),Nt.Kj.ExtrudePolygon=(e,t,i,n,s,r,o,a=earcut)=>sf(e,{shape:t,holes:s,depth:i,updatable:r,sideOrientation:o},n,a);const af={CreateLathe:of};function lf(e,t,i=null){const n=t.path;let s=t.instance,r=1;void 0!==t.radius?r=t.radius:s&&(r=s._creationDataStorage.radius);const a=t.tessellation||64,l=t.radiusFunction||null;let h=t.cap||Nt.Kj.NO_CAP;const c=t.invertUV||!1,u=t.updatable,d=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;const p=(e,t,i,n,s,r,a,l)=>{const h=t.getTangents(),c=t.getNormals(),u=t.getDistances(),d=2*Math.PI/s*l,p=r||(()=>n);let f,_,m,g;const v=o.jp.Matrix[0];let y=a===Nt.Kj.NO_CAP||a===Nt.Kj.CAP_END?0:2;for(let t=0;t<e.length;t++){_=p(t,u[t]),f=Array(),m=c[t];for(let i=0;i<s;i++)o.y3.RotationAxisToRef(h[t],d*i,v),g=f[i]?f[i]:o.P.Zero(),o.P.TransformCoordinatesToRef(m,v,g),g.scaleInPlace(_).addInPlace(e[t]),f[i]=g;i[y]=f,y++}const x=(t,i)=>{const n=Array();for(let s=0;s<t;s++)n.push(e[i]);return n};switch(a){case Nt.Kj.NO_CAP:break;case Nt.Kj.CAP_START:i[0]=x(s,0),i[1]=i[2].slice(0);break;case Nt.Kj.CAP_END:i[y]=i[y-1].slice(0),i[y+1]=x(s,e.length-1);break;case Nt.Kj.CAP_ALL:i[0]=x(s,0),i[1]=i[2].slice(0),i[y]=i[y-1].slice(0),i[y+1]=x(s,e.length-1)}return i};let f,_;if(s){const e=s._creationDataStorage,i=t.arc||e.arc;return f=e.path3D.update(n),_=p(n,f,e.pathArray,r,e.tessellation,l,e.cap,i),s=fs("",{pathArray:_,instance:s}),e.path3D=f,e.pathArray=_,e.arc=i,e.radius=r,s}f=new X.$B(n),h=h<0||h>3?0:h,_=p(n,f,new Array,r,a,l,h,t.arc);const m=fs(e,{pathArray:_,closePath:!0,closeArray:!1,updatable:u,sideOrientation:d,invertUV:c,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return m._creationDataStorage.pathArray=_,m._creationDataStorage.path3D=f,m._creationDataStorage.tessellation=a,m._creationDataStorage.cap=h,m._creationDataStorage.arc=t.arc,m._creationDataStorage.radius=r,m}Nt.Kj.CreateLathe=(e,t,i,n,s,r,o)=>of(e,{shape:t,radius:i,tessellation:n,sideOrientation:o,updatable:r},s);const hf={CreateTube:lf};Nt.Kj.CreateTube=(e,t,i,n,s,r,o,a,l,h)=>lf(e,{path:t,radius:i,tessellation:n,radiusFunction:s,arc:1,cap:r,updatable:a,sideOrientation:l,instance:h},o);var cf=i(6272);const uf=new o.P(1,0,0),df=new o.P(-1,0,0),pf=new o.P(0,1,0),ff=new o.P(0,-1,0),_f=new o.P(0,0,1),mf=new o.P(0,0,-1);class gf{constructor(e=o.P.Zero(),t=o.P.Up(),i=o.FM.Zero(),n=0,s=0,r=null,a=null,l=null,h=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=n,this.vertexIdxForBones=s,this.localPositionOverride=r,this.localNormalOverride=a,this.matrixIndicesOverride=l,this.matrixWeightsOverride=h}clone(){var e,t,i,n;return new gf(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,null===(e=this.localPositionOverride)||void 0===e?void 0:e.slice(),null===(t=this.localNormalOverride)||void 0===t?void 0:t.slice(),null===(i=this.matrixIndicesOverride)||void 0===i?void 0:i.slice(),null===(n=this.matrixWeightsOverride)||void 0===n?void 0:n.slice())}}function vf(e,t,i){const n=!!t.skeleton,s=i.localMode||n,r=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,a=t.getIndices(),l=n?t.getPositionData(!0,!0):t.getVerticesData(qe.o.PositionKind),h=n?t.getNormalsData(!0,!0):t.getVerticesData(qe.o.NormalKind),c=s?n?t.getVerticesData(qe.o.PositionKind):l:null,u=s?n?t.getVerticesData(qe.o.NormalKind):h:null,d=t.getVerticesData(qe.o.UVKind),p=n?t.getVerticesData(qe.o.MatricesIndicesKind):null,f=n?t.getVerticesData(qe.o.MatricesWeightsKind):null,_=n?t.getVerticesData(qe.o.MatricesIndicesExtraKind):null,m=n?t.getVerticesData(qe.o.MatricesWeightsExtraKind):null,g=i.position||o.P.Zero();let v=i.normal||o.P.Up();const y=i.size||o.P.One(),x=i.angle||0;if(!v){const e=new o.P(0,0,1),i=t.getScene().activeCamera,n=o.P.TransformCoordinates(e,i.getWorldMatrix());v=i.globalPosition.subtract(n)}const b=-Math.atan2(v.z,v.x)-Math.PI/2,T=Math.sqrt(v.x*v.x+v.z*v.z),S=Math.atan2(v.y,T),E=o.y3.RotationYawPitchRoll(b,S,x).multiply(o.y3.Translation(g.x,g.y,g.z)),C=o.y3.Invert(E),A=t.getWorldMatrix().multiply(C),P=new sn.x;P.indices=[],P.positions=[],P.normals=[],P.uvs=[],P.matricesIndices=n?[]:null,P.matricesWeights=n?[]:null,P.matricesIndicesExtra=_?[]:null,P.matricesWeightsExtra=m?[]:null;let R=0;const M=e=>{const t=new gf;if(!a||!l||!h)return t;const n=a[e];if(t.vertexIdx=3*n,t.vertexIdxForBones=4*n,t.position=new o.P(l[3*n],l[3*n+1],l[3*n+2]),o.P.TransformCoordinatesToRef(t.position,A,t.position),t.normal=new o.P(h[3*n],h[3*n+1],h[3*n+2]),o.P.TransformNormalToRef(t.normal,A,t.normal),i.captureUVS&&d){const e=d[2*n+1];t.uv=new o.FM(d[2*n],rn.e.UseOpenGLOrientationForUV?1-e:e)}return t},I=[0,0,0,0],D=(e,t)=>{if(0===e.length)return e;const i=.5*Math.abs(o.P.Dot(y,t)),n=(e,t,i,n)=>{for(let s=0;s<n;++s)if(e[i+s]===t)return i+s;return-1},s=(e,s)=>{var r,a,l,h,d,_,m,g,v,y,x,b,T,S,E,C;const A=o.P.GetClipFactor(e.position,s.position,t,i);let P=I,R=I;if(p&&f){const t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=null!==(r=e.matrixIndicesOverride)&&void 0!==r?r:p,o=null!==(a=e.matrixWeightsOverride)&&void 0!==a?a:f,c=s.matrixIndicesOverride?0:s.vertexIdxForBones,u=null!==(l=s.matrixIndicesOverride)&&void 0!==l?l:p,d=null!==(h=s.matrixWeightsOverride)&&void 0!==h?h:f;P=[0,0,0,0],R=[0,0,0,0];let _=0;for(let e=0;e<4;++e)if(o[t+e]>0){const s=n(u,i[t+e],c,4);P[_]=i[t+e],R[_]=lt.R.Lerp(o[t+e],s>=0?d[s]:0,A),_++}for(let e=0;e<4&&_<4;++e){const s=u[c+e];-1===n(i,s,t,4)&&(P[_]=s,R[_]=lt.R.Lerp(0,d[c+e],A),_++)}const m=R[0]+R[1]+R[2]+R[3];R[0]/=m,R[1]/=m,R[2]/=m,R[3]/=m}const M=e.localPositionOverride?e.localPositionOverride[0]:null!==(d=null==c?void 0:c[e.vertexIdx])&&void 0!==d?d:0,D=e.localPositionOverride?e.localPositionOverride[1]:null!==(_=null==c?void 0:c[e.vertexIdx+1])&&void 0!==_?_:0,O=e.localPositionOverride?e.localPositionOverride[2]:null!==(m=null==c?void 0:c[e.vertexIdx+2])&&void 0!==m?m:0,w=s.localPositionOverride?s.localPositionOverride[0]:null!==(g=null==c?void 0:c[s.vertexIdx])&&void 0!==g?g:0,N=s.localPositionOverride?s.localPositionOverride[1]:null!==(v=null==c?void 0:c[s.vertexIdx+1])&&void 0!==v?v:0,F=s.localPositionOverride?s.localPositionOverride[2]:null!==(y=null==c?void 0:c[s.vertexIdx+2])&&void 0!==y?y:0,L=e.localNormalOverride?e.localNormalOverride[0]:null!==(x=null==u?void 0:u[e.vertexIdx])&&void 0!==x?x:0,B=e.localNormalOverride?e.localNormalOverride[1]:null!==(b=null==u?void 0:u[e.vertexIdx+1])&&void 0!==b?b:0,U=e.localNormalOverride?e.localNormalOverride[2]:null!==(T=null==u?void 0:u[e.vertexIdx+2])&&void 0!==T?T:0,V=L+((s.localNormalOverride?s.localNormalOverride[0]:null!==(S=null==u?void 0:u[s.vertexIdx])&&void 0!==S?S:0)-L)*A,k=B+((s.localNormalOverride?s.localNormalOverride[1]:null!==(E=null==u?void 0:u[s.vertexIdx+1])&&void 0!==E?E:0)-B)*A,G=U+((s.localNormalOverride?s.localNormalOverride[2]:null!==(C=null==u?void 0:u[s.vertexIdx+2])&&void 0!==C?C:0)-U)*A,z=Math.sqrt(V*V+k*k+G*G);return new gf(o.P.Lerp(e.position,s.position,A),o.P.Lerp(e.normal,s.normal,A).normalize(),o.FM.Lerp(e.uv,s.uv,A),-1,-1,c?[M+(w-M)*A,D+(N-D)*A,O+(F-O)*A]:null,u?[V/z,k/z,G/z]:null,P,R)};let r=null;e.length>3&&(r=new Array);for(let n=0;n<e.length;n+=3){let a=0,l=null,h=null,c=null,u=null;const d=o.P.Dot(e[n].position,t)-i>0,p=o.P.Dot(e[n+1].position,t)-i>0,f=o.P.Dot(e[n+2].position,t)-i>0;switch(a=(d?1:0)+(p?1:0)+(f?1:0),a){case 0:e.length>3?(r.push(e[n]),r.push(e[n+1]),r.push(e[n+2])):r=e;break;case 1:if(r=null!=r?r:new Array,d&&(l=e[n+1],h=e[n+2],c=s(e[n],l),u=s(e[n],h)),p){l=e[n],h=e[n+2],c=s(e[n+1],l),u=s(e[n+1],h),r.push(c),r.push(h.clone()),r.push(l.clone()),r.push(h.clone()),r.push(c.clone()),r.push(u);break}f&&(l=e[n],h=e[n+1],c=s(e[n+2],l),u=s(e[n+2],h)),l&&h&&c&&u&&(r.push(l.clone()),r.push(h.clone()),r.push(c),r.push(u),r.push(c.clone()),r.push(h.clone()));break;case 2:r=null!=r?r:new Array,d||(l=e[n].clone(),h=s(l,e[n+1]),c=s(l,e[n+2]),r.push(l),r.push(h),r.push(c)),p||(l=e[n+1].clone(),h=s(l,e[n+2]),c=s(l,e[n]),r.push(l),r.push(h),r.push(c)),f||(l=e[n+2].clone(),h=s(l,e[n]),c=s(l,e[n+1]),r.push(l),r.push(h),r.push(c))}}return r},O=new Array(3);for(let e=0;e<a.length;e+=3){let t=O;if(t[0]=M(e),r&&s?(t[1]=M(e+2),t[2]=M(e+1)):(t[1]=M(e+1),t[2]=M(e+2)),!(i.cullBackFaces&&-t[0].normal.z<=0&&-t[1].normal.z<=0&&-t[2].normal.z<=0)&&(t=D(t,uf),t&&(t=D(t,df),t&&(t=D(t,pf),t&&(t=D(t,ff),t&&(t=D(t,_f),t&&(t=D(t,mf),t)))))))for(let e=0;e<t.length;e++){const n=t[e];if(P.indices.push(R),s?(n.localPositionOverride?(P.positions[3*R]=n.localPositionOverride[0],P.positions[3*R+1]=n.localPositionOverride[1],P.positions[3*R+2]=n.localPositionOverride[2]):c&&(P.positions[3*R]=c[n.vertexIdx],P.positions[3*R+1]=c[n.vertexIdx+1],P.positions[3*R+2]=c[n.vertexIdx+2]),n.localNormalOverride?(P.normals[3*R]=n.localNormalOverride[0],P.normals[3*R+1]=n.localNormalOverride[1],P.normals[3*R+2]=n.localNormalOverride[2]):u&&(P.normals[3*R]=u[n.vertexIdx],P.normals[3*R+1]=u[n.vertexIdx+1],P.normals[3*R+2]=u[n.vertexIdx+2])):(n.position.toArray(P.positions,3*R),n.normal.toArray(P.normals,3*R)),P.matricesIndices&&P.matricesWeights&&(n.matrixIndicesOverride?(P.matricesIndices[4*R]=n.matrixIndicesOverride[0],P.matricesIndices[4*R+1]=n.matrixIndicesOverride[1],P.matricesIndices[4*R+2]=n.matrixIndicesOverride[2],P.matricesIndices[4*R+3]=n.matrixIndicesOverride[3]):(p&&(P.matricesIndices[4*R]=p[n.vertexIdxForBones],P.matricesIndices[4*R+1]=p[n.vertexIdxForBones+1],P.matricesIndices[4*R+2]=p[n.vertexIdxForBones+2],P.matricesIndices[4*R+3]=p[n.vertexIdxForBones+3]),_&&P.matricesIndicesExtra&&(P.matricesIndicesExtra[4*R]=_[n.vertexIdxForBones],P.matricesIndicesExtra[4*R+1]=_[n.vertexIdxForBones+1],P.matricesIndicesExtra[4*R+2]=_[n.vertexIdxForBones+2],P.matricesIndicesExtra[4*R+3]=_[n.vertexIdxForBones+3])),n.matrixWeightsOverride?(P.matricesWeights[4*R]=n.matrixWeightsOverride[0],P.matricesWeights[4*R+1]=n.matrixWeightsOverride[1],P.matricesWeights[4*R+2]=n.matrixWeightsOverride[2],P.matricesWeights[4*R+3]=n.matrixWeightsOverride[3]):(f&&(P.matricesWeights[4*R]=f[n.vertexIdxForBones],P.matricesWeights[4*R+1]=f[n.vertexIdxForBones+1],P.matricesWeights[4*R+2]=f[n.vertexIdxForBones+2],P.matricesWeights[4*R+3]=f[n.vertexIdxForBones+3]),m&&P.matricesWeightsExtra&&(P.matricesWeightsExtra[4*R]=m[n.vertexIdxForBones],P.matricesWeightsExtra[4*R+1]=m[n.vertexIdxForBones+1],P.matricesWeightsExtra[4*R+2]=m[n.vertexIdxForBones+2],P.matricesWeightsExtra[4*R+3]=m[n.vertexIdxForBones+3]))),i.captureUVS)n.uv.toArray(P.uvs,2*R);else{P.uvs.push(.5+n.position.x/y.x);const e=.5+n.position.y/y.y;P.uvs.push(rn.e.UseOpenGLOrientationForUV?1-e:e)}R++}}const w=new Nt.Kj(e,t.getScene());return P.applyToMesh(w),s?(w.skeleton=t.skeleton,w.parent=t):(w.position=g.clone(),w.rotation=new o.P(S,b,x)),w.computeWorldMatrix(!0),w.refreshBoundingInfo(!0,!0),w}const yf={CreateDecal:vf};Nt.Kj.CreateDecal=(e,t,i,n,s,r)=>vf(e,t,{position:i,normal:n,size:s,angle:r});class xf{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(Math.floor(e),_.Y.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(Math.floor(t),_.Y.Warn("y is not an integer, floor(y) used"))}clone(){return new xf(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)&&(Math.floor(e),_.Y.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),_.Y.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)&&(Math.floor(e),_.Y.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),_.Y.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=o.P.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 xf(0,0)}}class bf{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new Tf("icosahedron","Regular",[[0,Me.Q_,-1],[-Me.Q_,1,0],[-1,0,-Me.Q_],[1,0,-Me.Q_],[Me.Q_,1,0],[0,Me.Q_,1],[-1,0,Me.Q_],[-Me.Q_,-1,0],[0,-Me.Q_,-1],[Me.Q_,-1,0],[1,0,Me.Q_],[0,-Me.Q_,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,n=this.n;let s,r,o,a,l,h=i,c=1,u=0;0!==n&&(h=lt.R.HCF(i,n)),c=i/h,u=n/h;const d=xf.Zero(),p=new xf(i,n),f=new xf(-n,i+n),_=xf.Zero(),m=xf.Zero(),g=xf.Zero();let v,y,x,b,T=[];const S=[],E=this.vertByDist,C=(i,n,s,r)=>{v=i+"|"+s,y=n+"|"+r,v in t||y in t?v in t&&!(y in t)?t[y]=t[v]:y in t&&!(v in t)&&(t[v]=t[y]):(t[v]=e,t[y]=e,e++),E[s][0]>2?S[t[v]]=[-E[s][0],E[s][1],t[v]]:S[t[v]]=[T[E[s][0]],E[s][1],t[v]]};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 y=0;y<20;y++){if(T=this.IDATA.face[y],o=T[2],a=T[1],l=T[0],x=d.x+"|"+d.y,v=y+"|"+x,v in t||(t[v]=o,S[o]=[T[E[x][0]],E[x][1]]),x=p.x+"|"+p.y,v=y+"|"+x,v in t||(t[v]=a,S[a]=[T[E[x][0]],E[x][1]]),x=f.x+"|"+f.y,v=y+"|"+x,v in t||(t[v]=l,S[l]=[T[E[x][0]],E[x][1]]),s=this.IDATA.edgematch[y][0],r=this.IDATA.edgematch[y][1],"B"===r)for(let e=1;e<h;e++)m.x=i-e*(c+u),m.y=n+e*c,g.x=-e*u,g.y=e*(c+u),x=m.x+"|"+m.y,b=g.x+"|"+g.y,C(y,s,x,b);if("O"===r)for(let e=1;e<h;e++)g.x=-e*u,g.y=e*(c+u),_.x=e*c,_.y=e*u,x=g.x+"|"+g.y,b=_.x+"|"+_.y,C(y,s,x,b);if(s=this.IDATA.edgematch[y][2],r=this.IDATA.edgematch[y][3],r&&"A"===r)for(let e=1;e<h;e++)_.x=e*c,_.y=e*u,m.x=i-(h-e)*(c+u),m.y=n+(h-e)*c,x=_.x+"|"+_.y,b=m.x+"|"+m.y,C(y,s,x,b);for(let i=0;i<this.vertices.length;i++)x=this.vertices[i].x+"|"+this.vertices[i].y,v=y+"|"+x,v in t||(t[v]=e++,E[x][0]>2?S[t[v]]=[-E[x][0],E[x][1],t[v]]:S[t[v]]=[T[E[x][0]],E[x][1],t[v]])}this.closestTo=S,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,n=e*e+t*t+e*t;this.coau=(e+t)/n,this.cobu=-t/n,this.coav=-i*(e-t)/n,this.cobv=i*(2*e+t)/n}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i<t+e+1;i++)for(let e=this.min[i];e<this.max[i]+1;e++)e<this.max[i]&&e<this.max[i+1]+1&&this.innerFacets.push(["|"+e+"|"+i,"|"+e+"|"+(i+1),"|"+(e+1)+"|"+i]),i>0&&e<this.max[i-1]&&e+1<this.max[i]+1&&this.innerFacets.push(["|"+e+"|"+i,"|"+(e+1)+"|"+i,"|"+(e+1)+"|"+(i-1)])}edgeVecsABOB(){const e=this.m,t=this.n,i=new xf(-t,e+t);for(let n=1;n<e+t;n++){const e=new xf(this.min[n],n),t=new xf(this.min[n-1],n-1),s=new xf(this.min[n+1],n+1),r=e.clone(),o=t.clone(),a=s.clone();r.rotate60About(i),o.rotate60About(i),a.rotate60About(i);const l=new xf(this.max[r.y],r.y),h=new xf(this.max[r.y-1],r.y-1),c=new xf(this.max[r.y-1]-1,r.y-1);r.x===l.x&&r.y===l.y||(r.x!==h.x?(this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([e,h,c]),this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([e,c,l])):r.y===a.y?(this.vertexTypes.push([1,1,0]),this.isoVecsABOB.push([e,t,h]),this.vertexTypes.push([1,0,1]),this.isoVecsABOB.push([e,h,s])):(this.vertexTypes.push([1,1,0]),this.isoVecsABOB.push([e,t,h]),this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([e,h,l])))}}mapABOBtoOBOA(){const e=new xf(0,0);for(let t=0;t<this.isoVecsABOB.length;t++){const i=[];for(let n=0;n<3;n++)e.x=this.isoVecsABOB[t][n].x,e.y=this.isoVecsABOB[t][n].y,0===this.vertexTypes[t][n]&&e.rotateNeg120(this.m,this.n),i.push(e.clone());this.isoVecsOBOA.push(i)}}mapABOBtoBAOA(){const e=new xf(0,0);for(let t=0;t<this.isoVecsABOB.length;t++){const i=[];for(let n=0;n<3;n++)e.x=this.isoVecsABOB[t][n].x,e.y=this.isoVecsABOB[t][n].y,1===this.vertexTypes[t][n]&&e.rotate120(this.m,this.n),i.push(e.clone());this.isoVecsBAOA.push(i)}}MapToFace(e,t){const i=this.IDATA.face[e],n=i[2],s=i[1],r=i[0],a=o.P.FromArray(this.IDATA.vertex[n]),l=o.P.FromArray(this.IDATA.vertex[s]),h=o.P.FromArray(this.IDATA.vertex[r]),c=l.subtract(a),u=h.subtract(a),d=c.scale(this.coau).add(u.scale(this.cobu)),p=c.scale(this.coav).add(u.scale(this.cobv)),f=[];let _,m=o.jp.Vector3[0];for(let i=0;i<this.cartesian.length;i++)m=d.scale(this.cartesian[i].x).add(p.scale(this.cartesian[i].y)).add(a),f[i]=[m.x,m.y,m.z],_=e+"|"+this.vertices[i].x+"|"+this.vertices[i].y,t.vertex[this.vecToidx[_]]=[m.x,m.y,m.z]}build(e,t){const i=new Array,n=xf.Zero(),s=new xf(e,t),r=new xf(-t,e+t);i.push(n,s,r);for(let n=t;n<e+1;n++)for(let t=0;t<e+1-n;t++)i.push(new xf(t,n));if(t>0){const n=lt.R.HCF(e,t),s=e/n,r=t/n;for(let o=1;o<n;o++)i.push(new xf(o*s,o*r)),i.push(new xf(-o*r,o*(s+r))),i.push(new xf(e-o*(s+r),t+o*s));const o=e/t;for(let n=1;n<t;n++)for(let s=0;s<n*o;s++)i.push(new xf(s,n)),i.push(new xf(s,n).rotate120(e,t)),i.push(new xf(s,n).rotateNeg120(e,t))}i.sort(((e,t)=>e.x-t.x)),i.sort(((e,t)=>e.y-t.y));const o=new Array(e+t+1),a=new Array(e+t+1);for(let e=0;e<o.length;e++)o[e]=1/0,a[e]=-1/0;let l=0,h=0;const c=i.length;for(let e=0;e<c;e++)h=i[e].x,l=i[e].y,o[l]=Math.min(h,o[l]),a[l]=Math.max(h,a[l]);const u=(i,n)=>{const s=i.clone();return"A"===n&&s.rotateNeg120(e,t),"B"===n&&s.rotate120(e,t),s.x<0?s.y:s.x+s.y},d=[],p=[],f=[],_=[],m={},g=[];let v=-1,y=-1;for(let e=0;e<c;e++)d[e]=i[e].toCartesianOrigin(new xf(0,0),.5),p[e]=u(i[e],"O"),f[e]=u(i[e],"A"),_[e]=u(i[e],"B"),p[e]===f[e]&&f[e]===_[e]?(v=3,y=p[e]):p[e]===f[e]?(v=4,y=p[e]):f[e]===_[e]?(v=5,y=f[e]):_[e]===p[e]&&(v=6,y=p[e]),p[e]<f[e]&&p[e]<_[e]&&(v=2,y=p[e]),f[e]<p[e]&&f[e]<_[e]&&(v=1,y=f[e]),_[e]<f[e]&&_[e]<p[e]&&(v=0,y=_[e]),g.push([v,y,i[e].x,i[e].y]);g.sort(((e,t)=>e[2]-t[2])),g.sort(((e,t)=>e[3]-t[3])),g.sort(((e,t)=>e[1]-t[1])),g.sort(((e,t)=>e[0]-t[0]));for(let e=0;e<g.length;e++)m[g[e][2]+"|"+g[e][3]]=[g[e][0],g[e][1],e];return this.m=e,this.n=t,this.vertices=i,this.vertByDist=m,this.cartesian=d,this.min=o,this.max=a,this}}class Tf{constructor(e,t,i,n){this.name=e,this.category=t,this.vertex=i,this.face=n}}class Sf extends Tf{innerToData(e,t){for(let i=0;i<t.innerFacets.length;i++)this.face.push(t.innerFacets[i].map((i=>t.vecToidx[e+i])))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let n=0;n<t.isoVecsABOB.length;n++){const s=[];for(let r=0;r<3;r++)0===t.vertexTypes[n][r]?s.push(e+"|"+t.isoVecsABOB[n][r].x+"|"+t.isoVecsABOB[n][r].y):s.push(i+"|"+t.isoVecsABOB[n][r].x+"|"+t.isoVecsABOB[n][r].y);this.face.push([t.vecToidx[s[0]],t.vecToidx[s[1]],t.vecToidx[s[2]]])}}mapOBOAtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let n=0;n<t.isoVecsOBOA.length;n++){const s=[];for(let r=0;r<3;r++)1===t.vertexTypes[n][r]?s.push(e+"|"+t.isoVecsOBOA[n][r].x+"|"+t.isoVecsOBOA[n][r].y):s.push(i+"|"+t.isoVecsOBOA[n][r].x+"|"+t.isoVecsOBOA[n][r].y);this.face.push([t.vecToidx[s[0]],t.vecToidx[s[1]],t.vecToidx[s[2]]])}}mapBAOAtoDATA(e,t){const i=t.IDATA.edgematch[e][2];for(let n=0;n<t.isoVecsBAOA.length;n++){const s=[];for(let r=0;r<3;r++)1===t.vertexTypes[n][r]?s.push(e+"|"+t.isoVecsBAOA[n][r].x+"|"+t.isoVecsBAOA[n][r].y):s.push(i+"|"+t.isoVecsBAOA[n][r].x+"|"+t.isoVecsBAOA[n][r].y);this.face.push([t.vecToidx[s[0]],t.vecToidx[s[1]],t.vecToidx[s[2]]])}}orderData(e){const t=[];for(let e=0;e<13;e++)t[e]=[];const i=e.closestTo;for(let e=0;e<i.length;e++)i[e][0]>-1?i[e][1]>0&&t[i[e][0]].push([e,i[e][1]]):t[12].push([e,i[e][0]]);const n=[];for(let e=0;e<12;e++)n[e]=e;let s=12;for(let e=0;e<12;e++){t[e].sort(((e,t)=>e[1]-t[1]));for(let i=0;i<t[e].length;i++)n[t[e][i][0]]=s++}for(let e=0;e<t[12].length;e++)n[t[12][e][0]]=s++;for(let e=0;e<this.vertex.length;e++)this.vertex[e].push(n[e]);this.vertex.sort(((e,t)=>e[3]-t[3]));for(let e=0;e<this.vertex.length;e++)this.vertex[e].pop();for(let e=0;e<this.face.length;e++)for(let t=0;t<this.face[e].length;t++)this.face[e][t]=n[this.face[e][t]];this.sharedNodes=t[12].length,this.poleNodes=this.vertex.length-this.sharedNodes}setOrder(e,t){const i=[],n=[];let s=t.pop();n.push(s);let r=this.face[s].indexOf(e);r=(r+2)%3;let o=this.face[s][r];i.push(o);let a=0;for(;t.length>0;)s=t[a],this.face[s].indexOf(o)>-1?(r=(this.face[s].indexOf(o)+1)%3,o=this.face[s][r],i.push(o),n.push(s),t.splice(a,1),a=0):a++;return this.adjacentFaces.push(i),n}toGoldbergPolyhedronData(){const e=new Tf("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let e=0;e<t;e++)i[e]=[];for(let e=0;e<this.face.length;e++)for(let t=0;t<3;t++)i[this.face[e][t]].push(e);let n=0,s=0,r=0,o=[],a=[];this.adjacentFaces=[];for(let t=0;t<i.length;t++)e.face[t]=this.setOrder(t,i[t].concat([])),i[t].forEach((t=>{n=0,s=0,r=0,o=this.face[t];for(let e=0;e<3;e++)a=this.vertex[o[e]],n+=a[0],s+=a[1],r+=a[2];e.vertex[t]=[n/3,s/3,r/3]}));return e}static BuildGeodesicData(e){const t=new Sf("Geodesic-m-n","Geodesic",[[0,Me.Q_,-1],[-Me.Q_,1,0],[-1,0,-Me.Q_],[1,0,-Me.Q_],[Me.Q_,1,0],[0,Me.Q_,1],[-1,0,Me.Q_],[-Me.Q_,-1,0],[0,-Me.Q_,-1],[Me.Q_,-1,0],[1,0,Me.Q_],[0,-Me.Q_,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;i<e.IDATA.face.length;i++)e.MapToFace(i,t),t.innerToData(i,e),"B"===e.IDATA.edgematch[i][1]&&t.mapABOBtoDATA(i,e),"O"===e.IDATA.edgematch[i][1]&&t.mapOBOAtoDATA(i,e),"A"===e.IDATA.edgematch[i][3]&&t.mapBAOAtoDATA(i,e);return t.orderData(e),t.vertex=t.vertex.map((function(e){const t=e[0],i=e[1],n=e[2],s=Math.sqrt(t*t+i*i+n*n);return e[0]*=1/s,e[1]*=1/s,e[2]*=1/s,e})),t}}function Ef(e,t,i=null){let n=t.m||1;n!==Math.floor(n)&&(Math.floor(n),_.Y.Warn("m not an integer only floor(m) used"));let s=t.n||0;if(s!==Math.floor(s)&&(Math.floor(s),_.Y.Warn("n not an integer only floor(n) used")),s>n){const e=s;s=n,n=e,_.Y.Warn("n > m therefore m and n swapped")}const r=new bf;return r.build(n,s),ya(e,{custom:Sf.BuildGeodesicData(r),size:t.size,sizeX:t.sizeX,sizeY:t.sizeY,sizeZ:t.sizeZ,faceUV:t.faceUV,faceColors:t.faceColors,flat:t.flat,updatable:t.updatable,sideOrientation:t.sideOrientation,frontUVs:t.frontUVs,backUVs:t.backUVs},i)}function Cf(e,t){const i=e.size,n=e.sizeX||i||1,s=e.sizeY||i||1,r=e.sizeZ||i||1,a=0===e.sideOrientation?0:e.sideOrientation||sn.x.DEFAULTSIDE,l=new Array,h=new Array,c=new Array,u=new Array;let d=1/0,p=-1/0,f=1/0,_=-1/0;for(let e=0;e<t.vertex.length;e++)d=Math.min(d,t.vertex[e][0]*n),p=Math.max(p,t.vertex[e][0]*n),f=Math.min(f,t.vertex[e][1]*s),_=Math.max(_,t.vertex[e][1]*s);let m=0;for(let e=0;e<t.face.length;e++){const i=t.face[e],a=o.P.FromArray(t.vertex[i[0]]),g=o.P.FromArray(t.vertex[i[2]]),v=o.P.FromArray(t.vertex[i[1]]),y=g.subtract(a),x=v.subtract(a),b=o.P.Cross(x,y).normalize();for(let e=0;e<i.length;e++){c.push(b.x,b.y,b.z);const o=t.vertex[i[e]];l.push(o[0]*n,o[1]*s,o[2]*r);const a=(o[1]*s-f)/(_-f);u.push((o[0]*n-d)/(p-d),rn.e.UseOpenGLOrientationForUV?1-a:a)}for(let e=0;e<i.length-2;e++)h.push(m,m+e+2,m+e+1);m+=i.length}sn.x._ComputeSides(a,l,h,c,u);const g=new sn.x;return g.positions=l,g.indices=h,g.normals=c,g.uvs=u,g}function Af(e,t,i=null){const n=t.size,s=t.sizeX||n||1,r=t.sizeY||n||1,l=t.sizeZ||n||1;let h=t.m||1;h!==Math.floor(h)&&(Math.floor(h),_.Y.Warn("m not an integer only floor(m) used"));let c=t.n||0;if(c!==Math.floor(c)&&(Math.floor(c),_.Y.Warn("n not an integer only floor(n) used")),c>h){const e=c;c=h,h=e,_.Y.Warn("n > m therefore m and n swapped")}const u=new bf;u.build(h,c);const d=Sf.BuildGeodesicData(u),p=d.toGoldbergPolyhedronData(),f=new Vp(e,i);t.sideOrientation=Nt.Kj._GetDefaultSideOrientation(t.sideOrientation),f._originalBuilderSideOrientation=t.sideOrientation,Cf(t,p).applyToMesh(f,t.updatable),f.goldbergData.nbSharedFaces=d.sharedNodes,f.goldbergData.nbUnsharedFaces=d.poleNodes,f.goldbergData.adjacentFaces=d.adjacentFaces,f.goldbergData.nbFaces=f.goldbergData.nbSharedFaces+f.goldbergData.nbUnsharedFaces,f.goldbergData.nbFacesAtPole=(f.goldbergData.nbUnsharedFaces-12)/12;for(let e=0;e<d.vertex.length;e++)f.goldbergData.faceCenters.push(o.P.FromArray(d.vertex[e])),f.goldbergData.faceCenters[e].x*=s,f.goldbergData.faceCenters[e].y*=r,f.goldbergData.faceCenters[e].z*=l,f.goldbergData.faceColors.push(new a.HE(1,1,1,1));for(let e=0;e<p.face.length;e++){const t=p.face[e],i=o.P.FromArray(p.vertex[t[0]]),n=o.P.FromArray(p.vertex[t[2]]),s=o.P.FromArray(p.vertex[t[1]]),r=n.subtract(i),a=s.subtract(i),l=o.P.Cross(a,r).normalize(),h=o.P.Cross(a,l).normalize();f.goldbergData.faceXaxis.push(a.normalize()),f.goldbergData.faceYaxis.push(l),f.goldbergData.faceZaxis.push(h)}return f}Nt.Kj.CreateGoldberg=Af;const Pf={CreateBox:Yn.NR,CreateTiledBox:jp,CreateSphere:Kn,CreateDisc:Ca,CreateIcoSphere:cf.Au,CreateRibbon:fs,CreateCylinder:an,CreateTorus:cn,CreateTorusKnot:Kp,CreateLineSystem:rs,CreateLines:os,CreateDashedLines:as,ExtrudeShape:ms,ExtrudeShapeCustom:gs,CreateLathe:of,CreateTiledPlane:Wp,CreatePlane:pa.pT,CreateGround:dn.$6,CreateTiledGround:dn.DG,CreateGroundFromHeightMap:dn.W,CreatePolygon:nf,ExtrudePolygon:sf,CreateTube:lf,CreatePolyhedron:ya,CreateGeodesic:Ef,CreateGoldberg:Af,CreateDecal:vf,CreateCapsule:Jn};class Rf{constructor(e,t,i){this.quality=e,this.distance=t,this.optimizeMesh=i}}class Mf{constructor(){this.running=!1,this._simplificationArray=[]}addTask(e){this._simplificationArray.push(e)}executeNext(){const e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1}runSimplification(e){if(e.parallelProcessing)e.settings.forEach((t=>{this._getSimplifier(e).simplify(t,(i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()}))}));else{const t=this._getSimplifier(e),i=(i,n)=>{t.simplify(i,(t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,n()}))};de.$g.Run(e.settings.length,(t=>{i(e.settings[t.index],(()=>{t.executeNext()}))}),(()=>{e.successCallback&&e.successCallback(),this.executeNext()}))}}_getSimplifier(e){return e.simplificationType,If.QUADRATIC,new Ff(e.mesh)}}var If;!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(If||(If={}));class Df{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class Of{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new wf,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class wf{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,n,s,r,o,a,l){return this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[n]*this.data[a]+this.data[t]*this.data[r]*this.data[o]-this.data[i]*this.data[s]*this.data[o]-this.data[e]*this.data[r]*this.data[a]-this.data[t]*this.data[n]*this.data[l]}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 wf;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,n){return new wf(wf.DataFromNumbers(e,t,i,n))}static DataFromNumbers(e,t,i,n){return[e*e,e*t,e*i,e*n,t*t,t*i,t*n,i*i,i*n,n*n]}}class Nf{constructor(e,t){this.vertexId=e,this.triangleId=t}}class Ff{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=Me.kn}simplify(e,t){this._initDecimatedMesh(),de.$g.Run(this._mesh.subMeshes.length,(t=>{this._initWithMesh(t.index,(()=>{this._runDecimation(e,t.index,(()=>{t.executeNext()}))}),e.optimizeMesh)}),(()=>{setTimeout((()=>{t(this._reconstructedMesh)}),0)}))}_runDecimation(e,t,i){const n=~~(this._triangles.length*e.quality);let s=0;const r=this._triangles.length,a=(e,t)=>{setTimeout((()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e<this._triangles.length;++e)this._triangles[e].isDirty=!1;const i=1e-9*Math.pow(e+3,this.aggressiveness);de.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=~~((this._triangles.length/2+e)%this._triangles.length),n=this._triangles[t];if(n&&!(n.error[3]>i||n.deleted||n.isDirty))for(let e=0;e<3;++e)if(n.error[e]<i){const t=[],i=[],r=n._vertices[e],a=n._vertices[(e+1)%3];if(r.isBorder||a.isBorder)continue;const l=o.P.Zero();this._calculateError(r,a,l);const h=new Array;if(this._isFlipped(r,a,l,t,h))continue;if(this._isFlipped(a,r,l,i,h))continue;if(t.indexOf(!0)<0||i.indexOf(!0)<0)continue;const c=new Array;if(h.forEach((e=>{-1===c.indexOf(e)&&(e.deletePending=!0,c.push(e))})),c.length%2!=0)continue;r.q=a.q.add(r.q),r.updatePosition(l);const u=this._references.length;s=this._updateTriangles(r,r,t,s),s=this._updateTriangles(r,a,i,s);const d=this._references.length-u;if(d<=r.triangleCount){if(d)for(let e=0;e<d;e++)this._references[r.triangleStart+e]=this._references[u+e]}else r.triangleStart=u;r.triangleCount=d;break}}),t,(()=>r-s<=n))}),0)};de.$g.Run(this.decimationIterations,(e=>{r-s<=n?e.breakLoop():a(e.index,(()=>{e.executeNext()}))}),(()=>{setTimeout((()=>{this._reconstructMesh(t),i()}),0)}))}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const n=this._mesh.getVerticesData(qe.o.PositionKind),s=this._mesh.getIndices(),r=this._mesh.subMeshes[e],a=e=>{if(i)for(let t=0;t<this._vertices.length;++t)if(this._vertices[t].position.equalsWithEpsilon(e,1e-4))return this._vertices[t];return null},l=[],h=r.verticesCount;de.$g.SyncAsyncForLoop(h,this.syncIterations/4>>0,(e=>{if(!n)return;const t=e+r.verticesStart,i=o.P.FromArray(n,3*t),s=a(i)||new Of(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),l.push(s.id)}),(()=>{de.$g.SyncAsyncForLoop(r.indexCount/3,this.syncIterations,(e=>{if(!s)return;const t=3*(r.indexStart/3+e),i=s[t+0],n=s[t+1],o=s[t+2],a=this._vertices[l[i-r.verticesStart]],h=this._vertices[l[n-r.verticesStart]],c=this._vertices[l[o-r.verticesStart]],u=new Df([a,h,c]);u.originalOffset=t,this._triangles.push(u)}),(()=>{this._init(t)}))}))}_init(e){de.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];t.normal=o.P.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(wf.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-o.P.Dot(t.normal,t._vertices[0].position)))}),(()=>{de.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])}),(()=>{e()}))}))}_reconstructMesh(e){const t=[];let i,n,s;for(i=0;i<this._vertices.length;++i)this._vertices[i].triangleCount=0;for(i=0;i<this._triangles.length;++i)if(!this._triangles[i].deleted){for(n=this._triangles[i],s=0;s<3;++s)n._vertices[s].triangleCount=1;t.push(n)}const r=this._reconstructedMesh.getVerticesData(qe.o.PositionKind)||[],o=this._reconstructedMesh.getVerticesData(qe.o.NormalKind)||[],a=this._reconstructedMesh.getVerticesData(qe.o.UVKind)||[],l=this._reconstructedMesh.getVerticesData(qe.o.ColorKind)||[],h=this._mesh.getVerticesData(qe.o.NormalKind),c=this._mesh.getVerticesData(qe.o.UVKind),u=this._mesh.getVerticesData(qe.o.ColorKind);let d=0;for(i=0;i<this._vertices.length;++i){const e=this._vertices[i];e.id=d,e.triangleCount&&e.originalOffsets.forEach((t=>{r.push(e.position.x),r.push(e.position.y),r.push(e.position.z),h&&h.length&&(o.push(h[3*t]),o.push(h[3*t+1]),o.push(h[3*t+2])),c&&c.length&&(a.push(c[2*t]),a.push(c[2*t+1])),u&&u.length&&(l.push(u[4*t]),l.push(u[4*t+1]),l.push(u[4*t+2]),l.push(u[4*t+3])),++d}))}const p=this._reconstructedMesh.getTotalIndices(),f=this._reconstructedMesh.getTotalVertices(),_=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(i=0;i<t.length;++i)n=t[i],[0,1,2].forEach((e=>{const t=g[n.originalOffset+e];let i=n._vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),m.push(n._vertices[e].id+i+f)}));this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(qe.o.PositionKind,r),o.length>0&&this._reconstructedMesh.setVerticesData(qe.o.NormalKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(qe.o.UVKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(qe.o.ColorKind,l);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],_.forEach((e=>{Ll.P.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),Ll.P.AddToMesh(v.materialIndex,f,d,p,3*t.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new Nt.Kj(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,n,s){for(let r=0;r<e.triangleCount;++r){const a=this._triangles[this._references[e.triangleStart+r].triangleId];if(a.deleted)continue;const l=this._references[e.triangleStart+r].vertexId,h=a._vertices[(l+1)%3],c=a._vertices[(l+2)%3];if(h===t||c===t){n[r]=!0,s.push(a);continue}let u=h.position.subtract(i);u=u.normalize();let d=c.position.subtract(i);if(d=d.normalize(),Math.abs(o.P.Dot(u,d))>.999)return!0;const p=o.P.Cross(u,d).normalize();if(n[r]=!1,o.P.Dot(p,a.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,n){let s=n;for(let n=0;n<t.triangleCount;++n){const r=this._references[t.triangleStart+n],o=this._triangles[r.triangleId];o.deleted||(i[n]&&o.deletePending?(o.deleted=!0,s++):(o._vertices[r.vertexId]=e,o.isDirty=!0,o.error[0]=this._calculateError(o._vertices[0],o._vertices[1])+o.borderFactor/2,o.error[1]=this._calculateError(o._vertices[1],o._vertices[2])+o.borderFactor/2,o.error[2]=this._calculateError(o._vertices[2],o._vertices[0])+o.borderFactor/2,o.error[3]=Math.min(o.error[0],o.error[1],o.error[2]),this._references.push(r)))}return s}_identifyBorder(){for(let e=0;e<this._vertices.length;++e){const t=[],i=[],n=this._vertices[e];let s;for(s=0;s<n.triangleCount;++s){const e=this._triangles[this._references[n.triangleStart+s].triangleId];for(let n=0;n<3;n++){let s=0;const r=e._vertices[n];for(;s<t.length&&i[s]!==r.id;)++s;s===t.length?(t.push(1),i.push(r.id)):t[s]++}}for(s=0;s<t.length;++s)1===t[s]?this._vertices[i[s]].isBorder=!0:this._vertices[i[s]].isBorder=!1}}_updateMesh(e=!1){let t,i,n,s;if(!e){const e=[];for(t=0;t<this._triangles.length;++t)this._triangles[t].deleted||e.push(this._triangles[t]);this._triangles=e}for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleCount=0,this._vertices[t].triangleStart=0;for(t=0;t<this._triangles.length;++t)for(i=this._triangles[t],n=0;n<3;++n)s=i._vertices[n],s.triangleCount++;let r=0;for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleStart=r,r+=this._vertices[t].triangleCount,this._vertices[t].triangleCount=0;const o=new Array(3*this._triangles.length);for(t=0;t<this._triangles.length;++t)for(i=this._triangles[t],n=0;n<3;++n)s=i._vertices[n],o[s.triangleStart+s.triangleCount]=new Nf(n,t),s.triangleCount++;this._references=o,e&&this._identifyBorder()}_vertexError(e,t){const i=t.x,n=t.y,s=t.z;return e.data[0]*i*i+2*e.data[1]*i*n+2*e.data[2]*i*s+2*e.data[3]*i+e.data[4]*n*n+2*e.data[5]*n*s+2*e.data[6]*n+e.data[7]*s*s+2*e.data[8]*s+e.data[9]}_calculateError(e,t,i){const n=e.q.add(t.q),s=e.isBorder&&t.isBorder;let r=0;const a=n.det(0,1,2,1,4,5,2,5,7);if(0===a||s){const s=e.position.add(t.position).divide(new o.P(2,2,2)),a=this._vertexError(n,e.position),l=this._vertexError(n,t.position),h=this._vertexError(n,s);r=Math.min(a,l,h),r===a?i&&i.copyFrom(e.position):r===l?i&&i.copyFrom(t.position):i&&i.copyFrom(s)}else i||(i=o.P.Zero()),i.x=-1/a*n.det(1,2,3,4,5,6,5,7,8),i.y=1/a*n.det(0,2,3,1,5,6,2,7,8),i.z=-1/a*n.det(0,1,3,1,4,6,2,5,8),r=this._vertexError(n,i);return r}}Object.defineProperty(k.x.prototype,"simplificationQueue",{get:function(){if(!this._simplificationQueue){this._simplificationQueue=new Mf;let e=this._getComponent(ve.l.NAME_SIMPLIFICATIONQUEUE);e||(e=new Lf(this),this._addComponent(e))}return this._simplificationQueue},set:function(e){this._simplificationQueue=e},enumerable:!0,configurable:!0}),Nt.Kj.prototype.simplify=function(e,t=!0,i=If.QUADRATIC,n){return this.getScene().simplificationQueue.addTask({settings:e,parallelProcessing:t,mesh:this,simplificationType:i,successCallback:n}),this};class Lf{constructor(e){this.name=ve.l.NAME_SIMPLIFICATIONQUEUE,this.scene=e}register(){this.scene._beforeCameraUpdateStage.registerStep(ve.l.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE,this,this._beforeCameraUpdate)}rebuild(){}dispose(){}_beforeCameraUpdate(){this.scene._simplificationQueue&&!this.scene._simplificationQueue.running&&this.scene._simplificationQueue.executeNext()}}var Bf=i(447),Uf=i(8261),Vf=(i(2708),i(7780));class kf{constructor(e=Recast){this.bjsRECAST={},this.name="RecastJSPlugin",this._maximumSubStepCount=10,this._timeStep=1/60,this._timeFactor=1,this._worker=null,"function"==typeof e?_.Y.Error("RecastJS is not ready. Please make sure you await Recast() before using the plugin."):this.bjsRECAST=e,this.isSupported()?(this.setTimeStep(),this._tempVec1=new this.bjsRECAST.Vec3,this._tempVec2=new this.bjsRECAST.Vec3):_.Y.Error("RecastJS is not available. Please make sure you included the js file.")}setWorkerURL(e){return!(!window||!window.Worker||(this._worker=new Worker(e),0))}setTimeStep(e=1/60){this._timeStep=e}getTimeStep(){return this._timeStep}setMaximumSubStepCount(e=10){this._maximumSubStepCount=e}getMaximumSubStepCount(){return this._maximumSubStepCount}set timeFactor(e){this._timeFactor=Math.max(e,0)}get timeFactor(){return this._timeFactor}createNavMesh(e,t,i){let n,s,r;this._worker&&!i?console.warn("A worker is avaible but no completion callback. Defaulting to blocking navmesh creation"):!this._worker&&i&&console.warn("A completion callback is avaible but no worker. Defaulting to blocking navmesh creation"),this.navMesh=new this.bjsRECAST.NavMesh;const o=[],a=[];let l=0;for(n=0;n<e.length;n++)if(e[n]){const t=e[n],i=t.getIndices();if(!i)continue;const h=t.getVerticesData(qe.o.PositionKind,!1,!1);if(!h)continue;const c=[],u=t.computeWorldMatrix(!0);if(t.hasThinInstances){const e=t.thinInstanceGetWorldMatrices();for(let t=0;t<e.length;t++){const i=new Gr.y3;e[t].multiplyToRef(u,i),c.push(i)}}else c.push(u);for(let e=0;e<c.length;e++){const t=c[e];for(s=0;s<i.length;s++)o.push(i[s]+l);const n=Gr.P.Zero(),u=Gr.P.Zero();for(r=0;r<h.length;r+=3)Gr.P.FromArrayToRef(h,r,u),Gr.P.TransformCoordinatesToRef(u,t,n),a.push(n.x,n.y,n.z);l+=h.length/3}}if(this._worker&&i)this._worker.postMessage([a,l,o,o.length,t]),this._worker.onmessage=function(e){i(e.data)};else{const e=new this.bjsRECAST.rcConfig;e.cs=t.cs,e.ch=t.ch,e.borderSize=t.borderSize?t.borderSize:0,e.tileSize=t.tileSize?t.tileSize:0,e.walkableSlopeAngle=t.walkableSlopeAngle,e.walkableHeight=t.walkableHeight,e.walkableClimb=t.walkableClimb,e.walkableRadius=t.walkableRadius,e.maxEdgeLen=t.maxEdgeLen,e.maxSimplificationError=t.maxSimplificationError,e.minRegionArea=t.minRegionArea,e.mergeRegionArea=t.mergeRegionArea,e.maxVertsPerPoly=t.maxVertsPerPoly,e.detailSampleDist=t.detailSampleDist,e.detailSampleMaxError=t.detailSampleMaxError,this.navMesh.build(a,l,o,o.length,e)}}createDebugNavMesh(e){let t,i;const n=this.navMesh.getDebugNavMesh(),s=n.getTriangleCount(),r=[],o=[];for(t=0;t<3*s;t++)r.push(t);for(t=0;t<s;t++)for(i=0;i<3;i++){const e=n.getTriangle(t).getPoint(i);o.push(e.x,e.y,e.z)}const a=new Nt.Kj("NavMeshDebug",e),l=new sn.x;return l.indices=r,l.positions=o,l.applyToMesh(a,!1),a}getClosestPoint(e){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z;const t=this.navMesh.getClosestPoint(this._tempVec1);return new Gr.P(t.x,t.y,t.z)}getClosestPointToRef(e,t){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z;const i=this.navMesh.getClosestPoint(this._tempVec1);t.set(i.x,i.y,i.z)}getRandomPointAround(e,t){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z;const i=this.navMesh.getRandomPointAround(this._tempVec1,t);return new Gr.P(i.x,i.y,i.z)}getRandomPointAroundToRef(e,t,i){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z;const n=this.navMesh.getRandomPointAround(this._tempVec1,t);i.set(n.x,n.y,n.z)}moveAlong(e,t){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this._tempVec2.x=t.x,this._tempVec2.y=t.y,this._tempVec2.z=t.z;const i=this.navMesh.moveAlong(this._tempVec1,this._tempVec2);return new Gr.P(i.x,i.y,i.z)}moveAlongToRef(e,t,i){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this._tempVec2.x=t.x,this._tempVec2.y=t.y,this._tempVec2.z=t.z;const n=this.navMesh.moveAlong(this._tempVec1,this._tempVec2);i.set(n.x,n.y,n.z)}computePath(e,t){let i;this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this._tempVec2.x=t.x,this._tempVec2.y=t.y,this._tempVec2.z=t.z;const n=this.navMesh.computePath(this._tempVec1,this._tempVec2),s=n.getPointCount(),r=[];for(i=0;i<s;i++){const e=n.getPoint(i);r.push(new Gr.P(e.x,e.y,e.z))}return r}createCrowd(e,t,i){return new Gf(this,e,t,i)}setDefaultQueryExtent(e){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this.navMesh.setDefaultQueryExtent(this._tempVec1)}getDefaultQueryExtent(){const e=this.navMesh.getDefaultQueryExtent();return new Gr.P(e.x,e.y,e.z)}buildFromNavmeshData(e){const t=e.length*e.BYTES_PER_ELEMENT,i=this.bjsRECAST._malloc(t),n=new Uint8Array(this.bjsRECAST.HEAPU8.buffer,i,t);n.set(e);const s=new this.bjsRECAST.NavmeshData;s.dataPointer=n.byteOffset,s.size=e.length,this.navMesh=new this.bjsRECAST.NavMesh,this.navMesh.buildFromNavmeshData(s),this.bjsRECAST._free(n.byteOffset)}getNavmeshData(){const e=this.navMesh.getNavmeshData(),t=new Uint8Array(this.bjsRECAST.HEAPU8.buffer,e.dataPointer,e.size),i=new Uint8Array(e.size);return i.set(t),this.navMesh.freeNavmeshData(e),i}getDefaultQueryExtentToRef(e){const t=this.navMesh.getDefaultQueryExtent();e.set(t.x,t.y,t.z)}dispose(){}addCylinderObstacle(e,t,i){return this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this.navMesh.addCylinderObstacle(this._tempVec1,t,i)}addBoxObstacle(e,t,i){return this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this._tempVec2.x=t.x,this._tempVec2.y=t.y,this._tempVec2.z=t.z,this.navMesh.addBoxObstacle(this._tempVec1,this._tempVec2,i)}removeObstacle(e){this.navMesh.removeObstacle(e)}isSupported(){return void 0!==this.bjsRECAST}}class Gf{constructor(e,t,i,n){this.recastCrowd={},this.transforms=new Array,this.agents=new Array,this.reachRadii=new Array,this._agentDestinationArmed=new Array,this._agentDestination=new Array,this._onBeforeAnimationsObserver=null,this.onReachTargetObservable=new r.y$,this.bjsRECASTPlugin=e,this.recastCrowd=new this.bjsRECASTPlugin.bjsRECAST.Crowd(t,i,this.bjsRECASTPlugin.navMesh.getNavMesh()),this._scene=n,this._onBeforeAnimationsObserver=n.onBeforeAnimationsObservable.add((()=>{this.update(.001*n.getEngine().getDeltaTime()*e.timeFactor)}))}addAgent(e,t,i){const n=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;n.radius=t.radius,n.height=t.height,n.maxAcceleration=t.maxAcceleration,n.maxSpeed=t.maxSpeed,n.collisionQueryRange=t.collisionQueryRange,n.pathOptimizationRange=t.pathOptimizationRange,n.separationWeight=t.separationWeight,n.updateFlags=7,n.obstacleAvoidanceType=0,n.queryFilterType=0,n.userData=0;const s=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),n);return this.transforms.push(i),this.agents.push(s),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new Gr.P(0,0,0)),s}getAgentPosition(e){const t=this.recastCrowd.getAgentPosition(e);return new Gr.P(t.x,t.y,t.z)}getAgentPositionToRef(e,t){const i=this.recastCrowd.getAgentPosition(e);t.set(i.x,i.y,i.z)}getAgentVelocity(e){const t=this.recastCrowd.getAgentVelocity(e);return new Gr.P(t.x,t.y,t.z)}getAgentVelocityToRef(e,t){const i=this.recastCrowd.getAgentVelocity(e);t.set(i.x,i.y,i.z)}getAgentNextTargetPath(e){const t=this.recastCrowd.getAgentNextTargetPath(e);return new Gr.P(t.x,t.y,t.z)}getAgentNextTargetPathToRef(e,t){const i=this.recastCrowd.getAgentNextTargetPath(e);t.set(i.x,i.y,i.z)}getAgentState(e){return this.recastCrowd.getAgentState(e)}overOffmeshConnection(e){return this.recastCrowd.overOffmeshConnection(e)}agentGoto(e,t){this.recastCrowd.agentGoto(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z));const i=this.agents.indexOf(e);i>-1&&(this._agentDestinationArmed[i]=!0,this._agentDestination[i].set(t.x,t.y,t.z))}agentTeleport(e,t){this.recastCrowd.agentTeleport(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))}updateAgentParameters(e,t){const i=this.recastCrowd.getAgentParameters(e);void 0!==t.radius&&(i.radius=t.radius),void 0!==t.height&&(i.height=t.height),void 0!==t.maxAcceleration&&(i.maxAcceleration=t.maxAcceleration),void 0!==t.maxSpeed&&(i.maxSpeed=t.maxSpeed),void 0!==t.collisionQueryRange&&(i.collisionQueryRange=t.collisionQueryRange),void 0!==t.pathOptimizationRange&&(i.pathOptimizationRange=t.pathOptimizationRange),void 0!==t.separationWeight&&(i.separationWeight=t.separationWeight),this.recastCrowd.setAgentParameters(e,i)}removeAgent(e){this.recastCrowd.removeAgent(e);const t=this.agents.indexOf(e);t>-1&&(this.agents.splice(t,1),this.transforms.splice(t,1),this.reachRadii.splice(t,1),this._agentDestinationArmed.splice(t,1),this._agentDestination.splice(t,1))}getAgents(){return this.agents}update(e){if(this.bjsRECASTPlugin.navMesh.update(),e<=Gr.kn)return;const t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=Gr.kn)this.recastCrowd.update(e);else{let n=Math.floor(e/t);i&&n>i&&(n=i),n<1&&(n=1);const s=e/n;for(let e=0;e<n;e++)this.recastCrowd.update(s)}for(let e=0;e<this.agents.length;e++){const t=this.agents[e],i=this.getAgentPosition(t);if(this.transforms[e].position=i,this._agentDestinationArmed[e]){const n=i.x-this._agentDestination[e].x,s=i.z-this._agentDestination[e].z,r=this.reachRadii[e],o=this._agentDestination[e].y-this.reachRadii[e],a=this._agentDestination[e].y+this.reachRadii[e],l=n*n+s*s;i.y>o&&i.y<a&&l<r*r&&(this.onReachTargetObservable.notifyObservers({agentIndex:t,destination:this._agentDestination[e]}),this._agentDestinationArmed[e]=!1)}}}setDefaultQueryExtent(e){const t=new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z);this.recastCrowd.setDefaultQueryExtent(t)}getDefaultQueryExtent(){const e=this.recastCrowd.getDefaultQueryExtent();return new Gr.P(e.x,e.y,e.z)}getDefaultQueryExtentToRef(e){const t=this.recastCrowd.getDefaultQueryExtent();e.set(t.x,t.y,t.z)}getCorners(e){let t;const i=this.recastCrowd.getCorners(e),n=i.getPointCount(),s=[];for(t=0;t<n;t++){const e=i.getPoint(t);s.push(new Gr.P(e.x,e.y,e.z))}return s}dispose(){this.recastCrowd.destroy(),this._scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.onReachTargetObservable.clear()}}ue.D.OfflineProviderFactory=(e,t,i=!1)=>new zf(e,t,i);class zf{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=zf._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,zf.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,de.w1.SetImmediate((()=>{t(!0)}))):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){const e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`};let n=!1,s=i();const r=new Kc.g;navigator.onLine&&(n=!0,s=s+(null==s.match(/\?/)?"?":"&")+Date.now()),r.open("GET",s),r.addEventListener("load",(()=>{if(200===r.status||zf._ValidateXHRData(r,1))try{const t=JSON.parse(r.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&zf._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()}),!1),r.addEventListener("error",(()=>{if(n){n=!1;const e=i();r.open("GET",e),r.send()}else t()}),!1);try{r.send()}catch(t){_.Y.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))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{_.Y.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){_.Y.Error("Error while creating object stores. Exception: "+e.message),i()}}}else this._isSupported=!1,t&&t()}loadImage(e,t){const i=zf._ReturnFullUrlLocation(e),n=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?n():this._loadImageFromDBAsync(i,t,n)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let n;const s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;n&&"function"==typeof URL?(s=URL.createObjectURL(n.data),t.onerror=()=>{_.Y.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};const r=s.objectStore("textures").get(e);r.onsuccess=e=>{n=e.target.result},r.onerror=()=>{_.Y.Error("Error loading texture "+e+" from DB."),t.src=e}}else _.Y.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 n=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(zf._IsUASupportingBlobStorage){const s=new Kc.g;s.open("GET",e),s.responseType="blob",s.addEventListener("load",(()=>{if(200===s.status&&this._db){i=s.response;const r=this._db.transaction(["textures"],"readwrite");r.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}n()},r.oncomplete=()=>{n()};const o={textureUrl:e,data:i};try{const e=r.objectStore("textures").put(o);e.onsuccess=()=>{},e.onerror=()=>{n()}}catch(i){25===i.code&&(zf._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e}),!1),s.addEventListener("error",(()=>{_.Y.Error("Error in XHR request in BABYLON.Database."),t.src=e}),!1),s.send()}else t.src=e}else _.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,(()=>{this._saveVersionIntoDBAsync(e,t)}))}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let n;try{const s=this._db.transaction(["versions"]);s.oncomplete=()=>{n?this._manifestVersionFound!==n.data?(this._mustUpdateRessources=!0,i()):t(n.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};const r=s.objectStore("versions").get(e);r.onsuccess=e=>{n=e.target.result},r.onerror=()=>{_.Y.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){_.Y.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else _.Y.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=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const n={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(n);s.onsuccess=()=>{},s.onerror=()=>{_.Y.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){_.Y.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,n,s){const r=zf._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(r,t,i,s,n)};this._checkVersionFromDB(r,(e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(r,t,i,s,n):this._loadFileAsync(r,t,o):n&&n()}))}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let n,s;n=-1!==e.indexOf(".babylon")?"scenes":"textures";const r=this._db.transaction([n]);r.oncomplete=()=>{s?t(s.data):i()},r.onabort=()=>{i()};const o=r.objectStore(n).get(e);o.onsuccess=e=>{s=e.target.result},o.onerror=()=>{_.Y.Error("Error loading file "+e+" from DB."),i()}}else _.Y.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,n,s){if(this._isSupported){let r;r=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=new Kc.g;let a;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),n&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",(()=>{if(200===o.status||o.status<400&&zf._ValidateXHRData(o,n?6:1))if(a=n?o.response:o.responseText,!this._hasReachedQuota&&this._db){const i=this._db.transaction([r],"readwrite");let n;i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},i.oncomplete=()=>{t(a)},n="scenes"===r?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{const e=i.objectStore(r).put(n);e.onsuccess=()=>{},e.onerror=()=>{_.Y.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a);else o.status>=400&&s?s(o):t()}),!1),o.addEventListener("error",(()=>{_.Y.Error("error on XHR request."),s&&s()}),!1),o.send()}else _.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),s&&s()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){const i=Pc(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){const t=new Uint8Array(e.response,0,3);return 68===t[0]&&68===t[1]&&83===t[2]}}catch(e){}return!1}}zf._IsUASupportingBlobStorage=!0,zf.IDBStorageEnabled=!1,zf._ParseURL=e=>{document.createElement("a").href=e;const t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},zf._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?zf._ParseURL(window.location.href)+e:e;var Wf=i(5753),Hf=i(5089),Xf=i(5098);class jf{_isUbo(e){return void 0!==e.addUniform}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))}}si.v.ShadersStore.gpuUpdateParticlesPixelShader="#version 300 es\nvoid main() {\ndiscard;\n}\n";si.v.ShadersStore.gpuUpdateParticlesVertexShader="#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \nif (newAge>=life && stopFactor != 0.) {\nvec3 newPosition;\nvec3 newDirection;\nvec4 randoms=getRandomVec4(seed.x);\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=newAge-life;\noutSeed=seed;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nnewPosition=vec3(0,0,0);\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nnewPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\nnewDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\nnewDirection=newPosition+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nnewPosition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;\nnewDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));\nnewDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h *height.x;\nnewPosition=vec3(randX,randY,randZ); \nif (abs(cos(coneAngle))==1.0) {\nnewDirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\nnewDirection=normalize(newPosition+directionRandomizer*randoms3); \n}\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;\noutInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);\nnewDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;\nif (cellInfos.w==1.0) {\nratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);\n}\nelse {\nratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);\n}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}";class Yf{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:[]}}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateEffect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}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 Xf.E&&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 ds.Q("gpuUpdateParticles",this._updateEffectOptions,this._engine),new jf(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)}createParticleBuffer(e){return e}bindDrawBuffers(e){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 n=this._engine;n.bindTransformFeedbackBuffer(t.getBuffer()),n.setRasterizerState(!1),n.beginTransformFeedback(!0),n.drawArraysType(3,0,i),n.endTransformFeedback(),n.setRasterizerState(!0),n.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e<this._updateVAO.length;e++)this._engine.releaseVertexArrayObject(this._updateVAO[e]);this._updateVAO.length=0;for(let e=0;e<this._renderVAO.length;e++)this._engine.releaseVertexArrayObject(this._renderVAO[e]);this._renderVAO.length=0}_createUpdateVAO(e){const t={};t.position=e.createVertexBuffer("position",0,3);let i=3;t.age=e.createVertexBuffer("age",i,1),i+=1,t.size=e.createVertexBuffer("size",i,3),i+=3,t.life=e.createVertexBuffer("life",i,1),i+=1,t.seed=e.createVertexBuffer("seed",i,4),i+=4,t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._parent.particleEmitterType instanceof Xf.E&&(t.initialPosition=e.createVertexBuffer("initialPosition",i,3),i+=3),this._parent._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),this._parent._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._parent.noiseTexture&&(t.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",i,3),i+=3,t.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",i,3),i+=3),this._parent._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._parent._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1,this._parent.spriteRandomStartCell&&(t.cellStartOffset=e.createVertexBuffer("cellStartOffset",i,1),i+=1));const n=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),n}}(0,l.H)("BABYLON.WebGL2ParticleSystem",Yf);si.v.ShadersStoreWGSL.gpuUpdateParticlesComputeShader="struct Particle {\nposition : vec3<f32>,\nage : f32,\nsize : vec3<f32>,\nlife : f32,\nseed : vec4<f32>,\ndirection : vec3<f32>,\ndummy0: f32,\n#ifdef CUSTOMEMITTER\ninitialPosition : vec3<f32>,\ndummy1: f32,\n#endif\n#ifndef COLORGRADIENTS\ncolor : vec4<f32>,\n#endif\n#ifndef BILLBOARD\ninitialDirection : vec3<f32>,\ndummy2: f32,\n#endif\n#ifdef NOISE\nnoiseCoordinates1 : vec3<f32>,\ndummy3: f32,\nnoiseCoordinates2 : vec3<f32>,\ndummy4: f32,\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nangle : f32,\n#else\nangle : vec2<f32>,\n#endif\n#ifdef ANIMATESHEET\ncellIndex : f32,\n#ifdef ANIMATESHEETRANDOMSTART\ncellStartOffset : f32,\n#endif\n#endif\n};\nstruct Particles {\nparticles : array<Particle>,\n};\nstruct SimParams {\ncurrentCount : f32,\ntimeDelta : f32,\nstopFactor : f32,\nrandomTextureSize: i32,\nlifeTime : vec2<f32>,\nemitPower : vec2<f32>,\n#ifndef COLORGRADIENTS\ncolor1 : vec4<f32>,\ncolor2 : vec4<f32>,\n#endif\nsizeRange : vec2<f32>,\nscaleRange : vec4<f32>,\nangleRange : vec4<f32>,\ngravity : vec3<f32>,\n#ifdef LIMITVELOCITYGRADIENTS\nlimitVelocityDamping : f32,\n#endif\n#ifdef ANIMATESHEET\ncellInfos : vec4<f32>,\n#endif\n#ifdef NOISE\nnoiseStrength : vec3<f32>,\n#endif\n#ifndef LOCAL\nemitterWM : mat4x4<f32>,\n#endif\n#ifdef BOXEMITTER\ndirection1 : vec3<f32>,\ndirection2 : vec3<f32>,\nminEmitBox : vec3<f32>,\nmaxEmitBox : vec3<f32>,\n#endif\n#ifdef CONEEMITTER\nradius : vec2<f32>,\nconeAngle : f32,\nheight : vec2<f32>,\ndirectionRandomizer : f32,\n#endif\n#ifdef CYLINDEREMITTER\nradius : f32,\nheight : f32,\nradiusRange : f32,\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection1 : vec3<f32>,\ndirection2 : vec3<f32>,\n#else\ndirectionRandomizer : f32,\n#endif\n#endif\n#ifdef HEMISPHERICEMITTER\nradius : f32,\nradiusRange : f32,\ndirectionRandomizer : f32,\n#endif\n#ifdef POINTEMITTER\ndirection1 : vec3<f32>,\ndirection2 : vec3<f32>,\n#endif\n#ifdef SPHEREEMITTER\nradius : f32,\nradiusRange : f32,\n#ifdef DIRECTEDSPHEREEMITTER\ndirection1 : vec3<f32>,\ndirection2 : vec3<f32>,\n#else\ndirectionRandomizer : f32,\n#endif\n#endif\n};\n@binding(0) @group(0) var<uniform> params : SimParams;\n@binding(1) @group(0) var<storage,read> particlesIn : Particles;\n@binding(2) @group(0) var<storage,read_write> particlesOut : Particles;\n@binding(3) @group(0) var randomTexture : texture_2d<f32>;\n@binding(4) @group(0) var randomTexture2 : texture_2d<f32>;\n#ifdef SIZEGRADIENTS\n@binding(0) @group(1) var sizeGradientSampler : sampler;\n@binding(1) @group(1) var sizeGradientTexture : texture_2d<f32>;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\n@binding(2) @group(1) var angularSpeedGradientSampler : sampler;\n@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d<f32>;\n#endif \n#ifdef VELOCITYGRADIENTS\n@binding(4) @group(1) var velocityGradientSampler : sampler;\n@binding(5) @group(1) var velocityGradientTexture : texture_2d<f32>;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\n@binding(6) @group(1) var limitVelocityGradientSampler : sampler;\n@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d<f32>;\n#endif\n#ifdef DRAGGRADIENTS\n@binding(8) @group(1) var dragGradientSampler : sampler;\n@binding(9) @group(1) var dragGradientTexture : texture_2d<f32>;\n#endif\n#ifdef NOISE\n@binding(10) @group(1) var noiseSampler : sampler;\n@binding(11) @group(1) var noiseTexture : texture_2d<f32>;\n#endif\nfn getRandomVec3(offset : f32,vertexID : f32)->vec3<f32> {\nreturn textureLoad(randomTexture2,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;\n}\nfn getRandomVec4(offset : f32,vertexID : f32)->vec4<f32> {\nreturn textureLoad(randomTexture,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);\n}\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) GlobalInvocationID : vec3<u32>) {\nlet index : u32=GlobalInvocationID.x;\nlet vertexID : f32=f32(index);\nif (index>=u32(params.currentCount)) {\nreturn;\n}\nlet PI : f32=3.14159;\nlet timeDelta : f32=params.timeDelta;\nlet newAge : f32=particlesIn.particles[index].age+timeDelta;\nlet life : f32=particlesIn.particles[index].life;\nlet seed : vec4<f32>=particlesIn.particles[index].seed;\nlet direction : vec3<f32>=particlesIn.particles[index].direction;\nif (newAge>=life && params.stopFactor != 0.) {\nvar newPosition : vec3<f32>;\nvar newDirection : vec3<f32>;\nlet randoms : vec4<f32>=getRandomVec4(seed.x,vertexID);\nlet outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;\nparticlesOut.particles[index].life=outLife;\nparticlesOut.particles[index].age=newAge-life;\nparticlesOut.particles[index].seed=seed;\nvar sizex : f32;\n#ifdef SIZEGRADIENTS \nsizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(0.,0.),0.).r;\n#else\nsizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g;\n#endif\nparticlesOut.particles[index].size=vec3<f32>(\nsizex,\nparams.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b,\nparams.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a);\n#ifndef COLORGRADIENTS\nparticlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \nparticlesOut.particles[index].angle=vec2<f32>(\nparams.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r,\nparams.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a);\n#else\nparticlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r;\n#endif \n#if defined(POINTEMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);\nlet randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);\nnewPosition=vec3<f32>(0.,0.,0.);\nnewDirection=params.direction1+(params.direction2-params.direction1)*randoms3;\n#elif defined(BOXEMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);\nlet randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);\nnewPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;\nnewDirection=params.direction1+(params.direction2-params.direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);\nlet randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);\nlet phi : f32=2.0*PI*randoms2.x;\nlet theta : f32=acos(-1.0+2.0*randoms2.y);\nlet randX : f32=cos(phi)*sin(theta);\nlet randY : f32=cos(theta);\nlet randZ : f32=sin(phi)*sin(theta);\nnewPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,abs(randY),randZ);\nnewDirection=normalize(newPosition+params.directionRandomizer*randoms3);\n#elif defined(SPHEREEMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);\nlet randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);\nlet phi : f32=2.0*PI*randoms2.x;\nlet theta : f32=acos(-1.0+2.0*randoms2.y);\nlet randX : f32=cos(phi)*sin(theta);\nlet randY : f32=cos(theta);\nlet randZ : f32=sin(phi)*sin(theta);\nnewPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+params.directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);\nlet randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);\nlet yPos : f32=(-0.5+randoms2.x)*params.height;\nvar angle : f32=randoms2.y*PI*2.;\nlet inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);\nlet positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));\nlet xPos : f32=positionRadius*cos(angle);\nlet zPos : f32=positionRadius*sin(angle);\nnewPosition=vec3<f32>(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=params.direction1+(params.direction2-params.direction1)*randoms3;\n#else\nangle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;\nnewDirection=vec3<f32>(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));\nnewDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);\nlet s : f32=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nlet h : f32=0.0001;\n#else\nvar h : f32=randoms2.y*params.height.y;\nh=1.-h*h; \n#endif\nvar lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;\nlRadius=lRadius*h;\nlet randX : f32=lRadius*sin(s);\nlet randZ : f32=lRadius*cos(s);\nlet randY : f32=h *params.height.x;\nnewPosition=vec3<f32>(randX,randY,randZ); \nif (abs(cos(params.coneAngle))==1.0) {\nnewDirection=vec3<f32>(0.,1.0,0.);\n} else {\nlet randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);\nnewDirection=normalize(newPosition+params.directionRandomizer*randoms3); \n}\n#elif defined(CUSTOMEMITTER)\nnewPosition=particlesIn.particles[index].initialPosition;\nparticlesOut.particles[index].initialPosition=newPosition;\n#else \nnewPosition=vec3<f32>(0.,0.,0.);\nnewDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3<f32>(0.5,0.5,0.5));\n#endif\nlet power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a;\n#ifdef LOCAL\nparticlesOut.particles[index].position=newPosition;\n#else\nparticlesOut.particles[index].position=(params.emitterWM*vec4<f32>(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\nparticlesOut.particles[index].direction=direction;\n#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nlet initial : vec3<f32>=newDirection;\n#else \nlet initial : vec3<f32>=(params.emitterWM*vec4<f32>(newDirection,0.)).xyz;\n#endif\nparticlesOut.particles[index].direction=initial*power;\n#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \nparticlesOut.particles[index].cellIndex=params.cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\nparticlesOut.particles[index].cellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\nparticlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;\nparticlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2;\n#endif\n} else {\nvar directionScale : f32=timeDelta;\nparticlesOut.particles[index].age=newAge;\nlet ageGradient : f32=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2<f32>(ageGradient,0.),0.).r);\n#endif\nlet position : vec3<f32>=particlesIn.particles[index].position;\n#if defined(CUSTOMEMITTER)\nparticlesOut.particles[index].position=position+(direction-position)*ageGradient; \nparticlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition;\n#else\nparticlesOut.particles[index].position=position+direction*directionScale;\n#endif\nparticlesOut.particles[index].life=life;\nparticlesOut.particles[index].seed=seed;\n#ifndef COLORGRADIENTS \nparticlesOut.particles[index].color=particlesIn.particles[index].color;\n#endif\n#ifdef SIZEGRADIENTS\nparticlesOut.particles[index].size=vec3<f32>(\ntextureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(ageGradient,0.),0.).r,\nparticlesIn.particles[index].size.yz);\n#else\nparticlesOut.particles[index].size=particlesIn.particles[index].size;\n#endif \n#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\nparticlesOut.particles[index].direction=direction;\n#else\nvar updatedDirection : vec3<f32>=direction+params.gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nlet limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;\nlet currentVelocity : f32=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*params.limitVelocityDamping;\n}\n#endif\nparticlesOut.particles[index].direction=updatedDirection;\n#ifdef NOISE\nlet noiseCoordinates1 : vec3<f32>=particlesIn.particles[index].noiseCoordinates1;\nlet noiseCoordinates2 : vec3<f32>=particlesIn.particles[index].noiseCoordinates2;\nlet fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.x,noiseCoordinates1.y)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;\nlet fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.z,noiseCoordinates2.x)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;\nlet fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates2.y,noiseCoordinates2.z)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;\nlet force : vec3<f32>=vec3<f32>(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;\nparticlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;\nparticlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;\nparticlesOut.particles[index].noiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nlet angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2<f32>(ageGradient,0.),0.).r;\nparticlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta;\n#else\nlet angle : vec2<f32>=particlesIn.particles[index].angle;\nparticlesOut.particles[index].angle=vec2<f32>(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nvar offsetAge : f32=particlesOut.particles[index].age;\nlet dist : f32=params.cellInfos.y-params.cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\nlet cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;\nparticlesOut.particles[index].cellStartOffset=cellStartOffset;\noffsetAge=offsetAge+cellStartOffset;\n#else\nlet cellStartOffset : f32=0.;\n#endif \nvar ratio : f32;\nif (params.cellInfos.w==1.0) {\nratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);\n}\nelse {\nratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);\n}\nparticlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist));\n#endif\n}\n}\n";class qf{constructor(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}isUpdateBufferCreated(){return!!this._updateComputeShader}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateComputeShader)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}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 Dn("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split("\n")}),null===(t=this._simParamsComputeShader)||void 0===t||t.dispose(),this._simParamsComputeShader=new Ci.M(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 jf(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){const t=new $e(this._engine,4*e.length,11);return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()}bindDrawBuffers(e,t){this._engine.bindBuffers(this._renderVertexBuffers[e],null,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[1^e]),this._updateComputeShader.dispatch(Math.ceil(i/64))}releaseBuffers(){var e;for(let e=0;e<this._bufferComputeShader.length;++e)this._bufferComputeShader[e].dispose();this._bufferComputeShader.length=0,null===(e=this._simParamsComputeShader)||void 0===e||e.dispose(),this._simParamsComputeShader=null,this._updateComputeShader=null}releaseVertexBuffers(){this._renderVertexBuffers.length=0}}(0,l.H)("BABYLON.ComputeShaderParticleSystem",qf);class Kf{constructor(e,t,i){this.gradient=e,this.color1=t,this.color2=i}getColorToRef(e){this.color2?a.HE.LerpToRef(this.color1,this.color2,Math.random(),e):e.copyFrom(this.color1)}}class $f{constructor(e,t){this.gradient=e,this.color=t}}class Qf{constructor(e,t,i){this.gradient=e,this.factor1=t,this.factor2=i}getFactor(){return void 0===this.factor2||this.factor2===this.factor1?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()}}class Zf{static GetCurrentGradient(e,t,i){if(t[0].gradient>e)return void i(t[0],t[0],1);for(let n=0;n<t.length-1;n++){const s=t[n],r=t[n+1];if(e>=s.gradient&&e<=r.gradient)return void i(s,r,(e-s.gradient)/(r.gradient-s.gradient))}const n=t.length-1;i(t[n],t[n],1)}}class Jf{constructor(e){this.particleSystem=e,this.position=o.P.Zero(),this.direction=o.P.Zero(),this.color=new a.HE(0,0,0,0),this.colorStep=new a.HE(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new o.FM(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new a.HE(0,0,0,0),this._currentColor2=new a.HE(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=Jf._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID;let n;n=this._initialSpriteCellLoop?lt.R.Clamp(e*t%this.lifeTime/this.lifeTime):lt.R.Clamp(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+n*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=o.jp.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,o.jp.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(o.jp.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=Jf._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 o.Lt(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()))}}var e_;Jf._Count=0,function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(e_||(e_={}));class t_{constructor(e){if(this.particleSystem=e,this.type=e_.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=(0,l.q)("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof o.P?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&(e=new((0,l.q)("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1):e=new o.P;const t=new t_(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,n=!1){throw(0,Zl.S)("ParseParticle")}static Parse(e,t,i){const n=e.particleSystem,s=new t_(t_._ParseParticleSystem(n,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}}i(1030),i(8773);si.v.ShadersStore.particlesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<logDepthDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include<logDepthFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}",i(5501);si.v.ShadersStore.particlesVertexShader="attribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;\nvarying vec4 vColor;\nvarying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<logDepthDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvPositionW=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition;\nvPositionW=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;\nvPositionW=(invView*vec4(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvPositionW=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(vPositionW,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex*particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset/particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include<clipPlaneVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}";class i_ extends Wf.U{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 null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Ps.q(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 r.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,n=null,s=!1,l=.01){super(e),this._emitterInverseWorldMatrix=o.y3.Identity(),this._inheritedVelocityOffset=new o.P,this.onDisposeObservable=new r.y$,this.onStoppedObservable=new r.y$,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new a.HE(0,0,0,0),this._colorDiff=new a.HE(0,0,0,0),this._scaledDirection=o.P.Zero(),this._scaledGravity=o.P.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=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;if(0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new Jf(this),this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach((t=>{if(t.type===e_.ATTACHED){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}return e},this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(t.type===e_.END){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))},this._capacity=t,this._epsilon=l,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=o.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||A.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new Ps.q(this._engine)},this._customWrappers[0].effect=n,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new Hf.S3;let h=null;this.updateFunction=e=>{var t;let i=null;this.noiseTexture&&(i=this.noiseTexture.getSize(),null===(t=this.noiseTexture.getContent())||void 0===t||t.then((e=>{h=e})));for(let t=0;t<e.length;t++){const n=e[t];let s=this._scaledUpdateSpeed;const r=n.age;if(n.age+=s,n.age>n.lifeTime){const e=n.age-r;s=(n.lifeTime-r)*s/e,n.age=n.lifeTime}const l=n.age/n.lifeTime;this._colorGradients&&this._colorGradients.length>0?Zf.GetCurrentGradient(l,this._colorGradients,((e,t,i)=>{e!==n._currentColorGradient&&(n._currentColor1.copyFrom(n._currentColor2),t.getColorToRef(n._currentColor2),n._currentColorGradient=e),a.HE.LerpToRef(n._currentColor1,n._currentColor2,i,n.color)})):(n.colorStep.scaleToRef(s,this._scaledColorStep),n.color.addInPlace(this._scaledColorStep),n.color.a<0&&(n.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&Zf.GetCurrentGradient(l,this._angularSpeedGradients,((e,t,i)=>{e!==n._currentAngularSpeedGradient&&(n._currentAngularSpeed1=n._currentAngularSpeed2,n._currentAngularSpeed2=t.getFactor(),n._currentAngularSpeedGradient=e),n.angularSpeed=lt.R.Lerp(n._currentAngularSpeed1,n._currentAngularSpeed2,i)})),n.angle+=n.angularSpeed*s;let c=s;if(this._velocityGradients&&this._velocityGradients.length>0&&Zf.GetCurrentGradient(l,this._velocityGradients,((e,t,i)=>{e!==n._currentVelocityGradient&&(n._currentVelocity1=n._currentVelocity2,n._currentVelocity2=t.getFactor(),n._currentVelocityGradient=e),c*=lt.R.Lerp(n._currentVelocity1,n._currentVelocity2,i)})),n.direction.scaleToRef(c,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&Zf.GetCurrentGradient(l,this._limitVelocityGradients,((e,t,i)=>{e!==n._currentLimitVelocityGradient&&(n._currentLimitVelocity1=n._currentLimitVelocity2,n._currentLimitVelocity2=t.getFactor(),n._currentLimitVelocityGradient=e);const s=lt.R.Lerp(n._currentLimitVelocity1,n._currentLimitVelocity2,i);n.direction.length()>s&&n.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&Zf.GetCurrentGradient(l,this._dragGradients,((e,t,i)=>{e!==n._currentDragGradient&&(n._currentDrag1=n._currentDrag2,n._currentDrag2=t.getFactor(),n._currentDragGradient=e);const s=lt.R.Lerp(n._currentDrag1,n._currentDrag2,i);this._scaledDirection.scaleInPlace(1-s)})),this.isLocal&&n._localPosition?(n._localPosition.addInPlace(this._scaledDirection),o.P.TransformCoordinatesToRef(n._localPosition,this._emitterWorldMatrix,n.position)):n.position.addInPlace(this._scaledDirection),h&&i&&n._randomNoiseCoordinates1){const e=this._fetchR(n._randomNoiseCoordinates1.x,n._randomNoiseCoordinates1.y,i.width,i.height,h),t=this._fetchR(n._randomNoiseCoordinates1.z,n._randomNoiseCoordinates2.x,i.width,i.height,h),r=this._fetchR(n._randomNoiseCoordinates2.y,n._randomNoiseCoordinates2.z,i.width,i.height,h),a=o.jp.Vector3[0],l=o.jp.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*t-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),a.scaleToRef(s,l),n.direction.addInPlace(l)}this.gravity.scaleToRef(s,this._scaledGravity),n.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&Zf.GetCurrentGradient(l,this._sizeGradients,((e,t,i)=>{e!==n._currentSizeGradient&&(n._currentSize1=n._currentSize2,n._currentSize2=t.getFactor(),n._currentSizeGradient=e),n.size=lt.R.Lerp(n._currentSize1,n._currentSize2,i)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&Zf.GetCurrentGradient(l,this._colorRemapGradients,((e,t,i)=>{const s=lt.R.Lerp(e.factor1,t.factor1,i),r=lt.R.Lerp(e.factor2,t.factor2,i);n.remapData.x=s,n.remapData.y=r-s})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&Zf.GetCurrentGradient(l,this._alphaRemapGradients,((e,t,i)=>{const s=lt.R.Lerp(e.factor1,t.factor1,i),r=lt.R.Lerp(e.factor2,t.factor2,i);n.remapData.z=s,n.remapData.w=r-s}))),this._isAnimationSheetEnabled&&n.updateCellIndex(),n._inheritParticleInfoToSubEmitters(),n.age>=n.lifeTime&&(this._emitFromParticle(n),n._attachedSubEmitters&&(n._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),n._attachedSubEmitters=null),this.recycleParticle(n),t--)}}}_addFactorGradient(e,t,i,n){const s=new Qf(t,i,n);e.push(s),e.sort(((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const n of e){if(n.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(4*this._rawTextureWidth),t=a.zZ.Color3[0];for(let i=0;i<this._rawTextureWidth;i++){const n=i/this._rawTextureWidth;Zf.GetCurrentGradient(n,this._rampGradients,((n,s,r)=>{a.Wo.LerpToRef(n.color,s.color,r,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=Ee.l.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort(((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0)),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new $f(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 n=new Kf(e,t,i);return this._colorGradients.push(n),this._colorGradients.sort(((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.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)null==t||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,n,s){return s[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*n%n|0)*i)]/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!==i_.BILLBOARDMODE_STRETCHED&&this.billboardMode!==i_.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 qe.l(e,this._vertexData,!0,t);let i=0;const n=this._vertexBuffer.createVertexBuffer(qe.o.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[qe.o.PositionKind]=n,i+=3;const s=this._vertexBuffer.createVertexBuffer(qe.o.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[qe.o.ColorKind]=s,i+=4;const r=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=r,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||this.billboardMode===i_.BILLBOARDMODE_STRETCHED||this.billboardMode===i_.BILLBOARDMODE_STRETCHED_LOCAL){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let a;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new qe.l(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return;const e=[];let t=0;for(let i=0;i<this._capacity;i++)e.push(t),e.push(t+1),e.push(t+2),e.push(t),e.push(t+2),e.push(t+3),t+=4;this._indexBuffer=this._engine.createIndexBuffer(e)}getCapacity(){return this._capacity}isAlive(){return this._alive}isStarted(){return this._started}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach((e=>{e instanceof i_?this._subEmitters.push([new t_(e)]):e instanceof t_?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);else{if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=new Array),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){-1!==(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t<this.preWarmCycles;t++)this.animate(!0),e.render()}))}));else for(let e=0;e<this.preWarmCycles;e++)this.animate(!0)}this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,n){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)this.billboardMode!==i_.BILLBOARDMODE_STRETCHED&&this.billboardMode!==i_.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(o.P.TransformNormalToRef(e,this._emitterWorldMatrix,o.jp.Vector3[0]),e=o.jp.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}else{let e=t.direction;this.isLocal&&(o.P.TransformNormalToRef(e,this._emitterWorldMatrix,o.jp.Vector3[0]),e=o.jp.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===n?n=this._epsilon:1===n&&(n=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=n)}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach((e=>{e.stop(!0)})),this.activeSubSystems=new Array)}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=o.y3.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i<e&&this._particles.length!==this._capacity;i++){if(t=this._createParticle(),this._particles.push(t),this.targetStopDuration&&this._lifeTimeGradients&&this._lifeTimeGradients.length>0){const e=lt.R.Clamp(this._actualFrame/this.targetStopDuration);Zf.GetCurrentGradient(e,this._lifeTimeGradients,((i,n)=>{const s=i,r=n,o=s.getFactor(),a=r.getFactor(),l=(e-s.gradient)/(r.gradient-s.gradient);t.lifeTime=lt.R.Lerp(o,a,l)}))}else t.lifeTime=lt.R.RandomRange(this.minLifeTime,this.maxLifeTime);const e=lt.R.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(),o.P.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),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(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.size=lt.R.RandomRange(this.minSize,this.maxSize),t.scale.copyFromFloats(lt.R.RandomRange(this.minScaleX,this.maxScaleX),lt.R.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;Zf.GetCurrentGradient(e,this._startSizeGradients,((e,i,n)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const s=lt.R.Lerp(this._currentStartSize1,this._currentStartSize2,n);t.scale.scaleInPlace(s)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(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.angularSpeed=lt.R.RandomRange(this.minAngularSpeed,this.maxAngularSpeed),t.angle=lt.R.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&&0!==this._colorGradients.length)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);else{const e=lt.R.RandomRange(0,1);a.HE.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new o.Lt(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 o.P(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new o.P(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const n=[qe.o.PositionKind,qe.o.ColorKind,"angle","offset","size"];return e&&n.push("cellIndex"),t||n.push("direction"),i&&n.push("remapData"),n}static _GetEffectCreationOptions(e=!1,t=!1){const i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return(0,Ga.qx)(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&(0,Ga.lK)(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===i_.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case i_.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case i_.BILLBOARDMODE_STRETCHED:case i_.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===i_.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case i_.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...i_._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==i_.BILLBOARDMODE_STRETCHED&&this.billboardMode!==i_.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...i_._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(ki.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ki.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;const i=[];this.fillDefines(i,e);const n=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let s=this._drawWrappers[n];s||(s=this._drawWrappers[n]=[]);let r=s[e];r||(r=new Ps.q(this._engine),r.drawContext&&(r.drawContext.useInstancing=this._useInstancing),s[e]=r);const o=i.join("\n");if(r.defines!==o){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("particles",e,t,i,o),o)}return r}animate(e=!1){var t;if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let i;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this.manualEmitCount>-1)i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;Zf.GetCurrentGradient(t,this._emitRateGradients,((t,i,n)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=lt.R.Lerp(this._currentEmitRate1,this._currentEmitRate2,n)}))}i=e*this._scaledUpdateSpeed>>0,this._newPartsExcess+=e*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 e=0;for(let t=0;t<this._particles.length;t++){const i=this._particles[t];this._appendParticleVertices(e,i),e+=this._useInstancing?1:4}this._vertexBuffer&&this._vertexBuffer.updateDirectly(this._vertexData,0,this._particles.length)}0===this.manualEmitCount&&this.disposeOnStop&&this.stop()}_appendParticleVertices(e,t){this._appendParticleVertex(e++,t,0,0),this._useInstancing||(this._appendParticleVertex(e++,t,1,0),this._appendParticleVertex(e++,t,1,1),this._appendParticleVertex(e++,t,0,1))}rebuild(){var e,t;this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._createIndexBuffer(),null===(e=this._spriteBuffer)||void 0===e||e._rebuild(),null===(t=this._vertexBuffer)||void 0===t||t._rebuild();for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild();this.resetDrawCache()}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==i_.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(i_.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(i_.BLENDMODE_ADD).effect.isReady())return!1}return!0}_render(e){var t,i;const n=this._getWrapper(e),s=n.effect,r=this._engine;r.enableEffect(n);const a=null!==(t=this.defaultViewMatrix)&&void 0!==t?t:this._scene.getViewMatrix();if(s.setTexture("diffuseSampler",this.particleTexture),s.setMatrix("view",a),s.setMatrix("projection",null!==(i=this.defaultProjectionMatrix)&&void 0!==i?i:this._scene.getProjectionMatrix()),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();s.setFloat3("particlesInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,this.spriteCellWidth/e.width)}if(s.setVector2("translationPivot",this.translationPivot),s.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;s.setVector3("eyePosition",e.globalPosition)}this._rampGradientsTexture&&(this._rampGradients&&this._rampGradients.length||(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),s.setTexture("rampSampler",this._rampGradientsTexture));const l=s.defines;switch(this._scene&&(0,Ga.an)(s,this,this._scene),l.indexOf("#define BILLBOARDMODE_ALL")>=0&&(a.invertToRef(o.jp.Matrix[0]),s.setMatrix("invView",o.jp.Matrix[0])),void 0!==this._vertexArrayObject?(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,s)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):r.bindBuffers(this._vertexBuffers,this._indexBuffer,s),this.useLogarithmicDepth&&this._scene&&La.G.BindLogDepth(l,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case i_.BLENDMODE_ADD:r.setAlphaMode(1);break;case i_.BLENDMODE_ONEONE:r.setAlphaMode(6);break;case i_.BLENDMODE_STANDARD:r.setAlphaMode(2);break;case i_.BLENDMODE_MULTIPLY:r.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),this._useInstancing?r.drawArraysType(7,0,4,this._particles.length):r.drawElementsType(0,0,6*this._particles.length),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 t=this.blendMode===i_.BLENDMODE_MULTIPLYADD?this._render(i_.BLENDMODE_MULTIPLY)+this._render(i_.BLENDMODE_ADD):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._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 e=0;e<this._subEmitters.length;e++)for(const t of this._subEmitters[e])t.dispose();this._subEmitters=[],this.subEmitters=[]}if(this._disposeEmitterOnDispose&&this.emitter&&this.emitter.dispose&&this.emitter.dispose(!0),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){const n={...this._customWrappers};let s=null;const r=this._engine;if(r.createEffectForParticles&&null!=this.customShader){s=this.customShader;const e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=r.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);n[0]?n[0].effect=t:this.setCustomEffect(t,0)}const o=this.serialize(i),a=i_.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=s,a._customWrappers=n,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,this.preventAutoStart||a.start(),a}serialize(e=!1){const t={};if(i_._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 n=[];for(const t of i)n.push(t.serialize(e));t.subEmitters.push(n)}}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 i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.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,Te.p4.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 n=t.getColorGradients();if(n){e.colorGradients=[];for(const t of n){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const s=t.getRampGradients();if(s){e.rampGradients=[];for(const t of s){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const r=t.getColorRemapGradients();if(r){e.colorRemapGradients=[];for(const t of r){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const a=t.getSizeGradients();if(a){e.sizeGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const u=t.getEmitRateGradients();if(u){e.emitRateGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const d=t.getStartSizeGradients();if(d){e.startSizeGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const p=t.getLifeTimeGradients();if(p){e.lifeTimeGradients=[];for(const t of p){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const f=t.getLimitVelocityGradients();if(f){e.limitVelocityGradients=[];for(const t of f){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}static _Parse(e,t,i,n){var s,r,h;let c;c=i instanceof Rn.B?null:i;const u=(0,l.q)("BABYLON.Texture");if(u&&c&&(e.texture?t.particleTexture=u.Parse(e.texture,c,n):e.textureName&&(t.particleTexture=new u(n+e.textureName,c,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&c?t.emitter=c.getLastMeshById(e.emitterId):t.emitter=o.P.FromArray(e.emitter):t.emitter=o.P.Zero(),t.isLocal=!!e.isLocal,void 0!==e.renderingGroupId&&(t.renderingGroupId=e.renderingGroupId),void 0!==e.isBillboardBased&&(t.isBillboardBased=e.isBillboardBased),void 0!==e.billboardMode&&(t.billboardMode=e.billboardMode),void 0!==e.useLogarithmicDepth&&(t.useLogarithmicDepth=e.useLogarithmicDepth),e.animations){for(let i=0;i<e.animations.length;i++){const n=e.animations[i],s=(0,l.q)("BABYLON.Animation");s&&t.animations.push(s.Parse(n))}t.beginAnimationOnStart=e.beginAnimationOnStart,t.beginAnimationFrom=e.beginAnimationFrom,t.beginAnimationTo=e.beginAnimationTo,t.beginAnimationLoop=e.beginAnimationLoop}if(e.autoAnimate&&c&&c.beginAnimation(t,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),t.startDelay=0|e.startDelay,t.minAngularSpeed=e.minAngularSpeed,t.maxAngularSpeed=e.maxAngularSpeed,t.minSize=e.minSize,t.maxSize=e.maxSize,e.minScaleX&&(t.minScaleX=e.minScaleX,t.maxScaleX=e.maxScaleX,t.minScaleY=e.minScaleY,t.maxScaleY=e.maxScaleY),void 0!==e.preWarmCycles&&(t.preWarmCycles=e.preWarmCycles,t.preWarmStepOffset=e.preWarmStepOffset),void 0!==e.minInitialRotation&&(t.minInitialRotation=e.minInitialRotation,t.maxInitialRotation=e.maxInitialRotation),t.minLifeTime=e.minLifeTime,t.maxLifeTime=e.maxLifeTime,t.minEmitPower=e.minEmitPower,t.maxEmitPower=e.maxEmitPower,t.emitRate=e.emitRate,t.gravity=o.P.FromArray(e.gravity),e.noiseStrength&&(t.noiseStrength=o.P.FromArray(e.noiseStrength)),t.color1=a.HE.FromArray(e.color1),t.color2=a.HE.FromArray(e.color2),t.colorDead=a.HE.FromArray(e.colorDead),t.updateSpeed=e.updateSpeed,t.targetStopDuration=e.targetStopDuration,t.blendMode=e.blendMode,e.colorGradients)for(const i of e.colorGradients)t.addColorGradient(i.gradient,a.HE.FromArray(i.color1),i.color2?a.HE.FromArray(i.color2):void 0);if(e.rampGradients){for(const i of e.rampGradients)t.addRampGradient(i.gradient,a.Wo.FromArray(i.color));t.useRampGradients=e.useRampGradients}if(e.colorRemapGradients)for(const i of e.colorRemapGradients)t.addColorRemapGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.alphaRemapGradients)for(const i of e.alphaRemapGradients)t.addAlphaRemapGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.sizeGradients)for(const i of e.sizeGradients)t.addSizeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.angularSpeedGradients)for(const i of e.angularSpeedGradients)t.addAngularSpeedGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.velocityGradients)for(const i of e.velocityGradients)t.addVelocityGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.dragGradients)for(const i of e.dragGradients)t.addDragGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.emitRateGradients)for(const i of e.emitRateGradients)t.addEmitRateGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.startSizeGradients)for(const i of e.startSizeGradients)t.addStartSizeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.lifeTimeGradients)for(const i of e.lifeTimeGradients)t.addLifeTimeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.limitVelocityGradients){for(const i of e.limitVelocityGradients)t.addLimitVelocityGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);t.limitVelocityDamping=e.limitVelocityDamping}if(e.noiseTexture&&c){const i=(0,l.q)("BABYLON.ProceduralTexture");t.noiseTexture=i.Parse(e.noiseTexture,c,n)}let d;if(e.particleEmitterType){switch(e.particleEmitterType.type){case"SphereParticleEmitter":d=new Hf.Ai;break;case"SphereDirectedParticleEmitter":d=new Hf.cE;break;case"ConeEmitter":case"ConeParticleEmitter":d=new Hf.LV;break;case"CylinderParticleEmitter":d=new Hf.kT;break;case"CylinderDirectedParticleEmitter":d=new Hf.z;break;case"HemisphericParticleEmitter":d=new Hf.VD;break;case"PointParticleEmitter":d=new Hf.cl;break;case"MeshParticleEmitter":d=new Hf.F3;break;default:d=new Hf.S3}d.parse(e.particleEmitterType,c)}else d=new Hf.S3,d.parse(e,c);t.particleEmitterType=d,t.startSpriteCellID=e.startSpriteCellID,t.endSpriteCellID=e.endSpriteCellID,t.spriteCellLoop=null===(s=e.spriteCellLoop)||void 0===s||s,t.spriteCellWidth=e.spriteCellWidth,t.spriteCellHeight=e.spriteCellHeight,t.spriteCellChangeSpeed=e.spriteCellChangeSpeed,t.spriteRandomStartCell=e.spriteRandomStartCell,t.disposeOnStop=null!==(r=e.disposeOnStop)&&void 0!==r&&r,t.manualEmitCount=null!==(h=e.manualEmitCount)&&void 0!==h?h:-1}static Parse(e,t,i,n=!1,s){const r=e.name;let o,l,h=null,c=null;if(t instanceof Rn.B?o=t:(l=t,o=l.getEngine()),e.customShader&&o.createEffectForParticles){c=e.customShader;const t=c.shaderOptions.defines.length>0?c.shaderOptions.defines.join("\n"):"";h=o.createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,t)}const u=new i_(r,s||e.capacity,t,h,e.isAnimationSheetEnabled);if(u.customShader=c,u._rootUrl=i,e.id&&(u.id=e.id),e.subEmitters){u.subEmitters=[];for(const n of e.subEmitters){const e=[];for(const s of n)e.push(t_.Parse(s,t,i));u.subEmitters.push(e)}}return i_._Parse(e,u,t,i),e.textureMask&&(u.textureMask=a.HE.FromArray(e.textureMask)),e.preventAutoStart&&(u.preventAutoStart=e.preventAutoStart),n||u.preventAutoStart||u.start(),u}}i_.BILLBOARDMODE_Y=2,i_.BILLBOARDMODE_ALL=7,i_.BILLBOARDMODE_STRETCHED=8,i_.BILLBOARDMODE_STRETCHED_LOCAL=9,t_._ParseParticleSystem=i_.Parse;var n_=i(1499);si.v.IncludesShadersStore.clipPlaneFragmentDeclaration2="#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nin float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nin float fClipDistance6;\n#endif\n";si.v.ShadersStore.gpuRenderParticlesPixelShader="precision highp float;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform sampler2D diffuseSampler;\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<logDepthDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\ngl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif \n#include<logDepthFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\ngl_FragColor=applyImageProcessing(gl_FragColor);\n#endif\n#endif\n}\n";si.v.IncludesShadersStore.clipPlaneVertexDeclaration2="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;\nout float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;\nout float fClipDistance6;\n#endif\n";si.v.ShadersStore.gpuRenderParticlesVertexShader="precision highp float;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\nuniform vec3 worldOffset;\n#ifdef LOCAL\nuniform mat4 emitterWM;\n#endif\nattribute vec3 position;\nattribute float age;\nattribute float life;\nattribute vec3 size;\n#ifndef BILLBOARD\nattribute vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\nattribute float angle;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\nattribute vec2 offset;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying vec4 vColor;\nvarying vec3 vPositionW;\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#include<logDepthDeclaration>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nattribute vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture2D(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=(position+worldOffset)-eyePosition;\nyaxis.y=0.;\nvPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(vPositionW,1.0));\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=(position+worldOffset)-eyePosition;\nvPositionW=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(vPositionW,1.0));\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n#ifdef LOCAL\nvec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;\n#else\nvec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;\n#endif\nvPositionW=(invView*viewPosition).xyz;\n#endif\n#else\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvPositionW=rotate(yaxis,rotatedCorner);\nvec4 viewPosition=view*vec4(vPositionW,1.0);\n#endif\ngl_Position=projection*viewPosition;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include<clipPlaneVertex>\n#include<logDepthVertex>\n}";class s_ extends Wf.U{static get IsSupported(){if(!A.l.LastCreatedEngine)return!1;const e=A.l.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}getCapacity(){return this._capacity}get activeParticleCount(){return this._activeCount}set activeParticleCount(e){this._activeCount=Math.min(e,this._capacity)}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==i_.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(i_.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(i_.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";e?setTimeout((()=>{this.start(0)}),e):(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 null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Ps.q(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new r.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}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 Kf(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort(((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.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)null===(e=this._drawWrappers[t].drawContext)||void 0===e||e.reset()}_addFactorGradient(e,t,i){const n=new Qf(t,i);e.push(n),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(((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0));const n=this;n[t]&&(n[t].dispose(),n[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,n=null,s=!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 r.y$,this.onStoppedObservable=new r.y$,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=o.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||A.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!(0,l.q)("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,l.q)("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!(0,l.q)("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,l.q)("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new Ps.q(this._engine)},this._customWrappers[0].effect=n,this._drawWrappers={0:new Ps.q(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._attachImageProcessingConfiguration(null),(t=null!=t?t:{}).randomTextureSize||delete t.randomTextureSize;const a={capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize,...t},h=t;isFinite(h)&&(a.capacity=h),this._capacity=a.capacity,this._activeCount=a.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=s,this.particleEmitterType=new n_.S;const c=Math.min(this._engine.getCaps().maxTextureSize,a.randomTextureSize);let u=[];for(let e=0;e<c;++e)u.push(Math.random()),u.push(Math.random()),u.push(Math.random()),u.push(Math.random());this._randomTexture=new Ee.l(new Float32Array(u),c,1,5,i,!1,!1,1,1),this._randomTexture.name="GPUParticleSystem_random1",this._randomTexture.wrapU=1,this._randomTexture.wrapV=1,u=[];for(let e=0;e<c;++e)u.push(Math.random()),u.push(Math.random()),u.push(Math.random()),u.push(Math.random());this._randomTexture2=new Ee.l(new Float32Array(u),c,1,5,i,!1,!1,1,1),this._randomTexture2.name="GPUParticleSystem_random2",this._randomTexture2.wrapU=1,this._randomTexture2.wrapV=1,this._randomTextureSize=c}_reset(){this._releaseBuffers()}_createVertexBuffers(e,t,i){const n={};n.position=t.createVertexBuffer("position",0,3,this._attributesStrideSize,!0);let s=3;n.age=t.createVertexBuffer("age",s,1,this._attributesStrideSize,!0),s+=1,n.size=t.createVertexBuffer("size",s,3,this._attributesStrideSize,!0),s+=3,n.life=t.createVertexBuffer("life",s,1,this._attributesStrideSize,!0),s+=1,s+=4,this.billboardMode===i_.BILLBOARDMODE_STRETCHED&&(n.direction=t.createVertexBuffer("direction",s,3,this._attributesStrideSize,!0)),s+=3,this._platform.alignDataInBuffer&&(s+=1),this.particleEmitterType instanceof Xf.E&&(s+=3,this._platform.alignDataInBuffer&&(s+=1)),this._colorGradientsTexture||(n.color=t.createVertexBuffer("color",s,4,this._attributesStrideSize,!0),s+=4),this._isBillboardBased||(n.initialDirection=t.createVertexBuffer("initialDirection",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1)),this.noiseTexture&&(n.noiseCoordinates1=t.createVertexBuffer("noiseCoordinates1",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1),n.noiseCoordinates2=t.createVertexBuffer("noiseCoordinates2",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1)),n.angle=t.createVertexBuffer("angle",s,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?s++:s+=2,this._isAnimationSheetEnabled&&(n.cellIndex=t.createVertexBuffer("cellIndex",s,1,this._attributesStrideSize,!0),s+=1,this.spriteRandomStartCell&&(n.cellStartOffset=t.createVertexBuffer("cellStartOffset",s,1,this._attributesStrideSize,!0),s+=1)),n.offset=i.createVertexBuffer("offset",0,2),n.uv=i.createVertexBuffer("uv",2,2),this._renderVertexBuffers.push(n),this._platform.createVertexBuffers(e,n),this.resetDrawCache()}_initialize(e=!1){if(this._buffer0&&!e)return;const t=this._engine,i=new Array;this._attributesStrideSize=21,this._targetIndex=0,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1),this.particleEmitterType instanceof Xf.E&&(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),this.isBillboardBased||(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1,this.spriteRandomStartCell&&(this._attributesStrideSize+=1)),this.noiseTexture&&(this._attributesStrideSize+=6,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=2)),this._platform.alignDataInBuffer&&(this._attributesStrideSize+=3-(this._attributesStrideSize+3&3));const n=this.particleEmitterType instanceof Xf.E,s=o.jp.Vector3[0];let r=0;for(let e=0;e<this._capacity;e++)if(i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),n?(this.particleEmitterType.particleDestinationGenerator(e,null,s),i.push(s.x),i.push(s.y),i.push(s.z)):(i.push(0),i.push(0),i.push(0)),this._platform.alignDataInBuffer&&i.push(0),r+=16,n&&(this.particleEmitterType.particlePositionGenerator(e,null,s),i.push(s.x),i.push(s.y),i.push(s.z),this._platform.alignDataInBuffer&&i.push(0),r+=4),this._colorGradientsTexture||(i.push(0),i.push(0),i.push(0),i.push(0),r+=4),this.isBillboardBased||(i.push(0),i.push(0),i.push(0),this._platform.alignDataInBuffer&&i.push(0),r+=4),this.noiseTexture&&(i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),r+=8),i.push(0),r+=1,this._angularSpeedGradientsTexture||(i.push(0),r+=1),this._isAnimationSheetEnabled&&(i.push(0),r+=1,this.spriteRandomStartCell&&(i.push(0),r+=1)),this._platform.alignDataInBuffer){let e=3-(r+3&3);for(r+=e;e-- >0;)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 qe.l(t,l,!1,this._attributesStrideSize),this._buffer1=new qe.l(t,h,!1,this._attributesStrideSize),this._spriteBuffer=new qe.l(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+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),!(!this._platform.isUpdateBufferCreated()||this._cachedUpdateDefines!==e)||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e),this._platform.isUpdateBufferReady())}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;const i=[];this.fillDefines(i,e);let n=this._drawWrappers[e];n||(n=new Ps.q(this._engine),n.drawContext&&(n.drawContext.useInstancing=!0),this._drawWrappers[e]=n);const s=i.join("\n");if(n.defines!==s){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return n}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,n=!1){const s=[qe.o.PositionKind,"age","life","size","angle"];return e||s.push(qe.o.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),n||s.push("direction"),s.push("offset",qe.o.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1){const i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return(0,Ga.qx)(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&(0,Ga.lK)(this,this._scene,e),t===i_.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 i_.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case i_.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case i_.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}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(...s_._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===i_.BILLBOARDMODE_STRETCHED)),e.push(...s_._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(ki.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ki.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?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 n=new Float32Array(this._rawTextureWidth);for(let t=0;t<this._rawTextureWidth;t++){const i=t/this._rawTextureWidth;Zf.GetCurrentGradient(i,e,((e,i,s)=>{n[t]=lt.R.Lerp(e.factor1,i.factor1,s)}))}this[t]=Ee.l.CreateRTexture(n,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(4*this._rawTextureWidth),t=a.zZ.Color4[0];for(let i=0;i<this._rawTextureWidth;i++){const n=i/this._rawTextureWidth;Zf.GetCurrentGradient(n,this._colorGradients,((n,s,r)=>{a.HE.LerpToRef(n.color1,s.color1,r,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))}this._colorGradientsTexture=Ee.l.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,n;const s=this._getWrapper(e),r=s.effect;this._engine.enableEffect(s);const a=(null===(i=this._scene)||void 0===i?void 0:i.getViewMatrix())||o.y3.IdentityReadOnly;if(r.setMatrix("view",a),r.setMatrix("projection",null!==(n=this.defaultProjectionMatrix)&&void 0!==n?n:this._scene.getProjectionMatrix()),r.setTexture("diffuseSampler",this.particleTexture),r.setVector2("translationPivot",this.translationPivot),r.setVector3("worldOffset",this.worldOffset),this.isLocal&&r.setMatrix("emitterWM",t),this._colorGradientsTexture?r.setTexture("colorGradientSampler",this._colorGradientsTexture):r.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();r.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;r.setVector3("eyePosition",e.globalPosition)}const l=r.defines;if(this._scene&&(0,Ga.an)(r,this,this._scene),l.indexOf("#define BILLBOARDMODE_ALL")>=0){const e=a.clone();e.invert(),r.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&La.G.BindLogDepth(l,r,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(r),e){case i_.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case i_.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case i_.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case i_.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,r),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(r),this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer)return;if(!this._recreateUpdateEffect())return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const t=this.emitter;e=o.jp.Matrix[0],o.y3.TranslationToRef(t.x,t.y,t.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++,2===this._targetIndex&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e<this.preWarmCycles;e++)this.animate(!0),this.render(!0,!0);this._preWarmDone=!0}if(this._currentRenderId===this._scene.getRenderId()&&(!this._scene.activeCamera||this._scene.activeCamera&&this._currentRenderingCameraUniqueId===this._scene.activeCamera.uniqueId))return 0;this._currentRenderId=this._scene.getRenderId(),this._scene.activeCamera&&(this._currentRenderingCameraUniqueId=this._scene.activeCamera.uniqueId)}if(this._initialize(),this._accumulatedCount+=this.emitRate*this._timeDelta,this._accumulatedCount>1){const e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount=Math.min(this._activeCount,this._currentActiveCount+e)}if(!this._currentActiveCount)return 0;let i;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{const e=this.emitter;i=o.jp.Matrix[0],o.y3.TranslationToRef(e.x,e.y,e.z,i)}const n=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(n.setState(!1),this.forceDepthWrite&&n.setDepthWrite(!0),s=this.blendMode===i_.BLENDMODE_MULTIPLYADD?this._render(i_.BLENDMODE_MULTIPLY,i)+this._render(i_.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){this._initialize(!0)}_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 e in this._drawWrappers)this._drawWrappers[e].dispose();if(this._drawWrappers={},this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e<this._renderVertexBuffers.length;++e){const t=this._renderVertexBuffers[e];for(const e in t)t[e].dispose()}this._renderVertexBuffers=[],this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._limitVelocityGradientsTexture&&(this._limitVelocityGradientsTexture.dispose(),this._limitVelocityGradientsTexture=null),this._dragGradientsTexture&&(this._dragGradientsTexture.dispose(),this._dragGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onStoppedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}clone(e,t,i=!1){const n={...this._customWrappers};let s=null;const r=this._engine;if(r.createEffectForParticles&&null!=this.customShader){s=this.customShader;const e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"";n[0]=r.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}const o=this.serialize(i),a=s_.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=s,a._customWrappers=n,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,a}serialize(e=!1){const t={};return i_._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,n=!1,s){const r=e.name;let o,a;t instanceof Rn.B?o=t:(a=t,o=a.getEngine());const l=new s_(r,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",n=o.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,l);l.setCustomEffect(n,0),l.customShader=t}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),i_._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),n||l.preventAutoStart||l.start(),l}}class r_{constructor(){this._emitterNodeIsOwned=!0,this.systems=new Array}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const n=Kn("emitterSphere",{diameter:e.diameter,segments:e.segments},i);n.renderingGroupId=t;const s=new Gi.K("emitterSphereMaterial",i);s.emissiveColor=e.color,n.material=s;for(const e of this.systems)e.emitter=n;this._emitterNode=n}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={systems:[]};for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,n){const s=new r_,r=this.BaseAssetsUrl+"/textures/";t=t||A.l.LastCreatedScene;for(const o of e.systems)s.systems.push(i?s_.Parse(o,t,r,!0,n):i_.Parse(o,t,r,!0,n));if(e.emitter){const i=e.emitter.options;"Sphere"===e.emitter.kind&&s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:a.Wo.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}}r_.BaseAssetsUrl="https://assets.babylonjs.com/particles";class o_{static CreateDefault(e,t=500,i,n=!1){let s;return s=n?new s_("default system",{capacity:t},i):new i_("default system",t,i),s.emitter=e,s.particleTexture=new Ce.x("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new a.HE(1,1,1,1),s.color2=new a.HE(1,1,1,1),s.colorDead=new a.HE(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,n){t||(t=A.l.LastCreatedScene);const s={};return t.addPendingData(s),new Promise(((r,o)=>{if(i&&!s_.IsSupported)return t.removePendingData(s),o("Particle system with GPU is not supported.");de.w1.LoadFile(`${o_.BaseAssetsUrl}/systems/${e}.json`,(e=>{t.removePendingData(s);const o=JSON.parse(e.toString());return r(r_.Parse(o,t,i,n))}),void 0,void 0,void 0,(()=>(t.removePendingData(s),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`))))}))}static ExportSet(e){const t=new r_;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,n=!1,s="",r){return new Promise(((o,a)=>{const l=new Kc.g;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const t=JSON.parse(l.responseText);let a;a=n?s_.Parse(t,i,s,!1,r):i_.Parse(t,i,s,!1,r),e&&(a.name=e),o(a)}else a("Unable to load the particle system")})),l.open("GET",t),l.send()}))}static ParseFromSnippetAsync(e,t,i=!1,n="",s){if("_BLANK"===e){const e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise(((r,o)=>{const a=new Kc.g;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.particleSystem);let h;h=i?s_.Parse(l,t,n,!1,s):i_.Parse(l,t,n,!1,s),h.snippetId=e,r(h)}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}o_.BaseAssetsUrl=r_.BaseAssetsUrl,o_.SnippetUrl="https://snippet.babylonjs.com",o_.CreateFromSnippetAsync=o_.ParseFromSnippetAsync,n.p.AddParser(ve.l.NAME_PARTICLESYSTEM,((e,t,i,s)=>{const r=n.p.GetIndividualParser(ve.l.NAME_PARTICLESYSTEM);if(r&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,o=e.particleSystems.length;n<o;n++){const o=e.particleSystems[n];i.particleSystems.push(r(o,t,s))}})),n.p.AddIndividualParser(ve.l.NAME_PARTICLESYSTEM,((e,t,i)=>e.activeParticleCount?s_.Parse(e,t,i):i_.Parse(e,t,i))),ue.D.prototype.createEffectForParticles=function(e,t=[],i=[],n="",s,r,o,a){var l;let h=[],c=[];const u=[];return a?a.fillUniformsAttributesAndSamplerNames(c,h,u):(h=i_._GetAttributeNamesOrOptions(),c=i_._GetEffectCreationOptions()),-1===n.indexOf(" BILLBOARD")&&(n+="\n#define BILLBOARD\n"),(null==a?void 0:a.isAnimationSheetEnabled)&&-1===n.indexOf(" ANIMATESHEET")&&(n+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:null!==(l=null==a?void 0:a.vertexShaderName)&&void 0!==l?l:"particles",fragmentElement:e},h,c.concat(t),u.concat(i),n,s,r,o)},Nt.Kj.prototype.getEmittedParticleSystems=function(){const e=new Array;for(let t=0;t<this.getScene().particleSystems.length;t++){const i=this.getScene().particleSystems[t];i.emitter===this&&e.push(i)}return e},Nt.Kj.prototype.getHierarchyEmittedParticleSystems=function(){const e=new Array,t=this.getDescendants();t.push(this);for(let i=0;i<this.getScene().particleSystems.length;i++){const n=this.getScene().particleSystems[i],s=n.emitter;s.position&&-1!==t.indexOf(s)&&e.push(n)}return e};class a_{getBoundingInfo(){return this._boundingInfo}get hasBoundingInfo(){return null!==this._boundingInfo}constructor(e,t,i,n,s,r,l,h,c=null,u=null){this.idx=0,this.id=0,this.color=new a.HE(1,1,1,1),this.position=o.P.Zero(),this.rotation=o.P.Zero(),this.scaling=o.P.One(),this.uvs=new o.Lt(0,0,1,1),this.velocity=o.P.Zero(),this.pivot=o.P.Zero(),this.translateFromPivot=!1,this.alive=!0,this.isVisible=!0,this._pos=0,this._ind=0,this.shapeId=0,this.idxInShape=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this.materialIndex=null,this.props=null,this.cullingStrategy=Un.x.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this._globalPosition=o.P.Zero(),this.idx=e,this.id=t,this._pos=i,this._ind=n,this._model=s,this.shapeId=r,this.idxInShape=l,this._sps=h,c&&(this._modelBoundingInfo=c,this._boundingInfo=new wn.j(c.minimum,c.maximum)),null!==u&&(this.materialIndex=u)}copyToRef(e){return e.position.copyFrom(this.position),e.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(e.rotationQuaternion?e.rotationQuaternion.copyFrom(this.rotationQuaternion):e.rotationQuaternion=this.rotationQuaternion.clone()),e.scaling.copyFrom(this.scaling),this.color&&(e.color?e.color.copyFrom(this.color):e.color=this.color.clone()),e.uvs.copyFrom(this.uvs),e.velocity.copyFrom(this.velocity),e.pivot.copyFrom(this.pivot),e.translateFromPivot=this.translateFromPivot,e.alive=this.alive,e.isVisible=this.isVisible,e.parentId=this.parentId,e.cullingStrategy=this.cullingStrategy,null!==this.materialIndex&&(e.materialIndex=this.materialIndex),this}get scale(){return this.scaling}set scale(e){this.scaling=e}get quaternion(){return this.rotationQuaternion}set quaternion(e){this.rotationQuaternion=e}intersectsMesh(e){return!(!this._boundingInfo||!e.hasBoundingInfo)&&(this._sps._bSphereOnly?Nn.K.Intersects(this._boundingInfo.boundingSphere,e.getBoundingInfo().boundingSphere):this._boundingInfo.intersects(e.getBoundingInfo(),!1))}isInFrustum(e){return null!==this._boundingInfo&&this._boundingInfo.isInFrustum(e,this.cullingStrategy)}getRotationMatrix(e){let t;if(this.rotationQuaternion)t=this.rotationQuaternion;else{t=o.jp.Quaternion[0];const e=this.rotation;o._f.RotationYawPitchRollToRef(e.y,e.x,e.z,t)}t.toRotationMatrix(e)}}class l_{get shapeID(){return this.shapeId}set shapeID(e){this.shapeId=e}constructor(e,t,i,n,s,r,o,a,l){this._indicesLength=0,this.shapeId=e,this._shape=t,this._indices=i,this._indicesLength=i.length,this._shapeUV=r,this._shapeColors=s,this._normals=n,this._positionFunction=o,this._vertexFunction=a,this._material=l}}class h_{constructor(e,t,i,n){this.idx=0,this.ind=0,this.indicesLength=0,this.sqDistance=0,this.materialIndex=0,this.idx=e,this.ind=t,this.indicesLength=i,this.materialIndex=n}}class c_{constructor(){this.position=o.P.Zero(),this.color=new a.HE(1,1,1,1),this.uv=o.FM.Zero()}get x(){return this.position.x}set x(e){this.position.x=e}get y(){return this.position.y}set y(e){this.position.y=e}get z(){return this.position.z}set z(e){this.position.z=e}}class u_{constructor(e,t,i){this.particles=new Array,this.nbParticles=0,this.billboard=!1,this.recomputeNormals=!1,this.counter=0,this.vars={},this._bSphereOnly=!1,this._bSphereRadiusFactor=1,this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._index=0,this._updatable=!0,this._pickable=!1,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._depthSort=!1,this._expandable=!1,this._shapeCounter=0,this._copy=new a_(0,0,0,0,null,0,0,this),this._color=new a.HE(0,0,0,0),this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeParticleVertex=!1,this._computeBoundingBox=!1,this._autoFixFaceOrientation=!1,this._depthSortParticles=!0,this._mustUnrotateFixedNormals=!1,this._particlesIntersect=!1,this._needs32Bits=!1,this._isNotBuilt=!0,this._lastParticleId=0,this._idxOfId=[],this._multimaterialEnabled=!1,this._useModelMaterial=!1,this._depthSortFunction=(e,t)=>t.sqDistance-e.sqDistance,this._materialSortFunction=(e,t)=>e.materialIndex-t.materialIndex,this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||A.l.LastCreatedScene,this._camera=t.activeCamera,this._pickable=!!i&&i.isPickable,this._depthSort=!!i&&i.enableDepthSort,this._multimaterialEnabled=!!i&&i.enableMultiMaterial,this._useModelMaterial=!!i&&i.useModelMaterial,this._multimaterialEnabled=!!this._useModelMaterial||this._multimaterialEnabled,this._expandable=!!i&&i.expandable,this._particlesIntersect=!!i&&i.particleIntersection,this._bSphereOnly=!!i&&i.boundingSphereOnly,this._bSphereRadiusFactor=i&&i.bSphereRadiusFactor?i.bSphereRadiusFactor:1,this._computeBoundingBox=!!(null==i?void 0:i.computeBoundingBox)&&i.computeBoundingBox,this._autoFixFaceOrientation=!!(null==i?void 0:i.autoFixFaceOrientation)&&i.autoFixFaceOrientation,i&&void 0!==i.updatable?this._updatable=i.updatable:this._updatable=!0,this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]),(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]),this._multimaterialEnabled&&(this._multimaterial=new Ph.G(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new c_}buildMesh(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(0===this.nbParticles&&!this.mesh){const e=Ca("",{radius:1,tessellation:3},this._scene);this.addShape(e,1),e.dispose()}if(this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),!this.mesh){const e=new Nt.Kj(this.name,this._scene);this.mesh=e}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&sn.x.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();const e=new sn.x;if(e.indices=this._depthSort?this._indices:this._indices32,e.set(this._positions32,qe.o.PositionKind),e.set(this._normals32,qe.o.NormalKind),this._uvs32.length>0&&e.set(this._uvs32,qe.o.UVKind),this._colors32.length>0&&e.set(this._colors32,qe.o.ColorKind),e.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){let e=0;for(let t=0;t<this.nbParticles;t++){const i=this.particles[t],n=i._model._indicesLength;for(let t=0;t<n;t++)if(0==t%3){const t={idx:i.idx,faceId:e};this.pickedParticles[e]=t,e++}}}return this._multimaterialEnabled&&this.setMultiMaterial(this._materials),this._expandable||(this._depthSort||this._multimaterialEnabled||this._autoFixFaceOrientation||(this._indices=null),this._positions=null,this._normals=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0)),this._isNotBuilt=!1,this.recomputeNormals=!1,this._recomputeInvisibles=!0,this.mesh}digest(e,t){let i=t&&t.facetNb||1,n=t&&t.number||0,s=t&&t.delta||0;const r=e.getVerticesData(qe.o.PositionKind),a=e.getIndices(),l=e.getVerticesData(qe.o.UVKind),h=e.getVerticesData(qe.o.ColorKind),c=e.getVerticesData(qe.o.NormalKind),u=t&&t.storage?t.storage:null;let d=0;const p=a.length/3;n?(n=n>p?p:n,i=Math.round(p/n),s=0):i=i>p?p:i;const f=[],_=[],m=[],g=[],v=[],y=o.P.Zero(),x=i;for(;d<p;){i=x+Math.floor((1+s)*Math.random()),d>p-i&&(i=p-d),f.length=0,_.length=0,m.length=0,g.length=0,v.length=0;let t=0;for(let e=3*d;e<3*(d+i);e++){m.push(t);const i=a[e],n=3*i;if(f.push(r[n],r[n+1],r[n+2]),_.push(c[n],c[n+1],c[n+2]),l){const e=2*i;g.push(l[e],l[e+1])}if(h){const e=4*i;v.push(h[e],h[e+1],h[e+2],h[e+3])}t++}let n=this.nbParticles;const b=this._posToShape(f),T=this._uvsToShapeUV(g),S=m.slice(),E=v.slice(),C=_.slice();let A;for(y.copyFromFloats(0,0,0),A=0;A<b.length;A++)y.addInPlace(b[A]);y.scaleInPlace(1/b.length);const P=new o.P(1/0,1/0,1/0),R=new o.P(-1/0,-1/0,-1/0);for(A=0;A<b.length;A++)b[A].subtractInPlace(y),P.minimizeInPlaceFromFloats(b[A].x,b[A].y,b[A].z),R.maximizeInPlaceFromFloats(b[A].x,b[A].y,b[A].z);let M;this._particlesIntersect&&(M=new wn.j(P,R));let I=null;this._useModelMaterial&&(I=e.material?e.material:this._setDefaultMaterial());const D=new l_(this._shapeCounter,b,S,C,E,T,null,null,I),O=this._positions.length,w=this._indices.length;this._meshBuilder(this._index,w,b,this._positions,S,this._indices,g,this._uvs,E,this._colors,C,this._normals,n,0,null,D),this._addParticle(n,this._lastParticleId,O,w,D,this._shapeCounter,0,M,u),this.particles[this.nbParticles].position.addInPlace(y),u||(this._index+=b.length,n++,this.nbParticles++,this._lastParticleId++),this._shapeCounter++,d+=i}return this._isNotBuilt=!0,this}_unrotateFixedNormals(){let e=0,t=0;const i=o.jp.Vector3[0],n=o.jp.Quaternion[0],s=o.jp.Matrix[0];for(let r=0;r<this.particles.length;r++){const a=this.particles[r],l=a._model._shape;if(a.rotationQuaternion)a.rotationQuaternion.conjugateToRef(n);else{const e=a.rotation;o._f.RotationYawPitchRollToRef(e.y,e.x,e.z,n),n.conjugateInPlace()}n.toRotationMatrix(s);for(let n=0;n<l.length;n++)t=e+3*n,o.P.TransformNormalFromFloatsToRef(this._normals32[t],this._normals32[t+1],this._normals32[t+2],s,i),i.toArray(this._fixedNormal32,t);e=t+3}}_resetCopy(){const e=this._copy;e.position.setAll(0),e.rotation.setAll(0),e.rotationQuaternion=null,e.scaling.setAll(1),e.uvs.copyFromFloats(0,0,1,1),e.color=null,e.translateFromPivot=!1,e.shapeId=0,e.materialIndex=null}_meshBuilder(e,t,i,n,s,r,a,l,h,c,u,d,p,f,_,m){let g,v=0,y=0,x=0;this._resetCopy();const b=this._copy,T=!(!_||!_.storage);if(b.idx=p,b.idxInShape=f,b.shapeId=m.shapeId,this._useModelMaterial){const e=m._material.uniqueId,t=this._materialIndexesById;Object.prototype.hasOwnProperty.call(t,e)||(t[e]=this._materials.length,this._materials.push(m._material));const i=t[e];b.materialIndex=i}if(_&&_.positionFunction&&(_.positionFunction(b,p,f),this._mustUnrotateFixedNormals=!0),T)return b;const S=o.jp.Matrix[0],E=this._tmpVertex,C=E.position,A=E.color,P=E.uv,R=o.jp.Vector3[1],M=o.jp.Vector3[2],I=o.jp.Vector3[3];o.y3.IdentityToRef(S),b.getRotationMatrix(S),b.pivot.multiplyToRef(b.scaling,I),b.translateFromPivot?M.setAll(0):M.copyFrom(I);const D=_&&_.vertexFunction;for(g=0;g<i.length;g++){if(C.copyFrom(i[g]),b.color&&A.copyFrom(b.color),a&&P.copyFromFloats(a[v],a[v+1]),D&&_.vertexFunction(b,E,g),C.multiplyInPlace(b.scaling).subtractInPlace(I),o.P.TransformCoordinatesToRef(C,S,R),R.addInPlace(M).addInPlace(b.position),n.push(R.x,R.y,R.z),a){const e=b.uvs;l.push((e.z-e.x)*P.x+e.x,(e.w-e.y)*P.y+e.y),v+=2}if(b.color)this._color.copyFrom(A);else{const e=this._color;h&&void 0!==h[y]?(e.r=h[y],e.g=h[y+1],e.b=h[y+2],e.a=h[y+3]):(e.r=1,e.g=1,e.b=1,e.a=1)}c.push(this._color.r,this._color.g,this._color.b,this._color.a),y+=4,!this.recomputeNormals&&u&&(o.P.TransformNormalFromFloatsToRef(u[x],u[x+1],u[x+2],S,C),d.push(C.x,C.y,C.z),x+=3)}for(g=0;g<s.length;g++){const t=e+s[g];r.push(t),t>65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){const e=null!==b.materialIndex?b.materialIndex:0;this.depthSortedParticles.push(new h_(p,t,s.length,e))}return b}_posToShape(e){const t=[];for(let i=0;i<e.length;i+=3)t.push(o.P.FromArray(e,i));return t}_uvsToShapeUV(e){const t=[];if(e)for(let i=0;i<e.length;i++)t.push(e[i]);return t}_addParticle(e,t,i,n,s,r,o,a=null,l=null){const h=new a_(e,t,i,n,s,r,o,this,a);return(l||this.particles).push(h),h}addShape(e,t,i){const n=e.getVerticesData(qe.o.PositionKind),s=e.getIndices(),r=e.getVerticesData(qe.o.UVKind),o=e.getVerticesData(qe.o.ColorKind),a=e.getVerticesData(qe.o.NormalKind);this.recomputeNormals=!a;const l=Array.from(s),h=Array.from(a),c=o?Array.from(o):[],u=i&&i.storage?i.storage:null;let d=null;this._particlesIntersect&&(d=e.getBoundingInfo());const p=this._posToShape(n),f=this._uvsToShapeUV(r),_=i?i.positionFunction:null,m=i?i.vertexFunction:null;let g=null;this._useModelMaterial&&(g=e.material?e.material:this._setDefaultMaterial());const v=new l_(this._shapeCounter,p,l,h,c,f,_,m,g);for(let e=0;e<t;e++)this._insertNewParticle(this.nbParticles,e,v,p,s,r,o,a,d,u,i);return this._shapeCounter++,this._isNotBuilt=!0,this._shapeCounter-1}_rebuildParticle(e,t=!1){this._resetCopy();const i=this._copy;e._model._positionFunction&&e._model._positionFunction(i,e.idx,e.idxInShape);const n=o.jp.Matrix[0],s=o.jp.Vector3[0],r=o.jp.Vector3[1],a=o.jp.Vector3[2],l=o.jp.Vector3[3];i.getRotationMatrix(n),e.pivot.multiplyToRef(e.scaling,l),i.translateFromPivot?a.copyFromFloats(0,0,0):a.copyFrom(l);const h=e._model._shape;for(let t=0;t<h.length;t++)s.copyFrom(h[t]),e._model._vertexFunction&&e._model._vertexFunction(i,s,t),s.multiplyInPlace(i.scaling).subtractInPlace(l),o.P.TransformCoordinatesToRef(s,n,r),r.addInPlace(a).addInPlace(i.position).toArray(this._positions32,e._pos+3*t);t&&(e.position.setAll(0),e.rotation.setAll(0),e.rotationQuaternion=null,e.scaling.setAll(1),e.uvs.setAll(0),e.pivot.setAll(0),e.translateFromPivot=!1,e.parentId=null)}rebuildMesh(e=!1){for(let t=0;t<this.particles.length;t++)this._rebuildParticle(this.particles[t],e);return this.mesh.updateVerticesData(qe.o.PositionKind,this._positions32,!1,!1),this}removeParticles(e,t){const i=t-e+1;if(!this._expandable||i<=0||i>=this.nbParticles||!this._updatable)return[];const n=this.particles,s=this.nbParticles;if(t<s-1){const i=t+1,r=n[i]._pos-n[e]._pos,o=n[i]._ind-n[e]._ind;for(let e=i;e<s;e++){const t=n[e];t._pos-=r,t._ind-=o}}const r=n.splice(e,i);this._positions.length=0,this._indices.length=0,this._colors.length=0,this._uvs.length=0,this._normals.length=0,this._index=0,this._idxOfId.length=0,(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]);let o=0;const a=n.length;for(let e=0;e<a;e++){const t=n[e],i=t._model,s=i._shape,r=i._indices,a=i._normals,l=i._shapeColors,h=i._shapeUV;t.idx=e,this._idxOfId[t.id]=e,this._meshBuilder(this._index,o,s,this._positions,r,this._indices,h,this._uvs,l,this._colors,a,this._normals,t.idx,t.idxInShape,null,i),this._index+=s.length,o+=r.length}return this.nbParticles-=i,this._isNotBuilt=!0,r}insertParticlesFromArray(e){if(!this._expandable)return this;let t=0,i=e[0].shapeId;const n=e.length;for(let s=0;s<n;s++){const n=e[s],r=n._model,o=r._shape,a=r._indices,l=r._shapeUV,h=r._shapeColors,c=r._normals,u=!c;this.recomputeNormals=u||this.recomputeNormals;const d=n.getBoundingInfo(),p=this._insertNewParticle(this.nbParticles,t,r,o,a,l,h,c,d,null,null);n.copyToRef(p),t++,i!=n.shapeId&&(i=n.shapeId,t=0)}return this._isNotBuilt=!0,this}_insertNewParticle(e,t,i,n,s,r,o,a,l,h,c){const u=this._positions.length,d=this._indices.length,p=this._meshBuilder(this._index,d,n,this._positions,s,this._indices,r,this._uvs,o,this._colors,a,this._normals,e,t,c,i);let f=null;return this._updatable&&(f=this._addParticle(this.nbParticles,this._lastParticleId,u,d,i,this._shapeCounter,t,l,h),f.position.copyFrom(p.position),f.rotation.copyFrom(p.rotation),p.rotationQuaternion&&(f.rotationQuaternion?f.rotationQuaternion.copyFrom(p.rotationQuaternion):f.rotationQuaternion=p.rotationQuaternion.clone()),p.color&&(f.color?f.color.copyFrom(p.color):f.color=p.color.clone()),f.scaling.copyFrom(p.scaling),f.uvs.copyFrom(p.uvs),null!==p.materialIndex&&(f.materialIndex=p.materialIndex),this.expandable&&(this._idxOfId[f.id]=f.idx)),h||(this._index+=n.length,this.nbParticles++,this._lastParticleId++),f}setParticles(e=0,t=this.nbParticles-1,i=!0){if(!this._updatable||this._isNotBuilt)return this;this.beforeUpdateParticles(e,t,i);const n=o.jp.Matrix[0],s=o.jp.Matrix[1],r=this.mesh,a=this._colors32,l=this._positions32,h=this._normals32,c=this._uvs32,u=this._indices32,d=this._indices,p=this._fixedNormal32,f=this._depthSort&&this._depthSortParticles,_=o.jp.Vector3,m=_[5].copyFromFloats(1,0,0),g=_[6].copyFromFloats(0,1,0),v=_[7].copyFromFloats(0,0,1),y=_[8].setAll(Number.MAX_VALUE),x=_[9].setAll(-Number.MAX_VALUE),b=_[10].setAll(0),T=this._tmpVertex,S=T.position,E=T.color,C=T.uv;if((this.billboard||this._depthSort)&&(this.mesh.computeWorldMatrix(!0),this.mesh._worldMatrix.invertToRef(s)),this.billboard){const e=_[0];this._camera.getDirectionToRef(We.RD.Z,e),o.P.TransformNormalToRef(e,s,v),v.normalize();const t=this._camera.getViewMatrix(!0);o.P.TransformNormalFromFloatsToRef(t.m[1],t.m[5],t.m[9],s,g),o.P.CrossToRef(g,v,m),g.normalize(),m.normalize()}this._depthSort&&o.P.TransformCoordinatesToRef(this._camera.globalPosition,s,b),o.y3.IdentityToRef(n);let A=0,P=0,R=0,M=0,I=0,D=0,O=0;if(this.mesh.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh.getBoundingInfo();e&&(y.copyFrom(e.minimum),x.copyFrom(e.maximum))}P=this.particles[e]._pos;const w=P/3|0;M=4*w,D=2*w;for(let i=e;i<=t;i++){const e=this.particles[i];this.updateParticle(e);const t=e._model._shape,s=e._model._shapeUV,u=e._rotationMatrix,d=e.position,w=e.rotation,N=e.scaling,F=e._globalPosition;if(f){const t=this.depthSortedParticles[i];t.idx=e.idx,t.ind=e._ind,t.indicesLength=e._model._indicesLength,t.sqDistance=o.P.DistanceSquared(e.position,b)}if(e.alive&&(!e._stillInvisible||e.isVisible||this._recomputeInvisibles)){if(e.isVisible){e._stillInvisible=!1;const i=_[12];if(e.pivot.multiplyToRef(N,i),this.billboard&&(w.x=0,w.y=0),(this._computeParticleRotation||this.billboard)&&e.getRotationMatrix(n),null!==e.parentId){const t=this.getParticleById(e.parentId);if(t){const e=t._rotationMatrix,i=t._globalPosition,s=d.x*e[1]+d.y*e[4]+d.z*e[7],r=d.x*e[0]+d.y*e[3]+d.z*e[6],o=d.x*e[2]+d.y*e[5]+d.z*e[8];if(F.x=i.x+r,F.y=i.y+s,F.z=i.z+o,this._computeParticleRotation||this.billboard){const t=n.m;u[0]=t[0]*e[0]+t[1]*e[3]+t[2]*e[6],u[1]=t[0]*e[1]+t[1]*e[4]+t[2]*e[7],u[2]=t[0]*e[2]+t[1]*e[5]+t[2]*e[8],u[3]=t[4]*e[0]+t[5]*e[3]+t[6]*e[6],u[4]=t[4]*e[1]+t[5]*e[4]+t[6]*e[7],u[5]=t[4]*e[2]+t[5]*e[5]+t[6]*e[8],u[6]=t[8]*e[0]+t[9]*e[3]+t[10]*e[6],u[7]=t[8]*e[1]+t[9]*e[4]+t[10]*e[7],u[8]=t[8]*e[2]+t[9]*e[5]+t[10]*e[8]}}else e.parentId=null}else if(F.x=d.x,F.y=d.y,F.z=d.z,this._computeParticleRotation||this.billboard){const e=n.m;u[0]=e[0],u[1]=e[1],u[2]=e[2],u[3]=e[4],u[4]=e[5],u[5]=e[6],u[6]=e[8],u[7]=e[9],u[8]=e[10]}const r=_[11];for(e.translateFromPivot?r.setAll(0):r.copyFrom(i),O=0;O<t.length;O++){A=P+3*O,R=M+4*O,I=D+2*O;const n=2*O,o=n+1;S.copyFrom(t[O]),this._computeParticleColor&&e.color&&E.copyFrom(e.color),this._computeParticleTexture&&C.copyFromFloats(s[n],s[o]),this._computeParticleVertex&&this.updateParticleVertex(e,T,O);const a=S.x*N.x-i.x,d=S.y*N.y-i.y,f=S.z*N.z-i.z;let _=a*u[0]+d*u[3]+f*u[6],b=a*u[1]+d*u[4]+f*u[7],w=a*u[2]+d*u[5]+f*u[8];_+=r.x,b+=r.y,w+=r.z;const L=l[A]=F.x+m.x*_+g.x*b+v.x*w,B=l[A+1]=F.y+m.y*_+g.y*b+v.y*w,U=l[A+2]=F.z+m.z*_+g.z*b+v.z*w;if(this._computeBoundingBox&&(y.minimizeInPlaceFromFloats(L,B,U),x.maximizeInPlaceFromFloats(L,B,U)),!this._computeParticleVertex){const e=p[A],t=p[A+1],i=p[A+2],n=e*u[0]+t*u[3]+i*u[6],s=e*u[1]+t*u[4]+i*u[7],r=e*u[2]+t*u[5]+i*u[8];h[A]=m.x*n+g.x*s+v.x*r,h[A+1]=m.y*n+g.y*s+v.y*r,h[A+2]=m.z*n+g.z*s+v.z*r}if(this._computeParticleColor&&e.color){const e=this._colors32;e[R]=E.r,e[R+1]=E.g,e[R+2]=E.b,e[R+3]=E.a}if(this._computeParticleTexture){const t=e.uvs;c[I]=C.x*(t.z-t.x)+t.x,c[I+1]=C.y*(t.w-t.y)+t.y}}}else for(e._stillInvisible=!0,O=0;O<t.length;O++){if(A=P+3*O,R=M+4*O,I=D+2*O,l[A]=l[A+1]=l[A+2]=0,h[A]=h[A+1]=h[A+2]=0,this._computeParticleColor&&e.color){const t=e.color;a[R]=t.r,a[R+1]=t.g,a[R+2]=t.b,a[R+3]=t.a}if(this._computeParticleTexture){const t=e.uvs;c[I]=s[2*O]*(t.z-t.x)+t.x,c[I+1]=s[2*O+1]*(t.w-t.y)+t.y}}if(this._particlesIntersect){const t=e.getBoundingInfo(),i=t.boundingBox,n=t.boundingSphere,s=e._modelBoundingInfo;if(!this._bSphereOnly){const e=s.boundingBox.vectors,t=_[1],n=_[2];t.setAll(Number.MAX_VALUE),n.setAll(-Number.MAX_VALUE);for(let i=0;i<8;i++){const s=e[i].x*N.x,r=e[i].y*N.y,o=e[i].z*N.z,a=s*u[0]+r*u[3]+o*u[6],l=s*u[1]+r*u[4]+o*u[7],h=s*u[2]+r*u[5]+o*u[8],c=d.x+m.x*a+g.x*l+v.x*h,p=d.y+m.y*a+g.y*l+v.y*h,f=d.z+m.z*a+g.z*l+v.z*h;t.minimizeInPlaceFromFloats(c,p,f),n.maximizeInPlaceFromFloats(c,p,f)}i.reConstruct(t,n,r._worldMatrix)}const o=s.minimum.multiplyToRef(N,_[1]),a=s.maximum.multiplyToRef(N,_[2]),l=a.addToRef(o,_[3]).scaleInPlace(.5).addInPlace(F),h=a.subtractToRef(o,_[4]).scaleInPlace(.5*this._bSphereRadiusFactor),c=l.subtractToRef(h,_[1]),p=l.addToRef(h,_[2]);n.reConstruct(c,p,r._worldMatrix)}P=A+3,M=R+4,D=I+2}else O=t.length,P+=3*O,M+=4*O,D+=2*O}if(i){if(this._computeParticleColor){const e=r.getVertexBuffer(qe.o.ColorKind);e&&!r.isPickable?e.updateDirectly(a,0):r.updateVerticesData(qe.o.ColorKind,a,!1,!1)}if(this._computeParticleTexture){const e=r.getVertexBuffer(qe.o.UVKind);e&&!r.isPickable?e.updateDirectly(c,0):r.updateVerticesData(qe.o.UVKind,c,!1,!1)}const e=r.getVertexBuffer(qe.o.PositionKind);if(e&&!r.isPickable?e.updateDirectly(l,0):r.updateVerticesData(qe.o.PositionKind,l,!1,!1),!r.areNormalsFrozen||r.isFacetDataEnabled){if(this._computeParticleVertex||r.isFacetDataEnabled){const e=r.isFacetDataEnabled?r.getFacetDataParameters():null;sn.x.ComputeNormals(l,u,h,e);for(let e=0;e<h.length;e++)p[e]=h[e]}if(!r.areNormalsFrozen){const e=r.getVertexBuffer(qe.o.NormalKind);e&&!r.isPickable?e.updateDirectly(h,0):r.updateVerticesData(qe.o.NormalKind,h,!1,!1)}}if(f){const e=this.depthSortedParticles;e.sort(this._depthSortFunction);const t=e.length;let i=0,n=0;for(let s=0;s<t;s++){const t=e[s],r=t.indicesLength,o=t.ind;for(let e=0;e<r;e++)if(u[i]=d[o+e],i++,this._pickable&&0==e%3){const e=this.pickedParticles[n];e.idx=t.idx,e.faceId=n,n++}}}if(this._autoFixFaceOrientation){let e=0;for(let t=0;t<this.particles.length;t++){const i=f?this.particles[this.depthSortedParticles[t].idx]:this.particles[t];if(i.scale.x*i.scale.y*i.scale.z<0)for(let t=0;t<i._model._indicesLength;t+=3){const n=d[i._ind+t];u[e+t]=d[i._ind+t+1],u[e+t+1]=n}e+=i._model._indicesLength}}(f||this._autoFixFaceOrientation)&&r.updateIndices(u)}return this._computeBoundingBox&&(r.hasBoundingInfo?r.getBoundingInfo().reConstruct(y,x,r._worldMatrix):r.buildBoundingInfo(y,x,r._worldMatrix)),this._autoUpdateSubMeshes&&this.computeSubMeshes(),this._recomputeInvisibles=!1,this.afterUpdateParticles(e,t,i),this}dispose(){this.mesh.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._normals32=null,this._fixedNormal32=null,this._uvs32=null,this._colors32=null,this.pickedParticles=null,this.pickedBySubMesh=null,this._materials=null,this._materialIndexes=null,this._indicesByMaterial=null,this._idxOfId=null}pickedParticle(e){if(e.hit){const t=e.subMeshId,i=e.faceId-this.mesh.subMeshes[t].indexStart/3,n=this.pickedBySubMesh;if(n[t]&&n[t][i])return n[t][i]}return null}getParticleById(e){const t=this.particles[e];if(t&&t.id==e)return t;const i=this.particles,n=this._idxOfId[e];if(void 0!==n)return i[n];let s=0;const r=this.nbParticles;for(;s<r;){const t=i[s];if(t.id==e)return t;s++}return null}getParticlesByShapeId(e){const t=[];return this.getParticlesByShapeIdToRef(e,t),t}getParticlesByShapeIdToRef(e,t){t.length=0;for(let i=0;i<this.nbParticles;i++){const n=this.particles[i];n.shapeId==e&&t.push(n)}return this}computeSubMeshes(){if(!this.mesh||!this._multimaterialEnabled)return this;const e=this.depthSortedParticles;if(this.particles.length>0)for(let t=0;t<this.particles.length;t++){const i=this.particles[t];i.materialIndex||(i.materialIndex=0);const n=e[t];n.materialIndex=i.materialIndex,n.ind=i._ind,n.indicesLength=i._model._indicesLength,n.idx=i.idx}this._sortParticlesByMaterial();const t=this._indicesByMaterial,i=this._materialIndexes,n=this.mesh;n.subMeshes=[];const s=n.getTotalVertices();for(let e=0;e<i.length;e++){const r=t[e],o=t[e+1]-r,a=i[e];new Ll.P(a,0,s,r,o,n)}return this}_sortParticlesByMaterial(){const e=[0];this._indicesByMaterial=e;const t=[];this._materialIndexes=t;const i=this.depthSortedParticles;i.sort(this._materialSortFunction);const n=i.length,s=this._indices32,r=this._indices;let o=0,a=0,l=0,h=i[0].materialIndex;t.push(h),this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]);for(let c=0;c<n;c++){const n=i[c],u=n.indicesLength,d=n.ind;n.materialIndex!==h&&(h=n.materialIndex,e.push(l),t.push(h),this._pickable&&(o++,this.pickedBySubMesh[o]=[],a=0));let p=0;for(let e=0;e<u;e++){if(s[l]=r[d+e],this._pickable&&0==e%3){const e=this.pickedBySubMesh[o][a];e?(e.idx=n.idx,e.faceId=p):this.pickedBySubMesh[o][a]={idx:n.idx,faceId:p},a++,p++}l++}}return e.push(s.length),this._updatable&&this.mesh.updateIndices(s),this}_setMaterialIndexesById(){this._materialIndexesById={};for(let e=0;e<this._materials.length;e++){const t=this._materials[e].uniqueId;this._materialIndexesById[t]=e}}_filterUniqueMaterialId(e){return e.filter((function(e,t,i){return i.indexOf(e)===t}))}_setDefaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=new Gi.K(this.name+"DefaultMaterial",this._scene)),this._defaultMaterial}refreshVisibleSize(){return this._isVisibilityBoxLocked||this.mesh.refreshBoundingInfo(),this}setVisibilityBox(e){const t=e/2;this.mesh.buildBoundingInfo(new o.P(-t,-t,-t),new o.P(t,t,t))}get isAlwaysVisible(){return this._alwaysVisible}set isAlwaysVisible(e){this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e}set isVisibilityBoxLocked(e){this._isVisibilityBoxLocked=e,this.mesh.getBoundingInfo().isLocked=e}get isVisibilityBoxLocked(){return this._isVisibilityBoxLocked}set computeParticleRotation(e){this._computeParticleRotation=e}set computeParticleColor(e){this._computeParticleColor=e}set computeParticleTexture(e){this._computeParticleTexture=e}set computeParticleVertex(e){this._computeParticleVertex=e}set computeBoundingBox(e){this._computeBoundingBox=e}set depthSortParticles(e){this._depthSortParticles=e}get computeParticleRotation(){return this._computeParticleRotation}get computeParticleColor(){return this._computeParticleColor}get computeParticleTexture(){return this._computeParticleTexture}get computeParticleVertex(){return this._computeParticleVertex}get computeBoundingBox(){return this._computeBoundingBox}get depthSortParticles(){return this._depthSortParticles}get expandable(){return this._expandable}get multimaterialEnabled(){return this._multimaterialEnabled}get useModelMaterial(){return this._useModelMaterial}get materials(){return this._materials}setMultiMaterial(e){this._materials=this._filterUniqueMaterialId(e),this._setMaterialIndexesById(),this._multimaterial&&this._multimaterial.dispose(),this._multimaterial=new Ph.G(this.name+"MultiMaterial",this._scene);for(let e=0;e<this._materials.length;e++)this._multimaterial.subMaterials.push(this._materials[e]);this.computeSubMeshes(),this.mesh.material=this._multimaterial}get multimaterial(){return this._multimaterial}set multimaterial(e){this._multimaterial=e}get autoUpdateSubMeshes(){return this._autoUpdateSubMeshes}set autoUpdateSubMeshes(e){this._autoUpdateSubMeshes=e}initParticles(){}recycleParticle(e){return e}updateParticle(e){return e}updateParticleVertex(e,t,i){return this}beforeUpdateParticles(e,t,i){}afterUpdateParticles(e,t,i){}}class d_{constructor(e,t,i,n,s){this.idx=0,this.color=new Gr.HE(1,1,1,1),this.position=Gr.P.Zero(),this.rotation=Gr.P.Zero(),this.uv=new Gr.FM(0,0),this.velocity=Gr.P.Zero(),this.pivot=Gr.P.Zero(),this.translateFromPivot=!1,this._pos=0,this._ind=0,this.groupId=0,this.idxInGroup=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this._globalPosition=Gr.P.Zero(),this.idx=e,this._group=t,this.groupId=i,this.idxInGroup=n,this._pcs=s}get size(){return this.size}set size(e){this.size=e}get quaternion(){return this.rotationQuaternion}set quaternion(e){this.rotationQuaternion=e}intersectsMesh(e,t){if(!e.hasBoundingInfo)return!1;if(!this._pcs.mesh)throw new Error("Point Cloud System doesnt contain the Mesh");if(t)return e.getBoundingInfo().boundingSphere.intersectsPoint(this.position.add(this._pcs.mesh.position));const i=e.getBoundingInfo().boundingBox,n=i.maximumWorld.x,s=i.minimumWorld.x,r=i.maximumWorld.y,o=i.minimumWorld.y,a=i.maximumWorld.z,l=i.minimumWorld.z,h=this.position.x+this._pcs.mesh.position.x,c=this.position.y+this._pcs.mesh.position.y,u=this.position.z+this._pcs.mesh.position.z;return s<=h&&h<=n&&o<=c&&c<=r&&l<=u&&u<=a}getRotationMatrix(e){let t;if(this.rotationQuaternion)t=this.rotationQuaternion;else{t=Gr.jp.Quaternion[0];const e=this.rotation;Gr._f.RotationYawPitchRollToRef(e.y,e.x,e.z,t)}t.toRotationMatrix(e)}}class p_{get groupID(){return this.groupId}set groupID(e){this.groupId=e}constructor(e,t){this.groupId=e,this._positionFunction=t}}var f_,__,m_,g_,v_,y_,x_,b_,T_,S_;!function(e){e[e.Color=2]="Color",e[e.UV=1]="UV",e[e.Random=0]="Random",e[e.Stated=3]="Stated"}(f_||(f_={}));class E_{get positions(){return this._positions32}get colors(){return this._colors32}get uvs(){return this._uvs32}constructor(e,t,i,n){this.particles=new Array,this.nbParticles=0,this.counter=0,this.vars={},this._promises=[],this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._updatable=!0,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._groups=new Array,this._groupCounter=0,this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeBoundingBox=!1,this._isReady=!1,this.name=e,this._size=t,this._scene=i||A.l.LastCreatedScene,n&&void 0!==n.updatable?this._updatable=n.updatable:this._updatable=!0}buildMeshAsync(e){return Promise.all(this._promises).then((()=>(this._isReady=!0,this._buildMesh(e))))}_buildMesh(e){0===this.nbParticles&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);const t=new sn.x;t.set(this._positions32,qe.o.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,qe.o.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,qe.o.ColorKind));const n=new Nt.Kj(this.name,this._scene);t.applyToMesh(n,this._updatable),this.mesh=n,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let s=e;return s||(s=new Gi.K("point cloud material",this._scene),s.emissiveColor=new Gr.Wo(i,i,i),s.disableLighting=!0,s.pointsCloud=!0,s.pointSize=this._size),n.material=s,new Promise((e=>e(n)))}_addParticle(e,t,i,n){const s=new d_(e,t,i,n,this);return this.particles.push(s),s}_randomUnitVector(e){e.position=new o.P(Math.random(),Math.random(),Math.random()),e.color=new Gr.HE(1,1,1,1)}_getColorIndicesForCoord(e,t,i,n){const s=e._groupImageData,r=i*(4*n)+4*t,o=[r,r+1,r+2,r+3],a=o[1],l=o[2],h=o[3],c=s[o[0]],u=s[a],d=s[l],p=s[h];return new Gr.HE(c/255,u/255,d/255,p)}_setPointsColorOrUV(e,t,i,n,s,r,a){i&&e.updateFacetData();const l=2*e.getBoundingInfo().boundingSphere.radius;let h=e.getVerticesData(qe.o.PositionKind);const c=e.getIndices(),u=e.getVerticesData(qe.o.UVKind),d=e.getVerticesData(qe.o.ColorKind),p=o.P.Zero();e.computeWorldMatrix();const f=e.getWorldMatrix();if(!f.isIdentity()){h=h.slice(0);for(let e=0;e<h.length/3;e++)o.P.TransformCoordinatesFromFloatsToRef(h[3*e],h[3*e+1],h[3*e+2],f,p),h[3*e]=p.x,h[3*e+1]=p.y,h[3*e+2]=p.z}let _=0,m=0,g=0,v=0,y=0,x=0,b=0,T=0,S=0,E=0,C=0,A=0,P=0;const R=o.P.Zero(),M=o.P.Zero(),I=o.P.Zero(),D=o.P.Zero(),O=o.P.Zero();let w=0,N=0,F=0,L=0,B=0,U=0;const V=o.FM.Zero(),k=o.FM.Zero(),G=o.FM.Zero(),z=o.FM.Zero(),W=o.FM.Zero();let H=0,X=0,j=0,Y=0,q=0,K=0,$=0,Q=0,Z=0,J=0,ee=0,te=0;const ie=o.Lt.Zero(),ne=o.Lt.Zero(),se=o.Lt.Zero(),re=o.Lt.Zero(),oe=o.Lt.Zero();let ae,le,he=0,ce=0;a=a||0;let ue=new o.Lt(0,0,0,0),de=o.P.Zero(),pe=o.P.Zero(),fe=o.P.Zero(),_e=0,me=o.P.Zero(),ge=0,ve=0;const ye=new Yt.z(o.P.Zero(),new o.P(1,0,0));let xe,be=o.P.Zero();for(let p=0;p<c.length/3;p++){let f,Te,Se,Ee,Ce,Ae,Pe,Re;m=c[3*p],g=c[3*p+1],v=c[3*p+2],y=h[3*m],x=h[3*m+1],b=h[3*m+2],T=h[3*g],S=h[3*g+1],E=h[3*g+2],C=h[3*v],A=h[3*v+1],P=h[3*v+2],R.set(y,x,b),M.set(T,S,E),I.set(C,A,P),M.subtractToRef(R,D),I.subtractToRef(M,O),u&&(w=u[2*m],N=u[2*m+1],F=u[2*g],L=u[2*g+1],B=u[2*v],U=u[2*v+1],V.set(w,N),k.set(F,L),G.set(B,U),k.subtractToRef(V,z),G.subtractToRef(k,W)),d&&n&&(H=d[4*m],X=d[4*m+1],j=d[4*m+2],Y=d[4*m+3],q=d[4*g],K=d[4*g+1],$=d[4*g+2],Q=d[4*g+3],Z=d[4*v],J=d[4*v+1],ee=d[4*v+2],te=d[4*v+3],ie.set(H,X,j,Y),ne.set(q,K,$,Q),se.set(Z,J,ee,te),ne.subtractToRef(ie,re),se.subtractToRef(ne,oe));const Me=new Gr.Wo(0,0,0),Ie=new Gr.Wo(0,0,0);let De,Oe;for(let h=0;h<t._groupDensity[p];h++)_=this.particles.length,this._addParticle(_,t,this._groupCounter,p+h),Oe=this.particles[_],he=lt.R.RandomRange(0,1),ce=lt.R.RandomRange(0,1),ae=R.add(D.scale(he)).add(O.scale(he*ce)),i&&(de=e.getFacetNormal(p).normalize().scale(-1),pe=D.clone().normalize(),fe=o.P.Cross(de,pe),_e=lt.R.RandomRange(0,2*Math.PI),me=pe.scale(Math.cos(_e)).add(fe.scale(Math.sin(_e))),_e=lt.R.RandomRange(.1,Math.PI/2),be=me.scale(Math.cos(_e)).add(de.scale(Math.sin(_e))),ye.origin=ae.add(be.scale(1e-5)),ye.direction=be,ye.length=l,xe=ye.intersectsMesh(e),xe.hit&&(ve=xe.pickedPoint.subtract(ae).length(),ge=lt.R.RandomRange(0,1)*ve,ae.addInPlace(be.scale(ge)))),Oe.position=ae.clone(),this._positions.push(Oe.position.x,Oe.position.y,Oe.position.z),void 0!==n?u&&(le=V.add(z.scale(he)).add(W.scale(he*ce)),n?s&&null!==t._groupImageData?(f=t._groupImgWidth,Te=t._groupImgHeight,De=this._getColorIndicesForCoord(t,Math.round(le.x*f),Math.round(le.y*Te),f),Oe.color=De,this._colors.push(De.r,De.g,De.b,De.a)):d?(ue=ie.add(re.scale(he)).add(oe.scale(he*ce)),Oe.color=new Gr.HE(ue.x,ue.y,ue.z,ue.w),this._colors.push(ue.x,ue.y,ue.z,ue.w)):(ue=ie.set(Math.random(),Math.random(),Math.random(),1),Oe.color=new Gr.HE(ue.x,ue.y,ue.z,ue.w),this._colors.push(ue.x,ue.y,ue.z,ue.w)):(Oe.uv=le.clone(),this._uvs.push(Oe.uv.x,Oe.uv.y))):(r?(Me.set(r.r,r.g,r.b),Se=lt.R.RandomRange(-a,a),Ee=lt.R.RandomRange(-a,a),Re=Me.toHSV(),Ce=Re.r,Ae=Re.g+Se,Pe=Re.b+Ee,Ae<0&&(Ae=0),Ae>1&&(Ae=1),Pe<0&&(Pe=0),Pe>1&&(Pe=1),Gr.Wo.HSVtoRGBToRef(Ce,Ae,Pe,Ie),ue.set(Ie.r,Ie.g,Ie.b,1)):ue=ie.set(Math.random(),Math.random(),Math.random(),1),Oe.color=new Gr.HE(ue.x,ue.y,ue.z,ue.w),this._colors.push(ue.x,ue.y,ue.z,ue.w))}}_colorFromTexture(e,t,i){if(null===e.material)return _.Y.Warn(e.name+"has no material."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const n=e.material.getActiveTextures();if(0===n.length)return _.Y.Warn(e.name+"has no usable texture."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const s=e.clone();s.setEnabled(!1),this._promises.push(new Promise((e=>{Oa.V.WhenAllReady(n,(()=>{let r=t._textureNb;r<0&&(r=0),r>n.length-1&&(r=n.length-1);const o=()=>{t._groupImgWidth=n[r].getSize().width,t._groupImgHeight=n[r].getSize().height,this._setPointsColorOrUV(s,t,i,!0,!0),s.dispose(),e()};t._groupImageData=null;const a=n[r].readPixels();a?a.then((e=>{t._groupImageData=e,o()})):o()}))})))}_calculateDensity(e,t,i){let n,s,r,a,l,h,c,u,d,p,f,_,m=new Array;const g=o.P.Zero(),v=o.P.Zero(),y=o.P.Zero(),x=o.P.Zero(),b=o.P.Zero(),T=o.P.Zero();let S,E,C,A,P;const R=new Array;let M=0;const I=i.length/3;for(let e=0;e<I;e++)n=i[3*e],s=i[3*e+1],r=i[3*e+2],a=t[3*n],l=t[3*n+1],h=t[3*n+2],c=t[3*s],u=t[3*s+1],d=t[3*s+2],p=t[3*r],f=t[3*r+1],_=t[3*r+2],g.set(a,l,h),v.set(c,u,d),y.set(p,f,_),v.subtractToRef(g,x),y.subtractToRef(v,b),y.subtractToRef(g,T),S=x.length(),E=b.length(),C=T.length(),A=(S+E+C)/2,P=Math.sqrt(A*(A-S)*(A-E)*(A-C)),M+=P,R[e]=P;let D=0;for(let t=0;t<I;t++)m[t]=Math.floor(e*R[t]/M),D+=m[t];const O=e-D,w=Math.floor(O/I),N=O%I;w>0&&(m=m.map((e=>e+w)));for(let e=0;e<N;e++)m[e]+=1;return m}addPoints(e,t=this._randomUnitVector){const i=new p_(this._groupCounter,t);let n,s=this.nbParticles;for(let t=0;t<e;t++)n=this._addParticle(s,i,this._groupCounter,t),i&&i._positionFunction&&i._positionFunction(n,s,t),this._positions.push(n.position.x,n.position.y,n.position.z),n.color&&this._colors.push(n.color.r,n.color.g,n.color.b,n.color.a),n.uv&&this._uvs.push(n.uv.x,n.uv.y),s++;return this.nbParticles+=e,this._groupCounter++,this._groupCounter}addSurfacePoints(e,t,i,n,s){let r=i||f_.Random;(isNaN(r)||r<0||r>3)&&(r=f_.Random);const o=e.getVerticesData(qe.o.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new p_(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),r===f_.Color?l._textureNb=n||0:n=n||new Gr.HE(1,1,1,1),r){case f_.Color:this._colorFromTexture(e,l,!1);break;case f_.UV:this._setPointsColorOrUV(e,l,!1,!1,!1);break;case f_.Random:this._setPointsColorOrUV(e,l,!1);break;case f_.Stated:this._setPointsColorOrUV(e,l,!1,void 0,void 0,n,s)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,n,s){let r=i||f_.Random;(isNaN(r)||r<0||r>3)&&(r=f_.Random);const o=e.getVerticesData(qe.o.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new p_(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),r===f_.Color?l._textureNb=n||0:n=n||new Gr.HE(1,1,1,1),r){case f_.Color:this._colorFromTexture(e,l,!0);break;case f_.UV:this._setPointsColorOrUV(e,l,!0,!1,!1);break;case f_.Random:this._setPointsColorOrUV(e,l,!0);break;case f_.Stated:this._setPointsColorOrUV(e,l,!0,void 0,void 0,n,s)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){var n,s;if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const r=o.jp.Matrix[0],a=this.mesh,l=this._colors32,h=this._positions32,c=this._uvs32,u=o.jp.Vector3,d=u[5].copyFromFloats(1,0,0),p=u[6].copyFromFloats(0,1,0),f=u[7].copyFromFloats(0,0,1),_=u[8].setAll(Number.MAX_VALUE),m=u[9].setAll(-Number.MAX_VALUE);o.y3.IdentityToRef(r);let g=0;if((null===(n=this.mesh)||void 0===n?void 0:n.isFacetDataEnabled)&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=null===(s=this.mesh)||void 0===s?void 0:s.getBoundingInfo();e&&(_.copyFrom(e.minimum),m.copyFrom(e.maximum))}g=0;let v=0,y=0,x=0;for(let i=e;i<=t;i++){const e=this.particles[i];g=e.idx,v=3*g,y=4*g,x=2*g,this.updateParticle(e);const t=e._rotationMatrix,n=e.position,s=e._globalPosition;if(this._computeParticleRotation&&e.getRotationMatrix(r),null!==e.parentId){const i=this.particles[e.parentId],o=i._rotationMatrix,a=i._globalPosition,l=n.x*o[1]+n.y*o[4]+n.z*o[7],h=n.x*o[0]+n.y*o[3]+n.z*o[6],c=n.x*o[2]+n.y*o[5]+n.z*o[8];if(s.x=a.x+h,s.y=a.y+l,s.z=a.z+c,this._computeParticleRotation){const e=r.m;t[0]=e[0]*o[0]+e[1]*o[3]+e[2]*o[6],t[1]=e[0]*o[1]+e[1]*o[4]+e[2]*o[7],t[2]=e[0]*o[2]+e[1]*o[5]+e[2]*o[8],t[3]=e[4]*o[0]+e[5]*o[3]+e[6]*o[6],t[4]=e[4]*o[1]+e[5]*o[4]+e[6]*o[7],t[5]=e[4]*o[2]+e[5]*o[5]+e[6]*o[8],t[6]=e[8]*o[0]+e[9]*o[3]+e[10]*o[6],t[7]=e[8]*o[1]+e[9]*o[4]+e[10]*o[7],t[8]=e[8]*o[2]+e[9]*o[5]+e[10]*o[8]}}else if(s.x=0,s.y=0,s.z=0,this._computeParticleRotation){const e=r.m;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10]}const o=u[11];e.translateFromPivot?o.setAll(0):o.copyFrom(e.pivot);const a=u[0];a.copyFrom(e.position);const l=a.x-e.pivot.x,c=a.y-e.pivot.y,b=a.z-e.pivot.z;let T=l*t[0]+c*t[3]+b*t[6],S=l*t[1]+c*t[4]+b*t[7],E=l*t[2]+c*t[5]+b*t[8];T+=o.x,S+=o.y,E+=o.z;const C=h[v]=s.x+d.x*T+p.x*S+f.x*E,A=h[v+1]=s.y+d.y*T+p.y*S+f.y*E,P=h[v+2]=s.z+d.z*T+p.z*S+f.z*E;if(this._computeBoundingBox&&(_.minimizeInPlaceFromFloats(C,A,P),m.maximizeInPlaceFromFloats(C,A,P)),this._computeParticleColor&&e.color){const t=e.color,i=this._colors32;i[y]=t.r,i[y+1]=t.g,i[y+2]=t.b,i[y+3]=t.a}if(this._computeParticleTexture&&e.uv){const t=e.uv,i=this._uvs32;i[x]=t.x,i[x+1]=t.y}}return a&&(i&&(this._computeParticleColor&&a.updateVerticesData(qe.o.ColorKind,l,!1,!1),this._computeParticleTexture&&a.updateVerticesData(qe.o.UVKind,c,!1,!1),a.updateVerticesData(qe.o.PositionKind,h,!1,!1)),this._computeBoundingBox&&(a.hasBoundingInfo?a.getBoundingInfo().reConstruct(_,m,a._worldMatrix):a.buildBoundingInfo(_,m,a._worldMatrix))),this.afterUpdateParticles(e,t,i),this}dispose(){var e;null===(e=this.mesh)||void 0===e||e.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null}refreshVisibleSize(){var e;return this._isVisibilityBoxLocked||null===(e=this.mesh)||void 0===e||e.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const t=e/2;this.mesh.buildBoundingInfo(new o.P(-t,-t,-t),new o.P(t,t,t))}get isAlwaysVisible(){return this._alwaysVisible}set isAlwaysVisible(e){this.mesh&&(this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e)}set computeParticleRotation(e){this._computeParticleRotation=e}set computeParticleColor(e){this._computeParticleColor=e}set computeParticleTexture(e){this._computeParticleTexture=e}get computeParticleColor(){return this._computeParticleColor}get computeParticleTexture(){return this._computeParticleTexture}set computeBoundingBox(e){this._computeBoundingBox=e}get computeBoundingBox(){return this._computeBoundingBox}initParticles(){}recycleParticle(e){return e}updateParticle(e){return e}beforeUpdateParticles(e,t,i){}afterUpdateParticles(e,t,i){}}Object.defineProperty(Un.x.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),Un.x.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},Un.x.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},Un.x.prototype.setPhysicsLinkWith=function(e,t,i,n){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,Nh.q7.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:n}),this):this};class C_{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,Zl.S)("")}constructor(e,t=C_.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new o.P(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){this._physicsPlugin.raycast(e,t,i)}raycast(e,t){const i=new Fh.d;return this._physicsPlugin.raycast(e,t,i),i}}class A_{constructor(e,t,i,n){if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this.disablePreStep=!0,!n)return;const s=n.getPhysicsEngine();if(!s)throw new Error("No Physics Engine available.");if(this._physicsEngine=s,2!=s.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");const r=s.getPhysicsPlugin();if(!r)throw new Error("No Physics Plugin available.");this._physicsPlugin=r,e.rotationQuaternion||(e.rotationQuaternion=o._f.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),this.startAsleep=i;const a=e;a.hasThinInstances?this._physicsPlugin.initBodyInstances(this,t,a):this._physicsPlugin.initBody(this,t,e.absolutePosition,e.absoluteRotationQuaternion),this.transformNode=e,e.physicsBody=this,s.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}getClassName(){return"PhysicsBody"}clone(e){const t=new A_(e,this.getMotionType(),this.startAsleep,this.transformNode.getScene());return t.shape=this.shape,t}updateBodyInstances(){const e=this.transformNode;e.hasThinInstances&&this._physicsPlugin.updateBodyInstances(this,e)}get numInstances(){return this._pluginDataInstances.length}set shape(e){this._physicsPlugin.setShape(this,e)}get shape(){return this._physicsPlugin.getShape(this)}setEventMask(e,t){this._physicsPlugin.setEventMask(this,e,t)}getEventMask(e){return this._physicsPlugin.getEventMask(this,e)}setMotionType(e,t){this._physicsPlugin.setMotionType(this,e,t)}getMotionType(e){return this._physicsPlugin.getMotionType(this,e)}computeMassProperties(e){return this._physicsPlugin.computeMassProperties(this,e)}setMassProperties(e,t){this._physicsPlugin.setMassProperties(this,e,t)}getMassProperties(e){return this._physicsPlugin.getMassProperties(this,e)}setLinearDamping(e,t){this._physicsPlugin.setLinearDamping(this,e,t)}getLinearDamping(e){return this._physicsPlugin.getLinearDamping(this,e)}setAngularDamping(e,t){this._physicsPlugin.setAngularDamping(this,e,t)}getAngularDamping(e){return this._physicsPlugin.getAngularDamping(this,e)}setLinearVelocity(e,t){this._physicsPlugin.setLinearVelocity(this,e,t)}getLinearVelocityToRef(e,t){return this._physicsPlugin.getLinearVelocityToRef(this,e,t)}setAngularVelocity(e,t){this._physicsPlugin.setAngularVelocity(this,e,t)}getAngularVelocityToRef(e,t){return this._physicsPlugin.getAngularVelocityToRef(this,e,t)}applyImpulse(e,t,i){this._physicsPlugin.applyImpulse(this,e,t,i)}applyForce(e,t,i){this._physicsPlugin.applyForce(this,e,t,i)}getGeometry(){return this._physicsPlugin.getBodyGeometry(this)}getCollisionObservable(){return this._physicsPlugin.getCollisionObservable(this)}setCollisionCallbackEnabled(e){this._collisionCBEnabled=e,this._physicsPlugin.setCollisionCallbackEnabled(this,e)}getObjectCenterWorld(e){const t=new o.P;return this.getObjectCenterWorldToRef(t,e)}getObjectCenterWorldToRef(e,t){var i;if((null===(i=this._pluginDataInstances)||void 0===i?void 0:i.length)>0){const i=t||0,n=this.transformNode._thinInstanceDataStorage.matrixData;n&&e.set(n[16*i+12],n[16*i+13],n[16*i+14])}else e.copyFrom(this.transformNode.position);return e}addConstraint(e,t,i,n){this._physicsPlugin.addConstraint(this,e,t,i,n)}syncWithBone(e,t,i,n,s,r){const a=this.transformNode;if(a.rotationQuaternion)if(s){const i=o.jp.Quaternion[0];e.getRotationQuaternionToRef(We.T.WORLD,t,i),i.multiplyToRef(s,a.rotationQuaternion)}else e.getRotationQuaternionToRef(We.T.WORLD,t,a.rotationQuaternion);const l=o.jp.Vector3[0],h=o.jp.Vector3[1];r||((r=o.jp.Vector3[2]).x=0,r.y=1,r.z=0),e.getDirectionToRef(r,t,h),e.getAbsolutePositionToRef(t,l),null==n&&i&&(n=i.length()),null!=n&&(l.x+=h.x*n,l.y+=h.y*n,l.z+=h.z*n),a.setAbsolutePosition(l)}iterateOverAllInstances(e){var t;if((null===(t=this._pluginDataInstances)||void 0===t?void 0:t.length)>0)for(let t=0;t<this._pluginDataInstances.length;t++)e(this,t);else e(this,void 0)}setGravityFactor(e,t){this._physicsPlugin.setGravityFactor(this,e,t)}getGravityFactor(e){return this._physicsPlugin.getGravityFactor(this,e)}dispose(){this._collisionCBEnabled&&this.setCollisionCallbackEnabled(!1),this._nodeDisposeObserver&&(this.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this._physicsEngine.removeBody(this),this._physicsPlugin.removeBody(this),this._physicsPlugin.disposeBody(this),this._pluginData=null,this._pluginDataInstances.length=0}}!function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"}(__||(__={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(m_||(m_={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(g_||(g_={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(v_||(v_={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(y_||(y_={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(x_||(x_={}));class P_{constructor(e,t){var i;if(this._pluginData=void 0,!t)return;const n=t.getPhysicsEngine();if(!n)throw new Error("No Physics Engine available.");if(2!=n.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");const s=n.getPhysicsPlugin();if(!s)throw new Error("No Physics Plugin available.");if(this._physicsPlugin=s,void 0!==e.pluginData&&null!==e.pluginData)this._pluginData=e.pluginData,this._type=this._physicsPlugin.getShapeType(this);else if(void 0!==e.type&&null!==e.type){this._type=e.type;const t=null!==(i=e.parameters)&&void 0!==i?i:{};this._physicsPlugin.initShape(this,e.type,t)}}getClassName(){return"PhysicsShape"}get type(){return this._type}set filterMembershipMask(e){this._physicsPlugin.setShapeFilterMembershipMask(this,e)}get filterMembershipMask(){return this._physicsPlugin.getShapeFilterMembershipMask(this)}set filterCollideMask(e){this._physicsPlugin.setShapeFilterCollideMask(this,e)}get filterCollideMask(){return this._physicsPlugin.getShapeFilterCollideMask(this)}set material(e){this._physicsPlugin.setMaterial(this,e),this._material=e}get material(){return this._material}set density(e){this._physicsPlugin.setDensity(this,e)}get density(){return this._physicsPlugin.getDensity(this)}addChildFromParent(e,t,i){const n=i.computeWorldMatrix(!0),s=e.computeWorldMatrix(!0),r=o.jp.Matrix[0];n.multiplyToRef(o.y3.Invert(s),r);const a=o.jp.Vector3[0],l=o.jp.Quaternion[0],h=o.jp.Vector3[1];r.decompose(h,l,a),this._physicsPlugin.addChild(this,t,a,l,h)}addChild(e,t,i,n){this._physicsPlugin.addChild(this,e,t,i,n)}removeChild(e){this._physicsPlugin.removeChild(this,e)}getNumChildren(){return this._physicsPlugin.getNumChildren(this)}getBoundingBox(){return this._physicsPlugin.getBoundingBox(this)}dispose(){this._physicsPlugin.disposeShape(this)}}class R_ extends P_{constructor(e,t,i){super({type:v_.SPHERE,parameters:{center:e,radius:t}},i)}static FromMesh(e){const t=e.getBoundingInfo(),i=t.boundingSphere.center,n=t.boundingBox.extendSize,s=Math.max(n.x,n.y,n.z);return new R_(i,s,e.getScene())}}class M_ extends P_{constructor(e,t,i,n){super({type:v_.CAPSULE,parameters:{pointA:e,pointB:t,radius:i}},n)}static FromMesh(e){const t=e.getBoundingInfo(),i=t.boundingBox.extendSize.x,n=new o.P(0,t.boundingBox.extendSize.y-i,0),s=t.boundingBox.center.add(n),r=t.boundingBox.center.subtract(n);return new M_(s,r,i,e.getScene())}}class I_ extends P_{constructor(e,t,i,n){super({type:v_.CYLINDER,parameters:{pointA:e,pointB:t,radius:i}},n)}static FromMesh(e){const t=e.getBoundingInfo(),i=t.boundingBox.extendSize.x,n=new o.P(0,t.boundingBox.extendSize.y,0),s=t.boundingBox.center.add(n),r=t.boundingBox.center.subtract(n);return new I_(s,r,i,e.getScene())}}class D_ extends P_{constructor(e,t,i,n){super({type:v_.BOX,parameters:{center:e,rotation:t,extents:i}},n)}static FromMesh(e){const t=e.getBoundingInfo(),i=t.boundingBox.center,n=t.boundingBox.extendSize.scale(2);return new D_(i,o._f.Identity(),n,e.getScene())}}class O_ extends P_{constructor(e,t){super({type:v_.CONVEX_HULL,parameters:{mesh:e}},t)}}class w_ extends P_{constructor(e,t){super({type:v_.MESH,parameters:{mesh:e}},t)}}class N_ extends P_{constructor(e){super({type:v_.CONTAINER,parameters:{}},e)}}class F_{constructor(e,t,i){if(this._pluginData=void 0,!i)throw new Error("Missing scene parameter for constraint constructor.");const n=i.getPhysicsEngine();if(!n)throw new Error("No Physics Engine available.");if(2!=n.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");const s=n.getPhysicsPlugin();if(!s)throw new Error("No Physics Plugin available.");this._physicsPlugin=s,this._options=t,this._type=e}get type(){return this._type}get options(){return this._options}set isEnabled(e){this._physicsPlugin.setEnabled(this,e)}get isEnabled(){return this._physicsPlugin.getEnabled(this)}set isCollisionsEnabled(e){this._physicsPlugin.setCollisionsEnabled(this,e)}get isCollisionsEnabled(){return this._physicsPlugin.getCollisionsEnabled(this)}dispose(){this._physicsPlugin.disposeConstraint(this)}}class L_{}class B_ extends F_{constructor(e,t,i){super(g_.SIX_DOF,e,i),this.limits=t}setAxisFriction(e,t){this._physicsPlugin.setAxisFriction(this,e,t)}getAxisFriction(e){return this._physicsPlugin.getAxisFriction(this,e)}setAxisMode(e,t){this._physicsPlugin.setAxisMode(this,e,t)}getAxisMode(e){return this._physicsPlugin.getAxisMode(this,e)}setAxisMinLimit(e,t){this._physicsPlugin.setAxisMinLimit(this,e,t)}getAxisMinLimit(e){return this._physicsPlugin.getAxisMinLimit(this,e)}setAxisMaxLimit(e,t){this._physicsPlugin.setAxisMaxLimit(this,e,t)}getAxisMaxLimit(e){return this._physicsPlugin.getAxisMaxLimit(this,e)}setAxisMotorType(e,t){this._physicsPlugin.setAxisMotorType(this,e,t)}getAxisMotorType(e){return this._physicsPlugin.getAxisMotorType(this,e)}setAxisMotorTarget(e,t){this._physicsPlugin.setAxisMotorTarget(this,e,t)}getAxisMotorTarget(e){return this._physicsPlugin.getAxisMotorTarget(this,e)}setAxisMotorMaxForce(e,t){this._physicsPlugin.setAxisMotorMaxForce(this,e,t)}getAxisMotorMaxForce(e){return this._physicsPlugin.getAxisMotorMaxForce(this,e)}}class U_ extends F_{constructor(e,t,i,n,s){super(g_.BALL_AND_SOCKET,{pivotA:e,pivotB:t,axisA:i,axisB:n},s)}}class V_ extends F_{constructor(e,t){super(g_.DISTANCE,{maxDistance:e},t)}}class k_ extends F_{constructor(e,t,i,n,s){super(g_.HINGE,{pivotA:e,pivotB:t,axisA:i,axisB:n},s)}}class G_ extends F_{constructor(e,t,i,n,s){super(g_.SLIDER,{pivotA:e,pivotB:t,axisA:i,axisB:n},s)}}class z_ extends F_{constructor(e,t,i,n,s){super(g_.LOCK,{pivotA:e,pivotB:t,axisA:i,axisB:n},s)}}class W_ extends F_{constructor(e,t,i,n,s){super(g_.PRISMATIC,{pivotA:e,pivotB:t,axisA:i,axisB:n},s)}}!function(e){e[e.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",e[e.MINIMUM=1]="MINIMUM",e[e.MAXIMUM=2]="MAXIMUM",e[e.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",e[e.MULTIPLY=4]="MULTIPLY"}(b_||(b_={}));class H_{constructor(e,t,i={mass:0},n){var s;if(this.transformNode=e,this.type=t,this._options=i,this._scene=n,this._disposeShapeWhenDisposed=!0,!this.transformNode)return void _.Y.Error("No object was provided. A physics object is obligatory");const r=e;if(this.transformNode.parent&&0!==this._options.mass&&r.hasThinInstances&&_.Y.Warn("A physics body has been created for an object which has a parent and thin instances. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),!this._scene)return;this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution;const o=0===this._options.mass?x_.STATIC:x_.DYNAMIC,a=null!==(s=this._options.startAsleep)&&void 0!==s&&s;this.body=new A_(e,o,a,this._scene),this._addSizeOptions(),t.getClassName&&"PhysicsShape"===t.getClassName()?(this.shape=t,this._disposeShapeWhenDisposed=!1):this.shape=new P_({type:t,parameters:this._options},this._scene),this.material={friction:this._options.friction,restitution:this._options.restitution},this.body.shape=this.shape,this.shape.material=this.material,this.body.setMassProperties({mass:this._options.mass}),this._nodeDisposeObserver=this.transformNode.onDisposeObservable.add((()=>{this.dispose()}))}_getObjectBoundingBox(){return this.transformNode.getRawBoundingInfo?this.transformNode.getRawBoundingInfo().boundingBox:new On.k(new o.P(-.5,-.5,-.5),new o.P(.5,.5,.5))}_addSizeOptions(){var e,t,i,n,s,r,a,l;this.transformNode.computeWorldMatrix(!0);const h=this._getObjectBoundingBox(),c=o.jp.Vector3[0];c.copyFrom(h.extendSize),c.scaleInPlace(2),c.multiplyInPlace(this.transformNode.scaling);const u=o.jp.Vector3[1];if(u.copyFrom(h.minimum),u.multiplyInPlace(this.transformNode.scaling),!this._options.center){const e=new o.P;e.copyFrom(h.center),e.multiplyInPlace(this.transformNode.scaling),this._options.center=e}switch(this.type){case v_.SPHERE:!this._options.radius&&lt.R.WithinEpsilon(c.x,c.y,1e-4)&&lt.R.WithinEpsilon(c.x,c.z,1e-4)?this._options.radius=c.x/2:this._options.radius||(_.Y.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."),this._options.radius=Math.max(c.x,c.y,c.z)/2);break;case v_.CAPSULE:{const n=c.x/2;this._options.radius=null!==(e=this._options.radius)&&void 0!==e?e:n,this._options.pointA=null!==(t=this._options.pointA)&&void 0!==t?t:new o.P(0,u.y+n,0),this._options.pointB=null!==(i=this._options.pointB)&&void 0!==i?i:new o.P(0,u.y+c.y-n,0)}break;case v_.CYLINDER:{const e=c.x/2;this._options.radius=null!==(n=this._options.radius)&&void 0!==n?n:e,this._options.pointA=null!==(s=this._options.pointA)&&void 0!==s?s:new o.P(0,u.y,0),this._options.pointB=null!==(r=this._options.pointB)&&void 0!==r?r:new o.P(0,u.y+c.y,0)}break;case v_.MESH:case v_.CONVEX_HULL:if(this._options.mesh||"Mesh"!==this.transformNode.getClassName()&&"InstancedMesh"!==this.transformNode.getClassName()){if(!this._options.mesh||!this._options.mesh.getClassName||"Mesh"!==this._options.mesh.getClassName()&&"InstancedMesh"!==this._options.mesh.getClassName())throw new Error("No valid mesh was provided for mesh or convex hull shape parameter.")}else this._options.mesh=this.transformNode;break;case v_.BOX:this._options.extents=null!==(a=this._options.extents)&&void 0!==a?a:new o.P(c.x,c.y,c.z),this._options.rotation=null!==(l=this._options.rotation)&&void 0!==l?l:o._f.Identity()}}dispose(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()}}class X_{constructor(e,t,i){this._vertices=[],this._indices=[];const n=e.computeWorldMatrix(!0),s=new o.P,r=new o._f,a=new o.P;n.decompose(s,r,a),this._bodyFromWorld=o.y3.Compose(o.P.One(),e.rotationQuaternion?e.rotationQuaternion:o._f.Identity(),e.position),this._bodyFromWorld=this._bodyFromWorld.invert(),this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}addMesh(e,t){const i=this._vertices.length,n=e.computeWorldMatrix(!0).multiply(this._bodyFromWorld),s=e.getVerticesData(qe.o.PositionKind)||[],r=s.length/3;for(let e=0;e<r;e++){const t=new o.P(s[3*e+0],s[3*e+1],s[3*e+2]);this._vertices.push(o.P.TransformCoordinates(t,n))}if(this._collectIndices){const t=e.getIndices();if(t)for(let e=0;e<t.length;e+=3)this._isRightHanded?(this._indices.push(t[e+0]+i),this._indices.push(t[e+1]+i),this._indices.push(t[e+2]+i)):(this._indices.push(t[e+2]+i),this._indices.push(t[e+1]+i),this._indices.push(t[e+0]+i))}t&&e.getChildMeshes(!1).filter((e=>!e.physicsBody)).forEach((e=>this.addMesh(e,t)))}getVertices(e){const t=3*this._vertices.length,i=4*t,n=e._malloc(i),s=new Float32Array(e.HEAPU8.buffer,n,t);for(let e=0;e<this._vertices.length;e++)s[3*e+0]=this._vertices[e].x,s[3*e+1]=this._vertices[e].y,s[3*e+2]=this._vertices[e].z;return s}freeBuffer(e,t){e._free(t.byteOffset)}getTriangles(e){const t=4*this._indices.length,i=e._malloc(t),n=new Int32Array(e.HEAPU8.buffer,i,this._indices.length);for(let e=0;e<this._indices.length;e++)n[e]=this._indices[e];return n}}class j_{constructor(e){this.hpBodyId=e,this.userMassProps={centerOfMass:void 0,mass:void 0,inertia:void 0,inertiaOrientation:void 0}}}class Y_{constructor(){this.bodyId=BigInt(0),this.position=new o.P,this.normal=new o.P}}class q_{constructor(){this.contactOnA=new Y_,this.contactOnB=new Y_,this.impulseApplied=0}static readToRef(e,t,i){const n=new Int32Array(e,t),s=new Float32Array(e,t);i.contactOnA.bodyId=BigInt(n[2]),i.contactOnA.position.set(s[10],s[11],s[12]),i.contactOnA.normal.set(s[13],s[14],s[15]),i.contactOnB.bodyId=BigInt(n[18]),i.contactOnB.position.set(s[26],s[27],s[28]),i.contactOnB.normal.set(s[29],s[30],s[31]),i.impulseApplied=s[33]}}class K_{constructor(e=!0,t=HK){this._useDeltaForWorldStep=e,this._hknp={},this.name="HavokPlugin",this._fixedTimeStep=1/60,this._timeStep=1/60,this._tmpVec3=Xe.B.BuildArray(3,o.P.Zero),this._bodies=new Map,this._bodyCollisionObservable=new Map,this.onCollisionObservable=new r.y$,"function"!=typeof t?(this._hknp=t,this.isSupported()?(this.world=this._hknp.HP_World_Create()[1],this._queryCollector=this._hknp.HP_QueryCollector_Create(1)[1]):_.Y.Error("Havok is not available. Please make sure you included the js file.")):_.Y.Error("Havok is not ready. Please make sure you await HK() before using the plugin.")}isSupported(){return void 0!==this._hknp}setGravity(e){this._hknp.HP_World_SetGravity(this.world,this._bVecToV3(e))}setTimeStep(e){this._fixedTimeStep=e}getTimeStep(){return this._fixedTimeStep}executeStep(e,t){for(const e of t)e.disablePreStep||this.setPhysicsBodyTransformation(e,e.transformNode);this._hknp.HP_World_Step(this.world,this._useDeltaForWorldStep?e:this._timeStep),this._bodyBuffer=this._hknp.HP_World_GetBodyBuffer(this.world)[1];for(const e of t)this.sync(e);this._notifyCollisions()}getPluginVersion(){return 2}initBody(e,t,i,n){e._pluginData=new j_(this._hknp.HP_Body_Create()[1]),this._internalSetMotionType(e._pluginData,t);const s=[this._bVecToV3(i),this._bQuatToV4(n)];this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,s),this._hknp.HP_World_AddBody(this.world,e._pluginData.hpBodyId,e.startAsleep),this._bodies.set(e._pluginData.hpBodyId[0],{body:e,index:0})}removeBody(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(const t of e._pluginDataInstances)this._bodyCollisionObservable.delete(t.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,t.hpBodyId);e._pluginData&&(this._bodyCollisionObservable.delete(e._pluginData.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,e._pluginData.hpBodyId))}initBodyInstances(e,t,i){var n,s;const r=null!==(s=null===(n=i._thinInstanceDataStorage)||void 0===n?void 0:n.instancesCount)&&void 0!==s?s:0,o=i._thinInstanceDataStorage.matrixData;o&&(this._createOrUpdateBodyInstances(e,t,o,0,r,!1),e._pluginDataInstances.forEach(((t,i)=>{this._bodies.set(t.hpBodyId[0],{body:e,index:i})})))}_createOrUpdateBodyInstances(e,t,i,n,s,r){const a=o.jp.Quaternion[0],l=o.y3.Identity();for(let h=n;h<s;h++){const n=[i[16*h+12],i[16*h+13],i[16*h+14]];let s;s=r?e._pluginDataInstances[h].hpBodyId:this._hknp.HP_Body_Create()[1],l.setRowFromFloats(0,i[16*h+0],i[16*h+1],i[16*h+2],0),l.setRowFromFloats(1,i[16*h+4],i[16*h+5],i[16*h+6],0),l.setRowFromFloats(2,i[16*h+8],i[16*h+9],i[16*h+10],0),o._f.FromRotationMatrixToRef(l,a);const c=[n,[a.x,a.y,a.z,a.w]];if(this._hknp.HP_Body_SetQTransform(s,c),!r){const i=new j_(s);e._pluginDataInstances.length&&(i.userMassProps=e._pluginDataInstances[0].userMassProps),this._internalSetMotionType(i,t),this._internalUpdateMassProperties(i),e._pluginDataInstances.push(i),this._hknp.HP_World_AddBody(this.world,s,e.startAsleep),i.worldTransformOffset=this._hknp.HP_Body_GetWorldTransformOffset(s)[1]}}}updateBodyInstances(e,t){var i,n;const s=null!==(n=null===(i=t._thinInstanceDataStorage)||void 0===i?void 0:i.instancesCount)&&void 0!==n?n:0,r=t._thinInstanceDataStorage.matrixData;if(!r)return;const o=e._pluginDataInstances.length,a=this.getMotionType(e);if(s>o){this._createOrUpdateBodyInstances(e,a,r,o,s,!1);const t=this._hknp.HP_Body_GetShape(e._pluginDataInstances[0].hpBodyId)[1];for(let i=o;i<s;i++)this._hknp.HP_Body_SetShape(e._pluginDataInstances[i].hpBodyId,t),this._internalUpdateMassProperties(e._pluginDataInstances[i]),this._bodies.set(e._pluginDataInstances[i].hpBodyId[0],{body:e,index:i})}else if(s<o){const t=o-s;for(let i=0;i<t;i++){const t=e._pluginDataInstances.pop();this._bodies.delete(t.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,t.hpBodyId),this._hknp.HP_Body_Release(t.hpBodyId)}this._createOrUpdateBodyInstances(e,a,r,0,s,!0)}}sync(e){this.syncTransform(e,e.transformNode)}syncTransform(e,t){if(e._pluginDataInstances.length){const i=t,n=i._thinInstanceDataStorage.matrixData;if(!n)return;const s=e._pluginDataInstances.length;for(let t=0;t<s;t++){const i=e._pluginDataInstances[t].worldTransformOffset,s=new Float32Array(this._hknp.HEAPU8.buffer,this._bodyBuffer+i,16),r=16*t;for(let e=0;e<15;e++)3!=(3&e)&&(n[r+e]=s[e]);n[r+15]=1}i.thinInstanceBufferUpdated("matrix")}else try{const i=this._hknp.HP_Body_GetQTransform(e._pluginData.hpBodyId)[1],n=i[0],s=i[1],r=o.jp.Quaternion[0];r.set(s[0],s[1],s[2],s[3]);const a=t.parent;if(a&&a.absoluteRotationQuaternion){o.jp.Vector3[2].set(n[0],n[1],n[2]),a.absoluteRotationQuaternion.conjugateToRef(o.jp.Quaternion[1]),r.multiplyInPlace(o.jp.Quaternion[1]),o.jp.Vector3[2].subtractToRef(a.absolutePosition,o.jp.Vector3[0]);const e=o.jp.Vector3[1];o.jp.Vector3[0].rotateByQuaternionToRef(o.jp.Quaternion[1],e),t.position.set(e.x,e.y,e.z)}else t.position.set(n[0],n[1],n[2]);t.rotationQuaternion?t.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(t.rotation)}catch(e){console.log(`Syncing transform failed for node ${t.name}: ${e.message}...`)}}setShape(e,t){var i,n,s;const r=t&&t._pluginData?t._pluginData:BigInt(0);if(!(e.transformNode instanceof Nt.Kj&&(null===(i=e.transformNode._thinInstanceDataStorage)||void 0===i?void 0:i.matrixData)))return this._hknp.HP_Body_SetShape(e._pluginData.hpBodyId,r),void this._internalUpdateMassProperties(e._pluginData);const o=null!==(s=null===(n=e.transformNode._thinInstanceDataStorage)||void 0===n?void 0:n.instancesCount)&&void 0!==s?s:0;for(let t=0;t<o;t++)this._hknp.HP_Body_SetShape(e._pluginDataInstances[t].hpBodyId,r),this._internalUpdateMassProperties(e._pluginDataInstances[t])}_getPluginReference(e,t){var i;return(null===(i=e._pluginDataInstances)||void 0===i?void 0:i.length)?e._pluginDataInstances[null!=t?t:0]:e._pluginData}getShape(e){const t=this._getPluginReference(e),i=this._hknp.HP_Body_GetShape(t.hpBodyId)[1];if(0!=i){const t=e.transformNode.getScene();return new P_({pluginData:i},t)}return null}getShapeType(e){return e.type?e.type:this._hknp.HP_Shape_GetType(e._pluginData)}setEventMask(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t)}),i)}getEventMask(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetEventMask(i)[1]}_fromMassPropertiesTuple(e){return{centerOfMass:o.P.FromArray(e[0]),mass:e[1],inertia:o.P.FromArray(e[2]),inertiaOrientation:o._f.FromArray(e[3])}}_internalUpdateMassProperties(e){const t=this._internalComputeMassProperties(e),i=e.userMassProps;i.centerOfMass&&(t[0]=i.centerOfMass.asArray()),null!=i.mass&&(t[1]=i.mass),i.inertia&&(t[2]=i.inertia.asArray()),i.inertiaOrientation&&(t[3]=i.inertiaOrientation.asArray()),this._hknp.HP_Body_SetMassProperties(e.hpBodyId,t)}_internalSetMotionType(e,t){switch(t){case x_.STATIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.STATIC);break;case x_.ANIMATED:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.KINEMATIC);break;case x_.DYNAMIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.DYNAMIC)}}setMotionType(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._internalSetMotionType(e,t)}),i)}getMotionType(e,t){const i=this._getPluginReference(e,t),n=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(n){case this._hknp.MotionType.STATIC:return x_.STATIC;case this._hknp.MotionType.KINEMATIC:return x_.ANIMATED;case this._hknp.MotionType.DYNAMIC:return x_.DYNAMIC}throw new Error("Unknown motion type: "+n)}_internalComputeMassProperties(e){const t=this._hknp.HP_Body_GetShape(e.hpBodyId);if(t[0]==this._hknp.Result.RESULT_OK){const e=this._hknp.HP_Shape_BuildMassProperties(t[1]);if(e[0]==this._hknp.Result.RESULT_OK)return e[1]}return[[0,0,0],1,[1,1,1],[0,0,0,1]]}computeMassProperties(e,t){const i=this._getPluginReference(e,t),n=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(n)}setMassProperties(e,t,i){this._applyToBodyOrInstances(e,(e=>{e.userMassProps=t,this._internalUpdateMassProperties(e)}),i)}getMassProperties(e,t){const i=this._getPluginReference(e,t),n=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(n)}setLinearDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearDamping(e.hpBodyId,t)}),i)}getLinearDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetLinearDamping(i.hpBodyId)[1]}setAngularDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularDamping(e.hpBodyId,t)}),i)}getAngularDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetAngularDamping(i.hpBodyId)[1]}setLinearVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getLinearVelocityToRef(e,t,i){const n=this._getPluginReference(e,i),s=this._hknp.HP_Body_GetLinearVelocity(n.hpBodyId)[1];this._v3ToBvecRef(s,t)}_applyToBodyOrInstances(e,t,i){var n;if((null===(n=e._pluginDataInstances)||void 0===n?void 0:n.length)>0&&void 0===i)for(let i=0;i<e._pluginDataInstances.length;i++)t(e._pluginDataInstances[i]);else t(this._getPluginReference(e,i))}applyImpulse(e,t,i,n){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_ApplyImpulse(e.hpBodyId,this._bVecToV3(i),this._bVecToV3(t))}),n)}applyForce(e,t,i,n){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,n)}setAngularVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getAngularVelocityToRef(e,t,i){const n=this._getPluginReference(e,i),s=this._hknp.HP_Body_GetAngularVelocity(n.hpBodyId)[1];this._v3ToBvecRef(s,t)}setPhysicsBodyTransformation(e,t){const i=e.transformNode;if(e.numInstances>0){const t=i._thinInstanceDataStorage.matrixData;if(!t)return;const n=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),t,0,n,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))}setGravityFactor(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetGravityFactor(e.hpBodyId,t)}),i)}getGravityFactor(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetGravityFactor(i.hpBodyId)[1]}disposeBody(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(const t of e._pluginDataInstances)this._hknp.HP_Body_Release(t.hpBodyId),t.hpBodyId=void 0;e._pluginData&&(this._hknp.HP_Body_Release(e._pluginData.hpBodyId),e._pluginData.hpBodyId=void 0)}initShape(e,t,i){switch(t){case v_.SPHERE:{const t=i.radius||1,n=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateSphere(n,t)[1]}break;case v_.BOX:{const t=i.rotation?this._bQuatToV4(i.rotation):[0,0,0,1],n=i.extents?this._bVecToV3(i.extents):[1,1,1],s=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateBox(s,t,n)[1]}break;case v_.CAPSULE:{const t=i.pointA?this._bVecToV3(i.pointA):[0,0,0],n=i.pointB?this._bVecToV3(i.pointB):[0,1,0],s=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCapsule(t,n,s)[1]}break;case v_.CONTAINER:e._pluginData=this._hknp.HP_Shape_CreateContainer()[1];break;case v_.CYLINDER:{const t=i.pointA?this._bVecToV3(i.pointA):[0,0,0],n=i.pointB?this._bVecToV3(i.pointB):[0,1,0],s=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCylinder(t,n,s)[1]}break;case v_.CONVEX_HULL:case v_.MESH:{const n=i.mesh;if(!n)throw new Error("No mesh provided to create physics shape.");{const s=!!i.includeChildMeshes,r=t!=v_.CONVEX_HULL,o=new X_(n,r,null==n?void 0:n.getScene());o.addMesh(n,s);const a=o.getVertices(this._hknp),l=a.length/3;if(t==v_.CONVEX_HULL)e._pluginData=this._hknp.HP_Shape_CreateConvexHull(a.byteOffset,l)[1];else{const t=o.getTriangles(this._hknp),i=t.length/3;e._pluginData=this._hknp.HP_Shape_CreateMesh(a.byteOffset,l,t.byteOffset,i)[1],o.freeBuffer(this._hknp,t)}o.freeBuffer(this._hknp,a)}}break;default:throw new Error("Unsupported Shape Type.")}}setShapeFilterMembershipMask(e,t){const i=this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][1];this._hknp.HP_Shape_SetFilterInfo(e._pluginData,[t,i])}getShapeFilterMembershipMask(e){return this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][0]}setShapeFilterCollideMask(e,t){const i=this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][0];this._hknp.HP_Shape_SetFilterInfo(e._pluginData,[i,t])}getShapeFilterCollideMask(e){return this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][1]}setMaterial(e,t){var i,n,s,r,o;const a=null!==(i=t.friction)&&void 0!==i?i:.5,l=null!==(n=t.staticFriction)&&void 0!==n?n:a,h=null!==(s=t.restitution)&&void 0!==s?s:0,c=null!==(r=t.frictionCombine)&&void 0!==r?r:b_.MINIMUM,u=null!==(o=t.restitutionCombine)&&void 0!==o?o:b_.MAXIMUM,d=[l,a,h,this._materialCombineToNative(c),this._materialCombineToNative(u)];this._hknp.HP_Shape_SetMaterial(e._pluginData,d)}setDensity(e,t){this._hknp.HP_Shape_SetDensity(e._pluginData,t)}getDensity(e){return this._hknp.HP_Shape_GetDensity(e._pluginData)[1]}_getTransformInfos(e){if(e.parent)return e.computeWorldMatrix(),[this._bVecToV3(e.absolutePosition),this._bQuatToV4(e.absoluteRotationQuaternion)];let t=o.jp.Quaternion[0];if(e.rotationQuaternion)t=e.rotationQuaternion;else{const i=e.rotation;o._f.FromEulerAnglesToRef(i.x,i.y,i.z,t)}return[this._bVecToV3(e.position),this._bQuatToV4(t)]}addChild(e,t,i,n,s){const r=[i?this._bVecToV3(i):[0,0,0],n?this._bQuatToV4(n):[0,0,0,1],s?this._bVecToV3(s):[1,1,1]];this._hknp.HP_Shape_AddChild(e._pluginData,t._pluginData,r)}removeChild(e,t){this._hknp.HP_Shape_RemoveChild(e._pluginData,t)}getNumChildren(e){return this._hknp.HP_Shape_GetNumChildren(e._pluginData)[1]}getBoundingBox(e){return{}}getBodyGeometry(e){var t;const i=(null===(t=e._pluginDataInstances)||void 0===t?void 0:t.length)>0?e._pluginDataInstances[0]:e._pluginData,n=this._hknp.HP_Body_GetShape(i.hpBodyId)[1],s=this._hknp.HP_Shape_CreateDebugDisplayGeometry(n);if(s[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};const r=this._hknp.HP_DebugGeometry_GetInfo(s[1])[1],o=new Float32Array(this._hknp.HEAPU8.buffer,r[0],3*r[1]),a=new Uint32Array(this._hknp.HEAPU8.buffer,r[2],3*r[3]),l=o.slice(0),h=a.slice(0);return this._hknp.HP_DebugGeometry_Release(s[1]),{positions:l,indices:h}}disposeShape(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0}initConstraint(e,t,i,n,s){var r,a,l,h;const c=e.type,u=e.options;if(!c||!u)return void _.Y.Warn("No constraint type or options. Constraint is invalid.");if(t._pluginDataInstances.length>0&&void 0===n||i._pluginDataInstances.length>0&&void 0===s)return void _.Y.Warn("Body is instanced but no instance index was specified. Constraint will not be applied.");const d=this._hknp.HP_Constraint_Create()[1];e._pluginData=d;const p=this._getPluginReference(t,n).hpBodyId,f=this._getPluginReference(i,s).hpBodyId;this._hknp.HP_Constraint_SetParentBody(d,p),this._hknp.HP_Constraint_SetChildBody(d,f);const m=u.pivotA?this._bVecToV3(u.pivotA):this._bVecToV3(o.P.Zero()),g=null!==(r=u.axisA)&&void 0!==r?r:new o.P(1,0,0),v=this._tmpVec3[0];null==g||g.getNormalToRef(v),this._hknp.HP_Constraint_SetAnchorInParent(d,m,this._bVecToV3(g),this._bVecToV3(v));const y=u.pivotB?this._bVecToV3(u.pivotB):this._bVecToV3(o.P.Zero()),x=null!==(a=u.axisB)&&void 0!==a?a:new o.P(1,0,0),b=this._tmpVec3[0];if(x.getNormalToRef(b),this._hknp.HP_Constraint_SetAnchorInChild(d,y,this._bVecToV3(x),this._bVecToV3(b)),c==g_.LOCK)this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(c==g_.DISTANCE){const e=u.maxDistance||0,t=this._hknp.ConstraintAxis.LINEAR_DISTANCE;this._hknp.HP_Constraint_SetAxisMode(d,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(d,t,e),this._hknp.HP_Constraint_SetAxisMaxLimit(d,t,e)}else if(c==g_.HINGE)this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(c==g_.PRISMATIC)this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(c==g_.SLIDER)this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(c==g_.BALL_AND_SOCKET)this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else{if(c!=g_.SIX_DOF)throw new Error("Unsupported Constraint Type.");{const t=e;for(const e of t.limits){const t=this._constraintAxisToNative(e.axis);0==(null!==(l=e.minLimit)&&void 0!==l?l:-1)&&0==(null!==(h=e.maxLimit)&&void 0!==h?h:-1)?this._hknp.HP_Constraint_SetAxisMode(d,t,this._hknp.ConstraintAxisLimitMode.LOCKED):(null!=e.minLimit&&(this._hknp.HP_Constraint_SetAxisMode(d,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(d,t,e.minLimit)),null!=e.maxLimit&&(this._hknp.HP_Constraint_SetAxisMode(d,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMaxLimit(d,t,e.maxLimit)))}}}const T=!!u.collision;this._hknp.HP_Constraint_SetCollisionsEnabled(d,T),this._hknp.HP_Constraint_SetEnabled(d,!0)}addConstraint(e,t,i,n,s){this.initConstraint(i,e,t,n,s)}setEnabled(e,t){this._hknp.HP_Constraint_SetEnabled(e._pluginData,t)}getEnabled(e){return this._hknp.HP_Constraint_GetEnabled(e._pluginData)[1]}setCollisionsEnabled(e,t){this._hknp.HP_Constraint_SetCollisionsEnabled(e._pluginData,t)}getCollisionsEnabled(e){return this._hknp.HP_Constraint_GetCollisionsEnabled(e._pluginData)[1]}setAxisFriction(e,t,i){this._hknp.HP_Constraint_SetAxisFriction(e._pluginData,this._constraintAxisToNative(t),i)}getAxisFriction(e,t){return this._hknp.HP_Constraint_GetAxisFriction(e._pluginData,this._constraintAxisToNative(t))[1]}setAxisMode(e,t,i){this._hknp.HP_Constraint_SetAxisMode(e._pluginData,this._constraintAxisToNative(t),this._limitModeToNative(i))}getAxisMode(e,t){const i=this._hknp.HP_Constraint_GetAxisMode(e._pluginData,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(i)}setAxisMinLimit(e,t,i){this._hknp.HP_Constraint_SetAxisMinLimit(e._pluginData,this._constraintAxisToNative(t),i)}getAxisMinLimit(e,t){return this._hknp.HP_Constraint_GetAxisMinLimit(e._pluginData,this._constraintAxisToNative(t))[1]}setAxisMaxLimit(e,t,i){this._hknp.HP_Constraint_SetAxisMaxLimit(e._pluginData,this._constraintAxisToNative(t),i)}getAxisMaxLimit(e,t){return this._hknp.HP_Constraint_GetAxisMaxLimit(e._pluginData,this._constraintAxisToNative(t))[1]}setAxisMotorType(e,t,i){this._hknp.HP_Constraint_SetAxisMotorType(e._pluginData,this._constraintAxisToNative(t),this._constraintMotorTypeToNative(i))}getAxisMotorType(e,t){return this._nativeToMotorType(this._hknp.HP_Constraint_GetAxisMotorType(e._pluginData,this._constraintAxisToNative(t))[1])}setAxisMotorTarget(e,t,i){this._hknp.HP_Constraint_SetAxisMotorTarget(e._pluginData,this._constraintAxisToNative(t),i)}getAxisMotorTarget(e,t){return this._hknp.HP_Constraint_GetAxisMotorTarget(e._pluginData,this._constraintAxisToNative(t))[1]}setAxisMotorMaxForce(e,t,i){this._hknp.HP_Constraint_SetAxisMotorMaxForce(e._pluginData,this._constraintAxisToNative(t),i)}getAxisMotorMaxForce(e,t){return this._hknp.HP_Constraint_GetAxisMotorMaxForce(e._pluginData,this._constraintAxisToNative(t))[1]}disposeConstraint(e){const t=e._pluginData;this._hknp.HP_Constraint_SetEnabled(t,!1),this._hknp.HP_Constraint_Release(t),e._pluginData=void 0}raycast(e,t,i){i.reset(e,t);const n=[this._bVecToV3(e),this._bVecToV3(t),[-1,-1]];if(this._hknp.HP_World_CastRayWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const e=this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector,0)[1],t=e[1][3],n=e[1][4];i.setHitData({x:n[0],y:n[1],z:n[2]},{x:t[0],y:t[1],z:t[2]}),i.calculateHitDistance();const s=this._bodies.get(e[1][0][0]);i.body=null==s?void 0:s.body,i.bodyIndex=null==s?void 0:s.index}}getCollisionObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionObservable.get(t);return i||(i=new r.y$,this._bodyCollisionObservable.set(t,i)),i}setCollisionCallbackEnabled(e,t){const i=this._hknp.EventType.COLLISION_STARTED.value|this._hknp.EventType.COLLISION_CONTINUED.value|this._hknp.EventType.COLLISION_FINISHED.value;e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t?i:0)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,t?i:0)}_notifyCollisions(){let e=this._hknp.HP_World_GetCollisionEvents(this.world)[1];const t=new q_,i=Number(this.world);for(;e;){q_.readToRef(this._hknp.HEAPU8.buffer,e,t),t.contactOnB.position.subtractToRef(t.contactOnA.position,this._tmpVec3[0]);const n=o.P.Dot(this._tmpVec3[0],t.contactOnA.normal),s=this._bodies.get(t.contactOnA.bodyId),r=this._bodies.get(t.contactOnB.bodyId),a={collider:s.body,colliderIndex:s.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,point:t.contactOnA.position,distance:n,impulse:t.impulseApplied,normal:t.contactOnA.normal};if(this.onCollisionObservable.notifyObservers(a),this._bodyCollisionObservable.size){const e=this._bodyCollisionObservable.get(t.contactOnA.bodyId),i=this._bodyCollisionObservable.get(t.contactOnB.bodyId);e?e.notifyObservers(a):i&&(a.collider=r.body,a.colliderIndex=r.index,a.collidedAgainst=s.body,a.collidedAgainstIndex=s.index,a.normal=t.contactOnB.normal,i.notifyObservers(a))}e=this._hknp.HP_World_GetNextCollisionEvent(i,e)}}get numBodies(){return this._hknp.HP_World_GetNumBodies(this.world)[1]}dispose(){this._hknp.HP_QueryCollector_Release(this._queryCollector),this._queryCollector=BigInt(0),this._hknp.HP_World_Release(this.world),this.world=void 0}_v3ToBvecRef(e,t){t.set(e[0],e[1],e[2])}_bVecToV3(e){return[e._x,e._y,e._z]}_bQuatToV4(e){return[e._x,e._y,e._z,e._w]}_constraintMotorTypeToNative(e){switch(e){case y_.POSITION:return this._hknp.ConstraintMotorType.POSITION;case y_.VELOCITY:return this._hknp.ConstraintMotorType.VELOCITY}return this._hknp.ConstraintMotorType.NONE}_nativeToMotorType(e){switch(e){case this._hknp.ConstraintMotorType.POSITION:return y_.POSITION;case this._hknp.ConstraintMotorType.VELOCITY:return y_.VELOCITY}return y_.NONE}_materialCombineToNative(e){switch(e){case b_.GEOMETRIC_MEAN:return this._hknp.MaterialCombine.GEOMETRIC_MEAN;case b_.MINIMUM:return this._hknp.MaterialCombine.MINIMUM;case b_.MAXIMUM:return this._hknp.MaterialCombine.MAXIMUM;case b_.ARITHMETIC_MEAN:return this._hknp.MaterialCombine.ARITHMETIC_MEAN;case b_.MULTIPLY:return this._hknp.MaterialCombine.MULTIPLY}}_constraintAxisToNative(e){switch(e){case m_.LINEAR_X:return this._hknp.ConstraintAxis.LINEAR_X;case m_.LINEAR_Y:return this._hknp.ConstraintAxis.LINEAR_Y;case m_.LINEAR_Z:return this._hknp.ConstraintAxis.LINEAR_Z;case m_.ANGULAR_X:return this._hknp.ConstraintAxis.ANGULAR_X;case m_.ANGULAR_Y:return this._hknp.ConstraintAxis.ANGULAR_Y;case m_.ANGULAR_Z:return this._hknp.ConstraintAxis.ANGULAR_Z;case m_.LINEAR_DISTANCE:return this._hknp.ConstraintAxis.LINEAR_DISTANCE}}_nativeToLimitMode(e){switch(e){case this._hknp.ConstraintAxisLimitMode.FREE:return __.FREE;case this._hknp.ConstraintAxisLimitMode.LIMITED:return __.LIMITED;case this._hknp.ConstraintAxisLimitMode.LOCKED:return __.LOCKED}return __.FREE}_limitModeToNative(e){switch(e){case __.FREE:return this._hknp.ConstraintAxisLimitMode.FREE;case __.LIMITED:return this._hknp.ConstraintAxisLimitMode.LIMITED;case __.LOCKED:return this._hknp.ConstraintAxisLimitMode.LOCKED}}}k.x.prototype.getPhysicsEngine=function(){return this._physicsEngine},k.x.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(ve.l.NAME_PHYSICSENGINE);i||(i=new $_(this),this._addComponent(i));try{if(t&&1!==(null==t?void 0:t.getPluginVersion())){if(2!==(null==t?void 0:t.getPluginVersion()))throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new C_(e,t)}else this._physicsEngine=new Lh.T(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return _.Y.Error(e.message),!1}},k.x.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},k.x.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},k.x.prototype.deleteCompoundImpostor=function(e){const t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},k.x.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){const t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class $_{constructor(e){this.name=ve.l.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new r.y$,this.scene.onAfterPhysicsObservable=new r.y$,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(yi.Y.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)}))))},enumerable:!0,configurable:!0}),yi.Y.prototype.getPhysicsBody=function(){return this.physicsBody},yi.Y.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this};class Q_{static GetContactPointToRef(e,t,i,n,s){const r=e.getScene().getPhysicsEngine(),o=null==r?void 0:r.getPluginVersion();if(1===o){const s=new Yt.z(t,i).intersectsMesh(e);if(s.hit&&s.pickedPoint)return n.copyFrom(s.pickedPoint),!0}else if(2===o)return e.physicsBody.getObjectCenterWorldToRef(n,s),!0;return!1}static HasAppliedForces(e,t){var i,n,s;return e.getMotionType(t)===x_.STATIC||0===(null!==(n=null===(i=e.getMassProperties(t))||void 0===i?void 0:i.mass)&&void 0!==n?n:0)||0===(null===(s=e.transformNode)||void 0===s?void 0:s.getTotalVertices())}static IsInsideCylinder(e,t,i,n){const s=o.jp.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=n}}class Z_{constructor(e){this._hitData={force:new o.P,contactPoint:new o.P,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine||_.Y.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.")}applyRadialExplosionImpulse(e,t,i,n){if(!this._physicsEngine)return _.Y.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let s=!1;if("number"==typeof t){const e=t;(t=new nm).radius=e,t.strength=null!=i?i:t.strength,t.falloff=null!=n?n:t.falloff}else s=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const r=new J_(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{r.getImpostorHitData(i,e,o)&&(i.applyImpulse(o.force,o.contactPoint),s&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),r.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(r,e,o,s,((e,t)=>{e.applyImpulse(t.force,t.contactPoint,t.instanceIndex)}));return r.dispose(!1),r}applyRadialExplosionForce(e,t,i,n){if(!this._physicsEngine)return _.Y.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let s=!1;if("number"==typeof t){const e=t;(t=new nm).radius=e,t.strength=null!=i?i:t.strength,t.falloff=null!=n?n:t.falloff}else s=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const r=new J_(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{r.getImpostorHitData(i,e,o)&&(i.applyForce(o.force,o.contactPoint),s&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),r.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(r,e,o,s,((e,t)=>{e.applyForce(t.force,t.contactPoint,t.instanceIndex)}));return r.dispose(!1),r}_applicationForBodies(e,t,i,n,s){const r=Array(),o=this._physicsEngine.getBodies();for(const a of o)a.iterateOverAllInstances(((o,a)=>{e.getBodyHitData(o,t,i,a)&&(s(o,i),n&&r.push({body:o,hitData:this._copyPhysicsHitData(i)}))}));e.triggerAffectedBodiesCallback(r)}gravitationalField(e,t,i,n){if(!this._physicsEngine)return _.Y.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new nm).radius=e,t.strength=null!=i?i:t.strength,t.falloff=null!=n?n:t.falloff}const s=new em(this,this._scene,e,t);return s.dispose(!1),s}updraft(e,t,i,n,s){if(!this._physicsEngine)return _.Y.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new sm).radius=e,t.strength=null!=i?i:t.strength,t.height=null!=n?n:t.height,t.updraftMode=null!=s?s:t.updraftMode}const r=new tm(this._scene,e,t);return r.dispose(!1),r}vortex(e,t,i,n){if(!this._physicsEngine)return _.Y.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new rm).radius=e,t.strength=null!=i?i:t.strength,t.height=null!=n?n:t.height}const s=new im(this._scene,e,t);return s.dispose(!1),s}_copyPhysicsHitData(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}}}class J_{constructor(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options={...new nm,...this._options}}getData(){return this._dataFetched=!0,{sphere:this._sphere}}_getHitData(e,t,i,n){const s=o.jp.Vector3[0];s.copyFrom(t).subtractInPlace(i);const r=o.jp.Vector3[1];if(!Q_.GetContactPointToRef(e,i,s,r,n.instanceIndex))return!1;const a=o.P.Distance(i,r);if(a>this._options.radius)return!1;const l=this._options.falloff===T_.Constant?this._options.strength:this._options.strength*(1-a/this._options.radius);return s.scaleInPlace(l),n.force.copyFrom(s),n.contactPoint.copyFrom(r),n.distanceFromOrigin=a,!0}getBodyHitData(e,t,i,n){if(Q_.HasAppliedForces(e,n))return!1;const s=e.transformNode,r=e.getObjectCenterWorld(n);return i.instanceIndex=n,this._getHitData(s,r,t,i)}getImpostorHitData(e,t,i){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const n=e.object;if(!this._intersectsWithSphere(n,t,this._options.radius))return!1;const s=e.getObjectCenter();return this._getHitData(n,s,t,i),!0}triggerAffectedImpostorsCallback(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)}triggerAffectedBodiesCallback(e){this._options.affectedBodiesCallback&&this._options.affectedBodiesCallback(e)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_prepareSphere(){this._sphere||(this._sphere=Kn("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)}_intersectsWithSphere(e,t,i){return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling.setAll(2*i),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(e,!0)}}class em{constructor(e,t,i,n){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=n,this._dataFetched=!1,this._options={...new nm,...this._options},this._tickCallback=this._tick.bind(this),this._options.strength=-1*this._options.strength}getData(){return this._dataFetched=!0,{sphere:this._sphere}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_tick(){var e;if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{const t=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);t&&(this._sphere=null===(e=t.getData().sphere)||void 0===e?void 0:e.clone("radialExplosionEventSphereClone"))}}}class tm{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=o.P.Zero(),this._originDirection=o.P.Zero(),this._cylinderPosition=o.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new sm,...this._options},this._origin.addToRef(new o.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new o.P(0,this._options.height,0),this._originTop),this._options.updraftMode===S_.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=this._tick.bind(this),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)}),0))}_getHitData(e,t){let i;i=this._options.updraftMode===S_.Perpendicular?this._originDirection:e.subtract(this._originTop);const n=o.P.Distance(this._origin,e),s=-1*this._options.strength,r=i.multiplyByFloats(s,s,s);t.force.copyFrom(r),t.contactPoint.copyFrom(e),t.distanceFromOrigin=n}_getBodyHitData(e,t,i){if(Q_.HasAppliedForces(e))return!1;const n=e.getObjectCenterWorld(i);return!!Q_.IsInsideCylinder(n,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(n,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const n=e.getObjectCenter();return this._getHitData(n,t),!0}_tick(){const e=tm._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=an("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}tm._HitData={force:new o.P,contactPoint:new o.P,distanceFromOrigin:0};class im{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=o.P.Zero(),this._cylinderPosition=o.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new rm,...this._options},this._origin.addToRef(new o.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new o.P(0,this._options.height,0),this._originTop),this._tickCallback=this._tick.bind(this),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout((()=>{this._dataFetched||this._cylinder.dispose()}),0))}_getHitData(e,t,i){const n=im.originOnPlane;n.set(this._origin.x,t.y,this._origin.z);const s=o.jp.Vector3[0];t.subtractToRef(n,s);const r=o.jp.Vector3[1];if(!Q_.GetContactPointToRef(e,n,s,r,i.instanceIndex))return!1;const a=o.P.Distance(r,n)/this._options.radius,l=o.jp.Vector3[2];let h,c,u;if(r.normalizeToRef(l),a>this._options.centripetalForceThreshold&&l.negateInPlace(),a>this._options.centripetalForceThreshold)h=l.x*this._options.centripetalForceMultiplier,c=l.y*this._options.updraftForceMultiplier,u=l.z*this._options.centripetalForceMultiplier;else{const e=o.P.Cross(n,t).normalize();h=(e.x+l.x)*this._options.centrifugalForceMultiplier,c=this._originTop.y*this._options.updraftForceMultiplier,u=(e.z+l.z)*this._options.centrifugalForceMultiplier}const d=o.jp.Vector3[3];return d.set(h,c,u),d.scaleInPlace(this._options.strength),i.force.copyFrom(d),i.contactPoint.copyFrom(t),i.distanceFromOrigin=a,!0}_getBodyHitData(e,t,i){if(Q_.HasAppliedForces(e,i))return!1;const n=e.transformNode,s=e.getObjectCenterWorld(i);return!!Q_.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(n,s,t))}_getImpostorHitData(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const n=e.getObjectCenter();return this._getHitData(i,n,t),!0}_tick(){const e=im.hitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=an("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}im.originOnPlane=o.P.Zero(),im.hitData={force:new o.P,contactPoint:new o.P,distanceFromOrigin:0};class nm{constructor(){this.radius=5,this.strength=10,this.falloff=T_.Constant,this.sphere={segments:32,diameter:1}}}class sm{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=S_.Center}}class rm{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(T_||(T_={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(S_||(S_={}));si.v.ShadersStore.blackAndWhitePixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}";class om extends ni.D{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,n,s,r){super(e,"blackAndWhite",["degree"],null,t,i,n,s,r),this.degree=1,this.onApplyObservable.add((e=>{e.setFloat("degree",this.degree)}))}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new om(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,be.gn)([(0,Te.qC)()],om.prototype,"degree",void 0),(0,l.H)("BABYLON.BlackAndWhitePostProcess",om);class am{constructor(e,t,i,n){this._name=t,this._singleInstance=n||!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 e=0;e<t.length;e++)if(!t[e].isSupported)return!1}return!0}_update(){}_attachCameras(e){let t;const i=de.w1.MakeArray(e||this._cameras);if(i)for(let e=0;e<i.length;e++){const n=i[e];if(!n)continue;const s=n.name;if(t=this._singleInstance?0:s,!this._postProcesses[t]){const e=this._getPostProcesses();e&&(this._postProcesses[t]=Array.isArray(e)?e:[e])}this._indicesForCamera[s]||(this._indicesForCamera[s]=[]),this._postProcesses[t].forEach((e=>{const t=n.attachPostProcess(e);this._indicesForCamera[s].push(t)})),this._cameras[s]||(this._cameras[s]=n)}}_detachCameras(e){const t=de.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){const i=t[e],n=i.name,s=this._postProcesses[this._singleInstance?0:n];s&&s.forEach((e=>{i.detachPostProcess(e)})),this._cameras[n]&&(this._cameras[n]=null)}}_enable(e){const t=de.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){const i=t[e],n=i.name;for(let s=0;s<this._indicesForCamera[n].length;s++)void 0!==i._postProcesses[this._indicesForCamera[n][s]]&&null!==i._postProcesses[this._indicesForCamera[n][s]]||this._postProcesses[this._singleInstance?0:n].forEach((i=>{t[e].attachPostProcess(i,this._indicesForCamera[n][s])}))}}_disable(e){const t=de.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){const i=t[e],n=i.name;this._postProcesses[this._singleInstance?0:n].forEach((e=>{i.detachPostProcess(e)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}si.v.ShadersStore.extractHighlightsPixelShader="#include<helperFunctions>\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}";class lm extends ni.D{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,n,s,r,o=0,a=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,n,s,r,null,o,void 0,null,a),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,Me.zp)),e.setFloat("exposure",this._exposure)}))}}(0,be.gn)([(0,Te.qC)()],lm.prototype,"threshold",void 0),(0,l.H)("BABYLON.ExtractHighlightsPostProcess",lm);si.v.ShadersStore.bloomMergePixelShader="uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n";class hm extends ni.D{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,n,s,r,o,a,l,h=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,r,o,a,l,null,h,void 0,null,!0),this.weight=1,this.weight=n,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)})),c||this.updateEffect()}}(0,be.gn)([(0,Te.qC)()],hm.prototype,"weight",void 0),(0,l.H)("BABYLON.BloomMergePostProcess",hm);class cm extends am{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,n,s=0,r=!1){super(e.getEngine(),"bloom",(()=>this._effects),!0),this._bloomScale=t,this._effects=[],this._downscale=new lm("highlights",1,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,r),this._blurX=new wa("horizontal blur",new o.FM(1,0),10,t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,r),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new wa("vertical blur",new o.FM(0,1),10,t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,r),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=n,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new hm("bloomMerge",this._downscale,this._blurY,i,t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,r),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){for(let e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0}}si.v.ShadersStore.chromaticAberrationPixelShader="uniform sampler2D textureSampler; \nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\nvarying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x==0. && directionOfEffect.y==0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}";class um extends ni.D{getClassName(){return"ChromaticAberrationPostProcess"}constructor(e,t,i,n,s,r,a,l,h=0,c=!1){super(e,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],n,s,r,a,l,null,h,void 0,null,c),this.aberrationAmount=30,this.radialIntensity=0,this.direction=new o.FM(.707,.707),this.centerPosition=new o.FM(.5,.5),this.screenWidth=t,this.screenHeight=i,this.onApplyObservable.add((e=>{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new um(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,n)}}(0,be.gn)([(0,Te.qC)()],um.prototype,"aberrationAmount",void 0),(0,be.gn)([(0,Te.qC)()],um.prototype,"radialIntensity",void 0),(0,be.gn)([(0,Te.qC)()],um.prototype,"direction",void 0),(0,be.gn)([(0,Te.qC)()],um.prototype,"centerPosition",void 0),(0,be.gn)([(0,Te.qC)()],um.prototype,"screenWidth",void 0),(0,be.gn)([(0,Te.qC)()],um.prototype,"screenHeight",void 0),(0,l.H)("BABYLON.ChromaticAberrationPostProcess",um);si.v.ShadersStore.circleOfConfusionPixelShader="uniform sampler2D depthSampler;\nvarying vec2 vUV;\nuniform vec2 cameraMinMaxZ;\nuniform float focusDistance;\nuniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,coc,coc,1.0);\n}\n";class dm extends ni.D{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,n,s,r,o,a=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,n,s,r,o,null,a,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{if(!this._depthTexture)return void _.Y.Warn("No depth texture set on CircleOfConfusionPostProcess");e.setTexture("depthSampler",this._depthTexture);const t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);const i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}))}set depthTexture(e){this._depthTexture=e}}(0,be.gn)([(0,Te.qC)()],dm.prototype,"lensSize",void 0),(0,be.gn)([(0,Te.qC)()],dm.prototype,"fStop",void 0),(0,be.gn)([(0,Te.qC)()],dm.prototype,"focusDistance",void 0),(0,be.gn)([(0,Te.qC)()],dm.prototype,"focalLength",void 0),(0,l.H)("BABYLON.CircleOfConfusionPostProcess",dm);si.v.ShadersStore.colorCorrectionPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;\nconst float SLICE_COUNT=16.0; \nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}";class pm extends ni.D{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,n,s,r,o){super(e,"colorCorrection",null,["colorTable"],i,n,s,r,o);const a=(null==n?void 0:n.getScene())||null;this._colorTableTexture=new Ce.x(t,a,!0,!1,Ce.x.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=Ce.x.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new pm(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,be.gn)([(0,Te.qC)()],pm.prototype,"colorTableUrl",void 0),(0,l.H)("BABYLON.ColorCorrectionPostProcess",pm);si.v.ShadersStore.convolutionPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}";class fm extends ni.D{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,n,s,r,o,a=0){super(e,"convolution",["kernel","screenSize"],null,i,n,s,r,o,null,a),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new fm(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType)),e,i,n)}}fm.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],fm.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],fm.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],fm.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],fm.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],fm.GaussianKernel=[0,1,0,1,1,1,0,1,0],(0,be.gn)([(0,Te.qC)()],fm.prototype,"kernel",void 0),(0,l.H)("BABYLON.ConvolutionPostProcess",fm);class _m extends wa{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,n,s,r,o,a=null,l=Ce.x.BILINEAR_SAMPLINGMODE,h,c,u=0,d=!1,p=5){super(e,i,n,s,r,2,h,c,u,"#define DOF 1\r\n",d,p),this.direction=i,this.externalTextureSamplerBinding=!!a,this.onApplyObservable.add((e=>{null!=a&&e.setTextureFromPostProcess("textureSampler",a),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)}))}}(0,be.gn)([(0,Te.qC)()],_m.prototype,"direction",void 0),(0,l.H)("BABYLON.DepthOfFieldBlurPostProcess",_m);si.v.ShadersStore.depthOfFieldMergePixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\nvec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n";class mm extends ni.D{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,n,s,r,o,a,l,h=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,r,o,a,l,null,h,void 0,null,!0),this._blurSteps=n,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),n.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(n.length-i-1),t)}))})),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,n,s,r){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,n,s,r)}}var gm;!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(gm||(gm={}));class vm extends am{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=gm.Low,n=0,s=!1){super(e.getEngine(),"depth of field",(()=>this._effects),!0),this._effects=[];const r=e.getEngine(),a=r.isWebGPU||r.webGLVersion>1?6:5;this._circleOfConfusion=new dm("circleOfConfusion",t,1,null,Ce.x.BILINEAR_SAMPLINGMODE,r,!1,n,s),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let l=1,h=15;switch(i){case gm.High:l=3,h=51;break;case gm.Medium:l=2,h=31;break;default:h=15,l=1}const c=h/Math.pow(2,l-1);let u=1;for(let t=0;t<l;t++){const i=new _m("vertical blur",e,new o.FM(0,1),c,u,null,this._circleOfConfusion,0==t?this._circleOfConfusion:null,Ce.x.BILINEAR_SAMPLINGMODE,r,!1,n,s,0==t?a:5);i.autoClear=!1,u=.75/Math.pow(2,t);const l=new _m("horizontal blur",e,new o.FM(1,0),c,u,null,this._circleOfConfusion,null,Ce.x.BILINEAR_SAMPLINGMODE,r,!1,n,s);l.autoClear=!1,this._depthOfFieldBlurY.push(i),this._depthOfFieldBlurX.push(l)}this._effects=[this._circleOfConfusion];for(let e=0;e<this._depthOfFieldBlurX.length;e++)this._effects.push(this._depthOfFieldBlurY[e]),this._effects.push(this._depthOfFieldBlurX[e]);this._dofMerge=new mm("dofMerge",this._circleOfConfusion,this._circleOfConfusion,this._depthOfFieldBlurX,u,null,Ce.x.BILINEAR_SAMPLINGMODE,r,!1,n,s),this._dofMerge.autoClear=!1,this._effects.push(this._dofMerge)}getClassName(){return"DepthOfFieldEffect"}set depthTexture(e){this._circleOfConfusion.depthTexture=e}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){for(let e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0}}si.v.ShadersStore.displayPassPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}";class ym extends ni.D{getClassName(){return"DisplayPassPostProcess"}constructor(e,t,i,n,s,r){super(e,"displayPass",["passSampler"],["passSampler"],t,i,n,s,r)}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new ym(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,l.H)("BABYLON.DisplayPassPostProcess",ym);si.v.ShadersStore.filterPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}";class xm extends ni.D{getClassName(){return"FilterPostProcess"}constructor(e,t,i,n,s,r,o){super(e,"filter",["kernelMatrix"],null,i,n,s,r,o),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new xm(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,be.gn)([(0,Te.oQ)()],xm.prototype,"kernelMatrix",void 0),(0,l.H)("BABYLON.FilterPostProcess",xm);si.v.ShadersStore.fxaaPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);\n#endif\n}";si.v.ShadersStore.fxaaVertexShader="attribute vec2 position;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class bm extends ni.D{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,n,s,r,o=0){super(e,"fxaa",["texelSize"],null,t,i,n||Ce.x.BILINEAR_SAMPLINGMODE,s,r,null,o,"fxaa",void 0,!0);const a=this._getDefines();this.updateEffect(a),this.onApplyObservable.add((e=>{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.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\n":null}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new bm(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,l.H)("BABYLON.FxaaPostProcess",bm);si.v.ShadersStore.grainPixelShader="#include<helperFunctions>\nuniform sampler2D textureSampler; \nuniform float intensity;\nuniform float animatedSeed;\nvarying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}";class Tm extends ni.D{getClassName(){return"GrainPostProcess"}constructor(e,t,i,n,s,r,o=0,a=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,n,s,r,null,o,void 0,null,a),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new Tm(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,be.gn)([(0,Te.qC)()],Tm.prototype,"intensity",void 0),(0,be.gn)([(0,Te.qC)()],Tm.prototype,"animated",void 0),(0,l.H)("BABYLON.GrainPostProcess",Tm);si.v.ShadersStore.highlightsPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}";class Sm extends ni.D{getClassName(){return"HighlightsPostProcess"}constructor(e,t,i,n,s,r,o=0){super(e,"highlights",null,null,t,i,n,s,r,null,o)}}si.v.IncludesShadersStore.mrtFragmentDeclaration="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";si.v.ShadersStore.geometryPixelShader="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;\nvarying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT]\n#include<bumpFragmentMainFunctions>\n#include<bumpFragmentFunctions>\n#include<helperFunctions>\nvoid main() {\n#include<clipPlaneFragment>\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include<bumpFragment>\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef PREPASS\n#ifdef PREPASS_DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#else\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\ngl_FragData[1]=vec4(normalOutput,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=abs(a-b);\nvelocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;\ngl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;\nfloat roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;\nroughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;\nvec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);\nreflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";si.v.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;\nuniform mat4 view;";si.v.IncludesShadersStore.geometryUboDeclaration="#include<sceneUboDeclaration>\n",i(6255);si.v.ShadersStore.geometryVertexShader="precision highp float;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<instancesDeclaration>\n#include<__decl__geometryVertex>\n#include<clipPlaneVertexDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;\nvarying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;\nuniform mat4 albedoMatrix;\nvarying vec2 vReflectivityUV;\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousViewProjection;\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\nvec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;\nvNormalW=normalUpdated;\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\nvViewPos=view*worldPos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;\npreviousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include<clipPlaneVertex>\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include<bumpVertex>\n}\n";const Em=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,Ga.qx)(Em);class Cm{_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===Cm.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===Cm.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===Cm.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===Cm.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===Cm.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 Cm.POSITION_TEXTURE_TYPE:return this._positionIndex;case Cm.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case Cm.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;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 this._ratio}constructor(e,t=1,i=15){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new a.HE(0,0,0,0),this._clearDepthColor=new a.HE(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._ratio=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,Cm._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const n=[],s=[qe.o.PositionKind,qe.o.NormalKind],r=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(n.push("#define ALPHATEST"),n.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&Va.k.BumpTextureEnabled&&(n.push("#define BUMP"),n.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(n.push("#define ORMTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),n.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(n.push("#define METALLIC"),n.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(n.push("#define ROUGHNESS"),n.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(n.push("#define ALBEDOTEXTURE"),n.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&n.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&n.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(n.push("#define SPECULARGLOSSINESSTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&n.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&n.push("#define GLOSSINESSS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(n.push("#define ORMTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),n.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(n.push("#define METALLIC"),n.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(n.push("#define ROUGHNESS"),n.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(n.push("#define ALBEDOTEXTURE"),n.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&n.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&n.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(n.push("#define SPECULARGLOSSINESSTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&n.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&n.push("#define GLOSSINESSS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(n.push("#define REFLECTIVITYTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&n.push("#define REFLECTIVITYCOLOR"))}e&&(n.push("#define NEED_UV"),r.isVerticesDataPresent(qe.o.UVKind)&&(s.push(qe.o.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(qe.o.UV2Kind)&&(s.push(qe.o.UV2Kind),n.push("#define UV2")))}this._linkedWithPrePass&&(n.push("#define PREPASS"),-1!==this._depthIndex&&(n.push("#define DEPTH_INDEX "+this._depthIndex),n.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(n.push("#define NORMAL_INDEX "+this._normalIndex),n.push("#define PREPASS_NORMAL"))),this._enablePosition&&(n.push("#define POSITION"),n.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(n.push("#define VELOCITY"),n.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(r)&&n.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(n.push("#define REFLECTIVITY"),n.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),r.useBones&&r.computeBonesUsingShaders?(s.push(qe.o.MatricesIndicesKind),s.push(qe.o.MatricesWeightsKind),r.numBoneInfluencers>4&&(s.push(qe.o.MatricesIndicesExtraKind),s.push(qe.o.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0");const o=r.morphTargetManager;let a=0;o&&o.numInfluencers>0&&(a=o.numInfluencers,n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+a),o.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),La.G.PrepareAttributesForMorphTargetsInfluencers(s,r,a)),t&&(n.push("#define INSTANCES"),La.G.PushAttributesForInstances(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this._linkedWithPrePass?n.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):n.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),(0,Ga.lK)(i,this._scene,n);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,u=n.join("\n");return c!==u&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:Em,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets"],defines:u,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:a}},l),u),h.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 n=0;if(e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?n=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(n=2),this._multiRenderTarget=new Xc("gBuffer",{width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio},t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:n,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const s=[!0],r=[!1],a=[!0];for(let e=1;e<t;++e)s.push(!0),a.push(!1),r.push(!0);const l=e.buildTextureLayout(s),h=e.buildTextureLayout(r),c=e.buildTextureLayout(a);this._multiRenderTarget.onClearObservable.add((e=>{e.bindAttachments(this.useSpecificClearForDepthTexture?h:l),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(c),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(l)})),this._resizeObserver=e.onResizeObservable.add((()=>{this._multiRenderTarget&&this._multiRenderTarget.resize({width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio})}));const u=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),n=this._scene,s=n.getEngine(),r=e.getMaterial();if(!r)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:o.y3.Identity(),viewProjection:n.getTransformMatrix()},t.skeleton)){const e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}const a=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(a.mustReturn)return;const l=s.getCaps().instancedArrays&&(null!==a.visibleInstances[e._id]||t.hasThinInstances),h=i.getWorldMatrix();if(this.isReady(e,l)){const o=e._getDrawWrapper();if(!o)return;const c=o.effect;let u;s.enableEffect(o),l||t._bind(e,c,r.fillMode),this._useUbo?(La.G.BindSceneUniformBuffer(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",n.getTransformMatrix()),c.setMatrix("view",n.getViewMatrix()));const d=t._instanceDataStorage;if(d.isFrozen||!r.backFaceCulling&&null===t.overrideMaterialSideOrientation)u=d.sideOrientation;else{const e=i._getWorldMatrixDeterminant();u=t.overrideMaterialSideOrientation,null===u&&(u=r.sideOrientation),e<0&&(u=u===cs.F.ClockWiseSideOrientation?cs.F.CounterClockWiseSideOrientation:cs.F.ClockWiseSideOrientation)}if(r._preBind(o,u),r.needAlphaTesting()){const e=r.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}r.bumpTexture&&n.getEngine().getCaps().standardDerivatives&&Va.k.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",r.bumpTexture.coordinatesIndex,1/r.bumpTexture.level,r.parallaxScaleBias),c.setMatrix("bumpMatrix",r.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",r.bumpTexture),c.setFloat2("vTangentSpaceParams",r.invertNormalMapX?-1:1,r.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===r.getClassName()?(null!==r.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",r.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",r.metallicRoughnessTexture.getTextureMatrix())),null!==r.metallic&&c.setFloat("metallic",r.metallic),null!==r.roughness&&c.setFloat("glossiness",1-r.roughness),null!==r.baseTexture&&(c.setTexture("albedoSampler",r.baseTexture),c.setMatrix("albedoMatrix",r.baseTexture.getTextureMatrix())),null!==r.baseColor&&c.setColor3("albedoColor",r.baseColor)):"PBRSpecularGlossinessMaterial"===r.getClassName()?(null!==r.specularGlossinessTexture?(c.setTexture("reflectivitySampler",r.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",r.specularGlossinessTexture.getTextureMatrix())):null!==r.specularColor&&c.setColor3("reflectivityColor",r.specularColor),null!==r.glossiness&&c.setFloat("glossiness",r.glossiness)):"PBRMaterial"===r.getClassName()?(null!==r.metallicTexture&&(c.setTexture("reflectivitySampler",r.metallicTexture),c.setMatrix("reflectivityMatrix",r.metallicTexture.getTextureMatrix())),null!==r.metallic&&c.setFloat("metallic",r.metallic),null!==r.roughness&&c.setFloat("glossiness",1-r.roughness),null!==r.roughness||null!==r.metallic||null!==r.metallicTexture?(null!==r.albedoTexture&&(c.setTexture("albedoSampler",r.albedoTexture),c.setMatrix("albedoMatrix",r.albedoTexture.getTextureMatrix())),null!==r.albedoColor&&c.setColor3("albedoColor",r.albedoColor)):(null!==r.reflectivityTexture?(c.setTexture("reflectivitySampler",r.reflectivityTexture),c.setMatrix("reflectivityMatrix",r.reflectivityTexture.getTextureMatrix())):null!==r.reflectivityColor&&c.setColor3("reflectivityColor",r.reflectivityColor),null!==r.microSurface&&c.setFloat("glossiness",r.microSurface))):"StandardMaterial"===r.getClassName()&&(null!==r.specularTexture&&(c.setTexture("reflectivitySampler",r.specularTexture),c.setMatrix("reflectivityMatrix",r.specularTexture.getTextureMatrix())),null!==r.specularColor&&c.setColor3("reflectivityColor",r.specularColor))),(0,Ga.an)(c,r,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&(c.setMatrices("mBones",t.skeleton.getTransformMatrices(t)),this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])),La.G.BindMorphTargetParameters(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),l&&t.hasThinInstances&&c.setMatrix("world",h),t._processRendering(i,e,c,r.fillMode,a,l,((e,t)=>{e||c.setMatrix("world",t)}))}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=h.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,n)=>{if((n||0===i)&&t.subMeshes)for(let i=0;i<t.subMeshes.length;++i){const n=t.subMeshes[i],s=n.getMaterial(),r=n.getRenderingMesh();if(!s)continue;const o=r._getInstancesRenderList(n._id,!!n.getReplacementMesh()),a=e.getCaps().instancedArrays&&(null!==o.visibleInstances[n._id]||r.hasThinInstances);if(!this.isReady(n,a))return!1}return!0},this._multiRenderTarget.customRenderFunction=(t,i,n,s)=>{let r;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),r=0;r<s.length;r++)u(s.data[r]);e.setColorWrite(!0)}for(r=0;r<t.length;r++)u(t.data[r]);for(e.setDepthWrite(!1),r=0;r<i.length;r++)u(i.data[r]);if(this.renderTransparentMeshes)for(r=0;r<n.length;r++)u(n.data[r]);e.setDepthWrite(!0)}}_copyBonesTransformationMatrices(e,t){for(let i=0;i<e.length;i++)t[i]=e[i];return t}}Cm.DEPTH_TEXTURE_TYPE=0,Cm.NORMAL_TEXTURE_TYPE=1,Cm.POSITION_TEXTURE_TYPE=2,Cm.VELOCITY_TEXTURE_TYPE=3,Cm.REFLECTIVITY_TEXTURE_TYPE=4,Cm._SceneComponentInitialization=e=>{throw(0,Zl.S)("GeometryBufferRendererSceneComponent")};class Am{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(k.x.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),k.x.prototype.enableGeometryBufferRenderer=function(e=1,t=15){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new Cm(this,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},k.x.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class Pm{constructor(e){this.name=ve.l.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ve.l.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}Cm._SceneComponentInitialization=e=>{let t=e._getComponent(ve.l.NAME_GEOMETRYBUFFERRENDERER);t||(t=new Pm(e),e._addComponent(t))};si.v.ShadersStore.motionBlurPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float motionStrength;\nuniform float motionScale;\nuniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 texelSize=1.0/screenSize;\nvec4 velocityColor=texture2D(velocitySampler,vUV);\nvelocityColor.rg=velocityColor.rg*2.0-vec2(1.0);\nvec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;\nvelocity*=motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint samplesCount=int(clamp(speed,1.0,SAMPLES));\nvelocity=normalize(velocity)*texelSize;\nfloat hlim=float(-samplesCount)*0.5+0.5;\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(SAMPLES); ++i)\n{\nif (i>=samplesCount)\nbreak;\nvec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);\ngl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\ndepth=projection[2].z+projection[3].z/depth; \nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=inverseViewProjection*cpos;\ncpos/=cpos.w;\nvec4 ppos=prevViewProjection*cpos;\nppos/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";class Rm extends ni.D{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,n,s,r,o,a=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,n,s,r,o,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",a,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=!0)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new Am)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}const i=t.indexOf(e);-1!==i&&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 _.Y.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();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=o.y3.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 o.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(Cm.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=o.jp.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 o.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(Cm.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_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("\n"))}}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new Rm(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,n)}}(0,be.gn)([(0,Te.qC)()],Rm.prototype,"motionStrength",void 0),(0,be.gn)([(0,Te.qC)()],Rm.prototype,"motionBlurSamples",null),(0,be.gn)([(0,Te.qC)()],Rm.prototype,"isObjectBased",null),(0,l.H)("BABYLON.MotionBlurPostProcess",Rm);si.v.ShadersStore.refractionPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}";class Mm extends ni.D{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,n,s,r,o,a,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],r,o,a,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=n,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add((e=>{this._refTexture=this._refTexture||new Ce.x(t,e.getScene())})),this.onApplyObservable.add((e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)}))}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new Mm(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,be.gn)([(0,Te.qC)()],Mm.prototype,"color",void 0),(0,be.gn)([(0,Te.qC)()],Mm.prototype,"depth",void 0),(0,be.gn)([(0,Te.qC)()],Mm.prototype,"colorLevel",void 0),(0,be.gn)([(0,Te.qC)()],Mm.prototype,"refractionTextureUrl",void 0),(0,l.H)("BABYLON.RefractionPostProcess",Mm);si.v.ShadersStore.sharpenPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}";class Im extends ni.D{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,n,s,r,o=0,a=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,n,s,r,null,o,void 0,null,a),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new Im(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,n)}}(0,be.gn)([(0,Te.qC)()],Im.prototype,"colorAmount",void 0),(0,be.gn)([(0,Te.qC)()],Im.prototype,"edgeAmount",void 0),(0,l.H)("BABYLON.SharpenPostProcess",Im);class Dm{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(de.w1.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(de.w1.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=de.w1.MakeArray(e||this._cameras);if(!i)return;const n=[];let s;for(s=0;s<i.length;s++){const e=i[s];e&&(-1===this._cameras.indexOf(e)?this._cameras.push(e):t&&n.push(s))}for(s=0;s<n.length;s++)i.splice(n[s],1);for(const e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._attachCameras(i)}_detachCameras(e){const t=de.w1.MakeArray(e||this._cameras);if(t){for(const e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._detachCameras(t);for(let e=0;e<t.length;e++)this._cameras.splice(this._cameras.indexOf(t[e]),1)}}_update(){for(const e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._update();for(let e=0;e<this._cameras.length;e++){if(!this._cameras[e])continue;const t=this._cameras[e].name;this._renderEffectsForIsolatedPass[t]&&this._renderEffectsForIsolatedPass[t]._update()}}_reset(){this._renderEffects={},this._renderEffectsForIsolatedPass=new Array}_enableMSAAOnFirstPostProcess(e){if(!this._engine._features.supportMSAA)return!1;const t=Object.keys(this._renderEffects);if(t.length>0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}setPrePassRenderer(e){return!1}dispose(){}}(0,be.gn)([(0,Te.qC)()],Dm.prototype,"_name",void 0);class Om{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 n=this._renderPipelines[e];n&&n._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const n=this._renderPipelines[e];n&&n._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const n=this._renderPipelines[e];n&&n._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(k.x.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(ve.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new wm(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new Om}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class wm{constructor(e){this.name=ve.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ve.l.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 Nm extends Dm{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 cm(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;t<this._cameras.length;t++)e.disposeEffects(this._cameras[t])}get depthOfFieldEnabled(){return this._depthOfFieldEnabled}set depthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get depthOfFieldBlurLevel(){return this._depthOfFieldBlurLevel}set depthOfFieldBlurLevel(e){if(this._depthOfFieldBlurLevel===e)return;this._depthOfFieldBlurLevel=e;const t=this.depthOfField;this.depthOfField=new vm(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!1),this.depthOfField.focalLength=t.focalLength,this.depthOfField.focusDistance=t.focusDistance,this.depthOfField.fStop=t.fStop,this.depthOfField.lensSize=t.lensSize;for(let e=0;e<this._cameras.length;e++)t.disposeEffects(this._cameras[e]);this._buildPipeline()}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}set imageProcessingEnabled(e){this._imageProcessingEnabled!==e&&(this._scene.imageProcessingConfiguration.isEnabled=e)}get imageProcessingEnabled(){return this._imageProcessingEnabled}set glowLayerEnabled(e){e&&!this._glowLayer?this._glowLayer=new th("",this._scene):!e&&this._glowLayer&&(this._glowLayer.dispose(),this._glowLayer=null)}get glowLayerEnabled(){return null!=this._glowLayer}get glowLayer(){return this._glowLayer}set chromaticAberrationEnabled(e){this._chromaticAberrationEnabled!==e&&(this._chromaticAberrationEnabled=e,this._buildPipeline())}get chromaticAberrationEnabled(){return this._chromaticAberrationEnabled}set grainEnabled(e){this._grainEnabled!==e&&(this._grainEnabled=e,this._buildPipeline())}get grainEnabled(){return this._grainEnabled}constructor(e="",t=!0,i=A.l.LastCreatedScene,n,s=!0){super(i.getEngine(),e),this._camerasToBeAttached=[],this.SharpenPostProcessId="SharpenPostProcessEffect",this.ImageProcessingPostProcessId="ImageProcessingPostProcessEffect",this.FxaaPostProcessId="FxaaPostProcessEffect",this.ChromaticAberrationPostProcessId="ChromaticAberrationPostProcessEffect",this.GrainPostProcessId="GrainPostProcessEffect",this._glowLayer=null,this.animations=[],this._imageProcessingConfigurationObserver=null,this._sharpenEnabled=!1,this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._depthOfFieldBlurLevel=gm.Low,this._fxaaEnabled=!1,this._imageProcessingEnabled=!0,this._bloomScale=.5,this._chromaticAberrationEnabled=!1,this._grainEnabled=!1,this._buildAllowed=!0,this.onBuildObservable=new r.y$,this._resizeObserver=null,this._hardwareScaleLevel=1,this._bloomKernel=64,this._bloomWeight=.15,this._bloomThreshold=.9,this._samples=1,this._hasCleared=!1,this._prevPostProcess=null,this._prevPrevPostProcess=null,this._depthOfFieldSceneObserver=null,this._activeCameraChangedObserver=null,this._activeCamerasChangedObserver=null,this._cameras=n||i.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._buildAllowed=s,this._scene=i;const o=this._scene.getEngine().getCaps();this._hdr=t&&(o.textureHalfFloatRender||o.textureFloatRender),this._hdr?o.textureHalfFloatRender?this._defaultPipelineTextureType=2:o.textureFloatRender&&(this._defaultPipelineTextureType=1):this._defaultPipelineTextureType=0,i.postProcessRenderPipelineManager.addPipeline(this);const a=this._scene.getEngine();this.sharpen=new Im("sharpen",1,null,Ce.x.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._sharpenEffect=new am(a,this.SharpenPostProcessId,(()=>this.sharpen),!0),this.depthOfField=new vm(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 cm(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new um("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,Ce.x.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new am(a,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new Tm("Grain",1,null,Ce.x.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new am(a,this.GrainPostProcessId,(()=>this.grain),!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,de.w1.SetImmediate((()=>{this._buildPipeline()})))})),this._buildPipeline()}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(),null!==this._cameras&&(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 e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.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 Wi("imageProcessing",1,null,Ce.x.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new am(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(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 bm("fxaa",1,null,Ce.x.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new am(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(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._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&_.Y.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;t<this._cameras.length;t++){const i=this._cameras[t];this.imageProcessing&&this.imageProcessing.dispose(i),this.fxaa&&this.fxaa.dispose(i),e&&(this.sharpen&&this.sharpen.dispose(i),this.depthOfField&&(this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver),this.depthOfField.disposeEffects(i)),this.bloom&&this.bloom.disposeEffects(i),this.chromaticAberration&&this.chromaticAberration.dispose(i),this.grain&&this.grain.dispose(i),this._glowLayer&&this._glowLayer.dispose())}this.imageProcessing=null,this.fxaa=null,e&&(this.sharpen=null,this._sharpenEffect=null,this.depthOfField=null,this.bloom=null,this.chromaticAberration=null,this._chromaticAberrationEffect=null,this.grain=null,this._grainEffect=null,this._glowLayer=null)}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._buildAllowed=!1,this.onBuildObservable.clear(),this._disposePostProcesses(!0),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._scene._postProcessRenderPipelineManager.removePipeline(this.name),this._scene.autoClear=!0,this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this._scene.onActiveCameraChanged.remove(this._activeCameraChangedObserver),this._scene.onActiveCamerasChanged.remove(this._activeCamerasChangedObserver),this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver),super.dispose()}serialize(){const e=Te.p4.Serialize(this);return e.customType="DefaultRenderingPipeline",e}static Parse(e,t,i){return Te.p4.Parse((()=>new Nm(e._name,e._name._hdr,t)),e,t,i)}}(0,be.gn)([(0,Te.qC)()],Nm.prototype,"sharpenEnabled",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"bloomKernel",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"_bloomWeight",void 0),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"_bloomThreshold",void 0),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"_hdr",void 0),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"bloomWeight",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"bloomThreshold",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"bloomScale",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"bloomEnabled",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"depthOfFieldEnabled",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"depthOfFieldBlurLevel",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"fxaaEnabled",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"samples",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"imageProcessingEnabled",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"glowLayerEnabled",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"chromaticAberrationEnabled",null),(0,be.gn)([(0,Te.qC)()],Nm.prototype,"grainEnabled",null),(0,l.H)("BABYLON.DefaultRenderingPipeline",Nm);si.v.ShadersStore.lensHighlightsPixelShader="uniform sampler2D textureSampler; \nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\nvarying vec2 vUV;\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\nif (gain==-1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n}";si.v.ShadersStore.depthOfFieldPixelShader="uniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\nuniform float near;\nuniform float far;\nvarying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion==0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\nfloat sampleScreen(inout vec4 color,in vec2 offset,in float weight) {\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\nreturn col;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\nif (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\nfloat blur_amount=max(edge_blur_amount,coc);\nif (blur_amount==0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\ngl_FragColor=getBlurColor(blur_amount*1.7);\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n";class Fm extends Dm{constructor(e,t,i,n=1,s){super(i.getEngine(),e),this.LensChromaticAberrationEffect="LensChromaticAberrationEffect",this.HighlightsEnhancingEffect="HighlightsEnhancingEffect",this.LensDepthOfFieldEffect="LensDepthOfFieldEffect",this._pentagonBokehIsEnabled=!1,this._scene=i,this._depthTexture=i.enableDepthRenderer().getDepthMap(),t.grain_texture?this._grainTexture=t.grain_texture:this._createGrainTexture(),this._edgeBlur=t.edge_blur?t.edge_blur:0,this._grainAmount=t.grain_amount?t.grain_amount:0,this._chromaticAberration=t.chromatic_aberration?t.chromatic_aberration:0,this._distortion=t.distortion?t.distortion:0,this._highlightsGain=void 0!==t.dof_gain?t.dof_gain:-1,this._highlightsThreshold=t.dof_threshold?t.dof_threshold:1,this._dofDistance=void 0!==t.dof_focus_distance?t.dof_focus_distance:-1,this._dofAperture=t.dof_aperture?t.dof_aperture:1,this._dofDarken=t.dof_darken?t.dof_darken:0,this._dofPentagon=void 0===t.dof_pentagon||t.dof_pentagon,this._blurNoise=void 0===t.blur_noise||t.blur_noise,this._createChromaticAberrationPostProcess(n),this._createHighlightsPostProcess(n),this._createDepthOfFieldPostProcess(n/4),this.addEffect(new am(i.getEngine(),this.LensChromaticAberrationEffect,(()=>this._chromaticAberrationPostProcess),!0)),this.addEffect(new am(i.getEngine(),this.HighlightsEnhancingEffect,(()=>this._highlightsPostProcess),!0)),this.addEffect(new am(i.getEngine(),this.LensDepthOfFieldEffect,(()=>this._depthOfFieldPostProcess),!0)),-1===this._highlightsGain&&this._disableEffect(this.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(this),s&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"LensRenderingPipeline"}get scene(){return this._scene}get edgeBlur(){return this._edgeBlur}set edgeBlur(e){this.setEdgeBlur(e)}get grainAmount(){return this._grainAmount}set grainAmount(e){this.setGrainAmount(e)}get chromaticAberration(){return this._chromaticAberration}set chromaticAberration(e){this.setChromaticAberration(e)}get dofAperture(){return this._dofAperture}set dofAperture(e){this.setAperture(e)}get edgeDistortion(){return this._distortion}set edgeDistortion(e){this.setEdgeDistortion(e)}get dofDistortion(){return this._dofDistance}set dofDistortion(e){this.setFocusDistance(e)}get darkenOutOfFocus(){return this._dofDarken}set darkenOutOfFocus(e){this.setDarkenOutOfFocus(e)}get blurNoise(){return this._blurNoise}set blurNoise(e){this._blurNoise=e}get pentagonBokeh(){return this._pentagonBokehIsEnabled}set pentagonBokeh(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()}get highlightsGain(){return this._highlightsGain}set highlightsGain(e){this.setHighlightsGain(e)}get highlightsThreshold(){return this._highlightsThreshold}set highlightsThreshold(e){this.setHighlightsThreshold(e)}setEdgeBlur(e){this._edgeBlur=e}disableEdgeBlur(){this._edgeBlur=0}setGrainAmount(e){this._grainAmount=e}disableGrain(){this._grainAmount=0}setChromaticAberration(e){this._chromaticAberration=e}disableChromaticAberration(){this._chromaticAberration=0}setEdgeDistortion(e){this._distortion=e}disableEdgeDistortion(){this._distortion=0}setFocusDistance(e){this._dofDistance=e}disableDepthOfField(){this._dofDistance=-1}setAperture(e){this._dofAperture=e}setDarkenOutOfFocus(e){this._dofDarken=e}enablePentagonBokeh(){this._highlightsPostProcess.updateEffect("#define PENTAGON\n"),this._pentagonBokehIsEnabled=!0}disablePentagonBokeh(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()}enableNoiseBlur(){this._blurNoise=!0}disableNoiseBlur(){this._blurNoise=!1}setHighlightsGain(e){this._highlightsGain=e}setHighlightsThreshold(e){-1===this._highlightsGain&&(this._highlightsGain=1),this._highlightsThreshold=e}disableHighlights(){this._highlightsGain=-1}dispose(e=!1){this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()}_createChromaticAberrationPostProcess(e){this._chromaticAberrationPostProcess=new ni.D("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,Ce.x.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=e=>{e.setFloat("chromatic_aberration",this._chromaticAberration),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("radialIntensity",1),e.setFloat2("direction",17,17),e.setFloat2("centerPosition",.5,.5)}}_createHighlightsPostProcess(e){this._highlightsPostProcess=new ni.D("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,Ce.x.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?"#define PENTAGON\n":""),this._highlightsPostProcess.externalTextureSamplerBinding=!0,this._highlightsPostProcess.onApply=e=>{e.setFloat("gain",this._highlightsGain),e.setFloat("threshold",this._highlightsThreshold),e.setTextureFromPostProcess("textureSampler",this._chromaticAberrationPostProcess),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight())}}_createDepthOfFieldPostProcess(e){this._depthOfFieldPostProcess=new ni.D("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,Ce.x.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.externalTextureSamplerBinding=!0,this._depthOfFieldPostProcess.onApply=e=>{e.setTexture("depthSampler",this._depthTexture),e.setTexture("grainSampler",this._grainTexture),e.setTextureFromPostProcess("textureSampler",this._highlightsPostProcess),e.setTextureFromPostProcess("highlightsSampler",this._depthOfFieldPostProcess),e.setFloat("grain_amount",this._grainAmount),e.setBool("blur_noise",this._blurNoise),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("distortion",this._distortion),e.setBool("dof_enabled",-1!==this._dofDistance),e.setFloat("screen_distance",1/(.1-1/this._dofDistance)),e.setFloat("aperture",this._dofAperture),e.setFloat("darken",this._dofDarken),e.setFloat("edge_blur",this._edgeBlur),e.setBool("highlights",-1!==this._highlightsGain),this._scene.activeCamera&&(e.setFloat("near",this._scene.activeCamera.minZ),e.setFloat("far",this._scene.activeCamera.maxZ))}}_createGrainTexture(){this._grainTexture=new zi.c("LensNoiseTexture",512,this._scene,!1,Ce.x.BILINEAR_SAMPLINGMODE),this._grainTexture.wrapU=Ce.x.WRAP_ADDRESSMODE,this._grainTexture.wrapV=Ce.x.WRAP_ADDRESSMODE;const e=this._grainTexture.getContext();let t;for(let i=0;i<512;i++)for(let n=0;n<512;n++)t=Math.floor(255*(.42,.58,Math.random()*(.58-.42)+.42)),e.fillStyle="rgb("+t+", "+t+", "+t+")",e.fillRect(i,n,1,1);this._grainTexture.update(!1)}}class Lm{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}si.v.ShadersStore.ssao2PixelShader="precision highp float;\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nuniform float near;\nuniform float radius;\nuniform sampler2D depthSampler;\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform mat3 depthProjection;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;\nfloat depth=textureLod(depthSampler,vUV,0.0).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=textureLod(normalSampler,vUV,0.0).rgb;\nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);\nvec3 origin=vViewRay*vDepthFactor;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\nfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=step(EPSILON,difference)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BLUR\nuniform float outSize;\nuniform float soften;\nuniform float tolerance;\nuniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {\nfloat result=0.0;\nvec2 off1=vec2(1.411764705882353)*step;\nvec2 off2=vec2(3.2941176470588234)*step;\nvec2 off3=vec2(5.176470588235294)*step;\nfloat compareDepth=abs(textureLod(depthSampler,uv,0.0).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\nresult+=textureLod(image,uv,0.0).r*30.0;\nsampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+= weight;\nresult+=textureLod(image,uv+off1,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+= weight;\nresult+=textureLod(image,uv-off1,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv+off2,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv-off2,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv+off3,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv-off3,0.0).r*weight;\nreturn result/weightSum;\n}\n#endif\n#endif\nvoid main()\n{\nfloat result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);\nfloat weightSum=0.0;\nfor (int i=-samples; i<samples; i+=2)\n{\nvec2 samplePos=vUV+step*(float(i)+0.5);\nfloat sampleDepth=abs(textureLod(depthSampler,samplePos,0.0).r);\nfloat falloff=smoothstep(0.0,\nfloat(samples),\nfloat(samples)-abs(float(i))*soften);\nfloat minDivider=tolerance*0.5+0.003;\nfloat weight=falloff/( minDivider+abs(compareDepth-sampleDepth));\nresult+=textureLod(textureSampler,samplePos,0.0).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\n#endif\n#endif\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n";si.v.ShadersStore.ssaoCombinePixelShader="uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";class Bm extends Dm{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=A.l.LastCreatedEngine;return!!e&&e._features.supportSSAO2}get scene(){return this._scene}constructor(e,t,i,n,s=!1,r=0){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=r,this._forceGeometryBuffer=s,!this.isSupported)return void _.Y.Error("The current engine does not support SSAO 2.");const o=this._ratio.ssaoRatio||i,a=this._ratio.blurRatio||i;this._forceGeometryBuffer?t.enableGeometryBufferRenderer():t.enablePrePassRenderer(),this._createRandomTexture(),this._originalColorPostProcess=new ii.Q("SSAOOriginalSceneColor",1,null,Ce.x.BILINEAR_SAMPLINGMODE,t.getEngine(),void 0,this._textureType),this._originalColorPostProcess.samples=this.textureSamples,this._createSSAOPostProcess(1,r),this._createBlurPostProcess(o,a,this._textureType),this._createSSAOCombinePostProcess(a,this._textureType),this.addEffect(new am(t.getEngine(),this.SSAOOriginalSceneColorEffect,(()=>this._originalColorPostProcess),!0)),this.addEffect(new am(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new am(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new am(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new am(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),n&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,n)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e<this._scene.cameras.length;e++){const t=this._scene.cameras[e];this._originalColorPostProcess.dispose(t),this._ssaoPostProcess.dispose(t),this._blurHPostProcess.dispose(t),this._blurVPostProcess.dispose(t),this._ssaoCombinePostProcess.dispose(t)}this._randomTexture.dispose(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),super.dispose()}_rebuild(){super._rebuild()}_getSamplersForBlur(e){return e?["textureSampler"]:["textureSampler","depthSampler"]}_getDefinesForBlur(e,t){let i="#define BLUR\n";return t&&(i+="#define BLUR_BYPASS\n"),e||(i+="#define BLUR_LEGACY\n"),{h:i+"#define BLUR_H\n",v:i}}_createBlurPostProcess(e,t,i){const n=this._getDefinesForBlur(this.expensiveBlur,this.bypassBlur),s=this._getSamplersForBlur(this.bypassBlur);this._blurHPostProcess=this._createBlurFilter("BlurH",s,e,n.h,i,!0),this._blurVPostProcess=this._createBlurFilter("BlurV",s,t,n.v,i,!1)}_createBlurFilter(e,t,i,n,s,r){const o=new ni.D(e,"ssao2",["outSize","samples","soften","tolerance"],t,i,null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,n,s);return o.onApply=e=>{if(!this._scene.activeCamera)return;const t=r?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=r?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=2*t*Math.PI,n=1-.85*e,s=Math.sqrt(1-n*n);return new o.P(Math.cos(i)*s,Math.sin(i)*s,n)}_generateHemisphere(){const e=this.samples,t=[];let i,n=0;for(;n<e;){if(e<16)i=this._hemisphereSample_uniform(Math.random(),Math.random());else{const t=this._hammersley(n,e);i=this._hemisphereSample_uniform(t[0],t[1])}t.push(i.x,i.y,i.z),n++}return t}_getDefinesForSSAO(){return`#define SSAO\n#define SAMPLES ${this.samples}\n#define EPSILON ${this.epsilon.toFixed(4)}`}_createSSAOPostProcess(e,t){this._sampleSphere=this._generateHemisphere();const i=this._getDefinesForSSAO();this._ssaoPostProcess=new ni.D("ssao2","ssao2",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","base","range","projection","near","texelSize","xViewport","yViewport","maxZ","minZAspect","depthProjection"],["randomSampler","depthSampler","normalSampler"],e,null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i,t),this._ssaoPostProcess.onApply=e=>{var t,i,n,s;if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===Mt.V.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",Bm.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const r=this._scene.getEngine().getRenderWidth()/2,o=this._scene.getEngine().getRenderHeight()/2,a=null!==(t=this._scene.activeCamera.orthoLeft)&&void 0!==t?t:-r,l=null!==(i=this._scene.activeCamera.orthoRight)&&void 0!==i?i:r,h=null!==(n=this._scene.activeCamera.orthoBottom)&&void 0!==n?n:-o,c=null!==(s=this._scene.activeCamera.orthoTop)&&void 0!==s?s:o;e.setMatrix3x3("depthProjection",Bm.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(l-a)),e.setFloat("yViewport",.5*(c-h))}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new Lm)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new ni.D("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{const t=this._scene.activeCamera.viewport;e.setVector4("viewport",o.jp.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){this._randomTexture=new zi.c("SSAORandomTexture",128,this._scene,!1,Ce.x.BILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=Ce.x.WRAP_ADDRESSMODE,this._randomTexture.wrapV=Ce.x.WRAP_ADDRESSMODE;const e=this._randomTexture.getContext(),t=(e,t)=>Math.random()*(t-e)+e,i=o.P.Zero();for(let n=0;n<128;n++)for(let s=0;s<128;s++)i.x=t(0,1),i.y=t(0,1),i.z=0,i.normalize(),i.scaleInPlace(255),i.x=Math.floor(i.x),i.y=Math.floor(i.y),e.fillStyle="rgb("+i.x+", "+i.y+", "+i.z+")",e.fillRect(n,s,1,1);this._randomTexture.update(!1)}serialize(){const e=Te.p4.Serialize(this);return e.customType="SSAO2RenderingPipeline",e}static Parse(e,t,i){return Te.p4.Parse((()=>new Bm(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)),e,t,i)}}Bm.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],Bm.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],(0,be.gn)([(0,Te.qC)()],Bm.prototype,"totalStrength",void 0),(0,be.gn)([(0,Te.qC)()],Bm.prototype,"maxZ",void 0),(0,be.gn)([(0,Te.qC)()],Bm.prototype,"minZAspect",void 0),(0,be.gn)([(0,Te.qC)("epsilon")],Bm.prototype,"_epsilon",void 0),(0,be.gn)([(0,Te.qC)("samples")],Bm.prototype,"_samples",void 0),(0,be.gn)([(0,Te.qC)("textureSamples")],Bm.prototype,"_textureSamples",void 0),(0,be.gn)([(0,Te.qC)()],Bm.prototype,"_forceGeometryBuffer",void 0),(0,be.gn)([(0,Te.qC)()],Bm.prototype,"_ratio",void 0),(0,be.gn)([(0,Te.qC)()],Bm.prototype,"_textureType",void 0),(0,be.gn)([(0,Te.qC)()],Bm.prototype,"radius",void 0),(0,be.gn)([(0,Te.qC)()],Bm.prototype,"base",void 0),(0,be.gn)([(0,Te.qC)("bypassBlur")],Bm.prototype,"_bypassBlur",void 0),(0,be.gn)([(0,Te.qC)("expensiveBlur")],Bm.prototype,"_expensiveBlur",void 0),(0,be.gn)([(0,Te.qC)()],Bm.prototype,"bilateralSamples",void 0),(0,be.gn)([(0,Te.qC)()],Bm.prototype,"bilateralSoften",void 0),(0,be.gn)([(0,Te.qC)()],Bm.prototype,"bilateralTolerance",void 0),(0,l.H)("BABYLON.SSAO2RenderingPipeline",Bm);si.v.ShadersStore.ssaoPixelShader="uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n";class Um extends Dm{get scene(){return this._scene}constructor(e,t,i,n){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 s=i.ssaoRatio||i,r=i.combineRatio||i;this._originalColorPostProcess=new ii.Q("SSAOOriginalSceneColor",r,null,Ce.x.BILINEAR_SAMPLINGMODE,t.getEngine(),!1),this._createSSAOPostProcess(s),this._createBlurPostProcess(s),this._createSSAOCombinePostProcess(r),this.addEffect(new am(t.getEngine(),this.SSAOOriginalSceneColorEffect,(()=>this._originalColorPostProcess),!0)),this.addEffect(new am(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new am(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new am(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new am(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),n&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,n)}_attachCameras(e,t){super._attachCameras(e,t);for(const e of this._cameras)this._scene.enableDepthRenderer(e).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e<this._scene.cameras.length;e++){const t=this._scene.cameras[e];this._originalColorPostProcess.dispose(t),this._ssaoPostProcess.dispose(t),this._blurHPostProcess.dispose(t),this._blurVPostProcess.dispose(t),this._ssaoCombinePostProcess.dispose(t)}this._randomTexture.dispose(),e&&this._scene.disableDepthRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),super.dispose()}_createBlurPostProcess(e){this._blurHPostProcess=new wa("BlurH",new o.FM(1,0),16,e,null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,0),this._blurVPostProcess=new wa("BlurV",new o.FM(0,1),16,e,null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,0),this._blurHPostProcess.onActivateObservable.add((()=>{const e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((()=>{const e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e}))}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const t=[.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];this._ssaoPostProcess=new ni.D("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new ni.D("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Ce.x.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",o.jp.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){this._randomTexture=new zi.c("SSAORandomTexture",512,this._scene,!1,Ce.x.TRILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=Ce.x.WRAP_ADDRESSMODE,this._randomTexture.wrapV=Ce.x.WRAP_ADDRESSMODE;const e=this._randomTexture.getContext(),t=(e,t)=>Math.random()*(t-e)+e,i=o.P.Zero();for(let n=0;n<512;n++)for(let s=0;s<512;s++)i.x=Math.floor(255*Math.max(0,t(-1,1))),i.y=Math.floor(255*Math.max(0,t(-1,1))),i.z=Math.floor(255*Math.max(0,t(-1,1))),e.fillStyle="rgb("+i.x+", "+i.y+", "+i.z+")",e.fillRect(n,s,1,1);this._randomTexture.update(!1)}}(0,be.gn)([(0,Te.qC)()],Um.prototype,"totalStrength",void 0),(0,be.gn)([(0,Te.qC)()],Um.prototype,"radius",void 0),(0,be.gn)([(0,Te.qC)()],Um.prototype,"area",void 0),(0,be.gn)([(0,Te.qC)()],Um.prototype,"fallOff",void 0),(0,be.gn)([(0,Te.qC)()],Um.prototype,"base",void 0);class Vm{constructor(){this.enabled=!1,this.name="screenSpaceReflections",this.texturesRequired=[6,3,1]}}si.v.ShadersStore.screenSpaceReflectionPixelShader="uniform sampler2D textureSampler;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;\nuniform sampler2D normalSampler;\nuniform sampler2D positionSampler;\n#endif\nuniform mat4 view;\nuniform mat4 projection;\nuniform float stepSize;\nuniform float strength;\nuniform float threshold;\nuniform float roughnessFactor;\nuniform float reflectionSpecularFalloffExponent;\nvarying vec2 vUV;\n#ifdef SSR_SUPPORTED\nstruct ReflectionInfo {\nvec3 color;\nvec4 coords;\n};\n/**\n* According to specular,see https:\n*/\nvec3 fresnelSchlick(float cosTheta,vec3 F0)\n{\nreturn F0+(1.0-F0)*pow(1.0-cosTheta,5.0);\n}\n/**\n* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit\n* by sampling multiple reflection pixels.\n*/\nReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord)\n{\nReflectionInfo info;\ninfo.color=vec3(0.0);\nvec4 projectedCoord;\nfloat sampledDepth;\nfor(int i=0; i<SMOOTH_STEPS; i++)\n{\nprojectedCoord=projection*vec4(hitCoord,1.0);\nprojectedCoord.xy/=projectedCoord.w;\nprojectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);\nsampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;\nfloat depth=sampledDepth-hitCoord.z;\ndir*=0.5;\nif(depth>0.0)\nhitCoord-=dir;\nelse\nhitCoord+=dir;\ninfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\n}\nprojectedCoord=projection*vec4(hitCoord,1.0);\nprojectedCoord.xy/=projectedCoord.w;\nprojectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);\ninfo.coords=vec4(projectedCoord.xy,sampledDepth,1.0);\ninfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\ninfo.color/=float(SMOOTH_STEPS+1);\nreturn info;\n}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{\nReflectionInfo info;\nvec4 projectedCoord;\nfloat sampledDepth;\ndir*=stepSize;\nfor(int i=0; i<REFLECTION_SAMPLES; i++)\n{\nhitCoord+=dir;\nprojectedCoord=projection*vec4(hitCoord,1.0);\nprojectedCoord.xy/=projectedCoord.w;\nprojectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);\nsampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;\nfloat depth=sampledDepth-hitCoord.z;\n#ifdef RIGHT_HANDED_SCENE\ndepth*=-1.0;\n#endif\nif(((depth-dir.z)<threshold) && depth<=0.0)\n{\n#ifdef ENABLE_SMOOTH_REFLECTIONS\nreturn smoothReflectionInfo(dir,hitCoord);\n#else\ninfo.color=texture2D(textureSampler,projectedCoord.xy).rgb;\ninfo.coords=vec4(projectedCoord.xy,sampledDepth,0.0);\nreturn info;\n#endif\n}\n}\ninfo.color=texture2D(textureSampler,projectedCoord.xy).rgb;\ninfo.coords=vec4(projectedCoord.xy,sampledDepth,0.0);\nreturn info;\n}\nvec3 hash(vec3 a)\n{\na=fract(a*0.8);\na+=dot(a,a.yxz+19.19);\nreturn fract((a.xxy+a.yxx)*a.zyx);\n}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 albedoFull=texture2D(textureSampler,vUV);\nvec3 albedo=albedoFull.rgb;\nfloat spec=texture2D(reflectivitySampler,vUV).r;\nif (spec==0.0) {\ngl_FragColor=albedoFull;\nreturn;\n}\nvec3 normal=(texture2D(normalSampler,vUV)).xyz;\nvec3 position=(view*texture2D(positionSampler,vUV)).xyz;\nvec3 reflected=normalize(reflect(normalize(position),normalize(normal)));\nfloat roughness=1.0-texture2D(reflectivitySampler,vUV).a;\nvec3 jitt=mix(vec3(0.0),hash(position),roughness)*roughnessFactor;\nReflectionInfo info=getReflectionInfo(jitt+reflected,position);\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-info.coords.xy));\nfloat screenEdgefactor=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\nvec3 F0=vec3(0.04);\nF0 =mix(F0,albedo,spec);\nvec3 fresnel=fresnelSchlick(max(dot(normalize(normal),normalize(position)),0.0),F0);\n#ifdef RIGHT_HANDED_SCENE\nreflected.z*=-1.0;\n#endif\nfloat reflectionMultiplier=clamp(pow(spec*strength,reflectionSpecularFalloffExponent)*screenEdgefactor*reflected.z,0.0,0.9);\nfloat albedoMultiplier=1.0-reflectionMultiplier;\nvec3 SSR=info.color*fresnel;\ngl_FragColor=vec4((albedo*albedoMultiplier)+(SSR*reflectionMultiplier),albedoFull.a);\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";class km extends ni.D{get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"ScreenSpaceReflectionPostProcess"}constructor(e,t,i,n,s,r,o,a=0,l=!1,h=!1){if(super(e,"screenSpaceReflection",["projection","view","threshold","reflectionSpecularFalloffExponent","strength","stepSize","roughnessFactor"],["textureSampler","normalSampler","positionSampler","reflectivitySampler"],i,n,s,r,o,"#define SSR_SUPPORTED\n#define REFLECTION_SAMPLES 64\n#define SMOOTH_STEPS 5\n",a,void 0,null,l),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=h,this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&e.isSupported&&(e.enablePosition=!0,e.enableReflectivity=!0)}else{const e=t.enablePrePassRenderer();null==e||e.markAsDirty(),this._prePassEffectConfiguration=new Vm}this._updateEffectDefines(),this.onApply=e=>{const i=this._geometryBufferRenderer,n=this._prePassRenderer;if(!n&&!i)return;if(i){const t=i.getTextureIndex(Cm.POSITION_TEXTURE_TYPE),n=i.getTextureIndex(Cm.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[n])}else if(n){const t=n.getIndex(1),i=n.getIndex(3),s=n.getIndex(6);e.setTexture("normalSampler",n.getRenderTarget().textures[s]),e.setTexture("positionSampler",n.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",n.getRenderTarget().textures[i])}const s=t.activeCamera;if(!s)return;const r=s.getViewMatrix(!0),o=s.getProjectionMatrix(!0);e.setMatrix("projection",o),e.setMatrix("view",r),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.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("\n"))}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new km(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,n)}}(0,be.gn)([(0,Te.qC)()],km.prototype,"threshold",void 0),(0,be.gn)([(0,Te.qC)()],km.prototype,"strength",void 0),(0,be.gn)([(0,Te.qC)()],km.prototype,"reflectionSpecularFalloffExponent",void 0),(0,be.gn)([(0,Te.qC)()],km.prototype,"step",void 0),(0,be.gn)([(0,Te.qC)()],km.prototype,"roughnessFactor",void 0),(0,be.gn)([(0,Te.qC)()],km.prototype,"enableSmoothReflections",null),(0,be.gn)([(0,Te.qC)()],km.prototype,"reflectionSamples",null),(0,be.gn)([(0,Te.qC)()],km.prototype,"smoothSteps",null),(0,l.H)("BABYLON.ScreenSpaceReflectionPostProcess",km);si.v.ShadersStore.standardPixelShader="uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric= (worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include<packingFunctions>\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\n#endif\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV/*lensFlareCoords*/);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n";class Gm extends Dm{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("\n"))}}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())return void _.Y.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");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\n#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\n#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,n=null,s){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=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=n,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(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new km("HDRPass",t,e,null,Ce.x.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess})),this.addEffect(new am(t.getEngine(),"HDRScreenSpaceReflections",(()=>this.screenSpaceReflectionPostProcess),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new ni.D("HDRPass","standard",[],[],e,null,Ce.x.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 am(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 ni.D("HDRDepthOfFieldSource","standard",[],[],e,null,Ce.x.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new am(t.getEngine(),"HDRBaseDepthOfFieldSource",(()=>this.textureAdderFinalPostProcess),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new ni.D("HDRVLSFinal","standard",[],[],e,null,Ce.x.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new am(t.getEngine(),"HDRVLSFinal",(()=>this.volumetricLightFinalPostProcess),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new ni.D("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,Ce.x.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new am(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(()=>this.lensFlareFinalPostProcess),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new ni.D("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,Ce.x.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new am(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 bm("fxaa",1,null,Ce.x.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new am(t.getEngine(),"HDRFxaa",(()=>this.fxaaPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&_.Y.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 ni.D("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0;const n=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let r=-2;r<2;r++)i[t]=(e+.5)*(1/n),i[t+1]=(r+.5)*(1/s),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new am(e.getEngine(),"HDRDownSampleX4",(()=>this.downSampleX4PostProcess),!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new ni.D("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{const t=1/this.brightPassPostProcess.width,n=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*n,i[2]=.5*t,i[3]=.5*n,i[4]=-.5*t,i[5]=-.5*n,i[6]=.5*t,i[7]=-.5*n,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new am(e.getEngine(),"HDRBrightPass",(()=>this.brightPassPostProcess),!0))}_createBlurPostProcesses(e,t,i,n="blurWidth"){const s=e.getEngine(),r=new wa("HDRBlurH_"+i,new o.FM(1,0),this[n],t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),a=new wa("HDRBlurV_"+i,new o.FM(0,1),this[n],t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);r.onActivateObservable.add((()=>{const e=r.width/s.getRenderWidth();r.kernel=this[n]*e})),a.onActivateObservable.add((()=>{const e=a.height/s.getRenderHeight();a.kernel=this.horizontalBlur?64*e:this[n]*e})),this.addEffect(new am(e.getEngine(),"HDRBlurH"+i,(()=>r),!0)),this.addEffect(new am(e.getEngine(),"HDRBlurV"+i,(()=>a),!0)),this.blurHPostProcesses.push(r),this.blurVPostProcesses.push(a)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new ni.D("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new am(e.getEngine(),"HDRTextureAdder",(()=>this.textureAdderPostProcess),!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const n=i.getGBuffer();this.volumetricLightPostProcess=new ni.D("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));const s=o.FM.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",n.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new am(e.getEngine(),"HDRVLS",(()=>this.volumetricLightPostProcess),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new ni.D("HDRVLSMerge","standard",[],["originalSampler"],t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new am(e.getEngine(),"HDRVLSMerge",(()=>this.volumetricLightMergePostProces),!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,Gm.LuminanceSteps);this.luminancePostProcess=new ni.D("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const n=[];this.luminancePostProcess.onApply=e=>{const t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;n[0]=-.5*t,n[1]=.5*i,n[2]=.5*t,n[3]=.5*i,n[4]=-.5*t,n[5]=-.5*i,n[6]=.5*t,n[7]=-.5*i,e.setArray2("lumOffsets",n)},this.addEffect(new am(e.getEngine(),"HDRLuminance",(()=>this.luminancePostProcess),!0));for(let n=Gm.LuminanceSteps-1;n>=0;n--){i=Math.pow(3,n);let s="#define LUMINANCE_DOWN_SAMPLE\n";0===n&&(s+="#define FINAL_DOWN_SAMPLER");const r=new ni.D("HDRLuminanceDownSample"+n,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,t);this.luminanceDownSamplePostProcesses.push(r)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(((t,i)=>{const n=new Array(18);t.onApply=e=>{if(!s)return;let r=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)n[r]=e/s.width,n[r+1]=t/s.height,r+=2;e.setArray2("dsOffsets",n),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{const t=e.getEngine().readPixels(0,0,1,1),i=new o.Lt(1/16581375,1/65025,1/255,1);t.then((e=>{const t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),this.addEffect(new am(e.getEngine(),"HDRLuminanceDownSample"+i,(()=>t),!0))}))}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new ni.D("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let n=1,s=0,r=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),n<0)n=this._hdrCurrentLuminance;else{const e=(r-s)/1e3;this._hdrCurrentLuminance<n+this.hdrDecreaseRate*e?n+=this.hdrDecreaseRate*e:this._hdrCurrentLuminance>n-this.hdrIncreaseRate*e?n-=this.hdrIncreaseRate*e:n=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/n:(n=lt.R.Clamp(n,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",n)),r=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new am(e.getEngine(),"HDR",(()=>this.hdrPostProcess),!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new ni.D("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new am(e.getEngine(),"HDRLensFlare",(()=>this.lensFlarePostProcess),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new ni.D("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new am(e.getEngine(),"HDRLensFlareCompose",(()=>this.lensFlareComposePostProcess),!0));const i=new o.FM(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const n=o.y3.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=o.y3.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);const t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2);let r=o.P.Dot(t.toVector3(),new o.P(1,0,0))+o.P.Dot(i.toVector3(),new o.P(0,0,1));r*=4;const a=o.y3.FromValues(.5*Math.cos(r),-Math.sin(r),0,0,Math.sin(r),.5*Math.cos(r),0,0,0,0,1,0,0,0,0,1),l=s.multiply(a).multiply(n);e.setMatrix("lensStarMatrix",l),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new ni.D("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new am(e.getEngine(),"HDRDepthOfField",(()=>this.depthOfFieldPostProcess),!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new Rm("HDRMotionBlur",e,t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new ni.D("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Ce.x.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,n=o.y3.Identity();const s=o.y3.Identity();let r=o.y3.Identity();const a=o.FM.Zero();this.motionBlurPostProcess.onApply=t=>{r=e.getProjectionMatrix().multiply(e.getViewMatrix()),r.invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",n),n=r,a.x=this.motionBlurPostProcess.width,a.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",a),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new am(e.getEngine(),"HDRMotionBlur",(()=>this.motionBlurPostProcess),!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;e<this._cameras.length;e++){const t=this._cameras[e];this.originalPostProcess&&this.originalPostProcess.dispose(t),this.screenSpaceReflectionPostProcess&&this.screenSpaceReflectionPostProcess.dispose(t),this.downSampleX4PostProcess&&this.downSampleX4PostProcess.dispose(t),this.brightPassPostProcess&&this.brightPassPostProcess.dispose(t),this.textureAdderPostProcess&&this.textureAdderPostProcess.dispose(t),this.volumetricLightPostProcess&&this.volumetricLightPostProcess.dispose(t),this.volumetricLightSmoothXPostProcess&&this.volumetricLightSmoothXPostProcess.dispose(t),this.volumetricLightSmoothYPostProcess&&this.volumetricLightSmoothYPostProcess.dispose(t),this.volumetricLightMergePostProces&&this.volumetricLightMergePostProces.dispose(t),this.volumetricLightFinalPostProcess&&this.volumetricLightFinalPostProcess.dispose(t),this.lensFlarePostProcess&&this.lensFlarePostProcess.dispose(t),this.lensFlareComposePostProcess&&this.lensFlareComposePostProcess.dispose(t);for(let e=0;e<this.luminanceDownSamplePostProcesses.length;e++)this.luminanceDownSamplePostProcesses[e].dispose(t);this.luminancePostProcess&&this.luminancePostProcess.dispose(t),this.hdrPostProcess&&this.hdrPostProcess.dispose(t),this.hdrFinalPostProcess&&this.hdrFinalPostProcess.dispose(t),this.depthOfFieldPostProcess&&this.depthOfFieldPostProcess.dispose(t),this.motionBlurPostProcess&&this.motionBlurPostProcess.dispose(t),this.fxaaPostProcess&&this.fxaaPostProcess.dispose(t);for(let e=0;e<this.blurHPostProcesses.length;e++)this.blurHPostProcesses[e].dispose(t);for(let e=0;e<this.blurVPostProcesses.length;e++)this.blurVPostProcesses[e].dispose(t)}this.originalPostProcess=null,this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.textureAdderPostProcess=null,this.textureAdderFinalPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.luminancePostProcess=null,this.hdrPostProcess=null,this.hdrFinalPostProcess=null,this.depthOfFieldPostProcess=null,this.motionBlurPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.luminanceDownSamplePostProcesses.length=0,this.blurHPostProcesses.length=0,this.blurVPostProcesses.length=0}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}serialize(){const e=Te.p4.Serialize(this);return this.sourceLight&&(e.sourceLightId=this.sourceLight.id),this.screenSpaceReflectionPostProcess&&(e.screenSpaceReflectionPostProcess=Te.p4.Serialize(this.screenSpaceReflectionPostProcess)),e.customType="StandardRenderingPipeline",e}static Parse(e,t,i){const n=Te.p4.Parse((()=>new Gm(e._name,t,e._ratio)),e,t,i);return e.sourceLightId&&(n.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&Te.p4.Parse((()=>n.screenSpaceReflectionPostProcess),e.screenSpaceReflectionPostProcess,t,i),n}}Gm.LuminanceSteps=6,(0,be.gn)([(0,Te.qC)()],Gm.prototype,"brightThreshold",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"blurWidth",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"horizontalBlur",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"exposure",null),(0,be.gn)([(0,Te.oU)("lensTexture")],Gm.prototype,"lensTexture",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"volumetricLightCoefficient",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"volumetricLightPower",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"volumetricLightBlurScale",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"hdrMinimumLuminance",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"hdrDecreaseRate",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"hdrIncreaseRate",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"hdrAutoExposure",null),(0,be.gn)([(0,Te.oU)("lensColorTexture")],Gm.prototype,"lensColorTexture",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"lensFlareStrength",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"lensFlareGhostDispersal",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"lensFlareHaloWidth",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"lensFlareDistortionStrength",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"lensFlareBlurWidth",void 0),(0,be.gn)([(0,Te.oU)("lensStarTexture")],Gm.prototype,"lensStarTexture",void 0),(0,be.gn)([(0,Te.oU)("lensFlareDirtTexture")],Gm.prototype,"lensFlareDirtTexture",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"depthOfFieldDistance",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"depthOfFieldBlurWidth",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"motionStrength",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"objectBasedMotionBlur",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"_ratio",void 0),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"BloomEnabled",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"DepthOfFieldEnabled",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"LensFlareEnabled",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"HDREnabled",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"VLSEnabled",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"MotionBlurEnabled",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"fxaaEnabled",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"screenSpaceReflectionsEnabled",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"volumetricLightStepsCount",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"motionBlurSamples",null),(0,be.gn)([(0,Te.qC)()],Gm.prototype,"samples",null),(0,l.H)("BABYLON.StandardRenderingPipeline",Gm);class zm{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}si.v.IncludesShadersStore.screenSpaceRayTrace="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)<nearPlaneZ ? (nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#endif\nvec3 csEndPoint=csOrigin+csDirection*rayLength;\nhitPixel=vec2(-1.0,-1.0);\nvec4 H0=projectToPixelMatrix*vec4(csOrigin,1.0);\nvec4 H1=projectToPixelMatrix*vec4(csEndPoint,1.0);\nfloat k0=1.0/H0.w;\nfloat k1=1.0/H1.w;\nvec3 Q0=csOrigin*k0;\nvec3 Q1=csEndPoint*k1;\nvec2 P0=H0.xy*k0;\nvec2 P1=H1.xy*k1;\n#ifdef SSRAYTRACE_CLIP_TO_FRUSTUM\nfloat xMax=csZBufferSize.x-0.5,xMin=0.5,yMax=csZBufferSize.y-0.5,yMin=0.5;\nfloat alpha=0.0;\nif ((P1.y>yMax) || (P1.y<yMin)) {\nalpha=(P1.y-((P1.y>yMax) ? yMax : yMin))/(P1.y-P0.y);\n}\nif ((P1.x>xMax) || (P1.x<xMin)) {\nalpha=max(alpha,(P1.x-((P1.x>xMax) ? xMax : xMin))/(P1.x-P0.x));\n}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);\nvec2 delta=P1-P0;\nbool permute=false;\nif (abs(delta.x)<abs(delta.y)) { \npermute=true;\ndelta=delta.yx;\nP0=P0.yx;\nP1=P1.yx; \n}\nfloat stepDirection=sign(delta.x);\nfloat invdx=stepDirection/delta.x;\nvec2 dP=vec2(stepDirection,delta.y*invdx);\nvec3 dQ=(Q1-Q0)*invdx;\nfloat dk=(k1-k0)*invdx;\nfloat zMin=min(csEndPoint.z,csOrigin.z);\nfloat zMax=max(csEndPoint.z,csOrigin.z);\ndP*=stride; dQ*=stride; dk*=stride;\nP0+=dP*jitterFraction; Q0+=dQ*jitterFraction; k0+=dk*jitterFraction;\nvec4 pqk=vec4(P0,Q0.z,k0);\nvec4 dPQK=vec4(dP,dQ.z,dk);\nstartPixel=permute ? P0.yx : P0.xy;\nfloat prevZMaxEstimate=csOrigin.z;\nfloat rayZMin=prevZMaxEstimate,rayZMax=prevZMaxEstimate;\nfloat sceneZMax=rayZMax+1e4;\nfloat end=P1.x*stepDirection;\nbool hit=false;\nfloat stepCount;\nfor (stepCount=0.0;\nstepCount<=selfCollisionNumSkip ||\n(pqk.x*stepDirection)<=end &&\nstepCount<maxSteps &&\n!hit &&\nsceneZMax != 0.0; \npqk+=dPQK,++stepCount)\n{\nhitPixel=permute ? pqk.yx : pqk.xy;\nrayZMin=prevZMaxEstimate;\nrayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);\nrayZMax=clamp(rayZMax,zMin,zMax);\nprevZMaxEstimate=rayZMax;\nif (rayZMin>rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;\n}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\nhit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\nhit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;\nstepCount-=1.0;\nif (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {\nhit=false;\n}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {\npqk-=dPQK;\nstepCount-=1.0;\nfloat invStride=1.0/stride;\ndPQK*=invStride;\nfloat refinementStepCount=0.0;\nprevZMaxEstimate=pqk.z/pqk.w;\nrayZMax=prevZMaxEstimate;\nsceneZMax=rayZMax+1e7;\nfor (;\nrefinementStepCount<=1.0 ||\n(refinementStepCount<=stride*1.4) &&\n(rayZMax<sceneZMax) && (sceneZMax != 0.0);\npqk+=dPQK,refinementStepCount+=1.0)\n{\nrayZMin=prevZMaxEstimate;\nrayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);\nrayZMax=clamp(rayZMax,zMin,zMax);\nprevZMaxEstimate=rayZMax;\nrayZMax=max(rayZMax,rayZMin);\nhitPixel=permute ? pqk.yx : pqk.xy;\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n}\npqk-=dPQK;\nrefinementStepCount-=1.0;\nstepCount+=refinementStepCount/stride;\n}\n#endif\nQ0.xy+=dQ.xy*stepCount;\nQ0.z=pqk.z;\ncsHitPoint=Q0/pqk.w;\nnumIterations=stepCount+1.0;\n#ifdef SSRAYTRACE_DEBUG\nif (((pqk.x+dPQK.x)*stepDirection)>end) {\ndebugColor=vec3(0,0,1);\n} else if ((stepCount+1.0)>=maxSteps) {\ndebugColor=vec3(1,0,0);\n} else if (sceneZMax==0.0) {\ndebugColor=vec3(1,1,0);\n} else {\ndebugColor=vec3(0,stepCount/maxSteps,0);\n}\n#endif\nreturn hit;\n}\n";si.v.ShadersStore.screenSpaceReflection2PixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;\nuniform sampler2D normalSampler;\nuniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;\nuniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;\nuniform mat4 invView;\nuniform mat4 projection;\nuniform mat4 invProjectionMatrix;\nuniform mat4 projectionPixel;\nuniform float nearPlaneZ;\nuniform float stepSize;\nuniform float maxSteps;\nuniform float strength;\nuniform float thickness;\nuniform float roughnessFactor;\nuniform float reflectionSpecularFalloffExponent;\nuniform float maxDistance;\nuniform float selfCollisionNumSkip;\nuniform float reflectivityThreshold;\n#include<helperFunctions>\n#include<screenSpaceRayTrace>\nvec3 fresnelSchlick(float cosTheta,vec3 F0)\n{\nreturn F0+(1.0-F0)*pow(1.0-cosTheta,5.0);\n}\nvec3 hash(vec3 a)\n{\na=fract(a*0.8);\na+=dot(a,a.yxz+19.19);\nreturn fract((a.xxy+a.yxx)*a.zyx);\n}\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {\nvec4 ndc;\nndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nndc.z=-projection[2].z-projection[3].z/depth;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\nndc.w=1.0;\nvec4 eyePos=invProjectionMatrix*ndc;\neyePos.xyz/=eyePos.w;\nreturn eyePos.xyz;\n}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {\nfloat attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));\nattenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;\nfloat directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));\nattenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;\n}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec3 color=colorFull.rgb;\nvec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;\n}\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));\nvec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;\nvec3 csPosition=computeViewPosFromUVDepth(vUV,depth);\nvec3 csViewDirection=normalize(csPosition);\nvec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);\nwReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;\nbool rayHasHit=false;\nvec2 startPixel;\nvec2 hitPixel;\nvec3 hitPoint;\nfloat numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;\nvec3 jitt=mix(vec3(0.0),hash(csPosition),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;\nfloat c=(uv2.x+uv2.y)*0.25;\nfloat jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);\n}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);\nreturn;\n#endif\nvec3 F0=reflectivity.rgb;\nvec3 fresnel=fresnelSchlick(max(dot(csNormal,-csViewDirection),0.0),F0);\nvec3 SSR=envColor;\nif (rayHasHit) {\nvec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);\nSSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;\n}\nSSR*=fresnel;\n#ifdef SSR_USE_BLUR\nfloat blur_radius=0.0;\nfloat roughness=1.0-reflectivity.a*(1.0-roughnessFactor);\nif (roughness>0.001) {\nfloat cone_angle=min(roughness,0.999)*3.14159265*0.5;\nfloat cone_len=distance(startPixel,hitPixel);\nfloat op_len=2.0*tan(cone_angle)*cone_len; \nfloat a=op_len;\nfloat h=cone_len;\nfloat a2=a*a;\nfloat fh2=4.0f*h*h;\nblur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);\n}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\nvec3 colorMultiplier=1.0-reflectionMultiplier;\nvec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";si.v.ShadersStore.screenSpaceReflection2BlurPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform vec2 texelOffsetScale;\nconst float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);\nvoid processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)\n{\nvec2 offsetUV=stepSize*i+uv;\nfloat coefficient=weights[int(2.0-abs(i))];\naccumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;\ndenominator+=coefficient;\n}\nvoid main()\n{\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);\nif (dot(colorFull,vec4(1.0))==0.0) {\ngl_FragColor=colorFull;\nreturn;\n}\nfloat blurRadius=colorFull.a*255.0; \nvec2 stepSize=texelOffsetScale.xy*blurRadius;\nvec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;\nfloat denominator=0.214607;\nprocessSample(vUV,1.0,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.2,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.4,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.6,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.8,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.2,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.4,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.6,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.8,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*2.0,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);\ngl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);\n}\n";si.v.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;\nuniform sampler2D reflectivitySampler;\nuniform float strength;\nuniform float reflectionSpecularFalloffExponent;\nuniform float reflectivityThreshold;\nvarying vec2 vUV;\n#include<helperFunctions>\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;\nvec4 color=texture2D(mainSampler,vUV);\nvec4 reflectivity=texture2D(reflectivitySampler,vUV);\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\ngl_FragColor=color;\nreturn;\n}\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\nvec3 colorMultiplier=1.0-reflectionMultiplier;\nvec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";const Wm=o.y3.Compose(new o.P(.5,.5,.5),o._f.Identity(),new o.P(.5,.5,.5)),Hm=o.y3.Compose(new o.P(.5,.5,1),o._f.Identity(),new o.P(.5,.5,0));class Xm extends Dm{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}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=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;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 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():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(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,n=!1,s=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._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=s,this._forceGeometryBuffer=n,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{const e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){var e,t;const i=this._scene.getEngine(),n=this._prePassRenderer;let s={width:i.getRenderWidth(),height:i.getRenderHeight()};if(n&&(null===(e=this._scene.activeCamera)||void 0===e?void 0:e._getFirstPostProcess())===this._ssrPostProcess){const e=n.getRenderTarget();e&&e.textures&&(s=e.textures[n.getIndex(4)].getSize())}else(null===(t=this._ssrPostProcess)||void 0===t?void 0:t.inputTexture)&&(s.width=this._ssrPostProcess.inputTexture.width,s.height=this._ssrPostProcess.inputTexture.height);return s}_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"),null===(e=this._ssrPostProcess)||void 0===e||e.updateEffect(t.join("\n"))}_buildPipeline(){var e;if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const t=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const t=null===(e=this._cameras)||void 0===e?void 0:e[0];t&&(this._depthRendererCamera=t,this._depthRenderer=new ph(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.getDepthMap().noPrePassRenderer=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),t.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new am(t,this.SSRRenderEffect,(()=>this._ssrPostProcess),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new am(t,this.SSRBlurRenderEffect,(()=>[this._blurPostProcessX,this._blurPostProcessY]),!0)),this.addEffect(new am(t,this.SSRCombineRenderEffect,(()=>this._blurCombinerPostProcess),!0))),null!==this._cameras&&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)),n=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===n||this._depthRenderer.getDepthMap().resize({width:i,height:n})}_disposeDepthRenderer(){var e;if(this._depthRenderer){if(this._depthRendererCamera){const t=null!==(e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()))&&void 0!==e?e:-1;-1!==t&&this._depthRendererCamera.customRenderTargets.splice(t,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,n;for(let s=0;s<this._cameras.length;s++){const r=this._cameras[s];null===(e=this._ssrPostProcess)||void 0===e||e.dispose(r),null===(t=this._blurPostProcessX)||void 0===t||t.dispose(r),null===(i=this._blurPostProcessY)||void 0===i||i.dispose(r),null===(n=this._blurCombinerPostProcess)||void 0===n||n.dispose(r)}this._ssrPostProcess=null,this._blurPostProcessX=null,this._blurPostProcessY=null,this._blurCombinerPostProcess=null}_createSSRPostProcess(){this._ssrPostProcess=new ni.D("ssr","screenSpaceReflection2",["projection","invProjectionMatrix","view","invView","thickness","reflectionSpecularFalloffExponent","strength","stepSize","maxSteps","roughnessFactor","projectionPixel","nearPlaneZ","maxDistance","selfCollisionNumSkip","vReflectionPosition","vReflectionSize","backSizeFactor","reflectivityThreshold"],["textureSampler","normalSampler","reflectivitySampler","depthSampler","envCubeSampler","backDepthSampler"],1,null,this._textureType,this._scene.getEngine(),!1,"",this._textureType),this._updateEffectDefines(),this._ssrPostProcess.onApply=e=>{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const i=t.getTextureIndex(Cm.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const t=i.getIndex(5),n=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[n])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const n=this._scene.activeCamera;if(!n)return;const s=n.getViewMatrix(!0),r=n.getProjectionMatrix(!0);r.invertToRef(o.jp.Matrix[0]),s.invertToRef(o.jp.Matrix[1]),e.setMatrix("projection",r),e.setMatrix("view",s),e.setMatrix("invView",o.jp.Matrix[1]),e.setMatrix("invProjectionMatrix",o.jp.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",n.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this.reflectivityThreshold);const a=this._getTextureSize();o.y3.ScalingToRef(a.width,a.height,1,o.jp.Matrix[2]),r.multiplyToRef(this._scene.getEngine().isWebGPU?Hm:Wm,o.jp.Matrix[3]),o.jp.Matrix[3].multiplyToRef(o.jp.Matrix[2],o.jp.Matrix[4]),e.setMatrix("projectionPixel",o.jp.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 zm)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new ni.D("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((e=>{var t,i;const n=null!==(i=null===(t=this._blurPostProcessX)||void 0===t?void 0:t.inputTexture.width)&&void 0!==i?i:this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/n,0)})),this._blurPostProcessY=new ni.D("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((e=>{var t,i;const n=null!==(i=null===(t=this._blurPostProcessY)||void 0===t?void 0:t.inputTexture.height)&&void 0!==i?i:this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/n)}));let t="";this._debug&&(t+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(t+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(t+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this._blurCombinerPostProcess=new ni.D("SSRblurCombiner","screenSpaceReflection2BlurCombiner",["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],["textureSampler","mainSampler","reflectivitySampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,t,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((e=>{var t;const i=this._geometryBufferRenderer,n=this._prePassRenderer;if(n||i){if(n&&(null===(t=this._scene.activeCamera)||void 0===t?void 0:t._getFirstPostProcess())===this._ssrPostProcess){const t=n.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[n.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(i){const t=i.getTextureIndex(Cm.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",i.getGBuffer().textures[t])}else if(n){const t=n.getIndex(3);e.setTexture("reflectivitySampler",n.getRenderTarget().textures[t])}e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this.reflectivityThreshold)}}))}serialize(){const e=Te.p4.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return Te.p4.Parse((()=>new Xm(e._name,t,e._ratio)),e,t,i)}}(0,be.gn)([(0,Te.qC)()],Xm.prototype,"samples",null),(0,be.gn)([(0,Te.qC)()],Xm.prototype,"maxDistance",void 0),(0,be.gn)([(0,Te.qC)()],Xm.prototype,"step",void 0),(0,be.gn)([(0,Te.qC)()],Xm.prototype,"thickness",void 0),(0,be.gn)([(0,Te.qC)()],Xm.prototype,"strength",void 0),(0,be.gn)([(0,Te.qC)()],Xm.prototype,"reflectionSpecularFalloffExponent",void 0),(0,be.gn)([(0,Te.qC)()],Xm.prototype,"maxSteps",void 0),(0,be.gn)([(0,Te.qC)()],Xm.prototype,"roughnessFactor",void 0),(0,be.gn)([(0,Te.qC)()],Xm.prototype,"selfCollisionNumSkip",void 0),(0,be.gn)([(0,Te.qC)()],Xm.prototype,"reflectivityThreshold",void 0),(0,be.gn)([(0,Te.qC)("_ssrDownsample")],Xm.prototype,"_ssrDownsample",void 0),(0,be.gn)([(0,Te.qC)()],Xm.prototype,"ssrDownsample",null),(0,be.gn)([(0,Te.qC)("blurDispersionStrength")],Xm.prototype,"_blurDispersionStrength",void 0),(0,be.gn)([(0,Te.qC)("blurDownsample")],Xm.prototype,"_blurDownsample",void 0),(0,be.gn)([(0,Te.qC)("enableSmoothReflections")],Xm.prototype,"_enableSmoothReflections",void 0),(0,be.gn)([(0,Te.qC)("environmentTexture")],Xm.prototype,"_environmentTexture",void 0),(0,be.gn)([(0,Te.qC)("environmentTextureIsProbe")],Xm.prototype,"_environmentTextureIsProbe",void 0),(0,be.gn)([(0,Te.qC)("attenuateScreenBorders")],Xm.prototype,"_attenuateScreenBorders",void 0),(0,be.gn)([(0,Te.qC)("attenuateIntersectionDistance")],Xm.prototype,"_attenuateIntersectionDistance",void 0),(0,be.gn)([(0,Te.qC)("attenuateIntersectionIterations")],Xm.prototype,"_attenuateIntersectionIterations",void 0),(0,be.gn)([(0,Te.qC)("attenuateFacingCamera")],Xm.prototype,"_attenuateFacingCamera",void 0),(0,be.gn)([(0,Te.qC)("attenuateBackfaceReflection")],Xm.prototype,"_attenuateBackfaceReflection",void 0),(0,be.gn)([(0,Te.qC)("clipToFrustum")],Xm.prototype,"_clipToFrustum",void 0),(0,be.gn)([(0,Te.qC)("enableAutomaticThicknessComputation")],Xm.prototype,"_enableAutomaticThicknessComputation",void 0),(0,be.gn)([(0,Te.qC)("backfaceDepthTextureDownsample")],Xm.prototype,"_backfaceDepthTextureDownsample",void 0),(0,be.gn)([(0,Te.qC)("backfaceForceDepthWriteTransparentMeshes")],Xm.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),(0,be.gn)([(0,Te.qC)("isEnabled")],Xm.prototype,"_isEnabled",void 0),(0,be.gn)([(0,Te.qC)("inputTextureColorIsInGammaSpace")],Xm.prototype,"_inputTextureColorIsInGammaSpace",void 0),(0,be.gn)([(0,Te.qC)("generateOutputInGammaSpace")],Xm.prototype,"_generateOutputInGammaSpace",void 0),(0,be.gn)([(0,Te.qC)("debug")],Xm.prototype,"_debug",void 0),(0,l.H)("BABYLON.SSRRenderingPipeline",Xm);var jm;si.v.ShadersStore.tonemapPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}",function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(jm||(jm={}));class Ym extends ni.D{getClassName(){return"TonemapPostProcess"}constructor(e,t,i,n,s=2,r,o=0,a){super(e,"tonemap",["_ExposureAdjustment"],null,1,n,s,r,a,null,o),this._operator=t,this.exposureAdjustment=i;let l="#define ";this._operator===jm.Hable?l+="HABLE_TONEMAPPING":this._operator===jm.Reinhard?l+="REINHARD_TONEMAPPING":this._operator===jm.HejiDawson?l+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":this._operator===jm.Photographic&&(l+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(l),this.onApply=e=>{e.setFloat("_ExposureAdjustment",this.exposureAdjustment)}}}si.v.ShadersStore.volumetricLightScatteringPixelShader="uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";si.v.ShadersStore.volumetricLightScatteringPassVertexShader="attribute vec3 position;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1)\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n";si.v.ShadersStore.volumetricLightScatteringPassPixelShader="#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n";class qm extends ni.D{get useDiffuseColor(){return _.Y.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){_.Y.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,n,s=100,r=Ce.x.BILINEAR_SAMPLINGMODE,a,l,h){var c,u;super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,r,a,l,"#define NUM_SAMPLES "+s),this._screenCoordinates=o.FM.Zero(),this.customMeshPosition=o.P.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=new Array,this.includedMeshes=new Array,this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,a=(h=null!==(u=null!==(c=null==i?void 0:i.getScene())&&void 0!==c?c:h)&&void 0!==u?u:this._scene).getEngine(),this._viewPort=new ui.l(0,0,1,1).toGlobal(a.getRenderWidth(),a.getRenderHeight()),this.mesh=null!=n?n:qm.CreateDefaultMesh("VolumetricLightScatteringMesh",h),this._createPass(h,t.passRatio||t),this.onActivate=e=>{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add((e=>{this._updateMeshScreenCoordinates(h),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)}))}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;const n=e.getMesh();if(n===this.mesh&&n.material)return n.material.isReady(n);const s=null===(i=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(n,e,t);const r=[],o=[qe.o.PositionKind],a=e.getMaterial();a&&(a.needAlphaTesting()&&r.push("#define ALPHATEST"),n.isVerticesDataPresent(qe.o.UVKind)&&(o.push(qe.o.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(qe.o.UV2Kind)&&(o.push(qe.o.UV2Kind),r.push("#define UV2"))),n.useBones&&n.computeBonesUsingShaders?(o.push(qe.o.MatricesIndicesKind),o.push(qe.o.MatricesWeightsKind),r.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),r.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),t&&(r.push("#define INSTANCES"),La.G.PushAttributesForInstances(o),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const l=e._getDrawWrapper(void 0,!0),h=l.defines,c=r.join("\n");return h!==c&&l.setEffect(n.getScene().getEngine().createEffect("volumetricLightScatteringPass",o,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],c,void 0,void 0,void 0,{maxSimultaneousMorphTargets:n.numBoneInfluencers}),c),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new Ai._("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const n=this.getCamera();n?n.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const s=e=>{var t;const i=e.getRenderingMesh(),n=e.getEffectiveMesh();if(this._meshExcluded(i))return;n._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const s=e.getMaterial();if(!s)return;const r=i.getScene(),o=r.getEngine();o.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);const a=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(a.mustReturn)return;const l=o.getCaps().instancedArrays&&(null!==a.visibleInstances[e._id]||i.hasThinInstances);if(this._isReady(e,l)){const h=null===(t=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[o.currentRenderPassId];let c=e._getDrawWrapper();if(i!==this.mesh||c||(c=s._getDrawWrapper()),!c)return;const u=c.effect;if(o.enableEffect(c),l||i._bind(e,u,s.fillMode),i===this.mesh)s.bind(n.getWorldMatrix(),i);else if(h)h.bindForSubMesh(n.getWorldMatrix(),n,e);else{if(u.setMatrix("viewProjection",r.getTransformMatrix()),s&&s.needAlphaTesting()){const e=s.getAlphaTestTexture();u.setTexture("diffuseSampler",e),e&&u.setMatrix("diffuseMatrix",e.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&u.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}l&&i.hasThinInstances&&u.setMatrix("world",n.getWorldMatrix()),i._processRendering(n,e,u,cs.F.TriangleFillMode,a,l,((e,t)=>{e||u.setMatrix("world",t)}))}};let r;const o=new a.HE(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((()=>{r=e.clearColor,e.clearColor=o})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((()=>{e.clearColor=r})),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,n)=>{if((n||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){const n=e.subMeshes[t],s=n.getMaterial(),r=n.getRenderingMesh();if(!s)continue;const o=r._getInstancesRenderList(n._id,!!n.getReplacementMesh()),a=i.getCaps().instancedArrays&&(null!==o.visibleInstances[n._id]||r.hasThinInstances);if(!this._isReady(n,a))return!1}return!0},this._volumetricLightScatteringRTT.customRenderFunction=(t,i,n,r)=>{const o=e.getEngine();let a;if(r.length){for(o.setColorWrite(!1),a=0;a<r.length;a++)s(r.data[a]);o.setColorWrite(!0)}for(a=0;a<t.length;a++)s(t.data[a]);for(a=0;a<i.length;a++)s(i.data[a]);if(n.length){for(a=0;a<n.length;a++){const t=n.data[a],i=t.getBoundingInfo();i&&e.activeCamera&&(t._alphaIndex=t.getMesh().alphaIndex,t._distanceToCamera=i.boundingSphere.centerWorld.subtract(e.activeCamera.position).length())}const t=n.data.slice(0,n.length);for(t.sort(((e,t)=>e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0)),o.setAlphaMode(2),a=0;a<t.length;a++)s(t[a]);o.setAlphaMode(0)}}}_updateMeshScreenCoordinates(e){const t=e.getTransformMatrix();let i;i=this.useCustomMeshPosition?this.customMeshPosition:this.attachedNode?this.attachedNode.position:this.mesh.parent?this.mesh.getAbsolutePosition():this.mesh.position;const n=o.P.Project(i,o.y3.Identity(),t,this._viewPort);this._screenCoordinates.x=n.x/this._viewPort.width,this._screenCoordinates.y=n.y/this._viewPort.height,this.invert&&(this._screenCoordinates.y=1-this._screenCoordinates.y)}static CreateDefaultMesh(e,t){const i=(0,pa.pT)(e,{size:1},t);i.billboardMode=Un.x.BILLBOARDMODE_ALL;const n=new Gi.K(e+"Material",t);return n.emissiveColor=new a.Wo(1,1,1),i.material=n,i}}(0,be.gn)([(0,Te.hd)()],qm.prototype,"customMeshPosition",void 0),(0,be.gn)([(0,Te.qC)()],qm.prototype,"useCustomMeshPosition",void 0),(0,be.gn)([(0,Te.qC)()],qm.prototype,"invert",void 0),(0,be.gn)([(0,Te.RR)()],qm.prototype,"mesh",void 0),(0,be.gn)([(0,Te.qC)()],qm.prototype,"excludedMeshes",void 0),(0,be.gn)([(0,Te.qC)()],qm.prototype,"includedMeshes",void 0),(0,be.gn)([(0,Te.qC)()],qm.prototype,"exposure",void 0),(0,be.gn)([(0,Te.qC)()],qm.prototype,"decay",void 0),(0,be.gn)([(0,Te.qC)()],qm.prototype,"weight",void 0),(0,be.gn)([(0,Te.qC)()],qm.prototype,"density",void 0),(0,l.H)("BABYLON.VolumetricLightScatteringPostProcess",qm);si.v.ShadersStore.screenSpaceCurvaturePixelShader="precision highp float;\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D normalSampler;\nuniform float curvature_ridge;\nuniform float curvature_valley;\n#ifndef CURVATURE_OFFSET\n#define CURVATURE_OFFSET 1\n#endif\nfloat curvature_soft_clamp(float curvature,float control)\n{\nif (curvature<0.5/control)\nreturn curvature*(1.0-curvature*control);\nreturn 0.25/control;\n}\nfloat calculate_curvature(ivec2 texel,float ridge,float valley)\n{\nvec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;\nvec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;\nvec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;\nvec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;\nfloat normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));\nif (normal_diff<0.0)\nreturn -2.0*curvature_soft_clamp(-normal_diff,valley);\nreturn 2.0*curvature_soft_clamp(normal_diff,ridge);\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nivec2 texel=ivec2(gl_FragCoord.xy);\nvec4 baseColor=texture2D(textureSampler,vUV);\nfloat curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);\nbaseColor.rgb*=curvature+1.0;\ngl_FragColor=baseColor;\n}";class Km extends ni.D{getClassName(){return"ScreenSpaceCurvaturePostProcess"}constructor(e,t,i,n,s,r,o,a=0,l=!1){super(e,"screenSpaceCurvature",["curvature_ridge","curvature_valley"],["textureSampler","normalSampler"],i,n,s,r,o,void 0,a,void 0,null,l),this.ridge=1,this.valley=1,this._geometryBufferRenderer=t.enableGeometryBufferRenderer(),this._geometryBufferRenderer?this.onApply=e=>{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}:_.Y.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=A.l.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,n){return Te.p4.Parse((()=>new Km(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,n)}}(0,be.gn)([(0,Te.qC)()],Km.prototype,"ridge",void 0),(0,be.gn)([(0,Te.qC)()],Km.prototype,"valley",void 0),(0,l.H)("BABYLON.ScreenSpaceCurvaturePostProcess",Km);si.v.IncludesShadersStore.boundingBoxRendererFragmentDeclaration="uniform vec4 color;\n";si.v.IncludesShadersStore.boundingBoxRendererUboDeclaration="#ifdef WEBGL2\nuniform vec4 color;\nuniform mat4 world;\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;\nuniform BoundingBoxRenderer {\nvec4 color;\nmat4 world;\nmat4 viewProjection;\nmat4 viewProjectionR;\n};\n#endif\n";si.v.ShadersStore.boundingBoxRendererPixelShader="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";si.v.IncludesShadersStore.boundingBoxRendererVertexDeclaration="uniform mat4 world;\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n";si.v.ShadersStore.boundingBoxRendererVertexShader="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n",Object.defineProperty(k.x.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),k.x.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new $m(this)),this._boundingBoxRenderer},Object.defineProperty(Un.x.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class $m{constructor(e){this.name=ve.l.NAME_BOUNDINGBOXRENDERER,this.frontColor=new a.Wo(1,1,1),this.backColor=new a.Wo(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new r.y$,this.onAfterBoxRenderingObservable=new r.y$,this.onResourcesReadyObservable=new r.y$,this.enabled=!0,this.renderList=new Fn.t(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new Ci.M(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new Ci.M(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(ve.l.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(ve.l.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(ve.l.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(ve.l.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();null!=i&&(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 us.j("colorShader",this.scene,"boundingBoxRenderer",{attributes:[qe.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new us.j("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[qe.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=(0,Yn.aR)({size:1});this._vertexBuffers[qe.o.PositionKind]=new qe.o(e,t.positions,qe.o.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[qe.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(0===this.renderList.length||!this.enabled)return;if(this._prepareResources(),!this._colorShader.isReady())return;const n=this.scene.getEngine();n.setDepthWrite(!1);const s=this.frontColor.toColor4(),r=this.backColor.toColor4(),a=this.scene.getTransformMatrix();for(let l=0;l<this.renderList.length;l++){const h=this.renderList.data[l];if(h._tag!==e)continue;this._createWrappersForBoundingBox(h),this.onBeforeBoxRenderingObservable.notifyObservers(h);const c=h.minimum,u=h.maximum.subtract(c),d=c.add(u.scale(.5)),p=o.y3.Scaling(u.x,u.y,u.z).multiply(o.y3.Translation(d.x,d.y,d.z)).multiply(h.getWorldMatrix()),f=n.useReverseDepthBuffer;if(this.showBackLines){const e=null!==(t=h._drawWrapperBack)&&void 0!==t?t:this._colorShader._getDrawWrapper();this._colorShader._preBind(e),n.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),f?n.setDepthFunctionToLessOrEqual():n.setDepthFunctionToGreaterOrEqual(),this._uniformBufferBack.bindToEffect(e.effect,"BoundingBoxRenderer"),this._uniformBufferBack.updateDirectColor4("color",r),this._uniformBufferBack.updateMatrix("world",p),this._uniformBufferBack.updateMatrix("viewProjection",a),this._uniformBufferBack.update(),n.drawElementsType(cs.F.LineListDrawMode,0,24)}const _=null!==(i=h._drawWrapperFront)&&void 0!==i?i:this._colorShader._getDrawWrapper();this._colorShader._preBind(_),n.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),f?n.setDepthFunctionToGreater():n.setDepthFunctionToLess(),this._uniformBufferFront.bindToEffect(_.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateDirectColor4("color",s),this._uniformBufferFront.updateMatrix("world",p),this._uniformBufferFront.updateMatrix("viewProjection",a),this._uniformBufferFront.update(),n.drawElementsType(cs.F.LineListDrawMode,0,24),this.onAfterBoxRenderingObservable.notifyObservers(h)}this._colorShader.unbind(),n.setDepthFunctionToLessOrEqual(),n.setDepthWrite(!0)}_createWrappersForBoundingBox(e){if(!e._drawWrapperFront){const t=this.scene.getEngine();e._drawWrapperFront=new Ps.q(t),e._drawWrapperBack=new Ps.q(t),e._drawWrapperFront.setEffect(this._colorShader.getEffect()),e._drawWrapperBack.setEffect(this._colorShader.getEffect())}}renderOcclusionBoundingBox(e){const t=this.scene.getEngine();void 0===this._renderPassIdForOcclusionQuery&&(this._renderPassIdForOcclusionQuery=t.createRenderPassId("Render pass for occlusion query"));const i=t.currentRenderPassId;t.currentRenderPassId=this._renderPassIdForOcclusionQuery,this._prepareResources();const n=e.subMeshes[0];if(!this._colorShaderForOcclusionQuery.isReady(e,void 0,n)||!e.hasBoundingInfo)return void(t.currentRenderPassId=i);this._fillIndexBuffer||(this._fillIndexBuffer=t.createIndexBuffer(this._fillIndexData));const s=t.useReverseDepthBuffer;t.setDepthWrite(!1),t.setColorWrite(!1);const r=e.getBoundingInfo().boundingBox,a=r.minimum,l=r.maximum.subtract(a),h=a.add(l.scale(.5)),c=o.y3.Scaling(l.x,l.y,l.z).multiply(o.y3.Translation(h.x,h.y,h.z)).multiply(r.getWorldMatrix()),u=n._drawWrapper;this._colorShaderForOcclusionQuery._preBind(u),t.bindBuffers(this._vertexBuffers,this._fillIndexBuffer,u.effect),s?t.setDepthFunctionToGreater():t.setDepthFunctionToLess(),this.scene.resetCachedMaterial(),this._uniformBufferFront.bindToEffect(u.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateMatrix("world",c),this._uniformBufferFront.updateMatrix("viewProjection",this.scene.getTransformMatrix()),this._uniformBufferFront.update(),t.drawElementsType(cs.F.TriangleFillMode,0,36),this._colorShaderForOcclusionQuery.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0),t.setColorWrite(!0),t.currentRenderPassId=i}dispose(){if(void 0!==this._renderPassIdForOcclusionQuery&&(this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery),this._renderPassIdForOcclusionQuery=void 0),!this._colorShader)return;this.onBeforeBoxRenderingObservable.clear(),this.onAfterBoxRenderingObservable.clear(),this.onResourcesReadyObservable.clear(),this.renderList.dispose(),this._colorShader.dispose(),this._colorShaderForOcclusionQuery.dispose(),this._uniformBufferFront.dispose(),this._uniformBufferBack.dispose();const e=this._vertexBuffers[qe.o.PositionKind];e&&(e.dispose(),this._vertexBuffers[qe.o.PositionKind]=null),this.scene.getEngine()._releaseBuffer(this._indexBuffer),this._fillIndexBuffer&&(this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer),this._fillIndexBuffer=null)}}k.x.prototype.enableDepthRenderer=function(e,t=!1,i=!1,n=3,s=!1){if(!(e=e||this.activeCamera))throw"No camera available to enable depth renderer";if(this._depthRenderer||(this._depthRenderer={}),!this._depthRenderer[e.id]){const r=!!this.getEngine().getCaps().textureFloatRender;let o=0;o=!this.getEngine().getCaps().textureHalfFloatRender||i&&r?r?1:0:2,this._depthRenderer[e.id]=new ph(this,o,e,t,n,s)}return this._depthRenderer[e.id]},k.x.prototype.disableDepthRenderer=function(e){(e=e||this.activeCamera)&&this._depthRenderer&&this._depthRenderer[e.id]&&this._depthRenderer[e.id].dispose()};class Qm{constructor(e){this.name=ve.l.NAME_DEPTHRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ve.l.STEP_GATHERRENDERTARGETS_DEPTHRENDERER,this,this._gatherRenderTargets),this.scene._gatherActiveCameraRenderTargetsStage.registerStep(ve.l.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER,this,this._gatherActiveCameraRenderTargets)}rebuild(){}dispose(){for(const e in this.scene._depthRenderer)this.scene._depthRenderer[e].dispose()}_gatherRenderTargets(e){if(this.scene._depthRenderer)for(const t in this.scene._depthRenderer){const i=this.scene._depthRenderer[t];i.enabled&&!i.useOnlyInActiveCamera&&e.push(i.getDepthMap())}}_gatherActiveCameraRenderTargets(e){if(this.scene._depthRenderer)for(const t in this.scene._depthRenderer){const i=this.scene._depthRenderer[t];i.enabled&&i.useOnlyInActiveCamera&&this.scene.activeCamera.id===t&&e.push(i.getDepthMap())}}}ph._SceneComponentInitialization=e=>{let t=e._getComponent(ve.l.NAME_DEPTHRENDERER);t||(t=new Qm(e),e._addComponent(t))};si.v.ShadersStore.oitFinalPixelShader="precision highp float;\nuniform sampler2D uFrontColor;\nuniform sampler2D uBackColor;\nvoid main() {\nivec2 fragCoord=ivec2(gl_FragCoord.xy);\nvec4 frontColor=texelFetch(uFrontColor,fragCoord,0);\nvec4 backColor=texelFetch(uBackColor,fragCoord,0);\nfloat alphaMultiplier=1.0-frontColor.a;\nglFragColor=vec4(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);\n}";si.v.ShadersStore.oitBackBlendPixelShader="precision highp float;\nuniform sampler2D uBackColor;\nvoid main() {\nglFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);\nif (glFragColor.a==0.0) { \ndiscard;\n}\n}";class Zm{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class Jm{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){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&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 Fn.t(10),this._excludedSubMeshes=new Fn.t(10),this._excludedMeshes=[],this._colorCache=[new a.HE(Jm._DEPTH_CLEAR_VALUE,Jm._DEPTH_CLEAR_VALUE,0,0),new a.HE(-Jm._MIN_DEPTH,Jm._MAX_DEPTH,0,0),new a.HE(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,e.enablePrePassRenderer()){for(let e=0;e<this._layoutCacheFormat.length;++e)this._layoutCache[e]=this._engine.buildTextureLayout(this._layoutCacheFormat[e]);this._renderPassIds=[],this.useRenderPasses=!1,this._prePassEffectConfiguration=new Zm,this._createTextures(),this._createEffects()}else _.Y.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.")}_createRenderPassIds(){if(this._releaseRenderPassIds(),this._useRenderPasses)for(let e=0;e<this._passCount+1;++e)this._renderPassIds[e]||(this._renderPassIds[e]=this._engine.createRenderPassId(`DepthPeelingRenderer - pass #${e}`))}_releaseRenderPassIds(){for(let e=0;e<this._renderPassIds.length;++e)this._engine.releaseRenderPassId(this._renderPassIds[e]);this._renderPassIds=[]}_createTextures(){const e={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()};this._depthMrts=[new Xc("depthPeelingDepth0",e,3,this._scene),new Xc("depthPeelingDepth1",e,3,this._scene)],this._colorMrts=[new Xc("depthPeelingColor0",e,2,this._scene,{generateDepthBuffer:!1}),new Xc("depthPeelingColor1",e,2,this._scene,{generateDepthBuffer:!1})],this._blendBackMrt=new Xc("depthPeelingBack",e,1,this._scene,{generateDepthBuffer:!1}),this._outputRT=new Ai._("depthPeelingOutput",e,this._scene,!1);const t=[{format:7,samplingMode:1,type:this._engine.getCaps().textureFloatLinearFiltering?1:2,label:"DepthPeelingRenderer-DepthTexture"},{format:5,samplingMode:1,type:2,label:"DepthPeelingRenderer-ColorTexture"}];for(let i=0;i<2;i++){const n=this._engine._createInternalTexture(e,t[0],!1),s=this._engine._createInternalTexture(e,t[1],!1),r=this._engine._createInternalTexture(e,t[1],!1);this._depthMrts[i].setInternalTexture(n,0),this._depthMrts[i].setInternalTexture(s,1),this._depthMrts[i].setInternalTexture(r,2),this._colorMrts[i].setInternalTexture(s,0),this._colorMrts[i].setInternalTexture(r,1),this._thinTextures.push(new nu.g(n),new nu.g(s),new nu.g(r))}}_disposeTextures(){for(let e=0;e<this._thinTextures.length;e++)6!==e&&this._thinTextures[e].dispose();for(let e=0;e<2;e++)this._depthMrts[e].dispose(!0),this._colorMrts[e].dispose(!0),this._blendBackMrt.dispose(!0);this._outputRT.dispose(),this._thinTextures=[],this._colorMrts=[],this._depthMrts=[]}_updateTextures(){return this._depthMrts[0].getSize().width===this._engine.getRenderWidth()&&this._depthMrts[0].getSize().height===this._engine.getRenderHeight()||(this._disposeTextures(),this._createTextures()),this._updateTextureReferences()}_updateTextureReferences(){var e;const t=this._scene.prePassRenderer;if(!t)return!1;const i=t.getIndex(4),n=(null===(e=t.defaultRT.textures)||void 0===e?void 0:e.length)?t.defaultRT.textures[i].getInternalTexture():null;return!!n&&(this._blendBackTexture!==n&&(this._blendBackTexture=n,this._blendBackMrt.setInternalTexture(this._blendBackTexture,0),this._thinTextures[6]&&this._thinTextures[6].dispose(),this._thinTextures[6]=new nu.g(this._blendBackTexture),t.defaultRT.renderTarget._shareDepth(this._depthMrts[0].renderTarget)),!0)}_createEffects(){this._blendBackEffectWrapper=new Ih.H({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._blendBackEffectWrapperPingPong=new Ih.H({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._finalEffectWrapper=new Ih.H({fragmentShader:"oitFinal",useShaderStore:!0,engine:this._engine,samplerNames:["uFrontColor","uBackColor"],uniformNames:[]}),this._effectRenderer=new Ih.I(this._engine)}setPrePassRenderer(e){e.addEffectConfiguration(this._prePassEffectConfiguration)}bind(e){e.setTexture("oitDepthSampler",this._thinTextures[3*this._currentPingPongState]),e.setTexture("oitFrontColorSampler",this._thinTextures[3*this._currentPingPongState+1])}_renderSubMeshes(e){let t;this._useRenderPasses&&(t={});for(let i=0;i<e.length;i++){const n=e.data[i].getMaterial();let s=!0,r=!1;const o=e.data[i];let a,l=!1;if(this._useRenderPasses&&(a=o._getDrawWrapper(),l=!a),n&&(s=n.allowShaderHotSwapping,r=n.backFaceCulling,n.allowShaderHotSwapping=!1,n.backFaceCulling=!1),o.render(!1),l&&(a=o._getDrawWrapper(),a.materialContext)){let e=t[a.materialContext.uniqueId];e||(e=t[a.materialContext.uniqueId]=this._engine.createMaterialContext()),o._getDrawWrapper().materialContext=e}n&&(n.allowShaderHotSwapping=s,n.backFaceCulling=r)}}_finalCompose(e){var t;(null===(t=this._scene.prePassRenderer)||void 0===t?void 0:t.setCustomOutput(this._outputRT))?this._engine.bindFramebuffer(this._outputRT.renderTarget):this._engine.restoreDefaultFramebuffer(),this._engine.setAlphaMode(0),this._engine.applyStates(),this._engine.enableEffect(this._finalEffectWrapper._drawWrapper),this._finalEffectWrapper.effect.setTexture("uFrontColor",this._thinTextures[3*e+1]),this._finalEffectWrapper.effect.setTexture("uBackColor",this._thinTextures[6]),this._effectRenderer.render(this._finalEffectWrapper)}render(e){if(this._candidateSubMeshes.length=0,this._excludedSubMeshes.length=0,!(this._blendBackEffectWrapper.effect.isReady()&&this._blendBackEffectWrapperPingPong.effect.isReady()&&this._finalEffectWrapper.effect.isReady()&&this._updateTextures()))return this._excludedSubMeshes;for(let t=0;t<e.length;t++){const i=e.data[t],n=i.getMaterial(),s=n&&i.getRenderingMesh()._getRenderingFillMode(n.fillMode);!n||s!==cs.F.TriangleFanDrawMode&&s!==cs.F.TriangleFillMode&&s!==cs.F.TriangleStripDrawMode||-1!==this._excludedMeshes.indexOf(i.getMesh().uniqueId)?this._excludedSubMeshes.push(i):this._candidateSubMeshes.push(i)}if(!this._candidateSubMeshes.length)return this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._finalCompose(1),this._excludedSubMeshes;const t=this._engine.currentRenderPassId;this._scene.prePassRenderer._enabled=!1,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[0]),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[1],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaMode(11),this._engine.setAlphaEquation(3),this._engine.depthCullingState.depthMask=!1,this._engine.depthCullingState.depthTest=!0,this._engine.applyStates(),this._currentPingPongState=1,this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._scene.resetCachedMaterial();let i=0,n=0;for(let e=0;e<this._passCount;e++){i=e%2,n=1-i,this._currentPingPongState=i,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[e+1]),this._engine.bindFramebuffer(this._depthMrts[n].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[n].renderTarget),this._engine.bindFramebuffer(this._colorMrts[n].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[n].renderTarget),this._engine.bindFramebuffer(this._depthMrts[n].renderTarget),this._engine.bindAttachments(this._layoutCache[2]),this._engine.setAlphaMode(11),this._engine.setAlphaEquation(3),this._engine.depthCullingState.depthTest=!1,this._engine.applyStates(),this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[n].renderTarget),this._scene.resetCachedMaterial(),this._engine.bindFramebuffer(this._blendBackMrt.renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaEquation(0),this._engine.setAlphaMode(17),this._engine.applyStates();const t=0!==n&&this._useRenderPasses?this._blendBackEffectWrapperPingPong:this._blendBackEffectWrapper;this._engine.enableEffect(t._drawWrapper),t.effect.setTexture("uBackColor",this._thinTextures[3*n+2]),this._effectRenderer.render(t),this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget)}return this._engine.currentRenderPassId=t,this._finalCompose(n),this._scene.prePassRenderer._enabled=!0,this._engine.depthCullingState.depthMask=!0,this._engine.depthCullingState.depthTest=!0,this._excludedSubMeshes}dispose(){this._disposeTextures(),this._blendBackEffectWrapper.dispose(),this._finalEffectWrapper.dispose(),this._effectRenderer.dispose(),this._releaseRenderPassIds()}}Jm._DEPTH_CLEAR_VALUE=-99999,Jm._MIN_DEPTH=0,Jm._MAX_DEPTH=1,Object.defineProperty(k.x.prototype,"depthPeelingRenderer",{get:function(){if(!this._depthPeelingRenderer){let e=this._getComponent(ve.l.NAME_DEPTHPEELINGRENDERER);e||(e=new eg(this),this._addComponent(e))}return this._depthPeelingRenderer},set:function(e){this._depthPeelingRenderer=e},enumerable:!0,configurable:!0}),Object.defineProperty(k.x.prototype,"useOrderIndependentTransparency",{get:function(){return this._useOrderIndependentTransparency},set:function(e){var t;this._useOrderIndependentTransparency!==e&&(this._useOrderIndependentTransparency=e,this.markAllMaterialsAsDirty(63),null===(t=this.prePassRenderer)||void 0===t||t.markAsDirty())},enumerable:!0,configurable:!0});class eg{constructor(e){this.name=ve.l.NAME_DEPTHPEELINGRENDERER,this.scene=e,e.depthPeelingRenderer=new Jm(e)}register(){}rebuild(){}dispose(){var e;null===(e=this.scene.depthPeelingRenderer)||void 0===e||e.dispose(),this.scene.depthPeelingRenderer=null}}si.v.ShadersStore.linePixelShader="#include<clipPlaneFragmentDeclaration>\nuniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";si.v.ShadersStore.lineVertexShader="#include<instancesDeclaration>\n#include<clipPlaneVertexDeclaration>\nattribute vec3 position;\nattribute vec4 normal;\nuniform mat4 viewProjection;\nuniform float width;\nuniform float aspectRatio;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\nmat4 worldViewProjection=viewProjection*finalWorld;\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include<clipPlaneVertex>\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}",Un.x.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},Un.x.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new ig(this,e,t,!0,i),this},Object.defineProperty(Un.x.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),is._.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new ng(this,e,t),this},is.E.prototype.enableEdgesRendering=function(e=.95,t=!1){return is._.prototype.enableEdgesRendering.apply(this,arguments),this};class tg{constructor(){this.edges=new Array,this.edgesConnectedCount=0}}class ig{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 us.j("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,n=!0,s){var r;this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new Fn.t(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=null!=s?s:null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new Ps.q(e.getEngine())),this._prepareRessources(),n&&(null===(r=null==s?void 0:s.useAlternateEdgeFinder)||void 0===r||r?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add((()=>{this._rebuild()})),this._meshDisposeObserver=this._source.onDisposeObservable.add((()=>{this.dispose()}))}_prepareRessources(){this._lineShader||(this._lineShader=ig._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[qe.o.PositionKind];e&&e._rebuild(),e=this._buffers[qe.o.NormalKind],e&&e._rebuild();const t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[qe.o.PositionKind];t&&(t.dispose(),this._buffers[qe.o.PositionKind]=null),t=this._buffers[qe.o.NormalKind],t&&(t.dispose(),this._buffers[qe.o.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),null===(e=this._drawWrapper)||void 0===e||e.dispose()}_processEdgeForAdjacencies(e,t,i,n,s){return e===i&&t===n||e===n&&t===i?0:e===n&&t===s||e===s&&t===n?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,n,s){const r=1e-10;return e.equalsWithEpsilon(i,r)&&t.equalsWithEpsilon(n,r)||e.equalsWithEpsilon(n,r)&&t.equalsWithEpsilon(i,r)?0:e.equalsWithEpsilon(n,r)&&t.equalsWithEpsilon(s,r)||e.equalsWithEpsilon(s,r)&&t.equalsWithEpsilon(n,r)?1:e.equalsWithEpsilon(s,r)&&t.equalsWithEpsilon(i,r)||e.equalsWithEpsilon(i,r)&&t.equalsWithEpsilon(s,r)?2:-1}_checkEdge(e,t,i,n,s){let r;r=void 0===t||o.P.Dot(i[e],i[t])<this._epsilon,r&&this.createLine(n,s,this._linesPositions.length/3)}createLine(e,t,i){this._linesPositions.push(e.x,e.y,e.z,e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z),this._linesNormals.push(t.x,t.y,t.z,-1,t.x,t.y,t.z,1,e.x,e.y,e.z,-1,e.x,e.y,e.z,1),this._linesIndices.push(i,i+1,i+2,i,i+2,i+3)}_tessellateTriangle(e,t,i,n){const s=(e,t,i)=>{i>=0&&t.push(i);for(let i=0;i<e.length;++i)t.push(e[i][0])};let r=0;e[1].length>=e[0].length&&e[1].length>=e[2].length?r=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(r=2);for(let t=0;t<3;++t)t===r?e[t].sort(((e,t)=>e[1]<t[1]?-1:e[1]>t[1]?1:0)):e[t].sort(((e,t)=>e[1]>t[1]?-1:e[1]<t[1]?1:0));const o=[],a=[];s(e[r],o,-1);const l=o.length;for(let o=r+2;o>=r+1;--o)s(e[o%3],a,o!==r+2?n[i[t+(o+1)%3]]:-1);const h=a.length;i.push(n[i[t+r]],o[0],a[0]),i.push(n[i[t+(r+1)%3]],a[h-1],o[l-1]);const c=l<=h,u=c?l:h,d=c?h:l,p=c?l-1:h-1,f=c?0:1;let _=l+h-2,m=0,g=0;const v=c?o:a,y=c?a:o;let x=0;for(;_-- >0;){let e;f?i.push(v[m],y[g]):i.push(y[g],v[m]),x+=u,x>=d&&m<p?(e=v[++m],x-=d):e=y[++g],i.push(e)}i[t+0]=i[i.length-3],i[t+1]=i[i.length-2],i[t+2]=i[i.length-1],i.length=i.length-3}_generateEdgesLinesAlternate(){var e,t,i,n,s,r,a,l,h,c;const u=this._source.getVerticesData(qe.o.PositionKind);let d=this._source.getIndices();if(!d||!u)return;Array.isArray(d)||(d=Array.from(d));const p=null===(t=null===(e=this._options)||void 0===e?void 0:e.useFastVertexMerger)||void 0===t||t,f=p?Math.round(-Math.log(null!==(n=null===(i=this._options)||void 0===i?void 0:i.epsilonVertexMerge)&&void 0!==n?n:1e-6)/Math.log(10)):null!==(r=null===(s=this._options)||void 0===s?void 0:s.epsilonVertexMerge)&&void 0!==r?r:1e-6,_=[],m=[];if(p){const e={};for(let t=0;t<u.length;t+=3){const i=u[t+0],n=u[t+1],s=u[t+2],r=i.toFixed(f)+"|"+n.toFixed(f)+"|"+s.toFixed(f);if(void 0!==e[r])_.push(e[r]);else{const i=t/3;e[r]=i,_.push(i),m.push(i)}}}else for(let e=0;e<u.length;e+=3){const t=u[e+0],i=u[e+1],n=u[e+2];let s=!1;for(let r=0;r<e&&!s;r+=3){const e=u[r+0],o=u[r+1],a=u[r+2];if(Math.abs(t-e)<f&&Math.abs(i-o)<f&&Math.abs(n-a)<f){_.push(r/3),s=!0;break}}s||(_.push(e/3),m.push(e/3))}if(null===(a=this._options)||void 0===a?void 0:a.applyTessellation){const e=null!==(h=null===(l=this._options)||void 0===l?void 0:l.epsilonVertexAligned)&&void 0!==h?h:1e-6,t=[];for(let i=0;i<d.length;i+=3){let n;for(let s=0;s<3;++s){const r=_[d[i+s]],o=_[d[i+(s+1)%3]],a=_[d[i+(s+2)%3]];if(r===o)continue;const l=u[3*r+0],h=u[3*r+1],c=u[3*r+2],p=u[3*o+0],f=u[3*o+1],g=u[3*o+2],v=Math.sqrt((p-l)*(p-l)+(f-h)*(f-h)+(g-c)*(g-c));for(let d=0;d<m.length-1;d++){const _=m[d];if(_===r||_===o||_===a)continue;const y=u[3*_+0],x=u[3*_+1],b=u[3*_+2],T=Math.sqrt((y-l)*(y-l)+(x-h)*(x-h)+(b-c)*(b-c)),S=Math.sqrt((y-p)*(y-p)+(x-f)*(x-f)+(b-g)*(b-g));Math.abs(T+S-v)<e&&(n||(n={index:i,edgesPoints:[[],[],[]]},t.push(n)),n.edgesPoints[s].push([_,T]))}}}for(let e=0;e<t.length;++e){const i=t[e];this._tessellateTriangle(i.edgesPoints,i.index,d,_)}t.length=0}const g={};for(let e=0;e<d.length;e+=3){let t;for(let i=0;i<3;++i){let n=_[d[e+i]],s=_[d[e+(i+1)%3]];const r=_[d[e+(i+2)%3]];if(n===s||(n===r||s===r)&&(null===(c=this._options)||void 0===c?void 0:c.removeDegeneratedTriangles))continue;if(o.jp.Vector3[0].copyFromFloats(u[3*n+0],u[3*n+1],u[3*n+2]),o.jp.Vector3[1].copyFromFloats(u[3*s+0],u[3*s+1],u[3*s+2]),o.jp.Vector3[2].copyFromFloats(u[3*r+0],u[3*r+1],u[3*r+2]),t||(o.jp.Vector3[1].subtractToRef(o.jp.Vector3[0],o.jp.Vector3[3]),o.jp.Vector3[2].subtractToRef(o.jp.Vector3[1],o.jp.Vector3[4]),t=o.P.Cross(o.jp.Vector3[3],o.jp.Vector3[4]),t.normalize()),n>s){const e=n;n=s,s=e}const a=n+"_"+s,l=g[a];l?l.done||(o.P.Dot(t,l.normal)<this._epsilon&&this.createLine(o.jp.Vector3[0],o.jp.Vector3[1],this._linesPositions.length/3),l.done=!0):g[a]={normal:t,done:!1,index:e,i}}}for(const e in g){const t=g[e];if(!t.done){const e=_[d[t.index+t.i]],i=_[d[t.index+(t.i+1)%3]];o.jp.Vector3[0].copyFromFloats(u[3*e+0],u[3*e+1],u[3*e+2]),o.jp.Vector3[1].copyFromFloats(u[3*i+0],u[3*i+1],u[3*i+2]),this.createLine(o.jp.Vector3[0],o.jp.Vector3[1],this._linesPositions.length/3)}}const v=this._source.getScene().getEngine();this._buffers[qe.o.PositionKind]=new qe.o(v,this._linesPositions,qe.o.PositionKind,!1),this._buffers[qe.o.NormalKind]=new qe.o(v,this._linesNormals,qe.o.NormalKind,!1,!1,4),this._buffersForInstances[qe.o.PositionKind]=this._buffers[qe.o.PositionKind],this._buffersForInstances[qe.o.NormalKind]=this._buffers[qe.o.NormalKind],this._ib=v.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}_generateEdgesLines(){const e=this._source.getVerticesData(qe.o.PositionKind),t=this._source.getIndices();if(!t||!e)return;const i=new Array,n=new Array;let s,r;for(s=0;s<t.length;s+=3){r=new tg;const a=t[s],l=t[s+1],h=t[s+2];r.p0=new o.P(e[3*a],e[3*a+1],e[3*a+2]),r.p1=new o.P(e[3*l],e[3*l+1],e[3*l+2]),r.p2=new o.P(e[3*h],e[3*h+1],e[3*h+2]);const c=o.P.Cross(r.p1.subtract(r.p0),r.p2.subtract(r.p1));c.normalize(),n.push(c),i.push(r)}for(s=0;s<i.length;s++){r=i[s];for(let e=s+1;e<i.length;e++){const n=i[e];if(3===r.edgesConnectedCount)break;if(3===n.edgesConnectedCount)continue;const o=t[3*e],a=t[3*e+1],l=t[3*e+2];for(let i=0;i<3;i++){let h=0;if(void 0===r.edges[i]){switch(i){case 0:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p0,r.p1,n.p0,n.p1,n.p2):this._processEdgeForAdjacencies(t[3*s],t[3*s+1],o,a,l);break;case 1:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p1,r.p2,n.p0,n.p1,n.p2):this._processEdgeForAdjacencies(t[3*s+1],t[3*s+2],o,a,l);break;case 2:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p2,r.p0,n.p0,n.p1,n.p2):this._processEdgeForAdjacencies(t[3*s+2],t[3*s],o,a,l)}if(-1!==h&&(r.edges[i]=e,n.edges[h]=s,r.edgesConnectedCount++,n.edgesConnectedCount++,3===r.edgesConnectedCount))break}}}}for(s=0;s<i.length;s++){const e=i[s];this._checkEdge(s,e.edges[0],n,e.p0,e.p1),this._checkEdge(s,e.edges[1],n,e.p1,e.p2),this._checkEdge(s,e.edges[2],n,e.p2,e.p0)}const a=this._source.getScene().getEngine();this._buffers[qe.o.PositionKind]=new qe.o(a,this._linesPositions,qe.o.PositionKind,!1),this._buffers[qe.o.NormalKind]=new qe.o(a,this._linesNormals,qe.o.NormalKind,!1,!1,4),this._buffersForInstances[qe.o.PositionKind]=this._buffers[qe.o.PositionKind],this._buffersForInstances[qe.o.NormalKind]=this._buffers[qe.o.NormalKind],this._ib=a.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}isReady(){return this._lineShader.isReady(this._source,this._source.hasInstances&&this.customInstances.length>0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera)return void this._lineShader._setDrawWrapper(t);const i=this._source.hasInstances&&this.customInstances.length>0,n=i||this._source.hasThinInstances;let s=0;if(n)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 e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!e.isFrozen){let t=0;for(let i=0;i<s;++i)this.customInstances.data[i].copyToArray(e.instancesData,t),t+=16;e.instancesBuffer.updateDirectly(e.instancesData,0,s)}}else s=this._source.thinInstanceCount;const r=e.getEngine();this._lineShader._preBind(),1!==this._source.edgesColor.a?r.setAlphaMode(2):r.setAlphaMode(0),r.bindBuffers(n?this._buffersForInstances:this._buffers,this._ib,this._lineShader.getEffect()),e.resetCachedMaterial(),this._lineShader.setColor4("color",this._source.edgesColor),e.activeCamera.mode===Mt.V.ORTHOGRAPHIC_CAMERA?this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForOrthographic):this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForPerspective),this._lineShader.setFloat("aspectRatio",r.getAspectRatio(e.activeCamera)),this._lineShader.bind(this._source.getWorldMatrix()),r.drawElementsType(cs.F.TriangleFillMode,0,this._indicesCount,s),this._lineShader.unbind(),n&&r.unbindInstanceAttributes(),this._source.getScene()._activeMeshesFrozen||this.customInstances.reset(),this._lineShader._setDrawWrapper(t)}}class ng extends ig{constructor(e,t=.95,i=!1){super(e,t,i,!1),this._generateEdgesLines()}_generateEdgesLines(){const e=this._source.getVerticesData(qe.o.PositionKind),t=this._source.getIndices();if(!t||!e)return;const i=o.jp.Vector3[0],n=o.jp.Vector3[1],s=t.length-1;for(let r=0,a=0;r<s;r+=2,a+=4)o.P.FromArrayToRef(e,3*t[r],i),o.P.FromArrayToRef(e,3*t[r+1],n),this.createLine(i,n,a);const r=this._source.getScene().getEngine();this._buffers[qe.o.PositionKind]=new qe.o(r,this._linesPositions,qe.o.PositionKind,!1),this._buffers[qe.o.NormalKind]=new qe.o(r,this._linesNormals,qe.o.NormalKind,!1,!1,4),this._ib=r.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}}class sg extends Xc{constructor(e,t,i,n,s,r){super(e,i,n,s,r),this._beforeCompositionPostProcesses=[],this._internalTextureDirty=!1,this.enabled=!1,this.renderTargetTexture=null,this.renderTargetTexture=t}_createCompositionEffect(){this.imageProcessingPostProcess=new Wi("prePassComposition",1,null,void 0,this._engine),this.imageProcessingPostProcess._updateParameters()}_checkSize(){const e=this._engine.getRenderWidth(!0),t=this._engine.getRenderHeight(!0),i=this.getRenderWidth(),n=this.getRenderHeight();i===e&&n===t||(this.resize({width:e,height:t}),this._internalTextureDirty=!0)}updateCount(e,t,i){super.updateCount(e,t,i),this._internalTextureDirty=!0}_resetPostProcessChain(){this._beforeCompositionPostProcesses.length=0}dispose(){const e=this._scene;if(super.dispose(),e&&e.prePassRenderer){const t=e.prePassRenderer.renderTargets.indexOf(this);-1!==t&&e.prePassRenderer.renderTargets.splice(t,1)}this.imageProcessingPostProcess&&this.imageProcessingPostProcess.dispose(),this.renderTargetTexture&&(this.renderTargetTexture._prePassRenderTarget=null),this._outputPostProcess&&(this._outputPostProcess.autoClear=!0,this._outputPostProcess.restoreDefaultInputTexture())}}class rg{getIndex(e){return this._textureIndices[e]}get samples(){return this.defaultRT.samples}set samples(e){this.defaultRT.samples=e}get useSpecificClearForDepthTexture(){return this._useSpecificClearForDepthTexture}set useSpecificClearForDepthTexture(e){this._useSpecificClearForDepthTexture!==e&&(this._useSpecificClearForDepthTexture=e,this._isDirty=!0)}getRenderTarget(){return this._currentTarget}_setRenderTarget(e){e?this._currentTarget=e:(this._currentTarget=this.defaultRT,this._engine.currentRenderPassId=this._currentTarget.renderPassId)}get currentRTisSceneRT(){return this._currentTarget===this.defaultRT}_refreshGeometryBufferRendererLink(){if(this.doNotUseGeometryRendererFallback)this._geometryBuffer&&this._geometryBuffer._unlinkPrePassRenderer(),this._geometryBuffer=null,this._scene.disableGeometryBufferRenderer();else{if(this._geometryBuffer=this._scene.enableGeometryBufferRenderer(),!this._geometryBuffer)return void(this.doNotUseGeometryRendererFallback=!0);this._geometryBuffer._linkPrePassRenderer(this)}}get enabled(){return this._enabled}constructor(e){this.excludedSkinnedMesh=[],this.excludedMaterials=[],this.mrtCount=0,this._mrtTypes=[],this._mrtFormats=[],this._mrtLayout=[],this._mrtNames=[],this._textureIndices=[],this._useSpecificClearForDepthTexture=!1,this._isDirty=!0,this._effectConfigurations=[],this.doNotUseGeometryRendererFallback=!0,this.renderTargets=[],this._clearColor=new a.HE(0,0,0,0),this._clearDepthColor=new a.HE(1e8,0,0,1),this._enabled=!1,this._needsCompositionForThisPass=!1,this.disableGammaTransform=!1,this._scene=e,this._engine=e.getEngine();let t=0;if(this._engine._caps.textureFloat&&this._engine._caps.textureFloatLinearFiltering?t=1:this._engine._caps.textureHalfFloat&&this._engine._caps.textureHalfFloatLinearFiltering&&(t=2),1!==t)for(let e=0;e<rg.TextureFormats.length;++e)1===rg.TextureFormats[e].type&&(rg.TextureFormats[5].type=t);rg._SceneComponentInitialization(this._scene),this.defaultRT=this._createRenderTarget("sceneprePassRT",null),this._currentTarget=this.defaultRT}_createRenderTarget(e,t){const i=new sg(e,t,{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},0,this._scene,{generateMipMaps:!1,generateStencilBuffer:this._engine.isStencilEnable,defaultType:0,types:[],drawOnlyOnFirstAttachmentByDefault:!0});return this.renderTargets.push(i),i}get isSupported(){return this._scene.getEngine().getCaps().drawBuffersExtension}bindAttachmentsForEffect(e,t){const i=t.getMaterial(),n=i&&i.isPrePassCapable,s=i&&-1!==this.excludedMaterials.indexOf(i);this.enabled&&this._currentTarget.enabled&&(e._multiTarget&&n&&!s?this._engine.bindAttachments(this._multiRenderAttachments):(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment(),this._geometryBuffer&&this.currentRTisSceneRT&&!s&&this._geometryBuffer.renderList.push(t.getRenderingMesh())))}_reinitializeAttachments(){const e=[],t=[!1],i=[!1],n=[!0];for(let s=0;s<this.mrtCount;s++)e.push(!0),s>0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),n.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(n)}_resetLayout(){for(let e=0;e<rg.TextureFormats.length;e++)this._textureIndices[rg.TextureFormats[e].purpose]=-1;this._textureIndices[4]=0,this._mrtLayout=[4],this._mrtTypes=[rg.TextureFormats[4].type],this._mrtFormats=[rg.TextureFormats[4].format],this._mrtNames=[rg.TextureFormats[4].name],this.mrtCount=1}_updateGeometryBufferLayout(){if(this._refreshGeometryBufferRendererLink(),this._geometryBuffer){this._geometryBuffer._resetLayout();const e=[];for(let t=0;t<this._mrtLayout.length;t++)e.push(!1);this._geometryBuffer._linkInternalTexture(this.defaultRT.getInternalTexture());const t=[{prePassConstant:5,geometryBufferConstant:Cm.DEPTH_TEXTURE_TYPE},{prePassConstant:6,geometryBufferConstant:Cm.NORMAL_TEXTURE_TYPE},{prePassConstant:1,geometryBufferConstant:Cm.POSITION_TEXTURE_TYPE},{prePassConstant:3,geometryBufferConstant:Cm.REFLECTIVITY_TEXTURE_TYPE},{prePassConstant:2,geometryBufferConstant:Cm.VELOCITY_TEXTURE_TYPE}];for(let i=0;i<t.length;i++){const n=this._mrtLayout.indexOf(t[i].prePassConstant);-1!==n&&(this._geometryBuffer._forceTextureType(t[i].geometryBufferConstant,n),e[n]=!0)}this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(e))}}restoreAttachments(){this.enabled&&this._currentTarget.enabled&&this._defaultAttachments&&(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment())}_beforeDraw(e,t,i){this._isDirty&&this._update(),this._enabled&&this._currentTarget.enabled&&(this._geometryBuffer&&(this._geometryBuffer.renderList=[]),this._setupOutputForThisPass(this._currentTarget,e))}_prepareFrame(e,t,i){e.renderTargetTexture?e.renderTargetTexture._prepareFrame(this._scene,t,i,e.renderTargetTexture.useCameraPostProcesses):this._postProcessesSourceForThisPass.length?this._scene.postProcessManager._prepareFrame():this._engine.restoreDefaultFramebuffer()}setCustomOutput(e){const t=this._postProcessesSourceForThisPass[0];return!!t&&(t.inputTexture=e.renderTarget,!0)}_renderPostProcesses(e,t){var i;const n=this._postProcessesSourceForThisPass[0],s=n?n.inputTexture:e.renderTargetTexture?e.renderTargetTexture.renderTarget:null;let r=this._currentTarget._beforeCompositionPostProcesses;this._needsCompositionForThisPass&&(r=r.concat([this._currentTarget.imageProcessingPostProcess])),r.length&&(this._scene.postProcessManager._prepareFrame(null===(i=this._currentTarget.renderTarget)||void 0===i?void 0:i.texture,r),this._scene.postProcessManager.directRender(r,s,!1,t))}_afterDraw(e,t){this._enabled&&this._currentTarget.enabled&&(this._prepareFrame(this._currentTarget,e,t),this._renderPostProcesses(this._currentTarget,e))}_clear(){this._enabled&&this._currentTarget.enabled&&(this._bindFrameBuffer(this._currentTarget),this._engine.bindAttachments(this._clearAttachments),this._engine.clear(this._clearColor,!0,!1,!1),this._useSpecificClearForDepthTexture&&(this._engine.bindAttachments(this._clearDepthAttachments),this._engine.clear(this._clearDepthColor,!0,!1,!1)),this._engine.bindAttachments(this._defaultAttachments))}_bindFrameBuffer(e){if(this._enabled&&this._currentTarget.enabled){this._currentTarget._checkSize();const e=this._currentTarget.renderTarget;e&&this._engine.bindFramebuffer(e)}}_setEnabled(e){this._enabled=e}_setRenderTargetEnabled(e,t){e.enabled=t,t||this._unlinkInternalTexture(e)}addEffectConfiguration(e){for(let t=0;t<this._effectConfigurations.length;t++)if(this._effectConfigurations[t].name===e.name)return this._effectConfigurations[t];return this._effectConfigurations.push(e),e}_enable(){const e=this.mrtCount;for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled&&this._enableTextures(this._effectConfigurations[e].texturesRequired);for(let t=0;t<this.renderTargets.length;t++){this.mrtCount===e&&this.renderTargets[t].count===this.mrtCount||this.renderTargets[t].updateCount(this.mrtCount,{types:this._mrtTypes,formats:this._mrtFormats},this._mrtNames.concat("prePass_DepthBuffer")),this.renderTargets[t]._resetPostProcessChain();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled&&(!this._effectConfigurations[e].postProcess&&this._effectConfigurations[e].createPostProcess&&this._effectConfigurations[e].createPostProcess(),this._effectConfigurations[e].postProcess&&this.renderTargets[t]._beforeCompositionPostProcesses.push(this._effectConfigurations[e].postProcess))}this._reinitializeAttachments(),this._setEnabled(!0),this._updateGeometryBufferLayout()}_disable(){this._setEnabled(!1);for(let e=0;e<this.renderTargets.length;e++)this._setRenderTargetEnabled(this.renderTargets[e],!1);this._resetLayout();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled=!1}_getPostProcessesSource(e,t){if(t)return t._postProcesses;if(e.renderTargetTexture){if(e.renderTargetTexture.useCameraPostProcesses){const t=e.renderTargetTexture.activeCamera?e.renderTargetTexture.activeCamera:this._scene.activeCamera;return t?t._postProcesses:[]}return e.renderTargetTexture.postProcesses?e.renderTargetTexture.postProcesses:[]}return this._scene.activeCamera?this._scene.activeCamera._postProcesses:[]}_setupOutputForThisPass(e,t){const i=t&&this._scene.activeCameras&&!!this._scene.activeCameras.length&&0!==this._scene.activeCameras.indexOf(t);this._postProcessesSourceForThisPass=this._getPostProcessesSource(e,t),this._postProcessesSourceForThisPass=this._postProcessesSourceForThisPass.filter((e=>null!=e)),this._scene.autoClear=!0;const n=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!n&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),r=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||n,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),r?o=r:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:s&&(o=s),this._bindFrameBuffer(e),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;e<this._effectConfigurations.length;e++)if(this._effectConfigurations[e].enabled&&this._effectConfigurations[e].needsImageProcessing)return!0;return!1}_hasImageProcessing(e){var t;let i=!1;if(e)for(let n=0;n<e.length;n++)if("ImageProcessingPostProcess"===(null===(t=e[n])||void 0===t?void 0:t.getClassName())){i=!0;break}return i}_getFirstPostProcess(e){for(let t=0;t<e.length;t++)if(null!==e[t])return e[t];return null}markAsDirty(){this._isDirty=!0}_enableTextures(e){this._scene.needsPreviousWorldMatrices=!1;for(let t=0;t<e.length;t++){const i=e[t];-1===this._textureIndices[i]&&(this._textureIndices[i]=this._mrtLayout.length,this._mrtLayout.push(i),this._mrtTypes.push(rg.TextureFormats[i].type),this._mrtFormats.push(rg.TextureFormats[i].format),this._mrtNames.push(rg.TextureFormats[i].name),this.mrtCount++),2===i&&(this._scene.needsPreviousWorldMatrices=!0)}}_update(){this._disable();let e,t=!1;this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._scene._depthPeelingRenderer&&this._scene.useOrderIndependentTransparency&&(this._scene._depthPeelingRenderer.setPrePassRenderer(this),t=!0);for(let e=0;e<this._scene.materials.length;e++)this._scene.materials[e].setPrePassRenderer(this)&&(t=!0);t&&this._setRenderTargetEnabled(this.defaultRT,!0);for(let i=0;i<this.renderTargets.length;i++){if(this.renderTargets[i].renderTargetTexture)e=this._getPostProcessesSource(this.renderTargets[i]);else{const t=this._scene.activeCamera;if(!t)continue;e=t._postProcesses}if(e&&(e=e.filter((e=>null!=e)),e)){for(let n=0;n<e.length;n++)e[n].setPrePassRenderer(this)&&(this._setRenderTargetEnabled(this.renderTargets[i],!0),t=!0);this._hasImageProcessing(e)&&(this._scene.imageProcessingConfiguration.applyByPostProcess=!0)}}this._markAllMaterialsAsPrePassDirty(),this._isDirty=!1,t&&this._enable()}_markAllMaterialsAsPrePassDirty(){const e=this._scene.materials;for(let t=0;t<e.length;t++)e[t].markAsDirty(cs.F.PrePassDirtyFlag)}dispose(){for(let e=this.renderTargets.length-1;e>=0;e--)this.renderTargets[e].dispose();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].dispose&&this._effectConfigurations[e].dispose()}}rg._SceneComponentInitialization=e=>{throw(0,Zl.S)("PrePassRendererSceneComponent")},rg.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(k.x.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),k.x.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new rg(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,_.Y.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},k.x.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class og{constructor(e){this.name=ve.l.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(ve.l.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(ve.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(ve.l.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(ve.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(ve.l.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(ve.l.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(ve.l.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(ve.l.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,n){if(!n)return;const s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(n,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}}rg._SceneComponentInitialization=e=>{let t=e._getComponent(ve.l.NAME_PREPASSRENDERER);t||(t=new og(e),e._addComponent(t))};si.v.IncludesShadersStore.fibonacci="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{\nreturn vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));\n}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{\nvec2 f=Golden2dSeq(i,float(sampleCount));\nreturn vec2(sqrt(f.x),TWO_PI*f.y);\n}",i(4022);si.v.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];\nuniform float diffusionD[5];\nuniform float filterRadii[5];";si.v.ShadersStore.subSurfaceScatteringPixelShader="#include<fibonacci>\n#include<helperFunctions>\n#include<subSurfaceScatteringFunctions>\n#include<diffusionProfile>\nvarying vec2 vUV;\nuniform vec2 texelSize;\nuniform sampler2D textureSampler;\nuniform sampler2D irradianceSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D albedoSampler;\nuniform vec2 viewportSize;\nuniform float metersPerUnit;\nconst float LOG2_E=1.4426950408889634;\nconst float SSS_PIXELS_PER_SAMPLE=4.;\nconst int _SssSampleBudget=40;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{\nvec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; \n}\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{\nu=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));\nfloat n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));\nfloat r=x*rcpS;\nfloat rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);\n}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));\nfloat area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{\nfloat scale =rcp(float(n));\nfloat offset=rcp(float(n))*0.5;\nfloat sinPhase,cosPhase;\nsinPhase=sin(phase);\ncosPhase=cos(phase);\nvec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);\nfloat r=bdp.x;\nfloat rcpPdf=bdp.y;\nfloat phi=SampleDiskGolden(i,n).y;\nfloat sinPhi,cosPhi;\nsinPhi=sin(phi);\ncosPhi=cos(phi);\nfloat sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);\nvec2 position; \nfloat xy2;\nposition=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;\nxy2 =r*r;\nvec4 textureSample=texture2D(irradianceSampler,position);\nfloat viewZ=texture2D(depthSampler,position).r;\nvec3 irradiance =textureSample.rgb;\nif (testLightingForSSS(textureSample.a))\n{\nfloat relZ=viewZ-centerPosVS.z;\nvec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);\ntotalIrradiance+=weight*irradiance;\ntotalWeight +=weight;\n}\nelse\n{\n}\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);\nvec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;\nint diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));\nfloat centerDepth =0.;\nvec4 inputColor=texture2D(textureSampler,vUV);\nbool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);\nif (passedStencilTest)\n{\ncenterDepth=texture2D(depthSampler,vUV).r;\n}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;\nreturn;\n}\nfloat distScale =1.;\nvec3 S =diffusionS[diffusionProfileIndex];\nfloat d =diffusionD[diffusionProfileIndex];\nfloat filterRadius=filterRadii[diffusionProfileIndex];\nvec2 centerPosNDC=vUV;\nvec2 cornerPosNDC=vUV+0.5*texelSize;\nvec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));\nfloat unitsPerMm=rcp(mmPerUnit);\nfloat unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);\nfloat pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;\nfloat filterArea =PI*Sq(filterRadius*pixelsPerMm);\nint sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));\nint sampleBudget=_SssSampleBudget;\nint texturingMode=0;\nvec3 albedo =texture2D(albedoSampler,vUV).rgb;\nif (distScale==0. || sampleCount<1)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);\ngl_FragColor=vec4(green,1.0);\nreturn;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);\nreturn;\n}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);\nvec3 blue=vec3(0.,0.,1.);\ngl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);\nreturn;\n#endif\nfloat phase=0.;\nint n=min(sampleCount,sampleBudget);\nvec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);\nvec3 totalWeight =vec3(0.);\nfor (int i=0; i<n; i++)\n{\nEvaluateSample(i,n,S,d,centerPosVS,mmPerUnit,pixelsPerMm,\nphase,totalIrradiance,totalWeight);\n}\ntotalWeight=max(totalWeight,HALF_MIN);\ngl_FragColor=vec4(inputColor.rgb+albedo*max(totalIrradiance/totalWeight,vec3(0.0)),1.);\n}";class ag extends ni.D{getClassName(){return"SubSurfaceScatteringPostProcess"}constructor(e,t,i,n=null,s,r,o,a=0){super(e,"subSurfaceScattering",["texelSize","viewportSize","metersPerUnit"],["diffusionS","diffusionD","filterRadii","irradianceSampler","depthSampler","albedoSampler"],i,n,s||Ce.x.BILINEAR_SAMPLINGMODE,r,o,null,a,"postprocess",void 0,!0),this._scene=t,this.updateEffect(),this.onApplyObservable.add((e=>{if(!t.prePassRenderer||!t.subSurfaceConfiguration)return void _.Y.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");const i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)}))}}class lg{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=ve.l.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new a.Wo(1,1,1)),this._scene=e,lg._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return _.Y.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t<this._ssDiffusionS.length/3;t++)if(this._ssDiffusionS[3*t]===e.r&&this._ssDiffusionS[3*t+1]===e.g&&this._ssDiffusionS[3*t+2]===e.b)return t;return this._ssDiffusionS.push(e.r,e.b,e.g),this._ssDiffusionD.push(Math.max(Math.max(e.r,e.b),e.g)),this._ssFilterRadii.push(this.getDiffusionProfileParameters(e)),this.ssDiffusionProfileColors.push(e),this._ssDiffusionD.length-1}createPostProcess(){return this.postProcess=new ag("subSurfaceScattering",this._scene,1,null,void 0,this._scene.getEngine()),this.postProcess.autoClear=!1,this.postProcess}clearAllDiffusionProfiles(){this._ssDiffusionD=[],this._ssDiffusionS=[],this._ssFilterRadii=[],this.ssDiffusionProfileColors=[]}dispose(){this.clearAllDiffusionProfiles(),this.postProcess&&this.postProcess.dispose()}getDiffusionProfileParameters(e){const t=Math.max(e.r,e.g,e.b);return this._sampleBurleyDiffusionProfile(.997,t)}_sampleBurleyDiffusionProfile(e,t){const i=1+4*(e=1-e)*(2*e+Math.sqrt(1+4*e*e)),n=Math.pow(i,-1/3),s=1+i*n*n+n;return 3*Math.log(s/(4*e))*t}}lg._SceneComponentInitialization=e=>{throw(0,Zl.S)("SubSurfaceSceneComponent")},n.p.AddParser(ve.l.NAME_SUBSURFACE,((e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,n=e.ssDiffusionProfileColors.length;i<n;i++){const n=e.ssDiffusionProfileColors[i];t.subSurfaceConfiguration.addDiffusionProfile(new a.Wo(n.r,n.g,n.b))}})),Object.defineProperty(k.x.prototype,"subSurfaceConfiguration",{get:function(){return this._subSurfaceConfiguration},set:function(e){e&&this.enablePrePassRenderer()&&(this._subSurfaceConfiguration=e)},enumerable:!0,configurable:!0}),k.x.prototype.enableSubSurfaceForPrePass=function(){if(this._subSurfaceConfiguration)return this._subSurfaceConfiguration;const e=this.enablePrePassRenderer();return e?(this._subSurfaceConfiguration=new lg(this),e.addEffectConfiguration(this._subSurfaceConfiguration),this._subSurfaceConfiguration):null},k.x.prototype.disableSubSurfaceForPrePass=function(){this._subSurfaceConfiguration&&(this._subSurfaceConfiguration.dispose(),this._subSurfaceConfiguration=null)};class hg{constructor(e){this.name=ve.l.NAME_PREPASSRENDERER,this.scene=e}register(){}serialize(e){if(!this.scene.subSurfaceConfiguration)return;const t=this.scene.subSurfaceConfiguration.ssDiffusionProfileColors;e.ssDiffusionProfileColors=[];for(let i=0;i<t.length;i++)e.ssDiffusionProfileColors.push({r:t[i].r,g:t[i].g,b:t[i].b})}addFromContainer(){}removeFromContainer(){this.scene.prePassRenderer&&this.scene.subSurfaceConfiguration&&this.scene.subSurfaceConfiguration.clearAllDiffusionProfiles()}rebuild(){}dispose(){}}lg._SceneComponentInitialization=e=>{let t=e._getComponent(ve.l.NAME_SUBSURFACE);t||(t=new hg(e),e._addComponent(t))};si.v.ShadersStore.outlinePixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";si.v.ShadersStore.outlineVertexShader="attribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<clipPlaneVertexDeclaration>\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\nvec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);\ngl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<clipPlaneVertex>\n#include<logDepthVertex>\n}\n",k.x.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new cg(this)),this._outlineRenderer},Object.defineProperty(Nt.Kj.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(Nt.Kj.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class cg{constructor(e){this.name=ve.l.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(ve.l.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(ve.l.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e<this._passIdForDrawWrapper.length;++e)this._engine.releaseRenderPassId(this._passIdForDrawWrapper[e])}render(e,t,i=!1,n){n=null!=n?n:this._passIdForDrawWrapper[0];const s=this.scene,r=s.getEngine(),o=r.getCaps().instancedArrays&&(null!==t.visibleInstances[e._id]&&void 0!==t.visibleInstances[e._id]||e.getRenderingMesh().hasThinInstances);if(!this.isReady(e,o,n))return;const a=e.getMesh(),l=a._internalAbstractMeshDataInfo._actAsRegularMesh?a:null,h=e.getRenderingMesh(),c=l||h,u=e.getMaterial();if(!u||!s.activeCamera)return;const d=e._getDrawWrapper(n),p=Ps.q.GetEffect(d);if(r.enableEffect(d),u.useLogarithmicDepth&&p.setFloat("logarithmicDepthConstant",2/(Math.log(s.activeCamera.maxZ+1)/Math.LN2)),p.setFloat("offset",i?0:h.outlineWidth),p.setColor4("color",i?h.overlayColor:h.outlineColor,i?h.overlayAlpha:u.alpha),p.setMatrix("viewProjection",s.getTransformMatrix()),p.setMatrix("world",c.getWorldMatrix()),h.useBones&&h.computeBonesUsingShaders&&h.skeleton&&p.setMatrices("mBones",h.skeleton.getTransformMatrices(h)),h.morphTargetManager&&h.morphTargetManager.isUsingTextureForTargets&&h.morphTargetManager._bind(p),La.G.BindMorphTargetParameters(h,p),o||h._bind(e,p,u.fillMode),u&&u.needAlphaTesting()){const e=u.getAlphaTestTexture();e&&(p.setTexture("diffuseSampler",e),p.setMatrix("diffuseMatrix",e.getTextureMatrix()))}(0,Ga.an)(p,u,s),r.setZOffset(-this.zOffset),r.setZOffsetUnits(-this.zOffsetUnits),h._processRendering(c,e,p,u.fillMode,t,o,((e,t)=>{p.setMatrix("world",t)})),r.setZOffset(0),r.setZOffsetUnits(0)}isReady(e,t,i){i=null!=i?i:this._passIdForDrawWrapper[0];const n=[],s=[qe.o.PositionKind,qe.o.NormalKind],r=e.getMesh(),o=e.getMaterial();if(!o)return!1;const a=r.getScene();o.needAlphaTesting()&&(n.push("#define ALPHATEST"),r.isVerticesDataPresent(qe.o.UVKind)&&(s.push(qe.o.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(qe.o.UV2Kind)&&(s.push(qe.o.UV2Kind),n.push("#define UV2"))),o.useLogarithmicDepth&&n.push("#define LOGARITHMICDEPTH"),(0,Ga.lK)(o,a,n),r.useBones&&r.computeBonesUsingShaders?(s.push(qe.o.MatricesIndicesKind),s.push(qe.o.MatricesWeightsKind),r.numBoneInfluencers>4&&(s.push(qe.o.MatricesIndicesExtraKind),s.push(qe.o.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0");const l=r.morphTargetManager;let h=0;l&&l.numInfluencers>0&&(h=l.numInfluencers,n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),La.G.PrepareAttributesForMorphTargetsInfluencers(s,r,h)),t&&(n.push("#define INSTANCES"),La.G.PushAttributesForInstances(s),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));const c=e._getDrawWrapper(i,!0),u=c.defines,d=n.join("\n");if(u!==d){const e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,Ga.qx)(e),c.setEffect(this.scene.getEngine().createEffect("outline",s,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return c.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const n=t.getMaterial();n&&n.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(cg._StencilReference),this._engine.setStencilFunctionReference(cg._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),n&&n.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const e=this._engine.getAlphaMode(),n=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=n}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}cg._StencilReference=4;var ug,dg=i(1617);class pg{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!!(null===(e=this.vertexBuffers)||void 0===e?void 0:e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new r.y$,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 Ih.H({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new Ih.H({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||0===e)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||0===e)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;null===(e=this._depthEffectWrapper)||void 0===e||e.dispose(),null===(t=this._thicknessEffectWrapper)||void 0===t||t.dispose()}}class fg extends pg{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 _g{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){const e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,n,s,o,a=1,l=6,h=1,c=6,u=!1,d=null,p=!0,f=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new r.y$,this._name=e,this._scene=t,this._camera=d,this._engine=t.getEngine(),this._width=i,this._height=n,this._blurTextureSizeX=s,this._blurTextureSizeY=o,this._textureType=a,this._textureFormat=l,this._blurTextureType=h,this._blurTextureFormat=c,this._useStandardBlur=u,this._generateDepthBuffer=p,this._samples=f,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==o,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new Ce.x(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=Ce.x.CLAMP_ADDRESSMODE,this._texture.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,n,s,r=!1){const a=this._scene.getEngine(),l=new o.FM(Math.floor(this._blurTextureSizeX/n),Math.floor(this._blurTextureSizeY/n)),h=1===t&&a.getCaps().textureFloatLinearFiltering||2===t&&a.getCaps().textureHalfFloatLinearFiltering,c=this._engine.createRenderTargetTexture({width:l.x,height:l.y},{generateMipMaps:!1,type:t,format:i,samplingMode:h?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${s}`}),u=c.texture;u.incrementReferences();const d=new Ce.x(null,this._scene);if(d.name="rttBlurred"+s,d._texture=u,d.wrapU=Ce.x.CLAMP_ADDRESSMODE,d.wrapV=Ce.x.CLAMP_ADDRESSMODE,d.anisotropicFilteringLevel=1,r){const n=new ni.D("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.externalTextureSamplerBinding=!0,n.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",n.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=Ce.x.CLAMP_ADDRESSMODE,e.texture.wrapV=Ce.x.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n);const s=new ni.D("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.onApplyObservable.add((e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Ce.x.CLAMP_ADDRESSMODE,e.texture.wrapV=Ce.x.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s),n.autoClear=!1,s.autoClear=!1;const r=[];for(let e=0;e<2*this._blurNumIterations;++e)r[e]=1&e?s:n;return[c,d,r]}{const n=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],s=new ni.D("BilateralBlurX","fluidRenderingBilateralBlur",n,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Ce.x.CLAMP_ADDRESSMODE,e.texture.wrapV=Ce.x.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s);const r=new ni.D("BilateralBlurY","fluidRenderingBilateralBlur",n,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.onApplyObservable.add((e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Ce.x.CLAMP_ADDRESSMODE,e.texture.wrapV=Ce.x.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r),s.autoClear=!1,r.autoClear=!1;const o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?r:s;return[c,d,o]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))}_getProjectedParticleConstant(){var e,t;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((null!==(t=null===(e=this._camera)||void 0===e?void 0:e.fov)&&void 0!==t?t:45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){var e,t,i,n;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),null===(e=this._rt)||void 0===e||e.dispose(),this._rt=null,null===(t=this._texture)||void 0===t||t.dispose(),this._texture=null,null===(i=this._rtBlur)||void 0===i||i.dispose(),this._rtBlur=null,null===(n=this._textureBlurred)||void 0===n||n.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(ug||(ug={}));class mg{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 a.Wo(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new o.P(-2,-1,1).normalize(),this._debugFeature=ug.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 r.y$,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=null!=t?t:e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new o.y3,this._depthClearColor=new a.HE(1e6,1e6,1e6,1),this._thicknessClearColor=new a.HE(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 n=null!==(e=this._depthMapSize)&&void 0!==e?e:this._engine.getRenderWidth(),s=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new _g("Depth",this._scene,n,s,n,s,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const e=null!==(t=this._diffuseMapSize)&&void 0!==t?t:this._engine.getRenderWidth(),i=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new _g("Diffuse",this._scene,e,i,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const r=null!==(i=this._thicknessMapSize)&&void 0!==i?i:this._engine.getRenderWidth(),o=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new _g("Thickness",this._scene,r,o,r,o,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&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"],n=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const r=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new o.FM(1/r.getSize().width,1/r.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(null!==(e=this._environmentMap)&&void 0!==e?e:this._scene.environmentTexture)&&(n.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(n.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(n.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),n.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),n.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===ug.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===ug.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),n.push("debugSampler"),this._debugFeature!==ug.DepthTexture&&this._debugFeature!==ug.DepthBlurredTexture||s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new ni.D("FluidRendering","fluidRenderingRender",i,n,1,null,2,t,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add((e=>{var i,n,s,r,o,l,h,c,u,d,p,f,_,m,g,v,y,x,b,T,S,E,C;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),t.isWebGPU&&e.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(r=null===(s=this._depthRenderTarget.textureBlur)||void 0===s?void 0:s.getInternalTexture())&&void 0!==r?r:null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(n=null===(i=this._depthRenderTarget.texture)||void 0===i?void 0:i.getInternalTexture())&&void 0!==n?n:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(c=null===(h=this._diffuseRenderTarget.textureBlur)||void 0===h?void 0:h.getInternalTexture())&&void 0!==c?c:null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(l=null===(o=this._diffuseRenderTarget.texture)||void 0===o?void 0:o.getInternalTexture())&&void 0!==l?l:null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),t.isWebGPU&&e.setTextureSampler("bgDepthSamplerSampler",null!==(u=this._bgDepthTexture)&&void 0!==u?u:null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(_=null===(f=this._thicknessRenderTarget.textureBlur)||void 0===f?void 0:f.getInternalTexture())&&void 0!==_?_:null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(p=null===(d=this._thicknessRenderTarget.texture)||void 0===d?void 0:d.getInternalTexture())&&void 0!==p?p:null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){const i=null!==(m=this._environmentMap)&&void 0!==m?m:this._scene.environmentTexture;i&&(e.setTexture("reflectionSampler",i),t.isWebGPU&&e.setTextureSampler("reflectionSamplerSampler",null!==(g=null==i?void 0:i.getInternalTexture())&&void 0!==g?g:null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",a),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let i=null;switch(this._debugFeature){case ug.DepthTexture:i=this._depthRenderTarget.texture;break;case ug.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case ug.ThicknessTexture:i=null!==(y=null===(v=this._thicknessRenderTarget)||void 0===v?void 0:v.texture)&&void 0!==y?y:null;break;case ug.ThicknessBlurredTexture:i=(null===(x=this._thicknessRenderTarget)||void 0===x?void 0:x.enableBlur)?null!==(T=null===(b=this._thicknessRenderTarget)||void 0===b?void 0:b.textureBlur)&&void 0!==T?T:null:null!==(E=null===(S=this._thicknessRenderTarget)||void 0===S?void 0:S.texture)&&void 0!==E?E:null;break;case ug.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==ug.Normals&&(e.setTexture("debugSampler",i),t.isWebGPU&&e.setTextureSampler("debugSamplerSampler",null!==(C=null==i?void 0:i.getInternalTexture())&&void 0!==C?C:null))}}))}_clearTargets(){var e,t,i;(null===(e=this._depthRenderTarget)||void 0===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)),(null===(t=this._diffuseRenderTarget)||void 0===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)),(null===(i=this._thicknessRenderTarget)||void 0===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,n,s,r,o;if(this._needInitialization||!e.isReady())return;const a=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),(null===(t=this._depthRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(i=this._diffuseRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(n=this._thicknessRenderTarget)||void 0===n?void 0:n.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),null===(s=this._depthRenderTarget)||void 0===s||s.applyBlurPostProcesses(),null===(r=this._diffuseRenderTarget)||void 0===r||r.applyBlurPostProcesses(),null===(o=this._thicknessRenderTarget)||void 0===o||o.applyBlurPostProcesses(),a&&this._engine.bindFramebuffer(a)}dispose(e=!1){var t,i,n,s;e||(null===(t=this._depthRenderTarget)||void 0===t||t.dispose(),this._depthRenderTarget=null,null===(i=this._diffuseRenderTarget)||void 0===i||i.dispose(),this._diffuseRenderTarget=null,null===(n=this._thicknessRenderTarget)||void 0===n||n.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),null===(s=this._renderPostProcess)||void 0===s||s.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class gg extends pg{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,n=!0;switch(t){case"velocity":i=3;break;case"offset":n=!1}this._vertexBuffers[t]=new qe.o(this._engine,e[t],t,!0,!1,i,n)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new Ih.H({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){var e,t;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new qe.o(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&null!==(t=null===(e=this._diffuseEffectWrapper)||void 0===e?void 0:e.effect.isReady())&&void 0!==t&&t}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)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()),null!==this._particleSize&&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(),null===(e=this._diffuseEffectWrapper)||void 0===e||e.dispose();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();this._vertexBuffers={}}}var vg;si.v.ShadersStore.copyTextureToTexturePixelShader="uniform float conversion;\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#include<helperFunctions>\nvoid main(void) \n{\nvec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {\ncolor=toLinearSpace(color);\n} else if (conversion==2.) {\ncolor=toGammaSpace(color);\n}\ngl_FragColor=color;\n#endif\n}\n",function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(vg||(vg={}));class yg{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new Ih.I(e),this._effectWrapper=new Ih.H({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=vg.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const n=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&n&&(this._engine.depthCullingState.depthFunc=n),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class xg{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,n=1){this._engine=e,this._copyTextureToTexture=new yg(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:n,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil")}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}si.v.ShadersStore.fluidRenderingParticleDepthVertexShader="attribute vec3 position;\nattribute vec2 offset;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 size;\nvarying vec2 uv;\nvarying vec3 viewPos;\nvarying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;\nvarying float velocityNorm;\n#endif\nvoid main(void) {\nvec3 cornerPos;\ncornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\ncornerPos.z=0.0;\nviewPos=(view*vec4(position,1.0)).xyz;\ngl_Position=projection*vec4(viewPos+cornerPos,1.0);\nuv=offset;\nsphereRadius=size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";si.v.ShadersStore.fluidRenderingParticleDepthPixelShader="uniform mat4 projection;\nvarying vec2 uv;\nvarying vec3 viewPos;\nvarying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid main(void) {\nvec3 normal;\nnormal.xy=uv*2.0-1.0;\nfloat r2=dot(normal.xy,normal.xy);\nif (r2>1.0) discard;\nnormal.z=sqrt(1.0-r2);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);\nvec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";si.v.ShadersStore.fluidRenderingParticleThicknessVertexShader="attribute vec3 position;\nattribute vec2 offset;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 size;\nvarying vec2 uv;\nvoid main(void) {\nvec3 cornerPos;\ncornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\ncornerPos.z=0.0;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;\ngl_Position=projection*vec4(viewPos,1.0);\nuv=offset;\n}\n";si.v.ShadersStore.fluidRenderingParticleThicknessPixelShader="uniform float particleAlpha;\nvarying vec2 uv;\nvoid main(void) {\nvec3 normal;\nnormal.xy=uv*2.0-1.0;\nfloat r2=dot(normal.xy,normal.xy);\nif (r2>1.0) discard;\nfloat thickness=sqrt(1.0-r2);\nglFragColor=vec4(vec3(particleAlpha*thickness),1.0);\n}\n";si.v.ShadersStore.fluidRenderingParticleDiffuseVertexShader="attribute vec3 position;\nattribute vec2 offset;\nattribute vec4 color;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 size;\nvarying vec2 uv;\nvarying vec3 diffuseColor;\nvoid main(void) {\nvec3 cornerPos;\ncornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\ncornerPos.z=0.0;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;\ngl_Position=projection*vec4(viewPos,1.0);\nuv=offset;\ndiffuseColor=color.rgb;\n}\n";si.v.ShadersStore.fluidRenderingParticleDiffusePixelShader="uniform float particleAlpha;\nvarying vec2 uv;\nvarying vec3 diffuseColor;\nvoid main(void) {\nvec3 normal;\nnormal.xy=uv*2.0-1.0;\nfloat r2=dot(normal.xy,normal.xy);\nif (r2>1.0) discard;\nglFragColor=vec4(diffuseColor,1.0);\n}\n";si.v.ShadersStore.fluidRenderingBilateralBlurPixelShader="uniform sampler2D textureSampler;\nuniform int maxFilterSize;\nuniform vec2 blurDir;\nuniform float projectedParticleConstant;\nuniform float depthThreshold;\nvarying vec2 vUV;\nvoid main(void) {\nfloat depth=textureLod(textureSampler,vUV,0.).x;\nif (depth>=1e6 || depth<=0.) {\nglFragColor=vec4(vec3(depth),1.);\nreturn;\n}\nint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));\nfloat sigma=float(filterSize)/3.0;\nfloat two_sigma2=2.0*sigma*sigma;\nfloat sigmaDepth=depthThreshold/3.0;\nfloat two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;\nfloat sum=0.;\nfloat wsum=0.;\nfloat sumVel=0.;\nfor (int x=-filterSize; x<=filterSize; ++x) {\nvec2 coords=vec2(x);\nvec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;\nfloat r=dot(coords,coords);\nfloat w=exp(-r/two_sigma2);\nfloat rDepth=sampleDepthVel.r-depth;\nfloat wd=exp(-rDepth*rDepth/two_sigmaDepth2);\nsum+=sampleDepthVel.r*w*wd;\nsumVel+=sampleDepthVel.g*w*wd;\nwsum+=w*wd;\n}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);\n}\n";si.v.ShadersStore.fluidRenderingStandardBlurPixelShader="uniform sampler2D textureSampler;\nuniform int filterSize;\nuniform vec2 blurDir;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 s=textureLod(textureSampler,vUV,0.);\nif (s.r==0.) {\nglFragColor=vec4(0.,0.,0.,1.);\nreturn;\n}\nfloat sigma=float(filterSize)/3.0;\nfloat twoSigma2=2.0*sigma*sigma;\nvec4 sum=vec4(0.);\nfloat wsum=0.;\nfor (int x=-filterSize; x<=filterSize; ++x) {\nvec2 coords=vec2(x);\nvec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);\nfloat w=exp(-coords.x*coords.x/twoSigma2);\nsum+=sampl*w;\nwsum+=w;\n}\nsum/=wsum;\nglFragColor=vec4(sum.rgb,1.);\n}\n";function bg(e){return!!e.particleSystem}si.v.ShadersStore.fluidRenderingRenderPixelShader="/* disable_uniformity_analysis */\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;\nuniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;\nuniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;\nuniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform mat4 viewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 invProjectionMatrix;\nuniform vec2 texelSize;\nuniform vec3 dirLight;\nuniform float cameraFar;\nuniform float density;\nuniform float refractionStrength;\nuniform float fresnelClamp;\nuniform float specularPower;\nvarying vec2 vUV;\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {\nvec4 ndc;\nndc.xy=texCoord*2.0-1.0;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;\nvec4 eyePos=invProjectionMatrix*ndc;\neyePos.xyz/=eyePos.w;\nreturn eyePos.xyz;\n}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {\nfloat depth=textureLod(depthSampler,texCoord,0.).x;\nreturn computeViewPosFromUVDepth(texCoord,depth);\n}\nvoid main(void) {\nvec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);\nif (color.r>0.999 && color.g>0.999) {\nglFragColor=texture2D(textureSampler,texCoord);\n}\n#else\nglFragColor=vec4(color.rgb,1.);\nif (color.r<0.001 && color.g<0.001 && color.b<0.001) {\nglFragColor=texture2D(textureSampler,texCoord);\n}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;\nfloat depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;\nfloat depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;\ndepthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\nglFragColor=backColor;\nreturn;\n}\nvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);\nvec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;\nvec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;\nvec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));\nif (abs(ddx.z)>abs(ddx2.z)) {\nddx=ddx2;\n}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));\nif (abs(ddy.z)>abs(ddy2.z)) {\nddy=ddy2;\n}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {\nnormal=vec3(0.,0.,-1.);\n}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);\nreturn;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));\nvec3 H =normalize(lightDir-rayDir);\nfloat specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;\nglFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);\nreturn;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);\nvec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\nvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);\nvec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);\nfloat fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);\nvec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;\nfinalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);\n}\n",Object.defineProperty(k.x.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),k.x.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new Sg(this)),this._fluidRenderer},k.x.prototype.disableFluidRenderer=function(){var e;null===(e=this._fluidRenderer)||void 0===e||e.dispose(),this._fluidRenderer=null};class Tg{constructor(e){this.name=ve.l.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(ve.l.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(ve.l.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._prepareRendering()}_afterCameraDraw(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._render(e)}rebuild(){this.scene._fluidRenderer&&(this.scene.disableFluidRenderer(),this.scene.enableFluidRenderer())}dispose(){this.scene.disableFluidRenderer()}}class Sg{static _SceneComponentInitialization(e){let t=e._getComponent(ve.l.NAME_FLUIDRENDERER);t||(t=new Tg(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,Sg._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((()=>{this._initialize()}))}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,n){const s=new fg(this._scene,e);s.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)),i||(i=new mg(this._scene,n),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)),void 0!==t&&(i.generateDiffuseTexture=t);const r={object:s,targetRenderer:i};return this.renderObjects.push(r),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),r}addCustomParticles(e,t,i,n,s){const r=new gg(this._scene,e,t);r.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)),n||(n=new mg(this._scene,s),this.targetRenderers.push(n)),n._onUseVelocityChanged.hasObservers()||n._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)),void 0!==i&&(n.generateDiffuseTexture=i);const o={object:r,targetRenderer:n};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return-1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort(((e,t)=>e.object.priority<t.object.priority?-1:e.object.priority>t.object.priority?1:0))}_removeUnusedTargetRenderers(){const e={};for(let t=0;t<this.renderObjects.length;++t){const i=this.renderObjects[t].targetRenderer;e[this.targetRenderers.indexOf(i)]=!0}let t=!1;const i=[];for(let n=0;n<this.targetRenderers.length;++n)e[n]?i.push(this.targetRenderers[n]):(this.targetRenderers[n].dispose(),t=!0);return t&&(this.targetRenderers.length=0,this.targetRenderers.push(...i)),t}_getParticleSystemIndex(e){for(let t=0;t<this.renderObjects.length;++t){const i=this.renderObjects[t].object;if(bg(i)&&i.particleSystem===e)return t}return-1}_initialize(){for(let e=0;e<this.targetRenderers.length;++e)this.targetRenderers[e].dispose();const e=new Map;for(let t=0;t<this.targetRenderers.length;++t){const i=this.targetRenderers[t];if(i._initialize(),i.camera&&i._renderPostProcess){let n=e.get(i.camera);n||(n=[[],{}],e.set(i.camera,n)),n[0].push(i),i.camera.attachPostProcess(i._renderPostProcess,t)}}let t=e.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,n=e.get(t),s=t._getFirstPostProcess();if(!s)continue;const[r,o]=n;s.onSizeChangedObservable.add((()=>{var e;s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,r[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`);for(const t of r){const i=null===(e=t._thicknessRenderTarget)||void 0===e?void 0:e.renderTarget,n=null==i?void 0:i.texture;if(i&&n){const e=n.width+"_"+n.height;let t=o[e];t||(t=o[e]=new xg(this._engine,n.width,n.height)),t.depthRTWrapper._shareDepth(i)}}}))}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,n=this._cameras.get(t)[1],s=e.get(t);if(s)for(const e in n)s[1][e]||n[e].dispose();else for(const e in n)n[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t<this.renderObjects.length;++t){const i=this.renderObjects[t];let n=e.get(i.targetRenderer);void 0===n&&(n=0),e.set(i.targetRenderer,Math.max(n,i.object.particleSize))}e.forEach(((e,t)=>{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization)return void this._initialize()}_render(e){var t;for(let t=0;t<this.targetRenderers.length;++t)e&&this.targetRenderers[t].camera!==e||this.targetRenderers[t]._clearTargets();const i=this._cameras.keys();for(let n=i.next();!0!==n.done;n=i.next()){const i=n.value,s=this._cameras.get(i);if(e&&i!==e)continue;const r=i._getFirstPostProcess();if(!r)continue;const o=null===(t=r.inputTexture)||void 0===t?void 0:t.depthStencilTexture;if(o){const[e,t]=s;for(const t of e)t._bgDepthTexture=o;for(const e in t)t[e].copy(o)}}for(let t=0;t<this.renderObjects.length;++t){const i=this.renderObjects[t];e&&i.targetRenderer.camera!==e||i.targetRenderer._render(i.object)}}dispose(){this._engine.onResizeObservable.remove(this._onEngineResizeObserver),this._onEngineResizeObserver=null;for(let e=0;e<this.renderObjects.length;++e)this.renderObjects[e].object.dispose();for(let e=0;e<this.targetRenderers.length;++e)this.targetRenderers[e].dispose();this._cameras.forEach((e=>{const t=e[1];for(const e in t)t[e].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class Eg{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,n,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=n||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,e<t?this._direction=1:(this._direction=-1,this._toIndex=e,this._fromIndex=t),this.cellIndex=e,this._time=0}stopAnimation(){this._animationStarted=!1}_animate(e){this._animationStarted&&(this._time+=e,this._time>this._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex<this._fromIndex)&&(this._loopAnimation?this.cellIndex=this._direction>0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class Cg extends Eg{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new r.y$,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new a.HE(1,1,1,1),this.position=o.P.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,n,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,n,this._endAnimation)}dispose(){for(let e=0;e<this._manager.sprites.length;e++)this._manager.sprites[e]==this&&this._manager.sprites.splice(e,1);this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}serialize(){const e={};return e.name=this.name,e.position=this.position.asArray(),e.color=this.color.asArray(),e.width=this.width,e.height=this.height,e.angle=this.angle,e.cellIndex=this.cellIndex,e.cellRef=this.cellRef,e.invertU=this.invertU,e.invertV=this.invertV,e.disposeWhenFinishedAnimating=this.disposeWhenFinishedAnimating,e.isPickable=this.isPickable,e.isVisible=this.isVisible,e.useAlphaForPicking=this.useAlphaForPicking,e.animationStarted=this.animationStarted,e.fromIndex=this.fromIndex,e.toIndex=this.toIndex,e.loopAnimation=this.loopAnimation,e.delay=this.delay,e}static Parse(e,t){const i=new Cg(e.name,t);return i.position=o.P.FromArray(e.position),i.color=a.HE.FromArray(e.color),i.width=e.width,i.height=e.height,i.angle=e.angle,i.cellIndex=e.cellIndex,i.cellRef=e.cellRef,i.invertU=e.invertU,i.invertV=e.invertV,i.disposeWhenFinishedAnimating=e.disposeWhenFinishedAnimating,i.isPickable=e.isPickable,i.isVisible=e.isVisible,i.useAlphaForPicking=e.useAlphaForPicking,i.fromIndex=e.fromIndex,i.toIndex=e.toIndex,i.loopAnimation=e.loopAnimation,i.delay=e.delay,e.animationStarted&&i.playAnimation(i.fromIndex,i.toIndex,i.loopAnimation,i.delay),i}}k.x.prototype._internalPickSprites=function(e,t,i,n){if(!bn.p)return null;let s=null;if(!n){if(!this.activeCamera)return null;n=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let r=0;r<this.spriteManagers.length;r++){const o=this.spriteManagers[r];if(!o.isPickable)continue;const a=o.intersects(e,n,t,i);if(a&&a.hit&&(i||null==s||!(a.distance>=s.distance))&&(s=a,i))break}return s||new bn.p},k.x.prototype._internalMultiPickSprites=function(e,t,i){if(!bn.p)return null;let n=new Array;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s<this.spriteManagers.length;s++){const r=this.spriteManagers[s];if(!r.isPickable)continue;const o=r.multiIntersects(e,i,t);null!==o&&(n=n.concat(o))}return n},k.x.prototype.pickSprite=function(e,t,i,n,s){if(!this._tempSpritePickingRay)return null;this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,s);const r=this._internalPickSprites(this._tempSpritePickingRay,i,n,s);return r&&(r.ray=this.createPickingRayInCameraSpace(e,t,s)),r},k.x.prototype.pickSpriteWithRay=function(e,t,i,n){if(!this._tempSpritePickingRay)return null;if(!n){if(!this.activeCamera)return null;n=this.activeCamera}Yt.z.TransformToRef(e,n.getViewMatrix(),this._tempSpritePickingRay);const s=this._internalPickSprites(this._tempSpritePickingRay,t,i,n);return s&&(s.ray=e),s},k.x.prototype.multiPickSprite=function(e,t,i,n){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,n),this._internalMultiPickSprites(this._tempSpritePickingRay,i,n)},k.x.prototype.multiPickSpriteWithRay=function(e,t,i){if(!this._tempSpritePickingRay)return null;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}return Yt.z.TransformToRef(e,i.getViewMatrix(),this._tempSpritePickingRay),this._internalMultiPickSprites(this._tempSpritePickingRay,t,i)},k.x.prototype.setPointerOverSprite=function(e){this._pointerOverSprite!==e&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(10,c.V.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=e,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(9,c.V.CreateNewFromSprite(this._pointerOverSprite,this)))},k.x.prototype.getPointerOverSprite=function(){return this._pointerOverSprite};class Ag{constructor(e){this.name=ve.l.NAME_SPRITE,this.scene=e,this.scene.spriteManagers=new Array,this.scene._tempSpritePickingRay=Yt.z?Yt.z.Zero():null,this.scene.onBeforeSpritesRenderingObservable=new r.y$,this.scene.onAfterSpritesRenderingObservable=new r.y$,this._spritePredicate=e=>!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(ve.l.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(ve.l.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(ve.l.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,n,s){const r=this.scene.pickSprite(t,i,this._spritePredicate,n,s);return r&&(r.ray=e?e.ray:null),r}_pointerMove(e,t,i,n,s){const r=this.scene;return n?r.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,r.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(r.setPointerOverSprite(i.pickedSprite),!r.doNotHandleCursors&&s&&(r._pointerOverSprite&&r._pointerOverSprite.actionManager&&r._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=r._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=r.hoverCursor)):r.setPointerOverSprite(null),i}_pointerDown(e,t,i,n){const s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,n.button){case 0:i.pickedSprite.actionManager.processTrigger(2,c.V.CreateNewFromSprite(i.pickedSprite,s,n));break;case 1:i.pickedSprite.actionManager.processTrigger(4,c.V.CreateNewFromSprite(i.pickedSprite,s,n));break;case 2:i.pickedSprite.actionManager.processTrigger(3,c.V.CreateNewFromSprite(i.pickedSprite,s,n))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,c.V.CreateNewFromSprite(i.pickedSprite,s,n))}return i}_pointerUp(e,t,i,n,s){const r=this.scene;if(r.spriteManagers&&r.spriteManagers.length>0){const i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,c.V.CreateNewFromSprite(i.pickedSprite,r,n)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,c.V.CreateNewFromSprite(i.pickedSprite,r,n)),s&&i.pickedSprite.actionManager.processTrigger(6,c.V.CreateNewFromSprite(i.pickedSprite,r,n)))),r._pickedDownSprite&&r._pickedDownSprite.actionManager&&r._pickedDownSprite!==i.pickedSprite&&r._pickedDownSprite.actionManager.processTrigger(16,c.V.CreateNewFromSprite(r._pickedDownSprite,r,n)))}return i}}i(689);si.v.ShadersStore.spritesPixelShader="uniform bool alphaTest;\nvarying vec4 vColor;\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {\nvec2 res=vec2(textureSize(diffuseSampler,0));\nuv=uv*res;\nvec2 seam=floor(uv+0.5);\nuv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);\nreturn uv/res;\n}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);\nfloat fAlphaTest=float(alphaTest);\nif (fAlphaTest != 0.)\n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}";si.v.ShadersStore.spritesVertexShader="attribute vec4 position;\nattribute vec2 options;\nattribute vec2 offsets;\nattribute vec2 inverts;\nattribute vec4 cellInfo;\nattribute vec4 color;\nuniform mat4 view;\nuniform mat4 projection;\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=offsets.xy;\ncornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));\nvec2 uvPlace=cellInfo.xy;\nvec2 uvSize=cellInfo.zw;\nvUV.x=uvPlace.x+uvSize.x*uvOffset.x;\nvUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class Pg{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,n=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=n,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new qe.l(e,this._vertexData,!0,this._vertexBufferSize);const s=this._buffer.createVertexBuffer(qe.o.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),r=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o,a=6;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new qe.l(e,t,!1,2),o=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else o=this._buffer.createVertexBuffer("offsets",a,2,this._vertexBufferSize,this._useInstancing),a+=2;const l=this._buffer.createVertexBuffer("inverts",a,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",a+2,4,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer(qe.o.ColorKind,a+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[qe.o.PositionKind]=s,this._vertexBuffers.options=r,this._vertexBuffers.offsets=o,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[qe.o.ColorKind]=c,this._createEffects()}_createEffects(){var e,t,i,n;null===(e=this._drawWrapperBase)||void 0===e||e.dispose(),null===(t=this._drawWrapperFog)||void 0===t||t.dispose(),null===(i=this._drawWrapperDepth)||void 0===i||i.dispose(),null===(n=this._drawWrapperFogDepth)||void 0===n||n.dispose(),this._drawWrapperBase=new Ps.q(this._engine),this._drawWrapperFog=new Ps.q(this._engine),this._drawWrapperDepth=new Ps.q(this._engine,!1),this._drawWrapperFogDepth=new Ps.q(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);const s=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[qe.o.PositionKind,"options","offsets","inverts","cellInfo",qe.o.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],s),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[qe.o.PositionKind,"options","offsets","inverts","cellInfo",qe.o.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],s+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,n,s=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let r=this._drawWrapperBase,o=this._drawWrapperDepth,a=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(r=this._drawWrapperFog,o=this._drawWrapperFogDepth,a=!0);const l=r.effect;if(!l.isReady())return;const h=this._engine,c=!(!this._scene||!this._scene.useRightHandedSystem),u=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length);let p=0,f=!0;for(let i=0;i<d;i++){const n=e[i];n&&n.isVisible&&(f=!1,n._animate(t),this._appendSpriteVertex(p++,n,0,0,u,c,s),this._useInstancing||(this._appendSpriteVertex(p++,n,1,0,u,c,s),this._appendSpriteVertex(p++,n,1,1,u,c,s),this._appendSpriteVertex(p++,n,0,1,u,c,s)))}if(f)return;this._buffer.update(this._vertexData);const _=!!h.depthCullingState.cull,m=h.depthCullingState.zOffset,g=h.depthCullingState.zOffsetUnits;if(h.setState(_,m,!1,!1,void 0,void 0,g),h.enableEffect(r),l.setTexture("diffuseSampler",this.texture),l.setMatrix("view",i),l.setMatrix("projection",n),a){const e=this._scene;l.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),l.setColor3("vFogColor",e.fogColor)}this._useVAO?(this._vertexArrayObject||(this._vertexArrayObject=h.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,l)),h.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):h.bindBuffers(this._vertexBuffers,this._indexBuffer,l),h.depthCullingState.depthFunc=h.useReverseDepthBuffer?518:515,this.disableDepthWrite||(l.setBool("alphaTest",!0),h.setColorWrite(!1),h.enableEffect(o),this._useInstancing?h.drawArraysType(7,0,4,p):h.drawElementsType(0,0,p/4*6),h.enableEffect(r),h.setColorWrite(!0),l.setBool("alphaTest",!1)),h.setAlphaMode(this.blendMode),this._useInstancing?h.drawArraysType(7,0,4,p):h.drawElementsType(0,0,p/4*6),this.autoResetAlpha&&h.setAlphaMode(0),c&&this._scene.getEngine().setState(_,m,!1,!0,void 0,void 0,g),h.unbindInstanceAttributes()}_appendSpriteVertex(e,t,i,n,s,r,o){let a=e*this._vertexBufferSize;if(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===n?n=this._epsilon:1===n&&(n=1-this._epsilon),o)o(t,s);else{t.cellIndex||(t.cellIndex=0);const e=s.width/this.cellWidth,i=t.cellIndex/e>>0;t._xOffset=(t.cellIndex-i*e)*this.cellWidth/s.width,t._yOffset=i*this.cellHeight/s.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[a]=t.position.x,this._vertexData[a+1]=t.position.y,this._vertexData[a+2]=t.position.z,this._vertexData[a+3]=t.angle,this._vertexData[a+4]=t.width,this._vertexData[a+5]=t.height,this._useInstancing?a-=2:(this._vertexData[a+6]=i,this._vertexData[a+7]=n),this._vertexData[a+8]=r?t.invertU?0:1:t.invertU?1:0,this._vertexData[a+9]=t.invertV?1:0,this._vertexData[a+10]=t._xOffset,this._vertexData[a+11]=t._yOffset,this._vertexData[a+12]=t._xSize/s.width,this._vertexData[a+13]=t._ySize/s.height,this._vertexData[a+14]=t.color.r,this._vertexData[a+15]=t.color.g,this._vertexData[a+16]=t.color.b,this._vertexData[a+17]=t.color.a}_buildIndexBuffer(){const e=[];let t=0;for(let i=0;i<this._capacity;i++)e.push(t),e.push(t+1),e.push(t+2),e.push(t),e.push(t+2),e.push(t+3),t+=4;this._indexBuffer=this._engine.createIndexBuffer(e)}rebuild(){var e;this._indexBuffer&&this._buildIndexBuffer(),this._useVAO&&(this._vertexArrayObject=void 0),this._buffer._rebuild();for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild();null===(e=this._spriteBuffer)||void 0===e||e._rebuild()}dispose(){this._buffer&&(this._buffer.dispose(),this._buffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this.texture&&(this.texture.dispose(),this.texture=null),this._drawWrapperBase.dispose(),this._drawWrapperFog.dispose(),this._drawWrapperDepth.dispose(),this._drawWrapperFogDepth.dispose()}}class Rg{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get children(){return this.sprites}get scene(){return this._scene}get capacity(){return this._spriteRenderer.capacity}get texture(){return this._spriteRenderer.texture}set texture(e){e.wrapU=Ce.x.CLAMP_ADDRESSMODE,e.wrapV=Ce.x.CLAMP_ADDRESSMODE,this._spriteRenderer.texture=e,this._textureContent=null}get cellWidth(){return this._spriteRenderer.cellWidth}set cellWidth(e){this._spriteRenderer.cellWidth=e}get cellHeight(){return this._spriteRenderer.cellHeight}set cellHeight(e){this._spriteRenderer.cellHeight=e}get fogEnabled(){return this._spriteRenderer.fogEnabled}set fogEnabled(e){this._spriteRenderer.fogEnabled=e}get blendMode(){return this._spriteRenderer.blendMode}set blendMode(e){this._spriteRenderer.blendMode=e}get disableDepthWrite(){return this._disableDepthWrite}set disableDepthWrite(e){this._disableDepthWrite=e,this._spriteRenderer.disableDepthWrite=e}get pixelPerfect(){return this._spriteRenderer.pixelPerfect}set pixelPerfect(e){this._spriteRenderer.pixelPerfect=e,e&&3!==this.texture.samplingMode&&this.texture.updateSamplingMode(3)}constructor(e,t,i,n,s,o=.01,a=Ce.x.TRILINEAR_SAMPLINGMODE,l=!1,h=null){this.name=e,this.sprites=new Array,this.renderingGroupId=0,this.layerMask=268435455,this.isPickable=!1,this.metadata=null,this._wasDispatched=!1,this.onDisposeObservable=new r.y$,this._disableDepthWrite=!1,this._packedAndReady=!1,this._customUpdate=(e,t)=>{e.cellRef||(e.cellIndex=0);const i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},s||(s=A.l.LastCreatedScene),s._getComponent(ve.l.NAME_SPRITE)||s._addComponent(new Ag(s)),this._fromPacked=l,this._scene=s;const c=this._scene.getEngine();if(this._spriteRenderer=new Pg(c,i,o,s),n.width&&n.height)this.cellWidth=n.width,this.cellHeight=n.height;else{if(void 0===n)return void(this._spriteRenderer=null);this.cellWidth=n,this.cellHeight=n}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new Ce.x(t,s,!0,!1,a)),this._fromPacked&&this._makePacked(t,h)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if(e="string"==typeof t?JSON.parse(t):t,e.frames.length){const t={};for(let i=0;i<e.frames.length;i++){const n=e.frames[i];if("string"!=typeof Object.keys(n)[0])throw new Error("Invalid JSON Format. Check the frame values and make sure the name is the first parameter.");t[n[Object.keys(n)[0]]]=n}e.frames=t}const i=Reflect.ownKeys(e.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=e.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON from string. Spritesheet managed with constant cell size.")}else{const t=/\./g;let i;do{i=t.lastIndex,t.test(e)}while(t.lastIndex>0);const n=e.substring(0,i-1)+".json",s=()=>{_.Y.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},r=e=>{try{const t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};de.w1.LoadFile(n,r,void 0,void 0,!1,s)}}_checkTextureAlpha(e,t,i,n,s){if(!e.useAlphaForPicking||!this.texture)return!0;const r=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(r.width*r.height*4),this.texture.readPixels(0,0,this._textureContent));const a=o.jp.Vector3[0];a.copyFrom(t.direction),a.normalize(),a.scaleInPlace(i),a.addInPlace(t.origin);const l=(a.x-n.x)/(s.x-n.x)-.5,h=1-(a.y-n.y)/(s.y-n.y)-.5,c=e.angle,u=l*Math.cos(c)-h*Math.sin(c)+.5,d=l*Math.sin(c)+h*Math.cos(c)+.5,p=e._xOffset*r.width+u*e._xSize|0,f=e._yOffset*r.height+d*e._ySize|0;return this._textureContent[4*(p+f*r.width)+3]>.5}intersects(e,t,i,n){const s=Math.min(this.capacity,this.sprites.length),r=o.P.Zero(),a=o.P.Zero();let l=Number.MAX_VALUE,h=null;const c=o.jp.Vector3[0],u=o.jp.Vector3[1],d=t.getViewMatrix();let p=e,f=e;for(let t=0;t<s;t++){const s=this.sprites[t];if(s){if(i){if(!i(s))continue}else if(!s.isPickable)continue;if(o.P.TransformCoordinatesToRef(s.position,d,u),s.angle?(o.y3.TranslationToRef(-u.x,-u.y,0,o.jp.Matrix[1]),o.y3.TranslationToRef(u.x,u.y,0,o.jp.Matrix[2]),o.y3.RotationZToRef(s.angle,o.jp.Matrix[3]),o.jp.Matrix[1].multiplyToRef(o.jp.Matrix[3],o.jp.Matrix[4]),o.jp.Matrix[4].multiplyToRef(o.jp.Matrix[2],o.jp.Matrix[0]),p=e.clone(),o.P.TransformCoordinatesToRef(e.origin,o.jp.Matrix[0],p.origin),o.P.TransformNormalToRef(e.direction,o.jp.Matrix[0],p.direction)):p=e,r.copyFromFloats(u.x-s.width/2,u.y-s.height/2,u.z),a.copyFromFloats(u.x+s.width/2,u.y+s.height/2,u.z),p.intersectsBoxMinMax(r,a)){const e=o.P.Distance(u,p.origin);if(l>e){if(!this._checkTextureAlpha(s,p,e,r,a))continue;if(f=p,l=e,h=s,n)break}}}}if(h){const e=new bn.p;d.invertToRef(o.jp.Matrix[0]),e.hit=!0,e.pickedSprite=h,e.distance=l;const t=o.jp.Vector3[2];return t.copyFrom(f.direction),t.normalize(),t.scaleInPlace(l),f.origin.addToRef(t,c),e.pickedPoint=o.P.TransformCoordinates(c,o.jp.Matrix[0]),e}return null}multiIntersects(e,t,i){const n=Math.min(this.capacity,this.sprites.length),s=o.P.Zero(),r=o.P.Zero();let a;const l=[],h=o.jp.Vector3[0].copyFromFloats(0,0,0),c=o.jp.Vector3[1].copyFromFloats(0,0,0),u=t.getViewMatrix();for(let t=0;t<n;t++){const n=this.sprites[t];if(n){if(i){if(!i(n))continue}else if(!n.isPickable)continue;if(o.P.TransformCoordinatesToRef(n.position,u,c),s.copyFromFloats(c.x-n.width/2,c.y-n.height/2,c.z),r.copyFromFloats(c.x+n.width/2,c.y+n.height/2,c.z),e.intersectsBoxMinMax(s,r)){if(a=o.P.Distance(c,e.origin),!this._checkTextureAlpha(n,e,a,s,r))continue;const t=new bn.p;l.push(t),u.invertToRef(o.jp.Matrix[0]),t.hit=!0,t.pickedSprite=n,t.distance=a;const i=o.jp.Vector3[2];i.copyFrom(e.direction),i.normalize(),i.scaleInPlace(a),e.origin.addToRef(i,h),t.pickedPoint=o.P.TransformCoordinates(h,o.jp.Matrix[0])}}}return l}render(){if(this._fromPacked&&(!this._packedAndReady||!this._spriteMap||!this._cellData))return;const e=this._scene.getEngine().getDeltaTime();this._packedAndReady?this._spriteRenderer.render(this.sprites,e,this._scene.getViewMatrix(),this._scene.getProjectionMatrix(),this._customUpdate):this._spriteRenderer.render(this.sprites,e,this._scene.getViewMatrix(),this._scene.getProjectionMatrix())}rebuild(){var e;null===(e=this._spriteRenderer)||void 0===e||e.rebuild()}dispose(){if(this._spriteRenderer&&(this._spriteRenderer.dispose(),this._spriteRenderer=null),this._textureContent=null,this._scene.spriteManagers){const e=this._scene.spriteManagers.indexOf(this);this._scene.spriteManagers.splice(e,1)}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null}serialize(e=!1){const t={};t.name=this.name,t.capacity=this.capacity,t.cellWidth=this.cellWidth,t.cellHeight=this.cellHeight,t.fogEnabled=this.fogEnabled,t.blendMode=this.blendMode,t.disableDepthWrite=this.disableDepthWrite,t.pixelPerfect=this.pixelPerfect,this.texture&&(e?t.texture=this.texture.serialize():(t.textureUrl=this.texture.name,t.invertY=this.texture._invertY)),t.sprites=[];for(const e of this.sprites)t.sprites.push(e.serialize());return t.metadata=this.metadata,t}static Parse(e,t,i){const n=new Rg(e.name,"",e.capacity,{width:e.cellWidth,height:e.cellHeight},t);void 0!==e.fogEnabled&&(n.fogEnabled=e.fogEnabled),void 0!==e.blendMode&&(n.blendMode=e.blendMode),void 0!==e.disableDepthWrite&&(n.disableDepthWrite=e.disableDepthWrite),void 0!==e.pixelPerfect&&(n.pixelPerfect=e.pixelPerfect),void 0!==e.metadata&&(n.metadata=e.metadata),e.texture?n.texture=Ce.x.Parse(e.texture,t,i):e.textureName&&(n.texture=new Ce.x(i+e.textureUrl,t,!1,void 0===e.invertY||e.invertY));for(const t of e.sprites)Cg.Parse(t,n);return n}static ParseFromFileAsync(e,t,i,n=""){return new Promise(((s,r)=>{const o=new Kc.g;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),r=Rg.Parse(t,i||A.l.LastCreatedScene,n);e&&(r.name=e),s(r)}else r("Unable to load the sprite manager")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new Rg("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise(((n,s)=>{const r=new Kc.g;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){const s=JSON.parse(JSON.parse(r.responseText).jsonPayload),o=JSON.parse(s.spriteManager),a=Rg.Parse(o,t||A.l.LastCreatedScene,i);a.snippetId=e,n(a)}else s("Unable to load the snippet "+e)})),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()}))}}Rg.SnippetUrl="https://snippet.babylonjs.com",Rg.CreateFromSnippetAsync=Rg.ParseFromSnippetAsync;si.v.ShadersStore.spriteMapPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;\nvarying vec3 vPosition;\nvarying vec2 vUV;\nvarying vec2 tUV;\nuniform float time;\nuniform float spriteCount;\nuniform sampler2D spriteSheet;\nuniform vec2 spriteMapSize;\nuniform vec2 outputSize;\nuniform vec2 stageSize;\nuniform sampler2D frameMap;\nuniform sampler2D tileMaps[LAYERS];\nuniform sampler2D animationMap;\nuniform vec3 colorMul;\nfloat mt;\nconst float fdStep=1./4.;\nconst float aFrameSteps=1./MAX_ANIMATION_FRAMES;\nmat4 getFrameData(float frameID){\nfloat fX=frameID/spriteCount;\nreturn mat4(\ntexture2D(frameMap,vec2(fX,0.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*1.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*2.),0.),\nvec4(0.)\n);\n}\nvoid main(){\nvec4 color=vec4(0.);\nvec2 tileUV=fract(tUV);\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\nvec2 tileID=floor(tUV);\nvec2 sheetUnits=1./spriteMapSize;\nfloat spriteUnits=1./spriteCount;\nvec2 stageUnits=1./stageSize;\nfor(int i=0; i<LAYERS; i++) {\nfloat frameID;\n#define LAYER_ID_SWITCH\nvec4 animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,0.),0.);\nif(animationData.y>0.) {\nmt=mod(time*animationData.z,1.0);\nfor(float f=0.; f<MAX_ANIMATION_FRAMES; f++){\nif(animationData.y>mt){\nframeID=animationData.x;\nbreak;\n}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);\n}\n}\nmat4 frameData=getFrameData(frameID+0.5);\nvec2 frameSize=(frameData[0].zw)/spriteMapSize;\nvec2 offset=frameData[0].xy*sheetUnits;\nvec2 ratio=frameData[2].xy/frameData[0].zw;\nif (frameData[2].z==1.){\ntileUV.xy=tileUV.yx;\n}\nvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);\nif (i==0){\ncolor=nc;\n} else {\nfloat alpha=min(color.a+nc.a,1.0);\nvec3 mixed=mix(color.xyz,nc.xyz,nc.a);\ncolor=vec4(mixed,alpha);\n}\n}\ncolor.xyz*=colorMul;\ngl_FragColor=color;\n}";si.v.ShadersStore.spriteMapVertexShader="precision highp float;\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\nvarying vec3 vPosition;\nvarying vec2 vUV;\nvarying vec2 tUV;\nvarying vec2 stageUnits;\nvarying vec2 levelUnits;\nvarying vec2 tileID;\nuniform float time;\nuniform mat4 worldViewProjection;\nuniform vec2 outputSize;\nuniform vec2 stageSize;\nuniform vec2 spriteMapSize;\nuniform float stageScale;\nvoid main() {\nvec4 p=vec4( position,1. );\nvPosition=p.xyz;\nvUV=uv;\ntUV=uv*stageSize; \ngl_Position=worldViewProjection*p;\n}";class Mg{get spriteCount(){return this.sprites.length}get position(){return this._output.position}set position(e){this._output.position=e}get rotation(){return this._output.rotation}set rotation(e){this._output.rotation=e}get animationMap(){return this._animationMap}set animationMap(e){const t=e._texture._bufferView,i=this._createTileAnimationBuffer(t);this._animationMap.dispose(),this._animationMap=i,this._material.setTexture("animationMap",this._animationMap)}constructor(e,t,i,n,s){this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=n,n.stageSize=n.stageSize||new o.FM(1,1),n.outputSize=n.outputSize||n.stageSize,n.outputPosition=n.outputPosition||o.P.Zero(),n.outputRotation=n.outputRotation||o.P.Zero(),n.layerCount=n.layerCount||1,n.maxAnimationFrames=n.maxAnimationFrames||0,n.baseTile=n.baseTile||0,n.flipU=n.flipU||!1,n.colorMultiply=n.colorMultiply||new o.P(1,1,1),this._scene=s,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(let e=0;e<n.layerCount;e++)this._tileMaps.push(this._createTileBuffer(null,e));this._animationMap=this._createTileAnimationBuffer(null);const r=[];r.push("#define LAYERS "+n.layerCount),n.flipU&&r.push("#define FLIPU"),r.push(`#define MAX_ANIMATION_FRAMES ${n.maxAnimationFrames}.0`);const a=ds.Q.ShadersStore.spriteMapPixelShader;let l;if(s.getEngine()._features.supportSwitchCaseInShader){l="switch(i) {";for(let e=0;e<n.layerCount;e++)l+="case "+e+" : frameID = texture(tileMaps["+e+"], (tileID + 0.5) / stageSize, 0.).x;",l+="break;";l+="}"}else{l="";for(let e=0;e<n.layerCount;e++)l+=`if (${e} == i) { frameID = texture2D(tileMaps[${e}], (tileID + 0.5) / stageSize, 0.).x; }`}ds.Q.ShadersStore["spriteMap"+this.name+"PixelShader"]=a.replace("#define LAYER_ID_SWITCH",l),this._material=new us.j("spriteMap:"+this.name,this._scene,{vertex:"spriteMap",fragment:"spriteMap"+this.name},{defines:r,attributes:["position","normal","uv"],uniforms:["worldViewProjection","time","stageSize","outputSize","spriteMapSize","spriteCount","time","colorMul","mousePosition","curTile","flipU"],samplers:["spriteSheet","frameMap","tileMaps","animationMap"],needAlphaBlending:!0}),this._time=0,this._material.setFloat("spriteCount",this.spriteCount),this._material.setVector2("stageSize",n.stageSize),this._material.setVector2("outputSize",n.outputSize),this._material.setTexture("spriteSheet",this.spriteSheet),this._material.setVector2("spriteMapSize",new o.FM(1,1)),this._material.setVector3("colorMul",n.colorMultiply);let h=0;const c=()=>{this.spriteSheet&&this.spriteSheet.isReady()&&this.spriteSheet._texture?this._material.setVector2("spriteMapSize",new o.FM(this.spriteSheet._texture.baseWidth||1,this.spriteSheet._texture.baseHeight||1)):h<100&&setTimeout((()=>{h++,c()}),100)};c(),this._material.setVector3("colorMul",n.colorMultiply),this._material.setTexture("frameMap",this._frameMap),this._material.setTextureArray("tileMaps",this._tileMaps),this._material.setTexture("animationMap",this._animationMap),this._material.setFloat("time",this._time),this._output=(0,pa.pT)(e+":output",{size:1,updatable:!0},s),this._output.scaling.x=n.outputSize.x,this._output.scaling.y=n.outputSize.y,this.position=n.outputPosition,this.rotation=n.outputRotation,this._scene.onBeforeRenderObservable.add((()=>{this._time+=this._scene.getEngine().getDeltaTime(),this._material.setFloat("time",this._time)})),this._output.material=this._material}getTileID(){const e=this.getMousePosition();return e.multiplyInPlace(this.options.stageSize||o.FM.Zero()),e.x=Math.floor(e.x),e.y=Math.floor(e.y),e}getMousePosition(){const e=this._output,t=this._scene.pick(this._scene.pointerX,this._scene.pointerY,(t=>t===e));if(!t||!t.hit||!t.getTextureCoordinates)return new o.FM(-1,-1);return t.getTextureCoordinates()||new o.FM(-1,-1)}_createFrameBuffer(){const e=new Array;for(let t=0;t<this.spriteCount;t++)e.push(0,0,0,0),e.push(0,0,0,0),e.push(0,0,0,0),e.push(0,0,0,0);for(let t=0;t<this.spriteCount;t++){const i=this.sprites[t].frame,n=this.sprites[t].spriteSourceSize,s=this.sprites[t].sourceSize,r=this.sprites[t].rotated?1:0,o=this.sprites[t].trimmed?1:0;e[4*t]=i.x,e[4*t+1]=i.y,e[4*t+2]=i.w,e[4*t+3]=i.h,e[4*t+4*this.spriteCount]=n.x,e[4*t+1+4*this.spriteCount]=n.y,e[4*t+3+4*this.spriteCount]=n.h,e[4*t+8*this.spriteCount]=s.w,e[4*t+1+8*this.spriteCount]=s.h,e[4*t+2+8*this.spriteCount]=r,e[4*t+3+8*this.spriteCount]=o}const t=new Float32Array(e);return Ee.l.CreateRGBATexture(t,this.spriteCount,4,this._scene,!1,!1,Ce.x.NEAREST_NEAREST,ue.D.TEXTURETYPE_FLOAT)}_createTileBuffer(e,t=0){let i=new Array;const n=this.options.stageSize.y||0,s=this.options.stageSize.x||0;if(e)i=e;else{let e=this.options.baseTile;0!=t&&(e=0);for(let t=0;t<n;t++)for(let t=0;t<4*s;t+=4)i.push(e,0,0,0)}const r=new Float32Array(i);return Ee.l.CreateRGBATexture(r,s,n,this._scene,!1,!1,Ce.x.NEAREST_NEAREST,ue.D.TEXTURETYPE_FLOAT)}changeTiles(e=0,t,i=0){const n=this._tileMaps[e]._texture._bufferView;if(null===n)return;let s=new Array;t instanceof o.FM?s.push(t):s=t;const r=this.options.stageSize.x||0;for(let e=0;e<s.length;e++){const t=s[e];t.x=Math.floor(t.x),t.y=Math.floor(t.y),n[4*t.x+t.y*(4*r)]=i}const a=this._createTileBuffer(n);this._tileMaps[e].dispose(),this._tileMaps[e]=a,this._material.setTextureArray("tileMap",this._tileMaps)}_createTileAnimationBuffer(e){const t=new Array;let i;if(e)i=e;else{for(let e=0;e<this.spriteCount;e++){t.push(0,0,0,0);let e=1;for(;e<(this.options.maxAnimationFrames||4);)t.push(0,0,0,0),e++}i=new Float32Array(t)}return Ee.l.CreateRGBATexture(i,this.spriteCount,this.options.maxAnimationFrames||4,this._scene,!1,!1,Ce.x.NEAREST_NEAREST,ue.D.TEXTURETYPE_FLOAT)}addAnimationToTile(e=0,t=0,i=0,n=0,s=1){const r=this._animationMap._texture._bufferView,o=4*e+4*this.spriteCount*t;if(!r)return;r[o]=i,r[o+1]=n,r[o+2]=s;const a=this._createTileAnimationBuffer(r);this._animationMap.dispose(),this._animationMap=a,this._material.setTexture("animationMap",this._animationMap)}saveTileMaps(){let e="";for(let t=0;t<this._tileMaps.length;t++)t>0&&(e+="\n\r"),e+=this._tileMaps[t]._texture._bufferView.toString();const t=document.createElement("a");t.href="data:octet/stream;charset=utf-8,"+encodeURI(e),t.target="_blank",t.download=this.name+".tilemaps",t.click(),t.remove()}loadTileMaps(e){const t=new XMLHttpRequest;t.open("GET",e);const i=this.options.layerCount||0;t.onload=()=>{const e=t.response.split("\n\r");for(let t=0;t<i;t++){const i=e[t].split(",").map(Number),n=this._createTileBuffer(i);this._tileMaps[t].dispose(),this._tileMaps[t]=n}this._material.setTextureArray("tileMap",this._tileMaps)},t.send()}dispose(){this._output.dispose(),this._material.dispose(),this._animationMap.dispose(),this._tileMaps.forEach((e=>{e.dispose()})),this._frameMap.dispose()}}class Ig extends Rg{constructor(e,t,i,n,s=null,r=.01,o=Ce.x.TRILINEAR_SAMPLINGMODE){super(e,t,i,64,n,r,o,!0,s),this.name=e}}var Dg,Og=i(4710),wg=i(8657),Ng=i(5559);!function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(Dg||(Dg={}));class Fg{constructor(e){this.name=e,this._isCompleted=!1,this._taskState=Dg.INIT}get isCompleted(){return this._isCompleted}get taskState(){return this._taskState}get errorObject(){return this._errorObject}_setErrorObject(e,t){this._errorObject||(this._errorObject={message:e,exception:t})}run(e,t,i){this._taskState=Dg.RUNNING,this.runTask(e,(()=>{this._onDoneCallback(t,i)}),((e,t)=>{this._onErrorCallback(i,e,t)}))}runTask(e,t,i){throw new Error("runTask is not implemented")}reset(){this._taskState=Dg.INIT}_onErrorCallback(e,t,i){this._taskState=Dg.ERROR,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()}_onDoneCallback(e,t){try{this._taskState=Dg.DONE,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(e){this._onErrorCallback(t,"Task is done, error executing success callback(s)",e)}}}class Lg{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class Bg extends Fg{constructor(e,t,i,n,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=n,this.extension=s}runTask(e,t,i){ta.n.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,(e=>{this.loadedContainer=e,this.loadedMeshes=e.meshes,this.loadedTransformNodes=e.transformNodes,this.loadedParticleSystems=e.particleSystems,this.loadedSkeletons=e.skeletons,this.loadedAnimationGroups=e.animationGroups,t()}),null,((e,t,n)=>{i(t,n)}),this.extension)}}class Ug extends Fg{constructor(e,t,i,n,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=n,this.extension=s}runTask(e,t,i){ta.n.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,((e,i,n,s,r)=>{this.loadedMeshes=e,this.loadedTransformNodes=r,this.loadedParticleSystems=i,this.loadedSkeletons=n,this.loadedAnimationGroups=s,t()}),null,((e,t,n)=>{i(t,n)}),this.extension)}}class Vg extends Fg{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.text=e,t()}),void 0,!1,!1,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class kg extends Fg{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.data=e,t()}),void 0,!0,!0,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class Gg extends Fg{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const n=new Image;de.w1.SetCorsBehavior(this.url,n),n.onload=()=>{this.image=n,t()},n.onerror=e=>{i("Error loading image",e)},n.src=this.url}}class zg extends Fg{constructor(e,t,i,n=!0,s=Ce.x.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=n,this.samplingMode=s}runTask(e,t,i){this.texture=new Ce.x(this.url,e,this.noMipmap,this.invertY,this.samplingMode,(()=>{t()}),((e,t)=>{i(e,t)}))}}class Wg extends Fg{constructor(e,t,i,n,s,r){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=n,this.files=s,this.prefiltered=r}runTask(e,t,i){this.texture=new Fa.B(this.url,e,this.extensions,this.noMipmap,this.files,(()=>{t()}),((e,t)=>{i(e,t)}),void 0,this.prefiltered)}}class Hg extends Fg{constructor(e,t,i,n=!1,s=!0,r=!1,o=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=n,this.generateHarmonics=s,this.gammaSpace=r,this.reserved=o}runTask(e,t,i){this.texture=new Oh(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,(()=>{t()}),((e,t)=>{i(e,t)}))}}class Xg extends Fg{constructor(e,t,i,n=!1,s=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=n,this.gammaSpace=s}runTask(e,t,i){this.texture=new pc(this.url,e,this.size,this.noMipmap,this.gammaSpace,(()=>{t()}),((e,t)=>{i(e,t)}))}}class jg{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new r.y$,this.onTaskErrorObservable=new r.y$,this.onTasksDoneObservable=new r.y$,this.onProgressObservable=new r.y$,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||A.l.LastCreatedScene}addContainerTask(e,t,i,n,s){const r=new Bg(e,t,i,n,s);return this._tasks.push(r),r}addMeshTask(e,t,i,n,s){const r=new Ug(e,t,i,n,s);return this._tasks.push(r),r}addTextFileTask(e,t){const i=new Vg(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new kg(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new Gg(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,n,s=Ce.x.TRILINEAR_SAMPLINGMODE){const r=new zg(e,t,i,n,s);return this._tasks.push(r),r}addCubeTextureTask(e,t,i,n,s,r){const o=new Wg(e,t,i,n,s,r);return this._tasks.push(o),o}addHDRCubeTextureTask(e,t,i,n=!1,s=!0,r=!1,o=!1){const a=new Hg(e,t,i,n,s,r,o);return this._tasks.push(a),a}addEquiRectangularCubeTextureAssetTask(e,t,i,n=!1,s=!0){const r=new Xg(e,t,i,n,s);return this._tasks.push(r),r}removeTask(e){const t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)}_decreaseWaitingTasksCount(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new Lg(this._waitingTasksCount,this._totalTasksCount,e))}catch(e){_.Y.Error("Error running progress callbacks."),console.log(e)}if(0===this._waitingTasksCount){try{const e=this._tasks.slice();this.onFinish&&this.onFinish(e);for(const t of e)if(t.taskState===Dg.DONE){const e=this._tasks.indexOf(t);e>-1&&this._tasks.splice(e,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(e){_.Y.Error("Error running tasks-done callbacks."),console.log(e)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}}_runTask(e){const t=(t,i)=>{e._setErrorObject(t,i),this.onTaskError?this.onTaskError(e):e.onError||_.Y.Error(this._formatTaskErrorMessage(e)),this.onTaskErrorObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)};e.run(this._scene,(()=>{try{this.onTaskSuccess&&this.onTaskSuccess(e),this.onTaskSuccessObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)}catch(e){t("Error executing task success callbacks",e)}}),t)}_formatTaskErrorMessage(e){let t="Unable to complete task "+e.name;return e.errorObject.message&&(t+=`: ${e.errorObject.message}`),e.errorObject.exception&&(t+=`: ${e.errorObject.exception}`),t}reset(){return this._isLoading=!1,this._tasks=new Array,this}load(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(let e=0;e<this._tasks.length;e++){const t=this._tasks[e];t.taskState===Dg.INIT&&this._runTask(t)}return this}loadAsync(){return new Promise(((e,t)=>{this._isLoading?e():(this.onTasksDoneObservable.addOnce((i=>{i&&i.length?t(i):e()})),this.load())}))}}var Yg=i(7188);class qg{constructor(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new o.P(1,1,1),this._newPosition=o.P.Zero(),this._centerPosition=o.P.Zero(),this._meshes=e.slice(),t?this._centerMesh=t:this._setCenterMesh(),this._centerMesh.computeWorldMatrix(!0);const i=this._meshes.indexOf(this._centerMesh);i>=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(let e=0;e<this._meshes.length;e++)if(this._meshes[e]){const t=this._meshes[e];this._meshesOrigins[e]=t.getAbsolutePosition().clone(),this._toCenterVectors[e]=o.P.Zero(),t.hasBoundingInfo&&this._centerMesh.hasBoundingInfo&&(t.computeWorldMatrix(!0),t.getBoundingInfo().boundingBox.centerWorld.subtractToRef(this._centerMesh.getBoundingInfo().boundingBox.centerWorld,this._toCenterVectors[e]))}}_setCenterMesh(){let e=o.P.Zero();const t=o.P.Zero();let i=Number.MAX_VALUE;for(let e=0;e<this._meshes.length;e++)if(this._meshes[e]){const i=this._meshes[e].getBoundingInfo();i&&t.addInPlace(i.boundingBox.centerWorld)}e=t.scale(1/this._meshes.length);for(let t=0;t<this._meshes.length;t++)if(this._meshes[t]){const n=this._meshes[t],s=n.getBoundingInfo();if(s){const t=s.boundingBox.centerWorld.subtract(e).lengthSquared();t<i&&(this._centerMesh=n,i=t)}}}getClassName(){return"MeshExploder"}getMeshes(){const e=this._meshes.slice();return e.unshift(this._centerMesh),e}explode(e=1){for(let t=0;t<this._meshes.length;t++)this._meshes[t]&&this._meshesOrigins[t]&&this._toCenterVectors[t]&&(this._toCenterVectors[t].scaleToRef(e,this._scaledDirection),this._meshesOrigins[t].addToRef(this._scaledDirection,this._newPosition),this._meshes[t].setAbsolutePosition(this._newPosition));this._centerMesh.setAbsolutePosition(this._centerPosition)}}var Kg=i(679);class $g{static get FilesToLoad(){return Kg.X.FilesToLoad}constructor(e,t,i,n,s,r,o,a,l,h=!1){this.useAppend=h,this.onProcessFileCallback=()=>!0,this.displyLoadingUI=!0,this.loadAsync=(e,t)=>this.useAppend?ta.n.AppendAsync("file:",e,this._currentScene,t):ta.n.LoadAsync("file:",e,this._engine,t),this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=n,this._additionalRenderLoopLogicCallback=s,this._textureLoadingCallback=r,this._startingProcessingFilesCallback=o,this._onReloadCallback=a,this._errorCallback=l}monitorElementForDragNDrop(e){e&&(this._elementToMonitor=e,this._dragEnterHandler=e=>{this._drag(e)},this._dragOverHandler=e=>{this._drag(e)},this._dropHandler=e=>{this._drop(e)},this._elementToMonitor.addEventListener("dragenter",this._dragEnterHandler,!1),this._elementToMonitor.addEventListener("dragover",this._dragOverHandler,!1),this._elementToMonitor.addEventListener("drop",this._dropHandler,!1))}get filesToLoad(){return this._filesToLoad}dispose(){this._elementToMonitor&&(this._elementToMonitor.removeEventListener("dragenter",this._dragEnterHandler),this._elementToMonitor.removeEventListener("dragover",this._dragOverHandler),this._elementToMonitor.removeEventListener("drop",this._dropHandler))}_renderFunction(){if(this._additionalRenderLoopLogicCallback&&this._additionalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){const e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}}_drag(e){e.stopPropagation(),e.preventDefault()}_drop(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)}_traverseFolder(e,t,i,n){const s=e.createReader(),r=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");s.readEntries((e=>{i.count+=e.length;for(const s of e)s.isFile?s.file((e=>{e.correctName=r+e.name,t.push(e),0==--i.count&&n()})):s.isDirectory&&this._traverseFolder(s,t,i,n);0==--i.count&&n()}))}_processFiles(e){for(let t=0;t<e.length;t++){const i=e[t].correctName.toLowerCase(),n=i.split(".").pop();this.onProcessFileCallback(e[t],i,n,(e=>this._sceneFileToLoad=e))&&(ta.n.IsPluginForExtensionAvailable("."+n)&&(this._sceneFileToLoad=e[t]),$g.FilesToLoad[i]=e[t])}}loadFiles(e){if(e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&0!==this._filesToLoad.length&&(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(this._filesToLoad),this._filesToLoad&&this._filesToLoad.length>0)){const t=new Array,i=[],n=e.dataTransfer?e.dataTransfer.items:null;for(let e=0;e<this._filesToLoad.length;e++){const s=this._filesToLoad[e],r=s.name.toLowerCase();let o;if(s.correctName=r,n){const t=n[e];t.getAsEntry?o=t.getAsEntry():t.webkitGetAsEntry&&(o=t.webkitGetAsEntry())}o&&o.isDirectory?i.push(o):t.push(s)}if(0===i.length)this._processFiles(t),this._processReload();else{const e={count:i.length};for(const n of i)this._traverseFolder(n,t,e,(()=>{this._processFiles(t),0===e.count&&this._processReload()}))}}}_processReload(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()}reload(){this._sceneFileToLoad?(this.useAppend||this._currentScene&&(_.Y.errorsCount>0&&_.Y.ClearLogCache(),this._engine.stopRenderLoop()),ta.n.ShowLoadingScreen=!1,this.displyLoadingUI&&this._engine.displayLoadingUI(),this.loadAsync(this._sceneFileToLoad,this._progressCallback).then((e=>{this.useAppend?this.displyLoadingUI&&this._engine.hideLoadingUI():(this._currentScene&&this._currentScene.dispose(),this._currentScene=e,this._currentScene.executeWhenReady((()=>{this.displyLoadingUI&&this._engine.hideLoadingUI(),this._engine.runRenderLoop((()=>{this._renderFunction()}))}))),this._sceneLoadedCallback&&this._currentScene&&this._sceneLoadedCallback(this._sceneFileToLoad,this._currentScene)})).catch((e=>{this.displyLoadingUI&&this._engine.hideLoadingUI(),this._errorCallback&&this._errorCallback(this._sceneFileToLoad,this._currentScene,e.message)}))):_.Y.Error("Please provide a valid .babylon file.")}}class Qg{dispose(){if(this._observers&&this._observables)for(let e=0;e<this._observers.length;e++)this._observables[e].remove(this._observers[e]);this._observers=null,this._observables=null}static Watch(e,t,i=-1,n=null){const s=new Qg;s._observers=new Array,s._observables=e;for(const r of e){const e=r.add(t,i,!1,n);e&&s._observers.push(e)}return s}}r.y$.prototype.notifyObserversWithPromise=async function(e,t=-1,i,n,s){let r=Promise.resolve(e);if(!this.observers.length)return r;const o=this._eventState;return o.mask=t,o.target=i,o.currentTarget=n,o.skipNextObservers=!1,o.userInfo=s,this.observers.forEach((i=>{o.skipNextObservers||i._willBeUnregistered||i.mask&t&&(r=i.scope?r.then((t=>(o.lastReturnValue=t,i.callback.apply(i.scope,[e,o])))):r.then((t=>(o.lastReturnValue=t,i.callback(e,o)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await r,e};var Zg=i(4757);class Jg{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class ev extends Jg{getDescription(){return"Reducing render target texture size to "+this.maximumSize}constructor(e=0,t=1024,i=.5){super(e),this.priority=e,this.maximumSize=t,this.step=i}apply(e,t){let i=!0;for(let t=0;t<e.textures.length;t++){const n=e.textures[t];if(!n.canRescale||n.getContext)continue;const s=n.getSize();Math.max(s.width,s.height)>this.maximumSize&&(n.scale(this.step),i=!1)}return i}}class tv extends Jg{getDescription(){return"Setting hardware scaling level to "+this._currentScale}constructor(e=0,t=2,i=.25){super(e),this.priority=e,this.maximumScale=t,this.step=i,this._currentScale=-1,this._directionOffset=1}apply(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale}}class iv extends Jg{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class nv extends Jg{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class sv extends Jg{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class rv extends Jg{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return!this.onApply||this.onApply(e,t)}}class ov extends Jg{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class av extends Jg{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class lv extends Jg{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof Nt.Kj))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||0===t.getTotalVertices())}}static get UpdateSelectionTree(){return lv._UpdateSelectionTree}static set UpdateSelectionTree(e){lv._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const n=e.meshes.slice(0);let s=n.length;for(let e=0;e<s;e++){const t=new Array,i=n[e];if(this._canBeMerged(i)){t.push(i);for(let r=e+1;r<s;r++){const e=n[r];this._canBeMerged(e)&&e.material===i.material&&e.checkCollisions===i.checkCollisions&&(t.push(e),s--,n.splice(r,1),r--)}t.length<2||Nt.Kj.MergeMeshes(t,void 0,!0)}}const r=e;return r.createOrUpdateSelectionOctree&&(null!=i?i&&r.createOrUpdateSelectionOctree():lv.UpdateSelectionTree&&r.createOrUpdateSelectionOctree()),!0}}lv._UpdateSelectionTree=!1;class hv{constructor(e=60,t=2e3){this.targetFrameRate=e,this.trackerDuration=t,this.optimizations=new Array}addOptimization(e){return this.optimizations.push(e),this}addCustomOptimization(e,t,i=0){const n=new rv(i);return n.onApply=e,n.onGetDescription=t,this.optimizations.push(n),this}static LowDegradationAllowed(e){const t=new hv(e);let i=0;return t.addOptimization(new lv(i)),t.addOptimization(new iv(i)),t.addOptimization(new sv(i)),i++,t.addOptimization(new nv(i)),t.addOptimization(new ov(i)),i++,t.addOptimization(new ev(i,1024)),t}static ModerateDegradationAllowed(e){const t=new hv(e);let i=0;return t.addOptimization(new lv(i)),t.addOptimization(new iv(i)),t.addOptimization(new sv(i)),i++,t.addOptimization(new nv(i)),t.addOptimization(new ov(i)),i++,t.addOptimization(new ev(i,512)),i++,t.addOptimization(new av(i)),i++,t.addOptimization(new tv(i,2)),t}static HighDegradationAllowed(e){const t=new hv(e);let i=0;return t.addOptimization(new lv(i)),t.addOptimization(new iv(i)),t.addOptimization(new sv(i)),i++,t.addOptimization(new nv(i)),t.addOptimization(new ov(i)),i++,t.addOptimization(new ev(i,256)),i++,t.addOptimization(new av(i)),i++,t.addOptimization(new tv(i,4)),t}}class cv{get isInImprovementMode(){return this._improvementMode}set isInImprovementMode(e){this._improvementMode=e}get currentPriorityLevel(){return this._currentPriorityLevel}get currentFrameRate(){return this._currentFrameRate}get targetFrameRate(){return this._targetFrameRate}set targetFrameRate(e){this._targetFrameRate=e}get trackerDuration(){return this._trackerDuration}set trackerDuration(e){this._trackerDuration=e}get optimizations(){return this._options.optimizations}constructor(e,t,i=!0,n=!1){if(this._isRunning=!1,this._currentPriorityLevel=0,this._targetFrameRate=60,this._trackerDuration=2e3,this._currentFrameRate=0,this._improvementMode=!1,this.onSuccessObservable=new r.y$,this.onNewOptimizationAppliedObservable=new r.y$,this.onFailureObservable=new r.y$,this._options=t||new hv,this._options.targetFrameRate&&(this._targetFrameRate=this._options.targetFrameRate),this._options.trackerDuration&&(this._trackerDuration=this._options.trackerDuration),i){let e=0;for(const t of this._options.optimizations)t.priority=e++}this._improvementMode=n,this._scene=e||A.l.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>{this._sceneDisposeObserver=null,this.dispose()}))}stop(){this._isRunning=!1}reset(){this._currentPriorityLevel=0}start(){this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady((()=>{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)})))}_checkCurrentState(){if(!this._isRunning)return;const e=this._scene,t=this._options;if(this._currentFrameRate=Math.round(e.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);let i=!0,n=!0;for(let s=0;s<t.optimizations.length;s++){const r=t.optimizations[s];r.priority===this._currentPriorityLevel&&(n=!1,i=i&&r.apply(e,this),this.onNewOptimizationAppliedObservable.notifyObservers(r))}if(n)return this._isRunning=!1,void this.onFailureObservable.notifyObservers(this);i&&this._currentPriorityLevel++,e.executeWhenReady((()=>{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)}))}dispose(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)}static OptimizeAsync(e,t,i,n){const s=new cv(e,t||hv.ModerateDegradationAllowed(),!1);return i&&s.onSuccessObservable.add((()=>{i()})),n&&s.onFailureObservable.add((()=>{n()})),s.start(),s}}let uv=[];const dv=(e,t)=>{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),uv[e.id]=!0)},pv=(e,t)=>{const i={},n=e._geometry;return n&&(e.getScene().getGeometryById(n.id)||dv(n,t.geometries)),e.serialize&&e.serialize(i),i};class fv{static ClearCache(){uv=[]}static Serialize(e){return fv._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&Ce.x.ForceSerializeBuffers&&console.warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),fv.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(i.fogMode=e.fogMode,i.fogColor=e.fogColor.asArray(),i.fogStart=e.fogStart,i.fogEnd=e.fogEnd,i.fogDensity=e.fogDensity),e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const t of e.meshes){const e=t.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let n,s,r;for(i.lights=[],n=0;n<e.lights.length;n++)s=e.lights[n],s.doNotSerialize||i.lights.push(s.serialize());for(i.cameras=[],n=0;n<e.cameras.length;n++){const t=e.cameras[n];t.doNotSerialize||i.cameras.push(t.serialize())}if(e.activeCamera&&(i.activeCameraID=e.activeCamera.id),Te.p4.AppendSerializedAnimations(e,i),e.animationGroups&&e.animationGroups.length>0){i.animationGroups=[];for(let t=0;t<e.animationGroups.length;t++){const n=e.animationGroups[t];i.animationGroups.push(n.serialize())}}if(e.reflectionProbes&&e.reflectionProbes.length>0)for(i.reflectionProbes=[],n=0;n<e.reflectionProbes.length;n++){const t=e.reflectionProbes[n];i.reflectionProbes.push(t.serialize())}for(i.materials=[],i.multiMaterials=[],n=0;n<e.materials.length;n++)r=e.materials[n],r.doNotSerialize||i.materials.push(r.serialize());for(i.multiMaterials=[],n=0;n<e.multiMaterials.length;n++){const t=e.multiMaterials[n];i.multiMaterials.push(t.serialize())}for(e.environmentTexture&&(e.environmentTexture._files?i.environmentTexture=e.environmentTexture.serialize():(i.environmentTexture=e.environmentTexture.name,i.environmentTextureRotationY=e.environmentTexture.rotationY)),i.environmentIntensity=e.environmentIntensity,i.skeletons=[],n=0;n<e.skeletons.length;n++){const t=e.skeletons[n];t.doNotSerialize||i.skeletons.push(t.serialize())}for(i.transformNodes=[],n=0;n<e.transformNodes.length;n++)e.transformNodes[n].doNotSerialize||i.transformNodes.push(e.transformNodes[n].serialize());i.geometries={},i.geometries.boxes=[],i.geometries.spheres=[],i.geometries.cylinders=[],i.geometries.toruses=[],i.geometries.grounds=[],i.geometries.planes=[],i.geometries.torusKnots=[],i.geometries.vertexData=[],uv=[];const o=e.getGeometries();for(n=0;n<o.length;n++){const e=o[n];e.isReady()&&dv(e,i.geometries)}for(i.meshes=[],n=0;n<e.meshes.length;n++){const t=e.meshes[n];if(t instanceof Nt.Kj){const e=t;e.doNotSerialize||1!==e.delayLoadState&&0!==e.delayLoadState||i.meshes.push(pv(e,i))}}for(i.particleSystems=[],n=0;n<e.particleSystems.length;n++)i.particleSystems.push(e.particleSystems[n].serialize(!1));for(i.postProcesses=[],n=0;n<e.postProcesses.length;n++)i.postProcesses.push(e.postProcesses[n].serialize());e.actionManager&&(i.actions=e.actionManager.serialize("scene"));for(const t of e._serializableComponents)t.serialize(i);return i}static SerializeAsync(e){const t=fv._Serialize(e,!1),i=[];return this._CollectPromises(t,i),Promise.all(i).then((()=>t))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;i<e.length;++i){const n=e[i];n instanceof Promise?t.push(n.then((t=>e[i]=t))):(n instanceof Object||Array.isArray(n))&&this._CollectPromises(n,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const n=e[i];n instanceof Promise?t.push(n.then((t=>e[i]=t))):(n instanceof Object||Array.isArray(n))&&this._CollectPromises(n,t)}}static SerializeMesh(e,t=!1,i=!1){const n={};if(fv.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let n=0;n<e.length;++n)i&&e[n].getDescendants().forEach((t=>{t instanceof Nt.Kj&&e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[n].parent&&e.indexOf(e[n].parent)<0&&!e[n].parent.doNotSerialize&&e.push(e[n].parent);return e.forEach((e=>{((e,t)=>{if(1===e.delayLoadState||0===e.delayLoadState){const i=i=>{t.materials=t.materials||[],e.material&&!t.materials.some((t=>t.id===e.material.id))&&t.materials.push(i.serialize())};if(e.material&&!e.material.doNotSerialize)if(e.material instanceof Ph.G){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((t=>t.id===e.material.id))){t.multiMaterials.push(e.material.serialize());for(const t of e.material.subMaterials)t&&i(t)}}else i(e.material);else e.material||i(e.getScene().defaultMaterial);const n=e._geometry;n&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),dv(n,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(pv(e,t))}})(e,n)})),n}}var _v=i(4875);class mv{static IsSupported(e){const t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!mv.IsSupported(e))throw"Your browser does not support recording so far.";const i=e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options={...mv._DefaultOptions,...t};const n=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const e of this._options.audioTracks)n.addTrack(e);this._mediaRecorder=new MediaRecorder(n,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=this._handleDataAvailable.bind(this),this._mediaRecorder.onerror=this._handleError.bind(this),this._mediaRecorder.onstop=this._handleStop.bind(this)}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&de.w1.Download(e,this._fileName)}}mv._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};var gv=i(2286);let vv=null;function yv(e,t,i,n,s="image/png",r=!1){const{height:o,width:a}=Ev(e,t,i);if(!o||!a)return void _.Y.Error("Invalid 'size' parameter !");vv||(vv=document.createElement("canvas")),vv.width=a,vv.height=o;const l=vv.getContext("2d"),h=e.getRenderWidth()/e.getRenderHeight();let c=a,u=c/h;u>o&&(u=o,c=u*h);const d=Math.max(0,a-c)/2,p=Math.max(0,o-u)/2;t.getScene().activeCamera!==t?Tv(e,t,i,(e=>{if(r){const t=new Blob([e]);de.w1.DownloadBlob(t),n&&n("")}else n&&n(e)}),s,1,e.getCreationOptions().antialias):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();l&&t&&l.drawImage(t,d,p,c,u),vv&&(r?(de.w1.EncodeScreenshotCanvasData(vv,void 0,s),n&&n("")):de.w1.EncodeScreenshotCanvasData(vv,n,s))}))}function xv(e,t,i,n="image/png"){return new Promise(((s,r)=>{yv(e,t,i,(e=>{void 0!==e?s(e):r(new Error("Data is undefined"))}),n)}))}function bv(e,t,i,n,s="image/png"){return new Promise((r=>{yv(e,t,{width:i,height:n},(()=>{r()}),s,!0)}))}function Tv(e,t,i,n,s="image/png",r=1,o=!1,a,l=!1,h=!1,c=!0){const{height:u,width:d,finalWidth:p,finalHeight:f}=Ev(e,t,i),m={width:d,height:u};if(!u||!d)return void _.Y.Error("Invalid 'size' parameter !");const g={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(d,u);const v=t.getScene(),y=new Ai._("screenShot",m,v,!1,!1,0,!1,Ce.x.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,r);y.renderList=v.meshes.slice(),y.samples=r,y.renderSprites=l,y.activeCamera=t,y.forceLayerMaskCheck=c;const x=()=>{e.onEndFrameObservable.addOnce((()=>{p===d&&f===u?y.readPixels(void 0,void 0,void 0,!1).then((e=>{gv.B.DumpData(d,u,e,n,s,a,!0),y.dispose()})):(0,ro.$0)("pass",y.getInternalTexture(),v,void 0,void 0,void 0,p,f).then((t=>{e._readTexturePixels(t,p,f,-1,0,null,!0,!1,0,0).then((e=>{gv.B.DumpData(p,f,e,n,s,a,!0),t.dispose()}))}))})),v.incrementRenderId(),v.resetCachedMaterial(),y.render(!0),v.incrementRenderId(),v.resetCachedMaterial(),e.setSize(g.width,g.height),t.getProjectionMatrix(!0),v.render()};if(o){const e=new bm("antialiasing",1,v.activeCamera);y.addPostProcess(e),e.getEffect().isReady()?x():e.getEffect().onCompiled=()=>{x()}}else x()}function Sv(e,t,i,n="image/png",s=1,r=!1,o,a=!1,l=!1,h=!0){return new Promise(((c,u)=>{Tv(e,t,i,(e=>{void 0!==e?c(e):u(new Error("Data is undefined"))}),n,s,r,o,a,l,h)}))}function Ev(e,t,i){let n=0,s=0,r=0,o=0;if("object"==typeof i){const a=i.precision?Math.abs(i.precision):1;i.width&&i.height?(n=i.height*a,s=i.width*a):i.width&&!i.height?(s=i.width*a,n=Math.round(s/e.getAspectRatio(t))):i.height&&!i.width?(n=i.height*a,s=Math.round(n*e.getAspectRatio(t))):(s=Math.round(e.getRenderWidth()*a),n=Math.round(s/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(o=i.finalHeight,r=i.finalWidth):i.finalWidth&&!i.finalHeight?(r=i.finalWidth,o=Math.round(r/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(o=i.finalHeight,r=Math.round(o*e.getAspectRatio(t))):(r=s,o=n)}else isNaN(i)||(n=i,s=i,r=i,o=i);return s&&(s=Math.floor(s)),n&&(n=Math.floor(n)),r&&(r=Math.floor(r)),o&&(o=Math.floor(o)),{height:0|n,width:0|s,finalWidth:0|r,finalHeight:0|o}}const Cv={CreateScreenshot:yv,CreateScreenshotAsync:xv,CreateScreenshotWithResizeAsync:bv,CreateScreenshotUsingRenderTarget:Tv,CreateScreenshotUsingRenderTargetAsync:Sv};var Av;de.w1.CreateScreenshot=yv,de.w1.CreateScreenshotAsync=xv,de.w1.CreateScreenshotUsingRenderTarget=Tv,de.w1.CreateScreenshotUsingRenderTargetAsync=Sv,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(Av||(Av={}));var Pv,Rv=i(8121),Mv=i(4918),Iv=i(1918);class Dv{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(e){const t={};return{getItem:e=>{const i=t[e];return void 0===i?null:i},setItem:(e,i)=>{t[e]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}Dv._Storage=Dv._GetStorage();class Ov{constructor(){this._trackedScene=null}track(e){this._trackedScene=e,Te.p4.AllowLoadingUniqueId=!0,this._savedJSON=fv.Serialize(e),Te.p4.AllowLoadingUniqueId=!1}getDelta(){if(!this._trackedScene)return null;const e=Ce.x.ForceSerializeBuffers;Ce.x.ForceSerializeBuffers=!1,Te.p4.AllowLoadingUniqueId=!0;const t=fv.Serialize(this._trackedScene);Te.p4.AllowLoadingUniqueId=!1;const i={};for(const e in t)this._compareCollections(e,this._savedJSON[e],t[e],i);return Ce.x.ForceSerializeBuffers=e,i}_compareArray(e,t,i,n){if(0===t.length&&0===i.length)return!0;if(t.length&&!isNaN(t[0])||i.length&&!isNaN(i[0])){if(t.length!==i.length)return!1;if(0===t.length)return!0;for(let s=0;s<t.length;s++)if(t[s]!==i[s])return n[e]=i,!1;return!0}const s=[];for(let r=0;r<t.length;r++){const o=t[r],a=o.uniqueId;s.push(a);const l=i.filter((e=>e.uniqueId===a));if(l.length){const t=l[0],i={};this._compareObjects(o,t,i)||(n[e]||(n[e]=[]),i.__state={id:t.id||t.name},n[e].push(i))}else{const t={__state:{deleteId:o.id||o.name}};n[e]||(n[e]=[]),n[e].push(t)}}for(let t=0;t<i.length;t++){const r=i[t],o=r.uniqueId;-1===s.indexOf(o)&&(n[e]||(n[e]=[]),n[e].push(r))}return!0}_compareObjects(e,t,i){let n=!1;for(const s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;const r=e[s],o=t[s];let a=!1;if(Array.isArray(r))a=JSON.stringify(r)!==JSON.stringify(o);else if(isNaN(r)&&"[object String]"!=Object.prototype.toString.call(r)){if("object"==typeof r&&"object"==typeof o){const e={};this._compareObjects(r,o,e)||(i[s]=e,n=!0)}}else a=r!==o;a&&(n=!0,i[s]=o)}return!n}_compareCollections(e,t,i,n){if(t!==i&&t&&i)if(Array.isArray(t)&&Array.isArray(i)){if(this._compareArray(e,t,i,n))return}else if("object"==typeof t&&"object"==typeof i){const s={};return void(this._compareObjects(t,i,s)||(n[e]=s))}}static GetShadowGeneratorById(e,t){const i=e.lights.map((e=>e.getShadowGenerators()));for(const e of i)if(e){const i=e.values();for(let e=i.next();!0!==e.done;e=i.next()){const i=e.value;if(i&&i.id===t)return i}}return null}static ApplyDelta(e,t){"string"==typeof e&&(e=JSON.parse(e));const i=t;for(const n in e){const s=e[n],r=i[n];if(Array.isArray(r)||"shadowGenerators"===n)switch(n){case"cameras":this._ApplyDeltaForEntity(s,t,t.getCameraById.bind(t),(e=>Mt.V.Parse(e,t)));break;case"lights":this._ApplyDeltaForEntity(s,t,t.getLightById.bind(t),(e=>hh._.Parse(e,t)));break;case"shadowGenerators":this._ApplyDeltaForEntity(s,t,(e=>this.GetShadowGeneratorById(t,e)),(e=>dh.Parse(e,t)));break;case"meshes":this._ApplyDeltaForEntity(s,t,t.getMeshById.bind(t),(e=>Nt.Kj.Parse(e,t,"")));break;case"skeletons":this._ApplyDeltaForEntity(s,t,t.getSkeletonById.bind(t),(e=>Ye.O.Parse(e,t)));break;case"materials":this._ApplyDeltaForEntity(s,t,t.getMaterialById.bind(t),(e=>cs.F.Parse(e,t,"")));break;case"multiMaterials":this._ApplyDeltaForEntity(s,t,t.getMaterialById.bind(t),(e=>Ph.G.Parse(e,t,"")));break;case"transformNodes":this._ApplyDeltaForEntity(s,t,t.getTransformNodeById.bind(t),(e=>yi.Y.Parse(e,t,"")));break;case"particleSystems":this._ApplyDeltaForEntity(s,t,t.getParticleSystemById.bind(t),(e=>i_.Parse(e,t,"")));break;case"morphTargetManagers":this._ApplyDeltaForEntity(s,t,t.getMorphTargetById.bind(t),(e=>wh.O.Parse(e,t)));break;case"postProcesses":this._ApplyDeltaForEntity(s,t,t.getPostProcessByName.bind(t),(e=>ni.D.Parse(e,t,"")))}else isNaN(r)?r.fromArray&&r.fromArray(s):i[n]=s}}static _ApplyPropertiesToEntity(e,t){for(const i in e){const n=e[i],s=t[i];void 0!==s&&(!isNaN(s)||Array.isArray(s)?t[i]=n:s.fromArray?s.fromArray(n):"object"==typeof s&&null!==s&&this._ApplyPropertiesToEntity(n,s))}}static _ApplyDeltaForEntity(e,t,i,n){for(const s of e)if(s.__state&&void 0!==s.__state.id){const e=i(s.__state.id);e&&(this._ApplyPropertiesToEntity(s,e),Te.p4.ParseProperties(s,e,t,null))}else if(s.__state&&void 0!==s.__state.deleteId){const e=i(s.__state.deleteId);null==e||e.dispose()}else n(s)}}!function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),n=new t(i.characters);return n._insertionCosts=i.insertionCosts,n._deletionCosts=i.deletionCosts,n._substitutionCosts=i.substitutionCosts,n}constructor(e,t=null,i=null,n=null){let s;t=null!=t?t:()=>1,i=null!=i?i:()=>1,n=null!=n?n:(e,t)=>e===t?0:1,this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let r=0;r<e.length;++r){s=e[r],this._characterToIdx.set(s,r),this._insertionCosts[r]=t(s),this._deletionCosts[r]=i(s),this._substitutionCosts[r]=new Array(e.length);for(let t=r;t<e.length;++t)this._substitutionCosts[r][t]=n(s,e[t])}}getCharacterIdx(e){return this._characterToIdx.get(e)}getInsertionCost(e){return this._insertionCosts[e]}getDeletionCost(e){return this._deletionCosts[e]}getSubstitutionCost(e,t){const i=Math.min(e,t),n=Math.max(e,t);return this._substitutionCosts[i][n]}}e.Alphabet=t;class i{serialize(){return JSON.stringify(this._characters)}static Deserialize(e,t){const n=new i([],t);return n._characters=JSON.parse(e),n}constructor(e,t){if(e.length>i._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const n=e._alphabet;if(n!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const s=e._characters,r=t._characters,o=s.length,a=r.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;e<o;++e)l[e+1][0]=l[e][0]+n.getInsertionCost(s[e]);for(let e=0;e<a;++e)l[0][e+1]=l[0][e]+n.getInsertionCost(r[e]);for(let e=0;e<o;++e)for(let t=0;t<a;++t)i._InsertionCost=l[e+1][t]+n.getInsertionCost(r[t]),i._DeletionCost=l[e][t+1]+n.getDeletionCost(s[e]),i._SubstitutionCost=l[e][t]+n.getSubstitutionCost(s[e],r[t]),l[e+1][t+1]=Math.min(i._InsertionCost,i._DeletionCost,i._SubstitutionCost);return l[o][a]}}i._MAX_SEQUENCE_LENGTH=256,i._CostMatrix=[...Array(i._MAX_SEQUENCE_LENGTH+1)].map((()=>new Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}(Pv||(Pv={}));class wv{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new wv(t._segmentLength);return i._points=t._points.map((e=>new o.P(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/o.P.Distance(this._points[t-1],e);for(let n=i();n<=1;n=i()){const i=this._points[t-1].scale(1-n);e.scaleAndAddToRef(n,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new wv(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new o.P;for(let n=2;n<this._points.length;++n)wv._TransformSegmentDirToRef(this._points[n-2],this._points[n-1],this._points[n],i)&&t.push(wv._TokenizeSegment(i,e));return t}static _TransformSegmentDirToRef(e,t,i,n){return t.subtractToRef(e,wv._ForwardDir),wv._ForwardDir.normalize(),t.scaleToRef(-1,wv._InverseFromVec),wv._InverseFromVec.normalize(),!(Math.abs(o.P.Dot(wv._ForwardDir,wv._InverseFromVec))>.98||(o.P.CrossToRef(wv._ForwardDir,wv._InverseFromVec,wv._UpDir),wv._UpDir.normalize(),o.y3.LookAtLHToRef(e,t,wv._UpDir,wv._LookMatrix),i.subtractToRef(t,wv._FromToVec),wv._FromToVec.normalize(),o.P.TransformNormalToRef(wv._FromToVec,wv._LookMatrix,n),0))}static _TokenizeSegment(e,t){wv._BestMatch=0,wv._Score=o.P.Dot(e,t[0]),wv._BestScore=wv._Score;for(let i=1;i<t.length;++i)wv._Score=o.P.Dot(e,t[i]),wv._Score>wv._BestScore&&(wv._BestMatch=i,wv._BestScore=wv._Score);return wv._BestMatch}}wv._ForwardDir=new o.P,wv._InverseFromVec=new o.P,wv._UpDir=new o.P,wv._FromToVec=new o.P,wv._LookMatrix=new o.y3;class Nv{static Generate(e=64,t=256,i=.1,n=.001,s=[]){const r=new Nv(e);for(let t=0;t<e;++t)r.chars[t]=new o.P(Math.random()-.5,Math.random()-.5,Math.random()-.5),r.chars[t].normalize();for(let e=0;e<s.length;++e)r.chars[e].copyFrom(s[e]);let a,l;const h=new o.P,c=new o.P;for(let e=0;e<t;++e){a=(1-(u=e/(t-1)))*i+u*n;for(let e=s.length;e<r.chars.length;++e)h.copyFromFloats(0,0,0),r.chars.forEach((t=>{r.chars[e].subtractToRef(t,c),l=c.lengthSquared(),l>1e-6&&c.scaleAndAddToRef(1/(c.lengthSquared()*l),h)})),h.scaleInPlace(a),r.chars[e].addInPlace(h),r.chars[e].normalize()}var u;return r}serialize(){return JSON.stringify(this.chars)}static Deserialize(e){const t=JSON.parse(e),i=new Nv(t.length);for(let e=0;e<t.length;++e)i.chars[e]=new o.P(t[e]._x,t[e]._y,t[e]._z);return i}constructor(e){this.chars=new Array(e)}}class Fv{serialize(){return JSON.stringify(this._sequences.map((e=>e.serialize())))}static Deserialize(e,t){const i=new Fv;return i._sequences=JSON.parse(e).map((e=>Pv.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return Fv.CreateFromTokenizationPyramid(Fv._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new Fv;return i._sequences=e.map((e=>new Pv.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=Fv._FINEST_DESCRIPTOR_RESOLUTION){const n=[];for(let s=i;s>4;s=Math.floor(s/2))n.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return n}distance(e){let t,i=0;for(let n=0;n<this._sequences.length;++n)t=Math.pow(2,n),i+=t*this._sequences[n].distance(e._sequences[n]);return i}}Fv._FINEST_DESCRIPTOR_RESOLUTION=32;class Lv{serialize(){const e={};return e.descriptors=this._descriptors.map((e=>e.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),n=new Lv;return n._descriptors=i.descriptors.map((e=>Fv.Deserialize(e,t))),n._centroidIdx=i.centroidIdx,n._averageDistance=i.averageDistance,n}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let e=0;e<t.length;++e)(this._centroidIdx<0||t[e]<t[this._centroidIdx])&&(this._centroidIdx=e);this._averageDistance=0,this._descriptors.forEach((e=>{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,Lv._MIN_AVERAGE_DISTANCE))}}Lv._MIN_AVERAGE_DISTANCE=1;class Bv{serialize(){const e={};return e.maximumAllowableMatchCost=this._maximumAllowableMatchCost,e.vector3Alphabet=this._vector3Alphabet.serialize(),e.levenshteinAlphabet=this._levenshteinAlphabet.serialize(),e.nameToDescribedTrajectory=[],this._nameToDescribedTrajectory.forEach(((t,i)=>{e.nameToDescribedTrajectory.push(i),e.nameToDescribedTrajectory.push(t.serialize())})),JSON.stringify(e)}static Deserialize(e){const t=JSON.parse(e),i=new Bv;i._maximumAllowableMatchCost=t.maximumAllowableMatchCost,i._vector3Alphabet=Nv.Deserialize(t.vector3Alphabet),i._levenshteinAlphabet=Pv.Alphabet.Deserialize(t.levenshteinAlphabet);for(let e=0;e<t.nameToDescribedTrajectory.length;e+=2)i._nameToDescribedTrajectory.set(t.nameToDescribedTrajectory[e],Lv.Deserialize(t.nameToDescribedTrajectory[e+1],i._levenshteinAlphabet));return i}static Generate(){const e=Nv.Generate(64,256,.1,.001,[o.P.Forward()]),t=new Array(e.chars.length);for(let e=0;e<t.length;++e)t[e]=e;const i=new Pv.Alphabet(t,(e=>0===e?0:1),(e=>0===e?0:1),((t,i)=>Math.min(1-o.P.Dot(e.chars[t],e.chars[i]),1))),n=new Bv;return n._vector3Alphabet=e,n._levenshteinAlphabet=i,n}constructor(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}addTrajectoryToClassification(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new Lv),this._nameToDescribedTrajectory.get(t).add(Fv.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))}deleteClassification(e){return this._nameToDescribedTrajectory.delete(e)}classifyTrajectory(e){const t=Fv.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),i=[];if(this._nameToDescribedTrajectory.forEach(((e,n)=>{e.getMatchCost(t)<this._maximumAllowableMatchCost&&i.push(n)})),0===i.length)return null;let n,s=0,r=this._nameToDescribedTrajectory.get(i[s]).getMatchMinimumDistance(t);for(let e=0;e<i.length;++e)n=this._nameToDescribedTrajectory.get(i[e]).getMatchMinimumDistance(t),n<r&&(r=n,s=e);return i[s]}}var Uv=i(9703);class Vv{constructor(e,t,i){this._scene=e,_.Y.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{const t=e.data;if(t.startsWith(Vv._SERVER_PREFIX)){const e=t.substr(Vv._SERVER_PREFIX.length);return _.Y.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),void this._handleServerMessage(e)}_.Y.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{_.Y.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&fv.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}Vv._SERVER_PREFIX="$$";class kv{constructor(e){this._observer=null,this._currentState=[],this.onPressureChanged=new r.y$,kv.IsAvailable&&(this._observer=new PressureObserver((e=>{this._currentState=e,this.onPressureChanged.notifyObservers(e)}),e))}static get IsAvailable(){return"undefined"!=typeof PressureObserver&&PressureObserver.supportedSources.includes("cpu")}observe(e){var t;try{null===(t=this._observer)||void 0===t||t.observe(e),this.onPressureChanged.notifyObservers(this._currentState)}catch(e){}}unobserve(e){var t;try{null===(t=this._observer)||void 0===t||t.unobserve(e)}catch(e){}}dispose(){var e;null===(e=this._observer)||void 0===e||e.disconnect(),this._observer=null,this.onPressureChanged.clear()}}class Gv{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(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const zv=1800,Wv="timestamp",Hv="numPoints",Xv=/\r/g;class jv{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=G.F.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let n=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);n=e+this.datasets.data.at(e+jv.NumberOfPointsOffset)+jv.SliceDataOffset}if(this.datasets.startingIndices.push(n),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;e<t;e++)i.push(this.datasets.data.at(n+jv.SliceDataOffset+e));this.datasetObservable.notifyObservers(i)}},this.datasets={ids:[],data:new Gv(zv),startingIndices:new Gv(zv)},this._strategies=new Map,this._datasetMeta=new Map,this._eventRestoreSet=new Set,this._customEventObservable=new r.y$,this.datasetObservable=new r.y$,this.metadataObservable=new r.y$((e=>e.callback(this._datasetMeta,new r.he(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var n;if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(null===(n=this._strategies.get(e))||void 0===n||n.dispose(),this._strategies.delete(e));const s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,n=0;const s=t.onAfterRenderObservable.add((()=>{n=i,i=0})),r=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>n,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(r)}}},category:i}),s}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:n}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:n}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);let i="#";for(let e=0;e<24;e+=8)i+=("0"+(t>>e&255).toString(16)).substr(-2);return i}getCurrentSlice(){const e=[G.F.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const n=this._datasetMeta.get(e);n&&(n[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new Gv(zv),this.datasets.ids.length=0,this.datasets.startingIndices=new Gv(zv),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(Xv,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),n=jv.NumberOfPointsOffset;if(i.length<2)return!1;const s={ids:[],data:new Gv(zv),startingIndices:new Gv(zv)},[r,...o]=i;if(r.length<2||r[0]!==Wv||r[n]!==Hv)return!1;const a=new Map;for(let e=jv.SliceDataOffset;e<r.length;e++){const[t,i]=r[e].split("@");s.ids.push(t),a.set(t,i)}let l=0;for(const e of o){if(e.length<2)return!1;const t=parseFloat(e[0]),i=parseInt(e[n]);if(isNaN(i)||isNaN(t))return!1;if(s.data.push(t),s.data.push(i),i+jv.SliceDataOffset!==e.length)return!1;for(let t=jv.SliceDataOffset;t<e.length;t++){const i=parseFloat(e[t]);if(isNaN(i))return!1;s.data.push(i)}s.startingIndices.push(l),l+=e.length}if(this.datasets.ids=s.ids,this.datasets.data=s.data,this.datasets.startingIndices=s.startingIndices,t||this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),!t)for(const e of this.datasets.ids){const t=a.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${Wv},${Hv}`;for(let t=0;t<this.datasets.ids.length;t++)if(e+=`,${this.datasets.ids[t]}`,this._datasetMeta){const i=this._datasetMeta.get(this.datasets.ids[t]);(null==i?void 0:i.category)&&(e+=`@${i.category}`)}e+="\n";for(let t=0;t<this.datasets.startingIndices.itemLength;t++){const i=this.datasets.startingIndices.at(t),n=this.datasets.data.at(i),s=this.datasets.data.at(i+jv.NumberOfPointsOffset);e+=`${n},${s}`;for(let t=0;t<s;t++)e+=`,${this.datasets.data.at(i+jv.SliceDataOffset+t)}`;for(let t=0;t<this.datasets.ids.length-s;t++)e+=",";e+="\n"}const t=`${(new Date).toISOString()}-perfdata.csv`;de.w1.Download(new Blob([e],{type:"text/csv"}),t)}start(e){e?void 0===this._startingTimestamp&&(this._startingTimestamp=G.F.Now):(this.datasets.data=new Gv(zv),this.datasets.startingIndices=new Gv(zv),this._startingTimestamp=G.F.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}}const Yv=()=>{};class qv{static FpsStrategy(){return e=>{const t=e.getEngine();return{id:"FPS",getData:()=>t.getFps(),dispose:Yv}}}static ThermalStrategy(){return this._PressureStrategy("Thermal utilization","thermal")}static PowerSupplyStrategy(){return this._PressureStrategy("Power supply utilization","power-supply")}static PressureStrategy(){return this._PressureStrategy("Pressure")}static _PressureStrategy(e,t=null){return()=>{let i=0;const n=new kv;return n.observe("cpu"),n.onPressureChanged.add((e=>{for(const n of e)if(t&&n.factors.includes(t)||!t&&0===n.factors.length)switch(n.state){case"nominal":i=0;break;case"fair":i=.25;break;case"serious":i=.5;break;case"critical":i=1}})),{id:e,getData:()=>i,dispose:()=>n.dispose()}}}static TotalMeshesStrategy(){return e=>({id:"Total meshes",getData:()=>e.meshes.length,dispose:Yv})}static ActiveMeshesStrategy(){return e=>({id:"Active meshes",getData:()=>e.getActiveMeshes().length,dispose:Yv})}static ActiveIndicesStrategy(){return e=>({id:"Active indices",getData:()=>e.getActiveIndices(),dispose:Yv})}static ActiveFacesStrategy(){return e=>({id:"Active faces",getData:()=>e.getActiveIndices()/3,dispose:Yv})}static ActiveBonesStrategy(){return e=>({id:"Active bones",getData:()=>e.getActiveBones(),dispose:Yv})}static ActiveParticlesStrategy(){return e=>({id:"Active particles",getData:()=>e.getActiveParticles(),dispose:Yv})}static DrawCallsStrategy(){return e=>{let t=0;const i=e.onBeforeAnimationsObservable.add((()=>{e.getEngine()._drawCalls.fetchNewFrame()})),n=e.onAfterRenderObservable.add((()=>{t=e.getEngine()._drawCalls.current}));return{id:"Draw calls",getData:()=>t,dispose:()=>{e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(n)}}}}static TotalLightsStrategy(){return e=>({id:"Total lights",getData:()=>e.lights.length,dispose:Yv})}static TotalVerticesStrategy(){return e=>({id:"Total vertices",getData:()=>e.getTotalVertices(),dispose:Yv})}static TotalMaterialsStrategy(){return e=>({id:"Total materials",getData:()=>e.materials.length,dispose:Yv})}static TotalTexturesStrategy(){return e=>({id:"Total textures",getData:()=>e.textures.length,dispose:Yv})}static AbsoluteFpsStrategy(){return e=>{const t=new Ql(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:()=>1e3/t.frameTimeCounter.lastSecAverage,dispose:Yv}}}static MeshesSelectionStrategy(){return e=>{let t=G.F.Now,i=0;const n=e.onBeforeActiveMeshesEvaluationObservable.add((()=>{t=G.F.Now})),s=e.onAfterActiveMeshesEvaluationObservable.add((()=>{i=G.F.Now-t}));return{id:"Meshes Selection",getData:()=>i,dispose:()=>{e.onBeforeActiveMeshesEvaluationObservable.remove(n),e.onAfterActiveMeshesEvaluationObservable.remove(s)}}}}static RenderTargetsStrategy(){return e=>{let t=G.F.Now,i=0;const n=e.onBeforeRenderTargetsRenderObservable.add((()=>{t=G.F.Now})),s=e.onAfterRenderTargetsRenderObservable.add((()=>{i=G.F.Now-t}));return{id:"Render Targets",getData:()=>i,dispose:()=>{e.onBeforeRenderTargetsRenderObservable.remove(n),e.onAfterRenderTargetsRenderObservable.remove(s)}}}}static ParticlesStrategy(){return e=>{let t=G.F.Now,i=0;const n=e.onBeforeParticlesRenderingObservable.add((()=>{t=G.F.Now})),s=e.onAfterParticlesRenderingObservable.add((()=>{i=G.F.Now-t}));return{id:"Particles",getData:()=>i,dispose:()=>{e.onBeforeParticlesRenderingObservable.remove(n),e.onAfterParticlesRenderingObservable.remove(s)}}}}static SpritesStrategy(){return e=>{var t,i;let n=G.F.Now,s=0;const r=null===(t=e.onBeforeSpritesRenderingObservable)||void 0===t?void 0:t.add((()=>{n=G.F.Now})),o=null===(i=e.onAfterSpritesRenderingObservable)||void 0===i?void 0:i.add((()=>{s=G.F.Now-n}));return{id:"Sprites",getData:()=>s,dispose:()=>{var t,i;null===(t=e.onBeforeSpritesRenderingObservable)||void 0===t||t.remove(r),null===(i=e.onAfterSpritesRenderingObservable)||void 0===i||i.remove(o)}}}}static AnimationsStrategy(){return e=>{let t=G.F.Now,i=0;const n=e.onBeforeAnimationsObservable.add((()=>{t=G.F.Now})),s=e.onAfterAnimationsObservable.add((()=>{i=G.F.Now-t}));return{id:"Animations",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(n),e.onAfterAnimationsObservable.remove(s)}}}}static PhysicsStrategy(){return e=>{var t,i;let n=G.F.Now,s=0;const r=null===(t=e.onBeforePhysicsObservable)||void 0===t?void 0:t.add((()=>{n=G.F.Now})),o=null===(i=e.onAfterPhysicsObservable)||void 0===i?void 0:i.add((()=>{s=G.F.Now-n}));return{id:"Physics",getData:()=>s,dispose:()=>{var t,i;null===(t=e.onBeforePhysicsObservable)||void 0===t||t.remove(r),null===(i=e.onAfterPhysicsObservable)||void 0===i||i.remove(o)}}}}static RenderStrategy(){return e=>{let t=G.F.Now,i=0;const n=e.onBeforeDrawPhaseObservable.add((()=>{t=G.F.Now})),s=e.onAfterDrawPhaseObservable.add((()=>{i=G.F.Now-t}));return{id:"Render",getData:()=>i,dispose:()=>{e.onBeforeDrawPhaseObservable.remove(n),e.onAfterDrawPhaseObservable.remove(s)}}}}static FrameTotalStrategy(){return e=>{let t=G.F.Now,i=0;const n=e.onBeforeAnimationsObservable.add((()=>{t=G.F.Now})),s=e.onAfterRenderObservable.add((()=>{i=G.F.Now-t}));return{id:"Frame Total",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(n),e.onAfterRenderObservable.remove(s)}}}}static InterFrameStrategy(){return e=>{let t=G.F.Now,i=0;const n=e.onBeforeAnimationsObservable.add((()=>{i=G.F.Now-t})),s=e.onAfterRenderObservable.add((()=>{t=G.F.Now}));return{id:"Inter-frame",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(n),e.onAfterRenderObservable.remove(s)}}}}static GpuFrameTimeStrategy(){return e=>{const t=new $l(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:()=>Math.max(1e-6*t.gpuFrameTimeCounter.current,0),dispose:()=>{t.dispose()}}}}}k.x.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new jv(this)),this._perfCollector};var Kv=i(2697);r.y$.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,n=new Array,s=e.add((()=>{const e=t.length;for(let s=0;s<e;s++)(0,Kv.WP)(t.shift(),i.shift(),n.shift())}));return{scheduler:(e,s,r)=>{t.push(e),i.push(s),n.push(r)},dispose:()=>{e.remove(s)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return(0,Kv.sM)(e,this._coroutineScheduler)},r.y$.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};class $v extends Il.F{constructor(e,t={}){super(e),this.options=t,this._direction=new o.P(0,0,-1),this._mat=new o.y3,this._onSelectEnabled=!1,this._origin=new o.P(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new r.y$,this._onHitTestResults=e=>{const t=e.map((e=>{const t=o.y3.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&$v.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",de.w1.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,n){return e.requestHitTest(t,i).then((e=>{const t=n||(e=>!!e.hitMatrix);return e.filter(t)}))}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const n=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,n,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}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;o.y3.FromArrayToRef(t.transform.matrix,0,this._mat),o.P.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),o.P.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});$v.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}$v.Name=vl.b.HIT_TEST,$v.Version=1,vl.d.AddWebXRFeature($v.Name,((e,t)=>()=>new $v(e,t)),$v.Version,!1);let Qv=0;class Zv extends Il.F{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 r.y$,this.onAnchorRemovedObservable=new r.y$,this.onAnchorUpdatedObservable=new r.y$,this._tmpVector=new o.P,this._tmpQuaternion=new o._f,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 o.P,i=new o._f){this._populateTmpTransformation(t,i);const n=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)throw this.detach(),new Error("Anchors not enabled in this environment/browser");try{const t=await e.xrHitResult.createAnchor(n);return new Promise(((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:n,resolve:e,reject:i})}))}catch(e){throw new Error(e)}}async addAnchorAtPositionAndRotationAsync(e,t=new o._f,i=!1){this._populateTmpTransformation(e,t);const n=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}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(n,this._xrSessionManager.currentFrame):void 0;return new Promise(((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:n,resolve:e,reject:t})}))}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(e){}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((e=>!t.has(e.xrAnchor))).map((e=>this._trackedAnchors.indexOf(e)));let n=0;i.forEach((e=>{const t=this._trackedAnchors.splice(e-n,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),n++})),t.forEach((t=>{if(this._lastFrameDetected.has(t)){const i=this._findIndexInAnchorArray(t),n=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,n,e),n.attachedNode&&(n.attachedNode.rotationQuaternion=n.attachedNode.rotationQuaternion||new o._f,n.transformationMatrix.decompose(n.attachedNode.scaling,n.attachedNode.rotationQuaternion,n.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(n)}catch(e){de.w1.Warn("Anchor could not be updated")}}else{const i={id:Qv++,xrAnchor:t,remove:()=>t.delete()},n=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(n),this.onAnchorAddedObservable.notifyObservers(n);const s=this._futureAnchors.filter((e=>e.nativeAnchor===t))[0];s&&(s.resolve(n),s.resolved=!0)}})),this._lastFrameDetected=t}this._futureAnchors.forEach((t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then((e=>{t.nativeAnchor=e}),(e=>{t.resolved=!0,t.reject(e)})),t.submitted=!0)}))}_findIndexInAnchorArray(e){for(let t=0;t<this._trackedAnchors.length;++t)if(this._trackedAnchors[t].xrAnchor===e)return t;return-1}_updateAnchorWithXRFrame(e,t,i){const n=i.getPose(e.anchorSpace,this._xrSessionManager.referenceSpace);if(n){const e=t.transformationMatrix||new o.y3;o.y3.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}async _createAnchorAtTransformation(e,t){var i;if(!t.createAnchor)throw this.detach(),new Error("Anchors are not enabled in your browser");try{return t.createAnchor(e,null!==(i=this._referenceSpaceForFrameAnchors)&&void 0!==i?i:this._xrSessionManager.referenceSpace)}catch(e){throw new Error(e)}}}Zv.Name=vl.b.ANCHOR_SYSTEM,Zv.Version=1,vl.d.AddWebXRFeature(Zv.Name,((e,t)=>()=>new Zv(e,t)),Zv.Version);let Jv=0;class ey extends Il.F{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new r.y$,this.onPlaneRemovedObservable=new r.y$,this.onPlaneUpdatedObservable=new r.y$,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"undefined"!=typeof XRPlane}_onXRFrame(e){var t;if(!this.attached||!this._enabled||!e)return;const i=e.detectedPlanes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedPlanes);if(i){for(let e=0;e<this._detectedPlanes.length;e++){const t=this._detectedPlanes[e];i.has(t.xrPlane)||(this._detectedPlanes.splice(e--,1),this.onPlaneRemovedObservable.notifyObservers(t))}i.forEach((t=>{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._findIndexInPlaneArray(t),n=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,n,e),this.onPlaneUpdatedObservable.notifyObservers(n)}}else{const i={id:Jv++,xrPlane:t,polygonDefinition:[]},n=this._updatePlaneWithXRPlane(t,i,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)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()):e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map((e=>{const t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new o.P(e.x,e.y,e.z*t)}));const n=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(n){const e=t.transformationMatrix||new o.y3;o.y3.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t<this._detectedPlanes.length;++t)if(this._detectedPlanes[t].xrPlane===e)return t;return-1}}ey.Name=vl.b.PLANE_DETECTION,ey.Version=1,vl.d.AddWebXRFeature(ey.Name,((e,t)=>()=>new ey(e,t)),ey.Version);class ty extends Il.F{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new r.y$}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((t=>t.setEnabled(e))),this.onBackgroundStateChangedObservable.notifyObservers(e)}}ty.Name=vl.b.BACKGROUND_REMOVER,ty.Version=1,vl.d.AddWebXRFeature(ty.Name,((e,t)=>()=>new ty(e,t)),ty.Version,!0);class iy{}class ny extends Il.F{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||Qn.Q.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,n=Kn("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});n.isVisible=this._debugMode,n.isPickable=!1,n.rotationQuaternion=new o._f;const s=e.grip||e.pointer;n.position.copyFrom(s.position),n.rotationQuaternion.copyFrom(s.rotationQuaternion);const r=new Qn.Q(n,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:r,impostorMesh:n}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||_.Y.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((()=>{const i=new Qn.Q(t.rootMesh,Qn.Q.MeshImpostor,{mass:0,...this._options.physicsProperties}),n=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:n.position.clone(),oldRotation:n.rotationQuaternion.clone()}}))})):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new o._f,this._tmpVector=new o.P,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:Qn.Q.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=Kn("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new o._f,this._headsetMesh.isVisible=!1,this._headsetImpostor=new Qn.Q(this._headsetMesh,e.impostorType,{mass:0,...e})}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){var t,i;if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),null===(t=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===t?void 0:t.linearVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(null===(i=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===i?void 0:i.angularVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((e=>{var t,i;const n=this._controllers[e],s=n.xrController.grip||n.xrController.pointer,r=n.oldPos||n.impostorMesh.position;if(null===(t=n.xrController._lastXRPose)||void 0===t?void 0:t.linearVelocity){const e=n.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),n.impostor.setLinearVelocity(this._tmpVector)}else s.position.subtractToRef(r,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),n.impostor.setLinearVelocity(this._tmpVector);r.copyFrom(s.position),this._debugMode&&console.log(this._tmpVector,"linear");const o=n.oldRotation||n.impostorMesh.rotationQuaternion;if(null===(i=n.xrController._lastXRPose)||void 0===i?void 0:i.angularVelocity){const e=n.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),n.impostor.setAngularVelocity(this._tmpVector)}else if(!o.equalsWithEpsilon(s.rotationQuaternion)){o.conjugateInPlace().multiplyToRef(s.rotationQuaternion,this._tmpQuaternion);const e=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),e<.001)this._tmpVector.scaleInPlace(2);else{const t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}n.impostor.setAngularVelocity(this._tmpVector)}o.copyFrom(s.rotationQuaternion),this._debugMode&&console.log(this._tmpVector,this._tmpQuaternion,"angular")}))}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}ny.Name=vl.b.PHYSICS_CONTROLLERS,ny.Version=1,vl.d.AddWebXRFeature(ny.Name,((e,t)=>()=>new ny(e,t)),ny.Version,!0);class sy extends Il.F{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new o.y3,this._tmpPos=new o.P,this._tmpQuat=new o._f,this._initHitTestSource=e=>{if(!e)return;const t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),i.space?this._xrSessionManager.session.requestHitTestSource(i).then((e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})):de.w1.Warn("waiting for viewer reference space to initialize")},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new r.y$,this.paused=!1,this.xrNativeFeatureName="hit-test",de.w1.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach())return!1;if(!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((e=>{this._transientXrHitTestSource=e}))}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)}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((e=>{this._processWebXRHitTestResult(e.results,e.inputSource)}))}}_processWebXRHitTestResult(e,t){const i=[];e.forEach((e=>{const n=e.getPose(this._xrSessionManager.referenceSpace);if(!n)return;const s=n.transform.position,r=n.transform.orientation;this._tmpPos.set(s.x,s.y,s.z),this._tmpQuat.set(r.x,r.y,r.z,r.w),o.y3.FromFloat32ArrayToRefScaled(n.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 a={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:e};i.push(a)})),this.onHitTestResultObservable.notifyObservers(i)}}sy.Name=vl.b.HIT_TEST,sy.Version=2,vl.d.AddWebXRFeature(sy.Name,((e,t)=>()=>new sy(e,t)),sy.Version,!1);class ry extends Il.F{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new r.y$,this.onFeaturePointsUpdatedObservable=new r.y$,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}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&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);const e=t.length/5,i=new Array,n=new Array;for(let s=0;s<e;s++){const e=5*s,r=t[e+4];this._featurePointCloud[r]?i.push(r):(this._featurePointCloud[r]={position:new o.P,confidenceValue:0},n.push(r)),this._featurePointCloud[r].position.x=t[e],this._featurePointCloud[r].position.y=t[e+1],this._featurePointCloud[r].position.z=t[e+2],this._featurePointCloud[r].confidenceValue=t[e+3]}n.length>0&&this.onFeaturePointsAddedObservable.notifyObservers(n),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}ry.Name=vl.b.FEATURE_POINTS,ry.Version=1,vl.d.AddWebXRFeature(ry.Name,(e=>()=>new ry(e)),ry.Version);var oy=i(9596);let ay=0;class ly extends Il.F{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new r.y$,this.onMeshRemovedObservable=new r.y$,this.onMeshUpdatedObservable=new r.y$,this.xrNativeFeatureName="mesh-detection",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)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){var t;try{if(!this.attached||!e)return;const i=null===(t=e.worldInformation)||void 0===t?void 0:t.detectedMeshes;if(i){const t=new Set;this._detectedMeshes.forEach(((e,n)=>{i.has(n)||t.add(n)})),t.forEach((e=>{const t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))})),i.forEach((t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{const i={id:ay++,xrMesh:t},n=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,n),this.onMeshAddedObservable.notifyObservers(n)}}))}}catch(e){console.log(e.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){if(t.xrMesh=e,t.worldParentNode=this._options.worldParentNode,this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=e.positions,t.normals=e.normals;else{t.positions=new Float32Array(e.positions.length);for(let i=0;i<e.positions.length;i+=3)t.positions[i]=e.positions[i],t.positions[i+1]=e.positions[i+1],t.positions[i+2]=-1*e.positions[i+2];if(e.normals){t.normals=new Float32Array(e.normals.length);for(let i=0;i<e.normals.length;i+=3)t.normals[i]=e.normals[i],t.normals[i+1]=e.normals[i+1],t.normals[i+2]=-1*e.normals[i+2]}}t.indices=e.indices;const n=i.getPose(e.meshSpace,this._xrSessionManager.referenceSpace);if(n){const e=t.transformationMatrix||new Gr.y3;Gr.y3.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}}return t}}var hy;ly.Name=vl.b.MESH_DETECTION,ly.Version=1,vl.d.AddWebXRFeature(ly.Name,((e,t)=>()=>new ly(e,t)),ly.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(hy||(hy={}));class cy extends Il.F{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new r.y$,this.onTrackableImageFoundObservable=new r.y$,this.onTrackedImageUpdatedObservable=new r.y$,this._trackableScoreStatus=hy.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((e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map(((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth}))),{trackedImages:this._originalTrackingRequest}}catch(e){return de.w1.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===hy.Waiting)return;if(this._trackableScoreStatus===hy.NotReceived)return void this._checkScoresAsync();const t=e.getImageTrackingResults();for(const i of t){let t=!1;const n=i.index,s=this._trackedImages[n];if(!s)continue;s.xrTrackingResult=i,s.realWorldWidth!==i.measuredWidthInMeters&&(s.realWorldWidth=i.measuredWidthInMeters,t=!0);const r=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(r){const e=s.transformationMatrix;o.y3.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}const a="emulated"===i.trackingState;s.emulated!==a&&(s.emulated=a,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==hy.NotReceived)return;this._trackableScoreStatus=hy.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(e&&0!==e.length){for(let t=0;t<e.length;++t)if("untrackable"==e[t])this.onUntrackableImageFoundObservable.notifyObservers(t);else{const e=this._originalTrackingRequest[t].image,i={id:t,originalBitmap:e,transformationMatrix:new o.y3,ratio:e.width/e.height};this._trackedImages[t]=i,this.onTrackableImageFoundObservable.notifyObservers(i)}this._trackableScoreStatus=e.length>0?hy.Received:hy.NotReceived}else this._trackableScoreStatus=hy.NotReceived}}cy.Name=vl.b.IMAGE_TRACKING,cy.Version=1,vl.d.AddWebXRFeature(cy.Name,((e,t)=>()=>new cy(e,t)),cy.Version,!1);class uy extends Il.F{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",de.w1.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!(!super.attach()||!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type||(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),0))}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return de.w1.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){const e=document.querySelector(this.options.element);if(null===e)return de.w1.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}}}}uy.Name=vl.b.DOM_OVERLAY,uy.Version=1,vl.d.AddWebXRFeature(uy.Name,((e,t)=>()=>new uy(e,t)),uy.Version,!1);class dy extends Il.F{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,n,s,r,a,l;super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=null,this._tmpRotationMatrix=o.y3.Identity(),this._tmpTranslationDirection=new o.P,this._tmpMovementTranslation=new o.P,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController)for(const i of this._currentRegistrationConfigurations){let n=null;if(i.allowedComponentTypes)for(const t of i.allowedComponentTypes){const i=e.motionController.getComponentOfType(t);if(null!==i){n=i;break}}if(i.mainComponentOnly){const t=e.motionController.getMainComponent();if(null===t)continue;n=t}if("function"==typeof i.componentSelectionPredicate&&(n=i.componentSelectionPredicate(e)),n&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)continue;if(null===n)continue;const s={registrationConfiguration:i,component:n};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=n.onAxisValueChangedObservable.add((e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)}))),"buttonChangedhandler"in i&&(s.onButtonChangedObserver=n.onButtonStateChangedObservable.add((()=>{n.changes.pressed&&i.buttonChangedhandler(n.changes.pressed,this._movementState,this._featureContext,this._xrInput)})))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}},t&&void 0!==t.xrInput?(Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=dy.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:null===(i=t.movementOrientationFollowsViewerPose)||void 0===i||i,movementSpeed:null!==(n=t.movementSpeed)&&void 0!==n?n:1,movementThreshold:null!==(s=t.movementThreshold)&&void 0!==s?s:.25,rotationEnabled:null===(r=t.rotationEnabled)||void 0===r||r,rotationSpeed:null!==(a=t.rotationSpeed)&&void 0!==a?a:1,rotationThreshold:null!==(l=t.rotationThreshold)&&void 0!==l?l:.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput):de.w1.Error('WebXRControllerMovement feature requires "xrInput" option.')}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)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._controllers={},!0)}_onXRFrame(e){if(this.attach){if(null===this._movementDirection&&(this._movementDirection=this._xrInput.xrCamera.rotationQuaternion.clone()),0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){const e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);!0===this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=e,this._movementDirection=this._xrInput.xrCamera.rotationQuaternion.multiply(o._f.RotationYawPitchRoll(e,0,0))):this._movementDirection.multiplyInPlace(o._f.RotationYawPitchRoll(3*e,0,0))}else!0===this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);0===this._movementState.moveX&&0===this._movementState.moveY||!this._featureContext.movementEnabled||(o.y3.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),o.P.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 e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}dy.Name=vl.b.MOVEMENT,dy.REGISTRATIONS={default:[{allowedComponentTypes:[xl.THUMBSTICK_TYPE,xl.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[xl.THUMBSTICK_TYPE,xl.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},dy.Version=1,vl.d.AddWebXRFeature(dy.Name,((e,t)=>()=>new dy(e,t)),dy.Version,!0);var py=i(4185);class fy extends Il.F{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=o.P.Up().negateInPlace(),this._lightColor=a.Wo.White(),this._intensity=1,this._sphericalHarmonics=new qa._,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new r.y$,this._updateReflectionCubeMap=()=>{var e;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const e=Date.now();if(e-this._cubeMapPollTime<this.options.cubeMapPollInterval)return;this._cubeMapPollTime=e}const t=this._getXRGLBinding().getReflectionCubeMap(this._xrLightProbe);if(t&&this._reflectionCubeMap){if(this._reflectionCubeMap._texture)null===(e=this._reflectionCubeMap._texture._hardwareTexture)||void 0===e||e.set(t),this._reflectionCubeMap._texture.getEngine().resetTextureCache();else{const e=new Ei.l(this._xrSessionManager.scene.getEngine(),Ei.S.Unknown);e.isCube=!0,e.invertY=!1,e._useSRGBBuffer="srgba8"===this.options.reflectionFormat,e.format=5,e.generateMipMaps=!0,e.type="srgba8"!==this.options.reflectionFormat?2:0,e.samplingMode=3,e.width=this._reflectionCubeMapTextureSize,e.height=this._reflectionCubeMapTextureSize,e._cachedWrapU=1,e._cachedWrapV=1,e._hardwareTexture=new Yi.B(t,this._getCanvasContext()),this._reflectionCubeMap._texture=e}this._reflectionCubeMap._texture.isReady=!0,this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap)}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new Sa.O("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new o.P(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=py.m.FALLOFF_GLTF),de.w1.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 null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){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=null!==(e=this.options.reflectionFormat)&&void 0!==e?e:this._xrSessionManager.session.preferredReflectionFormat||"srgba8";return this.options.reflectionFormat=t,this._xrSessionManager.session.requestLightProbe({reflectionFormat:t}).then((e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new Oa.V(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 null===this._xrLightProbe||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),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){var t;if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){const e=Date.now();if(e-this._lightEstimationPollTime<this.options.lightEstimationPollInterval)return;this._lightEstimationPollTime=e}if(this._xrLightEstimate=e.getLightEstimate(this._xrLightProbe),this._xrLightEstimate){this._intensity=Math.max(1,this._xrLightEstimate.primaryLightIntensity.x,this._xrLightEstimate.primaryLightIntensity.y,this._xrLightEstimate.primaryLightIntensity.z);const e=this._xrSessionManager.scene.useRightHandedSystem?1:-1;this.options.disableVectorReuse&&(this._lightDirection=new o.P,this._lightColor=new a.Wo,this.directionalLight&&(this.directionalLight.direction=this._lightDirection,this.directionalLight.diffuse=this._lightColor)),this._lightDirection.copyFromFloats(this._xrLightEstimate.primaryLightDirection.x,this._xrLightEstimate.primaryLightDirection.y,this._xrLightEstimate.primaryLightDirection.z*e),this._lightColor.copyFromFloats(this._xrLightEstimate.primaryLightIntensity.x/this._intensity,this._xrLightEstimate.primaryLightIntensity.y/this._intensity,this._xrLightEstimate.primaryLightIntensity.z/this._intensity),this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients),this._reflectionCubeMap&&!this.options.disableSphericalPolynomial&&(this._reflectionCubeMap.sphericalPolynomial=this._reflectionCubeMap.sphericalPolynomial||new qa.i,null===(t=this._reflectionCubeMap.sphericalPolynomial)||void 0===t||t.updateFromHarmonics(this._sphericalHarmonics)),this._lightDirection.negateInPlace(),this.directionalLight&&(this.directionalLight.direction.copyFrom(this._lightDirection),this.directionalLight.intensity=Math.min(this._intensity,1),this.directionalLight.diffuse.copyFrom(this._lightColor))}}}}fy.Name=vl.b.LIGHT_ESTIMATION,fy.Version=1,vl.d.AddWebXRFeature(fy.Name,((e,t)=>()=>new fy(e,t)),fy.Version,!1);class _y extends Il.F{constructor(e){super(e),this.onEyeTrackingStartedObservable=new r.y$,this.onEyeTrackingEndedObservable=new r.y$,this.onEyeTrackingFrameUpdateObservable=new r.y$,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new Yt.z(o.P.Zero(),o.P.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 e=t.transform.orientation;o.jp.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?o.P.RightHandedForwardReadOnly.rotateByQuaternionToRef(o.jp.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,o.jp.Quaternion[0].z*=-1,o.jp.Quaternion[0].w*=-1,o.P.LeftHandedForwardReadOnly.rotateByQuaternionToRef(o.jp.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))}}_y.Name=vl.b.EYE_TRACKING,_y.Version=1,vl.d.AddWebXRFeature(_y.Name,(e=>()=>new _y(e)),_y.Version,!1);class my{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i<e;++i)this._samples.push(t?t():o.FM.Zero())}get length(){return this._samples.length}push(e,t){this._idx=(this._idx+this._samples.length-1)%this._samples.length,this.at(0).copyFromFloats(e,t)}at(e){if(e>=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class gy{constructor(){this._samples=new my(20),this._entropy=0,this.onFirstStepDetected=new r.y$}update(e,t,i,n){this._samples.push(e,t);const s=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=o.FM.Distance(s,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let r;for(r=this._samePointCheckStartIdx;r<this._samples.length&&!(o.FM.DistanceSquared(s,this._samples.at(r))<this._samePointSquaredDistanceThreshold);++r);if(r===this._samples.length)return;let a=-1,l=0;for(let e,t=1;t<r;++t)e=o.FM.DistanceSquared(s,this._samples.at(t)),e>a&&(l=t,a=e);if(a<this._apexSquaredDistanceThreshold)return;const h=this._samples.at(l),c=h.subtract(s);c.normalize();const u=o.jp.Vector2[0];let d,p,f=0;for(let e=1;e<r;++e)p=this._samples.at(e),p.subtractToRef(s,u),d=o.FM.Dot(c,u),f+=u.lengthSquared()-d*d;if(f>r*this._squaredProjectionDistanceThreshold)return;const _=o.jp.Vector3[0];_.set(i,n,0);const m=o.jp.Vector3[1];m.set(c.x,c.y,0);const g=o.P.Cross(_,m).z>0,v=s.clone(),y=s.clone();h.subtractToRef(s,c),g?(c.scaleAndAddToRef(this._axisToApexShrinkFactor,v),c.scaleAndAddToRef(this._axisToApexExtendFactor,y)):(c.scaleAndAddToRef(this._axisToApexExtendFactor,v),c.scaleAndAddToRef(this._axisToApexShrinkFactor,y)),this.onFirstStepDetected.notifyObservers({leftApex:v,rightApex:y,currentPosition:s,currentStepDirection:g?"right":"left"})}reset(){for(let e=0;e<this._samples.length;++e)this._samples.at(e).copyFromFloats(0,0)}get _samePointCheckStartIdx(){return Math.floor(this._samples.length/3)}get _samePointSquaredDistanceThreshold(){return 9e-4}get _apexSquaredDistanceThreshold(){return.0081}get _squaredProjectionDistanceThreshold(){return 9e-4}get _axisToApexShrinkFactor(){return.8}get _axisToApexExtendFactor(){return-1.6}get _entropyDecayFactor(){return.93}get _entropyThreshold(){return.4}}class vy{constructor(e,t,i,n){this._leftApex=new o.FM,this._rightApex=new o.FM,this._currentPosition=new o.FM,this._axis=new o.FM,this._axisLength=-1,this._forward=new o.FM,this._steppingLeft=!1,this._t=-1,this._maxT=-1,this._maxTPosition=new o.FM,this._vitality=0,this.onMovement=new r.y$,this.onFootfall=new r.y$,this._reset(e,t,i,"left"===n)}_reset(e,t,i,n){this._leftApex.copyFrom(e),this._rightApex.copyFrom(t),this._steppingLeft=n,this._steppingLeft?(this._leftApex.subtractToRef(this._rightApex,this._axis),this._forward.copyFromFloats(-this._axis.y,this._axis.x)):(this._rightApex.subtractToRef(this._leftApex,this._axis),this._forward.copyFromFloats(this._axis.y,-this._axis.x)),this._axisLength=this._axis.length(),this._forward.scaleInPlace(1/this._axisLength),this._updateTAndVitality(i.x,i.y),this._maxT=this._t,this._maxTPosition.copyFrom(i),this._vitality=1}_updateTAndVitality(e,t){this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._currentPosition.subtractInPlace(this._rightApex):this._currentPosition.subtractInPlace(this._leftApex);const i=this._t,n=o.FM.Dot(this._currentPosition,this._axis);this._t=n/(this._axisLength*this._axisLength);const s=this._currentPosition.lengthSquared()-n/this._axisLength*(n/this._axisLength);this._vitality*=.92-100*Math.max(s-.0016,0)+Math.max(this._t-i,0)}update(e,t){if(this._vitality<this._vitalityThreshold)return!1;const i=this._t;return this._updateTAndVitality(e,t),this._t>this._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitality<this._vitalityThreshold||(this._t>i&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),this._axisLength<.03))}get _vitalityThreshold(){return.1}get forward(){return this._forward}}class yy{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new gy,this._walker=null,this._movement=new o.FM,this._millisecondsSinceLastUpdate=yy._MillisecondsPerUpdate,this.movementThisFrame=o.P.Zero(),this._engine=e,this._detector.onFirstStepDetected.add((e=>{this._walker||(this._walker=new vy(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add((()=>{console.log("Footfall!")})),this._walker.onMovement.add((e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)})))}))}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=yy._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=yy._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 xy extends Il.F{static get Name(){return vl.b.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new o.P,this._forward=new o.P,this._position=new o.P,this._movement=new o.P,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&_.Y.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 void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!(!this.isCompatible||!super.attach()||(this._walker=new yy(this._sessionManager.scene.getEngine()),0))}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,n=t.transform.matrix;this._up.copyFromFloats(n[4],n[5],i*n[6]),this._forward.copyFromFloats(n[8],n[9],i*n[10]),this._position.copyFromFloats(n[12],n[13],i*n[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||o.P.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}vl.d.AddWebXRFeature(xy.Name,((e,t)=>()=>new xy(e,t)),xy.Version,!1);class by extends Hi{constructor(e,t,i,n,s,r){super(e,t,i,n,r),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=n,this.isMultiview=s,this.createRTTProvider=r}}class Ty extends qi{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){const i=this._lastSubImages.get(t),n="left"==t?0:1;return this._renderTargetTextures[n]&&(null==i?void 0:i.textureWidth)===e.textureWidth&&(null==i?void 0:i.textureHeight)==e.textureHeight||(this._renderTargetTextures[n]=this._createRenderTargetTexture(e.textureWidth,e.textureHeight,null,e.colorTexture,e.depthStencilTexture,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:e.textureWidth,framebufferHeight:e.textureHeight}),this._lastSubImages.set(t,e),this._renderTargetTextures[n]}_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){const i=t.textureWidth,n=t.textureHeight,s=t.viewport;e.x=s.x/i,e.y=s.y/n,e.width=s.width/i,e.height=s.height/n}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class Sy extends by{constructor(e,t,i){super((()=>e.textureWidth),(()=>e.textureHeight),e,"XRProjectionLayer",t,(e=>new Ey(e,i,this))),this.layer=e}}class Ey extends Ty{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)}}const Cy={},Ay={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};class Py extends Il.F{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={...Ay},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)}createXRWebGLLayer(e=Cy){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new Ki(t)}createProjectionLayer(e=Ay,t=!1){if(t&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)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={...this._xrSessionManager.session.renderState};t.baseLayer=void 0,t.layers=e.map((e=>e.layer)),this._xrSessionManager.updateRenderState(t),this._xrSessionManager._setBaseLayerWrapper(e.length>0?e[0]:null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){}}Py.Name=vl.b.LAYERS,Py.Version=1,vl.d.AddWebXRFeature(Py.Name,((e,t)=>()=>new Py(e,t)),Py.Version,!1);class Ry extends Il.F{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(),n=new Ei.l(i,Ei.S.Unknown);return n.isCube=!1,n.invertY=!1,n._useSRGBBuffer=!1,n.format="ushort"===this.depthDataFormat?2:5,n.generateMipMaps=!1,n.type="ushort"===this.depthDataFormat?5:1,n.samplingMode=7,n.width=null!==(e=this.width)&&void 0!==e?e:0,n.height=null!==(t=this.height)&&void 0!==t?t:0,n._cachedWrapU=1,n._cachedWrapV=1,n._hardwareTexture=new Yi.B(this._cachedWebGLTexture,i._gl),n}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?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 r.y$,this.xrNativeFeatureName="depth-sensing",de.w1.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!!super.attach(e)&&(null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0))}dispose(){var e;null===(e=this._cachedDepthImageTexture)||void 0===e||e.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(const t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:de.w1.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const n=e.getDepthInformation(t);if(null===n)return;const{data:s,width:r,height:o,rawValueToMeters:a,getDepthInMeters:l}=n;switch(this._width=r,this._height=o,this._rawValueToMeters=a,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(n)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Ee.l.CreateRTexture(null,r,o,this._xrSessionManager.scene,!1,!0,Ce.x.NEAREST_SAMPLINGMODE,ue.D.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map((e=>e*a)));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map((e=>e*a)))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const n=e.getDepthInformation(t);if(null===n)return;const{texture:s,width:r,height:o}=n;this._width=r,this._height=o,this._cachedWebGLTexture=s;const a=this._xrSessionManager.scene,l=a.getEngine().wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Ee.l.CreateRTexture(null,r,o,a,!1,!0,Ce.x.NEAREST_SAMPLINGMODE,"ushort"===i?ue.D.TEXTURETYPE_UNSIGNED_BYTE:ue.D.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){const e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((i=>{i(e&&t?{depthSensing:{usagePreference:this.options.usagePreference.map((e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:this.options.dataFormatPreference.map((e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}}:{})}))}}Ry.Name=vl.b.DEPTH_SENSING,Ry.Version=1,vl.d.AddWebXRFeature(Ry.Name,((e,t)=>()=>new Ry(e,t)),Ry.Version,!1);class My extends bl{constructor(e,t,i){super(e,Iy[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(){}}Al.RegisterController("generic-hand-select-grasp",((e,t)=>new My(t,e.gamepad,e.handedness)));const Iy={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 Dy extends bl{constructor(e,t,i){super(e,Oy["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="";return e="left"===this.handedness?Dy.MODEL_LEFT_FILENAME:Dy.MODEL_RIGHT_FILENAME,{filename:e,path:Dy.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){const e=ta.n.IsPluginForExtensionAvailable(".glb");return e||_.Y.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach(((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){const i=this._mapping.buttons[e],n=i.rootNodeName;if(!n)return void _.Y.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);const s=this._getChildByName(this.rootMesh,n);if(!s)return void _.Y.Warn("Missing button mesh with name: "+n);if(i.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){const t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add((e=>{this._lerpTransform(i,e.value)}),void 0,!0)}else _.Y.Warn("Missing button submesh under mesh with name: "+n)}})),this.getComponentIds().forEach((e=>{const t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach((i=>{if(!this.rootMesh)return;const n=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,n.rootNodeName);s?(n.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),n.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),n.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),n.valueMesh&&n.minMesh&&n.maxMesh?t&&t.onAxisValueChangedObservable.add((e=>{const t="x-axis"===i?e.x:e.y;this._lerpTransform(n,t,!0)}),void 0,!0):_.Y.Warn("Missing axis submesh under mesh with name: "+n.rootNodeName)):_.Y.Warn("Missing axis mesh with name: "+n.rootNodeName)}))})))}_setRootMesh(e){let t;this.rootMesh=new Nt.Kj(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i<e.length;i++){const n=e[i];n.isPickable=!1,n.parent||(t=n)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}Dy.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/",Dy.MODEL_LEFT_FILENAME="left.glb",Dy.MODEL_RIGHT_FILENAME="right.glb",Al.RegisterController("windows-mixed-reality",((e,t)=>new Dy(t,e.gamepad,e.handedness)));const Oy={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 wy extends bl{constructor(e,t,i,n=!1,s=!1){super(e,Ny[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?wy.MODEL_LEFT_FILENAME:wy.MODEL_RIGHT_FILENAME,{filename:e,path:this._isQuest()?wy.QUEST_MODEL_BASE_URL:wy.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach((e=>{const n=e&&this.getComponent(e);n&&n.onButtonStateChangedObservable.add((n=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(t||(this._modelRootNode.getChildren()[3].rotation.x=.2*-n.value,this._modelRootNode.getChildren()[3].position.y=.005*-n.value,this._modelRootNode.getChildren()[3].position.z=.005*-n.value));case"xr-standard-squeeze":return void(t||(this._modelRootNode.getChildren()[4].position.x=i*n.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(t||(n.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(t||(n.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new Nt.Kj(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0)),e.forEach((e=>{e.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}}wy.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",wy.MODEL_LEFT_FILENAME="left.babylon",wy.MODEL_RIGHT_FILENAME="right.babylon",wy.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",Al.RegisterController("oculus-touch",((e,t)=>new wy(t,e.gamepad,e.handedness))),Al.RegisterController("oculus-touch-legacy",((e,t)=>new wy(t,e.gamepad,e.handedness,!0)));const Ny={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 Fy extends bl{constructor(e,t,i){super(e,Ly[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:Fy.MODEL_FILENAME,path:Fy.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add((t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(this._modelRootNode.getChildren()[6].rotation.x=.15*-t.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new Nt.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}Fy.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",Fy.MODEL_FILENAME="wand.babylon",Al.RegisterController("htc-vive",((e,t)=>new Fy(t,e.gamepad,e.handedness)));const Ly={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 By{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 e;return null!==(e=this._nativeImpl._imageTrackingResults)&&void 0!==e?e:[]}}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 n=this._xrTransform.orientation;return n.x=this._xrPoseVectorData[4],n.y=this._xrPoseVectorData[5],n.z=this._xrPoseVectorData[6],n.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")}}$s("NativeXRFrame",By)},9257:(e,t,i)=>{i.d(t,{N:()=>c});var n=i(9472),s=i(4141),r=i(3956),o=i(5757),a=i(1431),l=i(4934);class h{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new o.y$,this._onClonedObservable=new o.y$}}class c{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,n){const s=this._NodeConstructors[e];return s?s(t,i,n):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null){this._isDirty=!1,this._nodeDataStorage=new h,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new o.y$,this._parentContainer=null,this.animations=new Array,this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=s.y3.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new o.y$,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||a.l.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return-1!==this._behaviors.indexOf(e)||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={},this._cache.parent=void 0}updateCache(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,this._updateCache())}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return!this._parentNode||!this._parentNode._isDirty&&this._parentUpdateId===this._parentNode._childUpdateId&&this._parentNode.isSynchronized()}isSynchronized(){return this._cache.parent!==this._parentNode?(this._cache.parent=this._parentNode,!1):!(this._parentNode&&!this.isSynchronizedWithParent())&&this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children&&this._children.forEach((e=>{e._syncParentEnabledState()}))}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let n=0;n<this._children.length;n++){const s=this._children[n];i&&!i(s)||e.push(s),t||s._getDescendants(e,!1,i)}}getDescendants(e,t){const i=new Array;return this._getDescendants(i,e,t),i}getChildMeshes(e,t){const i=[];return this._getDescendants(i,e,(e=>(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;t<this.animations.length;t++){const i=this.animations[t];if(i.name===e)return i}return null}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=c._AnimationRangeFactory(e,t,i);for(let n=0,s=this.animations.length;n<s;n++)this.animations[n]&&this.animations[n].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,n=this.animations.length;i<n;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}clone(e,t,i){const n=r.p4.Clone((()=>new c(e,this.getScene())),this);if(t&&(n.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i<t.length;i++){const s=t[i];s.clone(e+"."+s.name,n)}}return n}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}beginAnimation(e,t,i,n){const s=this.getAnimationRange(e);return s?this._scene.beginAnimation(this,s.from,s.to,t,i,n):null}serializeAnimationRanges(){const e=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const n={};n.name=t,n.from=i.from,n.to=i.to,e.push(n)}return e}computeWorldMatrix(e){return this._worldMatrix||(this._worldMatrix=s.y3.Identity()),this._worldMatrix}dispose(e,t=!1){if(this._nodeDataStorage._isDisposed=!0,!e){const i=this.getDescendants(!0);for(const n of i)n.dispose(e,t)}this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear();for(const e of this._behaviors)e.detach();this._behaviors.length=0,this.metadata=null}static ParseAnimationRanges(e,t,i){if(t.ranges)for(let i=0;i<t.ranges.length;i++){const n=t.ranges[i];e.createAnimationRange(n.name,n.from,n.to)}}getHierarchyBoundingVectors(e=!0,t=null){let i,n;this.getScene().incrementRenderId(),this.computeWorldMatrix(!0);const r=this;if(r.getBoundingInfo&&r.subMeshes){const e=r.getBoundingInfo();i=e.boundingBox.minimumWorld.clone(),n=e.boundingBox.maximumWorld.clone()}else i=new s.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new s.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e){const e=this.getDescendants(!1);for(const r of e){const e=r;if(e.computeWorldMatrix(!0),t&&!t(e))continue;if(!e.getBoundingInfo||0===e.getTotalVertices())continue;const o=e.getBoundingInfo().boundingBox,a=o.minimumWorld,l=o.maximumWorld;s.P.CheckExtends(a,i,n),s.P.CheckExtends(l,i,n)}}return{min:i,max:n}}}c._AnimationRangeFactory=(e,t,i)=>{throw(0,l.S)("AnimationRange")},c._NodeConstructors={},(0,n.gn)([(0,r.qC)()],c.prototype,"name",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"id",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"uniqueId",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"state",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"metadata",void 0)},1057:(e,t,i)=>{i.d(t,{x:()=>L,a:()=>R});var n=i(7257),s=i(8108),r=i(5757),o=i(5363),a=i(7090),l=i(4875),h=i(4141),c=i(5655),u=i(4475),d=i(3743),p=i(5670),f=i(2633),_=i(727),m=i(4221),g=i(2333),v=i(6797),y=i(1431),x=i(4934),b=i(1903),T=i(1803),S=i(2925),E=i(3255),C=i(3739);class A{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}}class P{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._totalPointersPressed=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new h.FM(0,0),this._previousStartingPointerPosition=new h.FM(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||y.l.LastCreatedScene,this._scene}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new h.FM(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){const t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){const i=this._scene,n=i.getEngine(),s=n.getInputElement();s&&(s.tabIndex=n.canvasTabIndex,i.doNotHandleCursors||(s.style.cursor=i.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,i);for(const t of i._pointerMoveStage){const i=!!(null==e?void 0:e.pickedMesh);e=t.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,i,s)}const r=t.inputIndex>=E.Fz.MouseWheelX&&t.inputIndex<=E.Fz.MouseWheelZ?b.kD.POINTERWHEEL:b.kD.POINTERMOVE;let o;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,r)),e?(o=new b.R5(r,t,e),this._setRayOnPointerInfo(e,t)):(o=new b.R5(r,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,r)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,h.y3.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const n=this._scene,s=new b.FV(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,e.originMesh&&(s.nearInteractionPickingInfo=e)),n.onPrePointerObservable.notifyObservers(s,i),!!s.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,!1,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const n=i.getEngine().getInputElement();if(null==e?void 0:e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&n&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(n.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=E.Fz.Move,this._checkPrePointerObservable(e,i,b.kD.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,b.kD.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(null==e?void 0:e.pickedMesh){this._pickedDownMesh=e.pickedMesh;const n=e.pickedMesh._getActionManagerForTrigger();if(n){if(n.hasPickTriggers)switch(n.processTrigger(5,f.V.CreateNew(e.pickedMesh,t)),t.button){case 0:n.processTrigger(2,f.V.CreateNew(e.pickedMesh,t));break;case 1:n.processTrigger(4,f.V.CreateNew(e.pickedMesh,t));break;case 2:n.processTrigger(3,f.V.CreateNew(e.pickedMesh,t))}n.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);(null==e?void 0:e.pickedMesh)&&n&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>P.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,f.V.CreateNew(e.pickedMesh,t)))}),P.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let n;const s=b.kD.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,s),n=new b.R5(s,t,e),this._setRayOnPointerInfo(e,t)):n=new b.R5(s,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(n,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const n=new PointerEvent("pointerup",t);n.inputIndex=E.Fz.Move;const s=new A;i?s.doubleClick=!0:s.singleClick=!0,this._checkPrePointerObservable(e,n,b.kD.POINTERUP)||this._processPointerUp(e,n,s)}_processPointerUp(e,t,i){const n=this._scene;if(null==e?void 0:e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(n.onPointerPick&&n.onPointerPick(t,e),i.singleClick&&!i.ignore&&n.onPointerObservable.observers.length>this._cameraObserverCount)){const i=b.kD.POINTERPICK,s=new b.R5(i,t,e);this._setRayOnPointerInfo(e,t),n.onPointerObservable.notifyObservers(s,i)}const s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,f.V.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,f.V.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,f.V.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const s of n._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,f.V.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const s=new b.R5(b.kD.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),n.onPointerObservable.notifyObservers(s,b.kD.POINTERUP),n.onPointerUp&&n.onPointerUp(t,e,b.kD.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let s=0;if(i.singleClick?s=b.kD.POINTERTAP:i.doubleClick&&(s=b.kD.POINTERDOUBLETAP),s){const i=new b.R5(s,t,e);n.onPointerObservable.hasObservers()&&n.onPointerObservable.hasSpecificMask(s)&&n.onPointerObservable.notifyObservers(i,s)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,n=null){const s=this._scene,r=s.getEngine();n||(n=r.getInputElement()),this._alreadyAttached&&this.detachControl(),n&&(this._alreadyAttachedTo=n),this._deviceSourceManager=new C.U(r),this._initActionManager=e=>{if(!this._meshPickProceed){const t=s.skipPointerUpPicking||0===s._registeredActions&&!this._checkForPicking()&&!s.onPointerUp?null:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,!1,s.cameraToUseForPointers);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>P.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=b.kD.POINTERTAP,n=new b.R5(i,t,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(i)&&s.onPointerObservable.notifyObservers(n,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,n)=>{var s,r;const o=new A;this._currentPickResult=null;let a=null,l=e.hasSpecificMask(b.kD.POINTERPICK)||t.hasSpecificMask(b.kD.POINTERPICK)||e.hasSpecificMask(b.kD.POINTERTAP)||t.hasSpecificMask(b.kD.POINTERTAP)||e.hasSpecificMask(b.kD.POINTERDOUBLETAP)||t.hasSpecificMask(b.kD.POINTERDOUBLETAP);!l&&T.O&&(a=this._initActionManager(a,o),a&&(l=a.hasPickTriggers));let h=!1;if(l){const l=i.button;if(o.hasSwiped=this._isPointerSwiping(),!o.hasSwiped){let c=!P.ExclusiveDoubleClickMode;if(c||(c=!e.hasSpecificMask(b.kD.POINTERDOUBLETAP)&&!t.hasSpecificMask(b.kD.POINTERDOUBLETAP),c&&!T.O.HasSpecificTrigger(6)&&(a=this._initActionManager(a,o),a&&(c=!a.hasSpecificTrigger(6)))),c)(Date.now()-this._previousStartingPointerTime>P.DoubleClickDelay||l!==this._previousButtonPressed)&&(o.singleClick=!0,n(o,this._currentPickResult),h=!0);else{const e={evt:i,clickInfo:o,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,l,o,n),P.DoubleClickDelay)};this._delayedClicks[l]=e}let u=e.hasSpecificMask(b.kD.POINTERDOUBLETAP)||t.hasSpecificMask(b.kD.POINTERDOUBLETAP);!u&&T.O.HasSpecificTrigger(6)&&(a=this._initActionManager(a,o),a&&(u=a.hasSpecificTrigger(6))),u&&(l===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<P.DoubleClickDelay&&!this._doubleClickOccured?(o.hasSwiped||this._isPointerSwiping()?(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=l,P.ExclusiveDoubleClickMode?(this._delayedClicks[l]&&(clearTimeout(null===(r=this._delayedClicks[l])||void 0===r?void 0:r.timeoutId),this._delayedClicks[l]=null),n(o,this._previousPickResult)):n(o,this._currentPickResult)):(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,o.doubleClick=!0,o.ignore=!1,P.ExclusiveDoubleClickMode&&this._delayedClicks[l]&&(clearTimeout(null===(s=this._delayedClicks[l])||void 0===s?void 0:s.timeoutId),this._delayedClicks[l]=null),n(o,this._currentPickResult)),h=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=l))}}h||n(o,this._currentPickResult)},this._onPointerMove=e=>{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>P.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>P.DragMovementThreshold),r.isPointerLock&&r._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=E.Fz.MouseWheelX&&e.inputIndex<=E.Fz.MouseWheelZ?b.kD.POINTERWHEEL:b.kD.POINTERMOVE))return;if(!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking)return void this._processPointerMove(new p.p,e);s.pointerMovePredicate||(s.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!s.cameraToUseForPointers||0!=(s.cameraToUseForPointers.layerMask&e.layerMask)));const t=s._registeredActions>0?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{var t;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,P.ExclusiveDoubleClickMode)for(let i=0;i<this._delayedClicks.length;i++)if(this._delayedClicks[i])if(e.button===i)clearTimeout(null===(t=this._delayedClicks[i])||void 0===t?void 0:t.timeoutId);else{const e=this._delayedClicks[i].clickInfo;this._doubleClickOccured=!1,e.singleClick=!0,e.ignore=!1;const t=this._delayedClicks[i].evt,n=b.kD.POINTERTAP,r=new b.R5(n,t,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(r,n),this._delayedClicks[i]=null}if(this._updatePointerPosition(e),-1===this._swipeButtonPressed&&(this._swipeButtonPressed=e.button),s.preventDefaultOnPointerDown&&n&&(e.preventDefault(),n.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),this._checkPrePointerObservable(null,e,b.kD.POINTERDOWN))return;if(!s.cameraToUseForPointers&&!s.activeCamera)return;let i;this._pointerCaptures[e.pointerId]=!0,s.pointerDownPredicate||(s.pointerDownPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||0!=(s.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,i=s.skipPointerDownPicking||0===s._registeredActions&&!this._checkForPicking()&&!s.onPointerDown?new p.p:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,!1,s.cameraToUseForPointers),this._processPointerDown(i,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),s.preventDefaultOnPointerUp&&n&&(e.preventDefault(),n.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,e,((t,i)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,b.kD.POINTERUP))return void(this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1));t.hasSwiped||(t.singleClick&&s.onPrePointerObservable.hasSpecificMask(b.kD.POINTERTAP)&&this._checkPrePointerObservable(null,e,b.kD.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&s.onPrePointerObservable.hasSpecificMask(b.kD.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,b.kD.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(s.cameraToUseForPointers||s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||0!=(s.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(T.O&&T.O.HasTriggers||this._checkForPicking()||s.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=S.OG.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){const i=new S.WZ(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const i=new S.NG(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(14,f.V.CreateNewFromScene(s,e))},this._onKeyUp=e=>{const t=S.OG.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){const i=new S.WZ(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const i=new S.NG(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(15,f.V.CreateNewFromScene(s,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((n=>{n.deviceType===E.Yi.Mouse?n.onInputChangedObservable.add((s=>{s.inputIndex===E.Fz.LeftClick||s.inputIndex===E.Fz.MiddleClick||s.inputIndex===E.Fz.RightClick||s.inputIndex===E.Fz.BrowserBack||s.inputIndex===E.Fz.BrowserForward?t&&1===n.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===n.getInput(s.inputIndex)&&this._onPointerUp(s):i&&(s.inputIndex===E.Fz.Move?this._onPointerMove(s):s.inputIndex!==E.Fz.MouseWheelX&&s.inputIndex!==E.Fz.MouseWheelY&&s.inputIndex!==E.Fz.MouseWheelZ||this._onPointerMove(s))})):n.deviceType===E.Yi.Touch?n.onInputChangedObservable.add((s=>{s.inputIndex===E.Fz.LeftClick&&(t&&1===n.getInput(s.inputIndex)?(this._onPointerDown(s),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===n.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===E.Fz.Move&&this._onPointerMove(s)})):n.deviceType===E.Yi.Keyboard&&n.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,n){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const s=this._meshUnderPointerId[t];let r;s&&(r=s._getActionManagerForTrigger(10),r&&r.processTrigger(10,f.V.CreateNew(s,n,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,r=e._getActionManagerForTrigger(9),r&&r.processTrigger(9,f.V.CreateNew(e,n,{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]}}P.DragMovementThreshold=10,P.LongPressDelay=500,P.DoubleClickDelay=300,P.ExclusiveDoubleClickMode=!1;var R,M=i(8215),I=i(4649),D=i(1560),O=i(8718),w=i(5661),N=i(4185),F=i(5860);!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(R||(R={}));class L extends c.p{static DefaultMaterialFactory(e){throw(0,x.S)("StandardMaterial")}static CollisionCoordinatorFactory(){throw(0,x.S)("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 R.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case R.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case R.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}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 unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return P.DragMovementThreshold}static set DragMovementThreshold(e){P.DragMovementThreshold=e}static get LongPressDelay(){return P.LongPressDelay}static set LongPressDelay(e){P.LongPressDelay=e}static get DoubleClickDelay(){return P.DoubleClickDelay}static set DoubleClickDelay(e){P.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return P.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){P.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){var n;const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:null!==(n=this.activeCamera.globalPosition)&&void 0!==n?n:this.activeCamera.devicePosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return h.jp.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,h.jp.Vector4[0].x,h.jp.Vector4[0].y,h.jp.Vector4[0].z):e.setVector4(t,h.jp.Vector4[0])),h.jp.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=(0,F.M)(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=L.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=L.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 P(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new I.HE(.2,.2,.3,1),this.ambientColor=new I.Wo(0,0,0),this.environmentIntensity=1,this._performancePriority=R.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new r.y$,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=new Array,this.onDisposeObservable=new r.y$,this._onDisposeObserver=null,this.onBeforeRenderObservable=new r.y$,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new r.y$,this.onAfterRenderCameraObservable=new r.y$,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new r.y$,this.onAfterAnimationsObservable=new r.y$,this.onBeforeDrawPhaseObservable=new r.y$,this.onAfterDrawPhaseObservable=new r.y$,this.onReadyObservable=new r.y$,this.onBeforeCameraRenderObservable=new r.y$,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new r.y$,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new r.y$,this.onAfterActiveMeshesEvaluationObservable=new r.y$,this.onBeforeParticlesRenderingObservable=new r.y$,this.onAfterParticlesRenderingObservable=new r.y$,this.onDataLoadedObservable=new r.y$,this.onNewCameraAddedObservable=new r.y$,this.onCameraRemovedObservable=new r.y$,this.onNewLightAddedObservable=new r.y$,this.onLightRemovedObservable=new r.y$,this.onNewGeometryAddedObservable=new r.y$,this.onGeometryRemovedObservable=new r.y$,this.onNewTransformNodeAddedObservable=new r.y$,this.onTransformNodeRemovedObservable=new r.y$,this.onNewMeshAddedObservable=new r.y$,this.onMeshRemovedObservable=new r.y$,this.onNewSkeletonAddedObservable=new r.y$,this.onSkeletonRemovedObservable=new r.y$,this.onNewMaterialAddedObservable=new r.y$,this.onNewMultiMaterialAddedObservable=new r.y$,this.onMaterialRemovedObservable=new r.y$,this.onMultiMaterialRemovedObservable=new r.y$,this.onNewTextureAddedObservable=new r.y$,this.onTextureRemovedObservable=new r.y$,this.onBeforeRenderTargetsRenderObservable=new r.y$,this.onAfterRenderTargetsRenderObservable=new r.y$,this.onBeforeStepObservable=new r.y$,this.onAfterStepObservable=new r.y$,this.onActiveCameraChanged=new r.y$,this.onActiveCamerasChanged=new r.y$,this.onBeforeRenderingGroupObservable=new r.y$,this.onAfterRenderingGroupObservable=new r.y$,this.onMeshImportedObservable=new r.y$,this.onAnimationFileImportedObservable=new r.y$,this._registeredForLateAnimationBindings=new o.f(256),this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1,this.onPrePointerObservable=new r.y$,this.onPointerObservable=new r.y$,this.onPreKeyboardObservable=new r.y$,this.onKeyboardObservable=new r.y$,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=L.FOGMODE_NONE,this.fogColor=new I.Wo(.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 h.P(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=new Array,this.importedMeshesFiles=new Array,this.probesEnabled=!0,this._meshesForIntersections=new o.f(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new M.z,this._activeIndices=new M.z,this._activeParticles=new M.z,this._activeBones=new M.z,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 o.t(256),this._processedMaterials=new o.t(256),this._renderTargets=new o.f(256),this._materialsRenderTargets=new o.f(256),this._activeParticleSystems=new o.t(256),this._activeSkeletons=new o.f(32),this._softwareSkinnedMeshes=new o.f(32),this._activeAnimatables=new Array,this._transformMatrix=h.y3.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=g.H.Create(),this._beforeClearStage=g.H.Create(),this._beforeRenderTargetClearStage=g.H.Create(),this._gatherRenderTargetsStage=g.H.Create(),this._gatherActiveCameraRenderTargetsStage=g.H.Create(),this._isReadyForMeshStage=g.H.Create(),this._beforeEvaluateActiveMeshStage=g.H.Create(),this._evaluateSubMeshStage=g.H.Create(),this._preActiveMeshStage=g.H.Create(),this._cameraDrawRenderTargetStage=g.H.Create(),this._beforeCameraDrawStage=g.H.Create(),this._beforeRenderTargetDrawStage=g.H.Create(),this._beforeRenderingGroupDrawStage=g.H.Create(),this._beforeRenderingMeshStage=g.H.Create(),this._afterRenderingMeshStage=g.H.Create(),this._afterRenderingGroupDrawStage=g.H.Create(),this._afterCameraDrawStage=g.H.Create(),this._afterCameraPostProcessStage=g.H.Create(),this._afterRenderTargetDrawStage=g.H.Create(),this._afterRenderTargetPostProcessStage=g.H.Create(),this._afterRenderStage=g.H.Create(),this._pointerMoveStage=g.H.Create(),this._pointerDownStage=g.H.Create(),this._pointerUpStage=g.H.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=new Array;const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};this._engine=e||y.l.LastCreatedEngine,i.virtual?this._engine._virtualScenes.push(this):(y.l._LastCreatedScene=this,this._engine.scenes.push(this)),this._uid=null,this._renderingManager=new m.$(this),_.O&&(this.postProcessManager=new _.O(this)),(0,v.CG)()&&this.attachControl(),this._createUbo(),u.$&&(this._imageProcessingConfiguration=new u.$),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,t&&t.virtual||this._engine.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=this._getDefaultMeshCandidates.bind(this),this.getActiveSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getIntersectingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getCollidingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const i=this.getEngine();let n=!0;for(this._pendingData.length>0&&(n=!1),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t<this.meshes.length;t++){const s=this.meshes[t];if(!s.subMeshes||0===s.subMeshes.length)continue;if(!s.isReady(!0)){n=!1;continue}const r=s.hasThinInstances||"InstancedMesh"===s.getClassName()||"InstancedLinesMesh"===s.getClassName()||i.getCaps().instancedArrays&&s.instances.length>0;for(const e of this._isReadyForMeshStage)e.action(s,r)||(n=!1);if(!e)continue;const o=s.material||this.defaultMaterial;if(o)if(o._storeEffectOnSubMeshes)for(const e of s.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else o.hasRenderTargetTextures&&null!=o.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(o)&&(this._processedMaterials.push(o),this._materialsRenderTargets.concatWithNoDuplicate(o.getRenderTargetTextures()))}if(!n)return!1;if(!i.areAllEffectsReady())return!1;if(e)for(t=0;t<this._materialsRenderTargets.length;++t)if(!this._materialsRenderTargets.data[t].isReadyForRendering())return!1;for(t=0;t<this.geometries.length;t++)if(2===this.geometries[t].delayLoadState)return!1;if(this.activeCameras&&this.activeCameras.length>0){for(const e of this.activeCameras)if(!e.isReady(!0))return!1}else if(this.activeCamera&&!this.activeCamera.isReady(!0))return!1;for(const e of this.particleSystems)if(!e.isReady())return!1;return!0}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout((()=>{this.unregisterBeforeRender(t)}))};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout((()=>{this._executeOnceBeforeRender(e)}),t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=s.F.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,n){i||n||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?D.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=D.i.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,n):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new d.M(this._engine,void 0,!1,null!=e?e:"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return O.K.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&t<this.materials.length){if(t!==this.materials.length-1){const e=this.materials[this.materials.length-1];this.materials[t]=e,e._indexInSceneMaterialArray=t}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),t}removeActionManager(e){const t=this.actionManagers.indexOf(e);return-1!==t&&this.actionManagers.splice(t,1),t}removeTexture(e){const t=this.textures.indexOf(e);return-1!==t&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t}addLight(e){if(!this._blockEntityCollection){this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes();for(const t of this.meshes)-1===t.lightSources.indexOf(e)&&(t.lightSources.push(e),t._resyncLightSources());this.onNewLightAddedObservable.notifyObservers(e)}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(N.m.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),this.onNewCameraAddedObservable.notifyObservers(e),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),this.onNewSkeletonAddedObservable.notifyObservers(e))}addParticleSystem(e){this._blockEntityCollection||this.particleSystems.push(e)}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||this.animationGroups.push(e)}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),this.onNewMultiMaterialAddedObservable.notifyObservers(e))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneMaterialArray||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),this.onNewMaterialAddedObservable.notifyObservers(e))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}switchActiveCamera(e,t=!0){this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){const t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){const t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null}_getMaterial(e,t){for(let e=0;e<this.materials.length;e++){const i=this.materials[e];if(t(i))return i}if(e)for(let e=0;e<this.multiMaterials.length;e++){const i=this.multiMaterials[e];if(t(i))return i}return null}getMaterialByUniqueID(e,t=!1){return this._getMaterial(t,(t=>t.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null}getTextureByName(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].name===e)return this.textures[t];return null}getCameraById(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null}getCameraByUniqueId(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null}getCameraByName(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null}getBoneById(e){for(let t=0;t<this.skeletons.length;t++){const i=this.skeletons[t];for(let t=0;t<i.bones.length;t++)if(i.bones[t].id===e)return i.bones[t]}return null}getBoneByName(e){for(let t=0;t<this.skeletons.length;t++){const i=this.skeletons[t];for(let t=0;t<i.bones.length;t++)if(i.bones[t].name===e)return i.bones[t]}return null}getLightByName(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null}getLightById(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null}getLightByUniqueId(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null}getParticleSystemById(e){for(let t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null}getGeometryById(e){for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null}_getGeometryByUniqueId(e){if(this._geometriesByUniqueId){const t=this._geometriesByUniqueId[e];if(void 0!==t)return this.geometries[t]}else for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].uniqueId===e)return this.geometries[t];return null}pushGeometry(e,t){return!(!t&&this._getGeometryByUniqueId(e.uniqueId)||(this.addGeometry(e),this.onNewGeometryAddedObservable.notifyObservers(e),0))}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(t=this._geometriesByUniqueId[e.uniqueId],void 0===t)return!1}else if(t=this.geometries.indexOf(e),t<0)return!1;if(t!==this.geometries.length-1){const e=this.geometries[this.geometries.length-1];e&&(this.geometries[t]=e,this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null}getMeshesById(e){return this.meshes.filter((function(t){return t.id===e}))}getTransformNodeById(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getTransformNodeByUniqueId(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null}getTransformNodesById(e){return this.transformNodes.filter((function(t){return t.id===e}))}getMeshByUniqueId(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null}getLastMeshById(e){for(let t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const n=this.getLightById(e);if(n)return n;const s=this.getCameraById(e);if(s)return s;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const n=this.getLightByName(e);if(n)return n;const s=this.getCameraByName(e);if(s)return s;return this.getBoneByName(e)||null}getMeshByName(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null}getTransformNodeByName(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null}getLastSkeletonById(e){for(let t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null}getSkeletonById(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByName(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null}getMorphTargetManagerById(e){for(let t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null}getMorphTargetById(e){for(let t=0;t<this.morphTargetManagers.length;++t){const i=this.morphTargetManagers[t];for(let t=0;t<i.numTargets;++t){const n=i.getTarget(t);if(n.id===e)return n}}return null}getMorphTargetByName(e){for(let t=0;t<this.morphTargetManagers.length;++t){const i=this.morphTargetManagers[t];for(let t=0;t<i.numTargets;++t){const n=i.getTarget(t);if(n.name===e)return n}}return null}getPostProcessByName(e){for(let t=0;t<this.postProcesses.length;++t){const i=this.postProcesses[t];if(i.name===e)return i}return null}isActiveMesh(e){return-1!==this._activeMeshes.indexOf(e)}get uid(){return this._uid||(this._uid=n.w1.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new a.x),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new a.x),this._externalData.getOrAddWithFactory(e,t)}removeExternalData(e){return this._externalData.remove(e)}_evaluateSubMesh(e,t,i,n){if(n||e.isInFrustum(this._frustumPlanes)){for(const i of this._evaluateSubMeshStage)i.action(t,e);const i=e.getMaterial();null!=i&&(i.hasRenderTargetTextures&&null!=i.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(i)&&(this._processedMaterials.push(i),this._materialsRenderTargets.concatWithNoDuplicate(i.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,i))}}freeProcessedMaterials(){this._processedMaterials.dispose()}get blockfreeActiveMeshesAndRenderingGroups(){return this._preventFreeActiveMeshesAndRenderingGroups}set blockfreeActiveMeshesAndRenderingGroups(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)}freeActiveMeshes(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(let e=0;e<this.activeCameras.length;e++){const t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}}freeRenderingGroups(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(let e=0;e<this.textures.length;e++){const t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}}_isInIntermediateRendering(){return this._intermediateRendering}freezeActiveMeshes(e=!1,t,i,n=!0,s=!1){return this.executeWhenReady((()=>{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,n)for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._freeze();t&&t()}else i&&i("No active camera found")})),this}unfreezeActiveMeshes(){for(let e=0;e<this.meshes.length;e++){const t=this.meshes[e];t._internalAbstractMeshDataInfo&&(t._internalAbstractMeshDataInfo._isActive=!1)}for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this}_executeActiveContainerCleanup(e){(!this._engine.snapshotRendering||1!==this._engine.snapshotRenderingMode)&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce((()=>e.dispose()))}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(null===(e=this.activeCamera)||void 0===e||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t<e;t++)this._activeMeshes.data[t].computeWorldMatrix()}if(this._activeParticleSystems){const e=this._activeParticleSystems.length;for(let t=0;t<e;t++)this._activeParticleSystems.data[t].animate()}return void this._renderingManager.resetSprites()}if(!this.activeCamera)return;this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._materialsRenderTargets.reset();for(const e of this._beforeEvaluateActiveMeshStage)e.action();const t=this.getActiveMeshCandidates(),i=t.length;for(let e=0;e<i;e++){const i=t.data[e];if(i._internalAbstractMeshDataInfo._currentLODIsUpToDate=!1,i.isBlocked)continue;if(this._totalVertices.addCount(i.getTotalVertices(),!1),!i.isReady()||!i.isEnabled()||i.scaling.hasAZeroComponent)continue;i.computeWorldMatrix(),i.actionManager&&i.actionManager.hasSpecificTriggers2(12,13)&&this._meshesForIntersections.pushNoDuplicate(i);let n=this.customLODSelector?this.customLODSelector(i,this.activeCamera):i.getLOD(this.activeCamera);if(i._internalAbstractMeshDataInfo._currentLOD=n,i._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,null!=n&&(n!==i&&0!==n.billboardMode&&n.computeWorldMatrix(),i._preActivate(),i.isVisible&&i.visibility>0&&0!=(i.layerMask&this.activeCamera.layerMask)&&(this._skipFrustumClipping||i.alwaysSelectAsActiveMesh||i.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(i),this.activeCamera._activeMeshes.push(i),n!==i&&n._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(i);i._activate(this._renderId,!1)&&(i.isAnInstance?i._internalAbstractMeshDataInfo._actAsRegularMesh&&(n=i):n._internalAbstractMeshDataInfo._onlyForInstances=!1,n._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(i,n)),i._postActivate()}}if(this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e<this.particleSystems.length;e++){const t=this.particleSystems[e];if(!t.isStarted()||!t.emitter)continue;const i=t.emitter;i.position&&!i.isEnabled()||(this._activeParticleSystems.push(t),t.animate(),this._renderingManager.dispatchParticles(t))}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}_activeMesh(e,t){this._skeletonsEnabled&&null!==t.skeleton&&void 0!==t.skeleton&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&(t.skeleton.prepare(),this._activeBones.addCount(t.skeleton.bones.length,!1)),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t));let i=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){const n=this.getActiveSubMeshCandidates(t),s=n.length;i=i||1===s;for(let r=0;r<s;r++){const s=n.data[r];this._evaluateSubMesh(s,t,e,i)}}}updateTransformMatrix(e){if(this.activeCamera)if(this.activeCamera._renderingMultiview){const t=this.activeCamera._rigCameras[0],i=this.activeCamera._rigCameras[1];this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e),i.getViewMatrix(),i.getProjectionMatrix(e))}else this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(e))}_bindFrameBuffer(e,t=!0){e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer(),t&&this._clearFrameBuffer(e)}_clearFrameBuffer(e){if(e&&e._multiviewTexture);else if(e&&e.outputRenderTarget&&!e._renderingMultiview){const t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):t.skipInitialClear||(this.autoClear&&this._engine.clear(t.clearColor||this.clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())}_renderForCamera(e,t,i=!0){var s,r,o;if(e&&e._skipRendering)return;const a=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");if(a.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&i){let t=!0;e._renderingMultiview&&e.outputRenderTarget&&(t=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=t)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(let e=0;e<this._softwareSkinnedMeshes.length;e++){const t=this._softwareSkinnedMeshes.data[e];t.applySkeleton(t.skeleton)}this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let l=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){n.w1.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e<this._renderTargets.length;e++){const t=this._renderTargets.data[e];if(t._shouldRender()){this._renderId++;const e=t.activeCamera&&t.activeCamera!==this.activeCamera;t.render(e,this.dumpNextRenderTargets),l=!0}}n.w1.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)l=e.action(this.activeCamera)||l;this._intermediateRendering=!1}this._engine.currentRenderPassId=null!==(o=null!==(r=null===(s=e.outputRenderTarget)||void 0===s?void 0:s.renderPassId)&&void 0!==r?r:e.renderPassId)&&void 0!==o?o:0,l&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),a.snapshotRendering&&1===a.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t<e._rigCameras.length;t++)this._renderForCamera(e._rigCameras[t],e)}this._activeCamera=e,this.updateTransformMatrix(),this.onAfterRenderCameraObservable.notifyObservers(e)}_checkIntersections(){for(let e=0;e<this._meshesForIntersections.length;e++){const t=this._meshesForIntersections.data[e];if(t.actionManager)for(let e=0;t.actionManager&&e<t.actionManager.actions.length;e++){const i=t.actionManager.actions[e];if(12===i.trigger||13===i.trigger){const e=i.getTriggerParameter(),n=e.mesh?e.mesh:e,s=n.intersectsMesh(t,e.usePreciseIntersection),r=t._intersectionsInProgress.indexOf(n);s&&-1===r?12===i.trigger?(i._executeCurrent(f.V.CreateNew(t,void 0,n)),t._intersectionsInProgress.push(n)):13===i.trigger&&t._intersectionsInProgress.push(n):!s&&r>-1&&(13===i.trigger&&i._executeCurrent(f.V.CreateNew(t,void 0,n)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return n===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(r,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(L.MinDeltaTime,Math.min(this._engine.getDeltaTime(),L.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let n=0;const s=this._engine.getLockstepMaxSteps();let r=Math.floor(e/t);for(r=Math.min(r,s);e>0&&n<r;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=t*i,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,n++,e-=t;this._timeAccumulator=e<0?0:e}else{const e=this.useConstantAnimationDeltaTime?16:Math.max(L.MinDeltaTime,Math.min(this._engine.getDeltaTime(),L.MaxDeltaTime));this._animationRatio=.06*e,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)}}_clear(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)}_checkCameraRenderTarget(e){var t;if((null==e?void 0:e.outputRenderTarget)&&!(null==e?void 0:e.isRigCamera)&&(e.outputRenderTarget._cleared=!1),null===(t=null==e?void 0:e.rigCameras)||void 0===t?void 0:t.length)for(let t=0;t<e.rigCameras.length;++t){const i=e.rigCameras[t].outputRenderTarget;i&&(i._cleared=!1)}}resetDrawCache(e){if(this.meshes)for(const t of this.meshes)t.resetDrawCache(e)}render(e=!0,t=!1){var i,s,r;if(this.isDisposed)return;this.onReadyObservable.hasObservers()&&null===this._executeWhenReadyTimeoutId&&this._checkIsReady(),this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),(null===(i=this.activeCameras)||void 0===i?void 0:i.length)&&this.activeCameras.forEach(this._checkCameraRenderTarget),this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(11),t||this.animate();for(const e of this._beforeCameraUpdateStage)e.action();if(e)if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++){const t=this.activeCameras[e];if(t.update(),0!==t.cameraRigMode)for(let e=0;e<t._rigCameras.length;e++)t._rigCameras[e].update()}else if(this.activeCamera&&(this.activeCamera.update(),0!==this.activeCamera.cameraRigMode))for(let e=0;e<this.activeCamera._rigCameras.length;e++)this.activeCamera._rigCameras[e].update();this.onBeforeRenderObservable.notifyObservers(this);const o=this.getEngine();this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);const a=(null===(s=this.activeCameras)||void 0===s?void 0:s.length)?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){n.w1.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(let e=0;e<this.customRenderTargets.length;e++){const t=this.customRenderTargets[e];if(t._shouldRender()){if(this._renderId++,this.activeCamera=t.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");o.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),t.render(a!==this.activeCamera,this.dumpNextRenderTargets)}}n.w1.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=null!==(r=null==a?void 0:a.renderPassId)&&void 0!==r?r:0,this.activeCamera=a,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++)this._processSubCameras(this.activeCameras[e],e>0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e<this._toBeDisposed.length;e++){const t=this._toBeDisposed[e];t&&t.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}freezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].freeze()}unfreezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].unfreeze()}dispose(){if(this.isDisposed)return;this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this.importedMeshesFiles=new Array,this.stopAllAnimations&&this.stopAllAnimations(),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){console.error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;e<this.cameras.length;e++)this.cameras[e].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._disposeList(this.meshes,(e=>e.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),y.l._LastCreatedScene===this&&(this._engine.scenes.length>0?y.l._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:y.l._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,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=null!=t?t:e=>e.dispose();for(const e of i)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e<this.meshes.length;e++){const t=this.meshes[e].geometry;t&&t.clearCachedData()}}cleanCachedTextureBuffer(){for(const e of this.textures)e._buffer&&(e._buffer=null)}getWorldExtends(e){const t=new h.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new h.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return e=e||(()=>!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const n=e.getBoundingInfo(),s=n.boundingBox.minimumWorld,r=n.boundingBox.maximumWorld;h.P.CheckExtends(s,t,i),h.P.CheckExtends(r,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,n,s=!1){throw(0,x.S)("Ray")}createPickingRayToRef(e,t,i,n,s,r=!1,o=!1){throw(0,x.S)("Ray")}createPickingRayInCameraSpace(e,t,i){throw(0,x.S)("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,n){throw(0,x.S)("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,n,s,r){return new p.p}pickWithBoundingInfo(e,t,i,n,s){return new p.p}pickWithRay(e,t,i,n){throw(0,x.S)("Ray")}multiPick(e,t,i,n,s){throw(0,x.S)("Ray")}multiPickWithRay(e,t,i){throw(0,x.S)("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(void 0===t)return e;const n=[];i=i||(e=>{});for(const s in e){const r=e[s];l.$&&l.$.MatchesQuery(r,t)&&(n.push(r),i(r))}return n}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,n=null){this._renderingManager.setRenderingOrder(e,t,i,n)}setRenderingAutoClearDepthStencil(e,t,i=!0,n=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,n)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,n,s,r,o){const a=(0,w.vP)(e,t,i,n?this.offlineProvider:void 0,s,r,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_loadFileAsync(e,t,i,n,s){return new Promise(((r,o)=>{this._loadFile(e,(e=>{r(e)}),t,i,n,((e,t)=>{o(t)}),s)}))}_requestFile(e,t,i,n,s,r,o){const a=(0,w.FV)(e,t,i,n?this.offlineProvider:void 0,s,r,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_requestFileAsync(e,t,i,n,s){return new Promise(((r,o)=>{this._requestFile(e,(e=>{r(e)}),t,i,n,(e=>{o(e)}),s)}))}_readFile(e,t,i,n,s){const r=(0,w.Ip)(e,t,i,n,s);return this._activeRequests.push(r),r.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),r}_readFileAsync(e,t,i){return new Promise(((n,s)=>{this._readFile(e,(e=>{n(e)}),t,i,(e=>{s(e)}))}))}getPerfCollector(){throw(0,x.S)("performanceViewerSceneExtension")}}L.FOGMODE_NONE=0,L.FOGMODE_EXP=1,L.FOGMODE_EXP2=2,L.FOGMODE_LINEAR=3,L.MinDeltaTime=1,L.MaxDeltaTime=1e3,L.prototype.setActiveCameraByID=function(e){return this.setActiveCameraById(e)},L.prototype.getLastMaterialByID=function(e){return this.getLastMaterialById(e)},L.prototype.getMaterialByID=function(e){return this.getMaterialById(e)},L.prototype.getTextureByUniqueID=function(e){return this.getTextureByUniqueId(e)},L.prototype.getCameraByID=function(e){return this.getCameraById(e)},L.prototype.getCameraByUniqueID=function(e){return this.getCameraByUniqueId(e)},L.prototype.getBoneByID=function(e){return this.getBoneById(e)},L.prototype.getLightByID=function(e){return this.getLightById(e)},L.prototype.getLightByUniqueID=function(e){return this.getLightByUniqueId(e)},L.prototype.getParticleSystemByID=function(e){return this.getParticleSystemById(e)},L.prototype.getGeometryByID=function(e){return this.getGeometryById(e)},L.prototype.getMeshByID=function(e){return this.getMeshById(e)},L.prototype.getMeshesByID=function(e){return this.getMeshesById(e)},L.prototype.getTransformNodeByID=function(e){return this.getTransformNodeById(e)},L.prototype.getTransformNodeByUniqueID=function(e){return this.getTransformNodeByUniqueId(e)},L.prototype.getTransformNodesByID=function(e){return this.getTransformNodesById(e)},L.prototype.getMeshByUniqueID=function(e){return this.getMeshByUniqueId(e)},L.prototype.getLastMeshByID=function(e){return this.getLastMeshById(e)},L.prototype.getLastEntryByID=function(e){return this.getLastEntryById(e)},L.prototype.getNodeByID=function(e){return this.getNodeById(e)},L.prototype.getLastSkeletonByID=function(e){return this.getLastSkeletonById(e)}},2333:(e,t,i)=>{i.d(t,{H:()=>s,l:()=>n});class n{}n.NAME_EFFECTLAYER="EffectLayer",n.NAME_LAYER="Layer",n.NAME_LENSFLARESYSTEM="LensFlareSystem",n.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",n.NAME_PARTICLESYSTEM="ParticleSystem",n.NAME_GAMEPAD="Gamepad",n.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",n.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",n.NAME_PREPASSRENDERER="PrePassRenderer",n.NAME_DEPTHRENDERER="DepthRenderer",n.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",n.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",n.NAME_SPRITE="Sprite",n.NAME_SUBSURFACE="SubSurface",n.NAME_OUTLINERENDERER="Outline",n.NAME_PROCEDURALTEXTURE="ProceduralTexture",n.NAME_SHADOWGENERATOR="ShadowGenerator",n.NAME_OCTREE="Octree",n.NAME_PHYSICSENGINE="PhysicsEngine",n.NAME_AUDIO="Audio",n.NAME_FLUIDRENDERER="FluidRenderer",n.STEP_ISREADYFORMESH_EFFECTLAYER=0,n.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,n.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,n.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,n.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,n.STEP_BEFORECAMERADRAW_PREPASS=0,n.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,n.STEP_BEFORECAMERADRAW_LAYER=2,n.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,n.STEP_BEFORERENDERTARGETDRAW_LAYER=1,n.STEP_BEFORERENDERINGMESH_PREPASS=0,n.STEP_BEFORERENDERINGMESH_OUTLINE=1,n.STEP_AFTERRENDERINGMESH_PREPASS=0,n.STEP_AFTERRENDERINGMESH_OUTLINE=1,n.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,n.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,n.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,n.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,n.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,n.STEP_BEFORECLEAR_PREPASS=1,n.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,n.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,n.STEP_AFTERRENDERTARGETDRAW_LAYER=1,n.STEP_AFTERCAMERADRAW_PREPASS=0,n.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,n.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,n.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,n.STEP_AFTERCAMERADRAW_LAYER=4,n.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,n.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,n.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,n.STEP_AFTERRENDER_AUDIO=0,n.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,n.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,n.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,n.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,n.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,n.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,n.STEP_POINTERMOVE_SPRITE=0,n.STEP_POINTERDOWN_SPRITE=0,n.STEP_POINTERUP_SPRITE=0;class s extends Array{constructor(e){super(...e)}static Create(){return Object.create(s.prototype)}registerStep(e,t,i){let n=0,s=Number.MAX_VALUE;for(;n<this.length&&(s=this[n].index,!(e<s));n++);this.splice(n,0,{index:e,component:t,action:i.bind(t)})}clear(){this.length=0}}},9472:(e,t,i)=>{function n(e,t,i,n){var s,r=arguments.length,o=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(s=e[a])&&(o=(r<3?s(o):r>3?s(t,i,o):s(t,i))||o);return r>3&&o&&Object.defineProperty(t,i,o),o}i.d(t,{gn:()=>n}),Object.create,Object.create},2318:(e,t,i)=>{i.r(t),i.d(t,{GLTF1:()=>n,GLTF2:()=>s,GLTFFileLoader:()=>R,GLTFLoaderAnimationStartMode:()=>_,GLTFLoaderCoordinateSystemMode:()=>f,GLTFLoaderState:()=>m,GLTFValidation:()=>p,MTLFileLoader:()=>di,OBJFileLoader:()=>fi,STLFileLoader:()=>_i,SolidParser:()=>pi});var n={};i.r(n),i.d(n,{EBlendingFunction:()=>E,EComponentType:()=>g,ECullingType:()=>S,EParameterType:()=>y,EShaderType:()=>v,ETextureFilterType:()=>b,ETextureFormat:()=>T,ETextureWrapMode:()=>x,GLTFBinaryExtension:()=>Ee,GLTFLoader:()=>Te,GLTFLoaderBase:()=>be,GLTFLoaderExtension:()=>Se,GLTFMaterialsCommonExtension:()=>Ce,GLTFUtils:()=>Z});var s={};i.r(s),i.d(s,{ArrayItem:()=>Ve,EXT_lights_image_based:()=>Xe,EXT_mesh_gpu_instancing:()=>Ye,EXT_meshopt_compression:()=>$e,EXT_texture_webp:()=>Ze,ExtrasAsMetadata:()=>ui,GLTFLoader:()=>ke,KHR_animation_pointer:()=>Zt,KHR_draco_mesh_compression:()=>tt,KHR_lights:()=>st,KHR_materials_clearcoat:()=>ct,KHR_materials_emissive_strength:()=>ft,KHR_materials_ior:()=>xt,KHR_materials_iridescence:()=>dt,KHR_materials_pbrSpecularGlossiness:()=>ot,KHR_materials_sheen:()=>mt,KHR_materials_specular:()=>vt,KHR_materials_translucency:()=>Rt,KHR_materials_transmission:()=>At,KHR_materials_unlit:()=>lt,KHR_materials_variants:()=>Tt,KHR_materials_volume:()=>It,KHR_mesh_quantization:()=>Ot,KHR_texture_basisu:()=>Nt,KHR_texture_transform:()=>Lt,KHR_xmp_json_ld:()=>Ut,MSFT_audio_emitter:()=>ni,MSFT_lod:()=>ri,MSFT_minecraftMesh:()=>ai,MSFT_sRGBFactors:()=>hi});var r=i(5757),o=i(7257),a=i(9953),l=i(1468),h=i(2722),c=i(1918);function u(e,t,i,n){const s={externalResourceFunction:e=>n(e).then((e=>new Uint8Array(e)))};return i&&(s.uri="file:"===t?i:t+i),e instanceof ArrayBuffer?GLTFValidator.validateBytes(new Uint8Array(e),s):GLTFValidator.validateString(e,s)}function d(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":u(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,n)=>{const s=e.length;e.push({resolve:i,reject:n}),postMessage({id:"getExternalResource",index:s,uri:t})})))).then((e=>{postMessage({id:"validate.resolve",value:e})}),(e=>{postMessage({id:"validate.reject",reason:e})}));break;case"getExternalResource.resolve":e[i.index].resolve(i.value);break;case"getExternalResource.reject":e[i.index].reject(i.reason)}}}class p{static ValidateAsync(e,t,i,n){return"function"==typeof Worker?new Promise(((s,r)=>{const o=`${u}(${d})()`,a=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),l=new Worker(a),h=e=>{l.removeEventListener("error",h),l.removeEventListener("message",c),r(e)},c=e=>{const t=e.data;switch(t.id){case"getExternalResource":n(t.uri).then((e=>{l.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e])}),(e=>{l.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})}));break;case"validate.resolve":l.removeEventListener("error",h),l.removeEventListener("message",c),s(t.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",c),r(t.reason),l.terminate()}};l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({id:"init",url:this.Configuration.url}),l.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=o.w1.LoadScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>u(e,t,i,n))))}}p.Configuration={url:"https://preview.babylonjs.com/gltf_validator.js"};var f,_,m,g,v,y,x,b,T,S,E,C=i(5661),A=i(1722);function P(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(e){return Promise.reject(e)}}!function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(f||(f={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(_||(_={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(m||(m={}));class R{constructor(){this.onParsedObservable=new r.y$,this.coordinateSystemMode=f.AUTO,this.animationStartMode=_.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new r.y$,this.onSkinLoadedObservable=new r.y$,this.onTextureLoadedObservable=new r.y$,this.onMaterialLoadedObservable=new r.y$,this.onCameraLoadedObservable=new r.y$,this.onCompleteObservable=new r.y$,this.onErrorObservable=new r.y$,this.onDisposeObservable=new r.y$,this.onExtensionLoadedObservable=new r.y$,this.validate=!1,this.onValidatedObservable=new r.y$,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new r.y$,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,n,s,a){this._progressCallback=n;const l=t.name?"file:":o.w1.GetFolderPath(t),u=t.name||o.w1.GetFilename(t);if(s){if(this.useRangeRequests){this.validate&&h.Y.Warn("glTF validation is not supported when range requests are enabled");const n={abort:()=>{},onCompleteObservable:new r.y$},s={readAsync:(i,n)=>new Promise(((s,r)=>{this._loadFile(e,t,(e=>{s(new Uint8Array(e))}),!0,(e=>{r(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+n-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new c.d(s)).then((e=>{n.onCompleteObservable.notifyObservers(n),i(e)}),a?e=>a(void 0,e):void 0),n}return this._loadFile(e,t,(t=>{this._validate(e,t,l,u),this._unpackBinaryAsync(new c.d({readAsync:(e,i)=>P(t,e,i),byteLength:t.byteLength})).then((e=>{i(e)}),a?e=>a(void 0,e):void 0)}),!0,a)}return this._loadFile(e,t,(t=>{this._validate(e,t,l,u),i({json:this._parseJson(t)})}),s,a)}importMeshAsync(e,t,i,n,s,r){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,n,s,r))))}loadAsync(e,t,i,n,s){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,n,s))))}loadAssetContainerAsync(e,t,i,n,s){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t);const r=new l.TJ(e),o=[];this.onMaterialLoadedObservable.add((e=>{o.push(e)}));const a=[];this.onTextureLoadedObservable.add((e=>{a.push(e)}));const h=[];this.onCameraLoadedObservable.add((e=>{h.push(e)}));const c=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&c.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,r,t,i,n,s).then((e=>(Array.prototype.push.apply(r.geometries,e.geometries),Array.prototype.push.apply(r.meshes,e.meshes),Array.prototype.push.apply(r.particleSystems,e.particleSystems),Array.prototype.push.apply(r.skeletons,e.skeletons),Array.prototype.push.apply(r.animationGroups,e.animationGroups),Array.prototype.push.apply(r.materials,o),Array.prototype.push.apply(r.textures,a),Array.prototype.push.apply(r.lights,e.lights),Array.prototype.push.apply(r.transformNodes,e.transformNodes),Array.prototype.push.apply(r.cameras,h),Array.prototype.push.apply(r.morphTargetManagers,c),r)))}))}canDirectLoad(e){return-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+R._MagicBase64Encoded)||e.startsWith("data:;base64,"+R._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+R._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+R._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+R._MagicBase64Encoded)||t.startsWith(";base64,"+R._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+R._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+R._MagicBase64Encoded)){const i=(0,C.$K)(t);return this._validate(e,i),this._unpackBinaryAsync(new c.d({readAsync:(e,t)=>P(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new R}get loaderState(){return this._state}whenCompleteAsync(){return new Promise(((e,t)=>{this.onCompleteObservable.addOnce((()=>{e()})),this.onErrorObservable.addOnce((e=>{t(e)}))}))}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(m[this._state]))}_loadFile(e,t,i,n,s,r){const o=e._loadFile(t,i,(e=>{this._onProgress(e,o)}),!0,n,s,r);return o.onCompleteObservable.add((e=>{this._requests.splice(this._requests.indexOf(e),1)})),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,n=0,s=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;i=i&&e._lengthComputable,n+=e._loaded,s+=e._total}this._progressCallback({lengthComputable:i,loaded:n,total:i?s:0})}_validate(e,t,i="",n=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),p.ValidateAsync(t,i,n,(t=>this.preprocessUrlAsync(i+t).then((t=>e._loadFileAsync(t,void 0,!0,!0))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),o.w1.Warn(`Failed to validate: ${e.message}`),this.onValidatedObservable.clear()})))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const i=R._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=R._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(R._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const n={1:R._CreateGLTF1Loader,2:R._CreateGLTF2Loader}[i.major];if(!n)throw new Error("Unsupported version: "+t.version);return n(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then((()=>{const t=e.readUint32();if(1179937895!==t)throw new A.LH("Unexpected magic: "+t,A.SM.GLTFLoaderUnexpectedMagicError);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const n=e.readUint32();let s;switch(this.useRangeRequests||n===e.buffer.byteLength||h.Y.Warn(`Length in header does not match actual data length: ${n} != ${e.buffer.byteLength}`),i){case 1:s=this._unpackBinaryV1Async(e,n);break;case 2:s=this._unpackBinaryV2Async(e,n);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),s}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),n=e.readUint32();if(0!==n)throw new Error(`Unexpected content format: ${n}`);const s=t-e.byteOffset,r={json:this._parseJson(e.readString(i)),bin:null};if(0!==s){const t=e.byteOffset;r.bin={readAsync:(i,n)=>e.buffer.readAsync(t+i,n),byteLength:s}}return Promise.resolve(r)}_unpackBinaryV2Async(e,t){const i=1313821514,n=e.readUint32();if(e.readUint32()!==i)throw new Error("First chunk format is not JSON");return e.byteOffset+n===t?e.loadAsync(n).then((()=>({json:this._parseJson(e.readString(n)),bin:null}))):e.loadAsync(n+8).then((()=>{const s={json:this._parseJson(e.readString(n)),bin:null},r=()=>{const n=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;s.bin={readAsync:(i,n)=>e.buffer.readAsync(t+i,n),byteLength:n},e.skipBytes(n);break}default:e.skipBytes(n)}return e.byteOffset!==t?e.loadAsync(8).then(r):Promise.resolve(s)};return r()}))}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0}_logOpen(e){this._log(e),this._logIndentLevel++}_logClose(){--this._logIndentLevel}_logEnabled(e){const t=R._logSpaces.substr(0,2*this._logIndentLevel);h.Y.Log(`${t}${e}`)}_logDisabled(e){}_startPerformanceCounterEnabled(e){o.w1.StartPerformanceCounter(e)}_startPerformanceCounterDisabled(e){}_endPerformanceCounterEnabled(e){o.w1.EndPerformanceCounter(e)}_endPerformanceCounterDisabled(e){}}R.IncrementalLoading=!0,R.HomogeneousCoordinates=!1,R._MagicBase64Encoded="Z2xURg",R._logSpaces=" ",a.n&&a.n.RegisterPlugin(new R),function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.FLOAT=5126]="FLOAT"}(g||(g={})),function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"}(v||(v={})),function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.INT=5124]="INT",e[e.UNSIGNED_INT=5125]="UNSIGNED_INT",e[e.FLOAT=5126]="FLOAT",e[e.FLOAT_VEC2=35664]="FLOAT_VEC2",e[e.FLOAT_VEC3=35665]="FLOAT_VEC3",e[e.FLOAT_VEC4=35666]="FLOAT_VEC4",e[e.INT_VEC2=35667]="INT_VEC2",e[e.INT_VEC3=35668]="INT_VEC3",e[e.INT_VEC4=35669]="INT_VEC4",e[e.BOOL=35670]="BOOL",e[e.BOOL_VEC2=35671]="BOOL_VEC2",e[e.BOOL_VEC3=35672]="BOOL_VEC3",e[e.BOOL_VEC4=35673]="BOOL_VEC4",e[e.FLOAT_MAT2=35674]="FLOAT_MAT2",e[e.FLOAT_MAT3=35675]="FLOAT_MAT3",e[e.FLOAT_MAT4=35676]="FLOAT_MAT4",e[e.SAMPLER_2D=35678]="SAMPLER_2D"}(y||(y={})),function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"}(x||(x={})),function(e){e[e.NEAREST=9728]="NEAREST",e[e.LINEAR=9728]="LINEAR",e[e.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",e[e.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",e[e.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",e[e.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"}(b||(b={})),function(e){e[e.ALPHA=6406]="ALPHA",e[e.RGB=6407]="RGB",e[e.RGBA=6408]="RGBA",e[e.LUMINANCE=6409]="LUMINANCE",e[e.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA"}(T||(T={})),function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(S||(S={})),function(e){e[e.ZERO=0]="ZERO",e[e.ONE=1]="ONE",e[e.SRC_COLOR=768]="SRC_COLOR",e[e.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",e[e.DST_COLOR=774]="DST_COLOR",e[e.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",e[e.SRC_ALPHA=770]="SRC_ALPHA",e[e.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",e[e.DST_ALPHA=772]="DST_ALPHA",e[e.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",e[e.CONSTANT_COLOR=32769]="CONSTANT_COLOR",e[e.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",e[e.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",e[e.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",e[e.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE"}(E||(E={}));var M=i(4141),I=i(4649),D=i(2704),O=i(8482),w=i(4676),N=i(4026),F=i(5047),L=i(1979),B=i(7104),U=i(9828),V=i(252),k=i(8097),G=i(2262),z=i(2101),W=i(708),H=i(7321),X=i(9401),j=i(1795),Y=i(4496),q=i(7616),K=i(7951),$=i(5520),Q=i(6317);class Z{static SetMatrix(e,t,i,n,s){let r=null;if("MODEL"===i.semantic?r=t.getWorldMatrix():"PROJECTION"===i.semantic?r=e.getProjectionMatrix():"VIEW"===i.semantic?r=e.getViewMatrix():"MODELVIEWINVERSETRANSPOSE"===i.semantic?r=M.y3.Transpose(t.getWorldMatrix().multiply(e.getViewMatrix()).invert()):"MODELVIEW"===i.semantic?r=t.getWorldMatrix().multiply(e.getViewMatrix()):"MODELVIEWPROJECTION"===i.semantic?r=t.getWorldMatrix().multiply(e.getTransformMatrix()):"MODELINVERSE"===i.semantic?r=t.getWorldMatrix().invert():"VIEWINVERSE"===i.semantic?r=e.getViewMatrix().invert():"PROJECTIONINVERSE"===i.semantic?r=e.getProjectionMatrix().invert():"MODELVIEWINVERSE"===i.semantic?r=t.getWorldMatrix().multiply(e.getViewMatrix()).invert():"MODELVIEWPROJECTIONINVERSE"===i.semantic?r=t.getWorldMatrix().multiply(e.getTransformMatrix()).invert():"MODELINVERSETRANSPOSE"===i.semantic&&(r=M.y3.Transpose(t.getWorldMatrix().invert())),r)switch(i.type){case y.FLOAT_MAT2:s.setMatrix2x2(n,M.y3.GetAsMatrix2x2(r));break;case y.FLOAT_MAT3:s.setMatrix3x3(n,M.y3.GetAsMatrix3x3(r));break;case y.FLOAT_MAT4:s.setMatrix(n,r)}}static SetUniform(e,t,i,n){switch(n){case y.FLOAT:return e.setFloat(t,i),!0;case y.FLOAT_VEC2:return e.setVector2(t,M.FM.FromArray(i)),!0;case y.FLOAT_VEC3:return e.setVector3(t,M.P.FromArray(i)),!0;case y.FLOAT_VEC4:return e.setVector4(t,M.Lt.FromArray(i)),!0;default:return!1}}static GetWrapMode(e){switch(e){case x.CLAMP_TO_EDGE:return G.x.CLAMP_ADDRESSMODE;case x.MIRRORED_REPEAT:return G.x.MIRROR_ADDRESSMODE;case x.REPEAT:default:return G.x.WRAP_ADDRESSMODE}}static GetByteStrideFromType(e){switch(e.type){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}}static GetTextureFilterMode(e){switch(e){case b.LINEAR:case b.LINEAR_MIPMAP_NEAREST:case b.LINEAR_MIPMAP_LINEAR:return G.x.TRILINEAR_SAMPLINGMODE;case b.NEAREST:case b.NEAREST_MIPMAP_NEAREST:return G.x.NEAREST_SAMPLINGMODE;default:return G.x.BILINEAR_SAMPLINGMODE}}static GetBufferFromBufferView(e,t,i,n,s){i=t.byteOffset+i;const r=e.loadedBufferViews[t.buffer];if(i+n>r.byteLength)throw new Error("Buffer access is out of range");const o=r.buffer;switch(i+=r.byteOffset,s){case g.BYTE:return new Int8Array(o,i,n);case g.UNSIGNED_BYTE:return new Uint8Array(o,i,n);case g.SHORT:return new Int16Array(o,i,n);case g.UNSIGNED_SHORT:return new Uint16Array(o,i,n);default:return new Float32Array(o,i,n)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],n=t.count*Z.GetByteStrideFromType(t);return Z.GetBufferFromBufferView(e,i,t.byteOffset,n,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let n=0;n<i;++n)t+=String.fromCharCode(e[n]);return t}static GetDefaultMaterial(e){if(!Z._DefaultMaterial){L.Q.ShadersStore.GLTFDefaultMaterialVertexShader=["precision highp float;","","uniform mat4 worldView;","uniform mat4 projection;","","attribute vec3 position;","","void main(void)","{"," gl_Position = projection * worldView * vec4(position, 1.0);","}"].join("\n"),L.Q.ShadersStore.GLTFDefaultMaterialPixelShader=["precision highp float;","","uniform vec4 u_emission;","","void main(void)","{"," gl_FragColor = u_emission;","}"].join("\n");const t={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},i={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};Z._DefaultMaterial=new k.j("GLTFDefaultMaterial",e,t,i),Z._DefaultMaterial.setColor4("u_emission",new I.HE(.5,.5,.5,1))}return Z._DefaultMaterial}}Z._DefaultMaterial=null;var J,ee=i(7458);!function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"}(J||(J={}));class te{constructor(e){this._pos=0,this.currentToken=J.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return J.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=J.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=J.IDENTIFIER,this.currentIdentifier=this.currentString;!this.isEnd()&&(this.isLetterOrDigitPattern.test(this.currentString=this.peek())||"_"===this.currentString);)this.currentIdentifier+=this.currentString,this.forward();return this.currentToken}peek(){return this._toParse[this._pos]}read(){return this._toParse[this._pos++]}forward(){this._pos++}isEnd(){return this._pos>=this._maxPos}}const ie=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],ne=["world","view","projection","worldView","worldViewProjection","mBones"],se=["translation","rotation","scale"],re=["position","rotationQuaternion","scaling"],oe=(e,t,i)=>{for(const n in e){const s=e[n];i[t][n]=s}},ae=e=>{if(e)for(let t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},le=e=>{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},he=e=>{let t=null;if(e.translation||e.rotation||e.scale){const i=M.P.FromArray(e.scale||[1,1,1]),n=M._f.FromArray(e.rotation||[0,0,0,1]),s=M.P.FromArray(e.translation||[0,0,0]);t=M.y3.Compose(i,n,s)}else t=M.y3.FromArray(e.matrix);return t},ce=(e,t,i,n)=>{for(let e=0;e<n.bones.length;e++)if(n.bones[e].name===i)return n.bones[e];const s=e.nodes;for(const r in s){const o=s[r];if(!o.jointName)continue;const a=o.children;for(let s=0;s<a.length;s++){const l=e.nodes[a[s]];if(l.jointName&&l.jointName===i){const i=he(o),s=new N.N(o.name||"",n,ce(e,t,o.jointName,n),i);return s.id=r,s}}}return null},ue=(e,t)=>{for(let i=0;i<e.length;i++){const n=e[i];for(let e=0;e<n.node.children.length;e++)if(n.node.children[e]===t)return n.bone}return null},de=(e,t)=>{const i=e.nodes;let n=i[t];if(n)return{node:n,id:t};for(const e in i)if(n=i[e],n.jointName===t)return{node:n,id:e};return null},pe=(e,t)=>{for(let i=0;i<e.jointNames.length;i++)if(e.jointNames[i]===t)return!0;return!1},fe=(e,t,i,n,s)=>{if(s||(e.scene._blockEntityCollection=!!e.assetContainer,(s=new Y.Kj(t.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.id=n),!t.babylonNode)return s;const r=[];let o=null;const a=new Array,l=new Array,h=new Array,c=new Array;for(let t=0;t<i.length;t++){const n=i[t],s=e.meshes[n];if(s)for(let t=0;t<s.primitives.length;t++){const i=new z.x,n=s.primitives[t];n.mode;const u=n.attributes;let d=null,p=null;for(const t in u)if(d=e.accessors[u[t]],p=Z.GetBufferFromAccessor(e,d),"NORMAL"===t)i.normals=new Float32Array(p.length),i.normals.set(p);else if("POSITION"===t){if(R.HomogeneousCoordinates){i.positions=new Float32Array(p.length-p.length/4);for(let e=0;e<p.length;e+=4)i.positions[e]=p[e],i.positions[e+1]=p[e+1],i.positions[e+2]=p[e+2]}else i.positions=new Float32Array(p.length),i.positions.set(p);l.push(i.positions.length)}else if(-1!==t.indexOf("TEXCOORD_")){const e=Number(t.split("_")[1]),n=W.o.UVKind+(0===e?"":e+1),s=new Float32Array(p.length);s.set(p),ae(s),i.set(s,n)}else"JOINT"===t?(i.matricesIndices=new Float32Array(p.length),i.matricesIndices.set(p)):"WEIGHT"===t?(i.matricesWeights=new Float32Array(p.length),i.matricesWeights.set(p)):"COLOR"===t&&(i.colors=new Float32Array(p.length),i.colors.set(p));if(d=e.accessors[n.indices],d)p=Z.GetBufferFromAccessor(e,d),i.indices=new Int32Array(p.length),i.indices.set(p),c.push(i.indices.length);else{const e=[];for(let t=0;t<i.positions.length/3;t++)e.push(t);i.indices=new Int32Array(e),c.push(i.indices.length)}o?o.merge(i):o=i;const f=e.scene.getMaterialById(n.material);r.push(null===f?Z.GetDefaultMaterial(e.scene):f),a.push(0===a.length?0:a[a.length-1]+l[l.length-2]),h.push(0===h.length?0:h[h.length-1]+c[c.length-2])}}let u;e.scene._blockEntityCollection=!!e.assetContainer,r.length>1?(u=new U.G("multimat"+n,e.scene),u.subMaterials=r):u=new V.K("multimat"+n,e.scene),1===r.length&&(u=r[0]),u._parentContainer=e.assetContainer,s.material||(s.material=u),new H.Z(n,e.scene,o,!1,s),s.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,s.subMeshes=[];let d=0;for(let t=0;t<i.length;t++){const n=i[t],r=e.meshes[n];if(r)for(let e=0;e<r.primitives.length;e++)r.primitives[e].mode,X.P.AddToMesh(d,a[d],l[d],h[d],c[d],s,s,!0),d++}return s},_e=(e,t,i,n)=>{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=i),e.scaling&&(e.scaling=n)},me=(e,t,i)=>{let n=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(t.name||""))return null;if(t.skin){if(t.meshes){const s=e.skins[t.skin],r=fe(e,t,t.meshes,i,t.babylonNode);r.skeleton=e.scene.getLastSkeletonById(t.skin),null===r.skeleton&&(r.skeleton=((e,t,i,n)=>{if(n||(n=new F.O(t.name||"","",e.scene)),!t.babylonSkeleton)return n;const s=[],r=[];((e,t,i,n)=>{for(const s in e.nodes){const r=e.nodes[s],o=s;if(!r.jointName||pe(i,r.jointName))continue;const a=he(r),l=new N.N(r.name||"",t,null,a);l.id=o,n.push({bone:l,node:r,id:o})}for(let e=0;e<n.length;e++){const t=n[e],i=t.node.children;for(let e=0;e<i.length;e++){let s=null;for(let t=0;t<n.length;t++)if(n[t].id===i[e]){s=n[t];break}s&&(s.bone._parent=t.bone,t.bone.children.push(s.bone))}}})(e,n,t,s),n.bones=[];for(let i=0;i<t.jointNames.length;i++){const a=de(e,t.jointNames[i]);if(!a)continue;const l=a.node;if(!l){o.w1.Warn("Joint named "+t.jointNames[i]+" does not exist");continue}const h=a.id,c=e.scene.getBoneById(h);if(c){n.bones.push(c);continue}let u=!1,d=null;for(let s=0;s<i;s++){const i=de(e,t.jointNames[s]);if(!i)continue;const r=i.node;if(!r){o.w1.Warn("Joint named "+t.jointNames[s]+" does not exist when looking for parent");continue}const a=r.children;if(a){u=!1;for(let i=0;i<a.length;i++)if(a[i]===h){d=ce(e,t,t.jointNames[s],n),u=!0;break}if(u)break}}const p=he(l);!d&&s.length>0&&(d=ue(s,h),d&&-1===r.indexOf(d)&&r.push(d)),new N.N(l.jointName||"",n,d,p).id=h}const a=n.bones;n.bones=[];for(let i=0;i<t.jointNames.length;i++){const s=de(e,t.jointNames[i]);if(s)for(let e=0;e<a.length;e++)if(a[e].id===s.id){n.bones.push(a[e]);break}}n.prepare();for(let e=0;e<r.length;e++)n.bones.push(r[e]);return n})(e,s,0,s.babylonSkeleton),s.babylonSkeleton||(s.babylonSkeleton=r.skeleton)),n=r}}else if(t.meshes)n=fe(e,t,t.mesh?[t.mesh]:t.meshes,i,t.babylonNode);else if(!t.light||t.babylonNode||e.importOnlyMeshes){if(t.camera&&!t.babylonNode&&!e.importOnlyMeshes){const i=e.cameras[t.camera];if(i){if(e.scene._blockEntityCollection=!!e.assetContainer,"orthographic"===i.type){const i=new O.c(t.camera,M.P.Zero(),e.scene,!1);i.name=t.name||"",i.mode=D.V.ORTHOGRAPHIC_CAMERA,i.attachControl(),n=i,i._parentContainer=e.assetContainer}else if("perspective"===i.type){const s=i[i.type],r=new O.c(t.camera,M.P.Zero(),e.scene,!1);r.name=t.name||"",r.attachControl(),s.aspectRatio||(s.aspectRatio=e.scene.getEngine().getRenderWidth()/e.scene.getEngine().getRenderHeight()),s.znear&&s.zfar&&(r.maxZ=s.zfar,r.minZ=s.znear),n=r,r._parentContainer=e.assetContainer}e.scene._blockEntityCollection=!1}}}else{const i=e.lights[t.light];if(i)if("ambient"===i.type){const s=i[i.type],r=new q.e(t.light,M.P.Zero(),e.scene);r.name=t.name||"",s.color&&(r.diffuse=I.Wo.FromArray(s.color)),n=r}else if("directional"===i.type){const s=i[i.type],r=new K.O(t.light,M.P.Zero(),e.scene);r.name=t.name||"",s.color&&(r.diffuse=I.Wo.FromArray(s.color)),n=r}else if("point"===i.type){const s=i[i.type],r=new $.c(t.light,M.P.Zero(),e.scene);r.name=t.name||"",s.color&&(r.diffuse=I.Wo.FromArray(s.color)),n=r}else if("spot"===i.type){const s=i[i.type],r=new Q.P(t.light,M.P.Zero(),M.P.Zero(),0,0,e.scene);r.name=t.name||"",s.color&&(r.diffuse=I.Wo.FromArray(s.color)),s.fallOfAngle&&(r.angle=s.fallOfAngle),s.fallOffExponent&&(r.exponent=s.fallOffExponent),n=r}}if(!t.jointName){if(t.babylonNode)return t.babylonNode;if(null===n){e.scene._blockEntityCollection=!!e.assetContainer;const i=new Y.Kj(t.name||"",e.scene);i._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,t.babylonNode=i,n=i}}if(null!==n){if(t.matrix&&n instanceof Y.Kj)((e,t)=>{if(t.matrix){const i=new M.P(0,0,0),n=new M._f,s=new M.P(0,0,0);M.y3.FromArray(t.matrix).decompose(s,n,i),_e(e,i,n,s)}else t.translation&&t.rotation&&t.scale&&_e(e,M.P.FromArray(t.translation),M._f.FromArray(t.rotation),M.P.FromArray(t.scale));e.computeWorldMatrix(!0)})(n,t);else{const e=t.translation||[0,0,0],i=t.rotation||[0,0,0,1],s=t.scale||[1,1,1];_e(n,M.P.FromArray(e),M._f.FromArray(i),M.P.FromArray(s))}n.updateCache(!0),t.babylonNode=n}return n},ge=(e,t,i,n=!1)=>{const s=e.nodes[t];let r=null;if(n=!(e.importOnlyMeshes&&!n&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(s.name||"")||0===e.importMeshesNames.length,!s.jointName&&n&&(r=me(e,s,t),null!==r&&(r.id=t,r.parent=i)),s.children)for(let t=0;t<s.children.length;t++)ge(e,s.children[t],r,n)},ve=e=>{let t=e.currentScene;if(t)for(let i=0;i<t.nodes.length;i++)ge(e,t.nodes[i],null);else for(const i in e.scenes){t=e.scenes[i];for(let i=0;i<t.nodes.length;i++)ge(e,t.nodes[i],null)}(e=>{for(const t in e.animations){const i=e.animations[t];if(!i.channels||!i.samplers)continue;let n=null;for(let s=0;s<i.channels.length;s++){const r=i.channels[s],a=i.samplers[r.sampler];if(!a)continue;let l=null,h=null;i.parameters?(l=i.parameters[a.input],h=i.parameters[a.output]):(l=a.input,h=a.output);const c=Z.GetBufferFromAccessor(e,e.accessors[l]),u=Z.GetBufferFromAccessor(e,e.accessors[h]),d=r.target.id;let p=e.scene.getNodeById(d);if(null===p&&(p=e.scene.getNodeByName(d)),null===p){o.w1.Warn("Creating animation named "+t+". But cannot find node named "+d+" to attach to");continue}const f=p instanceof N.N;let _=r.target.path;const m=se.indexOf(_);-1!==m&&(_=re[m]);let g=w.f.ANIMATIONTYPE_MATRIX;f||("rotationQuaternion"===_?(g=w.f.ANIMATIONTYPE_QUATERNION,p.rotationQuaternion=new M._f):g=w.f.ANIMATIONTYPE_VECTOR3);let v=null;const y=[];let x=0,b=!1;f&&n&&n.getKeys().length===c.length&&(v=n,b=!0),b||(e.scene._blockEntityCollection=!!e.assetContainer,v=new w.f(t,f?"_matrix":_,1,g,w.f.ANIMATIONLOOPMODE_CYCLE),e.scene._blockEntityCollection=!1);for(let e=0;e<c.length;e++){let t=null;if("rotationQuaternion"===_?(t=M._f.FromArray([u[x],u[x+1],u[x+2],u[x+3]]),x+=4):(t=M.P.FromArray([u[x],u[x+1],u[x+2]]),x+=3),f){const i=p;let s=M.P.Zero(),r=new M._f,o=M.P.Zero(),a=i.getBaseMatrix();b&&n&&(a=n.getKeys()[e].value),a.decompose(o,r,s),"position"===_?s=t:"rotationQuaternion"===_?r=t:o=t,t=M.y3.Compose(o,r,s)}b?n&&(n.getKeys()[e].value=t):y.push({frame:c[e],value:t})}!b&&v&&(v.setKeys(y),p.animations.push(v)),n=v,e.scene.stopAnimation(p),e.scene.beginAnimation(p,0,c[c.length-1],!0,1)}}})(e);for(let t=0;t<e.scene.skeletons.length;t++){const i=e.scene.skeletons[t];e.scene.beginAnimation(i,0,Number.MAX_VALUE,!0,1)}},ye=(e,t,i)=>{for(const n in t.uniforms){const s=t.uniforms[n],r=t.parameters[s];if(e.currentIdentifier===n&&r.semantic&&!r.source&&!r.node){const e=ie.indexOf(r.semantic);if(-1!==e)return delete i[n],ne[e]}}return e.currentIdentifier},xe=e=>{for(const t in e.materials)Se.LoadMaterialAsync(e,t,(()=>{}),(()=>{}))};class be{static CreateRuntime(e,t,i){const n={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&oe(e.extensions,"extensions",n),e.extensionsUsed&&oe(e.extensionsUsed,"extensionsUsed",n),e.buffers&&((e,t)=>{for(const i in e){const n=e[i];t.buffers[i]=n,t.buffersCount++}})(e.buffers,n),e.bufferViews&&oe(e.bufferViews,"bufferViews",n),e.accessors&&oe(e.accessors,"accessors",n),e.meshes&&oe(e.meshes,"meshes",n),e.lights&&oe(e.lights,"lights",n),e.cameras&&oe(e.cameras,"cameras",n),e.nodes&&oe(e.nodes,"nodes",n),e.images&&oe(e.images,"images",n),e.textures&&oe(e.textures,"textures",n),e.shaders&&((e,t)=>{for(const i in e){const n=e[i];t.shaders[i]=n,t.shaderscount++}})(e.shaders,n),e.programs&&oe(e.programs,"programs",n),e.samplers&&oe(e.samplers,"samplers",n),e.techniques&&oe(e.techniques,"techniques",n),e.materials&&oe(e.materials,"materials",n),e.animations&&oe(e.animations,"animations",n),e.skins&&oe(e.skins,"skins",n),e.scenes&&(n.scenes=e.scenes),e.scene&&e.scenes&&(n.currentScene=e.scenes[e.scene]),n}static LoadBufferAsync(e,t,i,n,s){const r=e.buffers[t];o.w1.IsBase64(r.uri)?setTimeout((()=>i(new Uint8Array(o.w1.DecodeBase64(r.uri))))):o.w1.LoadFile(e.rootUrl+r.uri,(e=>i(new Uint8Array(e))),s,void 0,!0,(e=>{e&&n(e.status+" "+e.statusText)}))}static LoadTextureBufferAsync(e,t,i,n){const s=e.textures[t];if(!s||!s.source)return void n("");if(s.babylonTexture)return void i(null);const r=e.images[s.source];o.w1.IsBase64(r.uri)?setTimeout((()=>i(new Uint8Array(o.w1.DecodeBase64(r.uri))))):o.w1.LoadFile(e.rootUrl+r.uri,(e=>i(new Uint8Array(e))),void 0,void 0,!0,(e=>{e&&n(e.status+" "+e.statusText)}))}static CreateTextureAsync(e,t,i,n){const s=e.textures[t];if(s.babylonTexture)return void n(s.babylonTexture);const r=e.samplers[s.sampler],o=r.minFilter===b.NEAREST_MIPMAP_NEAREST||r.minFilter===b.NEAREST_MIPMAP_LINEAR||r.minFilter===b.LINEAR_MIPMAP_NEAREST||r.minFilter===b.LINEAR_MIPMAP_LINEAR,a=G.x.BILINEAR_SAMPLINGMODE,l=null==i?new Blob:new Blob([i]),h=URL.createObjectURL(l),c=()=>URL.revokeObjectURL(h),u=new G.x(h,e.scene,!o,!0,a,c,c);void 0!==r.wrapS&&(u.wrapU=Z.GetWrapMode(r.wrapS)),void 0!==r.wrapT&&(u.wrapV=Z.GetWrapMode(r.wrapT)),u.name=t,s.babylonTexture=u,n(u)}static LoadShaderStringAsync(e,t,i,n){const s=e.shaders[t];if(o.w1.IsBase64(s.uri)){const e=atob(s.uri.split(",")[1]);i&&i(e)}else o.w1.LoadFile(e.rootUrl+s.uri,i,void 0,void 0,!1,(e=>{e&&n&&n(e.status+" "+e.statusText)}))}static LoadMaterialAsync(e,t,i,n){const s=e.materials[t];if(!s.technique)return void(n&&n("No technique found."));const r=e.techniques[s.technique];if(!r){e.scene._blockEntityCollection=!!e.assetContainer;const n=new V.K(t,e.scene);return n._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,n.diffuseColor=new I.Wo(.5,.5,.5),n.sideOrientation=B.F.CounterClockWiseSideOrientation,void i(n)}const o=e.programs[r.program],a=r.states,l=L.Q.ShadersStore[o.vertexShader+"VertexShader"],h=L.Q.ShadersStore[o.fragmentShader+"PixelShader"];let c="",u="";const d=new te(l),p=new te(h),f={},_=[],m=[],g=[];for(const e in r.uniforms){const t=r.uniforms[e],i=r.parameters[t];if(f[e]=i,!i.semantic||i.node||i.source)i.type===y.SAMPLER_2D?g.push(e):_.push(e);else{const t=ie.indexOf(i.semantic);-1!==t?(_.push(ne[t]),delete f[e]):_.push(e)}}for(const e in r.attributes){const t=r.attributes[e],i=r.parameters[t];if(i.semantic){const e=le(i);e&&m.push(e)}}for(;!d.isEnd()&&d.getNextToken();){if(d.currentToken!==J.IDENTIFIER){c+=d.currentString;continue}let e=!1;for(const t in r.attributes){const i=r.attributes[t],n=r.parameters[i];if(d.currentIdentifier===t&&n.semantic){c+=le(n),e=!0;break}}e||(c+=ye(d,r,f))}for(;!p.isEnd()&&p.getNextToken();)p.currentToken===J.IDENTIFIER?u+=ye(p,r,f):u+=p.currentString;const v={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},x={attributes:m,uniforms:_,samplers:g,needAlphaBlending:a&&a.enable&&-1!==a.enable.indexOf(3042)};L.Q.ShadersStore[o.vertexShader+t+"VertexShader"]=c,L.Q.ShadersStore[o.fragmentShader+t+"PixelShader"]=u;const b=new k.j(t,e.scene,v,x);if(b.onError=((e,t,i)=>(n,s)=>{t.dispose(!0),i("Cannot compile program named "+e.name+". Error: "+s+". Default material will be applied")})(o,b,n),b.onCompiled=((e,t,i,n,s,r)=>o=>{((e,t,i,n,s)=>{const r=n.values||i.parameters,o=i.uniforms;for(const i in s){const a=s[i],l=a.type;let h=r[o[i]];if(void 0===h&&(h=a.value),!h)continue;const c=e=>i=>{a.value&&e&&(t.setTexture(e,i),delete s[e])};l===y.SAMPLER_2D?Se.LoadTextureAsync(e,n.values?h:a.value,c(i),(()=>c(null))):a.value&&Z.SetUniform(t,i,n.values?h:a.value,l)&&delete s[i]}})(e,t,i,n,s),t.onBind=o=>{((e,t,i,n,s,r,o)=>{const a=r.values||s.parameters;for(const o in i){const l=i[o],h=l.type;if(h===y.FLOAT_MAT2||h===y.FLOAT_MAT3||h===y.FLOAT_MAT4)if(!l.semantic||l.source||l.node){if(l.semantic&&(l.source||l.node)){let e=t.scene.getNodeByName(l.source||l.node||"");if(null===e&&(e=t.scene.getNodeById(l.source||l.node||"")),null===e)continue;Z.SetMatrix(t.scene,e,l,o,n.getEffect())}}else Z.SetMatrix(t.scene,e,l,o,n.getEffect());else{const e=a[s.uniforms[o]];if(!e)continue;if(h===y.SAMPLER_2D){const i=t.textures[r.values?e:l.value].babylonTexture;if(null==i)continue;n.getEffect().setTexture(o,i)}else Z.SetUniform(n.getEffect(),o,e,h)}}o(n)})(o,e,s,t,i,n,r)}})(e,b,r,s,f,i),b.sideOrientation=B.F.CounterClockWiseSideOrientation,a&&a.functions){const e=a.functions;e.cullFace&&e.cullFace[0]!==S.BACK&&(b.backFaceCulling=!1);const t=e.blendFuncSeparate;t&&(t[0]===E.SRC_ALPHA&&t[1]===E.ONE_MINUS_SRC_ALPHA&&t[2]===E.ONE&&t[3]===E.ONE?b.alphaMode=ee.g.ALPHA_COMBINE:t[0]===E.ONE&&t[1]===E.ONE&&t[2]===E.ZERO&&t[3]===E.ONE?b.alphaMode=ee.g.ALPHA_ONEONE:t[0]===E.SRC_ALPHA&&t[1]===E.ONE&&t[2]===E.ZERO&&t[3]===E.ONE?b.alphaMode=ee.g.ALPHA_ADD:t[0]===E.ZERO&&t[1]===E.ONE_MINUS_SRC_COLOR&&t[2]===E.ONE&&t[3]===E.ONE?b.alphaMode=ee.g.ALPHA_SUBTRACT:t[0]===E.DST_COLOR&&t[1]===E.ZERO&&t[2]===E.ONE&&t[3]===E.ONE?b.alphaMode=ee.g.ALPHA_MULTIPLY:t[0]===E.SRC_ALPHA&&t[1]===E.ONE_MINUS_SRC_COLOR&&t[2]===E.ONE&&t[3]===E.ONE&&(b.alphaMode=ee.g.ALPHA_MAXIMIZED))}}}class Te{static RegisterExtension(e){Te.Extensions[e.name]?o.w1.Error('Tool with the same name "'+e.name+'" already exists'):Te.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,n,s,r,a,l){return t.useRightHandedSystem=!0,Se.LoadRuntimeAsync(t,i,n,(t=>{t.assetContainer=s,t.importOnlyMeshes=!0,""===e?t.importMeshesNames=[]:"string"==typeof e?t.importMeshesNames=[e]:!e||e instanceof Array?(t.importMeshesNames=[],o.w1.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[e],this._createNodes(t);const i=new Array,n=new Array;for(const e in t.nodes){const n=t.nodes[e];n.babylonNode instanceof j.x&&i.push(n.babylonNode)}for(const e in t.skins){const i=t.skins[e];i.babylonSkeleton instanceof F.O&&n.push(i.babylonSkeleton)}this._loadBuffersAsync(t,(()=>{this._loadShadersAsync(t,(()=>{xe(t),ve(t),!R.IncrementalLoading&&r&&r(i,n)}))})),R.IncrementalLoading&&r&&r(i,n)}),l),!0}importMeshAsync(e,t,i,n,s,r){return new Promise(((o,a)=>{this._importMeshAsync(e,t,n,s,i,((e,t)=>{o({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[]})}),r,(e=>{a(new Error(e))}))}))}_loadAsync(e,t,i,n,s,r){e.useRightHandedSystem=!0,Se.LoadRuntimeAsync(e,t,i,(e=>{Se.LoadRuntimeExtensionsAsync(e,(()=>{this._createNodes(e),this._loadBuffersAsync(e,(()=>{this._loadShadersAsync(e,(()=>{xe(e),ve(e),R.IncrementalLoading||n()}))})),R.IncrementalLoading&&n()}),r)}),r)}loadAsync(e,t,i,n){return new Promise(((s,r)=>{this._loadAsync(e,t,i,(()=>{s()}),n,(e=>{r(new Error(e))}))}))}_loadShadersAsync(e,t){let i=!1;const n=(i,n)=>{Se.LoadShaderStringAsync(e,i,(s=>{s instanceof ArrayBuffer||(e.loadedShaderCount++,s&&(L.Q.ShadersStore[i+(n.type===v.VERTEX?"VertexShader":"PixelShader")]=s),e.loadedShaderCount===e.shaderscount&&t())}),(()=>{o.w1.Error("Error when loading shader program named "+i+" located at "+n.uri)}))};for(const t in e.shaders){i=!0;const s=e.shaders[t];s?n.bind(this,t,s)():o.w1.Error("No shader named: "+t)}i||t()}_loadBuffersAsync(e,t){let i=!1;const n=(i,n)=>{Se.LoadBufferAsync(e,i,(s=>{e.loadedBufferCount++,s&&(s.byteLength!=e.buffers[i].byteLength&&o.w1.Error("Buffer named "+i+" is length "+s.byteLength+". Expected: "+n.byteLength),e.loadedBufferViews[i]=s),e.loadedBufferCount===e.buffersCount&&t()}),(()=>{o.w1.Error("Error when loading buffer named "+i+" located at "+n.uri)}))};for(const t in e.buffers){i=!0;const s=e.buffers[t];s?n.bind(this,t,s)():o.w1.Error("No buffer named: "+t)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;i<t.nodes.length;i++)ge(e,t.nodes[i],null);else for(const i in e.scenes){t=e.scenes[i];for(let i=0;i<t.nodes.length;i++)ge(e,t.nodes[i],null)}}}Te.Extensions={};class Se{constructor(e){this._name=e}get name(){return this._name}loadRuntimeAsync(e,t,i,n,s){return!1}loadRuntimeExtensionsAsync(e,t,i){return!1}loadBufferAsync(e,t,i,n,s){return!1}loadTextureBufferAsync(e,t,i,n){return!1}createTextureAsync(e,t,i,n,s){return!1}loadShaderStringAsync(e,t,i,n){return!1}loadMaterialAsync(e,t,i,n){return!1}static LoadRuntimeAsync(e,t,i,n,s){Se._ApplyExtensions((r=>r.loadRuntimeAsync(e,t,i,n,s)),(()=>{setTimeout((()=>{n&&n(be.CreateRuntime(t.json,e,i))}))}))}static LoadRuntimeExtensionsAsync(e,t,i){Se._ApplyExtensions((n=>n.loadRuntimeExtensionsAsync(e,t,i)),(()=>{setTimeout((()=>{t()}))}))}static LoadBufferAsync(e,t,i,n,s){Se._ApplyExtensions((r=>r.loadBufferAsync(e,t,i,n,s)),(()=>{be.LoadBufferAsync(e,t,i,n,s)}))}static LoadTextureAsync(e,t,i,n){Se._LoadTextureBufferAsync(e,t,(s=>{s&&Se._CreateTextureAsync(e,t,s,i,n)}),n)}static LoadShaderStringAsync(e,t,i,n){Se._ApplyExtensions((s=>s.loadShaderStringAsync(e,t,i,n)),(()=>{be.LoadShaderStringAsync(e,t,i,n)}))}static LoadMaterialAsync(e,t,i,n){Se._ApplyExtensions((s=>s.loadMaterialAsync(e,t,i,n)),(()=>{be.LoadMaterialAsync(e,t,i,n)}))}static _LoadTextureBufferAsync(e,t,i,n){Se._ApplyExtensions((s=>s.loadTextureBufferAsync(e,t,i,n)),(()=>{be.LoadTextureBufferAsync(e,t,i,n)}))}static _CreateTextureAsync(e,t,i,n,s){Se._ApplyExtensions((r=>r.createTextureAsync(e,t,i,n,s)),(()=>{be.CreateTextureAsync(e,t,i,n)}))}static _ApplyExtensions(e,t){for(const t in Te.Extensions)if(e(Te.Extensions[t]))return;t()}}R._CreateGLTF1Loader=()=>new Te;class Ee extends Se{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,n){const s=t.json.extensionsUsed;return!(!s||-1===s.indexOf(this.name)||!t.bin||(this._bin=t.bin,n(be.CreateRuntime(t.json,e,i)),0))}loadBufferAsync(e,t,i,n){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(i,(e=>n(e.message))),!0)}loadTextureBufferAsync(e,t,i){const n=e.textures[t],s=e.images[n.source];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],o=e.bufferViews[r.bufferView];return i(Z.GetBufferFromBufferView(e,o,0,o.byteLength,g.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,i){const n=e.shaders[t];if(!n.extensions||!(this.name in n.extensions))return!1;const s=n.extensions[this.name],r=e.bufferViews[s.bufferView],o=Z.GetBufferFromBufferView(e,r,0,r.byteLength,g.UNSIGNED_BYTE);return setTimeout((()=>{const e=Z.DecodeBufferToText(o);i(e)})),!0}}Te.RegisterExtension(new Ee);class Ce extends Se{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const t in i){const n=i[t];switch(n.type){case"ambient":{const t=new q.e(n.name,new M.P(0,1,0),e.scene),i=n.ambient;i&&(t.diffuse=I.Wo.FromArray(i.color||[1,1,1]));break}case"point":{const t=new $.c(n.name,new M.P(10,10,10),e.scene),i=n.point;i&&(t.diffuse=I.Wo.FromArray(i.color||[1,1,1]));break}case"directional":{const t=new K.O(n.name,new M.P(0,-1,0),e.scene),i=n.directional;i&&(t.diffuse=I.Wo.FromArray(i.color||[1,1,1]));break}case"spot":{const t=n.spot;t&&(new Q.P(n.name,new M.P(0,10,0),new M.P(0,-1,0),t.fallOffAngle||Math.PI,t.fallOffExponent||0,e.scene).diffuse=I.Wo.FromArray(t.color||[1,1,1]));break}default:o.w1.Warn('GLTF Material Common extension: light type "'+n.type+"” not supported")}}return!1}loadMaterialAsync(e,t,i,n){const s=e.materials[t];if(!s||!s.extensions)return!1;const r=s.extensions[this.name];if(!r)return!1;const o=new V.K(t,e.scene);return o.sideOrientation=B.F.CounterClockWiseSideOrientation,"CONSTANT"===r.technique&&(o.disableLighting=!0),o.backFaceCulling=void 0!==r.doubleSided&&!r.doubleSided,o.alpha=void 0===r.values.transparency?1:r.values.transparency,o.specularPower=void 0===r.values.shininess?0:r.values.shininess,"string"==typeof r.values.ambient?this._loadTexture(e,r.values.ambient,o,"ambientTexture",n):o.ambientColor=I.Wo.FromArray(r.values.ambient||[0,0,0]),"string"==typeof r.values.diffuse?this._loadTexture(e,r.values.diffuse,o,"diffuseTexture",n):o.diffuseColor=I.Wo.FromArray(r.values.diffuse||[0,0,0]),"string"==typeof r.values.emission?this._loadTexture(e,r.values.emission,o,"emissiveTexture",n):o.emissiveColor=I.Wo.FromArray(r.values.emission||[0,0,0]),"string"==typeof r.values.specular?this._loadTexture(e,r.values.specular,o,"specularTexture",n):o.specularColor=I.Wo.FromArray(r.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,n,s){be.LoadTextureBufferAsync(e,t,(s=>{be.CreateTextureAsync(e,t,s,(e=>i[n]=e))}),s)}}Te.RegisterExtension(new Ce);var Ae=i(7188),Pe=i(4173),Re=i(2323),Me=i(9500),Ie=i(4674),De=i(7780),Oe=i(4702),we=i(3722);function Ne(e,t,i,n){return M.P.FromArray(t,i).scaleInPlace(n)}class Fe{constructor(e,t,i,n){this.type=e,this.name=t,this.getValue=i,this.getStride=n}_buildAnimation(e,t,i){const n=new w.f(e,this.name,t,this.type);return n.setKeys(i),n}}class Le extends Fe{buildAnimations(e,t,i,n,s){s(e._babylonTransformNode,this._buildAnimation(t,i,n))}}const Be={translation:[new Le(w.f.ANIMATIONTYPE_VECTOR3,"position",Ne,(()=>3))],rotation:[new Le(w.f.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,n){return M._f.FromArray(t,i).scaleInPlace(n)}),(()=>4))],scale:[new Le(w.f.ANIMATIONTYPE_VECTOR3,"scaling",Ne,(()=>3))],weights:[new class extends Fe{buildAnimations(e,t,i,n,s){if(e._numMorphTargets)for(let r=0;r<e._numMorphTargets;r++){const o=new w.f(`${t}_${r}`,this.name,i,this.type);if(o.setKeys(n.map((e=>({frame:e.frame,inTangent:e.inTangent?e.inTangent[r]:void 0,value:e.value[r],outTangent:e.outTangent?e.outTangent[r]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(r),i=o.clone();e.animations.push(i),s(e,i)}}}}(w.f.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,n){const s=new Array(e._numMorphTargets);for(let e=0;e<s.length;e++)s[e]=t[i++]*n;return s}),(e=>e._numMorphTargets))]};function Ue(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((n=>{const s=e[n],r=i[n];Array.isArray(s)&&Array.isArray(r)?e[n]=s.concat(...r):t(s)&&t(r)?e[n]=Ue(s,r):e[n]=r})),e)),{})}class Ve{static Get(e,t,i){if(!t||null==i||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static Assign(e){if(e)for(let t=0;t<e.length;t++)e[t].index=t}}class ke{static RegisterExtension(e,t){ke.UnregisterExtension(e)&&h.Y.Warn(`Extension with the name '${e}' already exists`),ke._RegisteredExtensions[e]={factory:t}}static UnregisterExtension(e){return!!ke._RegisteredExtensions[e]&&(delete ke._RegisteredExtensions[e],!0)}get gltf(){if(!this._gltf)throw new Error("glTF JSON is not available");return this._gltf}get bin(){return this._bin}get parent(){return this._parent}get babylonScene(){if(!this._babylonScene)throw new Error("Scene is not available");return this._babylonScene}get rootBabylonMesh(){return this._rootBabylonMesh}constructor(e){this._completePromises=new Array,this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._extensions=new Array,this._disposed=!1,this._rootUrl=null,this._fileName=null,this._uniqueRootUrl=null,this._bin=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions=new Array,this._parent=e}dispose(){this._disposed||(this._disposed=!0,this._completePromises.length=0,this._extensions.forEach((e=>e.dispose&&e.dispose())),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,n,s,r,o=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(n);let r=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);r=(e instanceof Array?e:[e]).map((e=>{const i=t[e];if(void 0===i)throw new Error(`Failed to find node '${e}'`);return i}))}return this._loadAsync(s,o,r,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries()})))}))}loadAsync(e,t,i,n,s=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,s,null,(()=>{})))))}_loadAsync(e,t,i,n){return Promise.resolve().then((()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._loadExtensions(),this._checkExtensions();const s=`${m[m.LOADING]} => ${m[m.READY]}`,r=`${m[m.LOADING]} => ${m[m.COMPLETE]}`;this._parent._startPerformanceCounter(s),this._parent._startPerformanceCounter(r),this._parent._setState(m.LOADING),this._extensionsOnLoading();const a=new Array,l=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(i)a.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=Ve.Get("/scene",this._gltf.scenes,this._gltf.scene||0);a.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e<this._gltf.materials.length;++e){const t=this._gltf.materials[e],i="/materials/"+e,n=B.F.TriangleFillMode;a.push(this._loadMaterialAsync(i,t,null,n,(()=>{})))}return this._babylonScene.blockMaterialDirtyMechanism=l,this._parent.compileMaterials&&a.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&a.push(this._compileShadowGeneratorsAsync()),Promise.all(a).then((()=>(this._rootBabylonMesh&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(m.READY),this._startAnimations(),n()))).then((e=>(this._parent._endPerformanceCounter(s),o.w1.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(r),this._parent._setState(m.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()}),(e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()}))})),e)))})).catch((e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e}))}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLength<e.bin.byteLength-3||i.byteLength>e.bin.byteLength)&&h.Y.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else h.Y.Warn("Unexpected BIN chunk")}}_setupData(){if(Ve.Assign(this._gltf.accessors),Ve.Assign(this._gltf.animations),Ve.Assign(this._gltf.buffers),Ve.Assign(this._gltf.bufferViews),Ve.Assign(this._gltf.cameras),Ve.Assign(this._gltf.images),Ve.Assign(this._gltf.materials),Ve.Assign(this._gltf.meshes),Ve.Assign(this._gltf.nodes),Ve.Assign(this._gltf.samplers),Ve.Assign(this._gltf.scenes),Ve.Assign(this._gltf.skins),Ve.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const i of t.children)e[i]=t.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const n=e[i.index];i.parent=void 0===n?t:this._gltf.nodes[n]}}}_loadExtensions(){for(const e in ke._RegisteredExtensions){const t=ke._RegisteredExtensions[e].factory(this);t.name!==e&&h.Y.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort(((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE))),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired)for(const e of this._gltf.extensionsRequired)if(!this._extensions.some((t=>t.name===e&&t.enabled)))throw new Error(`Require extension ${e} is not available`)}_createRootNode(){this._babylonScene._blockEntityCollection=!!this._assetContainer,this._rootBabylonMesh=new Y.Kj("__root__",this._babylonScene),this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const e={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case f.AUTO:this._babylonScene.useRightHandedSystem||(e.rotation=[0,1,0,0],e.scale=[1,1,-1],ke._LoadTransform(e,this._rootBabylonMesh));break;case f.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh),e}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const n=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const i of t.nodes){const t=Ve.Get(`${e}/nodes/${i}`,this._gltf.nodes,i);n.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=this._rootBabylonMesh})))}for(const e of this._postSceneLoadActions)e();return n.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(n).then((()=>{}))}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=new Array,t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{const i=t.geometry;i&&-1===e.indexOf(i)&&e.push(i)}));return e}_getMeshes(){const e=new Array;this._rootBabylonMesh&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{e.push(t)}));return e}_getTransformNodes(){const e=new Array,t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&"TransformNode"===i._babylonTransformNode.getClassName()&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=new Array,t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=new Array,t=this._gltf.animations;if(t)for(const i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case _.NONE:break;case _.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case _.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void h.Y.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,t,i=(()=>{})){const n=this._extensionsLoadNodeAsync(e,t,i);if(n)return n;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const s=new Array;this.logOpen(`${e} ${t.name||""}`);const r=n=>{if(ke.AddPointerMetadata(n,e),ke._LoadTransform(t,n),null!=t.camera){const i=Ve.Get(`${e}/camera`,this._gltf.cameras,t.camera);s.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=n})))}if(t.children)for(const i of t.children){const t=Ve.Get(`${e}/children/${i}`,this._gltf.nodes,i);s.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=n})))}i(n)};if(null==t.mesh||null!=t.skin){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Ie.Y(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=i:t._babylonTransformNodeForSkin=i,r(i)}if(null!=t.mesh)if(null==t.skin){const i=Ve.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,r))}else{const i=Ve.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const n=t._babylonTransformNodeForSkin;i.metadata=Ue(n.metadata,i.metadata||{});const r=Ve.Get(`${e}/skin`,this._gltf.skins,t.skin);s.push(this._loadSkinAsync(`/skins/${r.index}`,t,r,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=r.skeleton){const e=Ve.Get(`/skins/${r.index}/skeleton`,this._gltf.nodes,r.skeleton).parent;t.index===e.index?i.parent=n.parent:i.parent=e._babylonTransformNode}else i.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:n,skinnedNode:i})}))})))})))}return this.logClose(),Promise.all(s).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,n){const s=i.primitives;if(!s||!s.length)throw new Error(`${e}: Primitives are missing`);null==s[0].index&&Ve.Assign(s);const r=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(1===s.length){const n=i.primitives[0];r.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${n.index}`,o,t,i,n,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Ie.Y(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const n of s)r.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${n.index}`,`${o}_primitive${n.index}`,t,i,n,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return n(t._babylonTransformNode),this.logClose(),Promise.all(r).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,n,s,r){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,n,s,r);if(o)return o;this.logOpen(`${e}`);const a=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!n.primitives[0].targets;let l,h;if(a&&s._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=s._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=s._instanceData.promise;else{const r=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new Y.Kj(t,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?B.F.CounterClockWiseSideOrientation:B.F.ClockWiseSideOrientation,this._createMorphTargets(e,i,n,s,o),r.push(this._loadVertexDataAsync(e,s,o).then((t=>this._loadMorphTargetsAsync(e,s,o,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(o),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=ke._GetDrawMode(e,s.mode);if(null==s.material){let e=this._defaultBabylonMaterialData[c];e||(e=this._createDefaultMaterial("__GLTFLoader._default",c),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[c]=e),o.material=e}else if(!this.parent.skipMaterials){const t=Ve.Get(`${e}/material`,this._gltf.materials,s.material);r.push(this._loadMaterialAsync(`/materials/${t.index}`,t,o,c,(e=>{o.material=e})))}h=Promise.all(r),a&&(s._instanceData={babylonSourceMesh:o,promise:h}),l=o}return ke.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),r(l),this.logClose(),h.then((()=>l))}_loadVertexDataAsync(e,t,i){const n=this._extensionsLoadVertexDataAsync(e,t,i);if(n)return n;const s=t.attributes;if(!s)throw new Error(`${e}: Attributes are missing`);const r=new Array,o=new H.Z(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=Ve.Get(`${e}/indices`,this._gltf.accessors,t.indices);r.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{o.setIndices(e)})))}const a=(t,n,a)=>{if(null==s[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(n)&&i._delayInfo.push(n);const l=Ve.Get(`${e}/attributes/${t}`,this._gltf.accessors,s[t]);r.push(this._loadVertexAccessorAsync(`/accessors/${l.index}`,l,n).then((e=>{if(e.getKind()===W.o.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&l.min&&l.max){const e=M.jp.Vector3[0].copyFromFloats(...l.min),t=M.jp.Vector3[1].copyFromFloats(...l.max);if(l.normalized&&5126!==l.componentType){let i=1;switch(l.componentType){case 5120:i=127;break;case 5121:i=255;break;case 5122:i=32767;break;case 5123:i=65535}const n=1/i;e.scaleInPlace(n),t.scaleInPlace(n)}o._boundingInfo=new we.j(e,t),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(e,l.count)}))),n==W.o.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),a&&a(l)};return a("POSITION",W.o.PositionKind),a("NORMAL",W.o.NormalKind),a("TANGENT",W.o.TangentKind),a("TEXCOORD_0",W.o.UVKind),a("TEXCOORD_1",W.o.UV2Kind),a("TEXCOORD_2",W.o.UV3Kind),a("TEXCOORD_3",W.o.UV4Kind),a("TEXCOORD_4",W.o.UV5Kind),a("TEXCOORD_5",W.o.UV6Kind),a("JOINTS_0",W.o.MatricesIndicesKind),a("WEIGHTS_0",W.o.MatricesWeightsKind),a("JOINTS_1",W.o.MatricesIndicesExtraKind),a("WEIGHTS_1",W.o.MatricesWeightsExtraKind),a("COLOR_0",W.o.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(r).then((()=>o))}_createMorphTargets(e,t,i,n,s){if(!n.targets)return;if(null==t._numMorphTargets)t._numMorphTargets=n.targets.length;else if(n.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const r=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,s.morphTargetManager=new Oe.O(this._babylonScene),s.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e<n.targets.length;e++){const n=t.weights?t.weights[e]:i.weights?i.weights[e]:0,o=r?r[e]:`morphTarget${e}`;s.morphTargetManager.addTarget(new De.Y(o,n,s.getScene()))}}_loadMorphTargetsAsync(e,t,i,n){if(!t.targets)return Promise.resolve();const s=new Array,r=i.morphTargetManager;for(let i=0;i<r.numTargets;i++){const o=r.getTarget(i);s.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${i}`,n,t.targets[i],o))}return Promise.all(s).then((()=>{r.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,n){const s=new Array,r=(n,r,o)=>{if(null==i[n])return;const a=t.getVertexBuffer(r);if(!a)return;const l=Ve.Get(`${e}/${n}`,this._gltf.accessors,i[n]);s.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{o(a,e)})))};return r("POSITION",W.o.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,n)=>{i[n]=t[n]+e})),n.setPositions(i)})),r("NORMAL",W.o.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,n)=>{i[n]=t[n]+e})),n.setNormals(i)})),r("TANGENT",W.o.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let s=0;e.forEach(t.length/3*4,((e,n)=>{(n+1)%4!=0&&(i[s]=t[s]+e,s++)})),n.setTangents(i)})),Promise.all(s).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=M.P.Zero(),n=M._f.Identity(),s=M.P.One();e.matrix?M.y3.FromArray(e.matrix).decompose(s,n,i):(e.translation&&(i=M.P.FromArray(e.translation)),e.rotation&&(n=M._f.FromArray(e.rotation)),e.scale&&(s=M.P.FromArray(e.scale))),t.position=i,t.rotationQuaternion=n,t.scaling=s}_loadSkinAsync(e,t,i,n){const s=this._extensionsLoadSkinAsync(e,t,i);if(s)return s;if(i._data)return n(i._data.babylonSkeleton),i._data.promise;const r=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new F.O(i.name||r,r,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const a=this._loadSkinInverseBindMatricesDataAsync(e,i).then((e=>{this._updateBoneMatrices(o,e)}));return i._data={babylonSkeleton:o,promise:a},n(o),a}_loadBones(e,t,i){if(null==t.skeleton||this._parent.alwaysComputeSkeletonRootNode){const i=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(i)if(void 0===t.skeleton)t.skeleton=i.index;else{const n=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},s=Ve.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);s===i||n(s,i)||(h.Y.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else h.Y.Warn(`${e}: Failed to find common root`)}const n={};for(const s of t.joints){const r=Ve.Get(`${e}/joints/${s}`,this._gltf.nodes,s);this._loadBone(r,t,i,n)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const n of t){const t=new Array;let s=Ve.Get(`${e}/${n}`,this._gltf.nodes,n);for(;-1!==s.index;)t.unshift(s),s=s.parent;i[n]=t}let n=null;for(let e=0;;++e){let s=i[t[0]];if(e>=s.length)return n;const r=s[e];for(let o=1;o<t.length;++o)if(s=i[t[o]],e>=s.length||r!==s[e])return n;n=r}}_loadBone(e,t,i,n){let s=n[e.index];if(s)return s;let r=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?r=this._loadBone(e.parent,t,i,n):void 0!==t.skeleton&&h.Y.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return s=new N.N(e.name||`joint${e.index}`,i,r,this._getNodeMatrix(e),null,null,o),n[e.index]=s,this._postSceneLoadActions.push((()=>{s.linkTransformNode(e._babylonTransformNode)})),s}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=Ve.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(const i of e.bones){const e=M.y3.Identity(),n=i._index;t&&-1!==n&&(M.y3.FromArrayToRef(t,16*n,e),e.invertToRef(e));const s=i.getParent();s&&e.multiplyToRef(s.getInvertedAbsoluteTransform(),e),i.updateMatrix(e,!1,!1),i._updateDifferenceMatrix(void 0,!1)}}_getNodeMatrix(e){return e.matrix?M.y3.FromArray(e.matrix):M.y3.Compose(e.scale?M.P.FromArray(e.scale):M.P.One(),e.rotation?M._f.FromArray(e.rotation):M._f.Identity(),e.translation?M.P.FromArray(e.translation):M.P.Zero())}loadCameraAsync(e,t,i=(()=>{})){const n=this._extensionsLoadCameraAsync(e,t,i);if(n)return n;const s=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const r=new O.c(t.name||`camera${t.index}`,M.P.Zero(),this._babylonScene,!1);switch(r._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.ignoreParentScaling=!0,t._babylonCamera=r,r.rotation=new M.P(0,Math.PI,0),t.type){case"perspective":{const i=t.perspective;if(!i)throw new Error(`${e}: Camera perspective properties are missing`);r.fov=i.yfov,r.minZ=i.znear,r.maxZ=i.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);r.mode=D.V.ORTHOGRAPHIC_CAMERA,r.orthoLeft=-t.orthographic.xmag,r.orthoRight=t.orthographic.xmag,r.orthoBottom=-t.orthographic.ymag,r.orthoTop=t.orthographic.ymag,r.minZ=t.orthographic.znear,r.maxZ=t.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return ke.AddPointerMetadata(r,e),this._parent.onCameraLoadedObservable.notifyObservers(r),i(r),this.logClose(),Promise.all(s).then((()=>r))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i<e.length;i++){const n=e[i];t.push(this.loadAnimationAsync(`/animations/${n.index}`,n).then((e=>{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new Re.O(t.name||`animation${t.index}`,this._babylonScene);n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=n;const s=new Array;Ve.Assign(t.channels),Ve.Assign(t.samplers);for(const i of t.channels)s.push(this._loadAnimationChannelAsync(`${e}/channels/${i.index}`,e,t,i,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),n.addTargetedAnimation(t,e)})));return Promise.all(s).then((()=>(n.normalize(0),n)))}_loadAnimationChannelAsync(e,t,i,n,s){const r=this._extensionsLoadAnimationChannelAsync(e,t,i,n,s);if(r)return r;if(null==n.target.node)return Promise.resolve();const o=Ve.Get(`${e}/target/node`,this._gltf.nodes,n.target.node);if("weights"===n.target.path&&!o._numMorphTargets||"weights"!==n.target.path&&!o._babylonTransformNode)return Promise.resolve();let a;switch(n.target.path){case"translation":a=Be.translation;break;case"rotation":a=Be.rotation;break;case"scale":a=Be.scale;break;case"weights":a=Be.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${n.target.path})`)}const l={target:o,properties:a};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,n,l,s)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,n,s,r){const o=this.parent.targetFps,a=1/o,l=Ve.Get(`${e}/sampler`,i.samplers,n.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${n.sampler}`,l).then((e=>{let t=0;for(const l of s.properties){const h=l.getStride(s.target),c=e.input,u=e.output,d=new Array(c.length);let p=0;switch(e.interpolation){case"STEP":for(let e=0;e<c.length;e++){const t=l.getValue(s.target,u,p,1);p+=h,d[e]={frame:c[e]*o,value:t,interpolation:Pe.N.STEP}}break;case"CUBICSPLINE":for(let e=0;e<c.length;e++){const t=l.getValue(s.target,u,p,a);p+=h;const i=l.getValue(s.target,u,p,1);p+=h;const n=l.getValue(s.target,u,p,a);p+=h,d[e]={frame:c[e]*o,inTangent:t,value:i,outTangent:n}}break;case"LINEAR":for(let e=0;e<c.length;e++){const t=l.getValue(s.target,u,p,1);p+=h,d[e]={frame:c[e]*o,value:t}}}if(p>0){const e=`${i.name||`animation${i.index}`}_channel${n.index}_${t}`;l.buildAnimations(s.target,e,o,d,((e,i)=>{++t,r(e,i)}))}}}))}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const n=Ve.Get(`${e}/input`,this._gltf.accessors,t.input),s=Ve.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${n.index}`,n),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,n){const s=this._extensionsLoadBufferAsync(e,t,i,n);if(s)return s;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then((t=>{try{return new Uint8Array(t.buffer,t.byteOffset+i,n)}catch(t){throw new Error(`${e}: ${t.message}`)}}))}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const n=Ve.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${n.index}`,n,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const n=ke._GetNumComponents(e,t.type),s=n*W.o.GetTypeByteLength(t.componentType),r=n*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(r));else{const o=Ve.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then((a=>{if(5126!==t.componentType||t.normalized||o.byteStride&&o.byteStride!==s){const e=new i(r);return W.o.ForEach(a,t.byteOffset||0,o.byteStride||s,n,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return ke._GetTypedArray(e,t.componentType,a,t.byteOffset,r)}))}if(t.sparse){const r=t.sparse;t._data=t._data.then((o=>{const a=o,l=Ve.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,r.indices.bufferView),h=Ve.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,r.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then((([o,l])=>{const h=ke._GetTypedArray(`${e}/sparse/indices`,r.indices.componentType,o,r.indices.byteOffset,r.count),c=n*r.count;let u;if(5126!==t.componentType||t.normalized){const o=ke._GetTypedArray(`${e}/sparse/values`,t.componentType,l,r.values.byteOffset,c);u=new i(c),W.o.ForEach(o,0,s,n,t.componentType,u.length,t.normalized||!1,((e,t)=>{u[t]=e}))}else u=ke._GetTypedArray(`${e}/sparse/values`,t.componentType,l,r.values.byteOffset,c);let d=0;for(let e=0;e<h.length;e++){let t=h[e]*n;for(let e=0;e<n;e++)a[t++]=u[d++]}return a}))}))}return t._data}_loadFloatAccessorAsync(e,t){return this._loadAccessorAsync(e,t,Float32Array)}_loadIndicesAccessorAsync(e,t){if("SCALAR"!==t.type)throw new Error(`${e}/type: Invalid value ${t.type}`);if(5121!==t.componentType&&5123!==t.componentType&&5125!==t.componentType)throw new Error(`${e}/componentType: Invalid value ${t.componentType}`);if(t._data)return t._data;if(t.sparse){const i=ke._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,i)}else{const i=Ve.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i).then((i=>ke._GetTypedArray(e,t.componentType,i,t.byteOffset,t.count)))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then((e=>new W.l(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var n;if(null===(n=t._babylonVertexBuffer)||void 0===n?void 0:n[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new W.o(s,e,i,!1)));else if(i===W.o.MatricesIndicesKind||i===W.o.MatricesIndicesExtraKind)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new W.o(s,e,i,!1)));else{const n=Ve.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(n).then((r=>{const o=ke._GetNumComponents(e,t.type);return new W.o(s,r,i,!1,!1,n.byteStride,!1,t.byteOffset,o,t.componentType,t.normalized,!0,1,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);const n=new Array;return t&&(t.baseColorFactor?(i.albedoColor=I.Wo.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=I.Wo.White(),i.metallic=null==t.metallicFactor?1:t.metallicFactor,i.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&n.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e}))),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,n.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,(e=>{e.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=e}))),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(n).then((()=>{}))}_loadMaterialAsync(e,t,i,n,s=(()=>{})){const r=this._extensionsLoadMaterialAsync(e,t,i,n,s);if(r)return r;t._data=t._data||{};let o=t._data[n];if(!o){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,n);o={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[n]=o,ke.AddPointerMetadata(i,e),this._parent.onMaterialLoadedObservable.notifyObservers(i),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce((()=>{const e=o.babylonMeshes.indexOf(i);-1!==e&&o.babylonMeshes.splice(e,1)}))),s(o.babylonMaterial),o.promise.then((()=>o.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Me.Y(e,this._babylonScene);return i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.enableSpecularAntiAliasing=!0,i.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,i.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,i.transparencyMode=Me.Y.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const n=this._extensionsCreateMaterial(e,t,i);if(n)return n;const s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,i)}loadMaterialPropertiesAsync(e,t,i){const n=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(n)return n;const s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);const n=new Array;return i.emissiveColor=t.emissiveFactor?I.Wo.FromArray(t.emissiveFactor):new I.Wo(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,n.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,(e=>{e.name=`${i.name} (Normal)`,i.bumpTexture=e}))),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=t.normalTexture.scale&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,n.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,(e=>{e.name=`${i.name} (Occlusion)`,i.ambientTexture=e}))),i.useAmbientInGrayScale=!0,null!=t.occlusionTexture.strength&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&n.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,(e=>{e.name=`${i.name} (Emissive)`,i.emissiveTexture=e}))),Promise.all(n).then((()=>{}))}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=Me.Y.PBRMATERIAL_OPAQUE;break;case"MASK":i.transparencyMode=Me.Y.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=Me.Y.PBRMATERIAL_ALPHABLEND,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=(()=>{})){const n=this._extensionsLoadTextureInfoAsync(e,t,i);if(n)return n;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const s=Ve.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;const r=this._loadTextureAsync(`/textures/${t.index}`,s,(n=>{n.coordinatesIndex=t.texCoord||0,ke.AddPointerMetadata(n,e),this._parent.onTextureLoadedObservable.notifyObservers(n),i(n)}));return this.logClose(),r}_loadTextureAsync(e,t,i=(()=>{})){const n=this._extensionsLoadTextureAsync(e,t,i);if(n)return n;this.logOpen(`${e} ${t.name||""}`);const s=null==t.sampler?ke.DefaultSampler:Ve.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),r=Ve.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,s,r,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,n=(()=>{}),s,r){const o=this._loadSampler(`/samplers/${t.index}`,t),a=new Array,l=new Ae.B;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(t,i)=>{this._disposed||l.reject(new Error(`${e}: ${i&&i.message?i.message:t||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:s,useSRGBBuffer:!!r&&this._parent.useSRGBBuffers},c=new G.x(null,this._babylonScene,h);return c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.push(l.promise),a.push(this.loadImageAsync(`/images/${i.index}`,i).then((e=>{const t=i.uri||`${this._fileName}#image${i.index}`,n=`data:${this._uniqueRootUrl}${t}`;c.updateURL(n,e)}))),c.wrapU=o.wrapU,c.wrapV=o.wrapV,n(c),Promise.all(a).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:ke._GetTextureSamplingMode(e,t),wrapU:ke._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:ke._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const i=Ve.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){const n=this._extensionsLoadUriAsync(e,t,i);if(n)return n;if(!ke._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if((0,C.VL)(i)){const t=new Uint8Array((0,C.$K)(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${t.length} bytes)`),Promise.resolve(t)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then((t=>new Promise(((n,s)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),n(new Uint8Array(t)))}),!0,(t=>{s(new C.eh(`${e}: Failed to load '${i}'${t?": "+t.status+" "+t.statusText:""}`,t))}))}))))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},n=i.gltf=i.gltf||{};(n.pointers=n.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=null==t?10497:t){case 33071:return G.x.CLAMP_ADDRESSMODE;case 33648:return G.x.MIRROR_ADDRESSMODE;case 10497:return G.x.WRAP_ADDRESSMODE;default:return h.Y.Warn(`${e}: Invalid value (${t})`),G.x.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=null==t.magFilter?9729:t.magFilter,n=null==t.minFilter?9987:t.minFilter;if(9729===i)switch(n){case 9728:return G.x.LINEAR_NEAREST;case 9729:return G.x.LINEAR_LINEAR;case 9984:return G.x.LINEAR_NEAREST_MIPNEAREST;case 9985:return G.x.LINEAR_LINEAR_MIPNEAREST;case 9986:return G.x.LINEAR_NEAREST_MIPLINEAR;case 9987:return G.x.LINEAR_LINEAR_MIPLINEAR;default:return h.Y.Warn(`${e}/minFilter: Invalid value (${n})`),G.x.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&h.Y.Warn(`${e}/magFilter: Invalid value (${i})`),n){case 9728:return G.x.NEAREST_NEAREST;case 9729:return G.x.NEAREST_LINEAR;case 9984:return G.x.NEAREST_NEAREST_MIPNEAREST;case 9985:return G.x.NEAREST_LINEAR_MIPNEAREST;case 9986:return G.x.NEAREST_NEAREST_MIPLINEAR;case 9987:return G.x.NEAREST_LINEAR_MIPLINEAR;default:return h.Y.Warn(`${e}/minFilter: Invalid value (${n})`),G.x.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,i,n,s){const r=i.buffer;n=i.byteOffset+(n||0);const o=ke._GetTypedArrayConstructor(`${e}/componentType`,t),a=W.o.GetTypeByteLength(t);return n%a!=0?(h.Y.Warn(`${e}: Copying buffer as byte offset (${n}) is not a multiple of component type byte length (${a})`),new o(r.slice(n,n+s*a),0)):new o(r,n,s)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return o.w1.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return B.F.PointListDrawMode;case 1:return B.F.LineListDrawMode;case 2:return B.F.LineLoopDrawMode;case 3:return B.F.LineStripDrawMode;case 4:return B.F.TriangleFillMode;case 5:return B.F.TriangleStripDrawMode;case 6:return B.F.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials)for(const t of this._gltf.materials)if(t._data)for(const i in t._data){const n=t._data[i];for(const t of n.babylonMeshes){t.computeWorldMatrix(!0);const i=n.babylonMaterial;e.push(i.forceCompilationAsync(t)),e.push(i.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(i.forceCompilationAsync(t,{clipPlane:!0})),e.push(i.forceCompilationAsync(t,{clipPlane:!0,useInstances:!0})))}}return Promise.all(e).then((()=>{this._parent._endPerformanceCounter("Compile materials")}))}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const i of t){const t=i.getShadowGenerator();t&&e.push(t.forceCompilationAsync())}return Promise.all(e).then((()=>{this._parent._endPerformanceCounter("Compile shadow generators")}))}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(const n of this._extensions)if(n.enabled){const s=`${n.name}.${t}`,r=e;r._activeLoaderExtensionFunctions=r._activeLoaderExtensionFunctions||{};const o=r._activeLoaderExtensionFunctions;if(!o[s]){o[s]=!0;try{const e=i(n);if(e)return e}finally{delete o[s]}}}return null}_extensionsOnLoading(){this._forEachExtensions((e=>e.onLoading&&e.onLoading()))}_extensionsOnReady(){this._forEachExtensions((e=>e.onReady&&e.onReady()))}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",(i=>i.loadSceneAsync&&i.loadSceneAsync(e,t)))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",(n=>n.loadNodeAsync&&n.loadNodeAsync(e,t,i)))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",(n=>n.loadCameraAsync&&n.loadCameraAsync(e,t,i)))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",(n=>n._loadVertexDataAsync&&n._loadVertexDataAsync(e,t,i)))}_extensionsLoadMeshPrimitiveAsync(e,t,i,n,s,r){return this._applyExtensions(s,"loadMeshPrimitive",(o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,n,s,r)))}_extensionsLoadMaterialAsync(e,t,i,n,s){return this._applyExtensions(t,"loadMaterial",(r=>r._loadMaterialAsync&&r._loadMaterialAsync(e,t,i,n,s)))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",(n=>n.createMaterial&&n.createMaterial(e,t,i)))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",(n=>n.loadMaterialPropertiesAsync&&n.loadMaterialPropertiesAsync(e,t,i)))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",(n=>n.loadTextureInfoAsync&&n.loadTextureInfoAsync(e,t,i)))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",(n=>n._loadTextureAsync&&n._loadTextureAsync(e,t,i)))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",(i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t)))}_extensionsLoadAnimationChannelAsync(e,t,i,n,s){return this._applyExtensions(i,"loadAnimationChannel",(r=>r._loadAnimationChannelAsync&&r._loadAnimationChannelAsync(e,t,i,n,s)))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",(n=>n._loadSkinAsync&&n._loadSkinAsync(e,t,i)))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",(n=>n._loadUriAsync&&n._loadUriAsync(e,t,i)))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",(i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t)))}_extensionsLoadBufferAsync(e,t,i,n){return this._applyExtensions(t,"loadBuffer",(s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,i,n)))}static LoadExtensionAsync(e,t,i,n){if(!t.extensions)return null;const s=t.extensions[i];return s?n(`${e}/extensions/${i}`,s):null}static LoadExtraAsync(e,t,i,n){if(!t.extras)return null;const s=t.extras[i];return s?n(`${e}/extras/${i}`,s):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}ke._RegisteredExtensions={},ke.DefaultSampler={index:-1},R._CreateGLTF2Loader=e=>new ke(e);var Ge=i(1128),ze=i(6113),We=i(9630);const He="EXT_lights_image_based";class Xe{constructor(e){this.name=He,this._loader=e,this.enabled=this._loader.isExtensionUsed(He)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return ke.LoadExtensionAsync(e,t,this.name,((i,n)=>{const s=new Array;s.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const r=Ve.Get(`${i}/light`,this._lights,n.light);return s.push(this._loadLightAsync(`/extensions/${this.name}/lights/${n.light}`,r).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(s).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const n=new Array(t.specularImages.length);for(let s=0;s<t.specularImages.length;s++){const r=t.specularImages[s];n[s]=new Array(r.length);for(let t=0;t<r.length;t++){const o=`${e}/specularImages/${s}/${t}`;this._loader.logOpen(`${o}`);const a=r[t],l=Ve.Get(o,this._loader.gltf.images,a);i.push(this._loader.loadImageAsync(`/images/${a}`,l).then((e=>{n[s][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new We.N(this._loader.babylonScene,null,t.specularImageSize);if(i.name=t.name||"environment",t._babylonTexture=i,null!=t.intensity&&(i.level=t.intensity),t.rotation){let e=M._f.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=M._f.Inverse(e)),M.y3.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const s=ze._.FromArray(t.irradianceCoefficients);s.scaleInPlace(t.intensity),s.convertIrradianceToLambertianRadiance();const r=ze.i.FromHarmonics(s),o=(n.length-1)/Ge.R.Log2(t.specularImageSize);return i.updateRGBDAsync(n,r,o)}))}return t._loaded.then((()=>t._babylonTexture))}}ke.RegisterExtension(He,(e=>new Xe(e))),i(2708);const je="EXT_mesh_gpu_instancing";class Ye{constructor(e){this.name=je,this._loader=e,this.enabled=this._loader.isExtensionUsed(je)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((e,n)=>{this._loader._disableInstancedMesh++;const s=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return s;const r=new Array;let o=0;const a=t=>{if(null==n.attributes[t])return void r.push(Promise.resolve(null));const i=Ve.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,n.attributes[t]);if(r.push(this._loader._loadFloatAccessorAsync(`/accessors/${i.bufferView}`,i)),0===o)o=i.count;else if(o!==i.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return a("TRANSLATION"),a("ROTATION"),a("SCALE"),s.then((e=>Promise.all(r).then((([i,n,s])=>{const r=new Float32Array(16*o);M.jp.Vector3[0].copyFromFloats(0,0,0),M.jp.Quaternion[0].copyFromFloats(0,0,0,1),M.jp.Vector3[1].copyFromFloats(1,1,1);for(let e=0;e<o;++e)i&&M.P.FromArrayToRef(i,3*e,M.jp.Vector3[0]),n&&M._f.FromArrayToRef(n,4*e,M.jp.Quaternion[0]),s&&M.P.FromArrayToRef(s,3*e,M.jp.Vector3[1]),M.y3.ComposeToRef(M.jp.Vector3[1],M.jp.Quaternion[0],M.jp.Vector3[0],M.jp.Matrix[0]),M.jp.Matrix[0].copyToArray(r,16*e);for(const e of t._primitiveBabylonMeshes)e.thinInstanceSetBuffer("matrix",r,16,!0);return e}))))}))}}ke.RegisterExtension(je,(e=>new Ye(e)));var qe=i(9481);const Ke="EXT_meshopt_compression";class $e{constructor(e){this.name=Ke,this.enabled=e.isExtensionUsed(Ke),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return ke.LoadExtensionAsync(e,t,this.name,((i,n)=>{const s=t;if(s._meshOptData)return s._meshOptData;const r=Ve.Get(`${e}/buffer`,this._loader.gltf.buffers,n.buffer);return s._meshOptData=this._loader.loadBufferAsync(`/buffers/${r.index}`,r,n.byteOffset||0,n.byteLength).then((e=>qe.K.Default.decodeGltfBufferAsync(e,n.count,n.byteStride,n.mode,n.filter))),s._meshOptData}))}}ke.RegisterExtension(Ke,(e=>new $e(e)));const Qe="EXT_texture_webp";class Ze{constructor(e){this.name=Qe,this._loader=e,this.enabled=e.isExtensionUsed(Qe)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=null==t.sampler?ke.DefaultSampler:Ve.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=Ve.Get(`${n}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,r,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}ke.RegisterExtension(Qe,(e=>new Ze(e)));var Je=i(1500);const et="KHR_draco_mesh_compression";class tt{constructor(e){this.name=et,this._loader=e,this.enabled=Je.J.DecoderAvailable&&this._loader.isExtensionUsed(et)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{if(null!=t.mode){if(5!==t.mode&&4!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);if(5===t.mode)throw new Error(`${e}: Mode ${t.mode} is not currently supported`)}const r={},o={},a=(n,a)=>{const l=s.attributes[n];if(void 0===l||void 0===t.attributes[n])return;r[a]=l;const h=Ve.Get(`${e}/attributes/${n}`,this._loader.gltf.accessors,t.attributes[n]);if(h.normalized&&5126!==h.componentType){let e=1;switch(h.componentType){case 5120:e=127;break;case 5121:e=255;break;case 5122:e=32767;break;case 5123:e=65535}o[a]=e}i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(a)&&i._delayInfo.push(a)};a("POSITION",W.o.PositionKind),a("NORMAL",W.o.NormalKind),a("TANGENT",W.o.TangentKind),a("TEXCOORD_0",W.o.UVKind),a("TEXCOORD_1",W.o.UV2Kind),a("TEXCOORD_2",W.o.UV3Kind),a("TEXCOORD_3",W.o.UV4Kind),a("TEXCOORD_4",W.o.UV5Kind),a("TEXCOORD_5",W.o.UV6Kind),a("JOINTS_0",W.o.MatricesIndicesKind),a("WEIGHTS_0",W.o.MatricesWeightsKind),a("COLOR_0",W.o.ColorKind);const l=Ve.Get(n,this._loader.gltf.bufferViews,s.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||Je.J.Default).decodeMeshAsync(t,r,o).then((e=>{const t=new H.Z(i.name,this._loader.babylonScene);return e.applyToGeometry(t),t})).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}ke.RegisterExtension(et,(e=>new tt(e)));var it=i(9311);const nt="KHR_lights_punctual";class st{constructor(e){this.name=nt,this._loader=e,this.enabled=this._loader.isExtensionUsed(nt)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,Ve.Assign(this._lights)}}loadNodeAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadNodeAsync(e,t,(e=>{let t;const r=Ve.Get(n,this._lights,s.light),o=r.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,r.type){case"directional":t=new K.O(o,M.P.Backward(),this._loader.babylonScene);break;case"point":t=new $.c(o,M.P.Zero(),this._loader.babylonScene);break;case"spot":{const e=new Q.P(o,M.P.Zero(),M.P.Backward(),0,1,this._loader.babylonScene);e.angle=2*(r.spot&&r.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(r.spot&&r.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${n}: Invalid light type (${r.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,r._babylonLight=t,t.falloffType=it._.FALLOFF_GLTF,t.diffuse=r.color?I.Wo.FromArray(r.color):I.Wo.White(),t.intensity=null==r.intensity?1:r.intensity,t.range=null==r.range?Number.MAX_VALUE:r.range,t.parent=e,this._loader._babylonLights.push(t),ke.AddPointerMetadata(t,n),i(e)}))))}}ke.RegisterExtension(nt,(e=>new st(e)));const rt="KHR_materials_pbrSpecularGlossiness";class ot{constructor(e){this.name=rt,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(rt)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loadSpecularGlossinessPropertiesAsync(n,t,s,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i,n){if(!(n instanceof Me.Y))throw new Error(`${e}: Material type not supported`);const s=new Array;return n.metallic=null,n.roughness=null,i.diffuseFactor?(n.albedoColor=I.Wo.FromArray(i.diffuseFactor),n.alpha=i.diffuseFactor[3]):n.albedoColor=I.Wo.White(),n.reflectivityColor=i.specularFactor?I.Wo.FromArray(i.specularFactor):I.Wo.White(),n.microSurface=null==i.glossinessFactor?1:i.glossinessFactor,i.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,i.diffuseTexture,(e=>{e.name=`${n.name} (Diffuse)`,n.albedoTexture=e}))),i.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,i.specularGlossinessTexture,(e=>{e.name=`${n.name} (Specular Glossiness)`,n.reflectivityTexture=e,n.reflectivityTexture.hasAlpha=!0}))),n.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then((()=>{}))}}ke.RegisterExtension(rt,(e=>new ot(e)));const at="KHR_materials_unlit";class lt{constructor(e){this.name=at,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(at)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);const n=new Array;i.unlit=!0;const s=t.pbrMetallicRoughness;return s&&(s.baseColorFactor?(i.albedoColor=I.Wo.FromArray(s.baseColorFactor),i.alpha=s.baseColorFactor[3]):i.albedoColor=I.Wo.White(),s.baseColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,s.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e})))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then((()=>{}))}}ke.RegisterExtension(at,(e=>new lt(e)));const ht="KHR_materials_clearcoat";class ct{constructor(e){this.name=ht,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(ht)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadClearCoatPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);const n=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,null!=t.clearcoatFactor?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,(e=>{e.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=e}))),null!=t.clearcoatRoughnessFactor?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,(e=>{e.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=e})))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,(e=>{e.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=e}))),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,null!=t.clearcoatNormalTexture.scale&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(n).then((()=>{}))}}ke.RegisterExtension(ht,(e=>new ct(e)));const ut="KHR_materials_iridescence";class dt{constructor(e){this.name=ut,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(ut)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIridescencePropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){var n,s,r,o,a;if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);const l=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=null!==(n=t.iridescenceFactor)&&void 0!==n?n:0,i.iridescence.indexOfRefraction=null!==(r=null!==(s=t.iridescenceIor)&&void 0!==s?s:t.iridescenceIOR)&&void 0!==r?r:1.3,i.iridescence.minimumThickness=null!==(o=t.iridescenceThicknessMinimum)&&void 0!==o?o:100,i.iridescence.maximumThickness=null!==(a=t.iridescenceThicknessMaximum)&&void 0!==a?a:400,t.iridescenceTexture&&l.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&l.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(l).then((()=>{}))}}ke.RegisterExtension(ut,(e=>new dt(e)));const pt="KHR_materials_emissive_strength";class ft{constructor(e){this.name=pt,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(pt)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(n,s,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&i.emissiveColor.scaleToRef(t.emissiveStrength,i.emissiveColor)}}ke.RegisterExtension(pt,(e=>new ft(e)));const _t="KHR_materials_sheen";class mt{constructor(e){this.name=_t,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(_t)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadSheenPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);const n=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,null!=t.sheenColorFactor?i.sheen.color=I.Wo.FromArray(t.sheenColorFactor):i.sheen.color=I.Wo.Black(),t.sheenColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,(e=>{e.name=`${i.name} (Sheen Color)`,i.sheen.texture=e}))),void 0!==t.sheenRoughnessFactor?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,(e=>{e.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=e})))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(n).then((()=>{}))}}ke.RegisterExtension(_t,(e=>new mt(e)));const gt="KHR_materials_specular";class vt{constructor(e){this.name=gt,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(gt)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadSpecularPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);const n=new Array;return void 0!==t.specularFactor&&(i.metallicF0Factor=t.specularFactor),void 0!==t.specularColorFactor&&(i.metallicReflectanceColor=I.Wo.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,(e=>{e.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=e,i.useOnlyMetallicFromMetallicReflectanceTexture=!0})))),t.specularColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,(e=>{e.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=e}))),Promise.all(n).then((()=>{}))}}ke.RegisterExtension(gt,(e=>new vt(e)));const yt="KHR_materials_ior";class xt{constructor(e){this.name=yt,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(yt)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIorPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=xt._DEFAULT_IOR,Promise.resolve()}}xt._DEFAULT_IOR=1.5,ke.RegisterExtension(yt,(e=>new xt(e)));const bt="KHR_materials_variants";class Tt{constructor(e){this.name=bt,this._loader=e,this.enabled=this._loader.isExtensionUsed(bt)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return Tt.GetAvailableVariants(e)}static SelectVariant(e,t){const i=this._GetExtensionMetadata(e);if(!i)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${bt} extension`);const n=e=>{const t=i.variants[e];if(t)for(const e of t)e.mesh.material=e.material};if(t instanceof Array)for(const e of t)n(e);else n(t);i.lastSelected=t}selectVariant(e,t){return Tt.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${bt} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){return Tt.Reset(e)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${bt} extension`);return t.lastSelected}getLastSelectedVariant(e){return Tt.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){var t,i;return(null===(i=null===(t=null==e?void 0:e._internalMetadata)||void 0===t?void 0:t.gltf)||void 0===i?void 0:i[bt])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,i,n,s,r){return ke.LoadExtensionAsync(e,s,this.name,((o,a)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,n,s,(t=>{if(r(t),t instanceof Y.Kj){const i=ke._GetDrawMode(e,s.mode),n=this._loader.rootBabylonMesh,r=n?n._internalMetadata=n._internalMetadata||{}:{},h=r.gltf=r.gltf||{},c=h[bt]=h[bt]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e<a.mappings.length;++e){const s=a.mappings[e],r=Ve.Get(`${o}/mappings/${e}/material`,this._loader.gltf.materials,s.material);l.push(this._loader._loadMaterialAsync(`#/materials/${s.material}`,r,t,i,(e=>{for(let i=0;i<s.variants.length;++i){const r=s.variants[i],o=Ve.Get(`/extensions/${bt}/variants/${r}`,this._variants,r);c.variants[o.name]=c.variants[o.name]||[],c.variants[o.name].push({mesh:t,material:e}),t.onClonedObservable.add((e=>{const i=e;let s=null,r=i;do{if(r=r.parent,!r)return;s=Tt._GetExtensionMetadata(r)}while(null===s);if(n&&s===Tt._GetExtensionMetadata(n)){r._internalMetadata={};for(const e in n._internalMetadata)r._internalMetadata[e]=n._internalMetadata[e];r._internalMetadata.gltf=[];for(const e in n._internalMetadata.gltf)r._internalMetadata.gltf[e]=n._internalMetadata.gltf[e];r._internalMetadata.gltf[bt]={lastSelected:null,original:[],variants:{}};for(const e of s.original)r._internalMetadata.gltf[bt].original.push({mesh:e.mesh,material:e.material});for(const e in s.variants)if(Object.prototype.hasOwnProperty.call(s.variants,e)){r._internalMetadata.gltf[bt].variants[e]=[];for(const t of s.variants[e])r._internalMetadata.gltf[bt].variants[e].push({mesh:t.mesh,material:t.material})}s=r._internalMetadata.gltf[bt]}for(const e of s.original)e.mesh===t&&(e.mesh=i);for(const e of s.variants[o.name])e.mesh===t&&(e.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}ke.RegisterExtension(bt,(e=>new Tt(e)));var St=i(4246);class Et{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:ee.g.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...Et._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new r.y$,this._scene.onDisposeObservable.addOnce((()=>{this.dispose()})),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter((t=>this._options[t]!==e[t])).length)return;const t={...this._options,...e},i=this._options;this._options=t,t.renderSize===i.renderSize&&t.renderTargetTextureType===i.renderTargetTextureType&&t.generateMipmaps===i.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return!!e&&!!(e instanceof Me.Y&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),o.w1.SetImmediate((()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,-1===this._transparentMeshesCache.indexOf(e)&&this._transparentMeshesCache.push(e)):-1===this._opaqueMeshesCache.indexOf(e)&&this._opaqueMeshesCache.push(e)}))}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);-1!==t&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),-1!==t&&this._opaqueMeshesCache.splice(t,1)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),i=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof Me.Y&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),-1!==i?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e)):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===i&&this._opaqueMeshesCache.push(e)}_setupRenderTargets(){var e,t;let i,n;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new St._("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=null!==(t=null===(e=this._options.clearColor)||void 0===e?void 0:e.clone())&&void 0!==t?t:this._scene.clearColor.clone(),this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.onBeforeBindObservable.add((e=>{n=this._scene.environmentIntensity,this._scene.environmentIntensity=1,i=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?e.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(e.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0})),this._opaqueRenderTarget.onAfterUnbindObservable.add((()=>{this._scene.environmentIntensity=n,this._scene.imageProcessingConfiguration._applyByPostProcess=i})),this._transparentMeshesCache.forEach((e=>{this._shouldRenderAsTransmission(e.material)&&(e.material.refractionTexture=this._opaqueRenderTarget)}))}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const Ct="KHR_materials_transmission";class At{constructor(e){this.name=Ct,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ct),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadTransparentPropertiesAsync(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,n){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);const s=i;if(s.subSurface.isRefractionEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.useAlbedoToTintRefraction=!0,void 0===n.transmissionFactor)return s.subSurface.refractionIntensity=0,s.subSurface.isRefractionEnabled=!1,Promise.resolve();{s.subSurface.refractionIntensity=n.transmissionFactor;const e=s.getScene();s.subSurface.refractionIntensity&&!e._transmissionHelper&&new Et({},s.getScene())}return s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,n.transmissionTexture?(n.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,n.transmissionTexture,void 0).then((e=>{s.subSurface.refractionIntensityTexture=e,s.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}ke.RegisterExtension(Ct,(e=>new At(e)));const Pt="KHR_materials_translucency";class Rt{constructor(e){this.name=Pt,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(Pt),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadTranslucentPropertiesAsync(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,n){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);const s=i;return s.subSurface.isTranslucencyEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,s.subSurface.useAlbedoToTintTranslucency=!0,void 0===n.translucencyFactor?(s.subSurface.translucencyIntensity=0,s.subSurface.isTranslucencyEnabled=!1,Promise.resolve()):(s.subSurface.translucencyIntensity=n.translucencyFactor,n.translucencyTexture?(n.translucencyTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/translucencyTexture`,n.translucencyTexture).then((e=>{s.subSurface.translucencyIntensityTexture=e}))):Promise.resolve())}}ke.RegisterExtension(Pt,(e=>new Rt(e)));const Mt="KHR_materials_volume";class It{constructor(e){this.name=Mt,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(Mt),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadVolumePropertiesAsync(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,n){if(!(i instanceof Me.Y))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!n.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const s=void 0!==n.attenuationDistance?n.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=s,void 0!==n.attenuationColor&&3==n.attenuationColor.length&&i.subSurface.tintColor.copyFromFloats(n.attenuationColor[0],n.attenuationColor[1],n.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=n.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,n.thicknessTexture?(n.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,n.thicknessTexture).then((e=>{i.subSurface.thicknessTexture=e,i.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}ke.RegisterExtension(Mt,(e=>new It(e)));const Dt="KHR_mesh_quantization";class Ot{constructor(e){this.name=Dt,this.enabled=e.isExtensionUsed(Dt)}dispose(){}}ke.RegisterExtension(Dt,(e=>new Ot(e)));const wt="KHR_texture_basisu";class Nt{constructor(e){this.name=wt,this._loader=e,this.enabled=e.isExtensionUsed(wt)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=null==t.sampler?ke.DefaultSampler:Ve.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=Ve.Get(`${n}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,r,o,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}ke.RegisterExtension(wt,(e=>new Nt(e)));const Ft="KHR_texture_transform";class Lt{constructor(e){this.name=Ft,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ft)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof G.x))throw new Error(`${n}: Texture type not supported`);s.offset&&(e.uOffset=s.offset[0],e.vOffset=s.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,s.rotation&&(e.wAng=-s.rotation),s.scale&&(e.uScale=s.scale[0],e.vScale=s.scale[1]),null!=s.texCoord&&(e.coordinatesIndex=s.texCoord),i(e)}))))}}ke.RegisterExtension(Ft,(e=>new Lt(e)));const Bt="KHR_xmp_json_ld";class Ut{constructor(e){this.name=Bt,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(Bt)}dispose(){this._loader=null}onLoading(){var e,t,i;if(null===this._loader.rootBabylonMesh)return;const n=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_xmp_json_ld,s=null===(i=null===(t=this._loader.gltf.asset)||void 0===t?void 0:t.extensions)||void 0===i?void 0:i.KHR_xmp_json_ld;if(n&&s){const e=+s.packet;n.packets&&e<n.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=n.packets[e])}}}function Vt(e,t,i,n){return I.Wo.FromArray(t,i).scale(n)}function kt(e,t,i,n){return t[i]*n}function Gt(e,t,i,n){return-t[i]*n}function zt(e,t,i,n){return t[i+1]*n}function Wt(e,t,i,n){return t[i]*n*2}function Ht(e){return{scale:[new jt(w.f.ANIMATIONTYPE_FLOAT,`${e}.uScale`,kt,(()=>2)),new jt(w.f.ANIMATIONTYPE_FLOAT,`${e}.vScale`,zt,(()=>2))],offset:[new jt(w.f.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,kt,(()=>2)),new jt(w.f.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,zt,(()=>2))],rotation:[new jt(w.f.ANIMATIONTYPE_FLOAT,`${e}.wAng`,Gt,(()=>1))]}}ke.RegisterExtension(Bt,(e=>new Ut(e)));class Xt extends Fe{buildAnimations(e,t,i,n,s){s(e._babylonCamera,this._buildAnimation(t,i,n))}}class jt extends Fe{buildAnimations(e,t,i,n,s){for(const r in e._data)s(e._data[r].babylonMaterial,this._buildAnimation(t,i,n))}}class Yt extends Fe{buildAnimations(e,t,i,n,s){s(e._babylonLight,this._buildAnimation(t,i,n))}}const qt={__array__:{__target__:!0,...Be}},Kt={__array__:{__target__:!0,orthographic:{xmag:[new Xt(w.f.ANIMATIONTYPE_FLOAT,"orthoLeft",Gt,(()=>1)),new Xt(w.f.ANIMATIONTYPE_FLOAT,"orthoRight",zt,(()=>1))],ymag:[new Xt(w.f.ANIMATIONTYPE_FLOAT,"orthoBottom",Gt,(()=>1)),new Xt(w.f.ANIMATIONTYPE_FLOAT,"orthoTop",zt,(()=>1))],zfar:[new Xt(w.f.ANIMATIONTYPE_FLOAT,"maxZ",kt,(()=>1))],znear:[new Xt(w.f.ANIMATIONTYPE_FLOAT,"minZ",kt,(()=>1))]},perspective:{yfov:[new Xt(w.f.ANIMATIONTYPE_FLOAT,"fov",kt,(()=>1))],zfar:[new Xt(w.f.ANIMATIONTYPE_FLOAT,"maxZ",kt,(()=>1))],znear:[new Xt(w.f.ANIMATIONTYPE_FLOAT,"minZ",kt,(()=>1))]}}},$t={nodes:qt,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new jt(w.f.ANIMATIONTYPE_COLOR3,"albedoColor",Vt,(()=>4)),new jt(w.f.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,n){return t[i+3]*n}),(()=>4))],metallicFactor:[new jt(w.f.ANIMATIONTYPE_FLOAT,"metallic",kt,(()=>1))],roughnessFactor:[new jt(w.f.ANIMATIONTYPE_FLOAT,"roughness",kt,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:Ht("albedoTexture")}}},emissiveFactor:[new jt(w.f.ANIMATIONTYPE_COLOR3,"emissiveColor",Vt,(()=>3))],normalTexture:{scale:[new jt(w.f.ANIMATIONTYPE_FLOAT,"bumpTexture.level",kt,(()=>1))]},occlusionTexture:{strength:[new jt(w.f.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",kt,(()=>1))],extensions:{KHR_texture_transform:Ht("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:Ht("emissiveTexture")}},extensions:{KHR_materials_ior:{ior:[new jt(w.f.ANIMATIONTYPE_FLOAT,"indexOfRefraction",kt,(()=>1))]},KHR_materials_clearcoat:{clearcoatFactor:[new jt(w.f.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",kt,(()=>1))],clearcoatRoughnessFactor:[new jt(w.f.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",kt,(()=>1))]},KHR_materials_sheen:{sheenColorFactor:[new jt(w.f.ANIMATIONTYPE_COLOR3,"sheen.color",Vt,(()=>3))],sheenRoughnessFactor:[new jt(w.f.ANIMATIONTYPE_FLOAT,"sheen.roughness",kt,(()=>1))]},KHR_materials_specular:{specularFactor:[new jt(w.f.ANIMATIONTYPE_FLOAT,"metallicF0Factor",kt,(()=>1))],specularColorFactor:[new jt(w.f.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",Vt,(()=>3))]},KHR_materials_emissive_strength:{emissiveStrength:[new jt(w.f.ANIMATIONTYPE_FLOAT,"emissiveIntensity",kt,(()=>1))]},KHR_materials_transmission:{transmissionFactor:[new jt(w.f.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",kt,(()=>1))]},KHR_materials_volume:{attenuationColor:[new jt(w.f.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",Vt,(()=>3))],attenuationDistance:[new jt(w.f.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",kt,(()=>1))],thicknessFactor:[new jt(w.f.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",kt,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new jt(w.f.ANIMATIONTYPE_FLOAT,"iridescence.intensity",kt,(()=>1))],iridescenceIor:[new jt(w.f.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",kt,(()=>1))],iridescenceThicknessMinimum:[new jt(w.f.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",kt,(()=>1))],iridescenceThicknessMaximum:[new jt(w.f.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",kt,(()=>1))]}}}},cameras:Kt,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new Yt(w.f.ANIMATIONTYPE_COLOR3,"diffuse",Vt,(()=>3))],intensity:[new Yt(w.f.ANIMATIONTYPE_FLOAT,"intensity",kt,(()=>1))],range:[new Yt(w.f.ANIMATIONTYPE_FLOAT,"range",kt,(()=>1))],spot:{innerConeAngle:[new Yt(w.f.ANIMATIONTYPE_FLOAT,"innerAngle",Wt,(()=>1))],outerConeAngle:[new Yt(w.f.ANIMATIONTYPE_FLOAT,"angle",Wt,(()=>1))]}}}}}},Qt="KHR_animation_pointer";class Zt{constructor(e){this.name=Qt,this._loader=e}get enabled(){return this._loader.isExtensionUsed(Qt)}dispose(){this._loader=null}_loadAnimationChannelAsync(e,t,i,n,s){var r;const o=null===(r=n.target.extensions)||void 0===r?void 0:r.KHR_animation_pointer;if(!o)return null;"pointer"!==n.target.path&&h.Y.Warn(`${e}/target/path: Value (${n.target.path}) must be (pointer) when using the ${this.name} extension`),null!=n.target.node&&h.Y.Warn(`${e}/target/node: Value (${n.target.node}) must not be present when using the ${this.name} extension`);const a=`${e}/extensions/${this.name}`,l=o.pointer;if(!l)throw new Error(`${a}: Pointer is missing`);const c=this._parseAnimationPointer(`${a}/pointer`,l);return c?this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,n,c,s):(h.Y.Warn(`${a}/pointer: Invalid pointer (${l}) skipped`),null)}_parseAnimationPointer(e,t){if(!t.startsWith("/"))return h.Y.Warn(`${e}: Value (${t}) must start with a slash`),null;const i=t.split("/");i.shift();let n,s=$t,r=this._loader.gltf;for(const e of i){if(s.__array__)s=s.__array__;else if(s=s[e],!s)return null;r=r&&r[e],s.__target__&&(n=r)}return n&&Array.isArray(s)?{target:n,properties:s}:null}}ke.RegisterExtension(Qt,(e=>new Zt(e)));var Jt=i(8117),ei=i(3642),ti=i(710);const ii="MSFT_audio_emitter";class ni{constructor(e){this.name=ii,this._loader=e,this.enabled=this._loader.isExtensionUsed(ii)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,Ve.Assign(this._clips),Ve.Assign(this._emitters)}}loadSceneAsync(e,t){return ke.LoadExtensionAsync(e,t,this.name,((i,n)=>{const s=new Array;s.push(this._loader.loadSceneAsync(e,t));for(const e of n.emitters){const t=Ve.Get(`${i}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);s.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(s).then((()=>{}))}))}loadNodeAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((e,n)=>{const s=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of n.emitters){const n=Ve.Get(`${e}/emitters`,this._emitters,i);s.push(this._loadEmitterAsync(`${e}/emitters/${n.index}`,n).then((()=>{for(const e of n._babylonSounds)e.attachToMesh(t),null==n.innerAngle&&null==n.outerAngle||(e.setLocalDirectionToMesh(M.P.Forward()),e.setDirectionalCone(2*o.w1.ToDegrees(null==n.innerAngle?Math.PI:n.innerAngle),2*o.w1.ToDegrees(null==n.outerAngle?Math.PI:n.outerAngle),0))})))}i(t)})).then((e=>Promise.all(s).then((()=>e))))}))}loadAnimationAsync(e,t){return ke.LoadExtensionAsync(e,t,this.name,((i,n)=>this._loader.loadAnimationAsync(e,t).then((s=>{const r=new Array;Ve.Assign(n.events);for(const o of n.events)r.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,s));return Promise.all(r).then((()=>s))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const n=Ve.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${n.index}`,n)}return t._objectURL=i.then((e=>URL.createObjectURL(new Blob([e],{type:t.mimeType})))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const e=new Array,i=t.name||`emitter${t.index}`,n={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume};for(let s=0;s<t.clips.length;s++){const r=`/extensions/${this.name}/clips`,o=Ve.Get(r,this._clips,t.clips[s].clip);e.push(this._loadClipAsync(`${r}/${t.clips[s].clip}`,o).then((e=>{const r=t._babylonSounds[s]=new ei.$(i,e,this._loader.babylonScene,null,n);r.refDistance=t.refDistance||1,r.maxDistance=t.maxDistance||256,r.rolloffFactor=t.rolloffFactor||1,r.distanceModel=t.distanceModel||"exponential"})))}const s=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new ti.s(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*o.w1.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*o.w1.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:s}}return t._babylonData.loaded}_getEventAction(e,t,i,n,s){switch(i){case"play":return e=>{const i=(s||0)+(e-n);t.play(i)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,n,s){if(0==s.targetedAnimations.length)return Promise.resolve();const r=s.targetedAnimations[0],o=n.emitter,a=Ve.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,a).then((()=>{const t=a._babylonData.sound;if(t){const i=new Jt.O(n.time,this._getEventAction(e,t,n.action,n.time,n.startOffset));r.animation.addEvent(i),s.onAnimationGroupEndObservable.add((()=>{t.stop()})),s.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}ke.RegisterExtension(ii,(e=>new ni(e)));const si="MSFT_lod";class ri{constructor(e){this.name=si,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new r.y$,this.onMaterialLODsLoadedObservable=new r.y$,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(si)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e<this._nodePromiseLODs.length;e++){const t=Promise.all(this._nodePromiseLODs[e]).then((()=>{0!==e&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}for(let e=0;e<this._materialPromiseLODs.length;e++){const t=Promise.all(this._materialPromiseLODs[e]).then((()=>{0!==e&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return ke.LoadExtensionAsync(e,t,this.name,((e,n)=>{let s;const r=this._getLODs(e,t,this._loader.gltf.nodes,n.ids);this._loader.logOpen(`${e}`);for(let e=0;e<r.length;e++){const t=r[e];0!==e&&(this._nodeIndexLOD=e,this._nodeSignalLODs[e]=this._nodeSignalLODs[e]||new Ae.B);const n=e=>{i(e),e.setEnabled(!1)},o=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,n).then((t=>{if(0!==e){const t=r[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t}));this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?s=o:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(o))}return this._loader.logClose(),s}))}_loadMaterialAsync(e,t,i,n,s){return this._nodeIndexLOD?null:ke.LoadExtensionAsync(e,t,this.name,((e,r)=>{let o;const a=this._getLODs(e,t,this._loader.gltf.materials,r.ids);this._loader.logOpen(`${e}`);for(let e=0;e<a.length;e++){const t=a[e];0!==e&&(this._materialIndexLOD=e);const r=this._loader._loadMaterialAsync(`/materials/${t.index}`,t,i,n,(t=>{0===e&&s(t)})).then((t=>{if(0!==e){s(t);const i=a[e-1]._data;i[n]&&(this._disposeMaterials([i[n].babylonMaterial]),delete i[n])}return t}));this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?o=r:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(r))}return this._loader.logClose(),o}))}_loadUriAsync(e,t,i){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const n=this._nodeIndexLOD-1;return this._nodeSignalLODs[n]=this._nodeSignalLODs[n]||new Ae.B,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const n=this._materialIndexLOD-1;return this._materialSignalLODs[n]=this._materialSignalLODs[n]||new Ae.B,this._materialSignalLODs[n].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}return null}loadBufferAsync(e,t,i,n){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const t=(e,t)=>{const s=i,r=s+n-1;let o=e[t];return o?(o.start=Math.min(o.start,s),o.end=Math.max(o.end,r)):(o={start:s,end:r,loaded:new Ae.B},e[t]=o),o.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-o.start,n)))};return this._loader.log("deferred"),null!==this._nodeIndexLOD?t(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?t(this._materialBufferLODs,this._materialIndexLOD):t(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const i=e[t];i&&(this._loader.log(`Loading buffer range [${i.start}-${i.end}]`),this._loader.bin.readAsync(i.start,i.end-i.start+1).then((e=>{i.loaded.resolve(e)}),(e=>{i.loaded.reject(e)})))}_getLODs(e,t,i,n){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const s=new Array;for(let t=n.length-1;t>=0;t--)if(s.push(Ve.Get(`${e}/ids/${n[t]}`,i,n[t])),s.length===this.maxLODsToLoad)return s;return s.push(t),s}_disposeTransformNode(e){const t=new Array,i=e.material;i&&t.push(i);for(const i of e.getChildMeshes())i.material&&t.push(i.material);e.dispose();const n=t.filter((e=>this._loader.babylonScene.meshes.every((t=>t.material!=e))));this._disposeMaterials(n)}_disposeMaterials(e){const t={};for(const i of e){for(const e of i.getActiveTextures())t[e.uniqueId]=e;i.dispose()}for(const e in t)for(const i of this._loader.babylonScene.materials)i.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}}ke.RegisterExtension(si,(e=>new ri(e)));const oi="MSFT_minecraftMesh";class ai{constructor(e){this.name=oi,this._loader=e,this.enabled=this._loader.isExtensionUsed(oi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtraAsync(e,t,this.name,((n,s)=>{if(s){if(!(i instanceof Me.Y))throw new Error(`${n}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,s}return null}))}}ke.RegisterExtension(oi,(e=>new ai(e)));const li="MSFT_sRGBFactors";class hi{constructor(e){this.name=li,this._loader=e,this.enabled=this._loader.isExtensionUsed(li)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return ke.LoadExtraAsync(e,t,this.name,((n,s)=>{if(s){if(!(i instanceof Me.Y))throw new Error(`${n}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,i),r=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,r),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,r),s}return null}))}}ke.RegisterExtension(li,(e=>new hi(e)));const ci="ExtrasAsMetadata";class ui{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{};(i.gltf=i.gltf||{}).extras=t.extras}}constructor(e){this.name=ci,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}createMaterial(e,t,i){const n=this._loader.createMaterial(e,t,i);return this._assignExtras(n,t),n}}ke.RegisterExtension(ci,(e=>new ui(e)));class di{constructor(){this.materials=[]}parseMTL(e,t,i,n){if(t instanceof ArrayBuffer)return;const s=t.split("\n"),r=/\s+/;let o,a=null;for(let t=0;t<s.length;t++){const l=s[t].trim();if(0===l.length||"#"===l.charAt(0))continue;const h=l.indexOf(" ");let c=h>=0?l.substring(0,h):l;c=c.toLowerCase();const u=h>=0?l.substring(h+1).trim():"";if("newmtl"===c)a&&this.materials.push(a),e._blockEntityCollection=!!n,a=new V.K(u,e),a._parentContainer=n,e._blockEntityCollection=!1;else if("kd"===c&&a)o=u.split(r,3).map(parseFloat),a.diffuseColor=I.Wo.FromArray(o);else if("ka"===c&&a)o=u.split(r,3).map(parseFloat),a.ambientColor=I.Wo.FromArray(o);else if("ks"===c&&a)o=u.split(r,3).map(parseFloat),a.specularColor=I.Wo.FromArray(o);else if("ke"===c&&a)o=u.split(r,3).map(parseFloat),a.emissiveColor=I.Wo.FromArray(o);else if("ns"===c&&a)a.specularPower=parseFloat(u);else if("d"===c&&a)a.alpha=parseFloat(u);else if("map_ka"===c&&a)a.ambientTexture=di._GetTexture(i,u,e);else if("map_kd"===c&&a)a.diffuseTexture=di._GetTexture(i,u,e);else if("map_ks"===c&&a)a.specularTexture=di._GetTexture(i,u,e);else if("map_ns"===c);else if("map_bump"===c&&a){const t=u.split(r),n=t.indexOf("-bm");let s=null;n>=0&&(s=t[n+1],t.splice(n,2)),a.bumpTexture=di._GetTexture(i,t.join(" "),e),a.bumpTexture&&null!==s&&(a.bumpTexture.level=parseFloat(s))}else"map_d"===c&&a&&(a.opacityTexture=di._GetTexture(i,u,e))}a&&this.materials.push(a)}static _GetTexture(e,t,i){if(!t)return null;let n=e;if("file:"===e){let e=t.lastIndexOf("\\");-1===e&&(e=t.lastIndexOf("/")),n+=e>-1?t.substr(e+1):t}else n+=t;return new G.x(n,i,!1,di.INVERT_TEXTURE_Y)}}di.INVERT_TEXTURE_Y=!0;class pi{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new I.HE(.5,.5,.5,1),this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const i=e[t[0]].normals.indexOf(t[1]);return-1===i?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const i=e[t[0]].normals.indexOf(t[1]);return 1!=i&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,n,s,r,o){let a;a=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e,i,t]):this._isInArray(this._tuplePosNorm,[e,i]),-1===a?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(n),this._wrappedUvsForBabylon.push(s),this._wrappedNormalsForBabylon.push(r),void 0!==o&&this._wrappedColorsForBabylon.push(o),this._tuplePosNorm[e].normals.push(i),this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e].uv.push(t)):this._indicesForBabylon.push(a)}_unwrapData(){for(let e=0;e<this._wrappedPositionForBabylon.length;e++)this._unwrappedPositionsForBabylon.push(this._wrappedPositionForBabylon[e].x,this._wrappedPositionForBabylon[e].y,this._wrappedPositionForBabylon[e].z),this._unwrappedNormalsForBabylon.push(this._wrappedNormalsForBabylon[e].x,this._wrappedNormalsForBabylon[e].y,this._wrappedNormalsForBabylon[e].z),this._unwrappedUVForBabylon.push(this._wrappedUvsForBabylon[e].x,this._wrappedUvsForBabylon[e].y),this._loadingOptions.importVertexColors&&this._unwrappedColorsForBabylon.push(this._wrappedColorsForBabylon[e].r,this._wrappedColorsForBabylon[e].g,this._wrappedColorsForBabylon[e].b,this._wrappedColorsForBabylon[e].a);this._wrappedPositionForBabylon.length=0,this._wrappedNormalsForBabylon.length=0,this._wrappedUvsForBabylon.length=0,this._wrappedColorsForBabylon.length=0,this._tuplePosNorm.length=0,this._curPositionInIndices=0}_getTriangles(e,t){for(let i=t;i<e.length-1;i++)this._triangles.push(e[0],e[i],e[i+1])}_setDataForCurrentFaceWithPattern1(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=parseInt(this._triangles[e])-1;this._setData(t,0,0,this._positions[t],M.FM.Zero(),M.P.Up(),this._loadingOptions.importVertexColors?this._colors[t]:void 0)}this._triangles.length=0}_setDataForCurrentFaceWithPattern2(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),i=parseInt(t[0])-1,n=parseInt(t[1])-1;this._setData(i,n,0,this._positions[i],this._uvs[n],M.P.Up(),this._loadingOptions.importVertexColors?this._colors[i]:void 0)}this._triangles.length=0}_setDataForCurrentFaceWithPattern3(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),i=parseInt(t[0])-1,n=parseInt(t[1])-1,s=parseInt(t[2])-1;this._setData(i,n,s,this._positions[i],this._uvs[n],this._normals[s])}this._triangles.length=0}_setDataForCurrentFaceWithPattern4(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("//"),i=parseInt(t[0])-1,n=parseInt(t[1])-1;this._setData(i,1,n,this._positions[i],M.FM.Zero(),this._normals[n],this._loadingOptions.importVertexColors?this._colors[i]:void 0)}this._triangles.length=0}_setDataForCurrentFaceWithPattern5(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),i=this._positions.length+parseInt(t[0]),n=this._uvs.length+parseInt(t[1]),s=this._normals.length+parseInt(t[2]);this._setData(i,n,s,this._positions[i],this._uvs[n],this._normals[s],this._loadingOptions.importVertexColors?this._colors[i]:void 0)}this._triangles.length=0}_addPreviousObjMesh(){this._meshesFromObj.length>0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice(),this._handledMesh.uvs=this._unwrappedUVForBabylon.slice(),this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0)}_optimizeNormals(e){const t=e.getVerticesData(W.o.PositionKind),i=e.getVerticesData(W.o.NormalKind),n={};if(!t||!i)return;for(let e=0;e<t.length/3;e++){const i=t[3*e+0]+"_"+t[3*e+1]+"_"+t[3*e+2];let s=n[i];s||(s=[],n[i]=s),s.push(e)}const s=new M.P;for(const e in n){const t=n[e];if(t.length<2)continue;const r=t[0];for(let e=1;e<t.length;++e){const n=t[e];i[3*r+0]+=i[3*n+0],i[3*r+1]+=i[3*n+1],i[3*r+2]+=i[3*n+2]}s.copyFromFloats(i[3*r+0],i[3*r+1],i[3*r+2]),s.normalize();for(let e=0;e<t.length;++e){const n=t[e];i[3*n+0]=s.x,i[3*n+1]=s.y,i[3*n+2]=s.z}}e.setVerticesData(W.o.NormalKind,i)}parse(e,t,i,n,s){var r;const o=t.split("\n");for(let e=0;e<o.length;e++){const t=o[e].trim().replace(/\s\s/g," ");let i;if(0!==t.length&&"#"!==t.charAt(0))if(pi.VertexPattern.test(t)){if(i=t.match(/[^ ]+/g),this._positions.push(new M.P(parseFloat(i[1]),parseFloat(i[2]),parseFloat(i[3]))),this._loadingOptions.importVertexColors)if(i.length>=7){const e=parseFloat(i[4]),t=parseFloat(i[5]),n=parseFloat(i[6]);this._colors.push(new I.HE(e>1?e/255:e,t>1?t/255:t,n>1?n/255:n,7===i.length||void 0===i[7]?1:parseFloat(i[7])))}else this._colors.push(this._grayColor)}else if(null!==(i=pi.NormalPattern.exec(t)))this._normals.push(new M.P(parseFloat(i[1]),parseFloat(i[2]),parseFloat(i[3])));else if(null!==(i=pi.UVPattern.exec(t)))this._uvs.push(new M.FM(parseFloat(i[1])*this._loadingOptions.UVScaling.x,parseFloat(i[2])*this._loadingOptions.UVScaling.y));else if(null!==(i=pi.FacePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),1);else if(null!==(i=pi.FacePattern4.exec(t)))this._setDataForCurrentFaceWithPattern4(i[1].trim().split(" "),1);else if(null!==(i=pi.FacePattern5.exec(t)))this._setDataForCurrentFaceWithPattern5(i[1].trim().split(" "),1);else if(null!==(i=pi.FacePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),1);else if(null!==(i=pi.FacePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),1);else if(pi.GroupDescriptor.test(t)||pi.ObjectDescriptor.test(t)){const e={name:t.substring(2).trim(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:this._materialNameFromObj};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(pi.UseMtlDescriptor.test(t)){if(this._materialNameFromObj=t.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const e={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:this._materialNameFromObj};this._increment++,this._meshesFromObj.push(e),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else pi.MtlLibGroupDescriptor.test(t)?s(t.substring(7).trim()):pi.SmoothDescriptor.test(t)||console.log("Unhandled expression at line : "+t)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._handledMesh.normals=this._unwrappedNormalsForBabylon,this._handledMesh.uvs=this._unwrappedUVForBabylon,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){let e=null;if(this._indicesForBabylon.length)this._indicesForBabylon.reverse(),this._unwrapData();else{for(const e of this._positions)this._unwrappedPositionsForBabylon.push(e.x,e.y,e.z);if(this._normals.length)for(const e of this._normals)this._unwrappedNormalsForBabylon.push(e.x,e.y,e.z);if(this._uvs.length)for(const e of this._uvs)this._unwrappedUVForBabylon.push(e.x,e.y);if(this._colors.length)for(const e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);this._materialNameFromObj||(e=new V.K(H.Z.RandomId(),i),e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=I.Wo.White()))}this._meshesFromObj.push({name:H.Z.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:e})}for(let t=0;t<this._meshesFromObj.length;t++){if(e&&this._meshesFromObj[t].name)if(e instanceof Array){if(-1===e.indexOf(this._meshesFromObj[t].name))continue}else if(this._meshesFromObj[t].name!==e)continue;this._handledMesh=this._meshesFromObj[t],i._blockEntityCollection=!!n;const s=new Y.Kj(this._meshesFromObj[t].name,i);if(s._parentContainer=n,i._blockEntityCollection=!1,this._materialToUse.push(this._meshesFromObj[t].materialName),0===(null===(r=this._handledMesh.positions)||void 0===r?void 0:r.length)){this._babylonMeshesArray.push(s);continue}const o=new z.x;if(o.uvs=this._handledMesh.uvs,o.indices=this._handledMesh.indices,o.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const e=new Array;z.x.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),o.normals=e}else o.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(o.colors=this._handledMesh.colors),o.applyToMesh(s),this._loadingOptions.invertY&&(s.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(s),this._babylonMeshesArray.push(s),this._handledMesh.directMaterial&&(s.material=this._handledMesh.directMaterial)}}}pi.ObjectDescriptor=/^o/,pi.GroupDescriptor=/^g/,pi.MtlLibGroupDescriptor=/^mtllib /,pi.UseMtlDescriptor=/^usemtl /,pi.SmoothDescriptor=/^s /,pi.VertexPattern=/v(\s+[\d|.|+|\-|e|E]+){3,7}/,pi.NormalPattern=/vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,pi.UVPattern=/vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,pi.FacePattern1=/f\s+(([\d]{1,}[\s]?){3,})+/,pi.FacePattern2=/f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,pi.FacePattern3=/f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,pi.FacePattern4=/f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,pi.FacePattern5=/f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;class fi{static get INVERT_TEXTURE_Y(){return di.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){di.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||fi._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:fi.COMPUTE_NORMALS,optimizeNormals:fi.OPTIMIZE_NORMALS,importVertexColors:fi.IMPORT_VERTEX_COLORS,invertY:fi.INVERT_Y,invertTextureY:fi.INVERT_TEXTURE_Y,UVScaling:fi.UV_SCALING,materialLoadingFailsSilently:fi.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:fi.OPTIMIZE_WITH_UV,skipMaterials:fi.SKIP_MATERIALS}}_loadMTL(e,t,i,n){const s=t+e;o.w1.LoadFile(s,i,void 0,void 0,!1,((e,t)=>{n(s,t)}))}createPlugin(){return new fi(fi._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,n){return this._parseSolid(e,t,i,n).then((e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[]})))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then((()=>{}))}loadAssetContainerAsync(e,t,i){const n=new l.TJ(e);return this._assetContainer=n,this.importMeshAsync(null,e,t,i).then((e=>(e.meshes.forEach((e=>n.meshes.push(e))),e.meshes.forEach((e=>{const t=e.material;t&&-1==n.materials.indexOf(t)&&(n.materials.push(t),t.getActiveTextures().forEach((e=>{-1==n.textures.indexOf(e)&&n.textures.push(e)})))})),this._assetContainer=null,n))).catch((e=>{throw this._assetContainer=null,e}))}_parseSolid(e,t,i,n){let s="";const r=new di,a=new Array,l=[];new pi(a,l,this._loadingOptions).parse(e,i,t,this._assetContainer,(e=>{s=e}));const h=[];return""===s||this._loadingOptions.skipMaterials||h.push(new Promise(((e,i)=>{this._loadMTL(s,n,(h=>{try{r.parseMTL(t,h,n,this._assetContainer);for(let e=0;e<r.materials.length;e++){let t=0;const i=[];let n;for(;(n=a.indexOf(r.materials[e].name,t))>-1;)i.push(n),t=n+1;if(-1===n&&0===i.length)r.materials[e].dispose();else for(let t=0;t<i.length;t++){const n=l[i[t]],s=r.materials[e];n.material=s,n.getTotalIndices()||(s.pointsCloud=!0)}}e()}catch(t){o.w1.Warn(`Error processing MTL file: '${s}'`),this._loadingOptions.materialLoadingFailsSilently?e():i(t)}}),((t,n)=>{o.w1.Warn(`Error downloading MTL file: '${s}'`),this._loadingOptions.materialLoadingFailsSilently?e():i(n)}))}))),Promise.all(h).then((()=>l))}}fi.OPTIMIZE_WITH_UV=!0,fi.INVERT_Y=!1,fi.IMPORT_VERTEX_COLORS=!1,fi.COMPUTE_NORMALS=!1,fi.OPTIMIZE_NORMALS=!1,fi.UV_SCALING=new M.FM(1,1),fi.SKIP_MATERIALS=!1,fi.MATERIAL_LOADING_FAILS_SILENTLY=!0,a.n&&a.n.RegisterPlugin(new fi);class _i{constructor(){this.solidPattern=/solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,this.normalPattern=/normal[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.vertexPattern=/vertex[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.name="stl",this.extensions={".stl":{isBinary:!0}}}importMesh(e,t,i,n,s){let r;if("string"!=typeof i){if(this._isBinary(i)){const e=new Y.Kj("stlmesh",t);return this._parseBinary(e,i),s&&s.push(e),!0}const e=new Uint8Array(i);let n="";for(let t=0;t<i.byteLength;t++)n+=String.fromCharCode(e[t]);i=n}for(;r=this.solidPattern.exec(i);){let i=r[1];const n=r[3];if(n&&i!=n)return o.w1.Error("Error in STL, solid name != endsolid name"),!1;if(e&&i)if(e instanceof Array){if(!e.indexOf(i))continue}else if(i!==e)continue;i=i||"stlmesh";const a=new Y.Kj(i,t);this._parseASCII(a,r[2]),s&&s.push(a)}return!0}load(e,t,i){return this.importMesh(null,e,t,i,null)}loadAssetContainer(e,t,i){const n=new l.TJ(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,i,n.meshes),e._blockEntityCollection=!1,n}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const i=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==i[e])return!0;return!1}_parseBinary(e,t){const i=new DataView(t),n=i.getUint32(80,!0);let s=0;const r=new Float32Array(3*n*3),o=new Float32Array(3*n*3),a=new Uint32Array(3*n);let l=0;for(let e=0;e<n;e++){const t=84+50*e,n=i.getFloat32(t,!0),h=i.getFloat32(t+4,!0),c=i.getFloat32(t+8,!0);for(let e=1;e<=3;e++){const a=t+12*e;r[s]=i.getFloat32(a,!0),o[s]=n,_i.DO_NOT_ALTER_FILE_COORDINATES?(r[s+1]=i.getFloat32(a+4,!0),r[s+2]=i.getFloat32(a+8,!0),o[s+1]=h,o[s+2]=c):(r[s+2]=i.getFloat32(a+4,!0),r[s+1]=i.getFloat32(a+8,!0),o[s+2]=h,o[s+1]=c),s+=3}_i.DO_NOT_ALTER_FILE_COORDINATES?(a[l]=l,a[l+1]=l+2,a[l+2]=l+1,l+=3):(a[l]=l++,a[l]=l++,a[l]=l++)}e.setVerticesData(W.o.PositionKind,r),e.setVerticesData(W.o.NormalKind,o),e.setIndices(a),e.computeWorldMatrix(!0)}_parseASCII(e,t){const i=[],n=[],s=[];let r,o=0;for(;r=this.facetsPattern.exec(t);){const e=r[1],t=this.normalPattern.exec(e);if(this.normalPattern.lastIndex=0,!t)continue;const a=[Number(t[1]),Number(t[5]),Number(t[3])];let l;for(;l=this.vertexPattern.exec(e);)_i.DO_NOT_ALTER_FILE_COORDINATES?(i.push(Number(l[1]),Number(l[3]),Number(l[5])),n.push(a[0],a[2],a[1])):(i.push(Number(l[1]),Number(l[5]),Number(l[3])),n.push(a[0],a[1],a[2]));_i.DO_NOT_ALTER_FILE_COORDINATES?(s.push(o,o+2,o+1),o+=3):s.push(o++,o++,o++),this.vertexPattern.lastIndex=0}this.facetsPattern.lastIndex=0,e.setVerticesData(W.o.PositionKind,i),e.setVerticesData(W.o.NormalKind,n),e.setIndices(s),e.computeWorldMatrix(!0)}}_i.DO_NOT_ALTER_FILE_COORDINATES=!1,a.n&&a.n.RegisterPlugin(new _i)},3849:(e,t,i)=>{i.r(t),i.d(t,{CellMaterial:()=>g,CustomMaterial:()=>T,CustomShaderStructure:()=>x,FireMaterial:()=>I,FurMaterial:()=>N,GradientMaterial:()=>L,GridMaterial:()=>U,LavaMaterial:()=>k,MixMaterial:()=>z,NormalMaterial:()=>H,PBRCustomMaterial:()=>A,ShaderAlebdoParts:()=>C,ShaderSpecialParts:()=>b,ShadowOnlyMaterial:()=>j,SimpleMaterial:()=>q,SkyMaterial:()=>$,TerrainMaterial:()=>Z,TriPlanarMaterial:()=>ee,WaterMaterial:()=>le});var n=i(9472),s=i(3956),r=i(4649),o=i(1917),a=i(5346),l=i(580),h=i(85),c=i(708),u=i(1057),d=i(2208),p=i(8104);i(1423),i(2557),i(3756),i(6568),i(3996),i(6390),i(9519),i(5791),i(783),i(9490),i(6043),i(689);p.v.ShadersStore.cellPixelShader="precision highp float;\nuniform vec4 vEyePosition;\nuniform vec4 vDiffuseColor;\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<helperFunctions>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow)\n{\ndiffuseBase=info.diffuse*shadow;\n#ifdef CELLBASIC\nfloat level=1.0;\nif (info.ndl<0.5)\nlevel=0.5;\ndiffuseBase.rgb*vec3(level,level,level);\n#else\nfloat ToonThresholds[4];\nToonThresholds[0]=0.95;\nToonThresholds[1]=0.5;\nToonThresholds[2]=0.2;\nToonThresholds[3]=0.03;\nfloat ToonBrightnessLevels[5];\nToonBrightnessLevels[0]=1.0;\nToonBrightnessLevels[1]=0.8;\nToonBrightnessLevels[2]=0.6;\nToonBrightnessLevels[3]=0.35;\nToonBrightnessLevels[4]=0.2;\nif (info.ndl>ToonThresholds[0])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[0];\n}\nelse if (info.ndl>ToonThresholds[1])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[1];\n}\nelse if (info.ndl>ToonThresholds[2])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[2];\n}\nelse if (info.ndl>ToonThresholds[3])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[3];\n}\nelse\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[4];\n}\n#endif\nreturn max(diffuseBase,vec3(0.2));\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nlightingInfo info;\nvec3 diffuseBase=vec3(0.,0.,0.);\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include<lightFragment>[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}",i(7520),i(493),i(1063),i(6343),i(9042),i(6883),i(6655),i(3206),i(5215),i(962),i(1101),i(9025);p.v.ShadersStore.cellVertexShader="precision highp float;\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";var f=i(1434),_=i(99);class m extends o.H{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NDOTL=!0,this.CUSTOMUSERLIGHTING=!0,this.CELLBASIC=!0,this.DEPTHPREPASS=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class g extends l.a{constructor(e,t){super(e,t),this.diffuseColor=new r.Wo(1,1,1),this._computeHighLevel=!1,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new m);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,s.texturesEnabled&&this._diffuseTexture&&h.k.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(n.CELLBASIC=!this.computeHighLevel,a.G.PrepareDefinesForMisc(e,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=a.G.PrepareDefinesForLights(s,e,n,!1,this._maxSimultaneousLights,this._disableLighting),a.G.PrepareDefinesForFrameBoundValues(s,r,this,n,!!i),a.G.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),s.resetCachedMaterial();const i=new f.L;n.FOG&&i.addFallback(1,"FOG"),a.G.HandleFallbacksForShadows(n,i,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),n.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[c.o.PositionKind];n.NORMAL&&o.push(c.o.NormalKind),n.UV1&&o.push(c.o.UVKind),n.UV2&&o.push(c.o.UV2Kind),n.VERTEXCOLOR&&o.push(c.o.ColorKind),a.G.PrepareAttributesForBones(o,e,n,i),a.G.PrepareAttributesForInstances(o,n);const l="cell",h=n.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix"],d=["diffuseSampler"],p=new Array;(0,_.qx)(u),a.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},r),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,r)&&(this._diffuseTexture&&h.k.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),(0,_.an)(this._activeEffect,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),n.bindEyePosition(r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),n.lightsEnabled&&!this.disableLighting&&a.G.BindLights(n,t,this._activeEffect,s,this._maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}getClassName(){return"CellMaterial"}clone(e){return s.p4.Clone((()=>new g(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.CellMaterial",e}static Parse(e,t,i){return s.p4.Parse((()=>new g(e.name,t)),e,t,i)}}(0,n.gn)([(0,s.oU)("diffuseTexture")],g.prototype,"_diffuseTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],g.prototype,"diffuseTexture",void 0),(0,n.gn)([(0,s.n9)("diffuse")],g.prototype,"diffuseColor",void 0),(0,n.gn)([(0,s.qC)("computeHighLevel")],g.prototype,"_computeHighLevel",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],g.prototype,"computeHighLevel",void 0),(0,n.gn)([(0,s.qC)("disableLighting")],g.prototype,"_disableLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],g.prototype,"disableLighting",void 0),(0,n.gn)([(0,s.qC)("maxSimultaneousLights")],g.prototype,"_maxSimultaneousLights",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],g.prototype,"maxSimultaneousLights",void 0),(0,d.H)("BABYLON.CellMaterial",g);var v=i(1979),y=i(252);class x{constructor(){}}class b{constructor(){}}class T extends y.K{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?t.setVector4(i[1],this._newUniformInstances[e]):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e<this._newUniforms.length;e++)-1==this._customUniform[e].indexOf("sampler")&&t.push(this._newUniforms[e].replace(/\[\d*\]/g,""));if("sampler"==e&&this._newUniforms)for(let e=0;e<this._newUniforms.length;e++)-1!=this._customUniform[e].indexOf("sampler")&&t.push(this._newUniforms[e].replace(/\[\d*\]/g,""));return t}Builder(e,t,i,n,s,r){if(r&&this._customAttributes&&this._customAttributes.length>0&&r.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",n),this._isCreatedShader)return this._createdShaderName;this._isCreatedShader=!1,T.ShaderIndexer++;const o="custom_"+T.ShaderIndexer,a=this._afterBind.bind(this);return this._afterBind=(e,t)=>{if(t){this.AttachAfterBind(e,t);try{a(e,t)}catch(t){}}},v.Q.ShadersStore[o+"VertexShader"]=this.VertexShader.replace("#define CUSTOM_VERTEX_BEGIN",this.CustomParts.Vertex_Begin?this.CustomParts.Vertex_Begin:"").replace("#define CUSTOM_VERTEX_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Vertex_Definitions?this.CustomParts.Vertex_Definitions:"")).replace("#define CUSTOM_VERTEX_MAIN_BEGIN",this.CustomParts.Vertex_MainBegin?this.CustomParts.Vertex_MainBegin:"").replace("#define CUSTOM_VERTEX_UPDATE_POSITION",this.CustomParts.Vertex_Before_PositionUpdated?this.CustomParts.Vertex_Before_PositionUpdated:"").replace("#define CUSTOM_VERTEX_UPDATE_NORMAL",this.CustomParts.Vertex_Before_NormalUpdated?this.CustomParts.Vertex_Before_NormalUpdated:"").replace("#define CUSTOM_VERTEX_MAIN_END",this.CustomParts.Vertex_MainEnd?this.CustomParts.Vertex_MainEnd:""),this.CustomParts.Vertex_After_WorldPosComputed&&(v.Q.ShadersStore[o+"VertexShader"]=v.Q.ShadersStore[o+"VertexShader"].replace("#define CUSTOM_VERTEX_UPDATE_WORLDPOS",this.CustomParts.Vertex_After_WorldPosComputed)),v.Q.ShadersStore[o+"PixelShader"]=this.FragmentShader.replace("#define CUSTOM_FRAGMENT_BEGIN",this.CustomParts.Fragment_Begin?this.CustomParts.Fragment_Begin:"").replace("#define CUSTOM_FRAGMENT_MAIN_BEGIN",this.CustomParts.Fragment_MainBegin?this.CustomParts.Fragment_MainBegin:"").replace("#define CUSTOM_FRAGMENT_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Fragment_Definitions?this.CustomParts.Fragment_Definitions:"")).replace("#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE",this.CustomParts.Fragment_Custom_Diffuse?this.CustomParts.Fragment_Custom_Diffuse:"").replace("#define CUSTOM_FRAGMENT_UPDATE_ALPHA",this.CustomParts.Fragment_Custom_Alpha?this.CustomParts.Fragment_Custom_Alpha:"").replace("#define CUSTOM_FRAGMENT_BEFORE_LIGHTS",this.CustomParts.Fragment_Before_Lights?this.CustomParts.Fragment_Before_Lights:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR",this.CustomParts.Fragment_Before_FragColor?this.CustomParts.Fragment_Before_FragColor:"").replace("#define CUSTOM_FRAGMENT_MAIN_END",this.CustomParts.Fragment_MainEnd?this.CustomParts.Fragment_MainEnd:""),this.CustomParts.Fragment_Before_Fog&&(v.Q.ShadersStore[o+"PixelShader"]=v.Q.ShadersStore[o+"PixelShader"].replace("#define CUSTOM_FRAGMENT_BEFORE_FOG",this.CustomParts.Fragment_Before_Fog)),this._isCreatedShader=!0,this._createdShaderName=o,o}constructor(e,t){super(e,t),this.CustomParts=new b,this.customShaderNameResolve=this.Builder,this.FragmentShader=v.Q.ShadersStore.defaultPixelShader,this.VertexShader=v.Q.ShadersStore.defaultVertexShader}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Fragment_Custom_Diffuse(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}T.ShaderIndexer=1,(0,d.H)("BABYLON.CustomMaterial",T);var S=i(9500),E=i(6430);class C{constructor(){}}class A extends S.Y{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?t.setVector4(i[1],this._newUniformInstances[e]):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e<this._newUniforms.length;e++)-1==this._customUniform[e].indexOf("sampler")&&t.push(this._newUniforms[e].replace(/\[\d*\]/g,""));if("sampler"==e&&this._newUniforms)for(let e=0;e<this._newUniforms.length;e++)-1!=this._customUniform[e].indexOf("sampler")&&t.push(this._newUniforms[e].replace(/\[\d*\]/g,""));return t}Builder(e,t,i,n,s,r,o){if(o){const e=o.processFinalCode;o.processFinalCode=(t,i)=>{if("vertex"===t)return e?e(t,i):i;const n=new E.Z(i);return n.inlineToken="#define pbr_inline",n.processCode(),e?e(t,n.code):n.code}}if(r&&this._customAttributes&&this._customAttributes.length>0&&r.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",n),this._isCreatedShader)return this._createdShaderName;this._isCreatedShader=!1,A.ShaderIndexer++;const a="custom_"+A.ShaderIndexer,l=this._afterBind.bind(this);return this._afterBind=(e,t)=>{if(t){this.AttachAfterBind(e,t);try{l(e,t)}catch(t){}}},v.Q.ShadersStore[a+"VertexShader"]=this.VertexShader.replace("#define CUSTOM_VERTEX_BEGIN",this.CustomParts.Vertex_Begin?this.CustomParts.Vertex_Begin:"").replace("#define CUSTOM_VERTEX_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Vertex_Definitions?this.CustomParts.Vertex_Definitions:"")).replace("#define CUSTOM_VERTEX_MAIN_BEGIN",this.CustomParts.Vertex_MainBegin?this.CustomParts.Vertex_MainBegin:"").replace("#define CUSTOM_VERTEX_UPDATE_POSITION",this.CustomParts.Vertex_Before_PositionUpdated?this.CustomParts.Vertex_Before_PositionUpdated:"").replace("#define CUSTOM_VERTEX_UPDATE_NORMAL",this.CustomParts.Vertex_Before_NormalUpdated?this.CustomParts.Vertex_Before_NormalUpdated:"").replace("#define CUSTOM_VERTEX_MAIN_END",this.CustomParts.Vertex_MainEnd?this.CustomParts.Vertex_MainEnd:""),this.CustomParts.Vertex_After_WorldPosComputed&&(v.Q.ShadersStore[a+"VertexShader"]=v.Q.ShadersStore[a+"VertexShader"].replace("#define CUSTOM_VERTEX_UPDATE_WORLDPOS",this.CustomParts.Vertex_After_WorldPosComputed)),v.Q.ShadersStore[a+"PixelShader"]=this.FragmentShader.replace("#define CUSTOM_FRAGMENT_BEGIN",this.CustomParts.Fragment_Begin?this.CustomParts.Fragment_Begin:"").replace("#define CUSTOM_FRAGMENT_MAIN_BEGIN",this.CustomParts.Fragment_MainBegin?this.CustomParts.Fragment_MainBegin:"").replace("#define CUSTOM_FRAGMENT_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Fragment_Definitions?this.CustomParts.Fragment_Definitions:"")).replace("#define CUSTOM_FRAGMENT_UPDATE_ALBEDO",this.CustomParts.Fragment_Custom_Albedo?this.CustomParts.Fragment_Custom_Albedo:"").replace("#define CUSTOM_FRAGMENT_UPDATE_ALPHA",this.CustomParts.Fragment_Custom_Alpha?this.CustomParts.Fragment_Custom_Alpha:"").replace("#define CUSTOM_FRAGMENT_BEFORE_LIGHTS",this.CustomParts.Fragment_Before_Lights?this.CustomParts.Fragment_Before_Lights:"").replace("#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS",this.CustomParts.Fragment_Custom_MetallicRoughness?this.CustomParts.Fragment_Custom_MetallicRoughness:"").replace("#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE",this.CustomParts.Fragment_Custom_MicroSurface?this.CustomParts.Fragment_Custom_MicroSurface:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION",this.CustomParts.Fragment_Before_FinalColorComposition?this.CustomParts.Fragment_Before_FinalColorComposition:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR",this.CustomParts.Fragment_Before_FragColor?this.CustomParts.Fragment_Before_FragColor:"").replace("#define CUSTOM_FRAGMENT_MAIN_END",this.CustomParts.Fragment_MainEnd?this.CustomParts.Fragment_MainEnd:""),this.CustomParts.Fragment_Before_Fog&&(v.Q.ShadersStore[a+"PixelShader"]=v.Q.ShadersStore[a+"PixelShader"].replace("#define CUSTOM_FRAGMENT_BEFORE_FOG",this.CustomParts.Fragment_Before_Fog)),this._isCreatedShader=!0,this._createdShaderName=a,a}constructor(e,t){super(e,t),this.CustomParts=new C,this.customShaderNameResolve=this.Builder,this.FragmentShader=v.Q.ShadersStore.pbrPixelShader,this.VertexShader=v.Q.ShadersStore.pbrVertexShader,this.FragmentShader=this.FragmentShader.replace(/#include<pbrBlockAlbedoOpacity>/g,v.Q.IncludesShadersStore.pbrBlockAlbedoOpacity),this.FragmentShader=this.FragmentShader.replace(/#include<pbrBlockReflectivity>/g,v.Q.IncludesShadersStore.pbrBlockReflectivity),this.FragmentShader=this.FragmentShader.replace(/#include<pbrBlockFinalColorComposition>/g,v.Q.IncludesShadersStore.pbrBlockFinalColorComposition)}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_Custom_Albedo(e){return this.CustomParts.Fragment_Custom_Albedo=e.replace("result","surfaceAlbedo"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Custom_MetallicRoughness(e){return this.CustomParts.Fragment_Custom_MetallicRoughness=e,this}Fragment_Custom_MicroSurface(e){return this.CustomParts.Fragment_Custom_MicroSurface=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FinalColorComposition(e){return this.CustomParts.Fragment_Before_FinalColorComposition=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}A.ShaderIndexer=1,(0,d.H)("BABYLON.PBRCustomMaterial",A);var P=i(4875),R=i(2262);p.v.ShadersStore.firePixelShader="precision highp float;uniform vec4 vEyePosition;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\nuniform sampler2D distortionSampler;uniform sampler2D opacitySampler;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvec4 bx2(vec4 x)\n{return vec4(2.0)*x-vec4(1.0);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);float alpha=1.0;\n#ifdef DIFFUSE\nconst float distortionAmount0 =0.092;const float distortionAmount1 =0.092;const float distortionAmount2 =0.092;vec2 heightAttenuation=vec2(0.3,0.39);vec4 noise0=texture2D(distortionSampler,vDistortionCoords1);vec4 noise1=texture2D(distortionSampler,vDistortionCoords2);vec4 noise2=texture2D(distortionSampler,vDistortionCoords3);vec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;vec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);vec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy);\n#ifdef ALPHATEST\nif (opacityColor.r<0.1)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;baseColor*=opacityColor;baseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(1.0,1.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec4 color=vec4(baseColor.rgb,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}";p.v.ShadersStore.fireVertexShader="precision highp float;attribute vec3 position;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\nuniform float time;uniform float speed;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSE\nvDiffuseUV=uv;vDiffuseUV.y-=0.2;\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#ifdef DIFFUSE\nvec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;vDistortionCoords1.x=uv.x;vDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;vDistortionCoords2.x=uv.x;vDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;vDistortionCoords3.x=uv.x;vDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class M extends o.H{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.UV1=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.BonesPerMesh=0,this.NUM_BONE_INFLUENCERS=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class I extends l.a{constructor(e,t){super(e,t),this.diffuseColor=new r.Wo(1,1,1),this.speed=1,this._scaledDiffuse=new r.Wo,this._lastTime=0}needAlphaBlending(){return!1}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new M);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,this._diffuseTexture&&h.k.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(n.ALPHATEST=!!this._opacityTexture,n._areMiscDirty&&(n.POINTSIZE=this.pointsCloud||s.forcePointsCloud,n.FOG=s.fogEnabled&&e.applyFog&&s.fogMode!==u.x.FOGMODE_NONE&&this.fogEnabled),a.G.PrepareDefinesForFrameBoundValues(s,r,this,n,!!i),a.G.PrepareDefinesForAttributes(e,n,!1,!0),n.isDirty){n.markAsProcessed(),s.resetCachedMaterial();const i=new f.L;n.FOG&&i.addFallback(1,"FOG"),n.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),n.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[c.o.PositionKind];n.UV1&&o.push(c.o.UVKind),n.VERTEXCOLOR&&o.push(c.o.ColorKind),a.G.PrepareAttributesForBones(o,e,n,i),a.G.PrepareAttributesForInstances(o,n);const l="fire",h=["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","time","speed"];(0,_.qx)(h);const u=n.toString();t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:h,uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:u,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:null,maxSimultaneousLights:4,transformFeedbackVaryings:null},r),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene();if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,s)&&(this._diffuseTexture&&h.k.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),(0,_.an)(this._activeEffect,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),n.bindEyePosition(s)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),this._lastTime+=n.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._distortionTexture&&e.push(this._distortionTexture),this._opacityTexture&&e.push(this._opacityTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._distortionTexture===e||this._opacityTexture===e}getClassName(){return"FireMaterial"}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),super.dispose(e)}clone(e){return s.p4.Clone((()=>new I(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FireMaterial",e.diffuseColor=this.diffuseColor.asArray(),e.speed=this.speed,this._diffuseTexture&&(e._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(e._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(e._opacityTexture=this._opacityTexture.serialize()),e}static Parse(e,t,i){const n=new I(e.name,t);return n.diffuseColor=r.Wo.FromArray(e.diffuseColor),n.speed=e.speed,n.alpha=e.alpha,n.id=e.id,P.$.AddTagsTo(n,e.tags),n.backFaceCulling=e.backFaceCulling,n.wireframe=e.wireframe,e._diffuseTexture&&(n._diffuseTexture=R.x.Parse(e._diffuseTexture,t,i)),e._distortionTexture&&(n._distortionTexture=R.x.Parse(e._distortionTexture,t,i)),e._opacityTexture&&(n._opacityTexture=R.x.Parse(e._opacityTexture,t,i)),n}}(0,n.gn)([(0,s.oU)("diffuseTexture")],I.prototype,"_diffuseTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],I.prototype,"diffuseTexture",void 0),(0,n.gn)([(0,s.oU)("distortionTexture")],I.prototype,"_distortionTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],I.prototype,"distortionTexture",void 0),(0,n.gn)([(0,s.oU)("opacityTexture")],I.prototype,"_opacityTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],I.prototype,"opacityTexture",void 0),(0,n.gn)([(0,s.n9)("diffuse")],I.prototype,"diffuseColor",void 0),(0,n.gn)([(0,s.qC)()],I.prototype,"speed",void 0),(0,d.H)("BABYLON.FireMaterial",I);var D=i(4141),O=i(4160);p.v.ShadersStore.furPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 furColor;uniform float furLength;varying vec3 vPositionW;varying float vfur_length;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<helperFunctions>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform float furOcclusion;uniform sampler2D furTexture;varying vec2 vFurUV;\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<fogFragmentDeclaration>\n#include<clipPlaneFragmentDeclaration>\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=furColor;vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor*=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef HIGHLEVEL\nvec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));if (furTextureColor.a<=0.0 || furTextureColor.g<furOffset) {discard;}\nfloat occlusion=mix(0.0,furTextureColor.b*1.2,furOffset);baseColor=vec4(baseColor.xyz*max(occlusion,furOcclusion),1.1-furOffset);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0);\n#ifdef HIGHLEVEL\nvec4 color=vec4(finalDiffuse,alpha);\n#else\nfloat r=vfur_length/furLength*0.5;vec4 color=vec4(finalDiffuse*(0.5+r),alpha);\n#endif\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}";p.v.ShadersStore.furVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\nuniform float furLength;uniform float furAngle;\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform vec3 furGravity;uniform float furTime;uniform float furSpacing;uniform float furDensity;\n#endif\n#ifdef HEIGHTMAP\nuniform sampler2D heightTexture;\n#endif\n#ifdef HIGHLEVEL\nvarying vec2 vFurUV;\n#endif\n#include<instancesDeclaration>\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\nvarying float vfur_length;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nfloat r=Rand(position);\n#ifdef HEIGHTMAP\n#if __VERSION__>100\nvfur_length=furLength*texture(heightTexture,uv).x;\n#else\nvfur_length=furLength*texture2D(heightTexture,uv).r;\n#endif\n#else \nvfur_length=(furLength*r);\n#endif\nvec3 tangent1=vec3(normal.y,-normal.x,0);vec3 tangent2=vec3(-normal.z,0,normal.x);r=Rand(tangent1*r);float J=(2.0+4.0*r);r=Rand(tangent2*r);float K=(2.0+2.0*r);tangent1=tangent1*J+tangent2*K;tangent1=normalize(tangent1);vec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle);\n#ifdef HIGHLEVEL\nvec3 forceDirection=vec3(0.0,0.0,0.0);forceDirection.x=sin(furTime+position.x*0.05)*0.2;forceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;forceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;vec3 displacement=vec3(0.0,0.0,0.0);displacement=furGravity+forceDirection;float displacementFactor=pow(furOffset,3.0);vec3 aNormal=normal;aNormal.xyz+=displacement*displacementFactor;newPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing);\n#endif\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\ngl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#ifdef HIGHLEVEL\nvFurUV=vDiffuseUV*furDensity;\n#endif\n#else\n#ifdef HIGHLEVEL\nvFurUV=uv*furDensity;\n#endif\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class w extends o.H{constructor(){super(),this.DIFFUSE=!1,this.HEIGHTMAP=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.HIGHLEVEL=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class N extends l.a{constructor(e,t){super(e,t),this.diffuseColor=new r.Wo(1,1,1),this.furLength=1,this.furAngle=0,this.furColor=new r.Wo(.44,.21,.02),this.furOffset=0,this.furSpacing=12,this.furGravity=new D.P(0,0,0),this.furSpeed=100,this.furDensity=20,this.furOcclusion=0,this._disableLighting=!1,this._maxSimultaneousLights=4,this.highLevelFur=!0,this._furTime=0}get furTime(){return this._furTime}set furTime(e){this._furTime=e}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}updateFur(){for(let e=1;e<this._meshes.length;e++){const t=this._meshes[e].material;t.furLength=this.furLength,t.furAngle=this.furAngle,t.furGravity=this.furGravity,t.furSpacing=this.furSpacing,t.furSpeed=this.furSpeed,t.furColor=this.furColor,t.diffuseTexture=this.diffuseTexture,t.furTexture=this.furTexture,t.highLevelFur=this.highLevelFur,t.furTime=this.furTime,t.furDensity=this.furDensity}}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new w);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(n._areTexturesDirty&&s.texturesEnabled){if(this.diffuseTexture&&h.k.DiffuseTextureEnabled){if(!this.diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(this.heightTexture&&r.getCaps().maxVertexTextureImageUnits){if(!this.heightTexture.isReady())return!1;n._needUVs=!0,n.HEIGHTMAP=!0}}if(this.highLevelFur!==n.HIGHLEVEL&&(n.HIGHLEVEL=!0,n.markAsUnprocessed()),a.G.PrepareDefinesForMisc(e,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=a.G.PrepareDefinesForLights(s,e,n,!1,this._maxSimultaneousLights,this._disableLighting),a.G.PrepareDefinesForFrameBoundValues(s,r,this,n,!!i),a.G.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),s.resetCachedMaterial();const i=new f.L;n.FOG&&i.addFallback(1,"FOG"),a.G.HandleFallbacksForShadows(n,i,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),n.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[c.o.PositionKind];n.NORMAL&&o.push(c.o.NormalKind),n.UV1&&o.push(c.o.UVKind),n.UV2&&o.push(c.o.UV2Kind),n.VERTEXCOLOR&&o.push(c.o.ColorKind),a.G.PrepareAttributesForBones(o,e,n,i),a.G.PrepareAttributesForInstances(o,n);const l="fur",h=n.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity","furOcclusion"];(0,_.qx)(u);const d=["diffuseSampler","heightTexture","furTexture"],p=new Array;a.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},r),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,this._activeEffect),n.getCachedMaterial()!==this&&(this._diffuseTexture&&h.k.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),(0,_.an)(this._activeEffect,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),n.bindEyePosition(r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),n.lightsEnabled&&!this.disableLighting&&a.G.BindLights(n,t,this._activeEffect,s,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._activeEffect.setFloat("furOcclusion",this.furOcclusion),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._heightTexture&&e.push(this._heightTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e||this._heightTexture===e}dispose(e){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(let t=1;t<this._meshes.length;t++){const i=this._meshes[t].material;i&&i.dispose(e),this._meshes[t].dispose()}super.dispose(e)}clone(e){return s.p4.Clone((()=>new N(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FurMaterial",this._meshes&&(e.sourceMeshName=this._meshes[0].name,e.quality=this._meshes.length),e}getClassName(){return"FurMaterial"}static Parse(e,t,i){const n=s.p4.Parse((()=>new N(e.name,t)),e,t,i);return e.sourceMeshName&&n.highLevelFur&&t.executeWhenReady((()=>{const i=t.getMeshByName(e.sourceMeshName);if(i){const s=N.GenerateTexture("Fur Texture",t);n.furTexture=s,N.FurifyMesh(i,e.quality)}})),n}static GenerateTexture(e,t){const i=new O.c("FurTexture "+e,256,t,!0),n=i.getContext();for(let e=0;e<2e4;++e)n.fillStyle="rgba(255, "+Math.floor(255*Math.random())+", "+Math.floor(255*Math.random())+", 1)",n.fillRect(Math.random()*i.getSize().width,Math.random()*i.getSize().height,2,2);return i.update(!1),i.wrapU=R.x.WRAP_ADDRESSMODE,i.wrapV=R.x.WRAP_ADDRESSMODE,i}static FurifyMesh(e,t){const i=[e],n=e.material;let s;if(!(n instanceof N))throw"The material of the source mesh must be a Fur Material";for(s=1;s<t;s++){const r=new N(n.name+s,e.getScene());e.getScene().materials.pop(),P.$.EnableFor(r),P.$.AddTagsTo(r,"furShellMaterial"),r.furLength=n.furLength,r.furAngle=n.furAngle,r.furGravity=n.furGravity,r.furSpacing=n.furSpacing,r.furSpeed=n.furSpeed,r.furColor=n.furColor,r.diffuseTexture=n.diffuseTexture,r.furOffset=s/t,r.furTexture=n.furTexture,r.highLevelFur=n.highLevelFur,r.furTime=n.furTime,r.furDensity=n.furDensity;const o=e.clone(e.name+s);o.material=r,o.skeleton=e.skeleton,o.position=D.P.Zero(),i.push(o)}for(s=1;s<i.length;s++)i[s].parent=e;return e.material._meshes=i,i}}(0,n.gn)([(0,s.oU)("diffuseTexture")],N.prototype,"_diffuseTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],N.prototype,"diffuseTexture",void 0),(0,n.gn)([(0,s.oU)("heightTexture")],N.prototype,"_heightTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],N.prototype,"heightTexture",void 0),(0,n.gn)([(0,s.n9)()],N.prototype,"diffuseColor",void 0),(0,n.gn)([(0,s.qC)()],N.prototype,"furLength",void 0),(0,n.gn)([(0,s.qC)()],N.prototype,"furAngle",void 0),(0,n.gn)([(0,s.n9)()],N.prototype,"furColor",void 0),(0,n.gn)([(0,s.qC)()],N.prototype,"furOffset",void 0),(0,n.gn)([(0,s.qC)()],N.prototype,"furSpacing",void 0),(0,n.gn)([(0,s.hd)()],N.prototype,"furGravity",void 0),(0,n.gn)([(0,s.qC)()],N.prototype,"furSpeed",void 0),(0,n.gn)([(0,s.qC)()],N.prototype,"furDensity",void 0),(0,n.gn)([(0,s.qC)()],N.prototype,"furOcclusion",void 0),(0,n.gn)([(0,s.qC)("disableLighting")],N.prototype,"_disableLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],N.prototype,"disableLighting",void 0),(0,n.gn)([(0,s.qC)("maxSimultaneousLights")],N.prototype,"_maxSimultaneousLights",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],N.prototype,"maxSimultaneousLights",void 0),(0,n.gn)([(0,s.qC)()],N.prototype,"highLevelFur",void 0),(0,n.gn)([(0,s.qC)()],N.prototype,"furTime",null),(0,d.H)("BABYLON.FurMaterial",N);p.v.ShadersStore.gradientPixelShader="precision highp float;\nuniform vec4 vEyePosition;\nuniform vec4 topColor;\nuniform vec4 bottomColor;\nuniform float offset;\nuniform float scale;\nuniform float smoothness;\nvarying vec3 vPositionW;\nvarying vec3 vPosition;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<helperFunctions>\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\nfloat h=vPosition.y*scale+offset;\nfloat mysmoothness=clamp(smoothness,0.01,max(smoothness,10.));\nvec4 baseColor=mix(bottomColor,topColor,max(pow(max(h,0.0),mysmoothness),0.0));\nvec3 diffuseColor=baseColor.rgb;\nfloat alpha=baseColor.a;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef EMISSIVE\nvec3 diffuseBase=baseColor.rgb;\n#else\nvec3 diffuseBase=vec3(0.,0.,0.);\n#endif\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";p.v.ShadersStore.gradientVertexShader="precision highp float;\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\nvarying vec3 vPosition;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvPositionW=vec3(worldPos);\nvPosition=position;\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class F extends o.H{constructor(){super(),this.EMISSIVE=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class L extends l.a{constructor(e,t){super(e,t),this._maxSimultaneousLights=4,this.topColor=new r.Wo(1,0,0),this.topColorAlpha=1,this.bottomColor=new r.Wo(0,0,1),this.bottomColorAlpha=1,this.offset=0,this.scale=1,this.smoothness=1,this._disableLighting=!1}needAlphaBlending(){return this.alpha<1||this.topColorAlpha<1||this.bottomColorAlpha<1}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new F);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(a.G.PrepareDefinesForFrameBoundValues(s,r,this,n,!!i),a.G.PrepareDefinesForMisc(e,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=a.G.PrepareDefinesForLights(s,e,n,!1,this._maxSimultaneousLights,this._disableLighting),n.EMISSIVE=this._disableLighting,a.G.PrepareDefinesForAttributes(e,n,!1,!0),n.isDirty){n.markAsProcessed(),s.resetCachedMaterial();const i=new f.L;n.FOG&&i.addFallback(1,"FOG"),a.G.HandleFallbacksForShadows(n,i),n.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),n.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[c.o.PositionKind];n.NORMAL&&o.push(c.o.NormalKind),n.UV1&&o.push(c.o.UVKind),n.UV2&&o.push(c.o.UV2Kind),n.VERTEXCOLOR&&o.push(c.o.ColorKind),a.G.PrepareAttributesForBones(o,e,n,i),a.G.PrepareAttributesForInstances(o,n);const l="gradient",h=n.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","topColor","bottomColor","offset","smoothness","scale"];(0,_.qx)(u);const d=[],p=new Array;a.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},r),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,r),this._mustRebind(n,r)&&((0,_.an)(r,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),n.bindEyePosition(r)),n.lightsEnabled&&!this.disableLighting&&a.G.BindLights(n,t,this._activeEffect,s,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("scale",this.scale),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return s.p4.Clone((()=>new L(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GradientMaterial",e}getClassName(){return"GradientMaterial"}static Parse(e,t,i){return s.p4.Parse((()=>new L(e.name,t)),e,t,i)}}(0,n.gn)([(0,s.qC)("maxSimultaneousLights")],L.prototype,"_maxSimultaneousLights",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],L.prototype,"maxSimultaneousLights",void 0),(0,n.gn)([(0,s.n9)()],L.prototype,"topColor",void 0),(0,n.gn)([(0,s.qC)()],L.prototype,"topColorAlpha",void 0),(0,n.gn)([(0,s.n9)()],L.prototype,"bottomColor",void 0),(0,n.gn)([(0,s.qC)()],L.prototype,"bottomColorAlpha",void 0),(0,n.gn)([(0,s.qC)()],L.prototype,"offset",void 0),(0,n.gn)([(0,s.qC)()],L.prototype,"scale",void 0),(0,n.gn)([(0,s.qC)()],L.prototype,"smoothness",void 0),(0,n.gn)([(0,s.qC)("disableLighting")],L.prototype,"_disableLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],L.prototype,"disableLighting",void 0),(0,d.H)("BABYLON.GradientMaterial",L);p.v.ShadersStore.gridPixelShader="#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform float visibility;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\nfloat getDynamicVisibility(float position) {\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5)==floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \nfloat result=isPointOnLine(position,differentialLength);\nfloat dynamicVisibility=getDynamicVisibility(position);\nresult*=dynamicVisibility;\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset.xyz)/gridRatio;\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n#ifdef MAX_LINE \nfloat grid=clamp(max(max(x,y),z),0.,1.);\n#else\nfloat grid=clamp(x+y+z,0.,1.);\n#endif\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\nfloat opacity=1.0;\n#ifdef TRANSPARENT\nopacity=clamp(grid,0.08,gridControl.w*grid);\n#endif \n#ifdef OPACITY\nopacity*=texture2D(opacitySampler,vOpacityUV).a;\n#endif \ngl_FragColor=vec4(color.rgb,opacity*visibility);\n#ifdef TRANSPARENT\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else \n#endif\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";p.v.ShadersStore.gridVertexShader="precision highp float;\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#include<instancesDeclaration>\nuniform mat4 projection;\nuniform mat4 view;\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include<fogVertex>\nvec4 cameraSpacePosition=view*worldPos;\ngl_Position=projection*cameraSpacePosition;\n#ifdef OPACITY\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\nif (vOpacityInfos.x==0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif \nvPosition=position;\nvNormal=normal;\n#define CUSTOM_VERTEX_MAIN_END\n}";class B extends o.H{constructor(){super(),this.OPACITY=!1,this.TRANSPARENT=!1,this.FOG=!1,this.PREMULTIPLYALPHA=!1,this.MAX_LINE=!1,this.UV1=!1,this.UV2=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class U extends l.a{constructor(e,t){super(e,t),this.mainColor=r.Wo.Black(),this.lineColor=r.Wo.Teal(),this.gridRatio=1,this.gridOffset=D.P.Zero(),this.majorUnitFrequency=10,this.minorUnitVisibility=.33,this.opacity=1,this.preMultiplyAlpha=!1,this.useMaxLine=!1,this._gridControl=new D.Lt(this.gridRatio,this.majorUnitFrequency,this.minorUnitVisibility,this.opacity)}needAlphaBlending(){return this.opacity<1||this._opacityTexture&&this._opacityTexture.isReady()}needAlphaBlendingForMesh(e){return e.visibility<1||this.needAlphaBlending()}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new B);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(n.TRANSPARENT!==this.opacity<1&&(n.TRANSPARENT=!n.TRANSPARENT,n.markAsUnprocessed()),n.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(n.PREMULTIPLYALPHA=!n.PREMULTIPLYALPHA,n.markAsUnprocessed()),n.MAX_LINE!==this.useMaxLine&&(n.MAX_LINE=!n.MAX_LINE,n.markAsUnprocessed()),n._areTexturesDirty&&(n._needUVs=!1,s.texturesEnabled&&this._opacityTexture&&h.k.OpacityTextureEnabled)){if(!this._opacityTexture.isReady())return!1;n._needUVs=!0,n.OPACITY=!0}if(a.G.PrepareDefinesForMisc(e,s,!1,!1,this.fogEnabled,!1,n),a.G.PrepareDefinesForFrameBoundValues(s,s.getEngine(),this,n,!!i),n.isDirty){n.markAsProcessed(),s.resetCachedMaterial(),a.G.PrepareDefinesForAttributes(e,n,!1,!1);const i=[c.o.PositionKind,c.o.NormalKind];n.UV1&&i.push(c.o.UVKind),n.UV2&&i.push(c.o.UV2Kind),n.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess,a.G.PrepareAttributesForInstances(i,n);const r=n.toString();t.setEffect(s.getEngine().createEffect("grid",i,["projection","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view","opacityMatrix","vOpacityInfos","visibility"],["opacitySampler"],r,void 0,this.onCompiled,this.onError),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;r&&(this._activeEffect=r,this._activeEffect.setFloat("visibility",t.visibility),s.INSTANCES&&!s.THIN_INSTANCE||this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",n.getViewMatrix()),this._activeEffect.setMatrix("projection",n.getProjectionMatrix()),this._mustRebind(n,r)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl),this._opacityTexture&&h.k.OpacityTextureEnabled&&(this._activeEffect.setTexture("opacitySampler",this._opacityTexture),this._activeEffect.setFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._activeEffect.setMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix()))),a.G.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}dispose(e){super.dispose(e)}clone(e){return s.p4.Clone((()=>new U(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GridMaterial",e}getClassName(){return"GridMaterial"}static Parse(e,t,i){return s.p4.Parse((()=>new U(e.name,t)),e,t,i)}}(0,n.gn)([(0,s.n9)()],U.prototype,"mainColor",void 0),(0,n.gn)([(0,s.n9)()],U.prototype,"lineColor",void 0),(0,n.gn)([(0,s.qC)()],U.prototype,"gridRatio",void 0),(0,n.gn)([(0,s.hd)()],U.prototype,"gridOffset",void 0),(0,n.gn)([(0,s.qC)()],U.prototype,"majorUnitFrequency",void 0),(0,n.gn)([(0,s.qC)()],U.prototype,"minorUnitVisibility",void 0),(0,n.gn)([(0,s.qC)()],U.prototype,"opacity",void 0),(0,n.gn)([(0,s.qC)()],U.prototype,"preMultiplyAlpha",void 0),(0,n.gn)([(0,s.qC)()],U.prototype,"useMaxLine",void 0),(0,n.gn)([(0,s.oU)("opacityTexture")],U.prototype,"_opacityTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],U.prototype,"opacityTexture",void 0),(0,d.H)("BABYLON.GridMaterial",U);p.v.ShadersStore.lavaPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;uniform float time;uniform float speed;uniform float movingSpeed;uniform vec3 fogColor;uniform sampler2D noiseTexture;uniform float fogDensity;varying float noise;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<helperFunctions>\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nfloat random( vec3 scale,float seed ){return fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nvec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );vec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time *0.02;vec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;T1.x+=noiseTex.x*2.0;T1.y+=noiseTex.y*2.0;T2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;T2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;float p=texture2D( noiseTexture,T1*3.0 ).a;vec4 lavaColor=texture2D( diffuseSampler,T2*4.0);vec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );baseColor=temp;float depth=gl_FragCoord.z*4.0;const float LOG2=1.442695;float fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );fogFactor=1.0-clamp( fogFactor,0.0,1.0 );baseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );diffuseColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}";p.v.ShadersStore.lavaVertexShader="precision highp float;uniform float time;uniform float lowFrequencySpeed;varying float noise;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n/* NOISE FUNCTIONS */\nvec3 mod289(vec3 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 permute(vec4 x)\n{return mod289(((x*34.0)+1.0)*x);}\nvec4 taylorInvSqrt(vec4 r)\n{return 1.79284291400159-0.85373472095314*r;}\nvec3 fade(vec3 t) {return t*t*t*(t*(t*6.0-15.0)+10.0);}\nfloat pnoise(vec3 P,vec3 rep)\n{vec3 Pi0=mod(floor(P),rep); \nvec3 Pi1=mod(Pi0+vec3(1.0),rep); \nPi0=mod289(Pi0);Pi1=mod289(Pi1);vec3 Pf0=fract(P); \nvec3 Pf1=Pf0-vec3(1.0); \nvec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);vec4 iy=vec4(Pi0.yy,Pi1.yy);vec4 iz0=Pi0.zzzz;vec4 iz1=Pi1.zzzz;vec4 ixy=permute(permute(ix)+iy);vec4 ixy0=permute(ixy+iz0);vec4 ixy1=permute(ixy+iz1);vec4 gx0=ixy0*(1.0/7.0);vec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;gx0=fract(gx0);vec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);vec4 sz0=step(gz0,vec4(0.0));gx0-=sz0*(step(0.0,gx0)-0.5);gy0-=sz0*(step(0.0,gy0)-0.5);vec4 gx1=ixy1*(1.0/7.0);vec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;gx1=fract(gx1);vec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);vec4 sz1=step(gz1,vec4(0.0));gx1-=sz1*(step(0.0,gx1)-0.5);gy1-=sz1*(step(0.0,gy1)-0.5);vec3 g000=vec3(gx0.x,gy0.x,gz0.x);vec3 g100=vec3(gx0.y,gy0.y,gz0.y);vec3 g010=vec3(gx0.z,gy0.z,gz0.z);vec3 g110=vec3(gx0.w,gy0.w,gz0.w);vec3 g001=vec3(gx1.x,gy1.x,gz1.x);vec3 g101=vec3(gx1.y,gy1.y,gz1.y);vec3 g011=vec3(gx1.z,gy1.z,gz1.z);vec3 g111=vec3(gx1.w,gy1.w,gz1.w);vec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));g000*=norm0.x;g010*=norm0.y;g100*=norm0.z;g110*=norm0.w;vec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));g001*=norm1.x;g011*=norm1.y;g101*=norm1.z;g111*=norm1.w;float n000=dot(g000,Pf0);float n100=dot(g100,vec3(Pf1.x,Pf0.yz));float n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));float n110=dot(g110,vec3(Pf1.xy,Pf0.z));float n001=dot(g001,vec3(Pf0.xy,Pf1.z));float n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));float n011=dot(g011,vec3(Pf0.x,Pf1.yz));float n111=dot(g111,Pf1);vec3 fade_xyz=fade(Pf0);vec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);vec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);float n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);return 2.2*n_xyz;}\n/* END FUNCTION */\nfloat turbulence( vec3 p ) {float w=100.0;float t=-.5;for (float f=1.0 ; f<=10.0 ; f++ ){float power=pow( 2.0,f );t+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );}\nreturn t;}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\n#ifdef NORMAL\nnoise=10.0* -.10*turbulence( .5*normal+time*1.15 );float b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );float displacement=- 1.5*noise+b;vec3 newPosition=position+normal*displacement;gl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class V extends o.H{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.UNLIT=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class k extends l.a{constructor(e,t){super(e,t),this.speed=1,this.movingSpeed=1,this.lowFrequencySpeed=1,this.fogDensity=.15,this._lastTime=0,this.diffuseColor=new r.Wo(1,1,1),this._disableLighting=!1,this._unlit=!1,this._maxSimultaneousLights=4,this._scaledDiffuse=new r.Wo}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new V);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,s.texturesEnabled&&this._diffuseTexture&&h.k.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(a.G.PrepareDefinesForMisc(e,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=!0,a.G.PrepareDefinesForLights(s,e,n,!1,this._maxSimultaneousLights,this._disableLighting),a.G.PrepareDefinesForFrameBoundValues(s,r,this,n,!!i),a.G.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),s.resetCachedMaterial();const i=new f.L;n.FOG&&i.addFallback(1,"FOG"),a.G.HandleFallbacksForShadows(n,i),n.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),n.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[c.o.PositionKind];n.NORMAL&&o.push(c.o.NormalKind),n.UV1&&o.push(c.o.UVKind),n.UV2&&o.push(c.o.UV2Kind),n.VERTEXCOLOR&&o.push(c.o.ColorKind),a.G.PrepareAttributesForBones(o,e,n,i),a.G.PrepareAttributesForInstances(o,n);const l="lava",h=n.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"];(0,_.qx)(u);const d=["diffuseSampler","noiseTexture"],p=new Array;a.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},r),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const o=i.effect;o&&(this._activeEffect=o,s.UNLIT=this._unlit,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,o)&&(this.diffuseTexture&&h.k.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),(0,_.an)(o,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),n.bindEyePosition(o)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),n.lightsEnabled&&!this.disableLighting&&a.G.BindLights(n,t,this._activeEffect,s),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),this._lastTime+=n.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=r.Wo.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),super.dispose(e)}clone(e){return s.p4.Clone((()=>new k(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.LavaMaterial",e}getClassName(){return"LavaMaterial"}static Parse(e,t,i){return s.p4.Parse((()=>new k(e.name,t)),e,t,i)}}(0,n.gn)([(0,s.oU)("diffuseTexture")],k.prototype,"_diffuseTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],k.prototype,"diffuseTexture",void 0),(0,n.gn)([(0,s.oU)()],k.prototype,"noiseTexture",void 0),(0,n.gn)([(0,s.n9)()],k.prototype,"fogColor",void 0),(0,n.gn)([(0,s.qC)()],k.prototype,"speed",void 0),(0,n.gn)([(0,s.qC)()],k.prototype,"movingSpeed",void 0),(0,n.gn)([(0,s.qC)()],k.prototype,"lowFrequencySpeed",void 0),(0,n.gn)([(0,s.qC)()],k.prototype,"fogDensity",void 0),(0,n.gn)([(0,s.n9)()],k.prototype,"diffuseColor",void 0),(0,n.gn)([(0,s.qC)("disableLighting")],k.prototype,"_disableLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],k.prototype,"disableLighting",void 0),(0,n.gn)([(0,s.qC)("unlit")],k.prototype,"_unlit",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],k.prototype,"unlit",void 0),(0,n.gn)([(0,s.qC)("maxSimultaneousLights")],k.prototype,"_maxSimultaneousLights",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],k.prototype,"maxSimultaneousLights",void 0),(0,d.H)("BABYLON.LavaMaterial",k);p.v.ShadersStore.mixPixelShader="precision highp float;\nuniform vec4 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<helperFunctions>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform sampler2D mixMap1Sampler;\nuniform vec2 vTextureInfos;\n#ifdef MIXMAP2\nuniform sampler2D mixMap2Sampler;\n#endif\nuniform sampler2D diffuse1Sampler;\nuniform sampler2D diffuse2Sampler;\nuniform sampler2D diffuse3Sampler;\nuniform sampler2D diffuse4Sampler;\nuniform vec2 diffuse1Infos;\nuniform vec2 diffuse2Infos;\nuniform vec2 diffuse3Infos;\nuniform vec2 diffuse4Infos;\n#ifdef MIXMAP2\nuniform sampler2D diffuse5Sampler;\nuniform sampler2D diffuse6Sampler;\nuniform sampler2D diffuse7Sampler;\nuniform sampler2D diffuse8Sampler;\nuniform vec2 diffuse5Infos;\nuniform vec2 diffuse6Infos;\nuniform vec2 diffuse7Infos;\nuniform vec2 diffuse8Infos;\n#endif\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\nvec4 finalMixColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef MIXMAP2\nvec4 mixColor2=vec4(1.,1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec4 mixColor=texture2D(mixMap1Sampler,vTextureUV);\n#include<depthPrePass>\nmixColor.rgb*=vTextureInfos.y;\nvec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);\nvec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);\nvec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);\nvec4 diffuse4Color=texture2D(diffuse4Sampler,vTextureUV*diffuse4Infos);\ndiffuse1Color.rgb*=mixColor.r;\ndiffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,mixColor.g);\ndiffuse3Color.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,mixColor.b);\nfinalMixColor.rgb=mix(diffuse3Color.rgb,diffuse4Color.rgb,1.0-mixColor.a);\n#ifdef MIXMAP2\nmixColor=texture2D(mixMap2Sampler,vTextureUV);\nmixColor.rgb*=vTextureInfos.y;\nvec4 diffuse5Color=texture2D(diffuse5Sampler,vTextureUV*diffuse5Infos);\nvec4 diffuse6Color=texture2D(diffuse6Sampler,vTextureUV*diffuse6Infos);\nvec4 diffuse7Color=texture2D(diffuse7Sampler,vTextureUV*diffuse7Infos);\nvec4 diffuse8Color=texture2D(diffuse8Sampler,vTextureUV*diffuse8Infos);\ndiffuse5Color.rgb=mix(finalMixColor.rgb,diffuse5Color.rgb,mixColor.r);\ndiffuse6Color.rgb=mix(diffuse5Color.rgb,diffuse6Color.rgb,mixColor.g);\ndiffuse7Color.rgb=mix(diffuse6Color.rgb,diffuse7Color.rgb,mixColor.b);\nfinalMixColor.rgb=mix(diffuse7Color.rgb,diffuse8Color.rgb,1.0-mixColor.a);\n#endif\n#endif\n#ifdef VERTEXCOLOR\nfinalMixColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*finalMixColor.rgb,0.0,1.0);\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";p.v.ShadersStore.mixVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class G extends o.H{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.MIXMAP2=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class z extends l.a{constructor(e,t){super(e,t),this.diffuseColor=new r.Wo(1,1,1),this.specularColor=new r.Wo(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new G);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(s.texturesEnabled){if(!this._mixTexture1||!this._mixTexture1.isReady())return!1;if(n._needUVs=!0,h.k.DiffuseTextureEnabled){if(!this._diffuseTexture1||!this._diffuseTexture1.isReady())return!1;if(n.DIFFUSE=!0,!this._diffuseTexture2||!this._diffuseTexture2.isReady())return!1;if(!this._diffuseTexture3||!this._diffuseTexture3.isReady())return!1;if(!this._diffuseTexture4||!this._diffuseTexture4.isReady())return!1;if(this._mixTexture2){if(!this._mixTexture2.isReady())return!1;if(n.MIXMAP2=!0,!this._diffuseTexture5||!this._diffuseTexture5.isReady())return!1;if(!this._diffuseTexture6||!this._diffuseTexture6.isReady())return!1;if(!this._diffuseTexture7||!this._diffuseTexture7.isReady())return!1;if(!this._diffuseTexture8||!this._diffuseTexture8.isReady())return!1}}}if(a.G.PrepareDefinesForMisc(e,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=a.G.PrepareDefinesForLights(s,e,n,!1,this._maxSimultaneousLights,this._disableLighting),a.G.PrepareDefinesForFrameBoundValues(s,r,this,n,!!i),a.G.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),s.resetCachedMaterial();const i=new f.L;n.FOG&&i.addFallback(1,"FOG"),a.G.HandleFallbacksForShadows(n,i,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),n.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[c.o.PositionKind];n.NORMAL&&o.push(c.o.NormalKind),n.UV1&&o.push(c.o.UVKind),n.UV2&&o.push(c.o.UV2Kind),n.VERTEXCOLOR&&o.push(c.o.ColorKind),a.G.PrepareAttributesForBones(o,e,n,i),a.G.PrepareAttributesForInstances(o,n);const l="mix",h=n.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos","diffuse4Infos","diffuse5Infos","diffuse6Infos","diffuse7Infos","diffuse8Infos"],d=["mixMap1Sampler","mixMap2Sampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","diffuse4Sampler","diffuse5Sampler","diffuse6Sampler","diffuse7Sampler","diffuse8Sampler"],p=new Array;(0,_.qx)(u),a.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},r),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,r)&&(this._mixTexture1&&(this._activeEffect.setTexture("mixMap1Sampler",this._mixTexture1),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture1.coordinatesIndex,this._mixTexture1.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture1.getTextureMatrix()),h.k.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale)),this._diffuseTexture4&&(this._activeEffect.setTexture("diffuse4Sampler",this._diffuseTexture4),this._activeEffect.setFloat2("diffuse4Infos",this._diffuseTexture4.uScale,this._diffuseTexture4.vScale)))),this._mixTexture2&&(this._activeEffect.setTexture("mixMap2Sampler",this._mixTexture2),h.k.DiffuseTextureEnabled&&(this._diffuseTexture5&&(this._activeEffect.setTexture("diffuse5Sampler",this._diffuseTexture5),this._activeEffect.setFloat2("diffuse5Infos",this._diffuseTexture5.uScale,this._diffuseTexture5.vScale)),this._diffuseTexture6&&(this._activeEffect.setTexture("diffuse6Sampler",this._diffuseTexture6),this._activeEffect.setFloat2("diffuse6Infos",this._diffuseTexture6.uScale,this._diffuseTexture6.vScale)),this._diffuseTexture7&&(this._activeEffect.setTexture("diffuse7Sampler",this._diffuseTexture7),this._activeEffect.setFloat2("diffuse7Infos",this._diffuseTexture7.uScale,this._diffuseTexture7.vScale)),this._diffuseTexture8&&(this._activeEffect.setTexture("diffuse8Sampler",this._diffuseTexture8),this._activeEffect.setFloat2("diffuse8Infos",this._diffuseTexture8.uScale,this._diffuseTexture8.vScale)))),(0,_.an)(r,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),n.bindEyePosition(r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),n.lightsEnabled&&!this.disableLighting&&a.G.BindLights(n,t,this._activeEffect,s,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this._mixTexture1&&this._mixTexture1.animations&&this._mixTexture1.animations.length>0&&e.push(this._mixTexture1),this._mixTexture2&&this._mixTexture2.animations&&this._mixTexture2.animations.length>0&&e.push(this._mixTexture2),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture1&&e.push(this._mixTexture1),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._diffuseTexture4&&e.push(this._diffuseTexture4),this._mixTexture2&&e.push(this._mixTexture2),this._diffuseTexture5&&e.push(this._diffuseTexture5),this._diffuseTexture6&&e.push(this._diffuseTexture6),this._diffuseTexture7&&e.push(this._diffuseTexture7),this._diffuseTexture8&&e.push(this._diffuseTexture8),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture1===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._diffuseTexture4===e||this._mixTexture2===e||this._diffuseTexture5===e||this._diffuseTexture6===e||this._diffuseTexture7===e||this._diffuseTexture8===e}dispose(e){this._mixTexture1&&this._mixTexture1.dispose(),super.dispose(e)}clone(e){return s.p4.Clone((()=>new z(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MixMaterial",e}getClassName(){return"MixMaterial"}static Parse(e,t,i){return s.p4.Parse((()=>new z(e.name,t)),e,t,i)}}(0,n.gn)([(0,s.oU)("mixTexture1")],z.prototype,"_mixTexture1",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],z.prototype,"mixTexture1",void 0),(0,n.gn)([(0,s.oU)("mixTexture2")],z.prototype,"_mixTexture2",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],z.prototype,"mixTexture2",void 0),(0,n.gn)([(0,s.oU)("diffuseTexture1")],z.prototype,"_diffuseTexture1",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],z.prototype,"diffuseTexture1",void 0),(0,n.gn)([(0,s.oU)("diffuseTexture2")],z.prototype,"_diffuseTexture2",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],z.prototype,"diffuseTexture2",void 0),(0,n.gn)([(0,s.oU)("diffuseTexture3")],z.prototype,"_diffuseTexture3",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],z.prototype,"diffuseTexture3",void 0),(0,n.gn)([(0,s.oU)("diffuseTexture4")],z.prototype,"_diffuseTexture4",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],z.prototype,"diffuseTexture4",void 0),(0,n.gn)([(0,s.oU)("diffuseTexture1")],z.prototype,"_diffuseTexture5",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],z.prototype,"diffuseTexture5",void 0),(0,n.gn)([(0,s.oU)("diffuseTexture2")],z.prototype,"_diffuseTexture6",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],z.prototype,"diffuseTexture6",void 0),(0,n.gn)([(0,s.oU)("diffuseTexture3")],z.prototype,"_diffuseTexture7",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],z.prototype,"diffuseTexture7",void 0),(0,n.gn)([(0,s.oU)("diffuseTexture4")],z.prototype,"_diffuseTexture8",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],z.prototype,"diffuseTexture8",void 0),(0,n.gn)([(0,s.n9)()],z.prototype,"diffuseColor",void 0),(0,n.gn)([(0,s.n9)()],z.prototype,"specularColor",void 0),(0,n.gn)([(0,s.qC)()],z.prototype,"specularPower",void 0),(0,n.gn)([(0,s.qC)("disableLighting")],z.prototype,"_disableLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],z.prototype,"disableLighting",void 0),(0,n.gn)([(0,s.qC)("maxSimultaneousLights")],z.prototype,"_maxSimultaneousLights",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],z.prototype,"maxSimultaneousLights",void 0),(0,d.H)("BABYLON.MixMaterial",z);p.v.ShadersStore.normalPixelShader="precision highp float;\nuniform vec4 vEyePosition;\nuniform vec4 vDiffuseColor;\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef LIGHTING\n#include<helperFunctions>\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef NORMAL\nbaseColor=mix(baseColor,vec4(vNormalW,1.0),0.5);\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef LIGHTING\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse= baseColor.rgb;\n#endif\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}";p.v.ShadersStore.normalVertexShader="precision highp float;\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class W extends o.H{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.LIGHTING=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class H extends l.a{constructor(e,t){super(e,t),this.diffuseColor=new r.Wo(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaBlendingForMesh(e){return this.needAlphaBlending()||e.visibility<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new W);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,s.texturesEnabled&&this._diffuseTexture&&h.k.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(a.G.PrepareDefinesForMisc(e,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=!0,a.G.PrepareDefinesForLights(s,e,n,!1,this._maxSimultaneousLights,this._disableLighting),a.G.PrepareDefinesForFrameBoundValues(s,r,this,n,!!i),n.LIGHTING=!this._disableLighting,a.G.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),s.resetCachedMaterial();const i=new f.L;n.FOG&&i.addFallback(1,"FOG"),a.G.HandleFallbacksForShadows(n,i),n.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),n.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[c.o.PositionKind];n.NORMAL&&o.push(c.o.NormalKind),n.UV1&&o.push(c.o.UVKind),n.UV2&&o.push(c.o.UV2Kind),a.G.PrepareAttributesForBones(o,e,n,i),a.G.PrepareAttributesForInstances(o,n);const l="normal",h=n.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix"],d=["diffuseSampler"],p=new Array;(0,_.qx)(u),a.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},r),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,r)&&(this.diffuseTexture&&h.k.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),(0,_.an)(r,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),n.bindEyePosition(r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),n.lightsEnabled&&!this.disableLighting&&a.G.BindLights(n,t,this._activeEffect,s),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),super.dispose(e)}clone(e){return s.p4.Clone((()=>new H(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.NormalMaterial",e}getClassName(){return"NormalMaterial"}static Parse(e,t,i){return s.p4.Parse((()=>new H(e.name,t)),e,t,i)}}(0,n.gn)([(0,s.oU)("diffuseTexture")],H.prototype,"_diffuseTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],H.prototype,"diffuseTexture",void 0),(0,n.gn)([(0,s.n9)()],H.prototype,"diffuseColor",void 0),(0,n.gn)([(0,s.qC)("disableLighting")],H.prototype,"_disableLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],H.prototype,"disableLighting",void 0),(0,n.gn)([(0,s.qC)("maxSimultaneousLights")],H.prototype,"_maxSimultaneousLights",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],H.prototype,"maxSimultaneousLights",void 0),(0,d.H)("BABYLON.NormalMaterial",H);p.v.ShadersStore.shadowOnlyPixelShader="precision highp float;\nuniform vec4 vEyePosition;\nuniform float alpha;\nuniform vec3 shadowColor;\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include<helperFunctions>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0..1]\nvec4 color=vec4(shadowColor,(1.0-clamp(shadow,0.,1.))*alpha);\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}";p.v.ShadersStore.shadowOnlyVertexShader="precision highp float;\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class X extends o.H{constructor(){super(),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.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class j extends l.a{constructor(e,t){super(e,t),this._needAlphaBlending=!0,this.shadowColor=r.Wo.Black()}needAlphaBlending(){return this._needAlphaBlending}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}get activeLight(){return this._activeLight}set activeLight(e){this._activeLight=e}_getFirstShadowLightForMesh(e){for(const t of e.lightSources)if(t.shadowEnabled)return t;return null}isReadyForSubMesh(e,t,i){var n;if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new X);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(this._activeLight)for(const t of e.lightSources)if(t.shadowEnabled){if(this._activeLight===t)break;const i=e.lightSources.indexOf(this._activeLight);-1!==i&&(e.lightSources.splice(i,1),e.lightSources.splice(0,0,this._activeLight));break}a.G.PrepareDefinesForFrameBoundValues(r,o,this,s,!!i),a.G.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=a.G.PrepareDefinesForLights(r,e,s,!1,1);const l=null===(n=this._getFirstShadowLightForMesh(e))||void 0===n?void 0:n.getShadowGenerator();if(this._needAlphaBlending=!0,l&&l.getClassName&&"CascadedShadowGenerator"===l.getClassName()){const e=l;this._needAlphaBlending=!e.autoCalcDepthBounds}if(a.G.PrepareDefinesForAttributes(e,s,!1,!0),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const i=new f.L;s.FOG&&i.addFallback(1,"FOG"),a.G.HandleFallbacksForShadows(s,i,1),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const n=[c.o.PositionKind];s.NORMAL&&n.push(c.o.NormalKind),a.G.PrepareAttributesForBones(n,e,s,i),a.G.PrepareAttributesForInstances(n,s);const l="shadowOnly",h=s.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","shadowColor","mBones"],d=new Array,p=new Array;(0,_.qx)(u),a.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:s,maxSimultaneousLights:1}),t.setEffect(r.getEngine().createEffect(l,{attributes:n,uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;if(r){if(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,r)&&((0,_.an)(r,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),this._activeEffect.setColor3("shadowColor",this.shadowColor),n.bindEyePosition(r)),n.lightsEnabled){a.G.BindLights(n,t,this._activeEffect,s,1);const e=this._getFirstShadowLightForMesh(t);e&&(e._renderId=-1)}(n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE||s.SHADOWCSM0)&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect)}}clone(e){return s.p4.Clone((()=>new j(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.ShadowOnlyMaterial",e}getClassName(){return"ShadowOnlyMaterial"}static Parse(e,t,i){return s.p4.Parse((()=>new j(e.name,t)),e,t,i)}}(0,d.H)("BABYLON.ShadowOnlyMaterial",j);p.v.ShadersStore.simplePixelShader="precision highp float;\nuniform vec4 vEyePosition;\nuniform vec4 vDiffuseColor;\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<helperFunctions>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include<lightFragment>[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}";p.v.ShadersStore.simpleVertexShader="precision highp float;\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class Y extends o.H{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class q extends l.a{constructor(e,t){super(e,t),this.diffuseColor=new r.Wo(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new Y);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,s.texturesEnabled&&this._diffuseTexture&&h.k.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(a.G.PrepareDefinesForMisc(e,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=a.G.PrepareDefinesForLights(s,e,n,!1,this._maxSimultaneousLights,this._disableLighting),a.G.PrepareDefinesForFrameBoundValues(s,r,this,n,!!i),a.G.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),s.resetCachedMaterial();const i=new f.L;n.FOG&&i.addFallback(1,"FOG"),a.G.HandleFallbacksForShadows(n,i,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),n.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[c.o.PositionKind];n.NORMAL&&o.push(c.o.NormalKind),n.UV1&&o.push(c.o.UVKind),n.UV2&&o.push(c.o.UV2Kind),n.VERTEXCOLOR&&o.push(c.o.ColorKind),a.G.PrepareAttributesForBones(o,e,n,i),a.G.PrepareAttributesForInstances(o,n);const l="simple",h=n.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix"],d=["diffuseSampler"],p=new Array;(0,_.qx)(u),a.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},r),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,r)&&(this._diffuseTexture&&h.k.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),(0,_.an)(r,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),n.bindEyePosition(r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),n.lightsEnabled&&!this.disableLighting&&a.G.BindLights(n,t,this._activeEffect,s,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}clone(e){return s.p4.Clone((()=>new q(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SimpleMaterial",e}getClassName(){return"SimpleMaterial"}static Parse(e,t,i){return s.p4.Parse((()=>new q(e.name,t)),e,t,i)}}(0,n.gn)([(0,s.oU)("diffuseTexture")],q.prototype,"_diffuseTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],q.prototype,"diffuseTexture",void 0),(0,n.gn)([(0,s.n9)("diffuse")],q.prototype,"diffuseColor",void 0),(0,n.gn)([(0,s.qC)("disableLighting")],q.prototype,"_disableLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],q.prototype,"disableLighting",void 0),(0,n.gn)([(0,s.qC)("maxSimultaneousLights")],q.prototype,"_maxSimultaneousLights",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],q.prototype,"maxSimultaneousLights",void 0),(0,d.H)("BABYLON.SimpleMaterial",q);p.v.ShadersStore.skyPixelShader="precision highp float;\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\nuniform vec3 cameraPosition;\nuniform vec3 cameraOffset;\nuniform vec3 up;\nuniform float luminance;\nuniform float turbidity;\nuniform float rayleigh;\nuniform float mieCoefficient;\nuniform float mieDirectionalG;\nuniform vec3 sunPosition;\n#include<fogFragmentDeclaration>\nconst float e=2.71828182845904523536028747135266249775724709369995957;\nconst float pi=3.141592653589793238462643383279502884197169;\nconst float n=1.0003;\nconst float N=2.545E25;\nconst float pn=0.035;\nconst vec3 lambda=vec3(680E-9,550E-9,450E-9);\nconst vec3 K=vec3(0.686,0.678,0.666);\nconst float v=4.0;\nconst float rayleighZenithLength=8.4E3;\nconst float mieZenithLength=1.25E3;\nconst float EE=1000.0;\nconst float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;\nconst float cutoffAngle=pi/1.95;\nconst float steepness=1.5;\nvec3 totalRayleigh(vec3 lambda)\n{\nreturn (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));\n}\nvec3 simplifiedRayleigh()\n{\nreturn 0.0005/vec3(94,40,18);\n}\nfloat rayleighPhase(float cosTheta)\n{ \nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));\n}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{\nfloat c=(0.2*T )*10E-18;\nreturn 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;\n}\nfloat hgPhase(float cosTheta,float g)\n{\nreturn (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));\n}\nfloat sunIntensity(float zenithAngleCos)\n{\nreturn EE*max(0.0,1.0-exp((-(cutoffAngle-acos(zenithAngleCos))/steepness)));\n}\nfloat A=0.15;\nfloat B=0.50;\nfloat C=0.10;\nfloat D=0.20;\nfloat EEE=0.02;\nfloat F=0.30;\nfloat W=1000.0;\nvec3 Uncharted2Tonemap(vec3 x)\n{\nreturn ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;\n}\n#if DITHER\n#include<helperFunctions>\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\n/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);\nfloat rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));\nvec3 sunDirection=normalize(sunPosition);\nfloat sunE=sunIntensity(dot(sunDirection,up));\nvec3 betaR=simplifiedRayleigh()*rayleighCoefficient;\nvec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;\nfloat zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition+cameraOffset))));\nfloat sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nfloat sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nvec3 Fex=exp(-(betaR*sR+betaM*sM));\nfloat cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);\nfloat rPhase=rayleighPhase(cosTheta*0.5+0.5);\nvec3 betaRTheta=betaR*rPhase;\nfloat mPhase=hgPhase(cosTheta,mieDirectionalG);\nvec3 betaMTheta=betaM*mPhase;\nvec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));\nLin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));\nvec3 direction=normalize(vPositionW-cameraPosition);\nfloat theta=acos(direction.y);\nfloat phi=atan(direction.z,direction.x);\nvec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);\nvec3 L0=vec3(0.1)*Fex;\nfloat sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);\nL0+=(sunE*19000.0*Fex)*sundisk;\nvec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));\nvec3 texColor=(Lin+L0);\ntexColor*=0.04 ;\ntexColor+=vec3(0.0,0.001,0.0025)*0.3;\nfloat g_fMaxLuminance=1.0;\nfloat fLumScaled=0.1/luminance; \nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); \nfloat ExposureBias=fLumCompressed;\nvec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);\nvec3 retColor=curr*whiteScale;\n/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if DITHER\nretColor.rgb+=dither(gl_FragCoord.xy,0.5);\n#endif\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";p.v.ShadersStore.skyVertexShader="precision highp float;\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=viewProjection*world*vec4(position,1.0);\nvec4 worldPos=world*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#include<clipPlaneVertex>\n#include<fogVertex>\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class K extends o.H{constructor(){super(),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.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.DITHER=!1,this.rebuild()}}class $ extends l.a{constructor(e,t){super(e,t),this.luminance=1,this.turbidity=10,this.rayleigh=2,this.mieCoefficient=.005,this.mieDirectionalG=.8,this.distance=500,this.inclination=.49,this.azimuth=.25,this.sunPosition=new D.P(0,100,0),this.useSunPosition=!1,this.cameraOffset=D.P.Zero(),this.up=D.P.Up(),this.dithering=!1,this._cameraPosition=D.P.Zero(),this._skyOrientation=new D._f}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new K);const i=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(a.G.PrepareDefinesForMisc(e,n,!1,this.pointsCloud,this.fogEnabled,!1,i),a.G.PrepareDefinesForAttributes(e,i,!0,!1),i.IMAGEPROCESSINGPOSTPROCESS!==n.imageProcessingConfiguration.applyByPostProcess&&i.markAsMiscDirty(),i.DITHER!==this.dithering&&i.markAsMiscDirty(),i.isDirty){i.markAsProcessed(),n.resetCachedMaterial();const e=new f.L;i.FOG&&e.addFallback(1,"FOG"),i.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess,i.DITHER=this.dithering;const s=[c.o.PositionKind];i.VERTEXCOLOR&&s.push(c.o.ColorKind);const r="sky",o=["world","viewProjection","view","vFogInfos","vFogColor","pointSize","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition","cameraOffset","up"];(0,_.qx)(o);const a=i.toString();t.setEffect(n.getEngine().createEffect(r,s,o,[],a,e,this.onCompiled,this.onError),i,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(i._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const n=this.getScene();if(!i.materialDefines)return;const s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),this._mustRebind(n,s)&&((0,_.an)(s,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize)),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect);const r=n.activeCamera;if(r){const e=r.getWorldMatrix();this._cameraPosition.x=e.m[12],this._cameraPosition.y=e.m[13],this._cameraPosition.z=e.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}if(this._activeEffect.setVector3("cameraOffset",this.cameraOffset),this._activeEffect.setVector3("up",this.up),this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){const e=Math.PI*(this.inclination-.5),t=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(t)*Math.cos(e),this.sunPosition.y=this.distance*Math.sin(-e),this.sunPosition.z=this.distance*Math.sin(t)*Math.cos(e),D._f.FromUnitVectorsToRef(D.P.UpReadOnly,this.up,this._skyOrientation),this.sunPosition.rotateByQuaternionToRef(this._skyOrientation,this.sunPosition)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect)}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return s.p4.Clone((()=>new $(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SkyMaterial",e}getClassName(){return"SkyMaterial"}static Parse(e,t,i){return s.p4.Parse((()=>new $(e.name,t)),e,t,i)}}(0,n.gn)([(0,s.qC)()],$.prototype,"luminance",void 0),(0,n.gn)([(0,s.qC)()],$.prototype,"turbidity",void 0),(0,n.gn)([(0,s.qC)()],$.prototype,"rayleigh",void 0),(0,n.gn)([(0,s.qC)()],$.prototype,"mieCoefficient",void 0),(0,n.gn)([(0,s.qC)()],$.prototype,"mieDirectionalG",void 0),(0,n.gn)([(0,s.qC)()],$.prototype,"distance",void 0),(0,n.gn)([(0,s.qC)()],$.prototype,"inclination",void 0),(0,n.gn)([(0,s.qC)()],$.prototype,"azimuth",void 0),(0,n.gn)([(0,s.hd)()],$.prototype,"sunPosition",void 0),(0,n.gn)([(0,s.qC)()],$.prototype,"useSunPosition",void 0),(0,n.gn)([(0,s.hd)()],$.prototype,"cameraOffset",void 0),(0,n.gn)([(0,s.hd)()],$.prototype,"up",void 0),(0,n.gn)([(0,s.qC)()],$.prototype,"dithering",void 0),(0,d.H)("BABYLON.SkyMaterial",$);p.v.ShadersStore.terrainPixelShader="precision highp float;\nuniform vec4 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<helperFunctions>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform sampler2D textureSampler;\nuniform vec2 vTextureInfos;\nuniform sampler2D diffuse1Sampler;\nuniform sampler2D diffuse2Sampler;\nuniform sampler2D diffuse3Sampler;\nuniform vec2 diffuse1Infos;\nuniform vec2 diffuse2Infos;\nuniform vec2 diffuse3Infos;\n#endif\n#ifdef BUMP\nuniform sampler2D bump1Sampler;\nuniform sampler2D bump2Sampler;\nuniform sampler2D bump3Sampler;\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,vec3 mixColor)\n{\nvec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;\nvec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;\nvec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;\nbump1Color.rgb*=mixColor.r;\nbump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);\nvec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);\nmap=map*255./127.-128./127.;\nmat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);\nreturn normalize(TBN*map);\n}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(textureSampler,vTextureUV);\n#if defined(BUMP) && defined(DIFFUSE)\nnormalW=perturbNormal(viewDirectionW,baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vTextureInfos.y;\nvec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);\nvec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);\nvec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);\ndiffuse1Color.rgb*=baseColor.r;\ndiffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);\nbaseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";p.v.ShadersStore.terrainVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class Q extends o.H{constructor(){super(),this.DIFFUSE=!1,this.BUMP=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class Z extends l.a{constructor(e,t){super(e,t),this.diffuseColor=new r.Wo(1,1,1),this.specularColor=new r.Wo(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new Q);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(s.texturesEnabled){if(!this.mixTexture||!this.mixTexture.isReady())return!1;if(n._needUVs=!0,h.k.DiffuseTextureEnabled){if(!this.diffuseTexture1||!this.diffuseTexture1.isReady())return!1;if(!this.diffuseTexture2||!this.diffuseTexture2.isReady())return!1;if(!this.diffuseTexture3||!this.diffuseTexture3.isReady())return!1;n.DIFFUSE=!0}if(this.bumpTexture1&&this.bumpTexture2&&this.bumpTexture3&&h.k.BumpTextureEnabled){if(!this.bumpTexture1.isReady())return!1;if(!this.bumpTexture2.isReady())return!1;if(!this.bumpTexture3.isReady())return!1;n._needNormals=!0,n.BUMP=!0}}if(a.G.PrepareDefinesForMisc(e,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=a.G.PrepareDefinesForLights(s,e,n,!1,this._maxSimultaneousLights,this._disableLighting),a.G.PrepareDefinesForFrameBoundValues(s,r,this,n,!!i),a.G.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),s.resetCachedMaterial();const i=new f.L;n.FOG&&i.addFallback(1,"FOG"),a.G.HandleFallbacksForShadows(n,i,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),n.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[c.o.PositionKind];n.NORMAL&&o.push(c.o.NormalKind),n.UV1&&o.push(c.o.UVKind),n.UV2&&o.push(c.o.UV2Kind),n.VERTEXCOLOR&&o.push(c.o.ColorKind),a.G.PrepareAttributesForBones(o,e,n,i),a.G.PrepareAttributesForInstances(o,n);const l="terrain",h=n.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],d=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler"],p=new Array;(0,_.qx)(u),a.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},r),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,r)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),h.k.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),h.k.BumpTextureEnabled&&n.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),(0,_.an)(r,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),n.bindEyePosition(r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),n.lightsEnabled&&!this.disableLighting&&a.G.BindLights(n,t,this._activeEffect,s,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture&&e.push(this._mixTexture),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._bumpTexture1&&e.push(this._bumpTexture1),this._bumpTexture2&&e.push(this._bumpTexture2),this._bumpTexture3&&e.push(this._bumpTexture3),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._bumpTexture1===e||this._bumpTexture2===e||this._bumpTexture3===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return s.p4.Clone((()=>new Z(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TerrainMaterial",e}getClassName(){return"TerrainMaterial"}static Parse(e,t,i){return s.p4.Parse((()=>new Z(e.name,t)),e,t,i)}}(0,n.gn)([(0,s.oU)("mixTexture")],Z.prototype,"_mixTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],Z.prototype,"mixTexture",void 0),(0,n.gn)([(0,s.oU)("diffuseTexture1")],Z.prototype,"_diffuseTexture1",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],Z.prototype,"diffuseTexture1",void 0),(0,n.gn)([(0,s.oU)("diffuseTexture2")],Z.prototype,"_diffuseTexture2",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],Z.prototype,"diffuseTexture2",void 0),(0,n.gn)([(0,s.oU)("diffuseTexture3")],Z.prototype,"_diffuseTexture3",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],Z.prototype,"diffuseTexture3",void 0),(0,n.gn)([(0,s.oU)("bumpTexture1")],Z.prototype,"_bumpTexture1",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],Z.prototype,"bumpTexture1",void 0),(0,n.gn)([(0,s.oU)("bumpTexture2")],Z.prototype,"_bumpTexture2",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],Z.prototype,"bumpTexture2",void 0),(0,n.gn)([(0,s.oU)("bumpTexture3")],Z.prototype,"_bumpTexture3",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],Z.prototype,"bumpTexture3",void 0),(0,n.gn)([(0,s.n9)()],Z.prototype,"diffuseColor",void 0),(0,n.gn)([(0,s.n9)()],Z.prototype,"specularColor",void 0),(0,n.gn)([(0,s.qC)()],Z.prototype,"specularPower",void 0),(0,n.gn)([(0,s.qC)("disableLighting")],Z.prototype,"_disableLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],Z.prototype,"disableLighting",void 0),(0,n.gn)([(0,s.qC)("maxSimultaneousLights")],Z.prototype,"_maxSimultaneousLights",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],Z.prototype,"maxSimultaneousLights",void 0),(0,d.H)("BABYLON.TerrainMaterial",Z);p.v.ShadersStore.triplanarPixelShader="precision highp float;\nuniform vec4 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<helperFunctions>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\nuniform sampler2D diffuseSamplerX;\n#ifdef BUMPX\nuniform sampler2D normalSamplerX;\n#endif\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\nuniform sampler2D diffuseSamplerY;\n#ifdef BUMPY\nuniform sampler2D normalSamplerY;\n#endif\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\nuniform sampler2D diffuseSamplerZ;\n#ifdef BUMPZ\nuniform sampler2D normalSamplerZ;\n#endif\n#endif\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\nvec4 baseColor=vec4(0.,0.,0.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=tangentSpace[2];\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec4 baseNormal=vec4(0.0,0.0,0.0,1.0);\nnormalW*=normalW;\n#ifdef DIFFUSEX\nbaseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x;\n#ifdef BUMPX\nbaseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x;\n#endif\n#endif\n#ifdef DIFFUSEY\nbaseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y;\n#ifdef BUMPY\nbaseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y;\n#endif\n#endif\n#ifdef DIFFUSEZ\nbaseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z;\n#ifdef BUMPZ\nbaseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z;\n#endif\n#endif\n#ifdef NORMAL\nnormalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";p.v.ShadersStore.triplanarVertexShader="precision highp float;\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\n#endif\nuniform float tileSize;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvPositionW=vec3(worldPos);\n#ifdef DIFFUSEX\nvTextureUVX=worldPos.zy/tileSize;\n#endif\n#ifdef DIFFUSEY\nvTextureUVY=worldPos.xz/tileSize;\n#endif\n#ifdef DIFFUSEZ\nvTextureUVZ=worldPos.xy/tileSize;\n#endif\n#ifdef NORMAL\nvec3 xtan=vec3(0,0,1);\nvec3 xbin=vec3(0,1,0);\nvec3 ytan=vec3(1,0,0);\nvec3 ybin=vec3(0,0,1);\nvec3 ztan=vec3(1,0,0);\nvec3 zbin=vec3(0,1,0);\nvec3 normalizedNormal=normalize(normal);\nnormalizedNormal*=normalizedNormal;\nvec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);\nvec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);\nworldTangent=(world*vec4(worldTangent,0.0)).xyz;\nworldBinormal=(world*vec4(worldBinormal,0.0)).xyz;\nvec3 worldNormal=(world*vec4(normalize(normal),0.0)).xyz;\ntangentSpace[0]=worldTangent;\ntangentSpace[1]=worldBinormal;\ntangentSpace[2]=worldNormal;\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class J extends o.H{constructor(){super(),this.DIFFUSEX=!1,this.DIFFUSEY=!1,this.DIFFUSEZ=!1,this.BUMPX=!1,this.BUMPY=!1,this.BUMPZ=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class ee extends l.a{constructor(e,t){super(e,t),this.tileSize=1,this.diffuseColor=new r.Wo(1,1,1),this.specularColor=new r.Wo(.2,.2,.2),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new J);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(n._areTexturesDirty&&s.texturesEnabled){if(h.k.DiffuseTextureEnabled){const e=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],t=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"];for(let i=0;i<e.length;i++)if(e[i]){if(!e[i].isReady())return!1;n[t[i]]=!0}}if(h.k.BumpTextureEnabled){const e=[this.normalTextureX,this.normalTextureY,this.normalTextureZ],t=["BUMPX","BUMPY","BUMPZ"];for(let i=0;i<e.length;i++)if(e[i]){if(!e[i].isReady())return!1;n[t[i]]=!0}}}if(a.G.PrepareDefinesForMisc(e,s,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=a.G.PrepareDefinesForLights(s,e,n,!1,this._maxSimultaneousLights,this._disableLighting),a.G.PrepareDefinesForFrameBoundValues(s,r,this,n,!!i),a.G.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),s.resetCachedMaterial();const i=new f.L;n.FOG&&i.addFallback(1,"FOG"),a.G.HandleFallbacksForShadows(n,i,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),n.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const o=[c.o.PositionKind];n.NORMAL&&o.push(c.o.NormalKind),n.VERTEXCOLOR&&o.push(c.o.ColorKind),a.G.PrepareAttributesForBones(o,e,n,i),a.G.PrepareAttributesForInstances(o,n);const l="triplanar",h=n.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","tileSize"],d=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ"],p=new Array;(0,_.qx)(u),a.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},r),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),n.getCachedMaterial()!==this&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),(0,_.an)(r,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),n.bindEyePosition(r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),n.lightsEnabled&&!this.disableLighting&&a.G.BindLights(n,t,this._activeEffect,s,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTextureX&&e.push(this._diffuseTextureX),this._diffuseTextureY&&e.push(this._diffuseTextureY),this._diffuseTextureZ&&e.push(this._diffuseTextureZ),this._normalTextureX&&e.push(this._normalTextureX),this._normalTextureY&&e.push(this._normalTextureY),this._normalTextureZ&&e.push(this._normalTextureZ),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTextureX===e||this._diffuseTextureY===e||this._diffuseTextureZ===e||this._normalTextureX===e||this._normalTextureY===e||this._normalTextureZ===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return s.p4.Clone((()=>new ee(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TriPlanarMaterial",e}getClassName(){return"TriPlanarMaterial"}static Parse(e,t,i){return s.p4.Parse((()=>new ee(e.name,t)),e,t,i)}}(0,n.gn)([(0,s.oU)()],ee.prototype,"mixTexture",void 0),(0,n.gn)([(0,s.oU)("diffuseTextureX")],ee.prototype,"_diffuseTextureX",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"diffuseTextureX",void 0),(0,n.gn)([(0,s.oU)("diffuseTexturY")],ee.prototype,"_diffuseTextureY",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"diffuseTextureY",void 0),(0,n.gn)([(0,s.oU)("diffuseTextureZ")],ee.prototype,"_diffuseTextureZ",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"diffuseTextureZ",void 0),(0,n.gn)([(0,s.oU)("normalTextureX")],ee.prototype,"_normalTextureX",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"normalTextureX",void 0),(0,n.gn)([(0,s.oU)("normalTextureY")],ee.prototype,"_normalTextureY",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"normalTextureY",void 0),(0,n.gn)([(0,s.oU)("normalTextureZ")],ee.prototype,"_normalTextureZ",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"normalTextureZ",void 0),(0,n.gn)([(0,s.qC)()],ee.prototype,"tileSize",void 0),(0,n.gn)([(0,s.n9)()],ee.prototype,"diffuseColor",void 0),(0,n.gn)([(0,s.n9)()],ee.prototype,"specularColor",void 0),(0,n.gn)([(0,s.qC)()],ee.prototype,"specularPower",void 0),(0,n.gn)([(0,s.qC)("disableLighting")],ee.prototype,"_disableLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],ee.prototype,"disableLighting",void 0),(0,n.gn)([(0,s.qC)("maxSimultaneousLights")],ee.prototype,"_maxSimultaneousLights",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],ee.prototype,"maxSimultaneousLights",void 0),(0,d.H)("BABYLON.TriPlanarMaterial",ee);var te=i(142),ie=i(7458),ne=i(5363),se=i(4246),re=i(4475);i(5141),i(3660),i(1030),i(8773);p.v.ShadersStore.waterPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec4 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<helperFunctions>\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform sampler2D normalSampler;\nuniform vec2 vNormalInfos;\n#endif\nuniform sampler2D refractionSampler;\nuniform sampler2D reflectionSampler;\nconst float LOG2=1.442695;\nuniform vec3 cameraPosition;\nuniform vec4 waterColor;\nuniform float colorBlendFactor;\nuniform vec4 waterColor2;\nuniform float colorBlendFactor2;\nuniform float bumpHeight;\nuniform float time;\nvarying vec3 vRefractionMapTexCoord;\nvarying vec3 vReflectionMapTexCoord;\nvarying vec3 vPosition;\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\nfloat alpha=vDiffuseColor.a;\n#ifdef BUMP\n#ifdef BUMPSUPERIMPOSE\nbaseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y));\n#else\nbaseColor=texture2D(normalSampler,vNormalUV);\n#endif\nvec3 bumpColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vNormalInfos.y;\n#else\nvec3 bumpColor=vec3(1.0);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec2 perturbation=bumpHeight*(baseColor.rg-0.5);\n#ifdef BUMPAFFECTSREFLECTION\nvec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));\nif (normalW.y<0.0) {\nnormalW.y=-normalW.y;\n}\n#else\nvec3 normalW=normalize(vNormalW);\n#endif\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\nvec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5);\n#endif\n#ifdef FRESNELSEPARATE\n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);\nvec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vec2(\nvReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3,\nvReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y\n),0.0,1.0);\nvec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);\nfloat fresnelTerm=clamp(abs(pow(dot(viewDirectionW,upVector),3.0)),0.05,0.65);\nfloat IfresnelTerm=1.0-fresnelTerm;\nrefractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;\nreflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;\nvec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;\nbaseColor=combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#else \n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);\nvec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);\nvec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);\nfloat fresnelTerm=max(dot(viewDirectionW,upVector),0.0);\nvec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);\nbaseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#endif\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#elif defined(IMAGEPROCESSING)\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n",i(5501);p.v.ShadersStore.waterVertexShader="precision highp float;\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform mat4 normalMatrix;\nuniform vec2 vNormalInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<logDepthDeclaration>\nuniform mat4 worldReflectionViewProjection;\nuniform vec2 windDirection;\nuniform float waveLength;\nuniform float time;\nuniform float windForce;\nuniform float waveHeight;\nuniform float waveSpeed;\nuniform float waveCount;\nvarying vec3 vPosition;\nvarying vec3 vRefractionMapTexCoord;\nvarying vec3 vReflectionMapTexCoord;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef BUMP\nif (vNormalInfos.x==0.)\n{\nvNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0));\n#endif\n}\nelse\n{\nvNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0));\n#endif\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\nfloat finalWaveCount=1.0/(waveCount*0.5);\nvec3 p=position;\nfloat newY=(sin(((p.x/finalWaveCount)+time*waveSpeed))*waveHeight*windDirection.x*5.0)\n+ (cos(((p.z/finalWaveCount)+ time*waveSpeed))*waveHeight*windDirection.y*5.0);\np.y+=abs(newY);\ngl_Position=viewProjection*finalWorld*vec4(p,1.0);\n#ifdef REFLECTION\nworldPos=viewProjection*finalWorld*vec4(p,1.0);\nvPosition=position;\nvRefractionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);\nvRefractionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);\nvRefractionMapTexCoord.z=worldPos.w;\nworldPos=worldReflectionViewProjection*vec4(position,1.0);\nvReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);\nvReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);\nvReflectionMapTexCoord.z=worldPos.w;\n#endif\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n";var oe=i(8027);class ae extends o.H{constructor(){super(),this.BUMP=!1,this.REFLECTION=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.SPECULARTERM=!1,this.LOGARITHMICDEPTH=!1,this.USE_REVERSE_DEPTHBUFFER=!1,this.FRESNELSEPARATE=!1,this.BUMPSUPERIMPOSE=!1,this.BUMPAFFECTSREFLECTION=!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.rebuild()}}class le extends l.a{get hasRenderTargetTextures(){return!0}constructor(e,t,i=new D.FM(512,512)){super(e,t),this.renderTargetSize=i,this.diffuseColor=new r.Wo(1,1,1),this.specularColor=new r.Wo(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4,this.windForce=6,this.windDirection=new D.FM(0,1),this.waveHeight=.4,this.bumpHeight=.4,this._bumpSuperimpose=!1,this._fresnelSeparate=!1,this._bumpAffectsReflection=!1,this.waterColor=new r.Wo(.1,.1,.6),this.colorBlendFactor=.2,this.waterColor2=new r.Wo(.1,.1,.6),this.colorBlendFactor2=.2,this.waveLength=.1,this.waveSpeed=1,this.waveCount=20,this.disableClipPlane=!1,this._renderTargets=new ne.t(16),this._mesh=null,this._reflectionTransform=D.y3.Zero(),this._lastTime=0,this._lastDeltaTime=0,this._createRenderTargets(this.getScene(),i),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._renderTargets.push(this._reflectionRTT),this._renderTargets.push(this._refractionRTT),this._renderTargets),this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()}get refractionTexture(){return this._refractionRTT}get reflectionTexture(){return this._reflectionRTT}addToRenderList(e){this._refractionRTT&&this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT&&this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)}enableRenderTargets(e){const t=e?1:0;this._refractionRTT&&(this._refractionRTT.refreshRate=t),this._reflectionRTT&&(this._reflectionRTT.refreshRate=t)}getRenderList(){return this._refractionRTT?this._refractionRTT.renderList:[]}get renderTargetsEnabled(){return!(this._refractionRTT&&0===this._refractionRTT.refreshRate)}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new ae);const n=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const r=s.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,s.texturesEnabled)){if(this.bumpTexture&&h.k.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;n._needUVs=!0,n.BUMP=!0}h.k.ReflectionTextureEnabled&&(n.REFLECTION=!0)}if(a.G.PrepareDefinesForFrameBoundValues(s,r,this,n,!!i),a.G.PrepareDefinesForMisc(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._areMiscDirty&&(this._fresnelSeparate&&(n.FRESNELSEPARATE=!0),this._bumpSuperimpose&&(n.BUMPSUPERIMPOSE=!0),this._bumpAffectsReflection&&(n.BUMPAFFECTSREFLECTION=!0)),n._needNormals=a.G.PrepareDefinesForLights(s,e,n,!0,this._maxSimultaneousLights,this._disableLighting),n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(a.G.PrepareDefinesForAttributes(e,n,!0,!0),this._mesh=e,this._waitingRenderList){for(let e=0;e<this._waitingRenderList.length;e++)this.addToRenderList(s.getNodeById(this._waitingRenderList[e]));this._waitingRenderList=null}if(n.isDirty){n.markAsProcessed(),s.resetCachedMaterial();const i=new f.L;n.FOG&&i.addFallback(1,"FOG"),n.LOGARITHMICDEPTH&&i.addFallback(0,"LOGARITHMICDEPTH"),a.G.HandleFallbacksForShadows(n,i,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e);const o=[c.o.PositionKind];n.NORMAL&&o.push(c.o.NormalKind),n.UV1&&o.push(c.o.UVKind),n.UV2&&o.push(c.o.UV2Kind),n.VERTEXCOLOR&&o.push(c.o.ColorKind),a.G.PrepareAttributesForBones(o,e,n,i),a.G.PrepareAttributesForInstances(o,n);const l="water",h=n.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","normalMatrix","logarithmicDepthConstant","worldReflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed","waveCount"],d=["normalSampler","refractionSampler","reflectionSampler"],p=new Array;re.$&&(re.$.PrepareUniforms(u,n),re.$.PrepareSamplers(d,n)),(0,_.qx)(u),a.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(s.getEngine().createEffect(l,{attributes:o,uniformsNames:u,uniformBuffersNames:p,samplers:d,defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},r),n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;if(!r||!this._mesh)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),a.G.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,r)&&(this.bumpTexture&&h.k.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),(0,_.an)(r,this,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),n.bindEyePosition(r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),n.lightsEnabled&&!this.disableLighting&&a.G.BindLights(n,t,this._activeEffect,s,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==u.x.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),a.G.BindFogParameters(n,t,this._activeEffect),a.G.BindLogDepth(s,this._activeEffect,n),h.k.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));const o=this._mesh.getWorldMatrix().multiply(this._reflectionTransform).multiply(n.getProjectionMatrix()),l=n.getEngine().getDeltaTime();l!==this._lastDeltaTime&&(this._lastDeltaTime=l,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("worldReflectionViewProjection",o),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._activeEffect.setFloat("waveCount",this.waveCount),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect),this._afterBind(t,this._activeEffect)}_createRenderTargets(e,t){let i;this._refractionRTT=new se._(name+"_refraction",{width:t.x,height:t.y},e,!1,!0),this._refractionRTT.wrapU=ie.g.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=ie.g.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0,this._reflectionRTT=new se._(name+"_reflection",{width:t.x,height:t.y},e,!1,!0),this._reflectionRTT.wrapU=ie.g.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=ie.g.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;let n,s=null;const r=D.y3.Zero();this._refractionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){s=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=te.J.FromPositionAndNormal(new D.P(0,t+.05,0),new D.P(0,1,0))}},this._refractionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),this.disableClipPlane||(e.clipPlane=s)},this._reflectionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){s=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=te.J.FromPositionAndNormal(new D.P(0,t-.05,0),new D.P(0,-1,0)),D.y3.ReflectionToRef(e.clipPlane,r)}n=e.getViewMatrix(),r.multiplyToRef(n,this._reflectionTransform),e.setTransformMatrix(this._reflectionTransform,e.getProjectionMatrix()),e._mirroredCameraPosition=D.P.TransformCoordinates(e.activeCamera.position,r)},this._reflectionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),e.clipPlane=s,e.setTransformMatrix(n,e.getProjectionMatrix()),e._mirroredCameraPosition=null}}getAnimatables(){const e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e}getActiveTextures(){const e=super.getActiveTextures();return this._bumpTexture&&e.push(this._bumpTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._bumpTexture===e}dispose(e){this.bumpTexture&&this.bumpTexture.dispose();let t=this.getScene().customRenderTargets.indexOf(this._refractionRTT);-1!=t&&this.getScene().customRenderTargets.splice(t,1),t=-1,t=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),-1!=t&&this.getScene().customRenderTargets.splice(t,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return s.p4.Clone((()=>new le(e,this.getScene())),this)}serialize(){const e=super.serialize();if(e.customType="BABYLON.WaterMaterial",e.renderList=[],this._refractionRTT&&this._refractionRTT.renderList)for(let t=0;t<this._refractionRTT.renderList.length;t++)e.renderList.push(this._refractionRTT.renderList[t].id);return e}getClassName(){return"WaterMaterial"}static Parse(e,t,i){const n=s.p4.Parse((()=>new le(e.name,t)),e,t,i);return n._waitingRenderList=e.renderList,n}static CreateDefaultMesh(e,t){return(0,oe.$6)(e,{width:512,height:512,subdivisions:32,updatable:!1},t)}}(0,n.gn)([(0,s.oU)("bumpTexture")],le.prototype,"_bumpTexture",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsTexturesDirty")],le.prototype,"bumpTexture",void 0),(0,n.gn)([(0,s.n9)()],le.prototype,"diffuseColor",void 0),(0,n.gn)([(0,s.n9)()],le.prototype,"specularColor",void 0),(0,n.gn)([(0,s.qC)()],le.prototype,"specularPower",void 0),(0,n.gn)([(0,s.qC)("disableLighting")],le.prototype,"_disableLighting",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],le.prototype,"disableLighting",void 0),(0,n.gn)([(0,s.qC)("maxSimultaneousLights")],le.prototype,"_maxSimultaneousLights",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsLightsDirty")],le.prototype,"maxSimultaneousLights",void 0),(0,n.gn)([(0,s.qC)()],le.prototype,"windForce",void 0),(0,n.gn)([(0,s.QC)()],le.prototype,"windDirection",void 0),(0,n.gn)([(0,s.qC)()],le.prototype,"waveHeight",void 0),(0,n.gn)([(0,s.qC)()],le.prototype,"bumpHeight",void 0),(0,n.gn)([(0,s.qC)("bumpSuperimpose")],le.prototype,"_bumpSuperimpose",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsMiscDirty")],le.prototype,"bumpSuperimpose",void 0),(0,n.gn)([(0,s.qC)("fresnelSeparate")],le.prototype,"_fresnelSeparate",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsMiscDirty")],le.prototype,"fresnelSeparate",void 0),(0,n.gn)([(0,s.qC)("bumpAffectsReflection")],le.prototype,"_bumpAffectsReflection",void 0),(0,n.gn)([(0,s.wz)("_markAllSubMeshesAsMiscDirty")],le.prototype,"bumpAffectsReflection",void 0),(0,n.gn)([(0,s.n9)()],le.prototype,"waterColor",void 0),(0,n.gn)([(0,s.qC)()],le.prototype,"colorBlendFactor",void 0),(0,n.gn)([(0,s.n9)()],le.prototype,"waterColor2",void 0),(0,n.gn)([(0,s.qC)()],le.prototype,"colorBlendFactor2",void 0),(0,n.gn)([(0,s.qC)()],le.prototype,"waveLength",void 0),(0,n.gn)([(0,s.qC)()],le.prototype,"waveSpeed",void 0),(0,n.gn)([(0,s.qC)()],le.prototype,"waveCount",void 0),(0,n.gn)([(0,s.qC)()],le.prototype,"disableClipPlane",void 0),(0,n.gn)([(0,s.qC)()],le.prototype,"useLogarithmicDepth",null),(0,d.H)("BABYLON.WaterMaterial",le)}},r={};function o(e){var t=r[e];if(void 0!==t)return t.exports;var i=r[e]={exports:{}};return s[e].call(i.exports,i,i.exports,o),i.exports}o.m=s,o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,o.t=function(i,n){if(1&n&&(i=this(i)),8&n)return i;if("object"==typeof i&&i){if(4&n&&i.__esModule)return i;if(16&n&&"function"==typeof i.then)return i}var s=Object.create(null);o.r(s);var r={};e=e||[null,t({}),t([]),t(t)];for(var a=2&n&&i;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>r[e]=()=>i[e]));return r.default=()=>i,o.d(s,r),s},o.d=(e,t)=>{for(var i in t)o.o(t,i)&&!o.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o.f={},o.e=e=>Promise.all(Object.keys(o.f).reduce(((t,i)=>(o.f[i](e,t),t)),[])),o.u=e=>e+".js",o.miniCssF=e=>{},o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i={},n="@dndbeyond/dice:",o.l=(e,t,s,r)=>{if(i[e])i[e].push(t);else{var a,l;if(void 0!==s)for(var h=document.getElementsByTagName("script"),c=0;c<h.length;c++){var u=h[c];if(u.getAttribute("src")==e||u.getAttribute("data-webpack")==n+s){a=u;break}}a||(l=!0,(a=document.createElement("script")).type="module",a.charset="utf-8",a.timeout=120,o.nc&&a.setAttribute("nonce",o.nc),a.setAttribute("data-webpack",n+s),a.src=e),i[e]=[t];var d=(t,n)=>{a.onerror=a.onload=null,clearTimeout(p);var s=i[e];if(delete i[e],a.parentNode&&a.parentNode.removeChild(a),s&&s.forEach((e=>e(n))),t)return t(n)},p=setTimeout(d.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=d.bind(null,a.onerror),a.onload=d.bind(null,a.onload),l&&document.head.appendChild(a)}},o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.p="/dist/",(()=>{var e={585:0};o.f.j=(t,i)=>{var n=o.o(e,t)?e[t]:void 0;if(0!==n)if(n)i.push(n[2]);else{var s=new Promise(((i,s)=>n=e[t]=[i,s]));i.push(n[2]=s);var r=o.p+o.u(t),a=new Error;o.l(r,(i=>{if(o.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var s=i&&("load"===i.type?"missing":i.type),r=i&&i.target&&i.target.src;a.message="Loading chunk "+t+" failed.\n("+s+": "+r+")",a.name="ChunkLoadError",a.type=s,a.request=r,n[1](a)}}),"chunk-"+t,t)}};var t=(t,i)=>{var n,s,[r,a,l]=i,h=0;if(r.some((t=>0!==e[t]))){for(n in a)o.o(a,n)&&(o.m[n]=a[n]);l&&l(o)}for(t&&t(i);h<r.length;h++)s=r[h],o.o(e,s)&&e[s]&&e[s][0](),e[s]=0},i=self.webpackChunk_dndbeyond_dice=self.webpackChunk_dndbeyond_dice||[];i.forEach(t.bind(null,0)),i.push=t.bind(null,i.push.bind(i))})();var a={};(()=>{o.d(a,{cp:()=>At,rq:()=>i,bV:()=>Kt,jx:()=>n,m8:()=>Mt,w$:()=>C,f4:()=>s,ZM:()=>A,S_:()=>$t,lD:()=>r,hi:()=>l,cU:()=>Rt,DI:()=>t,ro:()=>e,Yd:()=>oe,_w:()=>c,LM:()=>Dt,Gs:()=>It,ee:()=>d});var e={DICE_Advanced:"Dice-CharacterSheet",DICE_Menu:"Dice Menu",DICE_Toolbar:"Dice Toolbar",DICE_Settings:"Dice Settings",DICE_Result:"Dice Result"},t={DICE_Roll:"Roll from Click",DICE_Shake:"Roll from Shake",DICE_Custom_D20_Added:"D20 has been Added",DICE_Custom_D12_Added:"D12 has been Added",DICE_Custom_D10_Added:"D10 has been Added",DICE_Custom_D8_Added:"D8 has been Added",DICE_Custom_D6_Added:"D6 has been Added",DICE_Custom_D4_Added:"D4 has been Added",DICE_Custom_D100_Added:"D100 has been Added",DICE_Custom_D20_Removed:"D20 has been Removed",DICE_Custom_D12_Removed:"D12 has been Removed",DICE_Custom_D10_Removed:"D10 has been Removed",DICE_Custom_D8_Removed:"D8 has been Removed",DICE_Custom_D6_Removed:"D6 has been Removed",DICE_Custom_D4_Removed:"D4 has been Removed",DICE_Custom_D100_Removed:"D100 has been Removed",DICE_Toolbar_Open:"Dice Toolbar Opened",DICE_Toolbar_Close:"Dice Toolbar Opened",DICE_Enabled:"Dice Enabled",DICE_Disabled:"Dice Disabled",DICE_Modal:"Dice Modal Shown",DICE_Menu_Roll:"Dice Menu Roll",DICE_Menu_Advantage:"Dice Menu Roll Advantage",DICE_Menu_Disadvantage:"Dice Menu Roll Disadvantage",DICE_Menu_Critical:"Dice Menu Roll Critical"},i={id:"",manifestUrl:"/bundles/basic/default.json",familyId:"",setId:"",settings:{volume:1,vibrationEnabled:!0,particlesEnabled:!0,shadowQuality:3}},n=function(e){return e.ROLL="dice-roll",e.CLEAR="dice-clear",e}({}),s=function(e){return e[e.Sum=0]="Sum",e[e.Min=1]="Min",e[e.Max=2]="Max",e}({}),r=function(e){return e.d4="d4",e.d6="d6",e.d8="d8",e.d10="d10",e.d12="d12",e.d20="d20",e.d100="d100",e}({}),l=[r.d20,r.d12,r.d10,r.d100,r.d8,r.d6,r.d4],h=function(e){return e.None="",e.Advantage="advantage",e.Disadvantage="disadvantage",e.CriticalHit="critical hit",e}(h||{});const c=h;var u=function(e){return e.Roll="roll",e.ToHit="to hit",e.Damage="damage",e.Heal="heal",e.Spell="spell",e.Save="save",e.Check="check",e}(u||{});const d=u;function p(e,t,i,n,s,r,o){try{var a=e[r](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(n,s)}function f(e){return function(){var t=this,i=arguments;return new Promise((function(n,s){var r=e.apply(t,i);function o(e){p(r,n,s,o,a,"next",e)}function a(e){p(r,n,s,o,a,"throw",e)}o(void 0)}))}}function _(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function m(e){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},m(e)}function g(e){var t=function(e,t){if("object"!==m(e)||null===e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,"string");if("object"!==m(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"===m(t)?t:String(t)}function v(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,g(n.key),n)}}function y(e,t,i){return t&&v(e.prototype,t),i&&v(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function x(e,t,i){return(t=g(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var b=o(2841),T=o.n(b),S=o(7126),E=o.n(S),C=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3;_(this,e),x(this,"_resultHistory",void 0),x(this,"_animationIn",void 0),x(this,"_animationOut",void 0),x(this,"_historyMode",void 0),x(this,"historySize",void 0),x(this,"_enabled",void 0),this._resultHistory=[],this._enabled=!0,this._animationIn="animated faster bounceInUp",this._animationOut="animated faster bounceOutRight",this._historyMode="uncollapse",this.historySize=t,E().setMaxVisible(this.historySize)}return y(e,[{key:"setEnabled",value:function(e){this._enabled=e}},{key:"showDiceNotification",value:function(e,t){if(this._enabled){this.trimHistory();for(var i=e.rolls.length,n="",s=0;s<i;s++){var r=e.rolls[s],o=this._getMostCommonDie(r),a=r.rollType.replace(/[^a-z0-9]/gi,""),l="";o&&(l='\n <span class="dice-icon-die dice-icon-die--'.concat(o,'" alt=""></span>\n '));var h="",u="";switch(r.rollKind){case c.Advantage:h='<span class="dice_result__total-header dice_result__total-header--advantage">+ADV</span>';break;case c.Disadvantage:h='<span class="dice_result__total-header dice_result__total-header--disadvantage">-DIS</span>';break;case c.CriticalHit:h='<span class="dice_result__total-header dice_result__total-header--crit">CRIT</span>',u="dice_result--crit"}var d="string"==typeof e.context.messageTarget?parseInt(e.context.messageTarget):e.context.messageTarget;n+='\n <div class="dice_result '.concat(u,'">\n <div class="dice_result__info">\n <div class="dice_result__info__title">\n <span class="dice_result__info__rolldetail">').concat(e.action,': </span><span class="dice_result__rolltype rolltype_').concat(a,'">').concat(r.rollType,"</span>\n </div>\n ").concat("userId"===e.context.messageScope?'<div class="dice_result__info__title">\n <span class="dice_result__info__targetdetail">TO:'.concat(" ",t===d?"SELF":"DM","\n </span>\n </div>"):"",'\n <div class="dice_result__info__results">\n ').concat(l,'\n <span class="dice_result__info__breakdown" title="').concat(r.result.text,'">').concat(r.result.text,'</span>\n </div>\n <span class="dice_result__info__dicenotation" title="').concat(r.getDiceNotationString(),'">').concat(r.getDiceNotationString(),'</span>\n </div>\n <span class="dice_result__divider dice_result__divider--').concat("userId"===e.context.messageScope?"target":"",'"></span>\n <div class="dice_result__total-container">\n ').concat(h,'\n <span class="dice_result__total-result dice_result__total-result-').concat("userId"===e.context.messageScope?"target":"",'">').concat(r.result.total,"</span>\n </div>\n </div>\n ")}var p=new(E())({text:n,layout:"bottomRight",progressBar:!1,animation:{open:this._animationIn,close:this._animationOut}});p.setTheme("valhalla",!0),p.show(),this._resultHistory.unshift(p);for(var f=1;f<this._resultHistory.length;f++)this._resultHistory[f].setTheme("valhalla-min",!0);this.createNotificationControls()}}},{key:"_getMostCommonDie",value:function(e){for(var t=[],i={dieType:"d20",count:0},n=0;n<(null===(s=e.diceNotation.set)||void 0===s?void 0:s.length);n++){var s,r=e.diceNotation.set[n];r.dieType in t?t[r.dieType]+=r.count:t[r.dieType]=r.count,t[r.dieType]>i.count&&(i.count=t[r.dieType],i.dieType=r.dieType)}return i.dieType}},{key:"createNotificationControls",value:function(){var e=this,t='\n <div class="dice_notification_control dice_notification_controls__clear"><span>Clear All</span><i></i></div>\n <div class="dice_notification_control dice_notification_controls__'.concat(this._historyMode,'"><i></i></div>\n '),i=document.querySelector(".noty_layout");if(i){i.classList.add(this._historyMode);var n=i.getElementsByClassName("dice_notification_controls");if(n.length>0)return void i.appendChild(n[0]);var s=document.createElement("div");s.className="dice_notification_controls",s.innerHTML=t,s.getElementsByClassName("dice_notification_controls__clear")[0].addEventListener("click",(function(t){return e.clearNotifications(t)})),s.getElementsByClassName("dice_notification_controls__".concat(this._historyMode))[0].addEventListener("click",(function(t){return e.toggleHistory(t)})),i.appendChild(s)}}},{key:"toggleHistory",value:function(e){var t=document.querySelector(".noty_layout");e.currentTarget.classList.remove("dice_notification_controls__".concat(this._historyMode)),"collapse"===this._historyMode?(this._historyMode="uncollapse",t.classList.replace("collapse","uncollapse")):(this._historyMode="collapse",t.classList.replace("uncollapse","collapse")),e.currentTarget.classList.add("dice_notification_controls__".concat(this._historyMode))}},{key:"trimHistory",value:function(){for(;this._resultHistory.length>this.historySize-1;)this._resultHistory.pop().close()}},{key:"clearNotifications",value:function(e){var t,i;null==e||e.stopPropagation(),null===(t=document.querySelector(".dice_notification_controls"))||void 0===t||t.classList.add("animated","bounceOutRight"),E().closeAll(),this._historyMode="uncollapse",null===(i=document.querySelector(".noty_layout"))||void 0===i||i.classList.remove("collapse","uncollapse")}}]),e}(),A=function(){function e(t,i){_(this,e),x(this,"_diceManager",void 0),x(this,"_context",void 0),this._diceManager=t,this._context=i}return y(e,[{key:"roll",value:function(e,t,i){return e.context=this._context,this._diceManager.roll(e,t,i)}}]),e}();function P(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}function R(e){return function(e){if(Array.isArray(e))return P(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return P(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?P(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var M=o(8099);const I=Symbol.for("@dndbeyond/message-broker-lib");var D,O;const w=new URLSearchParams(location.search),N="true"===w.get("disableMb")&&"true"===w.get("disableLayout")&&w.has("userId");window.mobileApp||(window.mobileApp={}),window.mobileApp.subscribers||(window.mobileApp.subscribers=new Set),window.mobileApp.gameLogCallback||(window.mobileApp.gameLogCallback=e=>{var t,i;return null===(i=null===(t=window.mobileApp)||void 0===t?void 0:t.subscribers)||void 0===i?void 0:i.forEach((t=>t(e)))});const F={gameId:null!==(D=w.get("gameId"))&&void 0!==D?D:"0",userId:null!==(O=w.get("userId"))&&void 0!==O?O:"0",source:"",connectUrl:"",getMessagesUrl:"",fetchHistory:()=>Promise.resolve(),subscribe:e=>{var t,i;return null===(i=null===(t=window.mobileApp)||void 0===t?void 0:t.subscribers)||void 0===i||i.add(e),()=>{var t,i;return null===(i=null===(t=window.mobileApp)||void 0===t?void 0:t.subscribers)||void 0===i?void 0:i.delete(e)}},dispatch:e=>(e=>{var t,i,n,s,r,o;(null===(i=null===(t=window.webkit)||void 0===t?void 0:t.messageHandlers.mobileApp)||void 0===i?void 0:i.postMessage)?null===(s=null===(n=window.webkit)||void 0===n?void 0:n.messageHandlers.mobileApp)||void 0===s||s.postMessage(e):(null===(r=window.mobileApp)||void 0===r?void 0:r.postMessage)&&(null===(o=window.mobileApp)||void 0===o||o.postMessage(e))})(JSON.stringify(Object.assign({type:"gameLog"},e)))};var L,B;o(1932),function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(L||(L={})),new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,function(e){e.Pending="pending",e.Fulfilled="fulfilled",e.Rejected="rejected"}(B||(B={}));var U,V=o(1297),k=o.n(V),G=new Uint8Array(16);function z(){if(!U&&!(U="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return U(G)}const W=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var H=[],X=0;X<256;++X)H.push((X+256).toString(16).substr(1));const j=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=(H[e[t+0]]+H[e[t+1]]+H[e[t+2]]+H[e[t+3]]+"-"+H[e[t+4]]+H[e[t+5]]+"-"+H[e[t+6]]+H[e[t+7]]+"-"+H[e[t+8]]+H[e[t+9]]+"-"+H[e[t+10]]+H[e[t+11]]+H[e[t+12]]+H[e[t+13]]+H[e[t+14]]+H[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&W.test(e)}(i))throw TypeError("Stringified UUID is invalid");return i},Y=function(e,t,i){var n=(e=e||{}).random||(e.rng||z)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){i=i||0;for(var s=0;s<16;++s)t[i+s]=n[s];return t}return j(n)},q={d4:{dieType:r.d4,meshName:"d4",size:.1,meshSizeMultiplier:1.6,tab:-.1,af:7*Math.PI/6,chamfer:.96,vertices:[[1,1,1],[-1,-1,1],[-1,1,-1],[1,-1,-1]],faces:[[1,0,2,1],[0,1,3,2],[0,3,2,3],[1,2,3,4]],scaleFactor:1.2,values:4,faceTexts:[[],["0","0","0"],["2","4","3"],["1","3","4"],["2","1","4"],["1","2","3"]],textMargin:0,numberValues:{1:1,2:3,3:2,4:4},mass:6,inertia:5,invertUpside:!0,textureName:"d4_texture",baseRotation:{x:-35.26,y:28,z:45},baseHeight:.25},d6:{dieType:r.d6,meshName:"d6",size:.1,meshSizeMultiplier:1.3,tab:.1,af:Math.PI/4,chamfer:.96,vertices:[[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],faces:[[0,3,2,1,1],[1,2,6,5,2],[0,1,5,4,3],[3,7,6,2,4],[0,4,7,3,5],[4,5,6,7,6]],scaleFactor:.9,values:6,faceTexts:[" ","0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"],numberValues:{1:4,2:5,3:1,4:6,5:2,6:3},textMargin:1,mass:6,inertia:13,invertUpside:!1,textureName:"d6_texture",baseRotation:{x:0,y:90,z:0},baseHeight:.25},d8:{dieType:r.d8,meshName:"d8",size:.1,meshSizeMultiplier:1.4,tab:0,af:-Math.PI/4/2,chamfer:.965,vertices:[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]],faces:[[0,2,4,1],[0,4,3,2],[0,3,5,3],[0,5,2,4],[1,3,4,5],[1,4,2,6],[1,2,5,7],[1,5,3,8]],scaleFactor:1.6,values:8,faceTexts:[" ","0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"],numberValues:{0:0,1:4,2:2,3:7,4:1,5:8,6:6,7:3,8:5},textMargin:1.2,mass:6.8,inertia:10,invertUpside:!1,textureName:"d8_texture",baseRotation:{x:-35.26,y:149.4,z:-135},baseHeight:.15},d10:{dieType:r.d10,meshName:"d10",size:.1,meshSizeMultiplier:1.4,tab:0,af:6*Math.PI/5,chamfer:.945,vertices:[[1,0,-.105],[.8090169943749475,.5877852522924731,.105],[.30901699437494745,.9510565162951535,-.105],[-.30901699437494734,.9510565162951536,.105],[-.8090169943749473,.5877852522924732,-.105],[-1,12246467991473532e-32,.105],[-.8090169943749475,-.587785252292473,-.105],[-.30901699437494756,-.9510565162951535,.105],[.30901699437494723,-.9510565162951536,-.105],[.8090169943749473,-.5877852522924734,.105],[0,0,-1],[0,0,1]],faces:[[5,7,11,0],[4,2,10,1],[1,3,11,2],[0,8,10,3],[7,9,11,4],[8,6,10,5],[9,1,11,6],[2,0,10,7],[3,5,11,8],[6,4,10,9],[1,0,2,-1],[1,2,3,-1],[3,2,4,-1],[3,4,5,-1],[5,4,6,-1],[5,6,7,-1],[7,6,8,-1],[7,8,9,-1],[9,8,0,-1],[9,0,1,-1]],scaleFactor:1.6,values:10,faceTexts:[" ","0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"],numberValues:{0:6,1:7,2:10,3:5,4:2,5:9,6:8,7:3,8:4,9:1},textMargin:1,mass:7,inertia:9,invertUpside:!1,textureName:"d10_texture",baseRotation:{x:-42.14,y:271.7,z:17.92},baseHeight:.25},d12:{dieType:r.d12,meshName:"d12",size:.1,meshSizeMultiplier:1.7,tab:.2,af:-Math.PI/4/2,chamfer:.968,vertices:[[0,.6180339887498948,1.618033988749895],[0,.6180339887498948,-1.618033988749895],[0,-.6180339887498948,1.618033988749895],[0,-.6180339887498948,-1.618033988749895],[1.618033988749895,0,.6180339887498948],[1.618033988749895,0,-.6180339887498948],[-1.618033988749895,0,.6180339887498948],[-1.618033988749895,0,-.6180339887498948],[.6180339887498948,1.618033988749895,0],[.6180339887498948,-1.618033988749895,0],[-.6180339887498948,1.618033988749895,0],[-.6180339887498948,-1.618033988749895,0],[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],[-1,1,1],[-1,1,-1],[-1,-1,1],[-1,-1,-1]],faces:[[2,14,4,12,0,1],[15,9,11,19,3,2],[16,10,17,7,6,3],[6,7,19,11,18,4],[6,18,2,0,16,5],[18,11,9,14,2,6],[1,17,10,8,13,7],[1,13,5,15,3,8],[13,8,12,4,5,9],[5,4,14,9,15,10],[0,12,8,10,16,11],[3,19,7,17,1,12]],scaleFactor:.9,values:12,faceTexts:[" ","0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"],numberValues:{1:5,2:11,3:8,4:7,5:9,6:10,7:2,8:3,9:1,10:4,11:6,12:12},textMargin:1,mass:7,inertia:8,invertUpside:!1,textureName:"d12_texture",baseRotation:{x:58.28,y:343,z:-90},baseHeight:.25},d20:{dieType:r.d20,meshName:"d20",size:.1,meshSizeMultiplier:1.7,tab:-.2,af:-Math.PI/4/2,chamfer:.955,vertices:[[-1,1.618033988749895,0],[1,1.618033988749895,0],[-1,-1.618033988749895,0],[1,-1.618033988749895,0],[0,-1,1.618033988749895],[0,1,1.618033988749895],[0,-1,-1.618033988749895],[0,1,-1.618033988749895],[1.618033988749895,0,-1],[1.618033988749895,0,1],[-1.618033988749895,0,-1],[-1.618033988749895,0,1]],faces:[[0,11,5,1],[0,5,1,2],[0,1,7,3],[0,7,10,4],[0,10,11,5],[1,5,9,6],[5,11,4,7],[11,10,2,8],[10,7,6,9],[7,1,8,10],[3,9,4,11],[3,4,2,12],[3,2,6,13],[3,6,8,14],[3,8,9,15],[4,9,5,16],[2,4,11,17],[6,2,10,18],[8,6,7,19],[9,8,1,20]],scaleFactor:1,values:20,faceTexts:[" ","0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"],numberValues:{1:18,2:4,3:11,4:13,5:5,6:14,7:2,8:15,9:1,10:9,11:8,12:10,13:17,14:3,15:16,16:20,17:12,18:7,19:19,20:6},textMargin:1,mass:8,inertia:6,invertUpside:!1,textureName:"d20_texture",baseRotation:{x:-69.09,y:-29,z:90},baseHeight:.25},d100:{dieType:r.d100,meshName:"d10",size:.1,meshSizeMultiplier:1.4,tab:0,af:6*Math.PI/5,chamfer:.945,vertices:[[1,0,-.105],[.8090169943749475,.5877852522924731,.105],[.30901699437494745,.9510565162951535,-.105],[-.30901699437494734,.9510565162951536,.105],[-.8090169943749473,.5877852522924732,-.105],[-1,12246467991473532e-32,.105],[-.8090169943749475,-.587785252292473,-.105],[-.30901699437494756,-.9510565162951535,.105],[.30901699437494723,-.9510565162951536,-.105],[.8090169943749473,-.5877852522924734,.105],[0,0,-1],[0,0,1]],faces:[[5,7,11,0],[4,2,10,1],[1,3,11,2],[0,8,10,3],[7,9,11,4],[8,6,10,5],[9,1,11,6],[2,0,10,7],[3,5,11,8],[6,4,10,9],[1,0,2,-1],[1,2,3,-1],[3,2,4,-1],[3,4,5,-1],[5,4,6,-1],[5,6,7,-1],[7,6,8,-1],[7,8,9,-1],[9,8,0,-1],[9,0,1,-1]],scaleFactor:1.6,values:100,faceTexts:[" ","00","10","20","30","40","50","60","70","80","90","100","11","12","13","14","15","16","17","18","19","20"],numberValues:{0:60,1:70,2:0,3:50,4:20,5:90,6:80,7:30,8:40,9:10},textMargin:1,mass:7,inertia:9,invertUpside:!1,textureName:"d100_texture",baseRotation:{x:-42.14,y:271.7,z:17.92},baseHeight:.25}};var K=function(e){return e[e.None=0]="None",e[e.Low=1]="Low",e[e.Medium=2]="Medium",e[e.High=3]="High",e}({});const $={SoundEnabled:!1,MasterVolume:1,Vibrate:!1,Particles:!0,Aliasing:!0,clearRender:!0,Shadow:K.High,GlowIntensity:.75,AutoClearSeconds:7.5,CameraStartHeight:7.2,CameraFOV:.35,CameraUpperBetaLimit:Math.PI/2,CameraLowerBetaLimit:-Math.PI/2,CameraUpperRadiusLimit:5,CameraLowerRadiusLimit:.4,CameraWheelPrecision:75,CameraMinZ:.01,PreviewCameraStartHeight:1,PreviewCameraFOV:.8,ShadowFrustumSize:5,environmentTexture:"environmentSpecular.env"};var Q=function(e){return e[e.rollBegin=0]="rollBegin",e[e.collision=1]="collision",e[e.rollComplete=2]="rollComplete",e[e.minRoll=3]="minRoll",e[e.maxRoll=4]="maxRoll",e[e.dieRemoved=5]="dieRemoved",e}({}),Z=function(e){return e[e.NONE=0]="NONE",e[e.START=1]="START",e[e.STOP=2]="STOP",e[e.RESET=3]="RESET",e}({}),J=function(e){return e[e.DistanceBetween=.35]="DistanceBetween",e[e.StartHeight=1]="StartHeight",e[e.BaseStrength=5]="BaseStrength",e[e.AddPerDieStrength=.2]="AddPerDieStrength",e[e.StrengthHeight=1]="StrengthHeight",e[e.Gravity=-9.82]="Gravity",e[e.DiceFriction=.01]="DiceFriction",e[e.DiceRestitution=.9]="DiceRestitution",e[e.FloorFriction=.4]="FloorFriction",e[e.FloorRestitution=.15]="FloorRestitution",e[e.BarrierFriction=.25]="BarrierFriction",e[e.BarrierRestitution=.15]="BarrierRestitution",e}(J||{});const ee=J;function te(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function ie(e,t){return ie=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},ie(e,t)}function ne(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ie(e,t)}function se(e,t){if(t&&("object"===m(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return te(e)}function re(e){return re=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},re(e)}const oe=function(){function e(t){if(_(this,e),x(this,"memory",void 0),x(this,"Console",void 0),x(this,"attachedObject",void 0),this.attachedObject=t,this.isDebugMode())for(var i in console)"function"==typeof console[i]&&(this[i]=console[i].bind(window.console,"🎲[".concat(this.attachedObject.constructor.name,"] ")))}return y(e,[{key:"assert",value:function(e,t){}},{key:"clear",value:function(){}},{key:"count",value:function(e){}},{key:"debug",value:function(e){}},{key:"dir",value:function(e,t){}},{key:"dirxml",value:function(){}},{key:"error",value:function(e){}},{key:"exception",value:function(e){}},{key:"group",value:function(){}},{key:"groupCollapsed",value:function(){}},{key:"groupEnd",value:function(){}},{key:"info",value:function(e){}},{key:"log",value:function(e){}},{key:"markTimeline",value:function(e){}},{key:"profile",value:function(e){}},{key:"profileEnd",value:function(e){}},{key:"table",value:function(e,t){}},{key:"time",value:function(e){}},{key:"timeEnd",value:function(e){}},{key:"timeStamp",value:function(e){}},{key:"timeline",value:function(e){}},{key:"timelineEnd",value:function(e){}},{key:"trace",value:function(e){}},{key:"warn",value:function(e){}},{key:"countReset",value:function(e){}},{key:"timeLog",value:function(e){}},{key:"isDebugMode",value:function(){return!!(window.location.search&&window.location.search.indexOf("dice-debug")>0)}}]),e}();function ae(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var i,n=re(e);if(t){var s=re(this).constructor;i=Reflect.construct(n,arguments,s)}else i=n.apply(this,arguments);return se(this,i)}}var le=y((function e(t,i){_(this,e),x(this,"type",void 0),x(this,"key",void 0),x(this,"resourceUrl",void 0),this.key=t,this.resourceUrl=i})),he=function(e){ne(i,e);var t=ae(i);function i(e,n){var s;return _(this,i),(s=t.call(this,e,n)).type="mesh",s}return y(i)}(le),ce=y((function e(t,i){_(this,e),x(this,"key",void 0),x(this,"sound",void 0),x(this,"type",void 0),this.key=t,this.sound=i,this.type="sound"})),ue=function(e){ne(i,e);var t=ae(i);function i(e,n){var s;return _(this,i),(s=t.call(this,e,n)).type="texture",s}return y(i)}(le),de=function(e){ne(i,e);var t=ae(i);function i(e,n){var s;return _(this,i),(s=t.call(this,e,n)).type="particleSystem",s}return y(i)}(le),pe=function(e){ne(i,e);var t=ae(i);function i(e,n,s){var r;return _(this,i),x(te(r=t.call(this,e,n)),"clones",void 0),r.clones=s,r.type="animationGroup",r}return y(i)}(le),fe=function(){function e(){_(this,e),x(this,"textures",void 0),x(this,"sounds",void 0),x(this,"shaders",void 0),x(this,"particleSystems",void 0),x(this,"animationGroups",void 0),x(this,"assetContainers",void 0),x(this,"logger",void 0),this.logger=new oe(this),this.textures=new Map,this.sounds=new Map,this.shaders=new Map,this.particleSystems=new Map,this.animationGroups=new Map,this.assetContainers=new Map}return y(e,[{key:"instantiateContainer",value:function(e){var t=this.assetContainers[e];return t?t.instantiateModelsToScene((function(e){return"".concat(e)}),!0):null}},{key:"createShaderMaterial",value:function(e,t,i,n){var s=["world","worldView","worldViewProjection","view","projection","iGlobalTime","dieType","lastEvent","lastEventTime"];n&&s.push.apply(s,R(Object.keys(n)));var r=new M.ShaderMaterial(e,null,{vertex:i.key,fragment:i.key},{attributes:["position","normal","uv"],uniforms:s});return r.setFloat("iGlobalTime",0),r.setInt("lastEvent",0),r.setFloat("lastEventTime",0),r.setInt("dieType",0),this.deserializeUniforms(n,t).forEach((function(e){return e(r)})),r}},{key:"deserializeUniforms",value:function(e,t){var i=this,n=[];return e&&Object.keys(e).forEach((function(s){var r=e[s];if("texture"===r.type){var o=i.getTexture(r.value,t);if(!o)return void i.logger.warn("Could not load texture ".concat(r.value," for uniform ").concat(s));o.isReady||i.logger.warn("tex ".concat(o.name," not ready")),n.push((function(e){return e.setTexture(s,o)}))}else if("color"===r.type){var a=M.Color3.FromHexString(r.value);n.push((function(e){return e.setColor3(s,a)}))}else if("number"===r.type||"float"===r.type)n.push((function(e){return e.setFloat(s,r.value)}));else{if("int"!==r.type)throw"Unsupported uniform type ".concat(r.type);n.push((function(e){return e.setInt(s,r.value)}))}})),n}},{key:"getTexture",value:function(e,t){return this.textures[e]||null}},{key:"getSound",value:function(e){return this.sounds[e]||null}},{key:"getShader",value:function(e){return this.shaders[e]||null}},{key:"getParticleSystem",value:function(e,t){var i=this.particleSystems[e];return i?i.clone(i.name,t):null}},{key:"getAnimationGroup",value:function(e,t,i){var n=this.animationGroups[e];if(!n)return null;var s=JSON.parse(n);if(!s)return null;if(s.targetedAnimations&&s.targetedAnimations.length>0)for(var r=function(){var e,t,n=s.targetedAnimations[o],r=n.targetId,a="".concat(i.uniqueId,"-").concat(r),l=i.getChildMeshes(!1,(function(e){return e.id==r||e.id==a}));l&&1===l.length&&(l[0].id=a,n.targetId=a),null===(e=n.animation)||void 0===e||null===(t=e.keys)||void 0===t||t.forEach((function(e){var t;e.values=null===(t=e.values)||void 0===t?void 0:t.map((function(e){return"randomRotation"===e&&(e=Math.random()*Math.PI*2),e}))}))},o=0;o<s.targetedAnimations.length;o++)r();return M.AnimationGroup.Parse(s,t)}},{key:"clearTextureCache",value:function(){var e=this;Object.keys(this.textures).forEach((function(t){e.textures[t].dispose()})),this.textures.clear()}},{key:"addToTextureCache",value:function(e,t){this.textures[e]=t}},{key:"addToSoundCache",value:function(e,t){this.sounds[e]=t}},{key:"addToShaderCache",value:function(e,t){this.shaders[e]=t}},{key:"addToParticleSystemCache",value:function(e,t){this.particleSystems[e]=t}},{key:"addToAnimationGroupCache",value:function(e,t){this.animationGroups[e]=t}},{key:"addAssetContainer",value:function(e,t){this.assetContainers[e]=t}}]),e}();const _e=new fe;var me=function(e){ne(s,e);var t,i,n=(t=s,i=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,n=re(t);if(i){var s=re(this).constructor;e=Reflect.construct(n,arguments,s)}else e=n.apply(this,arguments);return se(this,e)});function s(e,t,i){var r;_(this,s);var o=_e.getShader(i);return x(te(r=n.call(this,"DepthDieMaterial",e,{fragmentSource:o.key,vertexSource:o.key})),"dissolveMap",void 0),x(te(r),"dissolveValue",void 0),r}return y(s)}(M.ShaderMaterial),ge=function(){function e(t,i){_(this,e),x(this,"velocity",new M.Vector3),x(this,"angularVelocity",new M.Vector3),x(this,"maxWobble",.13),x(this,"wobbleSpeed",1),x(this,"recovery",2),x(this,"wobbleAmountX",0),x(this,"wobbleAmountZ",0),x(this,"wobbleAmountToAddX",0),x(this,"wobbleAmountToAddZ",0),x(this,"pulse",0),x(this,"lastPos",new M.Vector3),x(this,"lastRot",new M.Vector3),x(this,"time",0),x(this,"deltaTime",0),x(this,"objectPositionName",void 0),x(this,"cutName",void 0),x(this,"wobbleXName",void 0),x(this,"wobbleZName",void 0),x(this,"mesh",void 0),x(this,"rootMesh",void 0),this.mesh=t,this.rootMesh=i,this.objectPositionName=this.mesh.material.getBlockByName("ObjectPosition").output.associatedVariableName,this.cutName=this.mesh.material.getBlockByName("Cut").output.associatedVariableName,this.mesh.material.Cut=this.mesh.material.getBlockByName("Cut"),this.wobbleXName=this.mesh.material.getBlockByName("WobbleX").output.associatedVariableName,this.wobbleZName=this.mesh.material.getBlockByName("WobbleZ").output.associatedVariableName}return y(e,[{key:"lerp",value:function(e,t,i){return e*(1-i)+t*i}},{key:"clamp",value:function(e,t,i){return e<=t?t:e>=i?i:e}},{key:"Update",value:function(e){this.deltaTime=e,this.time+=this.deltaTime,this.wobbleAmountToAddX=this.lerp(this.wobbleAmountToAddX,0,this.deltaTime*this.recovery),this.wobbleAmountToAddZ=this.lerp(this.wobbleAmountToAddZ,0,this.deltaTime*this.recovery),this.pulse=2*Math.PI*this.wobbleSpeed,this.wobbleAmountX=this.wobbleAmountToAddX*Math.sin(this.pulse*this.time),this.wobbleAmountZ=this.wobbleAmountToAddZ*Math.sin(this.pulse*this.time);var t=this.mesh.material.getEffect();t.setFloat(this.wobbleXName,this.wobbleAmountX),t.setFloat(this.wobbleZName,this.wobbleAmountZ),t.setVector3(this.objectPositionName,this.rootMesh.position),this.velocity=this.lastPos.subtract(this.rootMesh.position).divide(new M.Vector3(this.deltaTime,this.deltaTime,this.deltaTime)),this.angularVelocity=this.rootMesh.rotation.subtract(this.lastRot),this.wobbleAmountToAddX+=this.clamp((this.velocity.x+.2*this.angularVelocity.z)*this.maxWobble,-this.maxWobble,this.maxWobble),this.wobbleAmountToAddZ+=this.clamp((this.velocity.z+.2*this.angularVelocity.x)*this.maxWobble,-this.maxWobble,this.maxWobble),this.lastPos=this.rootMesh.position.clone(),this.lastRot=this.rootMesh.rotation.clone()}}]),e}();function ve(e,t,i,n){i&&Object.defineProperty(e,t,{enumerable:i.enumerable,configurable:i.configurable,writable:i.writable,value:i.initializer?i.initializer.call(n):void 0})}function ye(){return ye="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,i){var n=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=re(e)););return e}(e,t);if(n){var s=Object.getOwnPropertyDescriptor(n,t);return s.get?s.get.call(arguments.length<3?e:i):s.value}},ye.apply(this,arguments)}function xe(e,t,i,n,s){var r={};return Object.keys(n).forEach((function(e){r[e]=n[e]})),r.enumerable=!!r.enumerable,r.configurable=!!r.configurable,("value"in r||r.initializer)&&(r.writable=!0),r=i.slice().reverse().reduce((function(i,n){return n(e,t,i)||i}),r),s&&void 0!==r.initializer&&(r.value=r.initializer?r.initializer.call(s):void 0,r.initializer=void 0),void 0===r.initializer&&(Object.defineProperty(e,t,r),r=null),r}var be=o(4649),Te=o(4141);const Se="\n\nvarying vec3 vPosition;\n\n\n";var Ee=o(1979),Ce=o(9500),Ae=o(2208);var Pe,Re,Me,Ie,De,Oe,we,Ne,Fe,Le,Be,Ue,Ve,ke,Ge,ze,We,He,Xe,je,Ye,qe,Ke,$e,Qe,Ze,Je,et,tt,it,nt,st,rt,ot=y((function e(){_(this,e),x(this,"Fragment_Begin",void 0),x(this,"Fragment_Definitions",void 0),x(this,"Fragment_MainBegin",void 0),x(this,"Fragment_Custom_Albedo",void 0),x(this,"Fragment_Before_Lights",void 0),x(this,"Fragment_Custom_MetallicRoughness",void 0),x(this,"Fragment_Custom_MicroSurface",void 0),x(this,"Fragment_Before_Fog",void 0),x(this,"Fragment_Custom_Alpha",void 0),x(this,"Fragment_Before_FragColor",void 0),x(this,"Vertex_Begin",void 0),x(this,"Vertex_Definitions",void 0),x(this,"Vertex_MainBegin",void 0),x(this,"Vertex_Before_PositionUpdated",void 0),x(this,"Vertex_Before_NormalUpdated",void 0),x(this,"Vertex_MainEnd",void 0)})),at=function(e){ne(s,e);var t,i,n=(t=s,i=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,n=re(t);if(i){var s=re(this).constructor;e=Reflect.construct(n,arguments,s)}else e=n.apply(this,arguments);return se(this,e)});function s(e,t){var i;return _(this,s),x(te(i=n.call(this,e,t)),"CustomParts",void 0),x(te(i),"_isCreatedShader",void 0),x(te(i),"_createdShaderName",void 0),x(te(i),"_customUniform",void 0),x(te(i),"_newUniforms",void 0),x(te(i),"_newUniformInstances",void 0),x(te(i),"_newSamplerInstances",void 0),x(te(i),"_customAttributes",void 0),x(te(i),"FragmentShader",void 0),x(te(i),"VertexShader",void 0),i.CustomParts=new ot,i.customShaderNameResolve=i.Builder,i.FragmentShader=Ee.Q.ShadersStore.pbrPixelShader,i.VertexShader=Ee.Q.ShadersStore.pbrVertexShader,i}return y(s,[{key:"AttachAfterBind",value:function(e,t){for(var i=0;i<this._newUniformInstances.length;i++)"vec2"==(n=i.toString().split("-"))[0]?t.setVector2(n[1],this._newUniformInstances[i]):"vec3"==n[0]?t.setVector3(n[1],this._newUniformInstances[i]):"vec4"==n[0]?t.setVector4(n[1],this._newUniformInstances[i]):"mat4"==n[0]?t.setMatrix(n[1],this._newUniformInstances[i]):"float"==n[0]&&t.setFloat(n[1],this._newUniformInstances[i]);for(i=0;i<this._newSamplerInstances.length;i++){var n;"sampler2D"==(n=i.toString().split("-"))[0]&&this._newSamplerInstances[i].isReady&&this._newSamplerInstances[i].isReady()&&t.setTexture(n[1],this._newSamplerInstances[i])}}},{key:"ReviewUniform",value:function(e,t){if("uniform"==e)for(var i=0;i<this._newUniforms.length;i++)-1==this._customUniform[i].indexOf("sampler")&&t.push(this._newUniforms[i]);if("sampler"==e)for(i=0;i<this._newUniforms.length;i++)-1!=this._customUniform[i].indexOf("sampler")&&t.push(this._newUniforms[i]);return t}},{key:"Builder",value:function(e,t,i,n,r,o){var a=this;if(o&&this._customAttributes&&this._customAttributes.length>0&&o.push.apply(o,R(this._customAttributes)),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",n),this._isCreatedShader)return this._createdShaderName;this._isCreatedShader=!1,s.ShaderIndexer++;var l="custom_"+s.ShaderIndexer,h=this._afterBind.bind(this);return this._afterBind=function(e,t){if(t){a.AttachAfterBind(e,t);try{h(e,t)}catch(t){}}},Ee.Q.ShadersStore[l+"VertexShader"]=this.VertexShader.replace("#define CUSTOM_VERTEX_BEGIN",this.CustomParts.Vertex_Begin?this.CustomParts.Vertex_Begin:"").replace("#define CUSTOM_VERTEX_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Vertex_Definitions?this.CustomParts.Vertex_Definitions:"")).replace("#define CUSTOM_VERTEX_MAIN_BEGIN",this.CustomParts.Vertex_MainBegin?this.CustomParts.Vertex_MainBegin:"").replace("#define CUSTOM_VERTEX_UPDATE_POSITION",this.CustomParts.Vertex_Before_PositionUpdated?this.CustomParts.Vertex_Before_PositionUpdated:"").replace("#define CUSTOM_VERTEX_UPDATE_NORMAL",this.CustomParts.Vertex_Before_NormalUpdated?this.CustomParts.Vertex_Before_NormalUpdated:"").replace("#define CUSTOM_VERTEX_MAIN_END",this.CustomParts.Vertex_MainEnd?this.CustomParts.Vertex_MainEnd:""),Ee.Q.ShadersStore[l+"PixelShader"]=this.FragmentShader.replace("#define CUSTOM_FRAGMENT_BEGIN",this.CustomParts.Fragment_Begin?this.CustomParts.Fragment_Begin:"").replace("#define CUSTOM_FRAGMENT_MAIN_BEGIN",this.CustomParts.Fragment_MainBegin?this.CustomParts.Fragment_MainBegin:"").replace("#define CUSTOM_FRAGMENT_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Fragment_Definitions?this.CustomParts.Fragment_Definitions:"")).replace("#define CUSTOM_FRAGMENT_UPDATE_ALBEDO",this.CustomParts.Fragment_Custom_Albedo?this.CustomParts.Fragment_Custom_Albedo:"").replace("#define CUSTOM_FRAGMENT_UPDATE_ALPHA",this.CustomParts.Fragment_Custom_Alpha?this.CustomParts.Fragment_Custom_Alpha:"").replace("#define CUSTOM_FRAGMENT_BEFORE_LIGHTS",this.CustomParts.Fragment_Before_Lights?this.CustomParts.Fragment_Before_Lights:"").replace("#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS",this.CustomParts.Fragment_Custom_MetallicRoughness?this.CustomParts.Fragment_Custom_MetallicRoughness:"").replace("#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE",this.CustomParts.Fragment_Custom_MicroSurface?this.CustomParts.Fragment_Custom_MicroSurface:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FOG",this.CustomParts.Fragment_Before_Fog?this.CustomParts.Fragment_Before_Fog:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR",this.CustomParts.Fragment_Before_FragColor?this.CustomParts.Fragment_Before_FragColor:""),this._isCreatedShader=!0,this._createdShaderName=l,l}},{key:"AddUniform",value:function(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances=new Array,this._newUniformInstances=new Array),i&&(t.indexOf("sampler"),this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}},{key:"AddAttribute",value:function(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}},{key:"Fragment_Begin",value:function(e){return this.CustomParts.Fragment_Begin=e,this}},{key:"Fragment_Definitions",value:function(e){return this.CustomParts.Fragment_Definitions=e,this}},{key:"Fragment_MainBegin",value:function(e){return this.CustomParts.Fragment_MainBegin=e,this}},{key:"Fragment_Custom_Albedo",value:function(e){return this.CustomParts.Fragment_Custom_Albedo=e.replace("result","surfaceAlbedo"),this}},{key:"Fragment_Custom_Alpha",value:function(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}},{key:"Fragment_Before_Lights",value:function(e){return this.CustomParts.Fragment_Before_Lights=e,this}},{key:"Fragment_Custom_MetallicRoughness",value:function(e){return this.CustomParts.Fragment_Custom_MetallicRoughness=e,this}},{key:"Fragment_Custom_MicroSurface",value:function(e){return this.CustomParts.Fragment_Custom_MicroSurface=e,this}},{key:"Fragment_Before_Fog",value:function(e){return this.CustomParts.Fragment_Before_Fog=e,this}},{key:"Fragment_Before_FragColor",value:function(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}},{key:"Vertex_Begin",value:function(e){return this.CustomParts.Vertex_Begin=e,this}},{key:"Vertex_Definitions",value:function(e){return this.CustomParts.Vertex_Definitions=e,this}},{key:"Vertex_MainBegin",value:function(e){return this.CustomParts.Vertex_MainBegin=e,this}},{key:"Vertex_Before_PositionUpdated",value:function(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}},{key:"Vertex_Before_NormalUpdated",value:function(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}},{key:"Vertex_MainEnd",value:function(e){return this.CustomParts.Vertex_MainEnd=e,this}}]),s}(Ce.Y);x(at,"ShaderIndexer",1),(0,Ae.H)("BABYLON.PBRCustomMaterial",at);var lt=(Pe=(0,M.serialize)(),Re=(0,M.serializeAsTexture)("numberTexture"),Me=(0,M.serializeAsColor3)("numberColor"),Ie=(0,M.serializeAsColor3)("numberHighlightColor"),De=(0,M.serialize)(),Oe=(0,M.serializeAsTexture)("dissolveTexture"),we=(0,M.serialize)(),Ne=(0,M.serializeAsTexture)("glitterNoiseTexture"),Fe=(0,M.serializeAsTexture)("glitterPatternTexture"),Le=(0,M.serialize)(),Be=(0,M.serialize)(),Ue=(0,M.serialize)(),Ve=(0,M.serialize)(),ke=(0,M.serialize)(),Ge=(0,M.serialize)(),ze=(0,M.serialize)(),We=function(e){ne(s,e);var t,i,n=(t=s,i=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,n=re(t);if(i){var s=re(this).constructor;e=Reflect.construct(n,arguments,s)}else e=n.apply(this,arguments);return se(this,e)});function s(e,t){var i;return _(this,s),ve(te(i=n.call(this,e,t)),"dieType",He,te(i)),ve(te(i),"numberTexture",Xe,te(i)),ve(te(i),"numberColor",je,te(i)),ve(te(i),"numberHighlightColor",Ye,te(i)),ve(te(i),"numberBumpScale",qe,te(i)),ve(te(i),"dissolveTexture",Ke,te(i)),ve(te(i),"glitterScale",$e,te(i)),ve(te(i),"glitterNoiseTexture",Qe,te(i)),ve(te(i),"glitterPatternTexture",Ze,te(i)),ve(te(i),"dissolveValue",Je,te(i)),ve(te(i),"useNumbers",et,te(i)),ve(te(i),"marbleAmplitude",tt,te(i)),ve(te(i),"marbleTiming",it,te(i)),ve(te(i),"marbleZoom",nt,te(i)),ve(te(i),"numbersMode",st,te(i)),ve(te(i),"fadeSpeed",rt,te(i)),i.AddUniform("iGlobalTime","float",0),i.AddUniform("dieType","lowp int",0),i.AddUniform("numberTexture","sampler2D",null),i.AddUniform("numberBumpScale","float",-i.numberBumpScale),i.AddUniform("numberColor","vec3",new Te.P(.8,.8,.8)),i.AddUniform("numberHighlightColor","vec3",new Te.P(1,1,1)),i.AddUniform("numberFadeCutoff","float",i.useNumbers?1:.11),i.AddUniform("numbersMode","lowp int",0),i.AddUniform("fadeSpeed","float",0),i.AddUniform("topFaceNormal","vec3",null),i.AddUniform("dissolveTexture","sampler2D",null),i.AddUniform("dissolveEdgeColor","vec3",new Te.P(.8,.8,.8)),i.AddUniform("dissolveValue","float",0),i.AddUniform("lastEvent","lowp int",0),i.AddUniform("lastEventTime","float",0),i.AddUniform("dieValue","lowp int",0),i.AddUniform("glitterScale","float",0),i.AddUniform("glitterNoiseTexture","sampler2D",null),i.AddUniform("glitterPatternTexture","sampler2D",null),i.AddUniform("marbleNoiseTexture","sampler2D",null),i.AddUniform("marbleAmplitude","float",0),i.AddUniform("marbleTiming","float",.025),i.AddUniform("marbleZoom","float",.5),i.invertNormalMapX=!1,i.invertNormalMapY=!1,i.onBind=function(){return i.updateUniforms()},i.allowShaderHotSwapping=!0,i.customShaderNameResolve=i.Builder,i.setCustomInspectableProperties(),i}return y(s,[{key:"Builder",value:function(e,t,i,n,r){var o,a=this;null===(o=this.glitterNoiseTexture)||void 0===o||o.updateSamplingMode(1);var l=this.name;this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",n);var h=this._afterBind.bind(this);this._afterBind=function(e,t){if(t){a.AttachAfterBind(e,t);try{h(e,t)}catch(t){}}};var c=[];return this.numberTexture&&c.push("#define USE_NUMBERS"),this.marbleAmplitude>0&&this.albedoTexture&&c.push("#define USE_MARBLE"),this.Fragment_Definitions("\n"+c.join("\n")+"\n#ifdef USE_NUMBERS\n\n#define NUMBERS_DEFAULT 1\n#define NUMBERS_HIGHLIGHT_TOPFACE 2\n\n#define NUMBERS_PULSE 1\n#define NUMBERS_FADE_IN 2\n\n#define NUMBER_PULSE_SPEED 1.5\n#define D4_Y_CUTOFF 0.09\n\n// This controls how fine the number fadeouts are (zoom factor into noise map)\n#define NUMBER_FADE_FREQ 4.0\n\n#define vNumbersUV vBumpUV\n\nvec4 sampleNumbersTexture(vec2 coords) {\n // Invert colors so the numbers are white on black\n vec3 numText = texture2D(numberTexture, coords).rgb;\n return vec4(1.0 - numText, numText.r);\n}\n\nvec4 stampNumbers(vec3 normal, int mode) {\n if (gl_FrontFacing == false) {\n return vec4(0.0);\n }\n\n // Controls mix between number color and number highlight color\n lowp float glowAmount = 0.0;\n\n if (lastEvent >= 2 && (mode == NUMBERS_HIGHLIGHT_TOPFACE || mode == NUMBERS_PULSE || mode == NUMBERS_FADE_IN)) {\n if (dieType == 4) {\n glowAmount = vPositionW.y > D4_Y_CUTOFF ? 1.0 : 0.0;\n } else {\n // topFaceNormal refers to the normal of the face that is used as the roll result.\n // Determine how similar it is to the normal of the current pixel being processed.\n // If they are very similar, this pixel is on the top face. Make it glow!\n // We want the dotproduct to be between [-1.0,1.0] so normalize the two vectors.\n float dotY = dot(normalize(topFaceNormal), normalize(normal));\n if (dotY > 0.99) {\n glowAmount = 1.0;\n }\n }\n }\n\n // Get raw number texture\n vec2 numTex = sampleNumbersTexture(vec2(vNumbersUV)).xz;\n\n numTex.y *= numberFadeCutoff;\n\n if (mode == NUMBERS_PULSE) {\n glowAmount = glowAmount * (0.5 + 0.5*sin(NUMBER_PULSE_SPEED * iGlobalTime));\n } else if (mode == NUMBERS_FADE_IN) {\n float delta = lastEvent < 2 ? 0.0 : (iGlobalTime - lastEventTime);\n glowAmount = glowAmount * (1.0 - exp(-1.0 * pow((delta / fadeSpeed), 4.0)));\n }\n return vec4(numTex.x * mix(numberColor, numberHighlightColor, glowAmount), numTex.y);\n}\n\nvec2 computeNumbersDerivative() {\n vec2 dSTdx = dFdx( vNumbersUV );\n vec2 dSTdy = dFdy( vNumbersUV );\n float Hll = numberBumpScale * sampleNumbersTexture(vNumbersUV).x;\n float dBx = (numberBumpScale * sampleNumbersTexture(vNumbersUV + dSTdx ).x) - Hll;\n float dBy = (numberBumpScale * sampleNumbersTexture(vNumbersUV + dSTdy ).x) - Hll;\n return vec2( dBx, dBy );\n}\n\nvec3 perturbNormalArb2( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n vec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n vec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 );\n fDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n}\n\nvec3 bumpNumbers(vec3 normal) {\n return perturbNormalArb2(vPositionW, normal, computeNumbersDerivative());\n}\n#endif\n\n#ifdef USE_MARBLE\n#define NUM_OCTAVES 20\nvec2 domainWarp(vec2 coords) {\n float amplitude = marbleAmplitude;\n float accumulatedNoise = 0.0;\n vec2 noiseCoords = coords + float(dieType);\n for (int i = 0; i<NUM_OCTAVES; i++) {\n noiseCoords += iGlobalTime * marbleTiming;\n accumulatedNoise += amplitude * texture2D(marbleNoiseTexture, noiseCoords).r;\n amplitude *= marbleAmplitude;\n noiseCoords *= 2.0;\n }\n coords = vec2(coords.x, coords.y + accumulatedNoise);\n return coords;\n}\n\n#endif\n"+Se),this.Vertex_Definitions("\n"+Se+"\n"),this.Vertex_Before_NormalUpdated("\n\nvPosition = positionUpdated.xzy;\n\n\n"),this.Fragment_Before_Lights("#ifdef USE_NUMBERS\n normalW = bumpNumbers(normalW );\n#endif\n"),this.Fragment_Custom_Alpha("#ifdef USE_MARBLE\n\nvec2 warpUv = mix(\n vPosition.xy,\n vPosition.zx,\n vPosition.z\n)*marbleZoom;\nsurfaceAlbedo = toLinearSpace(texture2D(albedoSampler, domainWarp(warpUv)).rgb);\n\n#endif"),this.Fragment_Before_FragColor("\n#define vGlitterUV vBumpUV\nif (glitterScale > 0.0) {\n vec2 glitterNormalCoords = vGlitterUV * glitterScale;\n\n // This should be viewDirection in object space\n mat3 invTBN = transposeMat3(TBN);\n vec3 tanViewDir = invTBN * viewDirectionW;\n\n float glitterDepthScale = 1.0;\n float height = texture2D(glitterNoiseTexture, glitterNormalCoords).r;\n vec2 glitterUVOffset = -glitterDepthScale * tanViewDir.xy * height;\n\n // The normal for the piece of glitter you'd see at this angle\n vec3 glitterNormalMap = texture2D(glitterNoiseTexture, glitterNormalCoords + glitterUVOffset).rgb;\n // [0, 1] => [-0.5, 0.5] \n glitterNormalMap = glitterNormalMap -= 0.5;\n\n vec3 glitterColor = vec3(0.0);\n if (length(glitterNormalMap) > 0.1) {\n // then normalize to [-1, 1]\n glitterNormalMap = normalize(glitterNormalMap);\n\n vec3 l = -vPositionW.xyz;\n vec3 r = normalize(reflect(l, glitterNormalMap));\n float glitterReflectance = max(0., dot(viewDirectionW, r));\n glitterReflectance = pow(glitterReflectance, 2.0);\n //glitterReflectance = dot(viewDirectionW, glitterNormalMap);\n \n if (glitterReflectance > 0.0) {\n glitterColor = texture2D(glitterPatternTexture, glitterNormalCoords).rgb;\n glitterColor = (1.0 - height) * glitterReflectance * glitterColor;\n }\n\n finalColor = vec4(finalColor.rgb + glitterColor, finalColor.a);\n }\n}\n#ifdef USE_NUMBERS\n vec4 numColor = stampNumbers(vNormalW, numbersMode);\n \n // For pixels beyond a certain alpha value, add the number color to a mixed version of the current color\n // attenuated by the inverse of the number alpha We don't use mix() as that would premultiply the alpha \n // into the number color, and it already has been\n if (numColor.a > 0.1) {\n finalColor = vec4(numColor.rgb, max(numColor.a, finalColor.a));\n }\n \n if (gl_FrontFacing == true) {\n finalColor.a = max(finalColor.a, numColor.a);\n } \n \n#endif\n\nif (gl_FrontFacing == false) {\n finalColor.a *= 0.1;\n}\n\n#define vDissolveUV vBumpUV\n\n\nif (lastEvent > 4) {\n float n = texture2D(dissolveTexture, vPositionW.xz).x - dissolveValue;\n if(n < 0.0) { discard; }\n #ifdef USE_DISSOLVE_EDGE\n if(n < 0.05) { gl_FragColor.rgb = dissolveEdgeColor; }\n #endif\n}"),s.isDieShaderCreated(l)||(M.Effect.ShadersStore[l+"VertexShader"]=this.VertexShader.replace("#define CUSTOM_VERTEX_BEGIN",this.CustomParts.Vertex_Begin?this.CustomParts.Vertex_Begin:"").replace("#define CUSTOM_VERTEX_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Vertex_Definitions?this.CustomParts.Vertex_Definitions:"")).replace("#define CUSTOM_VERTEX_MAIN_BEGIN",this.CustomParts.Vertex_MainBegin?this.CustomParts.Vertex_MainBegin:"").replace("#define CUSTOM_VERTEX_UPDATE_POSITION",this.CustomParts.Vertex_Before_PositionUpdated?this.CustomParts.Vertex_Before_PositionUpdated:"").replace("#define CUSTOM_VERTEX_UPDATE_NORMAL",this.CustomParts.Vertex_Before_NormalUpdated?this.CustomParts.Vertex_Before_NormalUpdated:"").replace("#define CUSTOM_VERTEX_MAIN_END",this.CustomParts.Vertex_MainEnd?this.CustomParts.Vertex_MainEnd:""),M.Effect.ShadersStore[l+"PixelShader"]=this.FragmentShader.replace("#define CUSTOM_FRAGMENT_BEGIN",this.CustomParts.Fragment_Begin?this.CustomParts.Fragment_Begin:"").replace("#define CUSTOM_FRAGMENT_MAIN_BEGIN",this.CustomParts.Fragment_MainBegin?this.CustomParts.Fragment_MainBegin:"").replace("#define CUSTOM_FRAGMENT_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Fragment_Definitions?this.CustomParts.Fragment_Definitions:"")).replace("#define CUSTOM_FRAGMENT_UPDATE_ALBEDO",this.CustomParts.Fragment_Custom_Albedo?this.CustomParts.Fragment_Custom_Albedo:"").replace("#define CUSTOM_FRAGMENT_UPDATE_ALPHA",this.CustomParts.Fragment_Custom_Alpha?this.CustomParts.Fragment_Custom_Alpha:"").replace("#define CUSTOM_FRAGMENT_BEFORE_LIGHTS",this.CustomParts.Fragment_Before_Lights?this.CustomParts.Fragment_Before_Lights:"").replace("#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS",this.CustomParts.Fragment_Custom_MetallicRoughness?this.CustomParts.Fragment_Custom_MetallicRoughness:"").replace("#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE",this.CustomParts.Fragment_Custom_MicroSurface?this.CustomParts.Fragment_Custom_MicroSurface:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FOG",this.CustomParts.Fragment_Before_Fog?this.CustomParts.Fragment_Before_Fog:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR",this.CustomParts.Fragment_Before_FragColor?this.CustomParts.Fragment_Before_FragColor:"")),l}},{key:"setCustomInspectableProperties",value:function(){this.inspectableCustomProperties=[{label:"Number Bump Scale",propertyName:"numberBumpScale",type:M.InspectableType.Slider},{label:"Number Color",propertyName:"numberColor",type:M.InspectableType.Color3},{label:"Number Highlight Color",propertyName:"numberHighlightColor",type:M.InspectableType.Color3},{label:"Glitter Scale",propertyName:"glitterScale",type:M.InspectableType.Slider}]}},{key:"updateUniforms",value:function(){var e=this.getEffect();e.setInt("dieType",this.dieType),e.setTexture("numberTexture",this.numberTexture),e.setFloat("numberBumpScale",-this.numberBumpScale),e.setColor3("numberColor",this.numberColor),e.setColor3("numberHighlightColor",this.numberHighlightColor),e.setFloat("numberFadeCutoff",this.useNumbers?1:0),e.setInt("numbersMode",this.numbersMode),e.setFloat("fadeSpeed",this.fadeSpeed),e.setTexture("dissolveTexture",this.dissolveTexture),e.setFloat("dissolveValue",0),e.setFloat("glitterScale",this.glitterScale),this.glitterNoiseTexture&&e.setTexture("glitterNoiseTexture",this.glitterNoiseTexture),this.glitterPatternTexture&&e.setTexture("glitterPatternTexture",this.glitterPatternTexture),e.setTexture("marbleNoiseTexture",this.dissolveTexture),e.setFloat("marbleAmplitude",this.marbleAmplitude),e.setFloat("marbleTiming",this.marbleTiming),e.setFloat("marbleZoom",this.marbleZoom)}},{key:"hasTexture",value:function(e){return!!ye(re(s.prototype),"hasTexture",this).call(this,e)||this.numberTexture==e||this.dissolveTexture==e||this.glitterNoiseTexture==e||this.glitterPatternTexture==e}},{key:"getActiveTextures",value:function(){var e=ye(re(s.prototype),"getActiveTextures",this).call(this);return this.numberTexture&&e.push(this.numberTexture),this.dissolveTexture&&e.push(this.dissolveTexture),this.glitterNoiseTexture&&e.push(this.glitterNoiseTexture),this.glitterPatternTexture&&e.push(this.glitterPatternTexture),e}},{key:"clone",value:function(e){var t=this,i=M.SerializationHelper.Clone((function(){return new s(e,t.getScene())}),this);return i.id=e,i.name=e,i.numberBumpScale=this.numberBumpScale,i.useNumbers=this.useNumbers,this.clearCoat.copyTo(i.clearCoat),this.anisotropy.copyTo(i.anisotropy),this.brdf.copyTo(i.brdf),this.sheen.copyTo(i.sheen),this.subSurface.copyTo(i.subSurface),i}},{key:"dispose",value:function(e,t){t&&(this.numberTexture&&this.numberTexture.dispose(),this.dissolveTexture&&this.dissolveTexture.dispose(),this.glitterNoiseTexture&&this.glitterNoiseTexture.dispose(),this.glitterPatternTexture&&this.glitterPatternTexture.dispose()),ye(re(s.prototype),"dispose",this).call(this,e,t)}}],[{key:"isDieShaderCreated",value:function(e){var t=!!M.Effect.ShadersStore[e+"VertexShader"],i=!!M.Effect.ShadersStore[e+"PixelShader"];return t||i}}]),s}(at),He=xe(We.prototype,"dieType",[Pe],{configurable:!0,enumerable:!0,writable:!0,initializer:null}),Xe=xe(We.prototype,"numberTexture",[Re],{configurable:!0,enumerable:!0,writable:!0,initializer:null}),je=xe(We.prototype,"numberColor",[Me],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return be.Wo.FromHexString("#880000")}}),Ye=xe(We.prototype,"numberHighlightColor",[Ie],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return be.Wo.FromHexString("#FF0000")}}),qe=xe(We.prototype,"numberBumpScale",[De],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return.1}}),Ke=xe(We.prototype,"dissolveTexture",[Oe],{configurable:!0,enumerable:!0,writable:!0,initializer:null}),$e=xe(We.prototype,"glitterScale",[we],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return 0}}),Qe=xe(We.prototype,"glitterNoiseTexture",[Ne],{configurable:!0,enumerable:!0,writable:!0,initializer:null}),Ze=xe(We.prototype,"glitterPatternTexture",[Fe],{configurable:!0,enumerable:!0,writable:!0,initializer:null}),Je=xe(We.prototype,"dissolveValue",[Le],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return 0}}),et=xe(We.prototype,"useNumbers",[Be],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return!0}}),tt=xe(We.prototype,"marbleAmplitude",[Ue],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return 0}}),it=xe(We.prototype,"marbleTiming",[Ve],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return.025}}),nt=xe(We.prototype,"marbleZoom",[ke],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return.5}}),st=xe(We.prototype,"numbersMode",[Ge],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return 1}}),rt=xe(We.prototype,"fadeSpeed",[ze],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return 2}}),We);var ht=function(e){ne(s,e);var t,i,n=(t=s,i=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,n=re(t);if(i){var s=re(this).constructor;e=Reflect.construct(n,arguments,s)}else e=n.apply(this,arguments);return se(this,e)});function s(e,t,i,r,o,a){var l;return _(this,s),(l=n.call(this,e,i,null,r,o,a)).setFragment(t),l}return y(s,[{key:"isReady",value:function(){return ye(re(s.prototype),"isReady",this).call(this)&&Object.values(this._textures).every((function(e){return e.isReady()}))}}]),s}(M.ProceduralTexture),ct=function(e,t){var i=e.x,n=e.y,s=e.z,r=t.x,o=t.y,a=t.z,l=t.w,h=l*i+o*s-a*n,c=l*n+a*i-r*s,u=l*s+r*n-o*i,d=-r*i-o*n-a*s;return e.x=h*l+d*-r+c*-a-u*-o,e.y=c*l+d*-o+u*-r-h*-a,e.z=u*l+d*-a+h*-o-c*-r,e},ut=function(e){return e.x*e.x+e.y*e.y+e.z*e.z},dt=function(e,t){var i=Math.sqrt(ut(e)*ut(t));0===i&&console.error("angleTo() can't handle zero length vectors.");var n,s=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z}(e,t)/i;return Math.acos((n=s,-1,1,Math.max(-1,Math.min(1,n))))};var pt=function(e){return e[e.INT_TYPE=0]="INT_TYPE",e[e.FLOAT_TYPE=1]="FLOAT_TYPE",e[e.VEC3_TYPE=2]="VEC3_TYPE",e}(pt||{}),ft=function(){function e(){_(this,e),x(this,"_uniforms",new Map)}return y(e,[{key:"setInt",value:function(e,t){this._uniforms.set(e,{type:pt.INT_TYPE,value:t})}},{key:"setFloat",value:function(e,t){this._uniforms.set(e,{type:pt.FLOAT_TYPE,value:t})}},{key:"setVec3",value:function(e,t){this._uniforms.set(e,{type:pt.VEC3_TYPE,value:t})}},{key:"applyUniforms",value:function(e){this._uniforms.forEach((function(t,i){var n=t.value;switch(t.type){case pt.INT_TYPE:e.setInt(i,n);break;case pt.FLOAT_TYPE:e.setFloat(i,Math.fround(n));break;case pt.VEC3_TYPE:n&&e.setVector3(i,n)}}))}}]),e}();const _t=function(e){return new Promise((function(t){return setTimeout(t,e)}))};var mt=function(){function e(t,i){_(this,e),x(this,"options",void 0),x(this,"DiceManager",void 0),x(this,"meshParent",void 0),x(this,"object",void 0),x(this,"onEventObservable",new M.Observable),x(this,"animationGroups",void 0),x(this,"animationStates",void 0),x(this,"rollIndex",void 0),x(this,"particleSystems",void 0),x(this,"events",void 0),x(this,"pairedDie",void 0),x(this,"globalTime",0),x(this,"logger",void 0),x(this,"collisionSounds",void 0),x(this,"uniformContainer",void 0),x(this,"proceduralTextures",void 0),x(this,"currentEvent",null),x(this,"faceValue",void 0),x(this,"result",{value:0,normal:M.Vector3.Up(),angle:0}),this.logger=new oe(this),this.options=i,this.DiceManager=t,this.object=null,this.animationGroups=null,this.animationStates=null,this.particleSystems=[],this.events=new Map,this.uniformContainer=new ft,this.proceduralTextures=[]}var t;return y(e,[{key:"create",value:function(e,t){var i,n=this,s=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=e[t],o=_e.instantiateContainer(r.modelFile);this.meshParent=o.rootNodes[0],this.setEnabled(!1);var a=this.DiceManager.SceneManager.scene;this._setupProceduralTextures(o.rootNodes,e,a),this.animationGroups=new Map,this.animationStates=new Map,o.animationGroups.map((function(e){n.animationGroups[e.name]=e,n.animationStates[e.name]=Z.NONE})),this.meshParent.position.y=this.options.baseHeight,this.updateSceneMeshChildren(this.meshParent,r),this.meshParent.scalingDeterminant=this.options.size*this.options.meshSizeMultiplier*(null!==(i=r.scale)&&void 0!==i?i:1),this.DiceManager.PhysicsManager.add(this.meshParent,this.options,r),s&&this._configureCollisionHandler(),this.instantiateParticleSystems(r),this.configureAnimations(r),this.configureSounds(r),r.siblingNodes&&this.instantiateSiblingNodes(r.siblingNodes,e)}},{key:"instantiateSiblingNodes",value:function(e,t){var i=this;e.forEach((function(e,n){var s,r,o,a,l,h=_e.instantiateContainer(e),c=h.rootNodes[0];c.parent=i.meshParent,c.scalingDeterminant=null!==(s=null===(r=t[e])||void 0===r?void 0:r.scale)&&void 0!==s?s:1,null!==(o=t[e])&&void 0!==o&&o.randomRotation&&(c.rotation=new M.Vector3(0,2*Math.random()*Math.PI,0)),h.animationGroups.forEach((function(e){i.animationGroups[e.name]=e,i.animationStates[e.name]=Z.NONE})),null!==(a=t[e])&&void 0!==a&&a.enforceBoundaries&&i.enforceBoundaries(c),null!==(l=t[e])&&void 0!==l&&l.stackSiblings&&i.stackSibling(c,t[e].stackSiblings),i.configureAnimations(t[e])}))}},{key:"enforceBoundaries",value:function(e){if(!this.DiceManager.previewDie){var t=e.getScene(),i=t.getMeshByName("wall1").position,n=t.getMeshByName("wall2").position,s=t.getMeshByName("wall3").position,r=t.getMeshByName("wall4").position,o=function(){var t=e.getHierarchyBoundingVectors(),o=t.min,a=t.max;o.z<i.z&&(e.position.z+=.05),a.z>n.z&&(e.position.z-=.05),a.x>s.x&&(e.position.x-=.05),o.x<r.x&&(e.position.x+=.05)};this.onEventObservable.add((function(e){"dieRemoved"===e&&t.unregisterBeforeRender(o)})),t.registerBeforeRender(o)}}},{key:"stackSibling",value:function(e,t){var i=this;this.onEventObservable.add((function(n){"rollComplete"===n&&(e.position.y+=i.DiceManager.stackOrder++*t),"dieRemoved"===n&&--i.DiceManager.stackOrder}))}},{key:"_setupProceduralTextures",value:function(e,t,i){var n=this;e.forEach((function(e){return e.getChildMeshes().forEach((function(e){n._setupProceduralTexturesOnObject(e.material,t,i),e.material instanceof M.PBRMaterial&&e.material.clearCoat&&n._setupProceduralTexturesOnObject(e.material.clearCoat,t,i)}))}))}},{key:"_setupProceduralTexturesOnObject",value:function(e,t,i){var n=this;e&&Object.keys(e).forEach((function(s){var r=e[s];if(r instanceof ht){var o=r.clone();e[s]=o,n.proceduralTextures.push(o);var a=t.resources.textures[o.name].uniforms;_e.deserializeUniforms(a,i).forEach((function(e){return e(o)})),n.logger.log("Cloning ".concat(r.name," for ").concat(s))}}))}},{key:"isFinished",value:function(){return e=this.meshParent.physicsImpostor.getAngularVelocity(),t=this.meshParent.physicsImpostor.getLinearVelocity(),e.lengthSquared()<.1&&t.lengthSquared()<.1;var e,t}},{key:"getUpsideValue",value:function(){var e=function(e,t,i,n){for(var s,r,o=new M.Vector3(0,e?-1:1),a=2*Math.PI,l=0;l<i.length;++l)if(-1!==n[l]){var h=new M.Vector3(i[l].x,i[l].y,i[l].z),c=ct(h,t),u=dt(c,o);u<a&&(a=u,r=c,s=n[l])}return{closest_face:s,closest_normal:r,closest_angle:a}}(this.options.invertUpside,this.meshParent.physicsImpostor.physicsBody.quaternion,this.meshParent.physicsImpostor.physicsBody.shapes[0].faceNormals,this.options.faces.map((function(e){return e[e.length-1]}))),t=e.closest_face,i=e.closest_normal,n=e.closest_angle;void 0!==this.options.numberValues&&(t=this.options.numberValues[t]);var s=t;if(this.options.dieType===r.d100&&this.pairedDie&&this.options.dieType>this.pairedDie.options.dieType){var o=this.pairedDie.getUpsideValue();10===o.result&&(o.result=0),s+=o.result,this.options.dieType===r.d100&&0===s&&(s=100)}return this.faceValue=t,this.result.angle=n,this.result.normal=i,this.result.value=s,{result:s,dieValue:t}}},{key:"disablePhysics",value:function(){this.meshParent.physicsImpostor.dispose()}},{key:"getDepthMaterial",value:function(e,t){return new me(this.DiceManager.SceneManager.scene,e,t.materials.defaultDepth.fragmentShader)}},{key:"instantiateParticleSystems",value:function(e){var t=this;$.Particles&&e.particleSystems&&e.particleSystems.forEach((function(e){var i=_e.getParticleSystem(e.definition,t.meshParent);if(i){var n;t.particleSystems.push(i);var s=null===(n=t.DiceManager.diceManifest.resources)||void 0===n?void 0:n.particleSystems[e.definition],r=i.getCustomEffect(i.blendMode);if(r){var o=_e.deserializeUniforms(s.uniforms,t.DiceManager.SceneManager.scene);r.onBind=function(){o.forEach((function(e){return e(r)})),r.setFloat("time",t.globalTime),r.setVector3("origin",t.meshParent.position)}}if(s.particleTexture){var a=_e.getTexture(s.particleTexture,t.DiceManager.SceneManager.scene);i.particleTexture=a.clone()}t.onEventObservable.add((function(n){t.handleTrigger(n,e,(function(e){e.loop||(i.targetStopDuration=.05),i.start()}),(function(e){i.stop()}))}))}}))}},{key:"setEnabled",value:function(e){this.meshParent.setEnabled(e)}},{key:"handleTrigger",value:function(e,t,i,n,s){t.triggerReverse&&(e==t.triggerReverse||t.triggerReverse.indexOf(e)>=0)&&s(t),t.triggerStart==e?i(t):t.triggerStop&&(e==t.triggerStop||t.triggerStop.indexOf(e)>=0)&&n(t)}},{key:"configureAnimations",value:function(e){var t,i=this;null===(t=e.animations)||void 0===t||t.forEach((function(e){Array.isArray(e)?i.handleRandomAnimation(e):i.configureAnimation(e)}))}},{key:"handleRandomAnimation",value:function(e){var t=this,i=e.length,n=e[Math.floor(Math.random()*i)];Array.isArray(n)?n.forEach((function(e){t.configureAnimation(e)})):this.configureAnimation(n)}},{key:"configureAnimation",value:function(e){var t=this;try{var i=this.animationGroups[e.definition];if(!i){var n=_e.getAnimationGroup(e.definition,this.DiceManager.SceneManager.scene,this.meshParent);if(!n)return;this.animationGroups[e.definition]=n,i=n}this.onEventObservable.add((function(n,s){try{t.handleTrigger(n,e,(function(e){var r;(s.currentTarget===e.value||"rollComplete"===n&&void 0===e.value)&&(i.stop(),null!==(r=i.metadata)&&void 0!==r&&r.uvOffsets&&t.configureUvAnimation(i),i.start(e.loop,1,0,i.to),t.animationStates[e.definition]=Z.START,t.onEventObservable.notifyObservers(e.definition,void 0,void 0,void 0))}),(function(e){i.stop(),t.animationStates[e.definition]=Z.STOP}),(function(e){s.currentTarget!==e.value&&[Z.START,Z.STOP].includes(t.animationStates[e.definition])&&(i.stop(),i.start(e.loop,1,i.to,0),t.animationStates[e.definition]=Z.RESET)}))}catch(e){t.logger.error(e)}}))}catch(e){this.logger.error(e)}}},{key:"configureUvAnimation",value:function(e){var t=this.result.value;this.options.dieType===r.d100?t=this.faceValue?this.faceValue/10:0:this.options.dieType===r.d10&&10===this.faceValue&&(t=0),e.targetedAnimations.forEach((function(i){var n;if(i.animation.targetProperty.indexOf("uOffset")>0)i.animation.setKeys([{frame:0,value:null===(n=e.metadata)||void 0===n?void 0:n.uvOffsets[t][0]}]);else if(i.animation.targetProperty.indexOf("vOffset")>0){var s;i.animation.setKeys([{frame:0,value:null===(s=e.metadata)||void 0===s?void 0:s.uvOffsets[t][1]}])}}))}},{key:"configureSounds",value:function(e){var t=this;e.sounds&&e.sounds.forEach((function(e){try{if(e.triggerStart){var i=_e.getSound(e.definition);i&&t.onEventObservable.add((function(n){t.DiceManager.SceneManager.scene.audioEnabled&&t.handleTrigger(n,e,(function(e){i.isPlaying||(i.setPosition(t.DiceManager.SceneManager.camera.position),i.setVolume(1),i.play())}),(function(e){return i.stop()}))}))}}catch(e){t.logger.error(e)}}))}},{key:"isReady",value:function(){return this.meshParent.isReady(!0)}},{key:"_configureCollisionHandler",value:function(){var e=this;this.collisionSounds=[];for(var t=0;t<3;t++){var i=_e.getSound("collision".concat(t+1));i&&this.collisionSounds.push(i.clone())}this.DiceManager.PhysicsManager.collisionEvent(this.meshParent,(function(t){if(e.DiceManager.throwRunning){e._processEvent("collision");var i=Math.abs(t.contact.getImpactVelocityAlongNormal());if(e.DiceManager.SceneManager.scene.audioEnabled){var n=e.collisionSounds[Math.floor(Math.random()*e.collisionSounds.length)];if(n&&!n.isPlaying){var s=M.Scalar.Clamp(i,0,1);n.attachToMesh(e.meshParent),n.setVolume(s),n.play(),n.detachFromMesh()}}$.Vibrate&&navigator.vibrate&&navigator.vibrate(i/2)}}))}},{key:"updateSceneMeshChildren",value:function(e,t){var i=this;this.uniformContainer.setInt("dieType",this.options.values),this.uniformContainer.setInt("dieValue",0),this.DiceManager.SceneManager.scene.onBeforeRenderObservable.add((function(){i.updateProceduralTextureUniforms()})),e.getChildMeshes(!1).forEach((function(n){var s,r,o=new Map;if(((null===(s=t.materials[(null===(r=n.material)||void 0===r?void 0:r.name)||"default"])||void 0===s?void 0:s.snippets)||[]).forEach((function(t){"liquid"===t&&o.set("liquid",new ge(n,e))})),n.material.onBindObservable.add((function(e,t){o.forEach((function(e,t){e.Update(i.DiceManager.SceneManager.scene.deltaTime/1e3)})),i.updateMaterialUniforms(n.material)})),$.Shadow>K.None){var a,l,h=!(null!==(a=t.materials[(null===(l=n.material)||void 0===l?void 0:l.name)||"default"])&&void 0!==a&&a.disableShadow);h?i.DiceManager.SceneManager.shadowGenerator.addShadowCaster(n,!1):i.logger.log("".concat(n.name," shadows disabled due to material config")),n.receiveShadows=h}}))}},{key:"updateMaterialUniforms",value:function(e){var t=null==e?void 0:e.getEffect();t&&this.uniformContainer.applyUniforms(t)}},{key:"updateProceduralTextureUniforms",value:function(){var e=this;this.proceduralTextures.forEach((function(t){e.uniformContainer.applyUniforms(t)}))}},{key:"updateGlobalTimeUniform",value:function(e){this.globalTime+=e/1e3,this.uniformContainer.setFloat("iGlobalTime",this.globalTime)}},{key:"update",value:function(e){this.updateGlobalTimeUniform(e)}},{key:"_processEvent",value:function(e,t){this.onEventObservable.notifyObservers(e,void 0,void 0,t),(!this.currentEvent||Q[e]>=this.currentEvent)&&(this.currentEvent=Q[e],this.uniformContainer.setInt("lastEvent",Q[e]),this.uniformContainer.setFloat("lastEventTime",this.globalTime))}},{key:"onRollBegin",value:function(){this._processEvent("rollBegin")}},{key:"onRollComplete",value:function(e){this._processEvent("rollComplete",e),this.options.dieType===r.d100?this.uniformContainer.setInt("dieValue",0===e?10:e/10):this.uniformContainer.setInt("dieValue",e),this.uniformContainer.setVec3("topFaceNormal",this.result.normal)}},{key:"onMinRoll",value:function(){this._processEvent("minRoll")}},{key:"onMaxRoll",value:function(){this._processEvent("maxRoll")}},{key:"onDieRemoved",value:function(){this._processEvent("dieRemoved"),this.result.value===this.options.values?this._processEvent("critDieRemoved"):1===this.result.value?this._processEvent("failDieRemoved"):this._processEvent("nonCritNonFailDieRemoved")}},{key:"runRemoval",value:function(){var e=this;this.DiceManager.PhysicsManager.remove(this.meshParent);var t=Date.now()+3e3;this.update=function(i){var n=.001*(t-Date.now());e.meshParent.getChildMeshes().forEach((function(e){e.material&&e.material instanceof lt&&(e.material.dissolveValue=3-n)})),e.uniformContainer.setFloat("dissolveValue",3-n),e.updateGlobalTimeUniform(i),n<=0&&(e.update=function(){},e.dispose(),e.particleSystems.forEach((function(e){return e.dispose()})))}}},{key:"dispose",value:function(){var e=this;try{this.particleSystems.forEach((function(e){return e.dispose(!0)})),this.meshParent.getChildMeshes().forEach((function(e){var t,i,n;null==e||null===(t=e.material)||void 0===t||t.unbind(),(null==e?void 0:e.material)instanceof M.ShaderMaterial?null==e||null===(i=e.material)||void 0===i||i.dispose(!1,!1,!0):null==e||null===(n=e.material)||void 0===n||n.dispose(!1,!0,!0)})),this.meshParent.dispose(!1,!1),Object.keys(this.animationGroups).forEach((function(t){e.animationGroups[t].dispose(),delete e.animationGroups[t]}))}catch(e){this.logger.error(e)}}},{key:"roll",value:(t=f(T().mark((function e(t,i,n,s){var r;return T().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(r={x:0,z:0}).x=n<3?-(n-1)*ee.DistanceBetween/2:-2*ee.DistanceBetween/2,r.z=n<9?-Math.floor((n-1)%9/3)*ee.DistanceBetween/2:-2*ee.DistanceBetween/2,this.onRollBegin(),this.setEnabled(!0),this.meshParent.position.set(i%3*ee.DistanceBetween+t.x+r.x,ee.StartHeight+Math.floor(i/9)*ee.DistanceBetween,Math.floor(i%9/3)*ee.DistanceBetween+t.z+r.z),this.meshParent.physicsImpostor.sleep(),this.meshParent.rotate(M.Axis.X,Math.random()*(2*Math.PI),M.Space.WORLD),this.meshParent.rotate(M.Axis.Y,Math.random()*(2*Math.PI),M.Space.WORLD),this.meshParent.rotate(M.Axis.Z,Math.random()*(2*Math.PI),M.Space.WORLD),e.next=12,_t(5);case 12:this.meshParent.physicsImpostor.wakeUp(),this.meshParent.physicsImpostor.setAngularVelocity(new M.Vector3(20*Math.random()-10,20*Math.random()-10,20*Math.random()-10)),this.meshParent.physicsImpostor.setLinearVelocity(s);case 15:case"end":return e.stop()}}),e,this)}))),function(e,i,n,s){return t.apply(this,arguments)})},{key:"toJSON",value:function(){return{dieType:this.options.dieType,dieValue:this.result.value}}}],[{key:"CreateRandomVelocity",value:function(e){var t=ee.BaseStrength+e*ee.AddPerDieStrength,i=Math.random()*t,n=t-i;return i*=Math.random()>=.5?1:-1,n*=Math.random()>=.5?1:-1,new M.Vector3(i,ee.StrengthHeight,n)}}]),e}(),gt=o(2318),vt=y((function e(t,i,n,s){var r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:void 0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:void 0,a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:void 0;_(this,e),x(this,"key",void 0),x(this,"type",void 0),x(this,"vertexUrl",void 0),x(this,"fragmentUrl",void 0),x(this,"vertexText",void 0),x(this,"fragmentText",void 0),x(this,"pixelUrl",void 0),x(this,"pixelText",void 0),this.key=t,this.type="shader",this.vertexUrl=i,this.fragmentUrl=n,this.vertexText=r,this.fragmentText=o,this.pixelUrl=s,this.pixelText=a}));const yt=vt;function xt(e,t){return e&&!e.startsWith("http")&&(e=(e="".concat(t,"/").concat(e)).replace(/([^:]\/|^\/)\/+/g,"$1")),e}function bt(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(e){if("string"==typeof e)return Tt(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?Tt(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0,s=function(){};return{s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){a=!0,r=e},f:function(){try{o||null==i.return||i.return()}finally{if(a)throw r}}}}function Tt(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}var St=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",i=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0;_(this,e),x(this,"baseLocation",void 0),x(this,"manifestRelativeLocation",void 0),x(this,"scene",void 0),x(this,"logger",void 0),x(this,"bundle",void 0),x(this,"manifest",void 0),this.logger=new oe(this),this.baseLocation=t,this.scene=i,this.bundle=n,M.SceneLoader.ShowLoadingScreen=!1,M.SceneLoader.OnPluginActivatedObservable.add((function(e){e instanceof gt.GLTFFileLoader&&(e.animationStartMode=gt.GLTFLoaderAnimationStartMode.NONE,gt.GLTFFileLoader.IncrementalLoading=!1)}),void 0,void 0,void 0,!0)}var t,i;return y(e,[{key:"createAssetsManager",value:function(){var e=this,t=new M.AssetsManager(this.scene);return t.useDefaultLoadingScreen=!1,t.onTaskErrorObservable.add((function(t){e.logger.error("AssetManager task failed",t.errorObject.message,t.errorObject.exception)})),t.onTaskSuccessObservable.add((function(t){e.logger.info("AssetManager task ".concat(t.name," complete"))})),t}},{key:"resolveUrl",value:function(e){var t=this;return new Promise((function(i){if(t.bundle){var n=t.bundle.file(e);return n||(t.logger.warn("".concat(e," not found in bundle")),i(xt(e,t.baseLocation))),n.async("blob").then((function(e){var t=URL.createObjectURL(e);i(t)}))}e.startsWith("/")?i(xt(e,t.baseLocation)):i(xt(e,t.baseLocation+t.manifestRelativeLocation))}))}},{key:"loadManifest",value:function(e){var t=this,i=this.createAssetsManager();return new Promise(function(){var n=f(T().mark((function n(s,r){var o;return T().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return(o=i.addTextFileTask("manifest",e)).onSuccess=function(i){try{t.logger.debug("Manifest ".concat(i.url," loaded"));var n=JSON.parse(o.text);t.logger.debug("Manifest parsed");var a=e.substring(t.baseLocation.length);a=a.substring(0,a.lastIndexOf("/")+1),t.manifestRelativeLocation=a,t.manifest=n,s(n)}catch(e){r(e)}},n.next=4,i.loadAsync();case 4:case"end":return n.stop()}}),n)})));return function(e,t){return n.apply(this,arguments)}}())}},{key:"loadAssets",value:function(){var e=this;return new Promise(function(){var t=f(T().mark((function t(i){var n,s,r;return T().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=e.createAssetsManager(),e.logger.groupCollapsed("Loading Assets"),n.onTasksDoneObservable.add((function(t){e.logger.groupEnd()})),s=e.getLoadableAssets(),r=[],s.map((function(t){t instanceof ue?r.push(e._loadTexture(t,n)):t instanceof yt?(t.vertexUrl||(t.vertexUrl="/shaders/default.vert"),r.push(e._loadShader(t,n))):t instanceof ce&&r.push(e.loadSound(t,n))})),t.next=8,Promise.all(r);case 8:return t.next=10,n.loadAsync();case 10:return e.logger.log("AssetManager.loadAsync() First Stage"),r=[],s.map((function(t){e.logger.log("Create load promise for ".concat(t.key)),t instanceof he?r.push(e._loadMesh(t,n)):t instanceof de?r.push(e._loadParticleSystem(t,n)):t instanceof pe&&r.push(e._loadAnimationGroup(t,n))})),e.logger.log("Waiting on ".concat(r.length," resources to load")),t.next=16,Promise.all(r);case 16:return t.next=18,n.loadAsync();case 18:e.logger.log("AssetManager.loadAsync() complete"),i();case 20:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}())}},{key:"_loadShader",value:function(e,t){var i=this;return e.pixelUrl?this.resolveUrl(e.pixelUrl).then((function(i){_e.addToShaderCache(e.key,new yt(e.key,null,null,null)),i&&(t.addTextFileTask("shader-".concat(e.key,"-pixel"),i).onSuccess=function(t){var i=_e.getShader(e.key);i.pixelText=t.text,i.pixelUrl=t.url,M.Effect.ShadersStore["".concat(e.key,"PixelShader")]=t.text})})):this.resolveUrl(e.vertexUrl).then((function(n){i.resolveUrl(e.fragmentUrl).then((function(i){_e.addToShaderCache(e.key,new yt(e.key,null,null,null)),n&&(t.addTextFileTask("shader-".concat(e.key,"-vert"),n).onSuccess=function(t){var i=_e.getShader(e.key);i.vertexText=t.text,i.vertexUrl=t.url,M.Effect.ShadersStore["".concat(e.key,"VertexShader")]=t.text}),i&&(t.addTextFileTask("shader-".concat(e.key,"-frag"),i).onSuccess=function(t){var i=_e.getShader(e.key);i.fragmentText=t.text,i.fragmentUrl=t.url,M.Effect.ShadersStore["".concat(e.key,"FragmentShader")]=t.text})}))}))}},{key:"loadSound",value:function(e,t){var i=this;return this.resolveUrl(e.sound).then((function(n){var s=t.addBinaryFileTask("sound-".concat(e.key),n);s.onError=function(e,t){i.logger.error(t)},s.onSuccess=function(t){var n=new M.Sound(e.key,t.data,i.scene,null,{spatialSound:!0,distanceModel:"linear",rolloffFactor:1});_e.addToSoundCache(e.key,n)}}))}},{key:"_loadParticleSystem",value:function(e,t){var i=this;return this.resolveUrl(e.resourceUrl).then((function(n){var s=t.addTextFileTask("particle-".concat(e.key),n);s.onError=function(e,t){i.logger.error(t)},s.onSuccess=function(t){try{var n=JSON.parse(t.text);if(n&&n.systems&&n.systems.length>0){var s=M.ParticleSystem.Parse(n.systems[0],i.scene,"",!0);_e.addToParticleSystemCache(e.key,s)}}catch(e){i.logger.error("Could not parse particle system: "+e)}}}))}},{key:"_loadAnimationGroup",value:function(e,t){var i=this;return this.resolveUrl(e.resourceUrl).then((function(n){var s=t.addTextFileTask("anim-".concat(e.key),n);s.onError=function(e,t){i.logger.error(t)},s.onSuccess=function(t){try{if(e.clones)for(var n=function(){var i=r[s],n=e.clones[i],o=JSON.parse(t.text);o.name=n.name,n.targetedAnimations.forEach((function(e,t){for(var i=0,n=Object.keys(e);i<n.length;i++){var s=n[i];o.targetedAnimations[t][s]=e[s]}})),_e.addToAnimationGroupCache(i,JSON.stringify(o))},s=0,r=Object.keys(e.clones);s<r.length;s++)n();else _e.addToAnimationGroupCache(e.key,t.text)}catch(e){i.logger.error("Could not parse animation group: "+e)}}}))}},{key:"_loadTexture",value:function(e,t){var i=this;return this.resolveUrl(e.resourceUrl).then((function(n){var s=t.addTextureTask("texture-".concat(e.key),n,null,!1);s.onError=function(e,t){i.logger.error(t)},s.onSuccess=function(t){_e.addToTextureCache(e.key,t.texture)}}))}},{key:"_loadMesh",value:function(e,t){var i=this;return new Promise(function(){var t=f(T().mark((function t(n,s){var r,o,a,l;return T().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,i.resolveUrl(e.resourceUrl);case 3:return r=t.sent,o=e.resourceUrl.substr(e.resourceUrl.lastIndexOf(".")),i.logger.log("Loading AssetContainer ".concat(r)),t.next=8,M.SceneLoader.LoadAssetContainerAsync(r,null,i.scene,null,o);case 8:(a=t.sent).animationGroups.forEach((function(e){e.stop()})),a.meshes.forEach((function(e){e.parent||(l=e)})),l.name=e.key,_e.addAssetContainer(e.key,a),i.logger.log("LoadAssetContainerAsync complete ".concat(e.key)),n(),t.next=21;break;case 17:t.prev=17,t.t0=t.catch(0),i.logger.error(t.t0),s();case 21:case"end":return t.stop()}}),t,null,[[0,17]])})));return function(e,i){return t.apply(this,arguments)}}())}},{key:"correlateResources",value:(i=f(T().mark((function e(t){var i,n,s,r=this;return T().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=T().mark((function e(){var i,o,a,l;return T().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=s[n],(o=r.manifest[i])&&o.materials){e.next=4;break}return e.abrupt("return","continue");case 4:if(r.logger.groupCollapsed("Correlating resources for ".concat(i)),o.materials&&Object.keys(o.materials).forEach((function(e){if(r._isMaterialManifest(o.materials[e])){var i=r._getMaterialDefinition(e,o.materials);i.properties=r._deserializeMaterialProperties(i.properties,t)}})),!o.modelFile){e.next=12;break}return a=_e.assetContainers[o.modelFile],l=a.meshes[0],o.billboardMode&&(l.billboardMode=o.billboardMode),e.next=12,r._updateMaterials(i,l,o.materials);case 12:r.logger.groupEnd();case 13:case"end":return e.stop()}}),e)})),n=0,s=Object.keys(this.manifest);case 2:if(!(n<s.length)){e.next=10;break}return e.delegateYield(i(),"t0",4);case 4:if("continue"!==e.t0){e.next=7;break}return e.abrupt("continue",7);case 7:n++,e.next=2;break;case 10:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"_deserializeMaterialProperties",value:function(e,t){var i=this;if(e)return["sheen"].forEach((function(t){delete e[t]})),Object.keys(e).forEach((function(n){if(n.endsWith("Color")){var s=M.Color3.FromHexString(e[n]);e[n]=s}else if(n.endsWith("Texture")){var r=e[n],o="string"==typeof r?r:r.name,a=_e.getTexture(o,t);if(a)a.hasAlpha=!0,e[n]=a;else{var l=i.manifest.resources.textures[r];if(l&&"string"!=typeof l){var h=l,c=new ht(o,h.shader,h.size||512,t);_e.deserializeUniforms(h.uniforms,t).forEach((function(e){return e(c)})),e[n]=c}else delete e[n]}if("string"!=typeof r&&e[n]){var u=e[n].clone();Object.keys(r).forEach((function(e){u[e]=r[e]})),e[n]=u}}})),e}},{key:"_isMaterialManifest",value:function(e){return"string"!=typeof e}},{key:"_getMaterialDefinition",value:function(e,t){var i=t[e];return this._isMaterialManifest(i)?i:this.manifest.resources.materials[i]}},{key:"_updateMaterials",value:(t=f(T().mark((function e(t,i,n){var s,r,o,a=this;return T().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!n){e.next=17;break}s=bt(i.getChildMeshes(!1)),e.prev=2,o=T().mark((function e(){var i,s,o,l,h,c,u,d,p,f;return T().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(s=r.value,a.logger.log("Updating Materials for ".concat(s.name," (").concat(null===(i=s.material)||void 0===i?void 0:i.name,")")),!s.material){e.next=32;break}if("__GLTFLoader._default"==(o=s.material.name||"default")&&(o="default"),!(l=a._getMaterialDefinition(o,n))||null==l||!l.shader||"default"==(null==l?void 0:l.shader)){e.next=11;break}(h=_e.getShader(l.shader))&&(c=s.material,s.material=_e.createShaderMaterial(o,a.scene,h,l.uniforms),a.scene.removeMaterial(c),c.dispose()),e.next=28;break;case 11:if(!(l&&null!=l&&l.nodeSnippet||null!=l&&l.nodeJson)){e.next=27;break}if(!l.nodeSnippet){e.next=18;break}return e.next=15,M.NodeMaterial.ParseFromSnippetAsync(l.nodeSnippet,a.scene);case 15:u=e.sent,e.next=24;break;case 18:return e.next=20,a.resolveUrl(l.nodeJson);case 20:return d=e.sent,e.next=23,M.NodeMaterial.ParseFromFileAsync(o,d,a.scene);case 23:u=e.sent;case 24:s.material=u,e.next=28;break;case 27:"default"===o&&(p=s.material,s.material=a.getDefaultMaterial(parseInt(t.substring(1)),a.manifest.setName),a.scene.removeMaterial(p),p.dispose(!0,!0));case 28:f=["anisotropy","brdf","clearCoat","detailMap","sheen","subSurface","iridescence","brdf"],l&&l.properties&&Object.keys(l.properties).forEach((function(e){f.includes(e)||(s.material[e]=l.properties[e])})),s.material instanceof M.PBRMaterial&&l&&l.properties&&(l.properties.sheenColor instanceof M.Color3&&(s.material.sheen.isEnabled=!0,s.material.sheen.color=l.properties.sheenColor),l.properties.clearCoatTexture instanceof M.Texture&&(s.material.clearCoat.isEnabled=!0,s.material.clearCoat.texture=l.properties.clearCoatTexture),l.properties.clearCoatBumpTexture instanceof M.Texture&&(s.material.clearCoat.isEnabled=!0,s.material.clearCoat.bumpTexture=l.properties.clearCoatBumpTexture),l.properties.clearCoatTintColor instanceof M.Color3&&(s.material.clearCoat.isEnabled=!0,s.material.clearCoat.isTintEnabled=!0,s.material.clearCoat.tintColor=l.properties.clearCoatTintColor),l.properties.clearCoatTintThickness&&(s.material.clearCoat.isEnabled=!0,s.material.clearCoat.tintThickness=l.properties.clearCoatTintThickness),l.properties.clearCoatRoughness&&(s.material.clearCoat.isEnabled=!0,s.material.clearCoat.roughness=l.properties.clearCoatRoughness),l.properties.clearCoatIOR&&(s.material.clearCoat.isEnabled=!0,s.material.clearCoat.indexOfRefraction=l.properties.clearCoatIOR),f.forEach((function(e){a._updateMaterialSubconfiguration(l,e,s.material)}))),s.material.sideOrientation=M.Mesh.DOUBLESIDE;case 32:case"end":return e.stop()}}),e)})),s.s();case 5:if((r=s.n()).done){e.next=9;break}return e.delegateYield(o(),"t0",7);case 7:e.next=5;break;case 9:e.next=14;break;case 11:e.prev=11,e.t1=e.catch(2),s.e(e.t1);case 14:return e.prev=14,s.f(),e.finish(14);case 17:case"end":return e.stop()}}),e,null,[[2,11,14,17]])}))),function(e,i,n){return t.apply(this,arguments)})},{key:"_updateMaterialSubconfiguration",value:function(e,t,i){var n=e.properties[t];n&&(this._deserializeMaterialProperties(n,this.scene),Object.keys(n).forEach((function(e){console.error(e),i[t][e]=n[e]})))}},{key:"getDefaultMaterial",value:function(e,t){var i="".concat(t,"-d").concat(e,"DieMaterial"),n=this.scene.getMaterialByName(i);return n||((n=new lt(i,this.scene)).dieType=e),n}},{key:"getLoadableAssets",value:function(){var e=this.manifest,t=[];if(e.resources){var i;e.resources.models&&Object.keys(e.resources.models).forEach((function(i){var n=e.resources.models[i];t.push(new he(i,n))})),e.resources.shaders&&Object.keys(e.resources.shaders).forEach((function(i){var n=e.resources.shaders[i];t.push(new yt(i,n.vertextShader,n.fragmentShader,n.pixelShader))})),e.resources.textures&&Object.keys(e.resources.textures).forEach((function(i){var n=e.resources.textures[i];"string"==typeof n&&t.push(new ue(i,n))})),e.resources.particleSystems&&Object.keys(e.resources.particleSystems).forEach((function(i){var n=e.resources.particleSystems[i];null!=n&&n.particleJson?t.push(new de(i,n.particleJson)):t.push(new de(i,n))})),e.resources.animationGroups&&Object.keys(e.resources.animationGroups).forEach((function(i){var n=e.resources.animationGroups[i];null!=n&&n.animationJson?t.push(new pe(i,n.animationJson,n.animationClones)):t.push(new pe(i,n))}));var n=null!==(i=e.resources.sounds)&&void 0!==i?i:{collision1:"/sounds/collision-1.wav",collision2:"/sounds/collision-2.wav",collision3:"/sounds/collision-3.wav"};Object.keys(n).forEach((function(e){var i=n[e];t.push(new ce(e,i))}))}return t}}]),e}();const Et=St;var Ct=function(){function e(){_(this,e),x(this,"SessionName",void 0)}return y(e,[{key:"init",value:function(e,t){this.SessionName=t,"function"!=typeof window.ga&&function(e,t,i,n,s,r,o){e.GoogleAnalyticsObject=s,e[s]=e[s]||function(){(e[s].q=e[s].q||[]).push(arguments)},e[s].l=1*new Date,r=t.createElement(i),o=t.getElementsByTagName(i)[0],r.async=1,r.src="https://www.google-analytics.com/analytics.js",o.parentNode.insertBefore(r,o)}(window,document,"script",0,"ga"),window.ga("create",e,"auto",t)}},{key:"log",value:function(e,t,i,n){window.ga("".concat(this.SessionName,".send"),"event",e,t,i,n)}}]),e}();const At=new Ct,Pt=function(e,t,i,n){var s=new M.Vector3,r=new M.Vector3;s.set(e,t,0),s=function(e,t,i,n){var s=t.viewport.toGlobal(i,n);return M.Vector3.Unproject(e,s.width,s.height,M.Matrix.Identity(),t.getViewMatrix(),t.getProjectionMatrix())}(s,i,n.width,n.height),s=s.subtract(i.position).normalize();var o=-i.position.y/s.y;return r.copyFrom(i.position).add(s.multiply((new M.Vector3).setAll(o)))};var Rt=function(){function e(t,i){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.Sum,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(_(this,e),x(this,"count",void 0),x(this,"dieType",void 0),x(this,"dice",[]),x(this,"operation",void 0),x(this,"operand",void 0),this.count=t,this.dieType=i,this.operation=n,this.operation===s.Min||this.operation===s.Max){if(r<1)throw"Operand must be > 0 for Min or Max operations";this.operand=r}}return y(e,[{key:"toString",value:function(){switch(this.operation){case s.Min:return"".concat(this.count).concat(this.dieType,"kl").concat(this.operand);case s.Max:return"".concat(this.count).concat(this.dieType,"kh").concat(this.operand);default:return"".concat(this.count).concat(this.dieType)}}},{key:"getResult",value:function(){switch(this.operation){case s.Sum:return this.dice.reduce((function(e,t){return e+t.result.value}),0);case s.Min:return this.dice.map((function(e){return e.result.value})).sort((function(e,t){return e-t})).slice(0,this.operand).reduce((function(e,t){return e+t}));case s.Max:return this.dice.map((function(e){return e.result.value})).sort((function(e,t){return t-e})).slice(0,this.operand).reduce((function(e,t){return e+t}))}}},{key:"getResultStr",value:function(){switch(this.operation){case s.Sum:return this.dice.map((function(e){return e.result.value})).join("+");case s.Min:case s.Max:return"(".concat(this.dice.map((function(e){return e.result.value})).join(","),")")}}}]),e}(),Mt=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;_(this,e),x(this,"set",void 0),x(this,"constant",void 0),this.set=t||[],this.constant=i}return y(e,[{key:"toDiceNotationString",value:function(){var e="";return this.set&&this.set.length>0&&(e=this.set.map((function(e){return e.toString()})).join("+")),0!=this.constant&&(this.set.length>0?e+=this.constant>0?"+".concat(this.constant):this.constant:e="".concat(this.constant)),e}}],[{key:"parseDiceNotation",value:function(t){var i,n=l,o=t.split("@"),a=/\s*(\d*)d(\d+)((k[hl])(\d+))?(\s*(\+|\-)\s*(\d+)){0,1}\s*(\+|$)/gi,h=new e;if(!isNaN(Number(t)))return h.constant=Number(t),h;for(;i=a.exec(o[0]);){var c={count:i[1],dieType:i[2],opModifier:i[4],opConstant:i[5],constantOperation:i[7],constant:i[8]},u=parseInt(c.count);""===c.count&&(u=1);var d=r["d"+c.dieType];if(-1===n.indexOf(d))throw"Unknown die type ".concat(d);var p=new Rt(u,d);"kh"===c.opModifier?p.operation=s.Max:"kl"===c.opModifier&&(p.operation=s.Min),c.opConstant&&(p.operand=parseInt(c.opConstant)),h.set.push(p),c.constant&&c.constantOperation&&("+"===c.constantOperation?h.constant+=parseInt(c.constant):h.constant-=parseInt(c.constant))}if(h.set.length<1)throw"No dice specified";return h}}]),e}(),It=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:d.Roll,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:c.None;_(this,e),x(this,"diceNotation",void 0),x(this,"rollType",void 0),x(this,"rollKind",void 0),x(this,"result",void 0),this.diceNotation=t instanceof Mt?t:Mt.parseDiceNotation(t),this.rollType=i,this.rollKind=n}return y(e,[{key:"getDiceNotationString",value:function(){return this.diceNotation.toDiceNotationString()}}]),e}(),Dt=y((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"custom",i=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0;_(this,e),x(this,"context",void 0),x(this,"rollId",void 0),x(this,"action",void 0),x(this,"rolls",[]),x(this,"setId",void 0),this.action=t,this.context=n,i&&this.rolls.push(new It(i))})),Ot=o(8401),wt=o(708),Nt=o(2722),Ft=o(934),Lt=o(4389),Bt=o(58),Ut=o(4453);function Vt(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}var kt=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:CANNON;_(this,e),x(this,"_physicsMaterials",new Array),x(this,"_fixedTimeStep",1/60),x(this,"_cannonRaycastResult",void 0),x(this,"_raycastResult",void 0),x(this,"_physicsBodysToRemoveAfterStep",new Array),x(this,"_firstFrame",!0),x(this,"_useDeltaForWorldStep",!0),x(this,"BJSCANNON",void 0),x(this,"world",void 0),x(this,"name","customCannonJs"),x(this,"_minus90X",new Te._f(-.7071067811865475,0,0,.7071067811865475)),x(this,"_plus90X",new Te._f(.7071067811865475,0,0,.7071067811865475)),x(this,"_tmpPosition",Te.P.Zero()),x(this,"_tmpDeltaPosition",Te.P.Zero()),x(this,"_tmpUnityRotation",new Te._f),this.BJSCANNON=i,this.isSupported()?(this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=t,this._cannonRaycastResult=new this.BJSCANNON.RaycastResult,this._raycastResult=new Ut.d):Nt.Y.Error("CannonJS is not available. Please make sure you included the js file.")}return y(e,[{key:"getPluginVersion",value:function(){return 1}},{key:"getBodyPressure",value:function(e){throw new Error("Method not implemented.")}},{key:"setBodyPressure",value:function(e,t){throw new Error("Method not implemented.")}},{key:"getBodyStiffness",value:function(e){throw new Error("Method not implemented.")}},{key:"setBodyStiffness",value:function(e,t){throw new Error("Method not implemented.")}},{key:"getBodyVelocityIterations",value:function(e){throw new Error("Method not implemented.")}},{key:"setBodyVelocityIterations",value:function(e,t){throw new Error("Method not implemented.")}},{key:"getBodyPositionIterations",value:function(e){throw new Error("Method not implemented.")}},{key:"setBodyPositionIterations",value:function(e,t){throw new Error("Method not implemented.")}},{key:"appendAnchor",value:function(e,t,i,n,s,r){throw new Error("Method not implemented.")}},{key:"appendHook",value:function(e,t,i,n,s){throw new Error("Method not implemented.")}},{key:"raycastToRef",value:function(e,t,i){throw new Error("Method not implemented.")}},{key:"setGravity",value:function(e){var t=e;this.world.gravity.set(t.x,t.y,t.z)}},{key:"setTimeStep",value:function(e){}},{key:"getTimeStep",value:function(){return this._fixedTimeStep}},{key:"executeStep",value:function(e,t){if(this._firstFrame){this._firstFrame=!1;var i,n=function(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(e){if("string"==typeof e)return Vt(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?Vt(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0,s=function(){};return{s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){a=!0,r=e},f:function(){try{o||null==i.return||i.return()}finally{if(a)throw r}}}}(t);try{for(n.s();!(i=n.n()).done;){var s=i.value;s.type!=Lt.Q.HeightmapImpostor&&s.type!==Lt.Q.PlaneImpostor&&s.beforeStep()}}catch(e){n.e(e)}finally{n.f()}}this.world.step(this._fixedTimeStep,this._useDeltaForWorldStep?e:0,3),this._removeMarkedPhysicsBodiesFromWorld()}},{key:"_removeMarkedPhysicsBodiesFromWorld",value:function(){var e=this;this._physicsBodysToRemoveAfterStep.length>0&&(this._physicsBodysToRemoveAfterStep.forEach((function(t){e.world.remove(t)})),this._physicsBodysToRemoveAfterStep=[])}},{key:"applyImpulse",value:function(e,t,i){var n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,n)}},{key:"applyForce",value:function(e,t,i){var n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,n)}},{key:"generatePhysicsBody",value:function(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){var t=this._createShape(e),i=e.physicsBody;i&&this.removePhysicsBody(e);var n=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:n},r=e.getParam("nativeOptions");for(var o in r)r.hasOwnProperty(o)&&(s[o]=r[o]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){var n=i[t];e.physicsBody[t].set(n.x,n.y,n.z)})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}}},{key:"_processChildMeshes",value:function(e){var t=this,i=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],n=e.object.rotationQuaternion;i.length&&i.filter((function(e){return!!e.physicsImpostor})).forEach(function i(s,r){if(n&&r.rotationQuaternion){var o=r.getPhysicsImpostor();if(o&&o.parent!==e){var a=r.position.clone();o.physicsBody&&(t.removePhysicsBody(o),o.physicsBody=null),o.parent=e,o.resetUpdateFlags(),e.physicsBody.addShape(t._createShape(o),new t.BJSCANNON.Vec3(a.x,a.y,a.z)),e.physicsBody.mass+=o.getParam("mass")}n.multiplyInPlace(r.rotationQuaternion),r.getChildMeshes(!0).filter((function(e){return!!e.physicsImpostor})).forEach(i.bind(t,r.getAbsolutePosition()))}}.bind(this,e.object.getAbsolutePosition()))}},{key:"removePhysicsBody",value:function(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodysToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodysToRemoveAfterStep.push(e.physicsBody)}},{key:"generateJoint",value:function(e){var t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(t&&i){var n,s=e.joint.jointData,r={pivotA:s.mainPivot?(new this.BJSCANNON.Vec3).set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?(new this.BJSCANNON.Vec3).set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?(new this.BJSCANNON.Vec3).set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?(new this.BJSCANNON.Vec3).set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case Bt.q7.HingeJoint:case Bt.q7.Hinge2Joint:n=new this.BJSCANNON.HingeConstraint(t,i,r);break;case Bt.q7.DistanceJoint:n=new this.BJSCANNON.DistanceConstraint(t,i,s.maxDistance||2);break;case Bt.q7.SpringJoint:var o=s;n=new this.BJSCANNON.Spring(t,i,{restLength:o.length,stiffness:o.stiffness,damping:o.damping,localAnchorA:r.pivotA,localAnchorB:r.pivotB});break;case Bt.q7.LockJoint:n=new this.BJSCANNON.LockConstraint(t,i,r);break;case Bt.q7.PointToPointJoint:case Bt.q7.BallAndSocketJoint:default:n=new this.BJSCANNON.PointToPointConstraint(t,r.pivotA,i,r.pivotB,r.maxForce)}n.collideConnected=!!s.collision,e.joint.physicsJoint=n,e.joint.type!==Bt.q7.SpringJoint?this.world.addConstraint(n):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){n.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}}},{key:"removeJoint",value:function(e){e.joint.type!==Bt.q7.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}},{key:"_addMaterial",value:function(e,t,i){var n,s;for(n=0;n<this._physicsMaterials.length;n++)if((s=this._physicsMaterials[n]).friction===t&&s.restitution===i)return s;var r=new this.BJSCANNON.Material(e);return r.friction=t,r.restitution=i,this._physicsMaterials.push(r),r}},{key:"_checkWithEpsilon",value:function(e){return e<M.Epsilon?M.Epsilon:e}},{key:"_createShape",value:function(e){var t,i=e.object,n=e.getObjectExtents();switch(e.type){case Lt.Q.SphereImpostor:var s=n.x,r=n.y,o=n.z;t=new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(s),this._checkWithEpsilon(r),this._checkWithEpsilon(o))/2);break;case Lt.Q.CylinderImpostor:var a=e.getParam("nativeOptions");a||(a={});var l=void 0!==a.radiusTop?a.radiusTop:this._checkWithEpsilon(n.x)/2,h=void 0!==a.radiusBottom?a.radiusBottom:this._checkWithEpsilon(n.x)/2,c=void 0!==a.height?a.height:this._checkWithEpsilon(n.y),u=void 0!==a.numSegments?a.numSegments:16;t=new this.BJSCANNON.Cylinder(l,h,c,u);var d=new this.BJSCANNON.Quaternion;d.setFromAxisAngle(new this.BJSCANNON.Vec3(1,0,0),-Math.PI/2);var p=new this.BJSCANNON.Vec3(0,0,0);t.transformAllPoints(p,d);break;case Lt.Q.BoxImpostor:var f=n.scale(.5);t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(f.x),this._checkWithEpsilon(f.y),this._checkWithEpsilon(f.z)));break;case Lt.Q.PlaneImpostor:t=new this.BJSCANNON.Plane;break;case Lt.Q.MeshImpostor:var _=i.getVerticesData?i.getVerticesData(wt.o.PositionKind):[],m=i.getIndices?i.getIndices():[];if(!_)return;var g=i.position.clone(),v=i.rotation&&i.rotation.clone(),y=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace();var x,b=i.computeWorldMatrix(!0),T=new Array;for(x=0;x<_.length;x+=3)Te.P.TransformCoordinates(Te.P.FromArray(_,x),b).toArray(T,x);Nt.Y.Warn("MeshImpostor only collides against spheres."),t=new this.BJSCANNON.Trimesh(T,m),i.position.copyFrom(g),v&&i.rotation&&i.rotation.copyFrom(v),y&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(y);break;case Lt.Q.HeightmapImpostor:var S=i.position.clone(),E=i.rotation&&i.rotation.clone(),C=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace(),i.rotationQuaternion&&i.rotationQuaternion.multiplyInPlace(this._minus90X),t=this._createHeightmap(i),i.position.copyFrom(S),E&&i.rotation&&i.rotation.copyFrom(E),C&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(C),i.computeWorldMatrix(!0);break;case Lt.Q.ParticleImpostor:t=new this.BJSCANNON.Particle;break;case Lt.Q.NoImpostor:t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0,0,0));break;case Lt.Q.ConvexHullImpostor:for(var A=e.getParam("shape"),P=A.vertices,R=A.faces,M=A.size*A.scaleFactor,I=new Array(P.length),D=new Array(R.length),O=0;O<P.length;++O){var w=P[O];I[O]=new this.BJSCANNON.Vec3(w[0]*M,w[1]*M,w[2]*M)}for(var N=0;N<R.length;++N)D[N]=R[N].slice(0,R[N].length-1);t=new this.BJSCANNON.ConvexPolyhedron(I,D)}return t}},{key:"_createHeightmap",value:function(e,t){var i,n=e.getVerticesData(wt.o.PositionKind),s=e.computeWorldMatrix(!0),r=new Array;for(i=0;i<n.length;i+=3)Te.P.TransformCoordinates(Te.P.FromArray(n,i),s).toArray(r,i);n=r;for(var o=new Array,a=t||~~(Math.sqrt(n.length/3)-1),l=e.getBoundingInfo(),h=Math.min(l.boundingBox.extendSizeWorld.x,l.boundingBox.extendSizeWorld.y),c=l.boundingBox.extendSizeWorld.z,u=2*h/a,d=0;d<n.length;d+=3){var p=Math.round(n[d+0]/u+a/2),f=Math.round(-1*(n[d+1]/u-a/2)),_=-n[d+2]+c;o[p]||(o[p]=[]),o[p][f]||(o[p][f]=_),o[p][f]=Math.max(_,o[p][f])}for(p=0;p<=a;++p){if(!o[p]){for(var m=1;!o[(p+m)%a];)m++;o[p]=o[(p+m)%a].slice()}for(f=0;f<=a;++f)if(!o[p][f]){var g;for(m=1;void 0===g;)g=o[p][(f+m++)%a];o[p][f]=g}}var v=new this.BJSCANNON.Heightfield(o,{elementSize:u});return v.minY=c,v}},{key:"_updatePhysicsBodyTransformation",value:function(e){var t=e.object;if(t.computeWorldMatrix&&t.computeWorldMatrix(!0),t.getBoundingInfo()){var i=e.getObjectCenter();this._tmpDeltaPosition.copyFrom(t.getAbsolutePivotPoint().subtract(i)),this._tmpDeltaPosition.divideInPlace(e.object.scaling),this._tmpPosition.copyFrom(i);var n=t.rotationQuaternion;if(n){if(e.type!==Lt.Q.PlaneImpostor&&e.type!==Lt.Q.HeightmapImpostor||(n=n.multiply(this._minus90X),e.setDeltaRotation(this._plus90X)),e.type===Lt.Q.HeightmapImpostor){var s=t,r=s.getBoundingInfo(),o=s.rotationQuaternion;s.rotationQuaternion=this._tmpUnityRotation,s.computeWorldMatrix(!0);var a=i.clone(),l=s.getPivotMatrix();l=l?l.clone():Te.y3.Identity();var h=Te.y3.Translation(r.boundingBox.extendSizeWorld.x,0,-r.boundingBox.extendSizeWorld.z);s.setPreTransformMatrix(h),s.computeWorldMatrix(!0);var c=r.boundingBox.centerWorld.subtract(i).subtract(s.position).negate();this._tmpPosition.copyFromFloats(c.x,c.y-r.boundingBox.extendSizeWorld.y,c.z),this._tmpDeltaPosition.copyFrom(r.boundingBox.centerWorld.subtract(a)),this._tmpDeltaPosition.y+=r.boundingBox.extendSizeWorld.y,s.rotationQuaternion=o,s.setPreTransformMatrix(l),s.computeWorldMatrix(!0)}else e.type===Lt.Q.MeshImpostor&&this._tmpDeltaPosition.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpDeltaPosition),e.physicsBody.position.set(this._tmpPosition.x,this._tmpPosition.y,this._tmpPosition.z),e.physicsBody.quaternion.set(n.x,n.y,n.z,n.w)}}}},{key:"setTransformationFromPhysicsBody",value:function(e){if(e.object.position.set(e.physicsBody.position.x,e.physicsBody.position.y,e.physicsBody.position.z),e.object.rotationQuaternion){var t=e.physicsBody.quaternion;e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}},{key:"setPhysicsBodyTransformation",value:function(e,t,i){e.physicsBody.position.set(t.x,t.y,t.z),e.physicsBody.quaternion.set(i.x,i.y,i.z,i.w)}},{key:"isSupported",value:function(){return void 0!==this.BJSCANNON}},{key:"setLinearVelocity",value:function(e,t){e.physicsBody.velocity.set(t.x,t.y,t.z)}},{key:"setAngularVelocity",value:function(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}},{key:"getLinearVelocity",value:function(e){var t=e.physicsBody.velocity;return t?new Te.P(t.x,t.y,t.z):null}},{key:"getAngularVelocity",value:function(e){var t=e.physicsBody.angularVelocity;return t?new Te.P(t.x,t.y,t.z):null}},{key:"setBodyMass",value:function(e,t){e.physicsBody.mass=t,e.physicsBody.updateMassProperties()}},{key:"getBodyMass",value:function(e){return e.physicsBody.mass}},{key:"getBodyFriction",value:function(e){return e.physicsBody.material.friction}},{key:"setBodyFriction",value:function(e,t){e.physicsBody.material.friction=t}},{key:"getBodyRestitution",value:function(e){return e.physicsBody.material.restitution}},{key:"setBodyRestitution",value:function(e,t){e.physicsBody.material.restitution=t}},{key:"sleepBody",value:function(e){e.physicsBody.sleep()}},{key:"wakeUpBody",value:function(e){e.physicsBody.wakeUp()}},{key:"updateDistanceJoint",value:function(e,t){e.physicsJoint.distance=t}},{key:"setMotor",value:function(e,t,i,n){n||(e.physicsJoint.enableMotor(),e.physicsJoint.setMotorSpeed(t),i&&this.setLimit(e,i))}},{key:"setLimit",value:function(e,t,i){e.physicsJoint.motorEquation.maxForce=t,e.physicsJoint.motorEquation.minForce=void 0===i?-t:i}},{key:"syncMeshWithImpostor",value:function(e,t){var i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.quaternion.x,e.rotationQuaternion.y=i.quaternion.y,e.rotationQuaternion.z=i.quaternion.z,e.rotationQuaternion.w=i.quaternion.w)}},{key:"getRadius",value:function(e){return e.physicsBody.shapes[0].boundingSphereRadius}},{key:"getBoxSizeToRef",value:function(e,t){var i=e.physicsBody.shapes[0];t.x=2*i.halfExtents.x,t.y=2*i.halfExtents.y,t.z=2*i.halfExtents.z}},{key:"dispose",value:function(){}},{key:"raycast",value:function(e,t){return this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),this._raycastResult.reset(e,t),this._cannonRaycastResult.hasHit&&(this._raycastResult.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}),this._raycastResult.setHitDistance(this._cannonRaycastResult.distance)),this._raycastResult}}]),e}();Ft.T.DefaultPluginFactory=function(){return new kt};var Gt=function(){function e(t){_(this,e);var i=new kt(16,Ot),n=new Ot.Vec3(0,ee.Gravity,0);t.scene.enablePhysics(n,i)}return y(e,[{key:"remove",value:function(e){var t;null===(t=e.physicsImpostor)||void 0===t||t.dispose()}},{key:"collisionEvent",value:function(e,t){e.physicsImpostor.physicsBody.addEventListener("collide",(function(e){return t(e)}))}},{key:"add",value:function(e,t,i){var n,s,r;return e.physicsImpostor=new M.PhysicsImpostor(e,M.PhysicsImpostor.ConvexHullImpostor,{shape:t,mass:null!==(n=i.mass)&&void 0!==n?n:t.mass,friction:null!==(s=i.friction)&&void 0!==s?s:ee.DiceFriction,restitution:null!==(r=i.restitution)&&void 0!==r?r:ee.DiceRestitution,nativeOptions:{contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}}),e.physicsImpostor.collisionFilterGroup=2,e.physicsImpostor.collisionFilterMask=3,e}},{key:"AddFloor",value:function(e){return e.physicsImpostor=new M.PhysicsImpostor(e,M.PhysicsImpostor.PlaneImpostor,{mass:0,friction:ee.FloorFriction,restitution:ee.FloorRestitution,nativeOptions:{contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}}),e.physicsImpostor.collisionFilterGroup=1,e.physicsImpostor.collisionFilterMask=2,e}},{key:"AddBarriers",value:function(e){return e.physicsImpostor=new M.PhysicsImpostor(e,M.PhysicsImpostor.PlaneImpostor,{mass:0,friction:ee.BarrierFriction,restitution:ee.BarrierRestitution,nativeOptions:{contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}}),e.physicsImpostor.collisionFilterGroup=1,e.physicsImpostor.collisionFilterMask=2,e}}]),e}(),zt=o(3849),Wt=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2?arguments[2]:void 0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};_(this,e),x(this,"logger",void 0),x(this,"PhysicsManager",void 0),x(this,"floor",void 0),x(this,"floorOffset",void 0),x(this,"scene",void 0),x(this,"SCREEN_WIDTH",void 0),x(this,"SCREEN_HEIGHT",void 0),x(this,"VIEW_ANGLE",void 0),x(this,"ASPECT",void 0),x(this,"NEAR",void 0),x(this,"FAR",void 0),x(this,"barriers",void 0),x(this,"camera",void 0),x(this,"engine",void 0),x(this,"canvas",void 0),x(this,"w",void 0),x(this,"h",void 0),x(this,"wh",void 0),x(this,"cw",void 0),x(this,"ch",void 0),x(this,"aspect",void 0),x(this,"scale",void 0),x(this,"stats",void 0),x(this,"bloomPass",void 0),x(this,"shadowGenerator",void 0),x(this,"environment",void 0),x(this,"assetBaseLocation",void 0),x(this,"previewMode",void 0),this.logger=new oe(this),this.scene=null,this.canvas=t,this.w=this.canvas.clientWidth/2,this.h=this.canvas.clientHeight/2,this.SCREEN_WIDTH=window.innerWidth,this.SCREEN_HEIGHT=window.innerHeight,this.VIEW_ANGLE=35,this.ASPECT=this.SCREEN_WIDTH/this.SCREEN_HEIGHT,this.NEAR=1,this.FAR=2e3,this.barriers=[],this.assetBaseLocation=n,this.previewMode=i,this.initEngine(this.canvas,this.previewMode,s),this.addCamera($.CameraStartHeight,$.CameraFOV);var r=this.addLights();this.setShadowQuality(r),this.enableSound($.SoundEnabled)}var t;return y(e,[{key:"addPhysics",value:function(e){this.scene.physicsEnabled=!0,this.PhysicsManager=e,this.addFloor(),this.previewMode||this.addBarriers()}},{key:"initEngine",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};i.xrCompatible=!1,this.engine=new M.Engine(e,!/OS 15_4/i.test(navigator.userAgent)||!("maxTouchPoints"in navigator&&navigator.maxTouchPoints>0||"matchMedia"in window&&window.matchMedia("(pointer:coarse)").matches||"orientation"in window||/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(navigator.userAgent)||/\b(Android|Windows Phone|iPad|iPod)\b/i.test(navigator.userAgent)),i),this.engine.getCaps().parallelShaderCompile=void 0,this.scene=new M.Scene(this.engine),this.scene.useRightHandedSystem=!0,this.scene.clearColor=new M.Color4(0,0,0,.01),this.scene.ambientColor=new M.Color3(1,1,1);var n;n=$.environmentTexture.endsWith("/")?new M.CubeTexture("".concat(this.assetBaseLocation,"/images/common/").concat($.environmentTexture),this.scene):M.CubeTexture.CreateFromPrefilteredData("".concat(this.assetBaseLocation,"/images/common/").concat($.environmentTexture),this.scene),this.environment=this.scene.createDefaultEnvironment({createSkybox:t,enableGroundMirror:!1,createGround:!0,groundSize:20,enableGroundShadow:!0,skyboxSize:50,environmentTexture:n,groundTexture:"".concat(this.assetBaseLocation,"/images/common/backgroundGround.png")}),this.environment.ground.isVisible=!1,this.scene.environmentTexture=n,M.Effect.ShadersStore.particlesVertexShader="// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nuniform vec3 origin;\n\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; // x (number of rows) y(number of columns) z(rowSize)\n#endif\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\nvarying vec4 vWorldPos;\n\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n\n#ifdef BILLBOARD\n\tuniform vec3 eyePosition;\n#endif\n\nvec3 rotate(vec3 yaxis, vec3 rotatedCorner) {\n\tvec3 xaxis = normalize(cross(vec3(0., 1.0, 0.), yaxis));\n\tvec3 zaxis = normalize(cross(yaxis, xaxis));\n\n\tvec3 row0 = vec3(xaxis.x, xaxis.y, xaxis.z);\n\tvec3 row1 = vec3(yaxis.x, yaxis.y, yaxis.z);\n\tvec3 row2 = vec3(zaxis.x, zaxis.y, zaxis.z);\n\n\tmat3 rotMatrix = mat3(row0, row1, row2);\n\n\tvec3 alignedCorner = rotMatrix * rotatedCorner;\n\treturn position + alignedCorner;\n}\n\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera, vec3 rotatedCorner) {\n\tvec3 normalizedToCamera = normalize(toCamera);\n\tvec3 normalizedCrossDirToCamera = normalize(cross(normalize(direction), normalizedToCamera));\n\tvec3 crossProduct = normalize(cross(normalizedToCamera, normalizedCrossDirToCamera));\n\n\tvec3 row0 = vec3(normalizedCrossDirToCamera.x, normalizedCrossDirToCamera.y, normalizedCrossDirToCamera.z);\n\tvec3 row1 = vec3(crossProduct.x, crossProduct.y, crossProduct.z);\n\tvec3 row2 = vec3(normalizedToCamera.x, normalizedToCamera.y, normalizedToCamera.z);\n\n\tmat3 rotMatrix = mat3(row0, row1, row2);\n\n\tvec3 alignedCorner = rotMatrix * rotatedCorner;\n\treturn position + alignedCorner;\n}\n#endif\n\nvoid main(void) {\n\tvec2 cornerPos;\n\n\tcornerPos = (vec2(offset.x - 0.5, offset.y - 0.5) - translationPivot) * size + translationPivot;\n#ifdef BILLBOARD\n\t// Rotate\n\tvec3 rotatedCorner;\n\n\t#ifdef BILLBOARDY\n\t\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n\t\trotatedCorner.z = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n\t\trotatedCorner.y = 0.;\n\n\t\tvec3 yaxis = position - eyePosition;\n\t\tyaxis.y = 0.;\n\n\t\tvec3 worldPos = rotate(normalize(yaxis), rotatedCorner);\n\n\t\tvec3 viewPos = (view * vec4(worldPos, 1.0)).xyz;\n\t#elif defined(BILLBOARDSTRETCHED)\n\t\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n\t\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n\t\trotatedCorner.z = 0.;\n\n\t\tvec3 toCamera = position - eyePosition;\n\t\tvec3 worldPos = rotateAlign(toCamera, rotatedCorner);\n\n\t\tvec3 viewPos = (view * vec4(worldPos, 1.0)).xyz;\n\t#else\n\t\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n\t\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n\t\trotatedCorner.z = 0.;\n\n\t\tvec3 viewPos = (view * vec4(position, 1.0)).xyz + rotatedCorner;\n\t\tvWorldPos = vec4((view * vec4(position - origin, 1.0)).xyz + rotatedCorner, 1.0);\n\n\t#endif\n\n\t#ifdef RAMPGRADIENT\n\t\tremapRanges = remapData;\n\t#endif\n\n\t// Position\n\tgl_Position = projection * vec4(viewPos, 1.0);\n\n#else\n\t// Rotate\n\tvec3 rotatedCorner;\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n\trotatedCorner.z = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n\trotatedCorner.y = 0.;\n\n\tvec3 yaxis = normalize(direction);\n\tvec3 worldPos = rotate(yaxis, rotatedCorner);\n\tgl_Position = projection * view * vec4(worldPos, 1.0);\n#endif\n\tvColor = color;\n\n\t#ifdef ANIMATESHEET\n\t\tfloat rowOffset = floor(cellIndex / particlesInfos.z);\n\t\tfloat columnOffset = cellIndex - rowOffset * particlesInfos.z;\n\n\t\tvec2 uvScale = particlesInfos.xy;\n\t\tvec2 uvOffset = vec2(offset.x , 1.0 - offset.y);\n\t\tvUV = (uvOffset + vec2(columnOffset, rowOffset)) * uvScale;\n\t#else\n\t\tvUV = offset;\n\t#endif\n\n\t// Clip plane\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\n#endif\n\t#include<clipPlaneVertex>\n\n\t\t//vWorldPos.w = 1.0;\n\n\n}"}},{key:"isSceneIdle",value:function(){return this.scene.meshes.filter((function(e){return!(e instanceof M.GroundMesh||e.name.startsWith("ground")||e.name.startsWith("Background"))})).length<1}},{key:"enableRenderLoop",value:function(e,t){var i=this;e?(this.logger.log("Enabling render loop"),this.engine.runRenderLoop((function(){var e=isNaN(i.scene.deltaTime)?0:i.scene.deltaTime;t&&t(e),i.scene.render()}))):(this.logger.log("Disabling render loop"),this.engine.stopRenderLoop())}},{key:"enableSceneDebugger",value:(t=f(T().mark((function e(){return T().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,o.e(273).then(o.t.bind(o,6273,23));case 2:this.scene.debugLayer.show({overlay:!0});case 3:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"addCamera",value:function(e,t,i){var n;this.camera&&this.camera.dispose(),i?(n=i.meshParent.position).y=.5*i.options.baseHeight:n=M.Vector3.Zero();var s=new M.ArcRotateCamera("mainCamera",0,0,e,n,this.scene);i&&(s.upperBetaLimit=$.CameraUpperBetaLimit,s.lowerBetaLimit=$.CameraLowerBetaLimit,s.upperRadiusLimit=$.CameraUpperRadiusLimit,s.lowerRadiusLimit=$.CameraLowerRadiusLimit,s.wheelPrecision=$.CameraWheelPrecision,s.minZ=$.CameraMinZ,s.attachControl(this.canvas,!0)),this.camera=s,this.camera.fov=t,this.camera.attachControl(this.canvas,!0)}},{key:"setFloorOffset",value:function(){this.floor.position.y=this.floorOffset}},{key:"addLights",value:function(){var e=new M.DirectionalLight("dirLight",new M.Vector3(5,-10,5),this.scene);return e.direction.normalize(),e.shadowMinZ=-30,e.shadowMaxZ=30,e.position=new M.Vector3(0,0,0),e.shadowEnabled=!0,e.autoUpdateExtends=!1,e.shadowFrustumSize=$.ShadowFrustumSize,new M.HemisphericLight("hemiLight",new M.Vector3(-.2,1,-.2),this.scene).intensity=.5,$.GlowIntensity>0&&(new M.GlowLayer("glow",this.scene,{mainTextureSamples:4}).intensity=$.GlowIntensity),e}},{key:"setShadowQuality",value:function(e){switch($.Shadow>K.None&&(this.shadowGenerator=new M.ShadowGenerator([0,1024,2048,2048][$.Shadow],e),this.shadowGenerator.bias=.001,this.shadowGenerator.normalBias=.01,this.shadowGenerator.darkness=.5,this.shadowGenerator.blurScale=2,this.shadowGenerator.frustumEdgeFalloff=.5,this.shadowGenerator.transparencyShadow=!0),$.Shadow){case K.None:this.scene.shadowsEnabled=!1;break;case K.Low:this.scene.shadowsEnabled=!0;break;case K.Medium:this.shadowGenerator.useExponentialShadowMap=!0,this.shadowGenerator.depthScale=10,this.scene.shadowsEnabled=!0;break;case K.High:this.shadowGenerator.useBlurExponentialShadowMap=!0,this.shadowGenerator.depthScale=10,this.shadowGenerator.useKernelBlur=!0,this.shadowGenerator.blurKernel=15,this.scene.shadowsEnabled=!0}this.setupCustomShadowShader()}},{key:"setupCustomShadowShader",value:function(){var e;M.Effect.ShadersStore.customShadowVertexShader="// This file seems to heavily influenced from\n// https://github.com/BabylonJS/Babylon.js/blob/master/packages/dev/core/src/Shaders/shadowMap.vertex.fx,\n// so if something goes wrong check what's changed there first.\n\n//Attribute\nattribute vec3 position;\n\n#ifdef NORMAL\n attribute vec3 normal;\n#endif\n\n#include<bonesDeclaration>\n\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<__decl__sceneVertex>\n#include<__decl__meshVertex>\n\n// Uniforms\n#include<helperFunctions>\n\nvarying vec3 vPositionW;\n\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\n#include<shadowMapVertexExtraDeclaration>\n\n#include<clipPlaneVertexDeclaration>\n\nvoid main(void)\n{\nvec3 positionUpdated = position;\n#ifdef UV1\n vec2 uvUpdated = uv;\n#endif \n#ifdef NORMAL\t\n\tvec3 normalUpdated = normal;\n#endif\n\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n\n#include<instancesVertex>\n#include<bonesVertex>\n\nvec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\nvPositionW = worldPos.xyz;\n#ifdef NORMAL\n mat3 normWorldSM = mat3(finalWorld);\n\n #if defined(INSTANCES) && defined(THIN_INSTANCES)\n vec3 vNormalW = normalUpdated / vec3(dot(normWorldSM[0], normWorldSM[0]), dot(normWorldSM[1], normWorldSM[1]), dot(normWorldSM[2], normWorldSM[2]));\n vNormalW = normalize(normWorldSM * vNormalW);\n #else\n #ifdef NONUNIFORMSCALING\n normWorldSM = transposeMat3(inverseMat3(normWorldSM));\n #endif\n\n vec3 vNormalW = normalize(normWorldSM * normalUpdated);\n #endif\n#endif\n\n#include<shadowMapVertexNormalBias>\n\n// Projection.\ngl_Position = viewProjection * worldPos;\n\n#include<shadowMapVertexMetric>\n\n #ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uvUpdated, 1.0, 0.0));\n #endif\n #ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n #endif\n\n#include<clipPlaneVertex>\n\n}\n",M.Effect.ShadersStore.customShadowFragmentShader="#include<shadowMapFragmentExtraDeclaration>\n\n\nvarying vec3 vPositionW;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float dissolve;\nuniform sampler2D noise;\n#include<clipPlaneFragmentDeclaration>\n\nvoid main(void)\n{\n#include<clipPlaneFragment>\n\n#ifdef ALPHATEST\n float alphaFromAlphaTexture = texture2D(diffuseSampler, vUV).a;\n if (alphaFromAlphaTexture < 0.4)\n discard;\n#endif\n\n float n = texture2D(noise, vPositionW.xz).x - dissolve;\n if (n < 0.0) { discard; }\n\n#if SM_SOFTTRANSPARENTSHADOW == 1\n #ifdef ALPHATEST\n if ((bayerDither8(floor(mod(gl_FragCoord.xy, 8.0)))) / 64.0 >= softTransparentShadowSM * alphaFromAlphaTexture) discard;\n #else\n if ((bayerDither8(floor(mod(gl_FragCoord.xy, 8.0)))) / 64.0 >= softTransparentShadowSM) discard;\n #endif\n#endif\n\n#include<shadowMapFragment>\n}\n",this.shadowGenerator.customShaderOptions={shaderName:"customShadow",attributes:["uv"],uniforms:["dissolve"],samplers:["noise"]},this.shadowGenerator.onBeforeShadowMapRenderMeshObservable.add((function(t){return e=t})),this.shadowGenerator.onBeforeShadowMapRenderObservable.add((function(t){e.material&&(e.material instanceof lt?(t.setFloat("dissolve",e.material.dissolveValue),t.setTexture("noise",e.material.dissolveTexture)):(t.setFloat("dissolve",0),t.setTexture("noise",null)))}))}},{key:"enableSound",value:function(e){var t,i=this;this.scene.audioEnabled=e,this.scene.audioListenerPositionProvider=function(){return i.camera.position},null===(t=M.Engine.audioEngine)||void 0===t||t.setGlobalVolume($.MasterVolume)}},{key:"addFloor",value:function(){var e=M.Mesh.CreatePlane("ground",120,this.scene,!0);this.PhysicsManager.AddFloor(e),e.isVisible=!1;var t=M.Mesh.CreatePlane("groundShadow",120,this.scene,!0);t.isVisible=!0;var i=new zt.ShadowOnlyMaterial("shadow",this.scene);i.sideOrientation=M.Mesh.DOUBLESIDE,i.transparencyMode=M.Material.MATERIAL_ALPHABLEND,i.alphaMode=M.Engine.ALPHA_MAXIMIZED,t.receiveShadows=!0,t.rotation.x=-Math.PI/2,t.material=i}},{key:"addBarriers",value:function(){this.barriers.push(this.addBarrier("wall1",new M.Vector3(0,0,.06*-this.h),M.Axis.X,Math.PI/2),this.addBarrier("wall2",new M.Vector3(0,0,.06*this.h),M.Axis.X,-Math.PI/2),this.addBarrier("wall3",new M.Vector3(.04*this.w,0,0),M.Axis.Z,Math.PI/2),this.addBarrier("wall4",new M.Vector3(.04*-this.w,0,0),M.Axis.Z,-Math.PI/2))}},{key:"addBarrier",value:function(e,t,i,n){var s=M.Mesh.CreateGround(e,20,20,2,this.scene);return s.position=t,s.rotate(i,n,M.Space.WORLD),s.isVisible=!1,this.PhysicsManager.AddBarriers(s),s}},{key:"reInit",value:function(e,t){this.cw=this.canvas.clientWidth/2,this.ch=this.canvas.clientHeight/2,e?(this.w=e.w,this.h=e.h):(this.w=this.cw,this.h=this.ch),this.aspect=Math.min(this.cw/this.w,this.ch/this.h),this.scale=Math.sqrt(this.w*this.w+this.h*this.h)/13,this.wh=this.ch/this.aspect/Math.tan(10*Math.PI/180),t&&this.resetBarrierPositions(),this.engine.resize()}},{key:"resetBarrierPositions",value:function(){var e=this.canvas.getBoundingClientRect();if(this.barriers.length>0){var t=Pt(e.width,e.height/2,this.camera,e);this.barriers[0].position=new M.Vector3(t.x,t.y,t.z),t=Pt(0,e.height/2,this.camera,e),this.barriers[1].position=new M.Vector3(t.x,t.y,t.z),t=Pt(e.width/2,e.height,this.camera,e),this.barriers[2].position=new M.Vector3(t.x,t.y,t.z),t=Pt(e.width/2,0,this.camera,e),this.barriers[3].position=new M.Vector3(t.x,t.y,t.z)}}}]),e}(),Ht=y((function e(t,i){_(this,e),x(this,"dice",void 0),x(this,"value",void 0),x(this,"stableCount",void 0),x(this,"result",void 0),this.dice=t,this.value=i,this.stableCount=0,this.result=null})),Xt=function(){function i(){_(this,i),x(this,"currentCollisionEffectDice",0),x(this,"maxCollisionEffectDice",20),x(this,"reInitTimeout",void 0),x(this,"dice",void 0),x(this,"diceRemoved",void 0),x(this,"diceConstant",void 0),x(this,"diceNotation",void 0),x(this,"SceneManager",void 0),x(this,"baseLocation",void 0),x(this,"PhysicsManager",void 0),x(this,"_isRolling",void 0),x(this,"rollRequest",void 0),x(this,"diceValues",void 0),x(this,"throwRunning",void 0),x(this,"stableCount",void 0),x(this,"result",void 0),x(this,"diceManifest",void 0),x(this,"diceAutoClearTimeout",void 0),x(this,"enableAutoClear",!0),x(this,"animationEnabled",!1),x(this,"logger",void 0),x(this,"previewDie",void 0),x(this,"assetsReadyPromise",void 0),x(this,"diceUserConfig",void 0),x(this,"_eventObservables",new Map),x(this,"_updateView",!1),x(this,"dimensions",void 0),x(this,"_messageBroker",void 0),x(this,"stackOrder",0),this.dice=[],this.diceRemoved=[],this.diceConstant=0,this.SceneManager=null,this.baseLocation="",this.baseLocation="https://stg.dndbeyond.com/dice",this.logger=new oe(this),this._eventObservables[n.ROLL]=new M.Observable,this._eventObservables[n.CLEAR]=new M.Observable}var o,a,l,h;return y(i,[{key:"analyticsInit",value:function(e,t){At.init(e,t)}},{key:"updateSettings",value:function(e){this.diceUserConfig=e;var t=e.settings;$.SoundEnabled=0!=t.volume,$.MasterVolume=t.volume,$.Shadow=t.shadowQuality,$.Particles=t.particlesEnabled,$.Vibrate=t.vibrationEnabled}},{key:"init",value:(h=f(T().mark((function e(t){var i,n,s,r,o,a,l;return T().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=t.assetBaseLocation,n=t.diceUserConfig,s=t.canvas,r=t.previewMode,o=t.isDebug,a=t.engineOptions,i&&(this.baseLocation=t.assetBaseLocation),this.updateSettings(n),this.SceneManager=new Wt(s,r,this.baseLocation,a),this.PhysicsManager=new Gt(this.SceneManager),this.SceneManager.addPhysics(this.PhysicsManager),s||this.logger.error("Canvas must be a valid HTMLCanvasElement"),l={w:s.clientWidth,h:s.clientHeight},this.SceneManager.reInit(l,!0),o&&this.SceneManager.enableSceneDebugger(),e.prev=10,e.next=13,new Promise(((e,t)=>function i(){const n=N?F:window[I];void 0===n?"complete"!==document.readyState&&"interactive"!==document.readyState?setTimeout(i,100):t(new Error("A message broker was never instantiated in this document")):e(n)}()));case 13:this._messageBroker=e.sent,e.next=19;break;case 16:e.prev=16,e.t0=e.catch(10),this.logger.log(e.t0);case 19:return e.abrupt("return",new Promise((function(e){return e()})));case 20:case"end":return e.stop()}}),e,this,[[10,16]])}))),function(e){return h.apply(this,arguments)})},{key:"_removeCurrentMaterialsAndTextures",value:function(){var e=this,t=["BackgroundPlaneMaterial","BackgroundSkyboxMaterial","default material","shadow"];_e.clearTextureCache();for(var i=1;i>0;)i=0,this.SceneManager.scene.materials.forEach((function(n){t.includes(n.name)||(i++,n.unbind(),e.SceneManager.scene.removeMaterial(n),n.dispose())}))}},{key:"load",value:function(e){var t=this;return this.clear(),this.previewDie&&this.previewDie.dispose(),this._removeCurrentMaterialsAndTextures(),this.assetsReadyPromise=new Promise(function(){var i=f(T().mark((function i(n){var s,r,o;return T().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return s="".concat(t.baseLocation).concat(e),i.prev=1,r=new Et(t.baseLocation,t.SceneManager.scene),i.next=5,r.loadManifest(s);case 5:return o=i.sent,t.diceManifest=o,i.next=9,r.loadAssets();case 9:return t.logger.debug("Assets loaded"),i.next=12,r.correlateResources(t.SceneManager.scene);case 12:t.logger.debug("Assets correlated"),n(o),i.next=19;break;case 16:i.prev=16,i.t0=i.catch(1),t.logger.error("Error loading manifest ".concat(s,": ").concat(i.t0));case 19:case"end":return i.stop()}}),i,null,[[1,16]])})));return function(e){return i.apply(this,arguments)}}()),this.assetsReadyPromise}},{key:"loadBundle",value:function(e){var t=this;return this.assetsReadyPromise=new Promise(function(){var i=f(T().mark((function i(n){var s,r,o,a,l;return T().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return i.prev=0,s=new(k()),i.next=4,s.loadAsync(e);case 4:return r=i.sent,i.next=7,r.file("manifest.json").async("text");case 7:return o=i.sent,a=new Et(t.baseLocation,t.SceneManager.scene,r),l=JSON.parse(o),t.diceManifest=l,a.manifest=l,i.next=14,a.loadAssets();case 14:return i.next=16,a.correlateResources(t.SceneManager.scene);case 16:n(t.diceManifest),i.next=22;break;case 19:i.prev=19,i.t0=i.catch(0),t.logger.error(i.t0);case 22:case"end":return i.stop()}}),i,null,[[0,19]])})));return function(e){return i.apply(this,arguments)}}()),this.assetsReadyPromise}},{key:"reInit",value:function(e){this.dimensions=e,this._updateView=!0,this.SceneManager.reInit(e,!1)}},{key:"_resetView",value:function(){this.dimensions=void 0,this._updateView=!1,this.SceneManager.reInit(this.dimensions,!0)}},{key:"clear",value:function(){if(!this._isRolling&&0!==this.dice.length){for(var e=0;e<this.diceRemoved.length;e++)this.diceRemoved[e].dispose();this.diceRemoved=[];for(var t=0;t<this.dice.length;t++){var i=this.dice[t];i.onDieRemoved(),this.dice[t].runRemoval(),this.dice.splice(t,1),this.diceRemoved.push(i),t--}this.dice=[],this.diceConstant=0,this.rollRequest=void 0,this.currentCollisionEffectDice=0,this._processEvent(n.CLEAR,void 0)}}},{key:"readyToRoll",value:function(){return this.assetsReadyPromise||Promise.reject("No assets loaded")}},{key:"_processRollKind",value:function(e){switch(e.rollKind){case c.Advantage:e.diceNotation.set.forEach((function(e){e.dieType===r.d20&&(e.count+=1,e.operation=s.Max,e.operand=1)}));break;case c.Disadvantage:e.diceNotation.set.forEach((function(e){e.dieType===r.d20&&(e.count+=1,e.operation=s.Min,e.operand=1)}));break;case c.CriticalHit:e.diceNotation.set.forEach((function(e){return e.count*=2}))}}},{key:"roll",value:(l=f(T().mark((function i(s,r,o){var a,l,h=this;return T().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return l="string"==typeof s?new Dt("custom",s):s,null===(a=M.Engine.audioEngine)||void 0===a||a.unlock(),this._updateView&&this._resetView(),i.next=5,this.readyToRoll();case 5:return l.setId=this.diceUserConfig.setId,l.rollId=Y(),i.abrupt("return",new Promise(function(){var i=f(T().mark((function i(s,a){var c,u,d,p,f,_,m,g;return T().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:if(i.prev=0,clearTimeout(h.diceAutoClearTimeout),h.enableAnimation(!0),!h._isRolling){i.next=6;break}return a(new Error("There is already a roll in progress.")),i.abrupt("return");case 6:"custom"===l.action?At.log(e.DICE_Toolbar,t.DICE_Roll):At.log(e.DICE_Advanced,t.DICE_Roll,l.action),h.clear(),h._isRolling=!0,h.rollRequest=l,c=0;case 11:if(!(c<h.rollRequest.rolls.length)){i.next=25;break}if(u=h.rollRequest.rolls[c],h._processRollKind(u),h.addDice(u.diceNotation,c),0!=u.diceNotation.set.length){i.next=22;break}return h._isRolling=!1,h.throwRunning=!1,h.result=h._getResultConstant(),h.broadcastRollMessage(h.result,"fulfilled"),s(h.result),i.abrupt("return");case 22:c++,i.next=11;break;case 25:return h.broadcastRollMessage(l,"pending"),i.next=28,h._waitForDiceMeshesReady();case 28:for(h.diceValues=[],d=h.SceneManager.canvas.getBoundingClientRect(),void 0===r&&(r=d.width/2+d.left),void 0===o&&(o=d.height/2+d.top),p=mt.CreateRandomVelocity(h.dice.length),f=[],_=0;_<h.dice.length;_++)f.push(h.dice[_].roll(Pt(r-d.left,o-d.top,h.SceneManager.camera,h.SceneManager.canvas.getBoundingClientRect()),_,h.dice.length,p)),h.diceValues.push(new Ht(h.dice[_],1));return i.next=37,Promise.all(f);case 37:!h.throwRunning&&h.dice&&h.dice.length>0&&h._prepareValues(),h.result=null,m=0,g=setInterval((function(){h.result?(h._isRolling=!1,h._startAutoClear(),h.broadcastRollMessage(h.result,"fulfilled"),s(h.result),clearInterval(g),h._processEvent(n.ROLL,h.result)):(m+=500)>=1e4&&(h._isRolling=!1,h.throwRunning=!1,h.diceValues.forEach((function(e){var t=e.dice.getUpsideValue().dieValue;e.result!==t&&(e.result=t,e.dice.onRollComplete(t))})),h._setResult(),h._startAutoClear(),h.broadcastRollMessage(h.result,"fulfilled"),s(h.result),clearInterval(g),h._processEvent(n.ROLL,h.result))}),500),setInterval((function(){return h.checkForIdleScene()}),1e3),i.next=50;break;case 46:i.prev=46,i.t0=i.catch(0),h.broadcastRollMessage(l,"rejected"),a(new Error(i.t0));case 50:case"end":return i.stop()}}),i,null,[[0,46]])})));return function(e,t){return i.apply(this,arguments)}}()));case 8:case"end":return i.stop()}}),i,this)}))),function(e,t,i){return l.apply(this,arguments)})},{key:"broadcastRollMessage",value:(a=f(T().mark((function e(t,i){var n,s,r,o,a,l,h,c,u,d;return T().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:null===(n=this._messageBroker)||void 0===n||n.dispatch({data:t,entityId:null===(s=t.context)||void 0===s||null===(r=s.entityId)||void 0===r?void 0:r.toString(),entityType:null===(o=t.context)||void 0===o||null===(a=o.entityType)||void 0===a?void 0:a.toString(),eventType:"dice/roll/".concat(i),persist:"fulfilled"===i,messageScope:null!==(l=null===(h=t.context)||void 0===h?void 0:h.messageScope)&&void 0!==l?l:"gameId",messageTarget:null!==(c=null===(u=t.context)||void 0===u||null===(d=u.messageTarget)||void 0===d?void 0:d.toString())&&void 0!==c?c:this._messageBroker.gameId});case 1:case"end":return e.stop()}}),e,this)}))),function(e,t){return a.apply(this,arguments)})},{key:"_startAutoClear",value:function(){var e=this;this.enableAutoClear&&(this.diceAutoClearTimeout=setTimeout((function(){return e.clear()}),1e3*$.AutoClearSeconds))}},{key:"_waitForDiceMeshesReady",value:function(){var e=this;return new Promise((function(t){var i=setInterval((function(){var n=e.dice.filter((function(e){return!e.isReady()})).length;n<1?(e.logger.log("All Dice Ready"),clearInterval(i),t()):e.logger.log("".concat(n," assets not yet ready"))}),10)}))}},{key:"_instantiateDie",value:function(e){var t=new mt(this,q[e]);return t.create(this.diceManifest,e,this.currentCollisionEffectDice++<this.maxCollisionEffectDice),t}},{key:"showDicePreview",value:(o=f(T().mark((function e(t){var i,n,s,o=arguments;return T().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=!(o.length>1&&void 0!==o[1])||o[1],e.next=3,this.readyToRoll();case 3:return this.previewDie&&(this.previewDie.runRemoval(),this.previewDie.dispose()),n=this._instantiateDie(t),this.previewDie=n,n.onRollBegin(),this._addDie(this.previewDie),e.next=10,this._waitForDiceMeshesReady();case 10:this.SceneManager.addCamera($.PreviewCameraStartHeight,$.PreviewCameraFOV,this.previewDie),this.SceneManager.environment.ground.isVisible=i,this.SceneManager.floor&&(this.SceneManager.floor.isVisible=!1),this.previewDie.meshParent.addRotation(M.Tools.ToRadians(q[t].baseRotation.x),M.Tools.ToRadians(q[t].baseRotation.y),M.Tools.ToRadians(q[t].baseRotation.z)),this.enableAnimation(!0),s=t==r.d100?0:this.previewDie.options.values,this.previewDie.onRollComplete(s),this.previewDie.setEnabled(!0);case 18:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"addDice",value:function(e,t){for(var i=0;i<e.set.length;i++){var n=e.set[i];n.dice=[];for(var s=0;s<n.count;s++)if(n.dieType===r.d100){var o=this._instantiateDie(n.dieType);o.rollIndex=t,this._addDie(o),n.dice.push(o);var a=this._instantiateDie("d10");a.rollIndex=t,this._addDie(a),o.pairedDie=a,a.pairedDie=o}else{var l=this._instantiateDie(n.dieType);l.rollIndex=t,this._addDie(l),n.dice.push(l)}}this.diceConstant+=e.constant}},{key:"_addDie",value:function(e){this.dice.push(e)}},{key:"checkForIdleScene",value:function(){this.animationEnabled&&this.SceneManager.isSceneIdle()&&this.enableAnimation(!1)}},{key:"enableAnimation",value:function(e){var t=this;this.animationEnabled!=e&&(this.SceneManager.enableRenderLoop(e,(function(e){t.animationEnabled&&t.update(e)})),this.animationEnabled=e,this.logger.debug("Animation ".concat(this.animationEnabled?"enabled":"disabled")))}},{key:"update",value:function(e){for(var t=0;t<this.dice.length;t++)null!=this.dice[t]&&this.dice[t].update(e);for(var i=0;i<this.diceRemoved.length;i++)null!=this.diceRemoved[i]&&this.diceRemoved[i].update(e);if(this.throwRunning){for(var n=!0,s=0;s<this.diceValues.length;s++){if(this.diceValues[s].dice.isFinished()){if(0===this.diceValues[s].stableCount){var r=this.diceValues[s].dice.getUpsideValue().dieValue;this.diceValues[s].result!==r&&(this.diceValues[s].result=r,this.diceValues[s].dice.onRollComplete(r))}this.diceValues[s].stableCount++}else this.diceValues[s].stableCount=0;this.diceValues[s].stableCount<20&&(n=!1)}n&&this._setResult()}}},{key:"_processEvent",value:function(e,t){var i=this._eventObservables[e];i&&i.notifyObservers(t)}},{key:"addEventListener",value:function(e,t){var i=this._eventObservables[e];if(!i)throw new Error("Unknown eventType ".concat(e));i.add(t)}},{key:"removeEventListener",value:function(e,t){var i=this._eventObservables[e];if(!i)throw new Error("Unknown eventType ".concat(e));i.removeCallback(t)}},{key:"_setResult",value:function(){var e=this;this.throwRunning=!1,this.result=this.rollRequest;for(var t=function(){var t,n=e.result.rolls[i];n.result={},n.result.constant=n.diceNotation.constant,n.result.values=[];for(var s=0;s<n.diceNotation.set.length;s++)n.diceNotation.set[s].dice.forEach((function(e){var t=e.getUpsideValue().result;e.disablePhysics(),e.pairedDie&&e.pairedDie.disablePhysics(),1===t?(e.onMinRoll(),e.pairedDie&&e.pairedDie.onMinRoll()):t===e.options.values&&(e.onMaxRoll(),e.pairedDie&&e.pairedDie.onMaxRoll()),n.result.values.push(t)}));(t=[]).concat.apply(t,R(e.result.rolls.map((function(e){var t;return(t=[]).concat.apply(t,R(e.diceNotation.set.map((function(e){return e.dice}))))})))).forEach((function(e){e.uniformContainer.setVec3("topFaceNormal",e.result.normal),e.pairedDie&&e.pairedDie.uniformContainer.setVec3("topFaceNormal",e.pairedDie.result.normal)}));var r=n.diceNotation.set.reduce((function(e,t){return e+t.getResult()}),0);n.result.total=r+n.diceNotation.constant;var o=0==n.diceNotation.constant?"":"+".concat(n.diceNotation.constant),a=n.diceNotation.set.map((function(e){return e.getResultStr()})).join("+");n.result.text="".concat(a).concat(o)},i=0;i<this.result.rolls.length;i++)t()}},{key:"_getResultConstant",value:function(){for(var e=this.rollRequest,t=0;t<e.rolls.length;t++){var i=e.rolls[t];i.result={},i.result.constant=i.diceNotation.constant,i.result.total=i.diceNotation.constant,i.result.values=[]}return e}},{key:"_prepareValues",value:function(){this.throwRunning=!0;for(var e=0;e<this.diceValues.length;e++)this.diceValues[e].stableCount=0}}]),i}();function jt(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Yt(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?jt(Object(i),!0).forEach((function(t){x(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):jt(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}var qt=function(){function n(){_(this,n),x(this,"defaultDiceManifestUrl","/bundles/basic/default.json"),x(this,"_diceManager",void 0),x(this,"_notifier",void 0),x(this,"_initializationPromise",void 0),x(this,"_error",void 0),x(this,"trackingId",void 0),x(this,"sessionName",void 0),this._diceManager=new Xt}var s,r;return y(n,[{key:"init",value:function(e){var t=this;if(this._initializationPromise)return this._initializationPromise;var n=Yt(Yt(Yt({},{assetBaseLocation:"./",notifier:new C,diceUserConfig:i}),e),{},{isDebug:window.location.search.includes("dice-debug")});return this.analyticsInit(n.trackingId,n.sessionName),this.checkWebGl()?(window.location.search&&window.location.search.indexOf("dice-noclear")>0&&(this._diceManager.enableAutoClear=!1),this._notifier=n.notifier,this._initializationPromise=this._diceManager.init(n).then((function(){return window.addEventListener("resize",(function(){return t._diceManager.reInit(null)})),t.load(n.diceUserConfig.manifestUrl)})),this._initializationPromise):(this._error=new Error("Failed to load WebGL"),new Promise((function(){throw t._error})))}},{key:"analyticsInit",value:function(e,t){this.trackingId=e,this.sessionName=t,this._diceManager.analyticsInit(e,t)}},{key:"checkWebGl",value:function(){var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");return t&&t instanceof WebGLRenderingContext}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0;return this._error?new Promise((function(){throw e._error})):(t||(t=this._diceManager.diceUserConfig.manifestUrl),this._diceManager.load(t))}},{key:"clear",value:function(){this._error||this._diceManager.clear()}},{key:"updateDiceUserConfig",value:function(e){this._diceManager.updateSettings(e)}},{key:"getRoller",value:(r=f(T().mark((function e(t){return T().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,null==this?void 0:this._initializationPromise;case 2:return e.abrupt("return",new A(this._diceManager,t));case 3:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"roll",value:(s=f(T().mark((function e(t,i,n){var s=this;return T().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this._error){e.next=2;break}return e.abrupt("return",new Promise((function(){throw s._error})));case 2:return e.abrupt("return",this._diceManager.roll(t,i,n));case 3:case"end":return e.stop()}}),e,this)}))),function(e,t,i){return s.apply(this,arguments)})},{key:"showDiceNotification",value:function(e,t){this._error||this._notifier&&this._notifier.showDiceNotification(e,t)}},{key:"setDiceNotificationEnabled",value:function(e){void 0!==this._notifier&&(e||this._notifier.clearNotifications(null),this._notifier.setEnabled(e))}},{key:"addEventListener",value:function(e,t){this._diceManager.addEventListener(e,t)}},{key:"removeEventListener",value:function(e,t){this._diceManager.removeEventListener(e,t)}},{key:"showDicePreview",value:function(e){this._error||this._diceManager.showDicePreview(e)}},{key:"previewEvent",value:function(e,t){var i,n;this._error||("rollComplete"===e?null===(i=this._diceManager.previewDie)||void 0===i||i.onRollComplete(t):null===(n=this._diceManager.previewDie)||void 0===n||n._processEvent(e,t))}},{key:"setEnabled",value:function(i){i?At.log(e.DICE_Settings,t.DICE_Enabled):At.log(e.DICE_Settings,t.DICE_Disabled)}},{key:"logModalShown",value:function(i){At.log(e.DICE_Settings,t.DICE_Modal,i?"subscriber":"non-subscriber")}}]),n}();x(qt,"ManifestLocalStorageKey","DefaultManifest");const Kt=new qt;var $t=function(){function e(){_(this,e)}return y(e,null,[{key:"CustomD20",value:function(e){var t="+";return 0===e?r.d20:(e<0&&(t=""),"".concat(r.d20).concat(t).concat(e))}}]),e}()})();var l=a.cp,h=a.rq,c=a.bV,u=a.jx,d=a.m8,p=a.w$,f=a.f4,_=a.ZM,m=a.S_,g=a.lD,v=a.hi,y=a.cU,x=a.DI,b=a.ro,T=a.Yd,S=a._w,E=a.LM,C=a.Gs,A=a.ee;export{l as Analytics,h as DefaultDiceUserConfig,c as Dice,u as DiceEvent,d as DiceNotation,p as DiceNotifier,f as DiceOperation,_ as DiceRoller,m as DiceTools,g as DiceType,v as DiceTypes,y as DieTerm,x as EventActions,b as EventCategories,T as Logger,S as RollKind,E as RollRequest,C as RollRequestRoll,A as RollType};