babylon.quarks 0.28.0 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +160 -0
- package/dist/babylon.quarks.cjs +1 -1
- package/dist/babylon.quarks.cjs.map +1 -1
- package/dist/babylon.quarks.esm.js +1 -1
- package/dist/babylon.quarks.esm.js.map +1 -1
- package/dist/babylon.quarks.umd.min.js +1 -1
- package/dist/babylon.quarks.umd.min.js.map +1 -1
- package/dist/types/index.d.cts +602 -190
- package/dist/types/index.d.ts +602 -190
- package/package.json +1 -1
- package/src/BatchedRenderer.ts +13 -1
- package/src/EffectPool.ts +5 -4
- package/src/ParticleEmitter.ts +89 -24
- package/src/ParticleSystem.ts +213 -30
- package/src/QuarksLoader.ts +9 -0
- package/src/QuarksSerializer.ts +1 -1
- package/src/QuarksUtil.ts +24 -2
- package/src/SpriteBatch.ts +3 -0
- package/src/TrailBatch.ts +8 -1
- package/src/VFXBatch.ts +112 -0
- package/src/batchKey.ts +2 -0
- package/src/batchSettings.ts +2 -0
- package/src/index.ts +2 -0
- package/src/shaderProgram.ts +103 -0
- package/src/shaderVariants.ts +102 -5
- package/src/shaders/chunks/blend.ts +15 -7
- package/src/shaders/chunks/imageProcessing.ts +143 -0
- package/src/shaders/particle_frag.glsl.ts +2 -0
- package/src/shaders/particle_frag.wgsl.ts +2 -0
- package/src/shaders/particle_physics_frag.glsl.ts +2 -0
- package/src/shaders/particle_physics_frag.wgsl.ts +2 -0
- package/src/shaders/trail_frag.glsl.ts +2 -0
- package/src/shaders/trail_frag.wgsl.ts +2 -0
- package/src/system/EmissionController.ts +21 -16
- package/src/system/ParticleSpawner.ts +96 -19
- package/src/system/integrate.ts +61 -4
- package/src/system/normalize.ts +28 -1
- package/src/system/settingsSchema.ts +25 -7
- package/src/system/types.ts +83 -14
package/dist/babylon.quarks.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var t=require("@babylonjs/core/Buffers/buffer.js"),e=require("@babylonjs/core/Misc/guid.js"),s=require("@babylonjs/core/Maths/math.frustum.js"),i=require("@babylonjs/core/Maths/math.plane.js"),n=require("@babylonjs/core/Meshes/transformNode.js"),r=require("@babylonjs/core/Engines/constants.js"),o=require("@babylonjs/core/Maths/math.color.js"),a=require("@babylonjs/core/Maths/math.vector.js"),h=require("@babylonjs/core/Cameras/camera.js"),l=require("@babylonjs/core/Materials/shaderMaterial.js"),c=require("@babylonjs/core/Materials/Textures/rawTexture.js"),u=require("@babylonjs/core/Meshes/mesh.js"),d=require("@babylonjs/core/Meshes/mesh.vertexData.js"),f=require("@babylonjs/core/Engines/shaderStore.js"),p=require("@babylonjs/core/Materials/effect.js"),m=require("@babylonjs/core/Materials/shaderLanguage.js"),y=require("@babylonjs/core/Culling/boundingInfo.js"),g=require("@babylonjs/core/Materials/Textures/baseTexture.js"),v=require("@babylonjs/core/scene.js"),x=require("@babylonjs/core/Meshes/instancedMesh.js"),S=require("@babylonjs/core/Materials/Textures/texture.js"),b=require("@babylonjs/core/Materials/standardMaterial.js");let w=null;function M(){return null===w?Math.random():w()}function z(){return w??Math.random}function _(t){const e=z();return w=t,e}function V(t){let e=t>>>0||2654435769;return()=>{e=e+1831565813|0;let t=e;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296}}const A=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let T=1234567;const O=Math.PI/180,P=180/Math.PI;function $(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(A[255&t]+A[t>>8&255]+A[t>>16&255]+A[t>>24&255]+"-"+A[255&e]+A[e>>8&255]+"-"+A[e>>16&15|64]+A[e>>24&255]+"-"+A[63&s|128]+A[s>>8&255]+"-"+A[s>>16&255]+A[s>>24&255]+A[255&i]+A[i>>8&255]+A[i>>16&255]+A[i>>24&255]).toLowerCase()}function E(t,e,s){return Math.max(e,Math.min(s,t))}function C(t,e){return(t%e+e)%e}function F(t,e,s,i,n){return i+(t-e)*(n-i)/(s-e)}function I(t,e,s){return t!==e?(s-t)/(e-t):0}function N(t,e,s){return(1-s)*t+s*e}function B(t,e,s,i){return N(t,e,1-Math.exp(-s*i))}function U(t,e=1){return e-Math.abs(C(t,2*e)-e)}function R(t,e,s){return t<=e?0:t>=s?1:(t=(t-e)/(s-e))*t*(3-2*t)}function D(t,e,s){return t<=e?0:t>=s?1:(t=(t-e)/(s-e))*t*t*(t*(6*t-15)+10)}function L(t,e){return t+Math.floor(M()*(e-t+1))}function k(t,e){return t+M()*(e-t)}function q(t){return t*(.5-M())}function J(t){void 0!==t&&(T=t);let e=T+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}function W(t){return t*O}function G(t){return t*P}function Q(t){return!(t&t-1)&&0!==t}function j(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function H(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function Y(t,e,s,i,n){const r=Math.cos,o=Math.sin,a=r(s/2),h=o(s/2),l=r((e+i)/2),c=o((e+i)/2),u=r((e-i)/2),d=o((e-i)/2),f=r((i-e)/2),p=o((i-e)/2);switch(n){case"XYX":t.set(a*c,h*u,h*d,a*l);break;case"YZY":t.set(h*d,a*c,h*u,a*l);break;case"ZXZ":t.set(h*u,h*d,a*c,a*l);break;case"XZX":t.set(a*c,h*p,h*f,a*l);break;case"YXY":t.set(h*f,a*c,h*p,a*l);break;case"ZYZ":t.set(h*p,h*f,a*c,a*l);break;default:console.warn("../math.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function X(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Z(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const K={DEG2RAD:O,RAD2DEG:P,generateUUID:$,clamp:E,euclideanModulo:C,mapLinear:F,inverseLerp:I,lerp:N,damp:B,pingpong:U,smoothstep:R,smootherstep:D,randInt:L,randFloat:k,randFloatSpread:q,seededRandom:J,degToRad:W,radToDeg:G,isPowerOfTwo:Q,ceilPowerOfTwo:j,floorPowerOfTwo:H,setQuaternionFromProperEuler:Y,normalize:Z,denormalize:X};class tt{constructor(t=0,e=0,s=0,i=1){this._x=t,this._y=e,this._z=s,this._w=i}static slerpFlat(t,e,s,i,n,r,o){let a=s[i+0],h=s[i+1],l=s[i+2],c=s[i+3];const u=n[r+0],d=n[r+1],f=n[r+2],p=n[r+3];if(0===o)return t[e+0]=a,t[e+1]=h,t[e+2]=l,void(t[e+3]=c);if(1===o)return t[e+0]=u,t[e+1]=d,t[e+2]=f,void(t[e+3]=p);if(c!==p||a!==u||h!==d||l!==f){let t=1-o;const e=a*u+h*d+l*f+c*p,s=e>=0?1:-1,i=1-e*e;if(i>Number.EPSILON){const n=Math.sqrt(i),r=Math.atan2(n,e*s);t=Math.sin(t*r)/n,o=Math.sin(o*r)/n}const n=o*s;if(a=a*t+u*n,h=h*t+d*n,l=l*t+f*n,c=c*t+p*n,t===1-o){const t=1/Math.sqrt(a*a+h*h+l*l+c*c);a*=t,h*=t,l*=t,c*=t}}t[e]=a,t[e+1]=h,t[e+2]=l,t[e+3]=c}static multiplyQuaternionsFlat(t,e,s,i,n,r){const o=s[i],a=s[i+1],h=s[i+2],l=s[i+3],c=n[r],u=n[r+1],d=n[r+2],f=n[r+3];return t[e]=o*f+l*c+a*d-h*u,t[e+1]=a*f+l*u+h*c-o*d,t[e+2]=h*f+l*d+o*u-a*c,t[e+3]=l*f-o*c-a*u-h*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,s,i){return this._x=t,this._y=e,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new tt(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const s=t._x,i=t._y,n=t._z,r=t._order,o=Math.cos,a=Math.sin,h=o(s/2),l=o(i/2),c=o(n/2),u=a(s/2),d=a(i/2),f=a(n/2);switch(r){case"XYZ":this._x=u*l*c+h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c-u*d*f;break;case"YXZ":this._x=u*l*c+h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c+u*d*f;break;case"ZXY":this._x=u*l*c-h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c-u*d*f;break;case"ZYX":this._x=u*l*c-h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c+u*d*f;break;case"YZX":this._x=u*l*c+h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c-u*d*f;break;case"XZY":this._x=u*l*c-h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c+u*d*f;break;default:console.warn("../math.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return!0===e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const s=e/2,i=Math.sin(s);return this._x=t.x*i,this._y=t.y*i,this._z=t.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,s=e[0],i=e[4],n=e[8],r=e[1],o=e[5],a=e[9],h=e[2],l=e[6],c=e[10],u=s+o+c;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(l-a)*t,this._y=(n-h)*t,this._z=(r-i)*t}else if(s>o&&s>c){const t=2*Math.sqrt(1+s-o-c);this._w=(l-a)/t,this._x=.25*t,this._y=(i+r)/t,this._z=(n+h)/t}else if(o>c){const t=2*Math.sqrt(1+o-s-c);this._w=(n-h)/t,this._x=(i+r)/t,this._y=.25*t,this._z=(a+l)/t}else{const t=2*Math.sqrt(1+c-s-o);this._w=(r-i)/t,this._x=(n+h)/t,this._y=(a+l)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let s=t.dot(e)+1;return s<Number.EPSILON?(s=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=s):(this._x=0,this._y=-t.z,this._z=t.y,this._w=s)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=s),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(E(this.dot(t),-1,1)))}rotateTowards(t,e){const s=this.angleTo(t);if(0===s)return this;const i=Math.min(1,e/s);return this.slerp(t,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const s=t._x,i=t._y,n=t._z,r=t._w,o=e._x,a=e._y,h=e._z,l=e._w;return this._x=s*l+r*o+i*h-n*a,this._y=i*l+r*a+n*o-s*h,this._z=n*l+r*h+s*a-i*o,this._w=r*l-s*o-i*a-n*h,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const s=this._x,i=this._y,n=this._z,r=this._w;let o=r*t._w+s*t._x+i*t._y+n*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=r,this._x=s,this._y=i,this._z=n,this;const a=1-o*o;if(a<=Number.EPSILON){const t=1-e;return this._w=t*r+e*this._w,this._x=t*s+e*this._x,this._y=t*i+e*this._y,this._z=t*n+e*this._z,this.normalize(),this}const h=Math.sqrt(a),l=Math.atan2(h,o),c=Math.sin((1-e)*l)/h,u=Math.sin(e*l)/h;return this._w=r*c+this._w*u,this._x=s*c+this._x*u,this._y=i*c+this._y*u,this._z=n*c+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,s){return this.copy(t).slerp(e,s)}random(){const t=2*Math.PI*M(),e=2*Math.PI*M(),s=M(),i=Math.sqrt(1-s),n=Math.sqrt(s);return this.set(i*Math.sin(t),i*Math.cos(t),n*Math.sin(e),n*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}Object.defineProperty(tt.prototype,"isQuaternion",{value:!0});class et{constructor(t=0,e=0,s=0){this.x=t,this.y=e,this.z=s}set(t,e,s){return void 0===s&&(s=this.z),this.x=t,this.y=e,this.z=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new et(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(it.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(it.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,s=this.y,i=this.z,n=t.elements;return this.x=n[0]*e+n[3]*s+n[6]*i,this.y=n[1]*e+n[4]*s+n[7]*i,this.z=n[2]*e+n[5]*s+n[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,s=this.y,i=this.z,n=t.elements,r=1/(n[3]*e+n[7]*s+n[11]*i+n[15]);return this.x=(n[0]*e+n[4]*s+n[8]*i+n[12])*r,this.y=(n[1]*e+n[5]*s+n[9]*i+n[13])*r,this.z=(n[2]*e+n[6]*s+n[10]*i+n[14])*r,this}applyQuaternion(t){const e=this.x,s=this.y,i=this.z,n=t.x,r=t.y,o=t.z,a=t.w,h=2*(r*i-o*s),l=2*(o*e-n*i),c=2*(n*s-r*e);return this.x=e+a*h+r*c-o*l,this.y=s+a*l+o*h-n*c,this.z=i+a*c+n*l-r*h,this}transformDirection(t){const e=this.x,s=this.y,i=this.z,n=t.elements;return this.x=n[0]*e+n[4]*s+n[8]*i,this.y=n[1]*e+n[5]*s+n[9]*i,this.z=n[2]*e+n[6]*s+n[10]*i,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(t,Math.min(e,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,s){return this.x=t.x+(e.x-t.x)*s,this.y=t.y+(e.y-t.y)*s,this.z=t.z+(e.z-t.z)*s,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const s=t.x,i=t.y,n=t.z,r=e.x,o=e.y,a=e.z;return this.x=i*a-n*o,this.y=n*r-s*a,this.z=s*o-i*r,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const s=t.dot(this)/e;return this.copy(t).multiplyScalar(s)}projectOnPlane(t){return st.copy(this).projectOnVector(t),this.sub(st)}reflect(t){return this.sub(st.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const s=this.dot(t)/e;return Math.acos(E(s,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,s=this.y-t.y,i=this.z-t.z;return e*e+s*s+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSphericalCoords(t,e,s){const i=Math.sin(e)*t;return this.x=i*Math.sin(s),this.y=Math.cos(e)*t,this.z=i*Math.cos(s),this}setFromCylindricalCoords(t,e,s){return this.x=t*Math.sin(e),this.y=s,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),s=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=s,this.z=i,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}random(){return this.x=M(),this.y=M(),this.z=M(),this}randomDirection(){const t=M()*Math.PI*2,e=2*M()-1,s=Math.sqrt(1-e*e);return this.x=s*Math.cos(t),this.y=e,this.z=s*Math.sin(t),this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this.z=Math.abs(this.z),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}Object.defineProperty(et.prototype,"isVector3",{value:!0});const st=new et,it=new tt,nt=2e3,rt=2001;class ot{constructor(t,e,s,i,n,r,o,a,h,l,c,u,d,f,p,m){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,s,i,n,r,o,a,h,l,c,u,d,f,p,m)}extractPosition(t){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(t)}multiplyToArray(t,e,s){return console.error("THREE.Matrix4: .multiplyToArray() has been removed."),this}setRotationFromQuaternion(t){return this.makeRotationFromQuaternion(t)}set(t,e,s,i,n,r,o,a,h,l,c,u,d,f,p,m){const y=this.elements;return y[0]=t,y[4]=e,y[8]=s,y[12]=i,y[1]=n,y[5]=r,y[9]=o,y[13]=a,y[2]=h,y[6]=l,y[10]=c,y[14]=u,y[3]=d,y[7]=f,y[11]=p,y[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new ot).fromArray(this.elements)}copy(t){const e=this.elements,s=t.elements;return e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=s[3],e[4]=s[4],e[5]=s[5],e[6]=s[6],e[7]=s[7],e[8]=s[8],e[9]=s[9],e[10]=s[10],e[11]=s[11],e[12]=s[12],e[13]=s[13],e[14]=s[14],e[15]=s[15],this}copyPosition(t){const e=this.elements,s=t.elements;return e[12]=s[12],e[13]=s[13],e[14]=s[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,s){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this}makeBasis(t,e,s){return this.set(t.x,e.x,s.x,0,t.y,e.y,s.y,0,t.z,e.z,s.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,s=t.elements,i=1/at.setFromMatrixColumn(t,0).length(),n=1/at.setFromMatrixColumn(t,1).length(),r=1/at.setFromMatrixColumn(t,2).length();return e[0]=s[0]*i,e[1]=s[1]*i,e[2]=s[2]*i,e[3]=0,e[4]=s[4]*n,e[5]=s[5]*n,e[6]=s[6]*n,e[7]=0,e[8]=s[8]*r,e[9]=s[9]*r,e[10]=s[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,s=t.x,i=t.y,n=t.z,r=Math.cos(s),o=Math.sin(s),a=Math.cos(i),h=Math.sin(i),l=Math.cos(n),c=Math.sin(n);if("XYZ"===t.order){const t=r*l,s=r*c,i=o*l,n=o*c;e[0]=a*l,e[4]=-a*c,e[8]=h,e[1]=s+i*h,e[5]=t-n*h,e[9]=-o*a,e[2]=n-t*h,e[6]=i+s*h,e[10]=r*a}else if("YXZ"===t.order){const t=a*l,s=a*c,i=h*l,n=h*c;e[0]=t+n*o,e[4]=i*o-s,e[8]=r*h,e[1]=r*c,e[5]=r*l,e[9]=-o,e[2]=s*o-i,e[6]=n+t*o,e[10]=r*a}else if("ZXY"===t.order){const t=a*l,s=a*c,i=h*l,n=h*c;e[0]=t-n*o,e[4]=-r*c,e[8]=i+s*o,e[1]=s+i*o,e[5]=r*l,e[9]=n-t*o,e[2]=-r*h,e[6]=o,e[10]=r*a}else if("ZYX"===t.order){const t=r*l,s=r*c,i=o*l,n=o*c;e[0]=a*l,e[4]=i*h-s,e[8]=t*h+n,e[1]=a*c,e[5]=n*h+t,e[9]=s*h-i,e[2]=-h,e[6]=o*a,e[10]=r*a}else if("YZX"===t.order){const t=r*a,s=r*h,i=o*a,n=o*h;e[0]=a*l,e[4]=n-t*c,e[8]=i*c+s,e[1]=c,e[5]=r*l,e[9]=-o*l,e[2]=-h*l,e[6]=s*c+i,e[10]=t-n*c}else if("XZY"===t.order){const t=r*a,s=r*h,i=o*a,n=o*h;e[0]=a*l,e[4]=-c,e[8]=h*l,e[1]=t*c+n,e[5]=r*l,e[9]=s*c-i,e[2]=i*c-s,e[6]=o*l,e[10]=n*c+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(lt,t,ct)}lookAt(t,e,s){const i=this.elements;return ft.subVectors(t,e),0===ft.lengthSq()&&(ft.z=1),ft.normalize(),ut.crossVectors(s,ft),0===ut.lengthSq()&&(1===Math.abs(s.z)?ft.x+=1e-4:ft.z+=1e-4,ft.normalize(),ut.crossVectors(s,ft)),ut.normalize(),dt.crossVectors(ft,ut),i[0]=ut.x,i[4]=dt.x,i[8]=ft.x,i[1]=ut.y,i[5]=dt.y,i[9]=ft.y,i[2]=ut.z,i[6]=dt.z,i[10]=ft.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const s=t.elements,i=e.elements,n=this.elements,r=s[0],o=s[4],a=s[8],h=s[12],l=s[1],c=s[5],u=s[9],d=s[13],f=s[2],p=s[6],m=s[10],y=s[14],g=s[3],v=s[7],x=s[11],S=s[15],b=i[0],w=i[4],M=i[8],z=i[12],_=i[1],V=i[5],A=i[9],T=i[13],O=i[2],P=i[6],$=i[10],E=i[14],C=i[3],F=i[7],I=i[11],N=i[15];return n[0]=r*b+o*_+a*O+h*C,n[4]=r*w+o*V+a*P+h*F,n[8]=r*M+o*A+a*$+h*I,n[12]=r*z+o*T+a*E+h*N,n[1]=l*b+c*_+u*O+d*C,n[5]=l*w+c*V+u*P+d*F,n[9]=l*M+c*A+u*$+d*I,n[13]=l*z+c*T+u*E+d*N,n[2]=f*b+p*_+m*O+y*C,n[6]=f*w+p*V+m*P+y*F,n[10]=f*M+p*A+m*$+y*I,n[14]=f*z+p*T+m*E+y*N,n[3]=g*b+v*_+x*O+S*C,n[7]=g*w+v*V+x*P+S*F,n[11]=g*M+v*A+x*$+S*I,n[15]=g*z+v*T+x*E+S*N,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],s=t[4],i=t[8],n=t[12],r=t[1],o=t[5],a=t[9],h=t[13],l=t[2],c=t[6],u=t[10],d=t[14];return t[3]*(+n*a*c-i*h*c-n*o*u+s*h*u+i*o*d-s*a*d)+t[7]*(+e*a*d-e*h*u+n*r*u-i*r*d+i*h*l-n*a*l)+t[11]*(+e*h*c-e*o*d-n*r*c+s*r*d+n*o*l-s*h*l)+t[15]*(-i*o*l-e*a*c+e*o*u+i*r*c-s*r*u+s*a*l)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,s){const i=this.elements;return"number"==typeof t?(i[12]=t,i[13]=e,i[14]=s):(i[12]=t.x,i[13]=t.y,i[14]=t.z),this}invert(){const t=this.elements,e=t[0],s=t[1],i=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],c=t[9],u=t[10],d=t[11],f=t[12],p=t[13],m=t[14],y=t[15],g=c*m*h-p*u*h+p*a*d-o*m*d-c*a*y+o*u*y,v=f*u*h-l*m*h-f*a*d+r*m*d+l*a*y-r*u*y,x=l*p*h-f*c*h+f*o*d-r*p*d-l*o*y+r*c*y,S=f*c*a-l*p*a-f*o*u+r*p*u+l*o*m-r*c*m,b=e*g+s*v+i*x+n*S;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/b;return t[0]=g*w,t[1]=(p*u*n-c*m*n-p*i*d+s*m*d+c*i*y-s*u*y)*w,t[2]=(o*m*n-p*a*n+p*i*h-s*m*h-o*i*y+s*a*y)*w,t[3]=(c*a*n-o*u*n-c*i*h+s*u*h+o*i*d-s*a*d)*w,t[4]=v*w,t[5]=(l*m*n-f*u*n+f*i*d-e*m*d-l*i*y+e*u*y)*w,t[6]=(f*a*n-r*m*n-f*i*h+e*m*h+r*i*y-e*a*y)*w,t[7]=(r*u*n-l*a*n+l*i*h-e*u*h-r*i*d+e*a*d)*w,t[8]=x*w,t[9]=(f*c*n-l*p*n-f*s*d+e*p*d+l*s*y-e*c*y)*w,t[10]=(r*p*n-f*o*n+f*s*h-e*p*h-r*s*y+e*o*y)*w,t[11]=(l*o*n-r*c*n-l*s*h+e*c*h+r*s*d-e*o*d)*w,t[12]=S*w,t[13]=(l*p*i-f*c*i+f*s*u-e*p*u-l*s*m+e*c*m)*w,t[14]=(f*o*i-r*p*i-f*s*a+e*p*a+r*s*m-e*o*m)*w,t[15]=(r*c*i-l*o*i+l*s*a-e*c*a-r*s*u+e*o*u)*w,this}scale(t){const e=this.elements,s=t.x,i=t.y,n=t.z;return e[0]*=s,e[4]*=i,e[8]*=n,e[1]*=s,e[5]*=i,e[9]*=n,e[2]*=s,e[6]*=i,e[10]*=n,e[3]*=s,e[7]*=i,e[11]*=n,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],s=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,s,i))}makeTranslation(t,e,s){return"number"==typeof t?this.set(1,0,0,t,0,1,0,e,0,0,1,s,0,0,0,1):this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),s=Math.sin(t);return this.set(1,0,0,0,0,e,-s,0,0,s,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),s=Math.sin(t);return this.set(e,0,s,0,0,1,0,0,-s,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),s=Math.sin(t);return this.set(e,-s,0,0,s,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const s=Math.cos(e),i=Math.sin(e),n=1-s,r=t.x,o=t.y,a=t.z,h=n*r,l=n*o;return this.set(h*r+s,h*o-i*a,h*a+i*o,0,h*o+i*a,l*o+s,l*a-i*r,0,h*a-i*o,l*a+i*r,n*a*a+s,0,0,0,0,1),this}makeScale(t,e,s){return this.set(t,0,0,0,0,e,0,0,0,0,s,0,0,0,0,1),this}makeShear(t,e,s,i,n,r){return this.set(1,s,n,0,t,1,r,0,e,i,1,0,0,0,0,1),this}compose(t,e,s){const i=this.elements,n=e._x,r=e._y,o=e._z,a=e._w,h=n+n,l=r+r,c=o+o,u=n*h,d=n*l,f=n*c,p=r*l,m=r*c,y=o*c,g=a*h,v=a*l,x=a*c,S=s.x,b=s.y,w=s.z;return i[0]=(1-(p+y))*S,i[1]=(d+x)*S,i[2]=(f-v)*S,i[3]=0,i[4]=(d-x)*b,i[5]=(1-(u+y))*b,i[6]=(m+g)*b,i[7]=0,i[8]=(f+v)*w,i[9]=(m-g)*w,i[10]=(1-(u+p))*w,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,s){const i=this.elements;let n=at.set(i[0],i[1],i[2]).length();const r=at.set(i[4],i[5],i[6]).length(),o=at.set(i[8],i[9],i[10]).length();this.determinant()<0&&(n=-n),t.x=i[12],t.y=i[13],t.z=i[14],ht.copy(this);const a=1/n,h=1/r,l=1/o;return ht.elements[0]*=a,ht.elements[1]*=a,ht.elements[2]*=a,ht.elements[4]*=h,ht.elements[5]*=h,ht.elements[6]*=h,ht.elements[8]*=l,ht.elements[9]*=l,ht.elements[10]*=l,e.setFromRotationMatrix(ht),s.x=n,s.y=r,s.z=o,this}makePerspective(t,e,s,i,n,r,o=2e3){const a=this.elements,h=2*n/(e-t),l=2*n/(s-i),c=(e+t)/(e-t),u=(s+i)/(s-i);let d,f;if(o===nt)d=-(r+n)/(r-n),f=-2*r*n/(r-n);else{if(o!==rt)throw new Error("Matrix4.makePerspective(): Invalid coordinate system: "+o);d=-r/(r-n),f=-r*n/(r-n)}return a[0]=h,a[4]=0,a[8]=c,a[12]=0,a[1]=0,a[5]=l,a[9]=u,a[13]=0,a[2]=0,a[6]=0,a[10]=d,a[14]=f,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(t,e,s,i,n,r,o=2e3){const a=this.elements,h=1/(e-t),l=1/(s-i),c=1/(r-n),u=(e+t)*h,d=(s+i)*l;let f,p;if(o===nt)f=(r+n)*c,p=-2*c;else{if(o!==rt)throw new Error("../math.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);f=n*c,p=-1*c}return a[0]=2*h,a[4]=0,a[8]=0,a[12]=-u,a[1]=0,a[5]=2*l,a[9]=0,a[13]=-d,a[2]=0,a[6]=0,a[10]=p,a[14]=-f,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(t){const e=this.elements,s=t.elements;for(let t=0;t<16;t++)if(e[t]!==s[t])return!1;return!0}fromArray(t,e=0){for(let s=0;s<16;s++)this.elements[s]=t[s+e];return this}toArray(t=[],e=0){const s=this.elements;return t[e]=s[0],t[e+1]=s[1],t[e+2]=s[2],t[e+3]=s[3],t[e+4]=s[4],t[e+5]=s[5],t[e+6]=s[6],t[e+7]=s[7],t[e+8]=s[8],t[e+9]=s[9],t[e+10]=s[10],t[e+11]=s[11],t[e+12]=s[12],t[e+13]=s[13],t[e+14]=s[14],t[e+15]=s[15],t}}Object.defineProperty(ot.prototype,"isMatrix4",{value:!0});const at=new et,ht=new ot,lt=new et(0,0,0),ct=new et(1,1,1),ut=new et,dt=new et,ft=new et,pt=new ot,mt=new tt;class yt{constructor(t=0,e=0,s=0,i=yt.DEFAULT_ORDER){this._x=t,this._y=e,this._z=s,this._order=i}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,s,i=this._order){return this._x=t,this._y=e,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new yt(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,s=!0){const i=t.elements,n=i[0],r=i[4],o=i[8],a=i[1],h=i[5],l=i[9],c=i[2],u=i[6],d=i[10];switch(e){case"XYZ":this._y=Math.asin(E(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,d),this._z=Math.atan2(-r,n)):(this._x=Math.atan2(u,h),this._z=0);break;case"YXZ":this._x=Math.asin(-E(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,h)):(this._y=Math.atan2(-c,n),this._z=0);break;case"ZXY":this._x=Math.asin(E(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-r,h)):(this._y=0,this._z=Math.atan2(a,n));break;case"ZYX":this._y=Math.asin(-E(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(a,n)):(this._x=0,this._z=Math.atan2(-r,h));break;case"YZX":this._z=Math.asin(E(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-l,h),this._y=Math.atan2(-c,n)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-E(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(u,h),this._y=Math.atan2(o,n)):(this._x=Math.atan2(-l,d),this._y=0);break;default:console.warn("../math.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===s&&this._onChangeCallback(),this}setFromQuaternion(t,e,s){return pt.makeRotationFromQuaternion(t),this.setFromRotationMatrix(pt,e,s)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return mt.setFromEuler(this),this.setFromQuaternion(mt,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(t){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}yt.DEFAULT_ORDER="XYZ",Object.defineProperty(yt.prototype,"isEuler",{value:!0});class gt{constructor(t,e,s,i,n,r,o,a,h){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,s,i,n,r,o,a,h)}set(t,e,s,i,n,r,o,a,h){const l=this.elements;return l[0]=t,l[1]=i,l[2]=o,l[3]=e,l[4]=n,l[5]=a,l[6]=s,l[7]=r,l[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,s=t.elements;return e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=s[3],e[4]=s[4],e[5]=s[5],e[6]=s[6],e[7]=s[7],e[8]=s[8],this}extractBasis(t,e,s){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const s=t.elements,i=e.elements,n=this.elements,r=s[0],o=s[3],a=s[6],h=s[1],l=s[4],c=s[7],u=s[2],d=s[5],f=s[8],p=i[0],m=i[3],y=i[6],g=i[1],v=i[4],x=i[7],S=i[2],b=i[5],w=i[8];return n[0]=r*p+o*g+a*S,n[3]=r*m+o*v+a*b,n[6]=r*y+o*x+a*w,n[1]=h*p+l*g+c*S,n[4]=h*m+l*v+c*b,n[7]=h*y+l*x+c*w,n[2]=u*p+d*g+f*S,n[5]=u*m+d*v+f*b,n[8]=u*y+d*x+f*w,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],s=t[1],i=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return e*r*l-e*o*h-s*n*l+s*o*a+i*n*h-i*r*a}invert(){const t=this.elements,e=t[0],s=t[1],i=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],c=l*r-o*h,u=o*a-l*n,d=h*n-r*a,f=e*c+s*u+i*d;if(0===f)return this.set(0,0,0,0,0,0,0,0,0);const p=1/f;return t[0]=c*p,t[1]=(i*h-l*s)*p,t[2]=(o*s-i*r)*p,t[3]=u*p,t[4]=(l*e-i*a)*p,t[5]=(i*n-o*e)*p,t[6]=d*p,t[7]=(s*a-h*e)*p,t[8]=(r*e-s*n)*p,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,s,i,n,r,o){const a=Math.cos(n),h=Math.sin(n);return this.set(s*a,s*h,-s*(a*r+h*o)+r+t,-i*h,i*a,-i*(-h*r+a*o)+o+e,0,0,1),this}scale(t,e){return this.premultiply(vt.makeScale(t,e)),this}rotate(t){return this.premultiply(vt.makeRotation(-t)),this}translate(t,e){return this.premultiply(vt.makeTranslation(t,e)),this}makeTranslation(t,e){return"number"==typeof t?this.set(1,0,t,0,1,e,0,0,1):this.set(1,0,t.x,0,1,t.y,0,0,1),this}makeRotation(t){const e=Math.cos(t),s=Math.sin(t);return this.set(e,-s,0,s,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,s=t.elements;for(let t=0;t<9;t++)if(e[t]!==s[t])return!1;return!0}fromArray(t,e=0){for(let s=0;s<9;s++)this.elements[s]=t[s+e];return this}toArray(t=[],e=0){const s=this.elements;return t[e]=s[0],t[e+1]=s[1],t[e+2]=s[2],t[e+3]=s[3],t[e+4]=s[4],t[e+5]=s[5],t[e+6]=s[6],t[e+7]=s[7],t[e+8]=s[8],t}clone(){return(new gt).fromArray(this.elements)}}Object.defineProperty(gt.prototype,"isMatrix3",{value:!0});const vt=new gt,xt=new Float32Array(4);class St extends tt{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const bt=St.prototype;bt.data=xt,bt.offset=0,Object.defineProperties(St.prototype,{_x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},_y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},_z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}},_w:{get(){return this.data[this.offset+3]},set(t){this.data[this.offset+3]=t}}});class wt{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new wt(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,s=this.y,i=t.elements;return this.x=i[0]*e+i[3]*s+i[6],this.y=i[1]*e+i[4]*s+i[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(t,Math.min(e,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const s=this.dot(t)/e;return Math.acos(E(s,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,s=this.y-t.y;return e*e+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,s){return this.x=t.x+(e.x-t.x)*s,this.y=t.y+(e.y-t.y)*s,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}rotateAround(t,e){const s=Math.cos(e),i=Math.sin(e),n=this.x-t.x,r=this.y-t.y;return this.x=n*s-r*i+t.x,this.y=n*i+r*s+t.y,this}random(){return this.x=M(),this.y=M(),this}*[Symbol.iterator](){yield this.x,yield this.y}}Object.defineProperty(wt.prototype,"isVector2",{value:!0});const Mt=new Float32Array(3);class zt extends et{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const _t=zt.prototype;_t.data=Mt,_t.offset=0,Object.defineProperties(zt.prototype,{x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}}});class Vt{constructor(t=0,e=0,s=0,i=1){this.x=t,this.y=e,this.z=s,this.w=i}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,s,i){return this.x=t,this.y=e,this.z=s,this.w=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new Vt(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,s=this.y,i=this.z,n=this.w,r=t.elements;return this.x=r[0]*e+r[4]*s+r[8]*i+r[12]*n,this.y=r[1]*e+r[5]*s+r[9]*i+r[13]*n,this.z=r[2]*e+r[6]*s+r[10]*i+r[14]*n,this.w=r[3]*e+r[7]*s+r[11]*i+r[15]*n,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,s,i,n;const r=.01,o=.1,a=t.elements,h=a[0],l=a[4],c=a[8],u=a[1],d=a[5],f=a[9],p=a[2],m=a[6],y=a[10];if(Math.abs(l-u)<r&&Math.abs(c-p)<r&&Math.abs(f-m)<r){if(Math.abs(l+u)<o&&Math.abs(c+p)<o&&Math.abs(f+m)<o&&Math.abs(h+d+y-3)<o)return this.set(1,0,0,0),this;e=Math.PI;const t=(h+1)/2,a=(d+1)/2,g=(y+1)/2,v=(l+u)/4,x=(c+p)/4,S=(f+m)/4;return t>a&&t>g?t<r?(s=0,i=.707106781,n=.707106781):(s=Math.sqrt(t),i=v/s,n=x/s):a>g?a<r?(s=.707106781,i=0,n=.707106781):(i=Math.sqrt(a),s=v/i,n=S/i):g<r?(s=.707106781,i=.707106781,n=0):(n=Math.sqrt(g),s=x/n,i=S/n),this.set(s,i,n,e),this}let g=Math.sqrt((m-f)*(m-f)+(c-p)*(c-p)+(u-l)*(u-l));return Math.abs(g)<.001&&(g=1),this.x=(m-f)/g,this.y=(c-p)/g,this.z=(u-l)/g,this.w=Math.acos((h+d+y-1)/2),this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(t,Math.min(e,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,s){return this.x=t.x+(e.x-t.x)*s,this.y=t.y+(e.y-t.y)*s,this.z=t.z+(e.z-t.z)*s,this.w=t.w+(e.w-t.w)*s,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}random(){return this.x=M(),this.y=M(),this.z=M(),this.w=M(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}Object.defineProperty(Vt.prototype,"isVector4",{value:!0});const At=new Float32Array(4);class Tt extends Vt{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const Ot=Tt.prototype;let Pt;Ot.data=At,Ot.offset=0,Object.defineProperties(Tt.prototype,{x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}},w:{get(){return this.data[this.offset+3]},set(t){this.data[this.offset+3]=t}}});class $t{constructor(t,e){this.resolver=t,this.bounce=e,this.type="ApplyCollision",this.tempV=new et}initialize(t){}update(t,e){const s=this.resolver??Pt;void 0!==s&&s.resolve(t.position,this.tempV)&&t.velocity.reflect(this.tempV).multiplyScalar(this.bounce)}frameUpdate(t){}toJSON(){return{type:this.type,bounce:this.bounce}}static fromJSON(t){return new $t(void 0,"number"==typeof t.bounce?t.bounce:1)}clone(){return new $t(this.resolver,this.bounce)}reset(){}}const Et=t=>({r:t.x,g:t.y,b:t.z,a:t.w}),Ct=t=>new Vt(t.r,t.g,t.b,t.a);function Ft(t,e){if("number"==typeof t)return t;switch(e){case"Color":return{r:t.x,g:t.y,b:t.z};case"Vector4":return t instanceof Vt?{x:t.x,y:t.y,z:t.z,w:t.w}:{...It(t),w:0};default:return It(t)}}const It=t=>({x:t.x,y:t.y,z:t.z}),Nt=t=>"number"==typeof t?t:0;function Bt(t){return"number"==typeof t?new et:"r"in t?new et(t.r,t.g,t.b):new et(t.x,t.y,t.z)}function Ut(t){return"number"==typeof t||"r"in t?new Vt:new Vt(t.x,t.y,t.z,"w"in t?t.w:0)}class Rt extends Error{constructor(t,e=[t]){super(t),this.name="QuarksFormatError",this.problems=e}}let Dt={};const Lt=[];function kt(t,e){const s=Dt,i=Lt.splice(0);Dt=t;try{return e()}finally{Dt=s,Lt.splice(0,Lt.length,...i)}}function qt(t,e){Lt.push(t);try{return e()}finally{Lt.pop()}}function Jt(){return Lt.reduce((t,e)=>t&&!e.startsWith("[")?`${t}.${e}`:t+e,"")}const Wt=t=>{const e=Jt();if(Dt.strict)throw new Rt(e?`${t} (at ${e})`:t);Dt.onWarning?Dt.onWarning(t,e):console.warn(`[quarks] ${t}${e?` (at ${e})`:""}`)},Gt=(t,e)=>Array.isArray(t)?new et(t[0]??e.x,t[1]??e.y,t[2]??e.z):e,Qt=(t,e)=>{const s=e?.type;return null==e?`Missing ${t}`:void 0===s?`${t[0].toUpperCase()}${t.slice(1)} without a type`:`Unknown ${t} ${JSON.stringify(s)}`};function jt(t,e){if(t===e)return!0;if("object"!=typeof t||"object"!=typeof e||null===t||null===e)return"number"==typeof t&&"number"==typeof e&&Number.isNaN(t)&&Number.isNaN(e);if(Array.isArray(t)!==Array.isArray(e))return!1;const s=new Set([...Object.keys(t),...Object.keys(e)]);for(const i of s)if(!jt(t[i],e[i]))return!1;return!0}function Ht(t,e){if(null===t||"object"!=typeof t||"string"!=typeof t.type)return t;const s=t=>{let s=!1;try{return{out:kt({onWarning:()=>s=!0},()=>e(t)),warned:s}}catch{return{out:void 0,warned:!0}}},i=s({type:t.type}).out;if(null==i||"object"!=typeof i)return t;const n={type:t.type};for(const[e,s]of Object.entries(t))"type"===e||void 0===s||jt(s,i[e])||(n[e]=s);if(Object.keys(n).length===Object.keys(t).length)return t;const r=s(n);return!r.warned&&jt(r.out,t)?n:t}class Yt{constructor(t){this.value=t,this.type="value"}startGen(t){}genValue(t){return this.value}toJSON(){return{type:"ConstantValue",value:this.value}}static fromJSON(t){return new Yt(t.value)}clone(){return new Yt(this.value)}}class Xt{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(M())}genValue(t){return-1===this.indexCount&&this.startGen(t),K.lerp(this.a,this.b,t[this.indexCount])}toJSON(){return{type:"IntervalValue",a:this.a,b:this.b}}static fromJSON(t){return new Xt(t.a,t.b)}clone(){return new Xt(this.a,this.b)}}class Zt{constructor(t,e,s,i){this.p=[t,e,s,i]}genValue(t){const e=this.p,s=t*t,i=1-t,n=i*i;return e[0]*n*i+e[1]*n*t*3+e[2]*i*s*3+e[3]*s*t}derivativeCoefficients(t){const e=[];for(let s=t,i=s.length-1;i>0;i--){const t=[];for(let e=0;e<i;e++){const n=i*(s[e+1]-s[e]);t.push(n)}e.push(t),s=t}return e}getSlope(t){const e=this.derivativeCoefficients(this.p)[0],s=1-t,i=s*t*2,n=t*t;return s*s*e[0]+i*e[1]+n*e[2]}controlCurve(t,e){this.p[1]=t/3+this.p[0],this.p[2]=this.p[3]-e/3}hull(t){let e=this.p;const s=[e[0],e[1],e[2],e[3]];for(;e.length>1;){const i=[];for(let n=0;n<e.length-1;n++){const r=(1-t)*e[n]+t*e[n+1];s.push(r),i.push(r)}e=i}return s}split(t){const e=this.hull(t);return{left:new Zt(e[0],e[4],e[7],e[9]),right:new Zt(e[9],e[8],e[6],e[3]),span:e}}clone(){return new Zt(this.p[0],this.p[1],this.p[2],this.p[3])}toJSON(){return{p0:this.p[0],p1:this.p[1],p2:this.p[2],p3:this.p[3]}}static fromJSON(t){return new Zt(t.p0,t.p1,t.p2,t.p3)}}class Kt{constructor(){this.functions=new Array}findFunction(t){const e=this.functions,s=e.length-1;if(s<=0)return 0===s&&t>=e[0][1]&&t<=1?0:-1;let i=0,n=s;for(;i+1<n;){const s=i+n>>1;if(t<e[s][1])n=s-1;else{if(!(t>this.getEndX(s)))return s;i=s+1}}for(let s=i;s<=n;s++)if(t>=e[s][1]&&t<=this.getEndX(s))return s;return-1}getStartX(t){return this.functions[t][1]}setStartX(t,e){t>0&&(this.functions[t][1]=e)}getEndX(t){return t+1<this.functions.length?this.functions[t+1][1]:1}setEndX(t,e){t+1<this.functions.length&&(this.functions[t+1][1]=e)}insertFunction(t,e){const s=Math.min(Math.max(t,0),1);let i=this.functions.findIndex(([,t])=>t>s);-1===i&&(i=this.functions.length),this.functions.splice(i,0,[e,s])}removeFunction(t){return this.functions.splice(t,1)[0][0]}getFunction(t){return this.functions[t][0]}setFunction(t,e){this.functions[t][0]=e}get numOfFunctions(){return this.functions.length}}class te extends Kt{constructor(t=[[new Zt(0,1/3,1/3*2,1),0]]){super(),this.table=null,this.tableSignature=null,this.type="function",this.functions=t}refreshTable(){const t=this.functions,e=t.length;if(0===e)return this.table=null,void(this.tableSignature=null);const s=5*e;let i=this.tableSignature,n=null===i||i.length!==s;n&&(i=new Float64Array(s));for(let s=0,r=0;s<e;s++,r+=5){const e=t[s][0].p,o=t[s][1];n||(n=i[r]!==e[0]||i[r+1]!==e[1]||i[r+2]!==e[2]||i[r+3]!==e[3]||i[r+4]!==o),n&&(i[r]=e[0],i[r+1]=e[1],i[r+2]=e[2],i[r+3]=e[3],i[r+4]=o)}if(!n&&null!==this.table)return;this.tableSignature=i;const r=te.TABLE_SIZE,o=null!==this.table&&this.table.length===r?this.table:new Float32Array(r),a=1/(r-1);for(let t=0;t<r;t++)o[t]=this.genValueExact(t*a);this.table=o}sampledTable(){return this.table}clearTable(){this.table=null,this.tableSignature=null}genValue(t,e=0){const s=this.table;if(null!==s){const t=s.length-1;if(e<=0)return s[0];if(e>=1)return s[t];const i=e*t,n=0|i,r=i-n,o=s[n];return o+(s[n+1]-o)*r}return this.genValueExact(e)}genValueExact(t){const e=this.functions,s=e.length;if(0===s)return 0;const i=this.findFunction(t);if(-1===i)return t<e[0][1]?e[0][0].genValue(0):e[s-1][0].genValue(1);const n=e[i][1],r=(i+1<s?e[i+1][1]:1)-n;return e[i][0].genValue(r>0?(t-n)/r:0)}toSVG(t,e){if(e<1||0===this.functions.length)return"";let s=["M",0,this.functions[0][0].p[0]].join(" ");for(let i=1/e;i<=1;i+=1/e)s=[s,"L",i*t,this.genValueExact(i)].join(" ");return s}toJSON(){return{type:"PiecewiseBezier",functions:this.functions.map(([t,e])=>({function:t.toJSON(),start:e}))}}static fromJSON(t){return new te(t.functions.map(t=>[Zt.fromJSON(t.function),t.start]))}clone(){return new te(this.functions.map(([t,e])=>[t.clone(),e]))}startGen(t){}}function ee(t){switch(t?.type){case"ConstantValue":return Yt.fromJSON(t);case"IntervalValue":return Xt.fromJSON(t);case"PiecewiseBezier":return te.fromJSON(t);default:return Wt(`${Qt("value generator",t)}; using 0.`),new Yt(0)}}te.TABLE_SIZE=257;const se=new et;class ie{constructor(t,e){this.axis=t,this.angle=e,this.type="rotation"}startGen(t){this.angle.startGen(t)}genValue(t,e,s,i){const n=this.axis,r=n.lengthSq();return 0===r?se.set(0,0,1):se.copy(n).multiplyScalar(1/Math.sqrt(r)),e.setFromAxisAngle(se,this.angle.genValue(t,i)*s)}toJSON(){return{type:"AxisAngle",axis:{x:this.axis.x,y:this.axis.y,z:this.axis.z},angle:this.angle.toJSON()}}static fromJSON(t){return new ie(new et(t.axis.x,t.axis.y,t.axis.z),ee(t.angle))}clone(){return new ie(this.axis.clone(),this.angle.clone())}}class ne{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(M())}genColor(t,e){return-1===this.indexCount&&this.startGen(t),e.copy(this.a).lerp(this.b,t[this.indexCount])}toJSON(){return{type:"ColorRange",a:Et(this.a),b:Et(this.b)}}static fromJSON(t){return new ne(Ct(t.a),Ct(t.b))}clone(){return new ne(this.a.clone(),this.b.clone())}}class re{constructor(t,e){this.subType=e,this.type="function",this.keys=t}findKey(t){const e=this.keys,s=e.length-1;if(s<0||t<e[0][1])return-1;if(t>=e[s][1])return s;if(1===s)return 0;let i=0,n=s;for(;i+1<n;){const s=i+n>>1;if(t<e[s][1])n=s-1;else{if(!(t>this.getEndX(s)))return s;i=s+1}}for(let s=i;s<=n;s++)if(t>=e[s][1]&&t<=this.getEndX(s))return s;return-1}getStartX(t){return this.keys[t][1]}getEndX(t){return t+1<this.keys.length?this.keys[t+1][1]:1}genValue(t,e){const s=this.keys,i=this.findKey(e),n=s.length-1;if("Number"===this.subType){if(-1===i)return s[0][0];if(i>=n)return s[n][0];const t=s[i][1],r=s[i][0],o=s[i+1][1]-t;return(s[i+1][0]-r)*(o>0?(e-t)/o:0)+r}{if(-1===i)return t.copy(s[0][0]);if(i>=n)return t.copy(s[n][0]);const r=s[i][1],o=s[i+1][1]-r;return t.copy(s[i][0]).lerp(s[i+1][0],o>0?(e-r)/o:0)}}toJSON(){return{type:"CLinearFunction",subType:this.subType,keys:this.keys.map(([t,e])=>({value:Ft(t,this.subType),pos:e}))}}static fromJSON(t){switch(t.subType){case"Number":return new re(t.keys.map(t=>[Nt(t.value),t.pos]),t.subType);case"Vector4":return new re(t.keys.map(t=>[Ut(t.value),t.pos]),t.subType);default:return new re(t.keys.map(t=>[Bt(t.value),t.pos]),t.subType)}}clone(){return"Number"===this.subType?new re(this.keys.map(([t,e])=>[t,e]),this.subType):new re(this.keys.map(([t,e])=>[t.clone(),e]),this.subType)}}const oe=new Vt;class ae{constructor(t=[[new et(1,1,1),0],[new et(1,1,1),1]],e=[[1,0],[1,1]]){this.table=null,this.tableSignature=null,this.type="function",this.color=new re(t,"Color"),this.alpha=new re(e,"Number")}refreshTable(){const t=this.color.keys,e=this.alpha.keys,s=4*t.length+2*e.length;let i=this.tableSignature,n=null===i||i.length!==s;n&&(i=new Float64Array(s));let r=0;for(let e=0;e<t.length;e++,r+=4){const s=t[e][0],o=t[e][1];n||(n=i[r]!==s.x||i[r+1]!==s.y||i[r+2]!==s.z||i[r+3]!==o),n&&(i[r]=s.x,i[r+1]=s.y,i[r+2]=s.z,i[r+3]=o)}for(let t=0;t<e.length;t++,r+=2){const s=e[t][0],o=e[t][1];n||(n=i[r]!==s||i[r+1]!==o),n&&(i[r]=s,i[r+1]=o)}if(!n&&null!==this.table)return;this.tableSignature=i;const o=ae.TABLE_SIZE,a=null!==this.table&&this.table.length===4*o?this.table:new Float32Array(4*o),h=1/(o-1),l=oe;for(let t=0;t<o;t++){this.genColorExact(l,t*h);const e=4*t;a[e]=l.x,a[e+1]=l.y,a[e+2]=l.z,a[e+3]=l.w}this.table=a}sampledTable(){return this.table}clearTable(){this.table=null,this.tableSignature=null}genColor(t,e,s){const i=this.table;if(null!==i){const t=ae.TABLE_SIZE-1;if(s<=0)return e.x=i[0],e.y=i[1],e.z=i[2],e.w=i[3],e;if(s>=1){const s=4*t;return e.x=i[s],e.y=i[s+1],e.z=i[s+2],e.w=i[s+3],e}const n=s*t,r=0|n,o=n-r,a=4*r,h=a+4;return e.x=i[a]+(i[h]-i[a])*o,e.y=i[a+1]+(i[h+1]-i[a+1])*o,e.z=i[a+2]+(i[h+2]-i[a+2])*o,e.w=i[a+3]+(i[h+3]-i[a+3])*o,e}return this.genColorExact(e,s)}genColorExact(t,e){const s=this.color.keys,i=s.length-1,n=this.color.findKey(e);let r,o,a;if(-1===n||n>=i){const t=s[-1===n?0:i][0];r=t.x,o=t.y,a=t.z}else{const t=s[n][0],i=s[n+1][0],h=s[n][1],l=s[n+1][1]-h,c=l>0?(e-h)/l:0;r=t.x+(i.x-t.x)*c,o=t.y+(i.y-t.y)*c,a=t.z+(i.z-t.z)*c}const h=this.alpha.keys,l=h.length-1,c=this.alpha.findKey(e);let u;if(-1===c||c>=l)u=h[-1===c?0:l][0];else{const t=h[c][1],s=h[c][0],i=h[c+1][1]-t;u=s+(h[c+1][0]-s)*(i>0?(e-t)/i:0)}return t.x=r,t.y=o,t.z=a,t.w=u,t}toJSON(){return{type:"Gradient",color:this.color.toJSON(),alpha:this.alpha.toJSON()}}static fromJSON(t){if(t.functions){const e=t.functions.map(({function:t,start:e})=>[ne.fromJSON(t),e]),s=e.map(([t,e])=>[t.a,e]);return e.length>0&&s.push([e[e.length-1][0].b,1]),new ae(s.map(([t,e])=>[new et(t.x,t.y,t.z),e]),s.map(([t,e])=>[t.w,e]))}{const e=new ae;return t.alpha?e.alpha=re.fromJSON(t.alpha):Wt("Gradient has no alpha keys; it is opaque."),t.color?e.color=re.fromJSON(t.color):Wt("Gradient has no color keys; it is white."),e}}clone(){const t=new ae;return t.alpha=this.alpha.clone(),t.color=this.color.clone(),t}startGen(t){}}ae.TABLE_SIZE=257;class he{constructor(t,e){this.a=t,this.b=e,this.type="value"}startGen(t){}genColor(t,e){const s=M();return e.copy(this.a).lerp(this.b,s)}toJSON(){return{type:"RandomColor",a:Et(this.a),b:Et(this.b)}}static fromJSON(t){return new he(Ct(t.a),Ct(t.b))}clone(){return new he(this.a.clone(),this.b.clone())}}const le=new Vt;class ce{constructor(t,e){this.indexCount=-1,this.type="function",this.gradient1=t,this.gradient2=e}startGen(t){this.indexCount=t.length,t.push(M())}genColor(t,e,s){return-1===this.indexCount&&this.startGen(t),this.gradient1.genColor(t,e,s),this.gradient2.genColor(t,le,s),e.lerp(le,t[this.indexCount])}toJSON(){return{type:"RandomColorBetweenGradient",gradient1:this.gradient1.toJSON(),gradient2:this.gradient2.toJSON()}}static fromJSON(t){return new ce(ae.fromJSON(t.gradient1),ae.fromJSON(t.gradient2))}clone(){return new ce(this.gradient1.clone(),this.gradient2.clone())}}class ue{constructor(t){this.color=t,this.type="value"}startGen(t){}genColor(t,e){return e.copy(this.color)}toJSON(){return{type:"ConstantColor",color:Et(this.color)}}static fromJSON(t){return new ue(Ct(t.color))}clone(){return new ue(this.color.clone())}}function de(t){switch(t?.type){case"ConstantColor":return ue.fromJSON(t);case"ColorRange":return ne.fromJSON(t);case"RandomColor":return he.fromJSON(t);case"Gradient":return ae.fromJSON(t);case"RandomColorBetweenGradient":return ce.fromJSON(t);default:return Wt(`${Qt("colour generator",t)}; using white.`),new ue(new Vt(1,1,1,1))}}class fe{get eular(){return this.euler}set eular(t){this.euler=t}constructor(t,e,s,i){this.angleX=t,this.angleY=e,this.angleZ=s,this.type="rotation",this.euler=new yt(0,0,0,i)}startGen(t){this.angleX.startGen(t),this.angleY.startGen(t),this.angleZ.startGen(t)}genValue(t,e,s,i){return this.euler.set(this.angleX.genValue(t,i)*s,this.angleY.genValue(t,i)*s,this.angleZ.genValue(t,i)*s),e.setFromEuler(this.euler)}toJSON(){return{type:"Euler",angleX:this.angleX.toJSON(),angleY:this.angleY.toJSON(),angleZ:this.angleZ.toJSON(),eulerOrder:this.euler.order}}static fromJSON(t){return new fe(ee(t.angleX),ee(t.angleY),ee(t.angleZ),t.eulerOrder)}clone(){return new fe(this.angleX.clone(),this.angleY.clone(),this.angleZ.clone(),this.euler.order)}}class pe{constructor(){this.indexCount=-1,this.type="rotation"}startGen(t){let e,s,i,n,r,o;this.indexCount=t.length;do{e=2*M()-1,s=2*M()-1,i=e*e+s*s}while(i>1);do{n=2*M()-1,r=2*M()-1,o=n*n+r*r}while(o>1);const a=Math.sqrt((1-i)/o);t.push(e,s,a*n,a*r)}genValue(t,e,s,i){-1===this.indexCount&&this.startGen(t);const n=this.indexCount;return e.set(t[n],t[n+1],t[n+2],t[n+3]),e}toJSON(){return{type:"RandomQuat"}}static fromJSON(t){return new pe}clone(){return new pe}}function me(t){switch(t?.type){case"AxisAngle":return ie.fromJSON(t);case"Euler":return fe.fromJSON(t);case"RandomQuat":return pe.fromJSON(t);default:return Wt(`${Qt("rotation generator",t)}; using a random rotation.`),new pe}}class ye{constructor(t,e,s){this.x=t,this.y=e,this.z=s,this.type="vec3function"}startGen(t){this.x.startGen(t),this.y.startGen(t),this.z.startGen(t)}genValue(t,e,s){return e.set(this.x.genValue(t,s),this.y.genValue(t,s),this.z.genValue(t,s))}toJSON(){return{type:"Vector3Function",x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new ye(ee(t.x),ee(t.y),ee(t.z))}clone(){return new ye(this.x.clone(),this.y.clone(),this.z.clone())}}function ge(t){return"Vector3Function"===t?.type?ye.fromJSON(t):(Wt(`${Qt("vector generator",t)}; using a zero vector.`),new ye(new Yt(0),new Yt(0),new Yt(0)))}function ve(t){switch(t?.type){case"ConstantValue":case"IntervalValue":case"PiecewiseBezier":return ee(t);case"AxisAngle":case"RandomQuat":case"Euler":return me(t);case"Vector3Function":return ge(t);default:return Wt(`${Qt("generator",t)}; using 0.`),new Yt(0)}}function xe(t,e){return"world"===t||"local"===t?t:e}function Se(t){return 0===t?0:1/t}class be{constructor(){this.position=new et,this.quaternion=new tt,this.scale=new et(1,1,1),this.quaternionInverse=new tt,this.scaleInverse=new et(1,1,1)}refresh(t){t.emitter.matrixWorld.decompose(this.position,this.quaternion,this.scale),this.quaternionInverse.copy(this.quaternion).invert(),this.scaleInverse.set(Se(this.scale.x),Se(this.scale.y),Se(this.scale.z))}toSimulation(t,e,s){return s&&"local"===e?t.multiply(this.scale).applyQuaternion(this.quaternion):s||"world"!==e||t.applyQuaternion(this.quaternionInverse).multiply(this.scaleInverse),t}pointToSimulation(t,e,s){return s&&"local"===e?t.multiply(this.scale).applyQuaternion(this.quaternion).add(this.position):s||"world"!==e||t.sub(this.position).applyQuaternion(this.quaternionInverse).multiply(this.scaleInverse),t}}class we{constructor(t,e,s="world"){this.direction=t,this.magnitude=e,this.space=s,this.type="ApplyForce",this._frame=new be,this._direction=new et,this._direction.copy(t)}initialize(t,e){this.ps=e,this.magnitude.startGen(t.memory)}_step(t){const e=this.ps;return(void 0===e||e.worldSpace)&&"world"===this.space?t*(e?.motionScale??1):t}update(t,e){const s=this.magnitude.genValue(t.memory)*this._step(e),i=this._direction,n=t.velocity;n.x+=i.x*s,n.y+=i.y*s,n.z+=i.z*s}updateAll(t,e,s){const i=this.magnitude,n=this._direction,r=this._step(s),o=i instanceof Yt,a=o?i.value*r:0;for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const h=o?a:i.genValue(e.memory)*r,l=e.velocity;l.x+=n.x*h,l.y+=n.y*h,l.z+=n.z*h}}frameUpdate(t){this._direction.copy(this.direction),void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)&&(this._frame.refresh(this.ps),this._frame.toSimulation(this._direction,this.space,this.ps.worldSpace))}toJSON(){return{type:this.type,direction:[this.direction.x,this.direction.y,this.direction.z],magnitude:this.magnitude.toJSON(),..."world"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new we(Gt(t.direction,new et(0,0,0)),ee(t.magnitude??t.force),xe(t.space,"world"))}clone(){return new we(this.direction.clone(),this.magnitude.clone(),this.space)}reset(){}}class Me{constructor(t=0,e=0,s=new et){this.scaleX=t,this.scaleY=e,this.position=s,this.locations=[]}transform(t,e){const s=this.locations.length;if(0===s)return;const i=this.locations[e%s];t.x=i.x*this.scaleX+this.position.x,t.y=i.y*this.scaleY+this.position.y,t.z=this.position.z}static fromJSON(t){const e=t.position,s=Array.isArray(e)?new et(e[0],e[1],e[2]):new et(e?.x??0,e?.y??0,e?.z??0),i=new Me(t.scaleX??0,t.scaleY??0,s);return i.locations=(t.locations??[]).map(t=>new wt(t.x,t.y)),i}clone(){const t=new Me(this.scaleX,this.scaleY,this.position.clone());return t.locations=this.locations.map(t=>t.clone()),t}toJSON(){return{type:"TextureSequencer",scaleX:this.scaleX,scaleY:this.scaleY,position:[this.position.x,this.position.y,this.position.z],locations:this.locations.map(t=>({x:t.x,y:t.y}))}}fromImage(t,e){const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const i=s.getContext("2d");if(!i)return;i.drawImage(t,0,0);const n=i.getImageData(0,0,s.width,s.height,{colorSpace:"srgb"});s.remove(),this.locations.length=0;for(let t=0;t<n.height;t++)for(let s=0;s<n.width;s++)n.data[4*(t*n.width+s)+3]>e&&this.locations.push(new wt(s,n.height-t))}}function ze(t){switch(t?.type){case void 0:return null==t?void Wt(`${Qt("sequencer",t)}; skipping it.`):Me.fromJSON(t);case"TextureSequencer":return Me.fromJSON(t);default:return void Wt(`${Qt("sequencer",t)}; skipping it.`)}}class _e{constructor(t){this.type="ApplySequences",this.sequencers=[],this.time=0,this.index=0,this.pCount=0,this.tempV=new et,this.states=new WeakMap,this.delay=t}initialize(t){const e=this.states.get(t);e?(e.id=this.pCount,e.inMotion=!1):this.states.set(t,{id:this.pCount,begin:new et,dst:new et,inMotion:!1}),this.pCount++}reset(){this.time=0,this.index=0,this.pCount=0}update(t,e){const s=this.sequencers[this.index];if(void 0===s)return;const i=this.states.get(t);if(void 0===i)return;const[n,r]=s,o=i.id*this.delay;if(this.time>=n.a+o&&this.time<=n.b+o){i.inMotion||(i.inMotion=!0,i.begin.copy(t.position),r.transform(i.dst,i.id));const e=n.b-n.a;t.position.lerpVectors(i.begin,i.dst,_e.BEZIER.genValue(e>0?(this.time-n.a-o)/e:1))}else this.time>n.b+o&&(i.inMotion=!1)}frameUpdate(t){for(;this.index+1<this.sequencers.length&&this.time>=this.sequencers[this.index+1][0].a;)this.index++;this.time+=t}appendSequencer(t,e){this.sequencers.push([t,e])}toJSON(){return{type:this.type,delay:this.delay,sequencers:this.sequencers.map(([t,e])=>({range:t.toJSON(),sequencer:e.toJSON()}))}}static fromJSON(t){const e=new _e("number"==typeof t.delay?t.delay:0);return(Array.isArray(t.sequencers)?t.sequencers:[]).forEach(t=>{const s=ze(t.sequencer);void 0!==s&&e.sequencers.push([ee(t.range),s])}),e}clone(){const t=new _e(this.delay);return t.sequencers=this.sequencers.map(t=>[t[0].clone(),t[1].clone()]),t}}_e.BEZIER=new Zt(0,0,1,1);class Ve{constructor(t){this.angle=t,this.type="ChangeEmitDirection",this._temp=new et,this._q=new tt,this.memory=[]}initialize(t){const e=t.velocity.length();0!=e&&(t.velocity.normalize(),0===t.velocity.x&&0===t.velocity.y?this._temp.set(0,t.velocity.z,0):this._temp.set(-t.velocity.y,t.velocity.x,0),this.memory.length=0,this.angle.startGen(this.memory),this._q.setFromAxisAngle(this._temp.normalize(),this.angle.genValue(this.memory)),this._temp.copy(t.velocity),t.velocity.applyQuaternion(this._q),this._q.setFromAxisAngle(this._temp,M()*Math.PI*2),t.velocity.applyQuaternion(this._q),t.velocity.setLength(e))}update(t,e){}frameUpdate(t){}toJSON(){return{type:this.type,angle:this.angle.toJSON()}}static fromJSON(t){return new Ve(ee(t.angle))}clone(){return new Ve(this.angle.clone())}reset(){this.memory.length=0}}function Ae(t,e){const s=t.velocity.length()*t.speedModifier,i=e.b-e.a;if(0===i)return s>=e.a?1:0;const n=(s-e.a)/i;return n<0?0:n>1?1:n}class Te{constructor(t,e){this.color=t,this.speedRange=e,this.type="ColorBySpeed"}initialize(t){this.color.startGen(t.memory)}update(t,e){const s=Ae(t,this.speedRange);this.color.genColor(t.memory,t.color,s),t.color.x*=t.startColor.x,t.color.y*=t.startColor.y,t.color.z*=t.startColor.z,t.color.w*=t.startColor.w}frameUpdate(t){}toJSON(){return{type:this.type,color:this.color.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new Te(de(t.color),t.speedRange?Xt.fromJSON(t.speedRange):new Xt(0,1))}clone(){return new Te(this.color.clone(),this.speedRange.clone())}reset(){}}class Oe{constructor(t){this.color=t,this.type="ColorOverLife"}initialize(t){this.color.startGen(t.memory)}update(t,e){const s=t.color,i=t.startColor;this.color.genColor(t.memory,s,t.age/t.life),s.x*=i.x,s.y*=i.y,s.z*=i.z,s.w*=i.w}updateAll(t,e,s){const i=this.color;for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const n=e.color,r=e.startColor;i.genColor(e.memory,n,e.age/e.life),n.x*=r.x,n.y*=r.y,n.z*=r.z,n.w*=r.w}}frameUpdate(t){this.color.refreshTable?.()}toJSON(){return{type:this.type,color:this.color.toJSON()}}static fromJSON(t){return new Oe(de(t.color))}clone(){return new Oe(this.color.clone())}reset(){}}class Pe{constructor(t=64){this.previousVelocity=Pe.EMPTY,this.rotationQuaternion=Pe.EMPTY,this.angularVelocityQuaternion=Pe.EMPTY,this.memory=new Float64Array(0),this.memoryStride=0,this.capacity=Math.max(1,t),this.position=new Float32Array(3*this.capacity),this.previousPosition=new Float32Array(3*this.capacity),this.previousSize=new Float32Array(3*this.capacity),this.previousColor=new Float32Array(4*this.capacity),this.velocity=new Float32Array(3*this.capacity),this.size=new Float32Array(3*this.capacity),this.startSize=new Float32Array(3*this.capacity),this.color=new Float32Array(4*this.capacity),this.startColor=new Float32Array(4*this.capacity),this.scalars=new Float64Array(this.capacity*Pe.SCALAR_STRIDE),this.rotation=new Float32Array(this.capacity),this.angularVelocity=new Float32Array(this.capacity),this.uvTile=new Float32Array(this.capacity),this.startSpeed=new Float32Array(this.capacity),this.flip=new Uint8Array(this.capacity)}ensureCapacity(t){if(t<=this.capacity)return!1;let e=this.capacity;for(;e<t;)e*=2;this.position=Pe.grow(this.position,3*e),this.previousPosition=Pe.grow(this.previousPosition,3*e);const s=this.previousSize===this.size,i=this.previousColor===this.color;if(s||(this.previousSize=Pe.grow(this.previousSize,3*e)),this.previousVelocity.length>0&&(this.previousVelocity=Pe.grow(this.previousVelocity,3*e)),this.rotationQuaternion.length>0){const t=this.rotationQuaternion.length;this.rotationQuaternion=Pe.grow(this.rotationQuaternion,4*e),this.angularVelocityQuaternion=Pe.grow(this.angularVelocityQuaternion,4*e);for(let s=t+3;s<4*e;s+=4)this.rotationQuaternion[s]=1,this.angularVelocityQuaternion[s]=1}if(i||(this.previousColor=Pe.grow(this.previousColor,4*e)),this.velocity=Pe.grow(this.velocity,3*e),this.size=Pe.grow(this.size,3*e),this.startSize=Pe.grow(this.startSize,3*e),this.color=Pe.grow(this.color,4*e),s&&(this.previousSize=this.size),i&&(this.previousColor=this.color),this.startColor=Pe.grow(this.startColor,4*e),this.scalars=Pe.growDouble(this.scalars,e*Pe.SCALAR_STRIDE),this.memoryStride>0){const t=new Float64Array(e*this.memoryStride);t.fill(NaN),t.set(this.memory),this.memory=t}this.rotation=Pe.grow(this.rotation,e),this.angularVelocity=Pe.grow(this.angularVelocity,e),this.uvTile=Pe.grow(this.uvTile,e),this.startSpeed=Pe.grow(this.startSpeed,e);const n=new Uint8Array(e);return n.set(this.flip),this.flip=n,this.capacity=e,!0}keepPreviousVelocity(){return!(this.previousVelocity.length>=3*this.capacity)&&(this.previousVelocity=new Float32Array(3*this.capacity),!0)}recordMemory(t,e){const s=e.length;let i=this.memoryStride;if(s>i||this.memory.length<this.capacity*i){i=Math.max(i,s);const t=new Float64Array(this.capacity*i);t.fill(NaN);const e=this.memoryStride,n=this.memory,r=e>0?n.length/e:0;for(let s=0,o=0,a=0;s<r;s++,o+=e,a+=i)for(let s=0;s<e;s++)t[a+s]=n[o+s];this.memory=t,this.memoryStride=i}const n=t*i;for(let t=0;t<i;t++){const i=t<s?e[t]:void 0;this.memory[n+t]="number"==typeof i?i:NaN}}useSizeSnapshot(t){t?this.previousSize===this.size&&(this.previousSize=new Float32Array(this.size)):this.previousSize=this.size}useColorSnapshot(t){t?this.previousColor===this.color&&(this.previousColor=new Float32Array(this.color)):this.previousColor=this.color}ensureQuaternionColumns(){if(this.rotationQuaternion.length>=4*this.capacity)return!1;this.rotationQuaternion=new Float32Array(4*this.capacity),this.angularVelocityQuaternion=new Float32Array(4*this.capacity);for(let t=3;t<this.rotationQuaternion.length;t+=4)this.rotationQuaternion[t]=1,this.angularVelocityQuaternion[t]=1;return!0}swapRows(t,e){if(t===e)return;const s=3*t,i=3*e;Pe.swap3(this.position,s,i),Pe.swap3(this.previousPosition,s,i),this.previousSize!==this.size&&Pe.swap3(this.previousSize,s,i),this.previousVelocity.length>0&&Pe.swap3(this.previousVelocity,s,i),Pe.swap3(this.velocity,s,i),Pe.swap3(this.size,s,i),Pe.swap3(this.startSize,s,i);const n=4*t,r=4*e;Pe.swap4(this.color,n,r),this.previousColor!==this.color&&Pe.swap4(this.previousColor,n,r),Pe.swap4(this.startColor,n,r),this.rotationQuaternion.length>0&&(Pe.swap4(this.rotationQuaternion,n,r),Pe.swap4(this.angularVelocityQuaternion,n,r)),Pe.swap3(this.scalars,t*Pe.SCALAR_STRIDE,e*Pe.SCALAR_STRIDE);const o=this.memoryStride;if(o>0){const s=this.memory;for(let i=0,n=t*o,r=e*o;i<o;i++,n++,r++){const t=s[n];s[n]=s[r],s[r]=t}}Pe.swap1(this.rotation,t,e),Pe.swap1(this.angularVelocity,t,e),Pe.swap1(this.uvTile,t,e),Pe.swap1(this.startSpeed,t,e),Pe.swap1(this.flip,t,e)}static swap1(t,e,s){const i=t[e];t[e]=t[s],t[s]=i}static growDouble(t,e){const s=new Float64Array(e);return s.set(t),s}static swap3(t,e,s){let i=t[e];t[e]=t[s],t[s]=i,i=t[e+1],t[e+1]=t[s+1],t[s+1]=i,i=t[e+2],t[e+2]=t[s+2],t[s+2]=i}static swap4(t,e,s){Pe.swap3(t,e,s);const i=t[e+3];t[e+3]=t[s+3],t[s+3]=i}static grow(t,e){const s=new Float32Array(e);return s.set(t),s}}Pe.EMPTY=new Float32Array(0),Pe.SCALAR_STRIDE=3,Pe.AGE=0,Pe.LIFE=1,Pe.SPEED_MODIFIER=2;class $e{constructor(t){this.data=t,this.next=null,this.prev=null}hasPrev(){return null!==this.prev}hasNext(){return null!==this.next}}class Ee{constructor(){this.length=0,this.head=this.tail=null}isEmpty(){return null===this.head}clear(){this.length=0,this.head=this.tail=null}front(){return null===this.head?null:this.head.data}back(){return null===this.tail?null:this.tail.data}dequeue(){if(this.head){const t=this.head.data;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,t}}pop(){if(this.tail){const t=this.tail.data;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,t}}queue(t){const e=new $e(t);this.tail||(this.tail=e),this.head&&(this.head.prev=e,e.next=this.head),this.head=e,this.length++}push(t){const e=new $e(t);this.head||(this.head=e),this.tail&&(this.tail.next=e,e.prev=this.tail),this.tail=e,this.length++}insertBefore(t,e){const s=new $e(e);s.next=t,s.prev=t.prev,null!==s.prev&&(s.prev.next=s),s.next.prev=s,t==this.head&&(this.head=s),this.length++}remove(t){if(null===this.head||null===this.tail)return;let e=this.head;for(t===this.head.data&&(this.head=this.head.next),t===this.tail.data&&(this.tail=this.tail.prev);null!==e.next&&e.data!==t;)e=e.next;e.data===t&&(null!==e.prev&&(e.prev.next=e.next),null!==e.next&&(e.next.prev=e.prev),this.length--)}*values(){let t=this.head;for(;null!==t;)yield t.data,t=t.next}}class Ce{get startSpeed(){return this.store.startSpeed[this.storeIndex]}set startSpeed(t){this.store.startSpeed[this.storeIndex]=t}get age(){return this.scalars[this.scalarOffset]}set age(t){this.scalars[this.scalarOffset]=t}get life(){return this.scalars[this.scalarOffset+1]}set life(t){this.scalars[this.scalarOffset+1]=t}get speedModifier(){return this.scalars[this.scalarOffset+2]}set speedModifier(t){this.scalars[this.scalarOffset+2]=t}get angularVelocity(){const t=this.angularVelocityQuaternion;return void 0!==t?t:this.store.angularVelocity[this.storeIndex]}set angularVelocity(t){if("number"==typeof t)this.angularVelocityQuaternion=void 0,this.store.angularVelocity[this.storeIndex]=t;else if(void 0===t)this.angularVelocityQuaternion=void 0,this.store.angularVelocity[this.storeIndex]=0;else{let e=this.angularVelocityQuaternion;void 0===e&&(this.store.ensureQuaternionColumns(),e=new St(this.store.angularVelocityQuaternion,4*this.storeIndex),this.angularVelocityQuaternion=e),e!==t&&e.copy(t)}}get rotation(){const t=this.rotationQuaternion;return void 0!==t?t:this.store.rotation[this.storeIndex]}set rotation(t){if("number"==typeof t)this.rotationQuaternion=void 0,this.store.rotation[this.storeIndex]=t;else{let e=this.rotationQuaternion;void 0===e&&(this.store.ensureQuaternionColumns(),e=new St(this.store.rotationQuaternion,4*this.storeIndex),this.rotationQuaternion=e),e!==t&&e.copy(t)}}get uvTile(){return this.store.uvTile[this.storeIndex]}set uvTile(t){this.store.uvTile[this.storeIndex]=t}get flip(){return this.store.flip[this.storeIndex]}set flip(t){this.store.flip[this.storeIndex]=t}constructor(t=new Pe(1),e=0){this.rotationQuaternion=void 0,this.angularVelocityQuaternion=void 0,this.memory=[],this.store=t,this.storeIndex=e;const s=3*e,i=4*e;this.position=new zt(t.position,s),this.previousPosition=new zt(t.previousPosition,s),this.previousVelocity=new zt(t.previousVelocity,s),this.velocity=new zt(t.velocity,s),this.size=new zt(t.size,s),this.startSize=new zt(t.startSize,s),this.color=new Tt(t.color,i),this.startColor=new Tt(t.startColor,i),this.scalars=t.scalars,this.scalarOffset=e*Pe.SCALAR_STRIDE,this.size.set(1,1,1),this.startSize.set(1,1,1),this.life=1,this.speedModifier=1}setStoreIndex(t){this.storeIndex=t,this.rebind()}rebind(){const t=this.store,e=3*this.storeIndex,s=4*this.storeIndex;this.position.bind(t.position,e),this.previousPosition.bind(t.previousPosition,e),this.previousVelocity.bind(t.previousVelocity,e),this.velocity.bind(t.velocity,e),this.size.bind(t.size,e),this.startSize.bind(t.startSize,e),this.color.bind(t.color,s),this.startColor.bind(t.startColor,s),this.rotationQuaternion?.bind(t.rotationQuaternion,s),this.angularVelocityQuaternion?.bind(t.angularVelocityQuaternion,s),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*Pe.SCALAR_STRIDE}get died(){return this.age>=this.life}reset(){this.memory.length=0}}const Fe=new Float32Array(0);class Ie{get startSpeed(){return this.store.startSpeed[this.storeIndex]}set startSpeed(t){this.store.startSpeed[this.storeIndex]=t}get age(){return this.scalars[this.scalarOffset]}set age(t){this.scalars[this.scalarOffset]=t}get life(){return this.scalars[this.scalarOffset+1]}set life(t){this.scalars[this.scalarOffset+1]=t}get speedModifier(){return this.scalars[this.scalarOffset+2]}set speedModifier(t){this.scalars[this.scalarOffset+2]=t}get previous(){return this._previous??(this._previous=new Ee)}set previous(t){this._previous=t}get uvTile(){return this.store.uvTile[this.storeIndex]}set uvTile(t){this.store.uvTile[this.storeIndex]=t}constructor(t=new Pe(1),e=0){this.length=30,this._previous=void 0,this.historyPositions=Fe,this.historySizes=Fe,this.historyBaseSizes=Fe,this.headWidthScale=1,this.historyColors=Fe,this.historySides=Fe,this.historyAges=Fe,this.historyDistances=Fe,this.historyCapacity=0,this.historyHead=0,this.historyCount=0,this.memory=[],this.store=t,this.storeIndex=e;const s=3*e,i=4*e;this.position=new zt(t.position,s),this.previousPosition=new zt(t.previousPosition,s),this.previousVelocity=new zt(t.previousVelocity,s),this.velocity=new zt(t.velocity,s),this.size=new zt(t.size,s),this.startSize=new zt(t.startSize,s),this.color=new Tt(t.color,i),this.startColor=new Tt(t.startColor,i),this.scalars=t.scalars,this.scalarOffset=e*Pe.SCALAR_STRIDE,this.size.set(1,1,1),this.startSize.set(1,1,1),this.life=1,this.speedModifier=1}setStoreIndex(t){this.storeIndex=t,this.rebind()}rebind(){const t=this.store,e=3*this.storeIndex,s=4*this.storeIndex;this.position.bind(t.position,e),this.previousPosition.bind(t.previousPosition,e),this.previousVelocity.bind(t.previousVelocity,e),this.velocity.bind(t.velocity,e),this.size.bind(t.size,e),this.startSize.bind(t.startSize,e),this.color.bind(t.color,s),this.startColor.bind(t.startColor,s),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*Pe.SCALAR_STRIDE}ensureHistoryCapacity(t){this.historyCapacity!==t&&(this.historyCapacity=t,this.historySizes.length<t&&(this.historyPositions=new Float32Array(3*t),this.historySizes=new Float32Array(t),this.historyBaseSizes=new Float32Array(t),this.historyColors=new Float32Array(4*t),this.historyAges=new Float32Array(t),this.historyDistances=new Float32Array(t),this.historySides.length>0&&(this.historySides=new Float32Array(3*t))),this.historyHead=0,this.historyCount=0)}ensureSideHistory(){this.historySides.length<3*this.historyCapacity&&(this.historySides=new Float32Array(3*this.historyCapacity))}resetHistory(){this.historyHead=0,this.historyCount=0}getHistoryIndex(t){const e=this.historyCapacity;return(this.historyHead-this.historyCount+e+t)%e}update(t=!1,e=!0){0===this.historyCapacity&&this.ensureHistoryCapacity(Math.max(1,Math.ceil(this.length)));const s=this.historyCapacity,i=this.store,n=this.storeIndex,r=n*Pe.SCALAR_STRIDE,o=i.scalars[r+Pe.AGE];if(o>=i.scalars[r+Pe.LIFE])return void this.dropOldest();const a=t&&this.historyCount>0,h=a?(this.historyHead+s-1)%s:this.historyHead,l=3*h,c=this.historyPositions,u=i.position,d=3*n;c[l]=u[d],c[l+1]=u[d+1],c[l+2]=u[d+2];const f=i.size[d];this.historyBaseSizes[h]=f,this.historySizes[h]=f*this.headWidthScale;const p=4*h,m=this.historyColors,y=i.color,g=4*n;m[p]=y[g],m[p+1]=y[g+1],m[p+2]=y[g+2],m[p+3]=y[g+3],this.historyAges[h]=o,a||(this.historyHead=(h+1)%s,this.historyCount<s&&this.historyCount++),e&&this.measureHeadDistance()}measureHeadDistance(){const t=this.historyCount;if(0===t)return;const e=this.historyCapacity,s=(this.historyHead+e-1)%e;if(1===t)return void(this.historyDistances[s]=0);const i=(s+e-1)%e,n=this.historyPositions,r=n[3*s]-n[3*i],o=n[3*s+1]-n[3*i+1],a=n[3*s+2]-n[3*i+2];this.historyDistances[s]=this.historyDistances[i]+Math.sqrt(r*r+o*o+a*a)}dropOldest(){this.historyCount>0&&this.historyCount--}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.headWidthScale=1,this.resetHistory()}}function Ne(t,e){return Math.floor(M()*(e-t))+t}function Be(t,e){const s=Number.isNaN(t)?0:1-K.clamp(t,0,1),i=K.lerp(Math.pow(s,e),1,M());return 2===e?Math.sqrt(i):Math.cbrt(i)}const Ue=new et(0,1,0),Re=new et(0,0,0),De=new et(1,1,1),Le=new et(0,0,1),ke=1e-6;var qe;exports.SubParticleEmitMode=void 0,(qe=exports.SubParticleEmitMode||(exports.SubParticleEmitMode={}))[qe.Death=0]="Death",qe[qe.Birth=1]="Birth",qe[qe.Frame=2]="Frame";const Je={color:1,size:2,rotation:4,lifetime:8};function We(t){let e=0;for(const s of t)e|=Je[s]??0;return e}class Ge{constructor(t,e,s,i=exports.SubParticleEmitMode.Frame,n=1,r=[]){this.particleSystem=t,this.useVelocityAsBasis=e,this.subParticleSystem=s,this.mode=i,this.emitProbability=n,this.inherit=r,this.type="EmitSubParticleSystem",this.q_=new tt,this.v_=new et,this.v2_=new et,this.v3_=new et,this.subEmissions=new Array,this.spareEmissions=new Array;const o=this.target;o&&(o.onlyUsedByOther=!0)}initialize(t){}update(t,e){(this.mode===exports.SubParticleEmitMode.Frame||this.mode===exports.SubParticleEmitMode.Birth&&0===t.age||this.mode===exports.SubParticleEmitMode.Death&&t.age+e>=t.life)&&this.emit(t,e)}get target(){const t=this.subParticleSystem;if(null===t||"object"!=typeof t)return;const e=t.system;return e?.isDisposed?void 0:e}emit(t,e){if(!this.target)return;if(M()>this.emitProbability)return;const s=this.spareEmissions.pop(),i=void 0!==s?s:{burstParticleCount:0,burstParticleIndex:0,isBursting:!1,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,matrix:new ot,travelDistance:0,particle:void 0,serial:void 0,previousWorldPos:void 0};i.burstParticleCount=0,i.burstParticleIndex=0,i.isBursting=!1,i.burstIndex=0,i.burstWaveIndex=0,i.time=0,i.waitEmiting=0,i.travelDistance=0,this.mode===exports.SubParticleEmitMode.Death?(i.particle=Ge.copyInto(i.ghost??(i.ghost=new Ce),t),i.serial=void 0):(i.particle=t,i.serial=t.serial),i.inherit=We(this.inherit),this.mode===exports.SubParticleEmitMode.Death&&(i.inherit&=~Je.lifetime),i.previousWorldPos=void 0,this.setMatrixFromParticle(i.matrix,t),this.subEmissions.push(i)}frameUpdate(t){const e=this.target;if(e)for(let s=0;s<this.subEmissions.length;s++)if(this.subEmissions[s].time>=e.duration){const t=this.subEmissions[s];t.particle=void 0,t.matrix=new ot,this.spareEmissions.push(t),this.subEmissions[s]=this.subEmissions[this.subEmissions.length-1],this.subEmissions.length=this.subEmissions.length-1,s--}else{const i=this.subEmissions[s],n=i.particle;void 0!==n&&n===i.ghost||(void 0!==n&&n.age<n.life&&n.serial===i.serial?this.setMatrixFromParticle(i.matrix,n):i.particle=void 0),e.emit(t,i,i.matrix)}else this.clearEmissions()}toJSON(){return{type:this.type,subParticleSystem:"string"==typeof this.subParticleSystem?this.subParticleSystem:this.subParticleSystem?this.subParticleSystem.uuid:"",useVelocityAsBasis:this.useVelocityAsBasis,mode:this.mode,emitProbability:this.emitProbability,...this.inherit.length>0?{inherit:this.inherit.slice()}:{}}}static fromJSON(t,e){return new Ge(e,Boolean(t.useVelocityAsBasis),t.subParticleSystem,t.mode,t.emitProbability,Ge.validInherit(t.inherit))}clone(){return new Ge(this.particleSystem,this.useVelocityAsBasis,this.subParticleSystem,this.mode,this.emitProbability,this.inherit.slice())}reset(){this.clearEmissions()}clearEmissions(){for(const t of this.subEmissions)t.particle=void 0,this.spareEmissions.push(t);this.subEmissions.length=0}static copyInto(t,e){return t.position.copy(e.position),t.velocity.copy(e.velocity),t.color.copy(e.color),t.size.copy(e.size),t.rotation=e.rotation??0,t.age=e.age,t.life=e.life,t}static validInherit(t){return Array.isArray(t)?t.filter(t=>t in Je):[]}setMatrixFromParticle(t,e){let s;if(void 0===e.rotation||this.useVelocityAsBasis){const s=e.position,i=this.v3_.copy(e.velocity),n=i.length(),r=this.v_,o=this.v2_;if(n<ke)r.set(1,0,0),o.set(0,1,0),i.set(0,0,1);else if(i.divideScalar(n),Math.abs(i.x)<ke&&Math.abs(i.y)<ke){const t=i.z>0?1:-1;r.set(1,0,0),o.set(0,t,0),i.set(0,0,t)}else r.copy(Le).cross(i).normalize(),o.copy(i).cross(r);t.set(r.x,o.x,i.x,s.x,r.y,o.y,i.y,s.y,r.z,o.z,i.z,s.z,0,0,0,1)}else e.rotation instanceof tt?s=e.rotation:(this.q_.setFromAxisAngle(Le,e.rotation),s=this.q_),t.compose(e.position,s,De);this.particleSystem.worldSpace||t.multiplyMatrices(this.particleSystem.emitter.matrixWorld,t)}}class Qe{initialize(t,e){this.ps=e,this.x.startGen(t.memory),this.y.startGen(t.memory),this.z.startGen(t.memory)}constructor(t,e,s,i="world"){this.x=t,this.y=e,this.z=s,this.space=i,this.type="ForceOverLife",this._temp=new et,this._frame=new be}_step(t){const e=this.ps;return(void 0===e||e.worldSpace)&&"world"===this.space?t*(e?.motionScale??1):t}update(t,e){const s=t.age/t.life;this._temp.set(this.x.genValue(t.memory,s),this.y.genValue(t.memory,s),this.z.genValue(t.memory,s));const i=void 0===this.ps||this.ps.worldSpace;this._frame.toSimulation(this._temp,this.space,i),t.velocity.addScaledVector(this._temp,this._step(e))}updateAll(t,e,s){const i=this._temp,n=this.x,r=this.y,o=this.z,a=this._frame,h=this.space,l=void 0===this.ps||this.ps.worldSpace,c=l!==("world"===h),u=this._step(s);for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const d=e.memory,f=e.age/e.life;i.set(n.genValue(d,f),r.genValue(d,f),o.genValue(d,f)),c&&a.toSimulation(i,h,l),e.velocity.addScaledVector(i,u)}}toJSON(){return{type:this.type,x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON(),..."world"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new Qe(ee(t.x),ee(t.y),ee(t.z),xe(t.space,"world"))}frameUpdate(t){void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)&&this._frame.refresh(this.ps)}clone(){return new Qe(this.x.clone(),this.y.clone(),this.z.clone(),this.space)}reset(){}}class je{constructor(t,e={}){this.type="FrameOverLife",this.salt=new Xt(0,1),this.frame=t,this.fps=e.fps??0,this.cycles=e.cycles??1,this.frameCount=e.frameCount??0,this.loop=e.loop??!0,this.random=e.random??!1,this.startFrame=e.startFrame}get frame(){return this._frame}set frame(t){this._frame=t}isPlain(){return!(this.fps>0)&&1===this.cycles&&void 0===this.startFrame}initialize(t){this._frame.startGen(t.memory),this.startFrame?.startGen(t.memory),this.salt.startGen(t.memory)}update(t,e){t.uvTile=this.frameAt(t,t.age,t.age/t.life)}updateAll(t,e,s){for(let s=0;s<e;s++){const e=t[s];e.age>=e.life||(e.uvTile=this.frameAt(e,e.age,e.age/e.life))}}frameAt(t,e,s){if(this.fps>0){const i=this.sampleFrame(t,s),n=this.frameCount;let r=Math.floor(e*this.fps)+this.offset(t);return this.random&&n>0?i+Math.floor(je.hash(r,this.saltOf(t))*n):(n>0&&(r=this.loop?je.wrap(r,n):Math.min(r,n-1)),i+r)}let i;if(1!==this.cycles&&this.cycles>0){const e=s*this.cycles;i=this.sampleFrame(t,s>=1?1:e-Math.floor(e))}else i=this.sampleFrame(t,s);return void 0!==this.startFrame&&(i+=this.offset(t),this.frameCount>0&&(i=je.wrap(i,this.frameCount))),i}offset(t){return void 0!==this.startFrame?Math.floor(this.startFrame.genValue(t.memory)):0}saltOf(t){const e=t.memory[this.salt.indexCount];return"number"==typeof e?e:0}static hash(t,e){const s=43758.5453*Math.sin(12.9898*t+7833.233*e);return Math.min(s-Math.floor(s),.999999)}static wrap(t,e){return(t%e+e)%e}sampleFrame(t,e){return"function"===this._frame.type?this._frame.genValue(t.memory,e):this._frame.genValue(t.memory)}frameUpdate(t){this._frame.refreshTable?.()}toJSON(){return{type:this.type,frame:this.frame.toJSON(),...this.fps>0?{fps:this.fps}:{},...1!==this.cycles?{cycles:this.cycles}:{},...this.frameCount>0?{frameCount:this.frameCount}:{},...this.loop?{}:{loop:!1},...this.random?{random:!0}:{},...void 0!==this.startFrame?{startFrame:this.startFrame.toJSON()}:{}}}static fromJSON(t){return new je(ee(t.frame),{fps:"number"==typeof t.fps?t.fps:void 0,cycles:"number"==typeof t.cycles?t.cycles:void 0,frameCount:"number"==typeof t.frameCount?t.frameCount:void 0,loop:"boolean"==typeof t.loop?t.loop:void 0,random:!0===t.random,startFrame:void 0!==t.startFrame?ee(t.startFrame):void 0})}clone(){return new je(this.frame.clone(),{fps:this.fps,cycles:this.cycles,frameCount:this.frameCount,loop:this.loop,random:this.random,startFrame:this.startFrame?.clone()})}reset(){}}class He{constructor(t,e){this.center=t,this.magnitude=e,this.type="GravityForce",this.temp=new et}initialize(t){}update(t,e){const s=t.position.distanceToSquared(this.center);0!==s&&(this.temp.copy(this.center).sub(t.position).normalize(),t.velocity.addScaledVector(this.temp,this.magnitude/s*e))}updateAll(t,e,s){const i=this.center.x,n=this.center.y,r=this.center.z,o=this.magnitude*s;for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const a=e.position,h=i-a.x,l=n-a.y,c=r-a.z,u=h*h+l*l+c*c;if(0===u)continue;const d=o/(u*Math.sqrt(u)),f=e.velocity;f.x+=h*d,f.y+=l*d,f.z+=c*d}}frameUpdate(t){}toJSON(){return{type:this.type,center:[this.center.x,this.center.y,this.center.z],magnitude:this.magnitude}}static fromJSON(t){return new He(Gt(t.center,new et(0,0,0)),"number"==typeof t.magnitude?t.magnitude:0)}clone(){return new He(this.center.clone(),this.magnitude)}reset(){}}class Ye{constructor(t=new Yt(1),e="initial"){this.multiplier=t,this.mode=e,this.type="InheritVelocity",this._temp=new et,this._tempPos=new et,this._tempQInv=new tt,this._tempScaleInv=new et(1,1,1)}initialize(t,e){this.ps=e,this.multiplier.startGen(t.memory),"initial"===this.mode&&e.emitterVelocity&&(this._temp.copy(e.emitterVelocity),e.worldSpace||(this.decomposeInverse(e),this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv)),t.velocity.addScaledVector(this._temp,this.multiplier.genValue(t.memory,0)))}frameUpdate(t){this.ps&&!this.ps.worldSpace&&this.decomposeInverse(this.ps)}update(t,e){"current"===this.mode&&void 0!==this.ps&&this.ps.emitterVelocity&&(this._temp.copy(this.ps.emitterVelocity),this.ps.worldSpace||this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv),t.position.addScaledVector(this._temp,this.multiplier.genValue(t.memory,t.age/t.life)*e))}decomposeInverse(t){t.emitter.matrixWorld.decompose(this._tempPos,this._tempQInv,this._tempScaleInv),this._tempQInv.invert(),this._tempScaleInv.set(1/this._tempScaleInv.x,1/this._tempScaleInv.y,1/this._tempScaleInv.z)}toJSON(){return{type:this.type,multiplier:this.multiplier.toJSON(),mode:this.mode}}static fromJSON(t){return new Ye(t.multiplier?ee(t.multiplier):new Yt(1),"current"===t.mode?"current":"initial")}clone(){return new Ye(this.multiplier.clone(),this.mode)}reset(){}}class Xe{initialize(t,e){void 0!==e&&(this.ps=e),this.speed.startGen(t.memory)}motionScale(){const t=this.ps;return void 0!==t&&t.worldSpace?t.motionScale??1:1}constructor(t,e){this.speed=t,this.dampen=e,this.type="LimitSpeedOverLife"}dampenStep(t){const e=this.dampen>1?1:this.dampen>0?this.dampen:0;return 1-Math.pow(1-e/3,60*t)}update(t,e){const s=t.velocity.length(),i=this.speed.genValue(t.memory,t.age/t.life)*this.motionScale();if(s>i){const n=(s-i)/s;t.velocity.multiplyScalar(1-n*this.dampenStep(e))}}updateAll(t,e,s){const i=this.speed,n=this.dampenStep(s),r=this.motionScale();for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const o=e.velocity,a=o.length(),h=i.genValue(e.memory,e.age/e.life)*r;a>h&&o.multiplyScalar(1-(a-h)/a*n)}}toJSON(){return{type:this.type,speed:this.speed.toJSON(),dampen:this.dampen}}static fromJSON(t){return new Xe(ee(t.speed),"number"==typeof t.dampen?t.dampen:1)}frameUpdate(t){this.speed.refreshTable?.()}clone(){return new Xe(this.speed.clone(),this.dampen)}reset(){}}const Ze=.5*(Math.sqrt(3)-1),Ke=(3-Math.sqrt(3))/6,ts=1/3,es=1/6,ss=(Math.sqrt(5)-1)/4,is=(5-Math.sqrt(5))/20,ns=new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),rs=new Float32Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);class os{constructor(t=e){const e="function"==typeof t?t:function(t){let e=0,s=0,i=0,n=1;const r=function(){let t=4022871197;return function(e){e=e.toString();for(let s=0;s<e.length;s++){t+=e.charCodeAt(s);let i=.02519603282416938*t;t=i>>>0,i-=t,i*=t,t=i>>>0,i-=t,t+=4294967296*i}return 2.3283064365386963e-10*(t>>>0)}}();e=r(" "),s=r(" "),i=r(" "),e-=r(t),e<0&&(e+=1);s-=r(t),s<0&&(s+=1);i-=r(t),i<0&&(i+=1);return function(){const t=2091639*e+2.3283064365386963e-10*n;return e=s,s=i,i=t-(n=0|t)}}(t);this.p=function(t){const e=new Uint8Array(256);for(let t=0;t<256;t++)e[t]=t;for(let s=0;s<255;s++){const i=s+~~(t()*(256-s)),n=e[s];e[s]=e[i],e[i]=n}return e}(e),this.perm=new Uint8Array(512),this.permMod12=new Uint8Array(512);for(let t=0;t<512;t++)this.perm[t]=this.p[255&t],this.permMod12[t]=this.perm[t]%12}noise2D(t,e){const s=this.permMod12,i=this.perm;let n=0,r=0,o=0;const a=(t+e)*Ze,h=Math.floor(t+a),l=Math.floor(e+a),c=(h+l)*Ke,u=t-(h-c),d=e-(l-c);let f,p;u>d?(f=1,p=0):(f=0,p=1);const m=u-f+Ke,y=d-p+Ke,g=u-1+2*Ke,v=d-1+2*Ke,x=255&h,S=255&l;let b=.5-u*u-d*d;if(b>=0){const t=3*s[x+i[S]];b*=b,n=b*b*(ns[t]*u+ns[t+1]*d)}let w=.5-m*m-y*y;if(w>=0){const t=3*s[x+f+i[S+p]];w*=w,r=w*w*(ns[t]*m+ns[t+1]*y)}let M=.5-g*g-v*v;if(M>=0){const t=3*s[x+1+i[S+1]];M*=M,o=M*M*(ns[t]*g+ns[t+1]*v)}return 70*(n+r+o)}noise3D(t,e,s){const i=this.permMod12,n=this.perm;let r,o,a,h;const l=(t+e+s)*ts,c=Math.floor(t+l),u=Math.floor(e+l),d=Math.floor(s+l),f=(c+u+d)*es,p=t-(c-f),m=e-(u-f),y=s-(d-f);let g,v,x,S,b,w;p>=m?m>=y?(g=1,v=0,x=0,S=1,b=1,w=0):p>=y?(g=1,v=0,x=0,S=1,b=0,w=1):(g=0,v=0,x=1,S=1,b=0,w=1):m<y?(g=0,v=0,x=1,S=0,b=1,w=1):p<y?(g=0,v=1,x=0,S=0,b=1,w=1):(g=0,v=1,x=0,S=1,b=1,w=0);const M=p-g+es,z=m-v+es,_=y-x+es,V=p-S+2*es,A=m-b+2*es,T=y-w+2*es,O=p-1+.5,P=m-1+.5,$=y-1+.5,E=255&c,C=255&u,F=255&d;let I=.6-p*p-m*m-y*y;if(I<0)r=0;else{const t=3*i[E+n[C+n[F]]];I*=I,r=I*I*(ns[t]*p+ns[t+1]*m+ns[t+2]*y)}let N=.6-M*M-z*z-_*_;if(N<0)o=0;else{const t=3*i[E+g+n[C+v+n[F+x]]];N*=N,o=N*N*(ns[t]*M+ns[t+1]*z+ns[t+2]*_)}let B=.6-V*V-A*A-T*T;if(B<0)a=0;else{const t=3*i[E+S+n[C+b+n[F+w]]];B*=B,a=B*B*(ns[t]*V+ns[t+1]*A+ns[t+2]*T)}let U=.6-O*O-P*P-$*$;if(U<0)h=0;else{const t=3*i[E+1+n[C+1+n[F+1]]];U*=U,h=U*U*(ns[t]*O+ns[t+1]*P+ns[t+2]*$)}return 32*(r+o+a+h)}noise4D(t,e,s,i){const n=this.perm;let r,o,a,h,l;const c=(t+e+s+i)*ss,u=Math.floor(t+c),d=Math.floor(e+c),f=Math.floor(s+c),p=Math.floor(i+c),m=(u+d+f+p)*is,y=t-(u-m),g=e-(d-m),v=s-(f-m),x=i-(p-m);let S=0,b=0,w=0,M=0;y>g?S++:b++,y>v?S++:w++,y>x?S++:M++,g>v?b++:w++,g>x?b++:M++,v>x?w++:M++;const z=S>=3?1:0,_=b>=3?1:0,V=w>=3?1:0,A=M>=3?1:0,T=S>=2?1:0,O=b>=2?1:0,P=w>=2?1:0,$=M>=2?1:0,E=S>=1?1:0,C=b>=1?1:0,F=w>=1?1:0,I=M>=1?1:0,N=y-z+is,B=g-_+is,U=v-V+is,R=x-A+is,D=y-T+2*is,L=g-O+2*is,k=v-P+2*is,q=x-$+2*is,J=y-E+3*is,W=g-C+3*is,G=v-F+3*is,Q=x-I+3*is,j=y-1+4*is,H=g-1+4*is,Y=v-1+4*is,X=x-1+4*is,Z=255&u,K=255&d,tt=255&f,et=255&p;let st=.6-y*y-g*g-v*v-x*x;if(st<0)r=0;else{const t=n[Z+n[K+n[tt+n[et]]]]%32*4;st*=st,r=st*st*(rs[t]*y+rs[t+1]*g+rs[t+2]*v+rs[t+3]*x)}let it=.6-N*N-B*B-U*U-R*R;if(it<0)o=0;else{const t=n[Z+z+n[K+_+n[tt+V+n[et+A]]]]%32*4;it*=it,o=it*it*(rs[t]*N+rs[t+1]*B+rs[t+2]*U+rs[t+3]*R)}let nt=.6-D*D-L*L-k*k-q*q;if(nt<0)a=0;else{const t=n[Z+T+n[K+O+n[tt+P+n[et+$]]]]%32*4;nt*=nt,a=nt*nt*(rs[t]*D+rs[t+1]*L+rs[t+2]*k+rs[t+3]*q)}let rt=.6-J*J-W*W-G*G-Q*Q;if(rt<0)h=0;else{const t=n[Z+E+n[K+C+n[tt+F+n[et+I]]]]%32*4;rt*=rt,h=rt*rt*(rs[t]*J+rs[t+1]*W+rs[t+2]*G+rs[t+3]*Q)}let ot=.6-j*j-H*H-Y*Y-X*X;if(ot<0)l=0;else{const t=n[Z+1+n[K+1+n[tt+1+n[et+1]]]]%32*4;ot*=ot,l=ot*ot*(rs[t]*j+rs[t+1]*H+rs[t+2]*Y+rs[t+3]*X)}return 27*(r+o+a+h+l)}}const as=100,hs=new Array(as),ls=new et,cs=new tt;function us(t){let e=hs[t];return void 0===e&&(e=new os(t),hs[t]=e),e}class ds{constructor(t,e,s=new Yt(1),i=new Yt(0),n=new Yt(0),r){this.frequency=t,this.power=e,this.positionAmount=s,this.rotationAmount=i,this.scrollSpeed=n,this.remap=r,this.type="Noise",this.duration=0,this.scrollOffset=0,this.scrollMemory=[],this._frequency=NaN,this._power=NaN,this._positionAmount=NaN,this._rotationAmount=NaN,this.scrollSpeed.startGen(this.scrollMemory)}sample(t,e,s){const i=t.noise2D(0,e),n=this.remap;return void 0===n?i:n.genValue(s,.5*(i+1))}initialize(t){const e="number"==typeof t.rotation;let s=t._noiseState;if(void 0===s)return s={lastPos:new et,lastRot:0,lastRotQ:e?null:new tt,generatorX:us(Ne(0,as)),generatorY:us(Ne(0,as)),generatorZ:us(Ne(0,as)),generatorW:us(Ne(0,as))},void(t._noiseState=s);s.lastPos.set(0,0,0),s.lastRot=0,e?s.lastRotQ=null:null===s.lastRotQ?s.lastRotQ=new tt:s.lastRotQ.set(0,0,0,1),s.generatorX=us(Ne(0,as)),s.generatorY=us(Ne(0,as)),s.generatorZ=us(Ne(0,as)),s.generatorW=us(Ne(0,as))}static constantOf(t){return t instanceof Yt?t.value:NaN}rotateByNoise(t,e,s,i,n){const r=e.lastRotQ;t.multiply(r.invert()),ls.set(this.sample(e.generatorX,s,n),this.sample(e.generatorY,s,n),this.sample(e.generatorZ,s,n));const o=ls.length();o>0?(ls.multiplyScalar(1/o),cs.setFromAxisAngle(ls,this.sample(e.generatorW,s,n)*Math.PI*i)):cs.set(0,0,0,1),t.multiply(cs),r.copy(cs)}update(t,e){const s=t._noiseState;if(void 0===s)return;const i=t.memory,n=t.age/t.life,r=this._frequency,o=r==r?r:this.frequency.genValue(i,n),a=this._power,h=a==a?a:this.power.genValue(i,n),l=this._positionAmount,c=l==l?l:this.positionAmount.genValue(i,n),u=this._rotationAmount,d=u==u?u:this.rotationAmount.genValue(i,n),f=t.age*o+this.scrollOffset;if(c>0){const e=h*c;t.position.sub(s.lastPos),ls.set(this.sample(s.generatorX,f,i)*e,this.sample(s.generatorY,f,i)*e,this.sample(s.generatorZ,f,i)*e),t.position.add(ls),s.lastPos.copy(ls)}if(d>0){const e=h*d;if("number"==typeof t.rotation){const n=this.sample(s.generatorW,f,i)*Math.PI*e;t.rotation=t.rotation-s.lastRot+n,s.lastRot=n}else null!==s.lastRotQ&&this.rotateByNoise(t.rotation,s,f,e,i)}}updateAll(t,e,s){const i=e>0?t[0].store:void 0;if(void 0===i){for(let i=0;i<e;i++){const e=t[i];e.age<e.life&&this.update(e,s)}return}const n=i.position,r=i.rotation,o=i.scalars,a=Pe.SCALAR_STRIDE,h=this._frequency,l=this._power,c=this._positionAmount,u=this._rotationAmount;for(let s=0,i=0,d=0;s<e;s++,i+=3,d+=a){const e=o[d],a=o[d+1];if(e>=a)continue;const f=t[s],p=f._noiseState;if(void 0===p)continue;const m=f.memory,y=e/a,g=h==h?h:this.frequency.genValue(m,y),v=l==l?l:this.power.genValue(m,y),x=c==c?c:this.positionAmount.genValue(m,y),S=u==u?u:this.rotationAmount.genValue(m,y),b=e*g+this.scrollOffset;if(x>0){const t=v*x,e=p.lastPos,s=this.sample(p.generatorX,b,m)*t,r=this.sample(p.generatorY,b,m)*t,o=this.sample(p.generatorZ,b,m)*t;n[i]=Math.fround(n[i]-e.x)+s,n[i+1]=Math.fround(n[i+1]-e.y)+r,n[i+2]=Math.fround(n[i+2]-e.z)+o,e.set(s,r,o)}if(S>0){const t=v*S;if("number"==typeof f.rotation){const e=this.sample(p.generatorW,b,m)*Math.PI*t;r[s]=r[s]-p.lastRot+e,p.lastRot=e}else null!==p.lastRotQ&&this.rotateByNoise(f.rotation,p,b,t,m)}}}toJSON(){return{type:this.type,frequency:this.frequency.toJSON(),power:this.power.toJSON(),positionAmount:this.positionAmount.toJSON(),rotationAmount:this.rotationAmount.toJSON(),scrollSpeed:this.scrollSpeed.toJSON(),...void 0!==this.remap?{remap:this.remap.toJSON()}:{}}}frameUpdate(t){this.duration+=t,this.scrollOffset+=this.scrollSpeed.genValue(this.scrollMemory,0)*t,this._frequency=ds.constantOf(this.frequency),this._power=ds.constantOf(this.power),this._positionAmount=ds.constantOf(this.positionAmount),this._rotationAmount=ds.constantOf(this.rotationAmount)}static fromJSON(t){return new ds(ee(t.frequency),ee(t.power),t.positionAmount?ee(t.positionAmount):void 0,t.rotationAmount?ee(t.rotationAmount):void 0,t.scrollSpeed?ee(t.scrollSpeed):new Yt(0),t.remap?ee(t.remap):void 0)}clone(){return new ds(this.frequency.clone(),this.power.clone(),this.positionAmount.clone(),this.rotationAmount.clone(),this.scrollSpeed.clone(),this.remap?.clone())}reset(){this.scrollOffset=0}}class fs{constructor(t,e=new et(0,1,0),s="local"){this.orbitSpeed=t,this.axis=e,this.space=s,this.type="OrbitOverLife",this.temp=new et,this._frame=new be,this._axis=new et(0,1,0),this._center=new et,this.rotation=new tt,this.refreshAxis()}initialize(t,e){this.ps=e,this.orbitSpeed.startGen(t.memory)}refreshAxis(){const t=this._axis.copy(this.axis),e=this._center.set(0,0,0);if(void 0!==this.ps){const s=this.ps.worldSpace;this._frame.toSimulation(t,this.space,s),this._frame.pointToSimulation(e,this.space,s)}const s=t.length();s>0?t.multiplyScalar(1/s):t.set(0,0,0)}converts(){return void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)}update(t,e){const s=this._axis;if(0===s.x&&0===s.y&&0===s.z)return;const i=t.position;i.sub(this._center),this.temp.copy(i).projectOnVector(s),this.rotation.setFromAxisAngle(s,this.orbitSpeed.genValue(t.memory,t.age/t.life)*e),i.sub(this.temp),i.applyQuaternion(this.rotation),i.add(this.temp),i.add(this._center)}updateAll(t,e,s){const i=this._axis;if(0===i.x&&0===i.y&&0===i.z)return;const n=this.orbitSpeed,r=this._center,o=this.temp,a=this.rotation;for(let h=0;h<e;h++){const e=t[h];if(e.age>=e.life)continue;const l=e.position;l.sub(r),o.copy(l).projectOnVector(i),a.setFromAxisAngle(i,n.genValue(e.memory,e.age/e.life)*s),l.sub(o),l.applyQuaternion(a),l.add(o),l.add(r)}}frameUpdate(t){this.converts()&&this._frame.refresh(this.ps),this.refreshAxis()}toJSON(){return{type:this.type,orbitSpeed:this.orbitSpeed.toJSON(),axis:[this.axis.x,this.axis.y,this.axis.z],..."local"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new fs(ee(t.orbitSpeed),t.axis?new et(t.axis[0],t.axis[1],t.axis[2]):void 0,xe(t.space,"local"))}clone(){return new fs(this.orbitSpeed.clone(),this.axis.clone(),this.space)}reset(){}}const ps=new tt;class ms{constructor(t){this.angularVelocity=t,this.type="Rotation3DOverLife",this.tempQuat=new tt}initialize(t){t.rotation instanceof tt&&(t.angularVelocity=t instanceof Ce?ps:new tt,this.angularVelocity.startGen(t.memory))}update(t,e){if(t.rotation instanceof tt){this.angularVelocity.genValue(t.memory,this.tempQuat,e,t.age/t.life),t.rotation.multiply(this.tempQuat);const s=t.angularVelocity;s instanceof tt&&s.copy(this.tempQuat)}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new ms(me(t.angularVelocity))}frameUpdate(t){}clone(){return new ms(this.angularVelocity.clone())}reset(){}}class ys{constructor(t,e){this.angularVelocity=t,this.speedRange=e,this.type="RotationBySpeed",this.tempQuat=new tt}initialize(t){"number"==typeof t.rotation&&this.angularVelocity.startGen(t.memory)}update(t,e){if("number"==typeof t.rotation){const s=Ae(t,this.speedRange),i=this.angularVelocity.genValue(t.memory,s);t.rotation+=e*i,t.angularVelocity=i}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new ys(ee(t.angularVelocity),t.speedRange?Xt.fromJSON(t.speedRange):new Xt(0,1))}frameUpdate(t){}clone(){return new ys(this.angularVelocity.clone(),this.speedRange.clone())}reset(){}}class gs{constructor(t){this.angularVelocity=t,this.type="RotationOverLife",this.tempQuat=new tt}initialize(t){"number"==typeof t.rotation?this.angularVelocity.startGen(t.memory):t.rotation instanceof tt&&(this.angularVelocity.startGen(t.memory),t.angularVelocity instanceof tt||(t.angularVelocity=new tt))}update(t,e){if("number"==typeof t.rotation){const s=this.angularVelocity.genValue(t.memory,t.age/t.life);t.rotation+=e*s,t.angularVelocity=s}else if(t.rotation instanceof tt){const s=this.angularVelocity.genValue(t.memory,t.age/t.life);this.turnAboutZ(t,t.rotation,s*e)}}updateAll(t,e,s){const i=this.angularVelocity;for(let n=0;n<e;n++){const e=t[n];if(e.age>=e.life)continue;const r=e.rotation;if("number"==typeof r){const t=i.genValue(e.memory,e.age/e.life);e.rotation=r+s*t,e.angularVelocity=t}else if(r instanceof tt){const t=i.genValue(e.memory,e.age/e.life);this.turnAboutZ(e,r,t*s)}}}turnAboutZ(t,e,s){const i=this.tempQuat.setFromAxisAngle(Le,s);e.multiply(i);const n=t.angularVelocity;n instanceof tt&&n.copy(i)}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new gs(ee(t.angularVelocity))}frameUpdate(t){this.angularVelocity.refreshTable?.()}clone(){return new gs(this.angularVelocity.clone())}reset(){}}class vs{initialize(t){this.size.startGen(t.memory)}constructor(t,e){this.size=t,this.speedRange=e,this.type="SizeBySpeed"}update(t){const e=Ae(t,this.speedRange);this.size instanceof ye?this.size.genValue(t.memory,t.size,e).multiply(t.startSize):t.size.copy(t.startSize).multiplyScalar(this.size.genValue(t.memory,e))}toJSON(){return{type:this.type,size:this.size.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new vs(ve(t.size),t.speedRange?Xt.fromJSON(t.speedRange):new Xt(0,1))}frameUpdate(t){}clone(){return new vs(this.size.clone(),this.speedRange.clone())}reset(){}}class xs{constructor(t){this.type="SizeOverLife",this._sizeIsVector3=!1,this.size=t}get size(){return this._size}set size(t){this._size=t,this._sizeIsVector3=t instanceof ye}initialize(t){this._size.startGen(t.memory)}update(t){const e=t.age/t.life;if(this._sizeIsVector3)this._size.genValue(t.memory,t.size,e).multiply(t.startSize);else{const s=this._size.genValue(t.memory,e),i=t.size,n=t.startSize;i.x=n.x*s,i.y=n.y*s,i.z=n.z*s}}updateAll(t,e,s){if(this._sizeIsVector3){const s=this._size;for(let i=0;i<e;i++){const e=t[i];e.age>=e.life||s.genValue(e.memory,e.size,e.age/e.life).multiply(e.startSize)}return}const i=this._size;for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const n=i.genValue(e.memory,e.age/e.life),r=e.size,o=e.startSize;r.x=o.x*n,r.y=o.y*n,r.z=o.z*n}}toJSON(){return{type:this.type,size:this.size.toJSON()}}static fromJSON(t){return new xs(ve(t.size))}frameUpdate(t){this._size.refreshTable?.()}clone(){return new xs(this.size.clone())}reset(){}}class Ss{initialize(t){this.speed.startGen(t.memory)}constructor(t){this.speed=t,this.type="SpeedOverLife"}update(t){t.speedModifier=this.speed.genValue(t.memory,t.age/t.life)}updateAll(t,e,s){const i=this.speed;for(let s=0;s<e;s++){const e=t[s];e.age>=e.life||(e.speedModifier=i.genValue(e.memory,e.age/e.life))}}toJSON(){return{type:this.type,speed:this.speed.toJSON()}}static fromJSON(t){return new Ss(ee(t.speed))}frameUpdate(t){this.speed.refreshTable?.()}clone(){return new Ss(this.speed.clone())}reset(){}}function bs(t){return 0===t?0:1/t}class ws{constructor(t,e,s,i,n=0){this.scale=t,this.octaves=e,this.velocityMultiplier=s,this.timeScale=i,this.seed=n,this.type="TurbulenceField",this.timeOffset=new et,this.initialOffset=new et,this.temp=new et,this.temp2=new et;const r=V(n);this.generator=new os(r),this.initialOffset.set(r()*bs(t.x)*i.x,r()*bs(t.y)*i.y,r()*bs(t.z)*i.z),this.timeOffset.copy(this.initialOffset)}initialize(t){}update(t,e){const s=t.position.x*bs(this.scale.x),i=t.position.y*bs(this.scale.y),n=t.position.z*bs(this.scale.z);this.temp.set(0,0,0);let r=1;for(let t=0;t<this.octaves;t++)this.temp2.set(this.generator.noise4D(s*r,i*r,n*r,this.timeOffset.x*r)/r,this.generator.noise4D(s*r,i*r,n*r,this.timeOffset.y*r)/r,this.generator.noise4D(s*r,i*r,n*r,this.timeOffset.z*r)/r),this.temp.add(this.temp2),r*=2;this.temp.multiply(this.velocityMultiplier),t.velocity.addScaledVector(this.temp,e)}updateAll(t,e,s){const i=e>0?t[0].store:void 0;if(void 0===i){for(let i=0;i<e;i++){const e=t[i];e.age<e.life&&this.update(e,s)}return}const n=i.position,r=i.velocity,o=i.scalars,a=Pe.SCALAR_STRIDE,h=this.generator,l=this.octaves,c=bs(this.scale.x),u=bs(this.scale.y),d=bs(this.scale.z),f=this.velocityMultiplier.x*s,p=this.velocityMultiplier.y*s,m=this.velocityMultiplier.z*s,y=this.timeOffset.x,g=this.timeOffset.y,v=this.timeOffset.z;for(let t=0,s=0,i=0;t<e;t++,s+=3,i+=a){if(o[i]>=o[i+1])continue;const t=n[s]*c,e=n[s+1]*u,a=n[s+2]*d;let x=0,S=0,b=0,w=1;for(let s=0;s<l;s++){const s=t*w,i=e*w,n=a*w;x+=h.noise4D(s,i,n,y*w)/w,S+=h.noise4D(s,i,n,g*w)/w,b+=h.noise4D(s,i,n,v*w)/w,w*=2}r[s]+=x*f,r[s+1]+=S*p,r[s+2]+=b*m}}toJSON(){return{type:this.type,scale:[this.scale.x,this.scale.y,this.scale.z],octaves:this.octaves,velocityMultiplier:[this.velocityMultiplier.x,this.velocityMultiplier.y,this.velocityMultiplier.z],timeScale:[this.timeScale.x,this.timeScale.y,this.timeScale.z],...0!==this.seed?{seed:this.seed}:{}}}frameUpdate(t){this.timeOffset.x+=t*this.timeScale.x,this.timeOffset.y+=t*this.timeScale.y,this.timeOffset.z+=t*this.timeScale.z}static fromJSON(t){return new ws(Gt(t.scale,new et(1,1,1)),"number"==typeof t.octaves?t.octaves:1,Gt(t.velocityMultiplier,new et(1,1,1)),Gt(t.timeScale,new et(1,1,1)),"number"==typeof t.seed?t.seed:0)}clone(){return new ws(this.scale.clone(),this.octaves,this.velocityMultiplier.clone(),this.timeScale.clone(),this.seed)}reset(){this.timeOffset.copy(this.initialOffset)}}const Ms=new et(1,0,0),zs=new et(0,1,0),_s=new et(0,0,1);class Vs{constructor(t=new Yt(0),e=new Yt(0),s=new Yt(0),i=new Yt(0),n=new Yt(0),r=new Yt(0),o="local",a=new Yt(0),h=new et){this.linearX=t,this.linearY=e,this.linearZ=s,this.orbitalX=i,this.orbitalY=n,this.orbitalZ=r,this.space=o,this.radial=a,this.orbitalOffset=h,this.type="VelocityOverLife",this._temp=new et,this._tempEmitterPos=new et,this._tempQ=new tt,this._tempQInv=new tt,this._tempScale=new et(1,1,1),this._tempScaleInv=new et(1,1,1),this._tempRot=new tt,this._axisX=new et(1,0,0),this._axisY=new et(0,1,0),this._axisZ=new et(0,0,1),this._center=new et}initialize(t,e){this.ps=e,this.linearX.startGen(t.memory),this.linearY.startGen(t.memory),this.linearZ.startGen(t.memory),this.orbitalX.startGen(t.memory),this.orbitalY.startGen(t.memory),this.orbitalZ.startGen(t.memory),this.radial.startGen(t.memory)}frameUpdate(t){this.ps&&(this.ps.emitter.matrixWorld.decompose(this._tempEmitterPos,this._tempQ,this._tempScale),this._tempQInv.copy(this._tempQ).invert(),this._tempScaleInv.set(1/this._tempScale.x,1/this._tempScale.y,1/this._tempScale.z),this._axisX.copy(Ms),this._axisY.copy(zs),this._axisZ.copy(_s),this._center.copy(this.orbitalOffset),this.ps.worldSpace&&(this._axisX.applyQuaternion(this._tempQ),this._axisY.applyQuaternion(this._tempQ),this._axisZ.applyQuaternion(this._tempQ),this._center.multiply(this._tempScale).applyQuaternion(this._tempQ).add(this._tempEmitterPos)))}update(t,e){const s=t.age/t.life;this._temp.set(this.linearX.genValue(t.memory,s),this.linearY.genValue(t.memory,s),this.linearZ.genValue(t.memory,s));const i=void 0!==this.ps&&this.ps.worldSpace;i&&"local"===this.space?this._temp.multiply(this._tempScale).applyQuaternion(this._tempQ):i||"world"!==this.space||this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv),t.position.addScaledVector(this._temp,e);const n=this.radial.genValue(t.memory,s);if(0!==n){this._temp.copy(t.position).sub(this._center);const s=this._temp.length();s>0&&t.position.addScaledVector(this._temp,n*e/s)}const r=this.orbitalX.genValue(t.memory,s)*e,o=this.orbitalY.genValue(t.memory,s)*e,a=this.orbitalZ.genValue(t.memory,s)*e;0===r&&0===o&&0===a||(t.position.sub(this._center),this.orbit(t.position,this._axisX,r),this.orbit(t.position,this._axisY,o),this.orbit(t.position,this._axisZ,a),t.position.add(this._center))}orbit(t,e,s){0!==s&&(this._tempRot.setFromAxisAngle(e,s),t.applyQuaternion(this._tempRot))}toJSON(){return{type:this.type,linearX:this.linearX.toJSON(),linearY:this.linearY.toJSON(),linearZ:this.linearZ.toJSON(),orbitalX:this.orbitalX.toJSON(),orbitalY:this.orbitalY.toJSON(),orbitalZ:this.orbitalZ.toJSON(),space:this.space,radial:this.radial.toJSON(),orbitalOffset:[this.orbitalOffset.x,this.orbitalOffset.y,this.orbitalOffset.z]}}static fromJSON(t){const e=t=>t?ee(t):new Yt(0);return new Vs(e(t.linearX),e(t.linearY),e(t.linearZ),e(t.orbitalX),e(t.orbitalY),e(t.orbitalZ),"world"===t.space?"world":"local",e(t.radial),Array.isArray(t.orbitalOffset)?new et(t.orbitalOffset[0]??0,t.orbitalOffset[1]??0,t.orbitalOffset[2]??0):new et)}clone(){return new Vs(this.linearX.clone(),this.linearY.clone(),this.linearZ.clone(),this.orbitalX.clone(),this.orbitalY.clone(),this.orbitalZ.clone(),this.space,this.radial.clone(),this.orbitalOffset.clone())}reset(){}}class As{initialize(t){this.width.startGen(t.memory)}constructor(t,e=!1){this.width=t,this.absolute=e,this.type="WidthOverLength"}update(t){if(!(t instanceof Ie))return;const e=t.memory;t.headWidthScale=this.absolute?1:this.width.genValue(e,0);const s=t.historyCount;if(0===s)return;const i=t.historyCapacity,n=t.historySizes,r=t.historyBaseSizes,o=1/s,a=this.absolute;let h=t.getHistoryIndex(0);for(let t=0;t<s;t++){const l=this.width.genValue(e,(s-t)*o);n[h]=a?l:r[h]*l,h++,h===i&&(h=0)}}frameUpdate(t){}toJSON(){return{type:this.type,width:this.width.toJSON(),absolute:this.absolute}}static fromJSON(t){return new As(ee(t.width),t.absolute??!0)}clone(){return new As(this.width.clone(),this.absolute)}reset(){}}const Ts={ApplyForce:{type:"ApplyForce",constructor:we,params:[["direction",["vec3"]],["magnitude",["value"]],["space",["string"]]],loadJSON:we.fromJSON},Noise:{type:"Noise",constructor:ds,params:[["frequency",["value"]],["power",["value"]],["positionAmount",["value"]],["rotationAmount",["value"]],["scrollSpeed",["value"]],["remap",["valueFunc"]]],loadJSON:ds.fromJSON},TurbulenceField:{type:"TurbulenceField",constructor:ws,params:[["scale",["vec3"]],["octaves",["number"]],["velocityMultiplier",["vec3"]],["timeScale",["vec3"]],["seed",["number"]]],loadJSON:ws.fromJSON},GravityForce:{type:"GravityForce",constructor:He,params:[["center",["vec3"]],["magnitude",["number"]]],loadJSON:He.fromJSON},ColorOverLife:{type:"ColorOverLife",constructor:Oe,params:[["color",["colorFunc"]]],loadJSON:Oe.fromJSON},RotationOverLife:{type:"RotationOverLife",constructor:gs,params:[["angularVelocity",["value","valueFunc"]]],loadJSON:gs.fromJSON},Rotation3DOverLife:{type:"Rotation3DOverLife",constructor:ms,params:[["angularVelocity",["rotationFunc"]]],loadJSON:ms.fromJSON},SizeOverLife:{type:"SizeOverLife",constructor:xs,params:[["size",["value","valueFunc","vec3Func"]]],loadJSON:xs.fromJSON},ColorBySpeed:{type:"ColorBySpeed",constructor:Te,params:[["color",["colorFunc"]],["speedRange",["range"]]],loadJSON:Te.fromJSON},RotationBySpeed:{type:"RotationBySpeed",constructor:ys,params:[["angularVelocity",["value","valueFunc"]],["speedRange",["range"]]],loadJSON:ys.fromJSON},SizeBySpeed:{type:"SizeBySpeed",constructor:vs,params:[["size",["value","valueFunc","vec3Func"]],["speedRange",["range"]]],loadJSON:vs.fromJSON},SpeedOverLife:{type:"SpeedOverLife",constructor:Ss,params:[["speed",["value","valueFunc"]]],loadJSON:Ss.fromJSON},FrameOverLife:{type:"FrameOverLife",constructor:je,params:[["frame",["value","valueFunc"]],["fps",["number"]],["cycles",["number"]],["frameCount",["number"]],["loop",["boolean"]],["random",["boolean"]],["startFrame",["value"]]],loadJSON:je.fromJSON},ForceOverLife:{type:"ForceOverLife",constructor:Qe,params:[["x",["value","valueFunc"]],["y",["value","valueFunc"]],["z",["value","valueFunc"]],["space",["string"]]],loadJSON:Qe.fromJSON},VelocityOverLife:{type:"VelocityOverLife",constructor:Vs,params:[["linearX",["value","valueFunc"]],["linearY",["value","valueFunc"]],["linearZ",["value","valueFunc"]],["orbitalX",["value","valueFunc"]],["orbitalY",["value","valueFunc"]],["orbitalZ",["value","valueFunc"]],["space",["string"]],["radial",["value","valueFunc"]],["orbitalOffset",["vec3"]]],loadJSON:Vs.fromJSON},InheritVelocity:{type:"InheritVelocity",constructor:Ye,params:[["multiplier",["value","valueFunc"]],["mode",["string"]]],loadJSON:Ye.fromJSON},OrbitOverLife:{type:"OrbitOverLife",constructor:fs,params:[["orbitSpeed",["value","valueFunc"]],["axis",["vec3"]],["space",["string"]]],loadJSON:fs.fromJSON},WidthOverLength:{type:"WidthOverLength",constructor:As,params:[["width",["value","valueFunc"]],["absolute",["boolean"]]],loadJSON:As.fromJSON},ChangeEmitDirection:{type:"ChangeEmitDirection",constructor:Ve,params:[["angle",["value"]]],loadJSON:Ve.fromJSON},ApplySequences:{type:"ApplySequences",constructor:_e,params:[["delay",["number"]]],loadJSON:_e.fromJSON},EmitSubParticleSystem:{type:"EmitSubParticleSystem",constructor:Ge,params:[["particleSystem",["self"]],["useVelocityAsBasis",["boolean"]],["subParticleSystem",["particleSystem"]],["mode",["number"]],["emitProbability",["number"]],["inherit",["subEmitterInherit"]]],loadJSON:Ge.fromJSON},LimitSpeedOverLife:{type:"LimitSpeedOverLife",constructor:Xe,params:[["speed",["value","valueFunc"]],["dampen",["number"]]],loadJSON:Xe.fromJSON},ApplyCollision:{type:"ApplyCollision",constructor:$t,params:[["bounce",["number"]]],loadJSON:$t.fromJSON}};function Os(t,e){const s=t?Ts[t.type]:void 0;return s?s.loadJSON(t,e):(Wt(`${Qt("behavior",t)}; it is skipped.`),null)}function Ps(t,e){const s=t.toJSON(),i=Ts[s?.type];return i?Ht(s,t=>i.loadJSON(t,e).toJSON()):s}const $s={PiecewiseBezier:te,Vector3Function:ye,Quaternion:tt,ConstantValue:Yt,Gradient:ae,Vector4View:Tt,AxisAngleGenerator:ie,IntervalValue:Xt,ColorRange:ne};function Es(t,e){return`const ${t} = ${e};\n const ${t}_tbl = ${t} instanceof deps.PiecewiseBezier ? ${t}.sampledTable() : null;\n const ${t}_last = ${t}_tbl !== null ? ${t}_tbl.length - 1 : 0;\n const ${t}_const = ${t} instanceof deps.ConstantValue;\n const ${t}_cv = ${t}_const ? ${t}.value : 0;\n const ${t}_iv = ${t} instanceof deps.IntervalValue;\n const ${t}_slot = ${t}_iv ? ${t}.indexCount : -1;\n const ${t}_col = ${t}_slot >= 0 && ${t}_slot < ms;\n const ${t}_a = ${t}_iv ? ${t}.a : 0, ${t}_b = ${t}_iv ? ${t}.b : 0;`}function Cs(t){return`const vx = vel[o3], vy = vel[o3 + 1], vz = vel[o3 + 2];\n const speed = Math.sqrt(vx * vx + vy * vy + vz * vz) * scalars[s + 2];\n let ts = span${t} === 0 ? (speed >= lo${t} ? 1 : 0) : (speed - lo${t}) / span${t};\n ts = ts < 0 ? 0 : ts > 1 ? 1 : ts;`}function Fs(t,e,s){return`let ${e};\n if (${t}_tbl !== null) {\n const tt = ${s};\n if (tt <= 0) ${e} = ${t}_tbl[0];\n else if (tt >= 1) ${e} = ${t}_tbl[${t}_last];\n else {\n const x = tt * ${t}_last;\n const ix = x | 0;\n const v0 = ${t}_tbl[ix];\n ${e} = v0 + (${t}_tbl[ix + 1] - v0) * (x - ix);\n }\n } else if (${t}_const) ${e} = ${t}_cv;\n else if (${t}_iv) {\n // The particle's own sample, from the memory column when it holds it.\n let r = ${t}_col ? mem[row * ms + ${t}_slot] : NaN;\n if (r !== r) r = p.memory[${t}_slot];\n ${e} = (1 - r) * ${t}_a + r * ${t}_b;\n } else ${e} = ${t}.genValue(p.memory, ${s});`}function Is(t,e){return`const ${t} = ${e};\n const ${t}_tbl = ${t} instanceof deps.Gradient ? ${t}.sampledTable() : null;\n const ${t}_last = ${t}_tbl !== null ? ${t}_tbl.length / 4 - 1 : 0;\n const ${t}_cr = ${t} instanceof deps.ColorRange;\n const ${t}_slot = ${t}_cr ? ${t}.indexCount : -1;\n const ${t}_col = ${t}_slot >= 0 && ${t}_slot < ms;\n // Rounded to float32 as copying the colour into the particle does.\n const ${t}_ax = ${t}_cr ? Math.fround(${t}.a.x) : 0, ${t}_ay = ${t}_cr ? Math.fround(${t}.a.y) : 0;\n const ${t}_az = ${t}_cr ? Math.fround(${t}.a.z) : 0, ${t}_aw = ${t}_cr ? Math.fround(${t}.a.w) : 0;\n const ${t}_bx = ${t}_cr ? ${t}.b.x : 0, ${t}_by = ${t}_cr ? ${t}.b.y : 0;\n const ${t}_bz = ${t}_cr ? ${t}.b.z : 0, ${t}_bw = ${t}_cr ? ${t}.b.w : 0;`}function Ns(t,e){return`if (${t}_tbl !== null) {\n const tt = ${e};\n const tbl = ${t}_tbl;\n let r, g, b, a;\n if (tt <= 0) {\n r = tbl[0]; g = tbl[1]; b = tbl[2]; a = tbl[3];\n } else if (tt >= 1) {\n const o = ${t}_last * 4;\n r = tbl[o]; g = tbl[o + 1]; b = tbl[o + 2]; a = tbl[o + 3];\n } else {\n const x = tt * ${t}_last;\n const ix = x | 0;\n const fr = x - ix;\n const o = ix * 4;\n const nx = o + 4;\n r = tbl[o] + (tbl[nx] - tbl[o]) * fr;\n g = tbl[o + 1] + (tbl[nx + 1] - tbl[o + 1]) * fr;\n b = tbl[o + 2] + (tbl[nx + 2] - tbl[o + 2]) * fr;\n a = tbl[o + 3] + (tbl[nx + 3] - tbl[o + 3]) * fr;\n }\n color[o4] = Math.fround(r) * startColor[o4];\n color[o4 + 1] = Math.fround(g) * startColor[o4 + 1];\n color[o4 + 2] = Math.fround(b) * startColor[o4 + 2];\n color[o4 + 3] = Math.fround(a) * startColor[o4 + 3];\n } else if (${t}_cr) {\n let r = ${t}_col ? mem[row * ms + ${t}_slot] : NaN;\n if (r !== r) r = p.memory[${t}_slot];\n color[o4] = Math.fround(${t}_ax + (${t}_bx - ${t}_ax) * r) * startColor[o4];\n color[o4 + 1] = Math.fround(${t}_ay + (${t}_by - ${t}_ay) * r) * startColor[o4 + 1];\n color[o4 + 2] = Math.fround(${t}_az + (${t}_bz - ${t}_az) * r) * startColor[o4 + 2];\n color[o4 + 3] = Math.fround(${t}_aw + (${t}_bw - ${t}_aw) * r) * startColor[o4 + 3];\n } else {\n ${t}.genColor(p.memory, tmpColor, ${e});\n color[o4] = tmpColor.x * startColor[o4];\n color[o4 + 1] = tmpColor.y * startColor[o4 + 1];\n color[o4 + 2] = tmpColor.z * startColor[o4 + 2];\n color[o4 + 3] = tmpColor.w * startColor[o4 + 3];\n }`}function Bs(t,e,s,i,n,r,o){return`{\n const cx = 2 * (${n} * ${s} - ${r} * ${e});\n const cy = 2 * (${r} * ${t} - ${i} * ${s});\n const cz = 2 * (${i} * ${e} - ${n} * ${t});\n const nx = ${t} + ${o} * cx + ${n} * cz - ${r} * cy;\n const ny = ${e} + ${o} * cy + ${r} * cx - ${i} * cz;\n ${s} = ${s} + ${o} * cz + ${i} * cy - ${n} * cx;\n ${t} = nx;\n ${e} = ny;\n }`}function Us(t,e){return`const ${t}_q = ${e};\n const ${t}x = ${t}_q.x, ${t}y = ${t}_q.y, ${t}z = ${t}_q.z, ${t}w = ${t}_q.w;`}function Rs(t,e){return`const ${t}_v = ${e};\n const ${t}x = ${t}_v.x, ${t}y = ${t}_v.y, ${t}z = ${t}_v.z;`}function Ds(t,e,s,i){return`{\n const half = ${t} / 2;\n const sn = Math.sin(half);\n const qx = ${e} * sn, qy = ${s} * sn, qz = ${i} * sn, qw = Math.cos(half);\n ${Bs("px","py","pz","qx","qy","qz","qw")}\n px = Math.fround(px); py = Math.fround(py); pz = Math.fround(pz);\n }`}function Ls(t,e){switch(t.type){case"ColorOverLife":return{setup:Is(`g${e}`,`behaviors[${e}].color`),body:`{${Ns(`g${e}`,"t")}}`};case"SizeOverLife":return{setup:`const g${e} = behaviors[${e}].size;\n const vec3_${e} = g${e} instanceof deps.Vector3Function;\n ${Es(`sg${e}`,`g${e}`)}`,body:`if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, t).multiply(p.startSize);\n } else {\n ${Fs(`sg${e}`,"v","t")}\n size[o3] = startSize[o3] * v;\n size[o3 + 1] = startSize[o3 + 1] * v;\n size[o3 + 2] = startSize[o3 + 2] * v;\n }`};case"ApplyForce":return{setup:`const b${e} = behaviors[${e}];\n const d${e} = b${e}._direction;\n const dx${e} = d${e}.x, dy${e} = d${e}.y, dz${e} = d${e}.z;\n const step${e} = b${e}._step(delta);\n ${Es(`g${e}`,`b${e}.magnitude`)}`,body:`{\n ${Fs(`g${e}`,"m","t")}\n const s = m * step${e};\n vel[o3] += dx${e} * s; vel[o3 + 1] += dy${e} * s; vel[o3 + 2] += dz${e} * s;\n }`};case"RotationOverLife":return{setup:`${Es(`g${e}`,`behaviors[${e}].angularVelocity`)}\n const rotation_${e} = count > 0 ? particles[0].rotation : undefined;\n const angle_${e} = typeof rotation_${e} === 'number';\n const rq${e} = store.rotationQuaternion, aq${e} = store.angularVelocityQuaternion;\n const quat_${e} = !angle_${e} && rq${e}.length > 0 && rotation_${e} instanceof deps.Quaternion;`,body:`if (angle_${e}) {\n ${Fs(`g${e}`,"rate","t")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n } else if (quat_${e}) {\n ${Fs(`g${e}`,"rate","t")}\n const half = (rate * delta) / 2;\n const qz = Math.sin(half), qw = Math.cos(half);\n const ax = rq${e}[o4], ay = rq${e}[o4 + 1], az = rq${e}[o4 + 2], aw = rq${e}[o4 + 3];\n rq${e}[o4] = ax * qw + ay * qz;\n rq${e}[o4 + 1] = ay * qw - ax * qz;\n rq${e}[o4 + 2] = az * qw + aw * qz;\n rq${e}[o4 + 3] = aw * qw - az * qz;\n aq${e}[o4] = 0; aq${e}[o4 + 1] = 0; aq${e}[o4 + 2] = qz; aq${e}[o4 + 3] = qw;\n }`};case"FrameOverLife":return{setup:`${Es(`g${e}`,`behaviors[${e}].frame`)}\n const b${e} = behaviors[${e}];\n const plain${e} = typeof b${e}.isPlain !== 'function' || b${e}.isPlain();`,body:`if (plain${e}) {${Fs(`g${e}`,"v","t")} uvTile[row] = v;}\n else uvTile[row] = b${e}.frameAt(p, age, t);`};case"SpeedOverLife":return{setup:Es(`g${e}`,`behaviors[${e}].speed`),body:`{${Fs(`g${e}`,"v","t")} scalars[s + 2] = v;}`};case"ForceOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Es(`gx${e}`,`b${e}.x`)}\n ${Es(`gy${e}`,`b${e}.y`)}\n ${Es(`gz${e}`,`b${e}.z`)}\n const world${e} = b${e}.ps === undefined || b${e}.ps.worldSpace;\n const toWorld${e} = world${e} && b${e}.space === 'local';\n const toLocal${e} = !world${e} && b${e}.space === 'world';\n const step${e} = b${e}._step(delta);\n const fr${e} = b${e}._frame;\n ${Rs(`sc${e}`,`toWorld${e} ? fr${e}.scale : fr${e}.scaleInverse`)}\n ${Us(`q${e}`,`toWorld${e} ? fr${e}.quaternion : fr${e}.quaternionInverse`)}`,body:`{\n ${Fs(`gx${e}`,"fx","t")}\n ${Fs(`gy${e}`,"fy","t")}\n ${Fs(`gz${e}`,"fz","t")}\n if (toWorld${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${Bs("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n } else if (toLocal${e}) {\n ${Bs("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n }\n vel[o3] += fx * step${e}; vel[o3 + 1] += fy * step${e}; vel[o3 + 2] += fz * step${e};}`};case"LimitSpeedOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Es(`g${e}`,`b${e}.speed`)}\n const dampen${e} = b${e}.dampenStep(delta);\n const ms${e} = typeof b${e}.motionScale === 'function' ? b${e}.motionScale() : 1;`,body:`{const vx = vel[o3], vy = vel[o3 + 1], vz = vel[o3 + 2];\n const speed = Math.sqrt(vx * vx + vy * vy + vz * vz);\n ${Fs(`g${e}`,"limitBase","t")}\n const limit = limitBase * ms${e};\n if (speed > limit) {\n const f = 1 - ((speed - limit) / speed) * dampen${e};\n vel[o3] = vx * f; vel[o3 + 1] = vy * f; vel[o3 + 2] = vz * f;\n }}`};case"GravityForce":return{setup:`const b${e} = behaviors[${e}];\n const cx${e} = b${e}.center.x, cy${e} = b${e}.center.y, cz${e} = b${e}.center.z;\n const gm${e} = b${e}.magnitude * delta;`,body:`{const dx = cx${e} - pos[o3], dy = cy${e} - pos[o3 + 1], dz = cz${e} - pos[o3 + 2];\n const d2 = dx * dx + dy * dy + dz * dz;\n if (d2 > 0) {\n const f = gm${e} / (d2 * Math.sqrt(d2));\n vel[o3] += dx * f; vel[o3 + 1] += dy * f; vel[o3 + 2] += dz * f;\n }}`};case"ColorBySpeed":return{setup:`const b${e} = behaviors[${e}];\n ${Is(`g${e}`,`b${e}.color`)}\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};`,body:`{${Cs(e)}\n ${Ns(`g${e}`,"ts")}}`};case"SizeBySpeed":return{setup:`const b${e} = behaviors[${e}];\n const g${e} = b${e}.size;\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};\n const vec3_${e} = g${e} instanceof deps.Vector3Function;\n ${Es(`sg${e}`,`g${e}`)}`,body:`{${Cs(e)}\n if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, ts).multiply(p.startSize);\n } else {\n ${Fs(`sg${e}`,"v","ts")}\n size[o3] = startSize[o3] * v;\n size[o3 + 1] = startSize[o3 + 1] * v;\n size[o3 + 2] = startSize[o3 + 2] * v;\n }}`};case"RotationBySpeed":return{setup:`const b${e} = behaviors[${e}];\n ${Es(`g${e}`,`b${e}.angularVelocity`)}\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};\n const angle_${e} = count > 0 && typeof particles[0].rotation === 'number';`,body:`if (angle_${e}) {\n ${Cs(e)}\n ${Fs(`g${e}`,"rate","ts")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n }`};case"OrbitOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Es(`g${e}`,`b${e}.orbitSpeed`)}\n ${Rs(`ax${e}`,`b${e}._axis`)}\n ${Rs(`c${e}`,`b${e}._center`)}\n const alen${e} = ax${e}x * ax${e}x + ax${e}y * ax${e}y + ax${e}z * ax${e}z;\n const orbit${e} = alen${e} !== 0;\n const chalf${e} = (g${e}_cv * delta) / 2;\n const csn${e} = Math.sin(chalf${e});\n const cqx${e} = ax${e}x * csn${e}, cqy${e} = ax${e}y * csn${e}, cqz${e} = ax${e}z * csn${e};\n const cqw${e} = Math.cos(chalf${e});`,body:`if (orbit${e}) {\n let px = Math.fround(pos[o3] - c${e}x), py = Math.fround(pos[o3 + 1] - c${e}y), pz = Math.fround(pos[o3 + 2] - c${e}z);\n // Divided by the squared length as projectOnVector does, so the bits match.\n const f = (ax${e}x * px + ax${e}y * py + ax${e}z * pz) / alen${e};\n const tx = ax${e}x * f, ty = ax${e}y * f, tz = ax${e}z * f;\n let qx, qy, qz, qw;\n if (g${e}_const) {\n qx = cqx${e}; qy = cqy${e}; qz = cqz${e}; qw = cqw${e};\n } else {\n ${Fs(`g${e}`,"sp","t")}\n const half = (sp * delta) / 2;\n const sn = Math.sin(half);\n qx = ax${e}x * sn; qy = ax${e}y * sn; qz = ax${e}z * sn; qw = Math.cos(half);\n }\n px = Math.fround(px - tx); py = Math.fround(py - ty); pz = Math.fround(pz - tz);\n ${Bs("px","py","pz","qx","qy","qz","qw")}\n px = Math.fround(Math.fround(px) + tx); py = Math.fround(Math.fround(py) + ty); pz = Math.fround(Math.fround(pz) + tz);\n pos[o3] = px + c${e}x;\n pos[o3 + 1] = py + c${e}y;\n pos[o3 + 2] = pz + c${e}z;}`};case"Rotation3DOverLife":return{setup:`const b${e} = behaviors[${e}];\n const g${e} = b${e}.angularVelocity;\n const q${e} = b${e}.tempQuat;\n const rq${e} = store.rotationQuaternion, aq${e} = store.angularVelocityQuaternion;\n const quat_${e} = rq${e}.length > 0 && count > 0 && particles[0].rotation instanceof deps.Quaternion;\n const fixed_${e} = g${e} instanceof deps.AxisAngleGenerator && g${e}.angle instanceof deps.ConstantValue;\n let cqx${e} = 0, cqy${e} = 0, cqz${e} = 0, cqw${e} = 1;\n if (fixed_${e}) {\n g${e}.genValue(undefined, q${e}, delta, 0);\n cqx${e} = q${e}.x; cqy${e} = q${e}.y; cqz${e} = q${e}.z; cqw${e} = q${e}.w;\n }`,body:`if (quat_${e}) {\n let qx, qy, qz, qw;\n if (fixed_${e}) {\n qx = cqx${e}; qy = cqy${e}; qz = cqz${e}; qw = cqw${e};\n } else {\n g${e}.genValue(p.memory, q${e}, delta, t);\n qx = q${e}.x; qy = q${e}.y; qz = q${e}.z; qw = q${e}.w;\n }\n const ax = rq${e}[o4], ay = rq${e}[o4 + 1], az = rq${e}[o4 + 2], aw = rq${e}[o4 + 3];\n rq${e}[o4] = ax * qw + aw * qx + ay * qz - az * qy;\n rq${e}[o4 + 1] = ay * qw + aw * qy + az * qx - ax * qz;\n rq${e}[o4 + 2] = az * qw + aw * qz + ax * qy - ay * qx;\n rq${e}[o4 + 3] = aw * qw - ax * qx - ay * qy - az * qz;\n aq${e}[o4] = qx; aq${e}[o4 + 1] = qy; aq${e}[o4 + 2] = qz; aq${e}[o4 + 3] = qw;\n }`};case"VelocityOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Es(`lx${e}`,`b${e}.linearX`)}\n ${Es(`ly${e}`,`b${e}.linearY`)}\n ${Es(`lz${e}`,`b${e}.linearZ`)}\n ${Es(`ox${e}`,`b${e}.orbitalX`)}\n ${Es(`oy${e}`,`b${e}.orbitalY`)}\n ${Es(`oz${e}`,`b${e}.orbitalZ`)}\n ${Rs(`aX${e}`,`b${e}._axisX`)}\n ${Rs(`aY${e}`,`b${e}._axisY`)}\n ${Rs(`aZ${e}`,`b${e}._axisZ`)}\n ${Es(`rd${e}`,`b${e}.radial`)}\n ${Rs(`ce${e}`,`b${e}._center`)}\n const world${e} = b${e}.ps !== undefined && b${e}.ps.worldSpace;\n const toWorld${e} = world${e} && b${e}.space === 'local';\n const convert${e} = toWorld${e} || (!world${e} && b${e}.space === 'world');\n ${Rs(`sc${e}`,`toWorld${e} ? b${e}._tempScale : b${e}._tempScaleInv`)}\n ${Us(`q${e}`,`toWorld${e} ? b${e}._tempQ : b${e}._tempQInv`)}`,body:`{\n ${Fs(`lx${e}`,"fx","t")}\n ${Fs(`ly${e}`,"fy","t")}\n ${Fs(`lz${e}`,"fz","t")}\n if (convert${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${Bs("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n }\n let px = Math.fround(pos[o3] + fx * delta);\n let py = Math.fround(pos[o3 + 1] + fy * delta);\n let pz = Math.fround(pos[o3 + 2] + fz * delta);\n ${Fs(`rd${e}`,"radial","t")}\n if (radial !== 0) {\n // Away from the centre, along the line through the particle.\n const dx = px - ce${e}x, dy = py - ce${e}y, dz = pz - ce${e}z;\n const length = Math.sqrt(dx * dx + dy * dy + dz * dz);\n if (length > 0) {\n const f = (radial * delta) / length;\n px = Math.fround(px + dx * f); py = Math.fround(py + dy * f); pz = Math.fround(pz + dz * f);\n }\n }\n ${Fs(`ox${e}`,"rx","t")}\n ${Fs(`oy${e}`,"ry","t")}\n ${Fs(`oz${e}`,"rz","t")}\n rx *= delta; ry *= delta; rz *= delta;\n if (rx !== 0 || ry !== 0 || rz !== 0) {\n px = Math.fround(px - ce${e}x); py = Math.fround(py - ce${e}y); pz = Math.fround(pz - ce${e}z);\n if (rx !== 0) ${Ds("rx",`aX${e}x`,`aX${e}y`,`aX${e}z`)}\n if (ry !== 0) ${Ds("ry",`aY${e}x`,`aY${e}y`,`aY${e}z`)}\n if (rz !== 0) ${Ds("rz",`aZ${e}x`,`aZ${e}y`,`aZ${e}z`)}\n px = Math.fround(px + ce${e}x); py = Math.fround(py + ce${e}y); pz = Math.fround(pz + ce${e}z);\n }\n pos[o3] = px; pos[o3 + 1] = py; pos[o3 + 2] = pz;}`};case"InheritVelocity":return{setup:`const b${e} = behaviors[${e}];\n const ps${e} = b${e}.ps;\n const ev${e} = b${e}.mode === 'current' && ps${e} !== undefined ? ps${e}.emitterVelocity : undefined;\n const active${e} = ev${e} !== undefined;\n let ivx${e} = 0, ivy${e} = 0, ivz${e} = 0;\n if (active${e}) {\n ivx${e} = ev${e}.x; ivy${e} = ev${e}.y; ivz${e} = ev${e}.z;\n if (!ps${e}.worldSpace) {\n ${Rs(`sc${e}`,`b${e}._tempScaleInv`)}\n ${Us(`q${e}`,`b${e}._tempQInv`)}\n ivx${e} *= sc${e}x; ivy${e} *= sc${e}y; ivz${e} *= sc${e}z;\n ${Bs(`ivx${e}`,`ivy${e}`,`ivz${e}`,`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n }\n }\n ${Es(`gm${e}`,`b${e}.multiplier`)}`,body:`if (active${e}) {\n ${Fs(`gm${e}`,"m","t")}\n const f = m * delta;\n pos[o3] += ivx${e} * f; pos[o3 + 1] += ivy${e} * f; pos[o3 + 2] += ivz${e} * f;\n }`};default:return null}}const ks=new Map;function qs(t,e,s){const i=ks.get(s);if(void 0!==i)return i??void 0;const n=function(t,e){const s=`\n if (count === 0) return;\n if (store === undefined) {\n store = particles[0].store;\n if (store === undefined) {\n // Particles of some other implementation, without columns: run the behaviors as they are.\n for (const k of [${e.join(", ")}]) {\n const b = behaviors[k];\n for (let i = 0; i < count; i++) {\n const p = particles[i];\n if (p.age < p.life) b.update(p, delta);\n }\n }\n return;\n }\n }\n const pos = store.position, vel = store.velocity;\n const size = store.size, startSize = store.startSize;\n const color = store.color, startColor = store.startColor;\n const scalars = store.scalars;\n const rot = store.rotation, angVel = store.angularVelocity;\n const uvTile = store.uvTile, startSpeed = store.startSpeed;\n const mem = store.memory, ms = store.memoryStride;\n ${t.map(t=>t.setup).join("\n")}\n // The system keeps particles[i] on row i. Anything else (a hand-built\n // list) is caught by its ends and read through each particle's row.\n const mapped = particles[0].storeIndex !== 0 || particles[count - 1].storeIndex !== count - 1;\n for (let i = 0; i < count; i++) {\n const p = particles[i];\n const row = mapped ? p.storeIndex : i;\n const s = row * 3;\n const age = scalars[s], life = scalars[s + 1];\n if (age >= life) continue;\n const t = age / life;\n const o3 = row * 3, o4 = row * 4;\n ${t.map(t=>t.body).join("\n")}\n }`;try{return new Function("deps",`const tmpColor = new deps.Vector4View(new Float32Array(4), 0);\n return function (behaviors, particles, count, delta, store) {${s}};`)($s)}catch(t){return}}(t,e);return ks.set(s,n??null),n}function Js(t){const e=[];let s=[],i=[],n=[],r=0;const o=()=>{if(0===i.length)return;const t=`${r}:${s.map(t=>t.type).join(",")}`,o=qs(i,n,t);if(void 0!==o)e.push({behaviors:s,run:o});else for(const t of s)e.push({behaviors:[t]});s=[],i=[],n=[]};for(let a=0;a<t.length;a++){const h=t[a],l=Ls(h,a);null!==l?(0===i.length&&(r=a),s.push(h),i.push(l),n.push(a)):(o(),e.push({behaviors:[h]}))}return o(),e}class Ws{constructor(t,e,s){this.position=t??new et,this.rotation=e??new tt,this.scale=s??new et(1,1,1)}apply(t){t.position.multiply(this.scale).applyQuaternion(this.rotation).add(this.position);const e=t.velocity,s=e.length();if(0===s)return;e.multiply(this.scale).applyQuaternion(this.rotation);const i=e.length();i>0&&e.multiplyScalar(s/i)}isIdentity(){const{position:t,rotation:e,scale:s}=this;return 0===t.x&&0===t.y&&0===t.z&&0===e.x&&0===e.y&&0===e.z&&1===e.w&&1===s.x&&1===s.y&&1===s.z}toJSON(){const t={},{position:e,rotation:s,scale:i}=this;return 0===e.x&&0===e.y&&0===e.z||(t.position=[e.x,e.y,e.z]),0===s.x&&0===s.y&&0===s.z&&1===s.w||(t.rotation=[s.x,s.y,s.z,s.w]),1===i.x&&1===i.y&&1===i.z||(t.scale=[i.x,i.y,i.z]),t}static fromJSON(t){if(!t)return;const{position:e,rotation:s,scale:i}=t;return new Ws(e?new et(e[0],e[1],e[2]):void 0,s?new tt(s[0],s[1],s[2],s[3]).normalize():void 0,i?new et(i[0],i[1],i[2]):void 0)}static toShapeJSON(t){return t&&!t.isIdentity()?{transform:t.toJSON()}:{}}clone(){return new Ws(this.position.clone(),this.rotation.clone(),this.scale.clone())}}var Gs,Qs;exports.BoxEmitFrom=void 0,(Gs=exports.BoxEmitFrom||(exports.BoxEmitFrom={}))[Gs.Volume=0]="Volume",Gs[Gs.Shell=1]="Shell",Gs[Gs.Edge=2]="Edge";class js{constructor(t={}){this.type="box",this._point=[0,0,0],this.width=t.width??1,this.height=t.height??1,this.depth=t.depth??1,this.emitFrom=t.emitFrom??exports.BoxEmitFrom.Volume,this.boxThickness=t.boxThickness?[...t.boxThickness]:[0,0,0],this.transform=t.transform}update(t,e){}initialize(t,e){const s=this._point;for(let t=0;t<3;t++)s[t]=2*M()-1;const i=Math.floor(3*M())%3;this.emitFrom===exports.BoxEmitFrom.Shell?s[i]=this.onSurface(i):this.emitFrom===exports.BoxEmitFrom.Edge&&(s[(i+1)%3]=this.onSurface((i+1)%3),s[(i+2)%3]=this.onSurface((i+2)%3)),t.position.set(s[0]*this.width/2,s[1]*this.height/2,s[2]*this.depth/2),t.velocity.set(0,0,t.startSpeed),this.transform?.apply(t)}onSurface(t){const e=M()<.5?-1:1,s=Math.min(this.boxThickness[t],1);return s<=0||M()<.5?e:e*(1-2*s*M())}toJSON(){return{type:"box",width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:[...this.boxThickness],...Ws.toShapeJSON(this.transform)}}static fromJSON(t){return new js({width:t.width,height:t.height,depth:t.depth,emitFrom:t.emitFrom,boxThickness:Array.isArray(t.boxThickness)?[Number(t.boxThickness[0])||0,Number(t.boxThickness[1])||0,Number(t.boxThickness[2])||0]:void 0,transform:Ws.fromJSON(t.transform)})}clone(){return new js({width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:this.boxThickness,transform:this.transform?.clone()})}}function Hs(t,e,s,i){let n;switch(t){case exports.EmitterMode.Loop:n=e-Math.floor(e);break;case exports.EmitterMode.PingPong:{const t=e-2*Math.floor(e/2);n=1-Math.abs(t-1);break}case exports.EmitterMode.Burst:n=i.isBursting&&i.burstParticleCount>0?i.burstParticleIndex/i.burstParticleCount:M();break;default:n=M()}return s>0&&(n=Math.floor(n/s)*s),n}exports.EmitterMode=void 0,(Qs=exports.EmitterMode||(exports.EmitterMode={}))[Qs.Random=0]="Random",Qs[Qs.Loop=1]="Loop",Qs[Qs.PingPong=2]="PingPong",Qs[Qs.Burst=3]="Burst";class Ys{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="circle",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Yt(1),this.memory=[],this.transform=t.transform}update(t,e){exports.EmitterMode.Random!==this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=Hs(this.mode,this.currentValue,this.spread,e),i=Be(this.thickness,2),n=s*this.arc;t.position.x=Math.cos(n),t.position.y=Math.sin(n),t.position.z=0,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)*i),this.transform?.apply(t)}toJSON(){return{type:"circle",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Ws.toShapeJSON(this.transform)}}static fromJSON(t){return new Ys({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?ee(t.speed):void 0,transform:Ws.fromJSON(t.transform),spread:t.spread})}clone(){return new Ys({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Xs{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="cone",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.angle=t.angle??Math.PI/6,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Yt(1),this.memory=[],this.transform=t.transform}update(t,e){exports.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=Hs(this.mode,this.currentValue,this.spread,e),i=Be(this.thickness,2),n=s*this.arc,r=Math.sin(n),o=Math.cos(n);t.position.x=i*o,t.position.y=i*r,t.position.z=0;const a=Math.min(Math.max(this.angle,0),Math.PI/2)*i;t.velocity.set(0,0,Math.cos(a)).addScaledVector(t.position,i>0?Math.sin(a)/i:0).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)),this.transform?.apply(t)}toJSON(){return{type:"cone",radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Ws.toShapeJSON(this.transform)}}static fromJSON(t){return new Xs({radius:t.radius,arc:t.arc,thickness:t.thickness,angle:t.angle,mode:t.mode,speed:t.speed?ee(t.speed):void 0,transform:Ws.fromJSON(t.transform),spread:t.spread})}clone(){return new Xs({radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Zs{constructor(t={}){this.type="donut",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.donutRadius=t.donutRadius??.2*this.radius,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Yt(1),this.memory=[],this.transform=t.transform,this._m1=new ot}reset(){this.currentValue=0,this.memory.length=0}update(t,e){exports.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=Hs(this.mode,this.currentValue,this.spread,e),i=M(),n=Be(this.thickness,2),r=s*this.arc,o=i*Math.PI*2,a=Math.sin(r),h=Math.cos(r),l=Math.max(0,this.radius),c=Math.max(0,this.donutRadius)*n;if(t.velocity.set(Math.cos(o)*h,Math.cos(o)*a,Math.sin(o)),t.position.set(l*h,l*a,0).addScaledVector(t.velocity,c),t.velocity.multiplyScalar(t.startSpeed),t.rotation instanceof tt){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(Re,t.velocity,Ue),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"donut",radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Ws.toShapeJSON(this.transform)}}static fromJSON(t){return new Zs({radius:t.radius,arc:t.arc,thickness:t.thickness,donutRadius:t.donutRadius,mode:t.mode,speed:t.speed?ee(t.speed):void 0,transform:Ws.fromJSON(t.transform),spread:t.spread})}clone(){return new Zs({radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Ks{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="edge",this.currentValue=0,this.radius=t.radius??1,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Yt(1),this.memory=[],this.transform=t.transform}update(t,e){exports.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=Hs(this.mode,this.currentValue,this.spread,e);t.position.set((2*s-1)*this.radius,0,0),t.velocity.set(0,t.startSpeed,0),this.transform?.apply(t)}toJSON(){return{type:"edge",radius:this.radius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Ws.toShapeJSON(this.transform)}}static fromJSON(t){return new Ks({radius:t.radius,mode:t.mode,speed:t.speed?ee(t.speed):void 0,spread:t.spread,transform:Ws.fromJSON(t.transform)})}clone(){return new Ks({radius:this.radius,mode:this.mode,speed:this.speed.clone(),spread:this.spread,transform:this.transform?.clone()})}}class ti{constructor(t={}){this.type="grid",this.width=t.width??1,this.height=t.height??1,this.column=t.column??10,this.row=t.row??10,this.transform=t.transform}initialize(t){const e=Number.isFinite(this.row)?Math.max(1,Math.floor(this.row)):1,s=Number.isFinite(this.column)?Math.max(1,Math.floor(this.column)):1,i=Math.floor(M()*e),n=Math.floor(M()*s);t.position.x=((n+.5)/s-.5)*this.width,t.position.y=((i+.5)/e-.5)*this.height,t.position.z=0,t.velocity.set(0,0,t.startSpeed),this.transform?.apply(t)}toJSON(){return{type:"grid",width:this.width,height:this.height,column:this.column,row:this.row,...Ws.toShapeJSON(this.transform)}}static fromJSON(t){return new ti({width:t.width,height:t.height,column:t.column,row:t.row,transform:Ws.fromJSON(t.transform)})}clone(){return new ti({width:this.width,height:this.height,column:this.column,row:this.row,transform:this.transform?.clone()})}update(t,e){}}class ei{constructor(t={}){this.type="hemisphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Yt(1),this.memory=[],this.transform=t.transform,this._m1=new ot}reset(){this.currentValue=0,this.memory.length=0}update(t,e){exports.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=Hs(this.mode,this.currentValue,this.spread,e),i=M(),n=Be(this.thickness,3),r=s*this.arc,o=Math.acos(i),a=Math.sin(r),h=Math.cos(r),l=Math.sin(o),c=Math.cos(o);if(t.position.x=l*h,t.position.y=l*a,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)*n),t.rotation instanceof tt){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(Re,t.position,Ue),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"hemisphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Ws.toShapeJSON(this.transform)}}static fromJSON(t){return new ei({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?ee(t.speed):void 0,transform:Ws.fromJSON(t.transform),spread:t.spread})}clone(){return new ei({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class si{constructor(t){this.type="point",this._m1=new ot,this.transform=t}update(t,e){}initialize(t){const e=M(),s=M(),i=e*Math.PI*2,n=2*s-1,r=Math.sqrt(Math.max(0,1-n*n));if(t.velocity.x=r*Math.cos(i),t.velocity.y=r*Math.sin(i),t.velocity.z=n,t.velocity.multiplyScalar(t.startSpeed),t.position.setScalar(0),t.rotation instanceof tt){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(Re,t.velocity,Ue),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"point",...Ws.toShapeJSON(this.transform)}}static fromJSON(t){return new si(Ws.fromJSON(t?.transform))}clone(){return new si(this.transform?.clone())}}class ii{constructor(t={}){this.type="sphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Yt(1),this.memory=[],this.transform=t.transform,this._m1=new ot}reset(){this.currentValue=0,this.memory.length=0}update(t,e){exports.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=Hs(this.mode,this.currentValue,this.spread,e),i=M(),n=Be(this.thickness,3),r=s*this.arc,o=Math.acos(2*i-1),a=Math.sin(r),h=Math.cos(r),l=Math.sin(o),c=Math.cos(o);if(t.position.x=l*h,t.position.y=l*a,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)*n),t.rotation instanceof tt){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(Re,t.position,Ue),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"sphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Ws.toShapeJSON(this.transform)}}static fromJSON(t){return new ii({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?ee(t.speed):void 0,transform:Ws.fromJSON(t.transform),spread:t.spread})}clone(){return new ii({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class ni{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="rectangle",this.currentValue=0,this.width=t.width??10,this.height=t.height??10,this.thickness=t.thickness??1,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Yt(1),this.memory=[],this.transform=t.transform,this._m1=new ot}update(t,e){exports.EmitterMode.Random!==this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=Hs(this.mode,this.currentValue,this.spread,e);M();const i=Math.max(0,this.width),n=Math.max(0,this.height),r=2*s*(i+n);let o,a,h,l;r<i?(o=r-i/2,a=-n/2,h=0,l=-1):r<i+n?(o=i/2,a=r-i-n/2,h=1,l=0):r<2*i+n?(o=i/2-(r-i-n),a=n/2,h=0,l=1):(o=-i/2,a=n/2-(r-2*i-n),h=-1,l=0);const c=Be(this.thickness,2);if(t.position.set(o*c,a*c,0),0===o&&0===a?t.velocity.set(h,l,0):t.velocity.set(o,a,0).normalize(),t.velocity.multiplyScalar(t.startSpeed),t.rotation instanceof tt){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(Re,t.velocity,Ue),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"rectangle",width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Ws.toShapeJSON(this.transform)}}static fromJSON(t){return new ni({width:t.width,height:t.height,thickness:t.thickness,mode:t.mode,speed:t.speed?ee(t.speed):void 0,transform:Ws.fromJSON(t.transform),spread:t.spread})}clone(){return new ni({width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}const ri={box:{type:"box",params:[["width",["number"]],["height",["number"]],["depth",["number"]],["emitFrom",["boxEmitFrom"]],["boxThickness",["vec3"]],["transform",["shapeTransform"]]],constructor:js,loadJSON:js.fromJSON},circle:{type:"circle",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:Ys,loadJSON:Ys.fromJSON},cone:{type:"cone",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:Xs,loadJSON:Xs.fromJSON},donut:{type:"donut",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["donutRadius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:Zs,loadJSON:Zs.fromJSON},edge:{type:"edge",params:[["radius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:Ks,loadJSON:Ks.fromJSON},point:{type:"point",params:[["transform",["shapeTransform"]]],constructor:si,loadJSON:si.fromJSON},sphere:{type:"sphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:ii,loadJSON:ii.fromJSON},hemisphere:{type:"hemisphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:ei,loadJSON:ei.fromJSON},grid:{type:"grid",params:[["width",["number"]],["height",["number"]],["column",["number"]],["row",["number"]],["transform",["shapeTransform"]]],constructor:ti,loadJSON:ti.fromJSON},rectangle:{type:"rectangle",params:[["width",["number"]],["height",["number"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:ni,loadJSON:ni.fromJSON}};function oi(t,e){const s=t?ri[t.type]:void 0;return s?s.loadJSON(t,e):(Wt(`${Qt("emitter shape",t)}; using a point emitter.`),new si)}function ai(t,e={}){const s=t.toJSON(),i=ri[s?.type];return i?Ht(s,t=>i.loadJSON(t,e).toJSON()):s}const hi=[];function li(t){if(!hi.find(e=>e.id===t.id)){t.initialize(),hi.push(t);for(const e of t.emitterShapes)ri[e.type]||(ri[e.type]=e);for(const e of t.behaviors)Ts[e.type]||(Ts[e.type]=e)}}function ci(t,e){if(e&&e.length>0)return e;const s=t.length/3,i=new Uint32Array(s);for(let t=0;t<s;t++)i[t]=t;return i}const ui=new WeakMap;function di(t){let s=ui.get(t);return void 0===s&&(s=e.RandomGUID(),ui.set(t,s)),s}function fi(t){return ui.get(t)}class pi{get mesh(){return this._mesh}set mesh(e){if(this._mesh=e,this._positions=void 0,this._indices=void 0,this._triangleIndexToArea.length=0,!e)return;const s=e.getVerticesData(t.VertexBuffer.PositionKind);if(!s||s.length<9)return;const i=new Float32Array(s),n=e.getIndices(),r=ci(i,n&&n.length>0?Uint32Array.from(n):void 0),o=Math.floor(r.length/3);if(0===o)return;this._positions=i,this._indices=new Int32Array(r.subarray(0,3*o));let a=0;this._triangleIndexToArea.push(0);const h=new et,l=new et,c=new et,u=new et;for(let t=0;t<o;t++){const e=r[3*t],i=r[3*t+1],n=r[3*t+2];h.set(s[3*e],s[3*e+1],s[3*e+2]),l.set(s[3*i],s[3*i+1],s[3*i+2]),c.set(s[3*n],s[3*n+1],s[3*n+2]),l.sub(h),c.sub(h),u.crossVectors(l,c),a+=.5*u.length(),this._triangleIndexToArea.push(a)}}constructor(t,e,s){this.type="mesh_surface",this._triangleIndexToArea=[],this._meshReferenceId=e,this.transform=s,t&&(this.mesh=t)}initialize(t){if(!this._positions||!this._indices)return t.position.set(0,0,0),t.velocity.set(0,0,1).multiplyScalar(t.startSpeed),void this.transform?.apply(t);const e=this._triangleIndexToArea.length-1;let s=0,i=e;const n=M()*this._triangleIndexToArea[e];for(;s+1<i;){const t=Math.floor((s+i)/2);n<this._triangleIndexToArea[t]?i=t:s=t}let r=M(),o=M();r+o>1&&(r=1-r,o=1-o);const a=this._indices[3*s],h=this._indices[3*s+1],l=this._indices[3*s+2],c=this._positions[3*a],u=this._positions[3*a+1],d=this._positions[3*a+2],f=this._positions[3*h]-c,p=this._positions[3*h+1]-u,m=this._positions[3*h+2]-d,y=this._positions[3*l]-c,g=this._positions[3*l+1]-u,v=this._positions[3*l+2]-d;t.position.set(c+f*r+y*o,u+p*r+g*o,d+m*r+v*o);const x=p*v-m*g,S=m*y-f*v,b=f*g-p*y,w=Math.sqrt(x*x+S*S+b*b)||1;t.velocity.set(x/w,S/w,b/w).multiplyScalar(t.startSpeed),this.transform?.apply(t)}toJSON(){return{type:"mesh_surface",mesh:this._mesh?di(this._mesh):this._meshReferenceId??"",...Ws.toShapeJSON(this.transform)}}static fromJSON(t){return new pi(void 0,t?.mesh,Ws.fromJSON(t?.transform))}clone(){return new pi(this._mesh,this._meshReferenceId,this.transform?.clone())}update(t,e){}}const mi={id:"babylon.quarks",initialize:()=>{},emitterShapes:[{type:"mesh_surface",params:[["mesh",["mesh"]]],constructor:pi,loadJSON:t=>pi.fromJSON(t)}],behaviors:[]};var yi;function gi(){return{direction:new a.Vector3(.4,-1,.6),color:new o.Color3(1,1,1),ambient:new o.Color3(.35,.35,.35)}}function vi(t){if(!t||"object"!=typeof t)return;const e=Array.isArray(t.color)?t.color:[1,1,1],s=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e;return{color:[s(e[0],1),s(e[1],1),s(e[2],1)],power:Math.max(.01,s(t.power,2)),strength:Math.max(0,s(t.strength,1)),mode:"mix"===t.mode||"fade"===t.mode?t.mode:"add"}}function xi(t,e={}){const s=t&&"object"==typeof t?t:{},i=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e,n=(t,e)=>Array.isArray(t)?[i(t[0],e[0]),i(t[1],e[1])]:[e[0],e[1]];return{channel:1===(s.channel??e.channel)?1:0,tiling:n(s.tiling,e.tiling??[1,1]),offset:n(s.offset,e.offset??[0,0]),scroll:n(s.scroll,e.scroll??[0,0])}}function Si(t,e){return t===e||t.channel===e.channel&&t.tiling[0]===e.tiling[0]&&t.tiling[1]===e.tiling[1]&&t.offset[0]===e.offset[0]&&t.offset[1]===e.offset[1]&&t.scroll[0]===e.scroll[0]&&t.scroll[1]===e.scroll[1]}function bi(t,e={}){const s=xi(void 0,e),i={};return t.channel!==s.channel&&(i.channel=t.channel),t.tiling[0]===s.tiling[0]&&t.tiling[1]===s.tiling[1]||(i.tiling=[...t.tiling]),t.offset[0]===s.offset[0]&&t.offset[1]===s.offset[1]||(i.offset=[...t.offset]),t.scroll[0]===s.scroll[0]&&t.scroll[1]===s.scroll[1]||(i.scroll=[...t.scroll]),Object.keys(i).length>0?i:void 0}exports.RenderMode=void 0,(yi=exports.RenderMode||(exports.RenderMode={}))[yi.BillBoard=0]="BillBoard",yi[yi.StretchedBillBoard=1]="StretchedBillBoard",yi[yi.Mesh=2]="Mesh",yi[yi.Trail=3]="Trail",yi[yi.HorizontalBillBoard=4]="HorizontalBillBoard",yi[yi.VerticalBillBoard=5]="VerticalBillBoard",yi[yi.Beam=6]="Beam";const wi={r:[1,0,0,0],g:[0,1,0,0],b:[0,0,1,0],a:[0,0,0,1],luminance:[.2126,.7152,.0722,0]};function Mi(t){if(!t||"object"!=typeof t||!t.ramp)return;const e=t.channel;return{ramp:t.ramp,channel:void 0!==e&&e in wi?e:"r"}}const zi=.05;function _i(t){if(!t||"object"!=typeof t)return;const e=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e,s=Array.isArray(t.edgeColor)?t.edgeColor:[1,1,1];return{mask:t.mask??null,maskUV:xi(t.maskUV),softness:Math.max(1e-4,e(t.softness,zi)),edgeWidth:Math.max(0,e(t.edgeWidth,0)),edgeColor:[e(s[0],1),e(s[1],1),e(s[2],1)]}}const Vi={scroll:[0,.5]},Ai=.05;function Ti(t){if(!t||"object"!=typeof t||!t.map)return;const e=t.strength;return{map:t.map,mapUV:xi(t.mapUV,Vi),strength:Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:Ai)}}function Oi(t){if(!t||"object"!=typeof t)return;const e=xi(t);return void 0===bi(e)?void 0:e}function Pi(t){const{mapUV:e,uvDistortion:s,erosion:i}=t;return 1===e?.channel||1===s?.mapUV.channel||!!i?.mask&&1===i.maskUV.channel}function $i(t){return"unlit"===t||"scene"===t?t:"fixed"}function Ei(t){return"distance"===t||"oldestInFront"===t||"youngestInFront"===t?t:"none"}function Ci(t){return"front"===t||"back"===t?t:"both"}function Fi(t){return"pause"===t||"pauseAndCatchUp"===t?t:"always"}function Ii(t){return!t||0===t.x&&0===t.y&&0===t.z?void 0:t.clone()}function Ni(t){return"number"==typeof t&&t>0?Math.min(t,1):0}function Bi(t){return"number"==typeof t&&Number.isFinite(t)&&t>=1?Math.floor(t):1}function Ui(t,e){return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:e}function Ri(t){const e=t.count,s="number"==typeof t.time&&Number.isFinite(t.time)&&t.time>0?t.time:0,i="number"==typeof t.cycle&&Number.isFinite(t.cycle)&&t.cycle>=1?t.cycle:1,n="number"==typeof t.interval&&Number.isFinite(t.interval)?Math.max(0,t.interval):.1,r="number"==typeof t.probability&&Number.isFinite(t.probability)?Math.min(1,Math.max(0,t.probability)):1;return{time:s,count:"number"==typeof e?new Yt(e):null!=e?e:new Yt(0),cycle:i,interval:n,probability:r}}function Di(t){return(t??[]).map(Ri).sort((t,e)=>t.time-e.time)}const Li=new Float32Array(0),ki=new Uint16Array(0);function qi(t){return t===exports.RenderMode.BillBoard||t===exports.RenderMode.StretchedBillBoard||t===exports.RenderMode.VerticalBillBoard||t===exports.RenderMode.HorizontalBillBoard}function Ji(t){return t.uTileCount>1||t.vTileCount>1}function Wi(t){return t.minParticleSize>0||t.maxParticleSize!==1/0}function Gi(t){const e=t.renderMode,s=e===exports.RenderMode.Mesh,i=e===exports.RenderMode.Trail,n=qi(e),o=t.softParticles,a=t.materialTransparent,h=t.pivot,l=Oi(t.mapUV),c=Ti(t.uvDistortion),u=Mi(t.gradientMap),d=_i(t.erosion),f=Bi(t.uTileCount),p=Bi(t.vTileCount);var m;return{renderMode:e,instancingGeometry:i?Li:t.instancingGeometry,instancingIndices:i?ki:t.instancingIndices,instancingUVs:i?void 0:t.instancingUVs,instancingUVs2:s&&Pi({mapUV:l,uvDistortion:c,erosion:d})?t.instancingUVs2:void 0,instancingNormals:s?t.instancingNormals:void 0,renderOrder:t.renderOrder,uTileCount:f,vTileCount:p,blendTiles:!i&&t.blendTiles&&Ji({uTileCount:f,vTileCount:p}),softParticles:o,softNearFade:o?Ui(t.softNearFade,0):0,softFarFade:o?Ui(t.softFarFade,1):0,materialBlendMode:a?t.materialBlendMode:r.Constants.ALPHA_DISABLE,materialTransparent:a,materialDepthTest:t.materialDepthTest,materialDepthWrite:t.materialDepthWrite,materialAlphaTest:t.materialAlphaTest>0?t.materialAlphaTest:0,texture:t.texture,reflectionTexture:s?t.reflectionTexture??null:null,reflectionLevel:s?t.reflectionLevel??1:1,reflectionAtlas:s?t.reflectionAtlas??null:null,layerMask:t.layerMask,renderingGroupId:t.renderingGroupId??0,applyFog:t.applyFog??!0,pivot:n&&h&&(0!==h.x||0!==h.y||0!==h.z)?h.clone():void 0,sortMode:t.sortMode??"none",renderFace:s?Ci(t.renderFace):"both",minParticleSize:n?Math.max(0,t.minParticleSize??0):0,maxParticleSize:n?(m=t.maxParticleSize,void 0!==m&&m>0?m:1/0):1/0,lighting:s?t.lighting??"fixed":"fixed",rim:s?vi(t.rim):void 0,mapUV:l,uvDistortion:c,gradientMap:u,erosion:d}}function Qi(t,e){return t.renderMode===e.renderMode&&t.instancingGeometry===e.instancingGeometry&&t.instancingIndices===e.instancingIndices&&t.instancingUVs===e.instancingUVs&&t.instancingUVs2===e.instancingUVs2&&t.instancingNormals===e.instancingNormals&&t.texture===e.texture&&t.reflectionTexture===e.reflectionTexture&&t.reflectionAtlas===e.reflectionAtlas&&t.lighting===e.lighting&&t.rim?.mode===e.rim?.mode&&t.uTileCount===e.uTileCount&&t.vTileCount===e.vTileCount&&t.blendTiles===e.blendTiles&&t.softParticles===e.softParticles&&t.materialBlendMode===e.materialBlendMode&&t.materialTransparent===e.materialTransparent&&t.materialDepthTest===e.materialDepthTest&&t.materialDepthWrite===e.materialDepthWrite&&t.materialAlphaTest>0==e.materialAlphaTest>0&&t.layerMask===e.layerMask&&t.renderingGroupId===e.renderingGroupId&&t.renderOrder===e.renderOrder&&t.applyFog===e.applyFog&&t.sortMode===e.sortMode&&t.renderFace===e.renderFace&&!t.pivot==!e.pivot&&Wi(t)===Wi(e)&&t.mapUV?.channel===e.mapUV?.channel&&t.uvDistortion?.map===e.uvDistortion?.map&&t.uvDistortion?.mapUV.channel===e.uvDistortion?.mapUV.channel&&!t.gradientMap==!e.gradientMap&&t.gradientMap?.ramp===e.gradientMap?.ramp&&!t.erosion==!e.erosion&&t.erosion?.mask===e.erosion?.mask&&t.erosion?.maskUV.channel===e.erosion?.maskUV.channel}function ji(t,e){return t.softNearFade===e.softNearFade&&t.softFarFade===e.softFarFade&&t.materialAlphaTest===e.materialAlphaTest&&t.reflectionLevel===e.reflectionLevel&&function(t,e){return(t?.x??0)===(e?.x??0)&&(t?.y??0)===(e?.y??0)&&(t?.z??0)===(e?.z??0)}(t.pivot,e.pivot)&&t.minParticleSize===e.minParticleSize&&t.maxParticleSize===e.maxParticleSize&&function(t,e){if(!t||!e)return!t==!e;return t.power===e.power&&t.strength===e.strength&&Yi(t.color,e.color)}(t.rim,e.rim)&&Xi(t.mapUV,e.mapUV)&&t.uvDistortion?.strength===e.uvDistortion?.strength&&Xi(t.uvDistortion?.mapUV,e.uvDistortion?.mapUV)&&t.gradientMap?.channel===e.gradientMap?.channel&&t.erosion?.softness===e.erosion?.softness&&t.erosion?.edgeWidth===e.erosion?.edgeWidth&&Yi(t.erosion?.edgeColor,e.erosion?.edgeColor)&&Xi(t.erosion?.maskUV,e.erosion?.maskUV)}function Hi(t,e){return Qi(t,e)&&ji(t,e)}function Yi(t,e){return t&&e?t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]:!t==!e}function Xi(t,e){return t&&e?t.tiling[0]===e.tiling[0]&&t.tiling[1]===e.tiling[1]&&t.offset[0]===e.offset[0]&&t.offset[1]===e.offset[1]&&t.scroll[0]===e.scroll[0]&&t.scroll[1]===e.scroll[1]:!t==!e}function Zi(t,e={}){const s=function(t,e){if(s=t,"function"==typeof s?.getDepthMap){const s=t,i=s._storeCameraSpaceZ?"viewZ":s._storeNonLinearDepth?"nonLinear":"linear";return{texture:t.getDepthMap(),encoding:e.encoding??i,packed:e.packed??t.isPacked}}var s;return{texture:t,encoding:e.encoding??"linear",packed:e.packed??!1}}(t,e);if(s.packed&&"viewZ"===s.encoding)throw new Error("[babylon.quarks] A packed view-Z depth cannot be decoded; use a float depth texture");return s}function Ki(t,e,s){if("viewZ"===e)return s.set(1,0,0,1);const i=t.getEngine(),n=i.useReverseDepthBuffer,r=i.isNDCHalfZRange,o=t.getProjectionMatrix().m,a=o[10],l=o[11],c=o[14],u=o[15];if("linear"===e){let e,i;t.mode===h.Camera.ORTHOGRAPHIC_CAMERA?(e=!n&&r?0:1,i=n&&r?0:1):(e=n&&r?t.minZ:r?0:t.minZ,i=n&&r?0:t.maxZ);const o=n?-1:1,l=e+i;return s.set(o*l/a,(-o*e-c)/a,0,1)}const d=r?1:2,f=r?0:-1;return s.set(-d*u,c-f*u,d*l,f*l-a)}const tn=2048,en=2047;class sn{constructor(t){this.counts=new Uint32Array(tn),this.floatView=new Float32Array(1),this.uintView=new Uint32Array(this.floatView.buffer),this.keys=new Uint32Array(t),this.orderA=new Uint32Array(t),this.orderB=new Uint32Array(t)}ensure(t){this.keys.length<t&&(this.keys=new Uint32Array(t),this.orderA=new Uint32Array(t),this.orderB=new Uint32Array(t))}floatKey(t,e){this.floatView[0]=t;const s=this.uintView[0];return e?~s>>>0:s}}const nn="\n#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n";function rn(t){return`\n#ifdef FOG\n vFogDistance = ${t};\n#endif\n`}const on="\n#ifdef FOG\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\n\nfloat quarksFogFactor() {\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n float fogDistance = length(vFogDistance);\n if (vFogInfos.x == 3.0) {\n // A zero-width band is a cut at its distance, not a division by zero.\n fogCoeff = (fogEnd - fogDistance) / max(fogEnd - fogStart, 1e-6);\n } else if (vFogInfos.x == 1.0) {\n fogCoeff = exp(-fogDistance * fogDensity);\n } else if (vFogInfos.x == 2.0) {\n fogCoeff = exp(-fogDistance * fogDistance * fogDensity * fogDensity);\n }\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n";function an(t){return`\n#ifdef FOG\n {\n float fogFactor = quarksFogFactor();\n#if defined(FOG_ADDITIVE)\n ${t} *= fogFactor;\n#elif defined(FOG_MULTIPLY)\n ${t} = mix(vec3(1.0), ${t}, fogFactor);\n#else\n ${t} = mix(vFogColor, ${t}, fogFactor);\n#endif\n }\n#endif\n`}const hn="\n#ifdef FOG\nvarying vFogDistance: vec3f;\n#endif\n";function ln(t){return`\n#ifdef FOG\n vertexOutputs.vFogDistance = ${t};\n#endif\n`}const cn="\n#ifdef FOG\nuniform vFogInfos: vec4f;\nuniform vFogColor: vec3f;\nvarying vFogDistance: vec3f;\n\nfn quarksFog(rgb: vec3f, fogDistanceVector: vec3f) -> vec3f {\n var fogCoeff = 1.0;\n let fogStart = uniforms.vFogInfos.y;\n let fogEnd = uniforms.vFogInfos.z;\n let fogDensity = uniforms.vFogInfos.w;\n let fogDistance = length(fogDistanceVector);\n if (uniforms.vFogInfos.x == 3.0) {\n // A zero-width band is a cut at its distance, not a division by zero.\n fogCoeff = (fogEnd - fogDistance) / max(fogEnd - fogStart, 1e-6);\n } else if (uniforms.vFogInfos.x == 1.0) {\n fogCoeff = exp(-fogDistance * fogDensity);\n } else if (uniforms.vFogInfos.x == 2.0) {\n fogCoeff = exp(-fogDistance * fogDistance * fogDensity * fogDensity);\n }\n let fogFactor = clamp(fogCoeff, 0.0, 1.0);\n#if defined(FOG_ADDITIVE)\n return rgb * fogFactor;\n#elif defined(FOG_MULTIPLY)\n return mix(vec3f(1.0), rgb, fogFactor);\n#else\n return mix(uniforms.vFogColor, rgb, fogFactor);\n#endif\n}\n#endif\n";function un(t){return`\n#ifdef FOG\n ${t} = vec4f(quarksFog(${t}.rgb, fragmentInputs.vFogDistance), ${t}.a);\n#endif\n`}function dn(t,e,s){const i=e*s,n=fn(Math.floor(t),i);return{column:fn(n,e),row:Math.floor(n/e)}}function fn(t,e){return t-e*Math.floor(t/e)}const pn="\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n";function mn(t){return`\n#ifdef UV_TILE\n {\n vec2 tc = vec2(tileCountX, tileCountY);\n float tileTotal = tc.x * tc.y;\n float baseTile = mod(floor(uvTile), tileTotal);\n vec2 tileUV = vec2(mod(baseTile, tc.x), tc.y - 1.0 - floor(baseTile / tc.x)) / tc;\n vUV = ${t} / tc + tileUV;\n#ifdef TILE_BLEND\n float nextTile = mod(baseTile + 1.0, tileTotal);\n vec2 nextUV = vec2(mod(nextTile, tc.x), tc.y - 1.0 - floor(nextTile / tc.x)) / tc;\n vUV2 = ${t} / tc + nextUV;\n vTileBlend = fract(uvTile);\n#endif\n }\n#else\n vUV = ${t};\n#endif\n`}const yn="\n#ifdef UV_TILE\nuniform tileCountX: f32;\nuniform tileCountY: f32;\n\n// A floored modulo, as GLSL's mod: never negative for a positive divisor.\nfn quarksWrap(value: f32, divisor: f32) -> f32 {\n return value - divisor * floor(value / divisor);\n}\n#endif\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n";function gn(t){return`\n#ifdef UV_TILE\n {\n let tc = vec2f(uniforms.tileCountX, uniforms.tileCountY);\n let tileTotal = tc.x * tc.y;\n let baseTile = quarksWrap(floor(vertexInputs.uvTile), tileTotal);\n let tileUV = vec2f(quarksWrap(baseTile, tc.x), tc.y - 1.0 - floor(baseTile / tc.x)) / tc;\n vertexOutputs.vUV = ${t} / tc + tileUV;\n#ifdef TILE_BLEND\n let nextTile = quarksWrap(baseTile + 1.0, tileTotal);\n let nextUV = vec2f(quarksWrap(nextTile, tc.x), tc.y - 1.0 - floor(nextTile / tc.x)) / tc;\n vertexOutputs.vUV2 = ${t} / tc + nextUV;\n vertexOutputs.vTileBlend = fract(vertexInputs.uvTile);\n#endif\n }\n#else\n vertexOutputs.vUV = ${t};\n#endif\n`}var vn=`\nattribute vec3 position;\nattribute vec2 uv;\nattribute vec3 normal;\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute vec4 rotation;\nattribute float uvTile;\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${pn}\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n#ifdef MESH_UV2\n// The mesh's second UV set.\nattribute vec2 uv2;\n#endif\n// UV channel 1: the mesh's second UV set, or its first when it has none.\nvarying vec2 vUV1;\n#endif\nvarying vec3 vNormal;\nvarying vec3 vWorldPos;\n\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\nvec3 applyQuaternion(vec3 v, vec4 q) {\n vec3 qVec = q.xyz;\n float qW = q.w;\n vec3 t = 2.0 * cross(qVec, v);\n return v + qW * t + cross(qVec, t);\n}\n\n${nn}\nvoid main() {\n vec3 scaledPosition = position * size;\n vec3 rotatedPosition = applyQuaternion(scaledPosition, rotation);\n // A normal scales by the inverse of the size, so a stretched mesh keeps its normals\n // perpendicular; a flat size counts as a sliver rather than dividing by zero.\n vec3 safeSize = vec3(\n abs(size.x) > 1e-6 ? size.x : 1e-6,\n abs(size.y) > 1e-6 ? size.y : 1e-6,\n abs(size.z) > 1e-6 ? size.z : 1e-6);\n // A mirrored size (an odd number of negative components) turns the winding inside out, so the\n // normal is turned with it and the fragment's front-face test agrees with the geometry.\n vec3 rotatedNormal = normalize(applyQuaternion(normal / safeSize, rotation)) * sign(safeSize.x * safeSize.y * safeSize.z);\n vec3 localPos = rotatedPosition + offset;\n\n vec4 worldPos = world * vec4(localPos, 1.0);\n vec4 viewPos = view * worldPos;\n gl_Position = projection * viewPos;\n${rn("viewPos.xyz")}\n\n vWorldPos = worldPos.xyz;\n vNormal = normalize((world * vec4(rotatedNormal, 0.0)).xyz);\n\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(viewPos.z);\n#endif\n\n${mn("uv")}\n\n#ifdef UV1\n#ifdef MESH_UV2\n vUV1 = uv2;\n#else\n vUV1 = uv;\n#endif\n#endif\n vColor = color;\n}\n`,xn=`\nattribute position: vec3f;\nattribute uv: vec2f;\nattribute normal: vec3f;\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: vec4f;\nattribute uvTile: f32;\n\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${yn}\n\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n#ifdef MESH_UV2\n// The mesh's second UV set.\nattribute uv2: vec2f;\n#endif\n// UV channel 1: the mesh's second UV set, or its first when it has none.\nvarying vUV1: vec2f;\n#endif\nvarying vNormal: vec3f;\nvarying vWorldPos: vec3f;\n\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\nfn applyQuaternion(v: vec3f, q: vec4f) -> vec3f {\n let qVec = q.xyz;\n let qW = q.w;\n let t = 2.0 * cross(qVec, v);\n return v + qW * t + cross(qVec, t);\n}\n\n${hn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let size = vertexInputs.size;\n let scaledPosition = vertexInputs.position * size;\n let rotatedPosition = applyQuaternion(scaledPosition, vertexInputs.rotation);\n // A normal scales by the inverse of the size, so a stretched mesh keeps its normals\n // perpendicular; a flat size counts as a sliver rather than dividing by zero.\n let safeSize = vec3f(\n select(1e-6, size.x, abs(size.x) > 1e-6),\n select(1e-6, size.y, abs(size.y) > 1e-6),\n select(1e-6, size.z, abs(size.z) > 1e-6));\n // A mirrored size (an odd number of negative components) turns the winding inside out, so the\n // normal is turned with it and the fragment's front-face test agrees with the geometry.\n let rotatedNormal = normalize(applyQuaternion(vertexInputs.normal / safeSize, vertexInputs.rotation)) * sign(safeSize.x * safeSize.y * safeSize.z);\n let localPos = rotatedPosition + vertexInputs.offset;\n\n let worldPos = uniforms.world * vec4f(localPos, 1.0);\n let viewPos = uniforms.view * worldPos;\n let clipPosition = uniforms.projection * viewPos;\n vertexOutputs.position = clipPosition;\n${ln("viewPos.xyz")}\n\n vertexOutputs.vWorldPos = worldPos.xyz;\n vertexOutputs.vNormal = normalize((uniforms.world * vec4f(rotatedNormal, 0.0)).xyz);\n\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(viewPos.z);\n#endif\n\n${gn("vertexInputs.uv")}\n\n#ifdef UV1\n#ifdef MESH_UV2\n vertexOutputs.vUV1 = vertexInputs.uv2;\n#else\n vertexOutputs.vUV1 = vertexInputs.uv;\n#endif\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;function Sn(t){return`\n#if defined(BLEND_PREMULTIPLY)\n ${t}.rgb *= ${t}.a;\n#elif defined(BLEND_MULTIPLY)\n ${t}.rgb = mix(vec3(1.0), ${t}.rgb, ${t}.a);\n#endif\n`}function bn(t){return`\n#if defined(BLEND_PREMULTIPLY)\n ${t} = vec4f(${t}.rgb * ${t}.a, ${t}.a);\n#elif defined(BLEND_MULTIPLY)\n ${t} = vec4f(mix(vec3f(1.0), ${t}.rgb, ${t}.a), ${t}.a);\n#endif\n`}const wn="\n#ifdef SOFT_PARTICLES\nuniform sampler2D depthTexture;\nuniform vec2 softParams;\nuniform vec4 projParams;\nvarying vec4 projPosition;\nvarying float linearDepth;\n\nfloat quarksSceneDepth(vec4 texel) {\n#ifdef SOFT_DEPTH_PACKED\n float d = dot(texel, vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0));\n#else\n float d = texel.r;\n#endif\n float denominator = projParams.z * d + projParams.w;\n float depth = abs(denominator) > 1e-8 ? abs((projParams.x * d + projParams.y) / denominator) : 0.0;\n // Nothing drawn there reads as infinitely far.\n return depth > 0.0 ? depth : 1e30;\n}\n#endif\n";function Mn(t){return`\n#ifdef SOFT_PARTICLES\n {\n vec2 softUV = 0.5 * (projPosition.xy / projPosition.w) + 0.5;\n float sceneDepth = quarksSceneDepth(texture2D(depthTexture, softUV));\n ${t}.a *= clamp(softParams.y * ((sceneDepth - softParams.x) - linearDepth), 0.0, 1.0);\n }\n#endif\n`}const zn="\n#ifdef SOFT_PARTICLES\nvar depthTextureSampler: sampler;\nvar depthTexture: texture_2d<f32>;\nuniform softParams: vec2f;\nuniform projParams: vec4f;\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n\nfn quarksSceneDepth(texel: vec4f) -> f32 {\n#ifdef SOFT_DEPTH_PACKED\n let d = dot(texel, vec4f(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0));\n#else\n let d = texel.r;\n#endif\n let denominator = uniforms.projParams.z * d + uniforms.projParams.w;\n let depth = select(0.0, abs((uniforms.projParams.x * d + uniforms.projParams.y) / denominator), abs(denominator) > 1e-8);\n // Nothing drawn there reads as infinitely far.\n return select(1e30, depth, depth > 0.0);\n}\n#endif\n";function _n(t){return`\n#ifdef SOFT_PARTICLES\n {\n let softUV = 0.5 * (fragmentInputs.projPosition.xy / fragmentInputs.projPosition.w) + 0.5;\n let sceneDepth = quarksSceneDepth(textureSample(depthTexture, depthTextureSampler, softUV));\n ${t}.a *= clamp(uniforms.softParams.y * ((sceneDepth - uniforms.softParams.x) - fragmentInputs.linearDepth), 0.0, 1.0);\n }\n#endif\n`}const Vn="\n#ifdef MAP_TRANSFORM\nuniform vec4 mapTransform;\n#endif\n#ifdef UV_DISTORTION\nuniform sampler2D distortionMap;\nuniform vec4 distortionTransform;\nuniform float distortionStrength;\n#endif\n#ifdef GRADIENT_MAP\nuniform sampler2D gradientMap;\nuniform vec2 gradientMapRange;\nuniform vec4 gradientMapChannel;\n#endif\n#ifdef EROSION\nuniform vec2 erosionParams;\nuniform vec3 erosionEdgeColor;\n#ifdef EROSION_MASK\nuniform sampler2D erosionMask;\nuniform vec4 erosionMaskTransform;\n#endif\n\nvec4 quarksErode(vec4 color, float level, float mask) {\n float softness = erosionParams.x;\n float edgeWidth = erosionParams.y;\n // At level 1 the cut sits below the lowest mask value by the soft band\n // and the edge band, so nothing is cut and no edge shows; at level 0 above\n // the highest. The edge then grows in as the cut rises, rather than popping.\n float cut = mix(-(softness + edgeWidth), 1.0, 1.0 - level);\n float visible = smoothstep(cut, cut + softness, mask);\n if (edgeWidth > 0.0) {\n float edge = 1.0 - smoothstep(cut + softness, cut + softness + edgeWidth, mask);\n color.rgb += erosionEdgeColor * edge;\n }\n color.a *= visible;\n return color;\n}\n#endif\n";function An(t){return`\n vec4 baseColor = vColor;\n#if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n vec2 mapUV = vUV1 * mapTransform.xy + mapTransform.zw;\n#elif defined(MAP_TRANSFORM)\n vec2 mapUV = vUV * mapTransform.xy + mapTransform.zw;\n#else\n vec2 mapUV = vUV;\n#endif\n#ifdef UV_DISTORTION\n #ifdef UV_DISTORTION_UV1\n vec2 distortionUV = vUV1;\n #else\n vec2 distortionUV = vUV;\n #endif\n vec2 distortion = (texture2D(distortionMap, distortionUV * distortionTransform.xy + distortionTransform.zw).rg - 0.5) * 2.0 * distortionStrength;\n mapUV += distortion;\n#endif\n#ifdef EROSION\n float erosionLevel = baseColor.a;\n baseColor.a = 1.0;\n float erosionMaskValue = 1.0;\n#endif\n#if defined(USE_MAP) || defined(GRADIENT_MAP)\n#ifdef USE_MAP\n vec4 texColor = texture2D(map, mapUV);\n ${t?"#ifdef TILE_BLEND\n #if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n vec2 mapUV2 = mapUV;\n #else\n #ifdef MAP_TRANSFORM\n vec2 mapUV2 = vUV2 * mapTransform.xy + mapTransform.zw;\n #else\n vec2 mapUV2 = vUV2;\n #endif\n #ifdef UV_DISTORTION\n mapUV2 += distortion;\n #endif\n #endif\n vec4 texColor2 = texture2D(map, mapUV2);\n texColor = mix(texColor, texColor2, vTileBlend);\n #endif":""}\n#else\n // No map: the ramp is looked up at white, its far end.\n vec4 texColor = vec4(1.0);\n#endif\n #ifdef GRADIENT_MAP\n float rampAt = clamp(dot(texColor, gradientMapChannel), 0.0, 1.0);\n vec4 ramp = texture2D(gradientMap, vec2(mix(gradientMapRange.x, gradientMapRange.y, rampAt), 0.5));\n texColor = vec4(ramp.rgb, ramp.a * mix(texColor.a, 1.0, gradientMapChannel.a));\n #endif\n #ifdef EROSION\n erosionMaskValue = texColor.a;\n #endif\n baseColor *= texColor;\n#endif\n#ifdef EROSION\n #ifdef EROSION_MASK\n #ifdef EROSION_MASK_UV1\n vec2 erosionUV = vUV1;\n #else\n vec2 erosionUV = vUV;\n #endif\n erosionMaskValue = texture2D(erosionMask, erosionUV * erosionMaskTransform.xy + erosionMaskTransform.zw).r;\n #endif\n baseColor = quarksErode(baseColor, erosionLevel, erosionMaskValue);\n#endif\n`}const Tn="\n#ifdef MAP_TRANSFORM\nuniform mapTransform: vec4f;\n#endif\n#ifdef UV_DISTORTION\nvar distortionMapSampler: sampler;\nvar distortionMap: texture_2d<f32>;\nuniform distortionTransform: vec4f;\nuniform distortionStrength: f32;\n#endif\n#ifdef GRADIENT_MAP\nvar gradientMapSampler: sampler;\nvar gradientMap: texture_2d<f32>;\nuniform gradientMapRange: vec2f;\nuniform gradientMapChannel: vec4f;\n#endif\n#ifdef EROSION\nuniform erosionParams: vec2f;\nuniform erosionEdgeColor: vec3f;\n#ifdef EROSION_MASK\nvar erosionMaskSampler: sampler;\nvar erosionMask: texture_2d<f32>;\nuniform erosionMaskTransform: vec4f;\n#endif\n\nfn quarksErode(colorIn: vec4f, level: f32, mask: f32) -> vec4f {\n var color = colorIn;\n let softness = uniforms.erosionParams.x;\n let edgeWidth = uniforms.erosionParams.y;\n let cut = mix(-(softness + edgeWidth), 1.0, 1.0 - level);\n let visible = smoothstep(cut, cut + softness, mask);\n if (edgeWidth > 0.0) {\n let edge = 1.0 - smoothstep(cut + softness, cut + softness + edgeWidth, mask);\n color = vec4f(color.rgb + uniforms.erosionEdgeColor * edge, color.a);\n }\n color.a *= visible;\n return color;\n}\n#endif\n";function On(t){return`\n var baseColor = fragmentInputs.vColor;\n#if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n var mapUV = fragmentInputs.vUV1 * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n#elif defined(MAP_TRANSFORM)\n var mapUV = fragmentInputs.vUV * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n#else\n var mapUV = fragmentInputs.vUV;\n#endif\n#ifdef UV_DISTORTION\n #ifdef UV_DISTORTION_UV1\n let distortionUV = fragmentInputs.vUV1;\n #else\n let distortionUV = fragmentInputs.vUV;\n #endif\n let distortion = (textureSample(distortionMap, distortionMapSampler, distortionUV * uniforms.distortionTransform.xy + uniforms.distortionTransform.zw).rg - 0.5) * 2.0 * uniforms.distortionStrength;\n mapUV += distortion;\n#endif\n#ifdef EROSION\n let erosionLevel = baseColor.a;\n baseColor.a = 1.0;\n var erosionMaskValue = 1.0;\n#endif\n#if defined(USE_MAP) || defined(GRADIENT_MAP)\n#ifdef USE_MAP\n var texColor = textureSample(map, mapSampler, mapUV);\n ${t?"#ifdef TILE_BLEND\n #if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n let mapUV2 = mapUV;\n #else\n #ifdef MAP_TRANSFORM\n var mapUV2 = fragmentInputs.vUV2 * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n #else\n var mapUV2 = fragmentInputs.vUV2;\n #endif\n #ifdef UV_DISTORTION\n mapUV2 += distortion;\n #endif\n #endif\n let texColor2 = textureSample(map, mapSampler, mapUV2);\n texColor = mix(texColor, texColor2, fragmentInputs.vTileBlend);\n #endif":""}\n#else\n // No map: the ramp is looked up at white, its far end.\n var texColor = vec4f(1.0);\n#endif\n #ifdef GRADIENT_MAP\n let rampAt = clamp(dot(texColor, uniforms.gradientMapChannel), 0.0, 1.0);\n let ramp = textureSample(gradientMap, gradientMapSampler, vec2f(mix(uniforms.gradientMapRange.x, uniforms.gradientMapRange.y, rampAt), 0.5));\n texColor = vec4f(ramp.rgb, ramp.a * mix(texColor.a, 1.0, uniforms.gradientMapChannel.a));\n #endif\n #ifdef EROSION\n erosionMaskValue = texColor.a;\n #endif\n baseColor *= texColor;\n#endif\n#ifdef EROSION\n #ifdef EROSION_MASK\n #ifdef EROSION_MASK_UV1\n let erosionUV = fragmentInputs.vUV1;\n #else\n let erosionUV = fragmentInputs.vUV;\n #endif\n erosionMaskValue = textureSample(erosionMask, erosionMaskSampler, erosionUV * uniforms.erosionMaskTransform.xy + uniforms.erosionMaskTransform.zw).r;\n #endif\n baseColor = quarksErode(baseColor, erosionLevel, erosionMaskValue);\n#endif\n`}var Pn=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\n\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${on}\n${wn}\n${Vn}\nvoid main() {\n${An(!0)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${an("baseColor.rgb")}\n${Mn("baseColor")}\n${Sn("baseColor")}\n gl_FragColor = baseColor;\n}\n`,$n=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\n\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${cn}\n${zn}\n${Tn}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${On(!0)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n${un("baseColor")}\n${_n("baseColor")}\n${bn("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,En=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\nvarying vec3 vNormal;\nvarying vec3 vWorldPos;\n\n#ifndef MESH_UNLIT\nuniform vec3 lightDirection;\nuniform vec3 lightColor;\nuniform vec3 ambientColor;\n#endif\n\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n#if defined(USE_ENVMAP_ATLAS) || defined(MESH_RIM)\nuniform vec3 eyePosition;\n#endif\n\n#ifdef MESH_RIM\nuniform vec3 rimColor;\nuniform vec2 rimParams;\n#endif\n\n// One 3×2 atlas (px py pz / nx ny nz). Avoids samplerCube and multi-face\n// sampler bindings that raise GL_INVALID_OPERATION on iOS WebKit.\n#ifdef USE_ENVMAP_ATLAS\nuniform sampler2D envAtlas;\nuniform float reflectionLevel;\n\nvec3 sampleEnvAtlas(vec3 r) {\n vec3 a = abs(r);\n vec2 localUV;\n float cellX;\n float cellY;\n // Atlas layout: +X +Y +Z on row 0, -X -Y -Z on row 1.\n if (a.x >= a.y && a.x >= a.z) {\n cellX = 0.0;\n if (r.x >= 0.0) {\n cellY = 0.0;\n localUV = vec2(-r.z, -r.y) / a.x * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(r.z, -r.y) / a.x * 0.5 + 0.5;\n }\n } else if (a.y >= a.z) {\n cellX = 1.0;\n if (r.y >= 0.0) {\n cellY = 0.0;\n localUV = vec2(r.x, r.z) / a.y * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(r.x, -r.z) / a.y * 0.5 + 0.5;\n }\n } else {\n cellX = 2.0;\n if (r.z >= 0.0) {\n cellY = 0.0;\n localUV = vec2(r.x, -r.y) / a.z * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(-r.x, -r.y) / a.z * 0.5 + 0.5;\n }\n }\n vec2 uv = (vec2(cellX, cellY) + clamp(localUV, 0.0, 1.0)) / vec2(3.0, 2.0);\n return texture2D(envAtlas, uv).rgb;\n}\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${on}\n${wn}\n${Vn}\nvoid main() {\n${An(!0)}\n // A back face lights, reflects and rims as the face the camera sees.\n vec3 N = normalize(vNormal) * (gl_FrontFacing ? 1.0 : -1.0);\n#ifdef MESH_UNLIT\n vec3 color = baseColor.rgb;\n#else\n vec3 L = normalize(-lightDirection);\n float NdotL = max(dot(N, L), 0.0);\n vec3 litColor = ambientColor + lightColor * NdotL;\n\n vec3 color = baseColor.rgb * litColor;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\n vec3 viewDir = normalize(vWorldPos - eyePosition);\n vec3 reflectionCoords = reflect(viewDir, N);\n color += sampleEnvAtlas(reflectionCoords) * reflectionLevel;\n#endif\n\n#ifdef MESH_RIM\n // Fresnel: strongest where the surface turns away from the camera.\n vec3 V = normalize(eyePosition - vWorldPos);\n float edgeTerm = pow(1.0 - abs(dot(N, V)), rimParams.x);\n #if defined(MESH_RIM_FADE)\n // Faces turned to the camera fade by the strength; edges stay.\n baseColor.a *= clamp(1.0 - rimParams.y * (1.0 - edgeTerm), 0.0, 1.0);\n #elif defined(MESH_RIM_MIX)\n color = mix(color, rimColor, clamp(edgeTerm * rimParams.y, 0.0, 1.0));\n #else\n color += rimColor * edgeTerm * rimParams.y;\n #endif\n#endif\n\n // After the rim, so a fade that empties a face can discard it.\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${an("color")}\n vec4 finalColor = vec4(color, baseColor.a);\n${Mn("finalColor")}\n${Sn("finalColor")}\n gl_FragColor = finalColor;\n}\n`,Cn=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\nvarying vNormal: vec3f;\nvarying vWorldPos: vec3f;\n\n#ifndef MESH_UNLIT\nuniform lightDirection: vec3f;\nuniform lightColor: vec3f;\nuniform ambientColor: vec3f;\n#endif\n\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n#if defined(USE_ENVMAP_ATLAS) || defined(MESH_RIM)\nuniform eyePosition: vec3f;\n#endif\n\n#ifdef MESH_RIM\nuniform rimColor: vec3f;\nuniform rimParams: vec2f;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\nvar envAtlasSampler: sampler;\nvar envAtlas: texture_2d<f32>;\nuniform reflectionLevel: f32;\n\nfn sampleEnvAtlas(r: vec3f) -> vec3f {\n let a = abs(r);\n var localUV: vec2f;\n var cellX: f32;\n var cellY: f32;\n if (a.x >= a.y && a.x >= a.z) {\n cellX = 0.0;\n if (r.x >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(-r.z, -r.y) / a.x * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(r.z, -r.y) / a.x * 0.5 + 0.5;\n }\n } else if (a.y >= a.z) {\n cellX = 1.0;\n if (r.y >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(r.x, r.z) / a.y * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(r.x, -r.z) / a.y * 0.5 + 0.5;\n }\n } else {\n cellX = 2.0;\n if (r.z >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(r.x, -r.y) / a.z * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(-r.x, -r.y) / a.z * 0.5 + 0.5;\n }\n }\n let uv = (vec2f(cellX, cellY) + clamp(localUV, vec2f(0.0), vec2f(1.0))) / vec2f(3.0, 2.0);\n return textureSample(envAtlas, envAtlasSampler, uv).rgb;\n}\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${cn}\n${zn}\n${Tn}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${On(!0)}\n // A back face lights, reflects and rims as the face the camera sees.\n let N = normalize(fragmentInputs.vNormal) * select(-1.0, 1.0, fragmentInputs.frontFacing);\n#ifdef MESH_UNLIT\n var color = baseColor.rgb;\n#else\n let L = normalize(-uniforms.lightDirection);\n let NdotL = max(dot(N, L), 0.0);\n let litColor = uniforms.ambientColor + uniforms.lightColor * NdotL;\n\n var color = baseColor.rgb * litColor;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\n let viewDir = normalize(fragmentInputs.vWorldPos - uniforms.eyePosition);\n let reflectionCoords = reflect(viewDir, N);\n color += sampleEnvAtlas(reflectionCoords) * uniforms.reflectionLevel;\n#endif\n\n#ifdef MESH_RIM\n // Fresnel: strongest where the surface turns away from the camera.\n let V = normalize(uniforms.eyePosition - fragmentInputs.vWorldPos);\n let edgeTerm = pow(1.0 - abs(dot(N, V)), uniforms.rimParams.x);\n #if defined(MESH_RIM_FADE)\n // Faces turned to the camera fade by the strength; edges stay.\n baseColor.a *= clamp(1.0 - uniforms.rimParams.y * (1.0 - edgeTerm), 0.0, 1.0);\n #elif defined(MESH_RIM_MIX)\n color = mix(color, uniforms.rimColor, clamp(edgeTerm * uniforms.rimParams.y, 0.0, 1.0));\n #else\n color += uniforms.rimColor * edgeTerm * uniforms.rimParams.y;\n #endif\n#endif\n\n // After the rim, so a fade that empties a face can discard it.\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n var finalColor = vec4f(color, baseColor.a);\n\n${un("finalColor")}\n${_n("finalColor")}\n${bn("finalColor")}\n fragmentOutputs.color = finalColor;\n}\n`,Fn=`\n// Per-vertex attributes\nattribute vec3 position;\nattribute vec2 uv;\n\n// Per-instance attributes\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute float rotation;\nattribute float uvTile;\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${pn}\n\n#ifdef PIVOT\n// Quad offset in particle-size units: xy in the quad's plane, z toward the camera.\nuniform vec3 pivot;\n#endif\n\n// Varyings\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vec2 vUV1;\n#endif\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform vec2 sizeLimits;\n#endif\n${nn}\nvoid main() {\n float c = cos(rotation);\n float s = sin(rotation);\n\n#ifdef SIZE_LIMITS\n // The particle's size on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n vec4 limitCenter = view * world * vec4(offset, 1.0);\n float limitDepth = abs(projection[2][3]) > 0.0 ? abs(limitCenter.z) : 1.0;\n float screenSize = max(abs(size.x), abs(size.y)) * projection[1][1] / (2.0 * limitDepth);\n float sizeScale = screenSize > 0.0 ? clamp(screenSize, sizeLimits.x, sizeLimits.y) / screenSize : 1.0;\n vec3 limitedSize = size * sizeScale;\n#else\n vec3 limitedSize = size;\n#endif\n // A negative size mirrors the quad, which is how flipped particles arrive.\n vec2 alignedPosition = position.xy * limitedSize.xy;\n#ifdef PIVOT\n // The pivot turns with the particle but is not mirrored with it.\n alignedPosition += pivot.xy * abs(limitedSize.xy);\n#endif\n vec2 rotatedPosition;\n rotatedPosition.x = c * alignedPosition.x - s * alignedPosition.y;\n rotatedPosition.y = s * alignedPosition.x + c * alignedPosition.y;\n\n#ifdef HORIZONTAL\n vec4 mvPosition = world * vec4(offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.z -= rotatedPosition.y;\n#ifdef PIVOT\n mvPosition.y += pivot.z * abs(limitedSize.x);\n#endif\n mvPosition = view * mvPosition;\n#elif defined(VERTICAL)\n vec4 mvPosition = world * vec4(offset, 1.0);\n mvPosition.y += rotatedPosition.y;\n mvPosition = view * mvPosition;\n mvPosition.x += rotatedPosition.x;\n#else\n vec4 mvPosition = view * world * vec4(offset, 1.0);\n mvPosition.xy += rotatedPosition;\n#endif\n#ifdef PIVOT\n#ifndef HORIZONTAL\n // Toward the camera along its view axis, whichever way the view space\n // faces: anything in front of the camera has the sign of the far side.\n mvPosition.z -= sign(mvPosition.z) * pivot.z * abs(limitedSize.x);\n#endif\n#endif\n\n gl_Position = projection * mvPosition;\n${rn("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(mvPosition.z);\n#endif\n\n${mn("uv")}\n\n#ifdef UV1\n vUV1 = uv;\n#endif\n vColor = color;\n}\n`,In=`\n// Per-vertex attributes\nattribute position: vec3f;\nattribute uv: vec2f;\n\n// Per-instance attributes\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: f32;\nattribute uvTile: f32;\n\n// Uniforms\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${yn}\n\n#ifdef PIVOT\n// Quad offset in particle-size units: xy in the quad's plane, z toward the camera.\nuniform pivot: vec3f;\n#endif\n\n// Varyings\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vUV1: vec2f;\n#endif\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform sizeLimits: vec2f;\n#endif\n${hn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let c = cos(vertexInputs.rotation);\n let s = sin(vertexInputs.rotation);\n\n#ifdef SIZE_LIMITS\n // The particle's size on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n let limitCenter = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n let limitDepth = select(1.0, abs(limitCenter.z), abs(uniforms.projection[2][3]) > 0.0);\n let screenSize = max(abs(vertexInputs.size.x), abs(vertexInputs.size.y)) * uniforms.projection[1][1] / (2.0 * limitDepth);\n let sizeScale = select(1.0, clamp(screenSize, uniforms.sizeLimits.x, uniforms.sizeLimits.y) / screenSize, screenSize > 0.0);\n let limitedSize = vertexInputs.size * sizeScale;\n#else\n let limitedSize = vertexInputs.size;\n#endif\n // A negative size mirrors the quad, which is how flipped particles arrive.\n var alignedPosition = vertexInputs.position.xy * limitedSize.xy;\n#ifdef PIVOT\n // The pivot turns with the particle but is not mirrored with it.\n alignedPosition += uniforms.pivot.xy * abs(limitedSize.xy);\n#endif\n let rotatedPosition = vec2f(\n c * alignedPosition.x - s * alignedPosition.y,\n s * alignedPosition.x + c * alignedPosition.y);\n\n#ifdef HORIZONTAL\n var mvPosition = uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.z -= rotatedPosition.y;\n#ifdef PIVOT\n mvPosition.y += uniforms.pivot.z * abs(limitedSize.x);\n#endif\n mvPosition = uniforms.view * mvPosition;\n#elif defined(VERTICAL)\n var mvPosition = uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.y += rotatedPosition.y;\n mvPosition = uniforms.view * mvPosition;\n mvPosition.x += rotatedPosition.x;\n#else\n var mvPosition = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.y += rotatedPosition.y;\n#endif\n#ifdef PIVOT\n#ifndef HORIZONTAL\n // Toward the camera along its view axis, whichever way the view space\n // faces: anything in front of the camera has the sign of the far side.\n mvPosition.z -= sign(mvPosition.z) * uniforms.pivot.z * abs(limitedSize.x);\n#endif\n#endif\n\n let clipPosition = uniforms.projection * mvPosition;\n vertexOutputs.position = clipPosition;\n${ln("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(mvPosition.z);\n#endif\n\n${gn("vertexInputs.uv")}\n\n#ifdef UV1\n vertexOutputs.vUV1 = vertexInputs.uv;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`,Nn=`\n// Per-vertex attributes\nattribute vec3 position;\nattribute vec2 uv;\n\n// Per-instance attributes\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute float rotation;\nattribute float uvTile;\nattribute vec4 velocity;\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${pn}\n\n#ifdef PIVOT\n// Streak offset in particle-size units: x from head to tail, y across.\nuniform vec3 pivot;\n#endif\n\n// Varyings\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vec2 vUV1;\n#endif\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform vec2 sizeLimits;\n#endif\n\n${nn}\nvoid main() {\n float lengthFactor = velocity.w;\n // A flipped particle arrives with a negative size: the streak keeps its\n // extent and mirrors its texture instead (see quadUV below).\n float avgSize = (abs(size.x) + abs(size.y)) * 0.5;\n vec4 mvPosition = view * world * vec4(offset, 1.0);\n vec3 viewVelocity = mat3(view * world) * velocity.xyz;\n float vlength = length(viewVelocity);\n // Stretch direction is the velocity direction; only a genuinely motionless particle has none.\n // Deriving it via normalize keeps the stretch aligned even when the speed contribution is ~0\n // (e.g. a speed factor of 0), instead of collapsing the whole burst onto a fixed screen axis.\n vec3 vdir = vlength > 0.000001 ? viewVelocity / vlength : vec3(0.0, 0.0, 1.0);\n // Seen straight along its length a streak has no side to face; any will do.\n vec3 sideRaw = cross(mvPosition.xyz, vdir);\n vec3 side = dot(sideRaw, sideRaw) > 1e-12 ? normalize(sideRaw) : vec3(1.0, 0.0, 0.0);\n#ifdef SIZE_LIMITS\n // The streak's width on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n float limitDepth = abs(projection[2][3]) > 0.0 ? abs(mvPosition.z) : 1.0;\n float screenSize = avgSize * projection[1][1] / (2.0 * limitDepth);\n if (screenSize > 0.0) {\n avgSize *= clamp(screenSize, sizeLimits.x, sizeLimits.y) / screenSize;\n }\n#endif\n mvPosition.xyz += position.y * side * avgSize;\n#ifdef BEAM\n // The vector runs from the particle to the beam's end: the quad spans it\n // exactly, U from the particle (0) to the end (1), as wide as the size.\n mvPosition.xyz += (position.x + 0.5) * viewVelocity;\n#else\n // Equivalent to viewVelocity * (1.0 + lengthFactor / vlength) for moving particles, but the\n // size-based term (vdir * lengthFactor) survives when the velocity contribution vanishes.\n mvPosition.xyz -= (position.x + 0.5) * (viewVelocity + vdir * lengthFactor) * avgSize;\n#endif\n#ifdef PIVOT\n // In particle-size units along the quad's own axes: x from head to tail, y across.\n mvPosition.xyz += (pivot.y * side - pivot.x * vdir) * avgSize;\n#endif\n gl_Position = projection * mvPosition;\n${rn("mvPosition.xyz")}\n vec2 quadUV = vec2(size.x < 0.0 ? 1.0 - uv.x : uv.x, size.y < 0.0 ? 1.0 - uv.y : uv.y);\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(mvPosition.z);\n#endif\n\n${mn("quadUV")}\n\n#ifdef UV1\n vUV1 = quadUV;\n#endif\n vColor = color;\n}\n`,Bn=`\n// Per-vertex attributes\nattribute position: vec3f;\nattribute uv: vec2f;\n\n// Per-instance attributes\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: f32;\nattribute uvTile: f32;\nattribute velocity: vec4f;\n\n// Uniforms\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${yn}\n\n#ifdef PIVOT\n// Streak offset in particle-size units: x from head to tail, y across.\nuniform pivot: vec3f;\n#endif\n\n// Varyings\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vUV1: vec2f;\n#endif\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform sizeLimits: vec2f;\n#endif\n\n${hn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let lengthFactor = vertexInputs.velocity.w;\n // A flipped particle arrives with a negative size: the streak keeps its\n // extent and mirrors its texture instead (see quadUV below).\n var avgSize = (abs(vertexInputs.size.x) + abs(vertexInputs.size.y)) * 0.5;\n var mvPosition = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n let viewWorld = uniforms.view * uniforms.world;\n let viewWorld3 = mat3x3f(viewWorld[0].xyz, viewWorld[1].xyz, viewWorld[2].xyz);\n let viewVelocity = viewWorld3 * vertexInputs.velocity.xyz;\n let vlength = length(viewVelocity);\n // Stretch direction is the velocity direction; only a genuinely motionless particle has none.\n // Deriving it via normalize keeps the stretch aligned even when the speed contribution is ~0\n // (e.g. a speed factor of 0), instead of collapsing the whole burst onto a fixed screen axis.\n var vdir = vec3f(0.0, 0.0, 1.0);\n if (vlength > 0.000001) {\n vdir = viewVelocity / vlength;\n }\n // Seen straight along its length a streak has no side to face; any will do.\n let sideRaw = cross(mvPosition.xyz, vdir);\n var side = vec3f(1.0, 0.0, 0.0);\n if (dot(sideRaw, sideRaw) > 1e-12) {\n side = normalize(sideRaw);\n }\n#ifdef SIZE_LIMITS\n // The streak's width on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n let limitDepth = select(1.0, abs(mvPosition.z), abs(uniforms.projection[2][3]) > 0.0);\n let screenSize = avgSize * uniforms.projection[1][1] / (2.0 * limitDepth);\n if (screenSize > 0.0) {\n avgSize *= clamp(screenSize, uniforms.sizeLimits.x, uniforms.sizeLimits.y) / screenSize;\n }\n#endif\n let widthOffset = vertexInputs.position.y * side * avgSize;\n // Equivalent to viewVelocity * (1.0 + lengthFactor / vlength) for moving particles, but the\n // size-based term (vdir * lengthFactor) survives when the velocity contribution vanishes.\n#ifdef BEAM\n // The vector runs from the particle to the beam's end: the quad spans it\n // exactly, U from the particle (0) to the end (1), as wide as the size.\n var stretched = mvPosition.xyz + widthOffset + (vertexInputs.position.x + 0.5) * viewVelocity;\n#else\n let lengthOffset = (vertexInputs.position.x + 0.5) * (viewVelocity + vdir * lengthFactor) * avgSize;\n var stretched = mvPosition.xyz + widthOffset - lengthOffset;\n#endif\n#ifdef PIVOT\n // In particle-size units along the quad's own axes: x from head to tail, y across.\n stretched += (uniforms.pivot.y * side - uniforms.pivot.x * vdir) * avgSize;\n#endif\n mvPosition.x = stretched.x;\n mvPosition.y = stretched.y;\n mvPosition.z = stretched.z;\n\n let clipPosition = uniforms.projection * mvPosition;\n vertexOutputs.position = clipPosition;\n${ln("mvPosition.xyz")}\n let quadUV = select(vertexInputs.uv, 1.0 - vertexInputs.uv, vertexInputs.size.xy < vec2f(0.0));\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(mvPosition.z);\n#endif\n\n${gn("quadUV")}\n\n#ifdef UV1\n vertexOutputs.vUV1 = quadUV;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`,Un=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${on}\n${wn}\n${Vn}\nvoid main() {\n${An(!1)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${an("baseColor.rgb")}\n${Mn("baseColor")}\n${Sn("baseColor")}\n gl_FragColor = baseColor;\n}\n`,Rn=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${cn}\n${zn}\n${Tn}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${On(!1)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n${un("baseColor")}\n${_n("baseColor")}\n${bn("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,Dn=`\nattribute vec3 position;\nattribute vec3 previous;\nattribute vec3 next;\nattribute float side;\nattribute float width;\nattribute vec2 uv;\nattribute vec4 color;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// Along the trail and across it, without the sheet's cell (UV channel 1).\nattribute vec2 uv2;\nvarying vec2 vUV1;\n#endif\n\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n// The unit tangent of a segment, or zero for a segment of no length.\nvec3 trailDirection(vec3 d) {\n float l = dot(d, d);\n return l > 1e-12 ? d * inversesqrt(l) : vec3(0.0);\n}\n\n// The direction a ribbon point is widened along, in view space: across the trail's tangent and\n// the line of sight, as Unity's View alignment and Niagara's ribbon facing do. Stays finite at\n// repeated points, at a hairpin and for a segment pointing at the camera.\nvec3 trailSide(vec3 previousPoint, vec3 point, vec3 nextPoint) {\n vec3 incoming = trailDirection(point - previousPoint);\n vec3 outgoing = trailDirection(nextPoint - point);\n vec3 tangent = incoming + outgoing;\n if (dot(tangent, tangent) < 1e-6) {\n // A hairpin turns the two directions against each other: face the way it now goes.\n tangent = dot(outgoing, outgoing) > 0.0 ? outgoing : incoming;\n }\n // The line of sight: to the point for a perspective camera, the view axis for an orthographic one.\n vec3 sight = projection[3][3] > 0.5 ? vec3(0.0, 0.0, 1.0) : point;\n vec3 side = cross(tangent, sight);\n if (dot(side, side) < 1e-12) {\n side = cross(tangent, vec3(0.0, 0.0, 1.0));\n }\n if (dot(side, side) < 1e-12) {\n side = vec3(1.0, 0.0, 0.0);\n }\n return normalize(side);\n}\n\n${nn}\nvoid main() {\n vec3 point = (view * vec4(position, 1.0)).xyz;\n // A swept trail lays its vertices out on the CPU and gives them no width.\n if (width > 0.0) {\n vec3 previousPoint = (view * vec4(previous, 1.0)).xyz;\n vec3 nextPoint = (view * vec4(next, 1.0)).xyz;\n point += trailSide(previousPoint, point, nextPoint) * (0.5 * width * side);\n }\n gl_Position = projection * vec4(point, 1.0);\n${rn("point")}\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(point.z);\n#endif\n vUV = uv;\n#ifdef UV1\n vUV1 = uv2;\n#endif\n vColor = color;\n}\n`,Ln=`\nattribute position: vec3f;\nattribute previous: vec3f;\nattribute next: vec3f;\nattribute side: f32;\nattribute width: f32;\nattribute uv: vec2f;\nattribute color: vec4f;\n\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// Along the trail and across it, without the sheet's cell (UV channel 1).\nattribute uv2: vec2f;\nvarying vUV1: vec2f;\n#endif\n\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n// The unit tangent of a segment, or zero for a segment of no length.\nfn trailDirection(d: vec3f) -> vec3f {\n let l = dot(d, d);\n return select(vec3f(0.0), d * inverseSqrt(max(l, 1e-24)), l > 1e-12);\n}\n\n// The direction a ribbon point is widened along, in view space: across the trail's tangent and\n// the line of sight, as Unity's View alignment and Niagara's ribbon facing do. Stays finite at\n// repeated points, at a hairpin and for a segment pointing at the camera.\nfn trailSide(previousPoint: vec3f, point: vec3f, nextPoint: vec3f) -> vec3f {\n let incoming = trailDirection(point - previousPoint);\n let outgoing = trailDirection(nextPoint - point);\n var tangent = incoming + outgoing;\n if (dot(tangent, tangent) < 1e-6) {\n // A hairpin turns the two directions against each other: face the way it now goes.\n tangent = select(incoming, outgoing, dot(outgoing, outgoing) > 0.0);\n }\n // The line of sight: to the point for a perspective camera, the view axis for an orthographic one.\n let sight = select(point, vec3f(0.0, 0.0, 1.0), uniforms.projection[3][3] > 0.5);\n var side = cross(tangent, sight);\n if (dot(side, side) < 1e-12) {\n side = cross(tangent, vec3f(0.0, 0.0, 1.0));\n }\n if (dot(side, side) < 1e-12) {\n side = vec3f(1.0, 0.0, 0.0);\n }\n return normalize(side);\n}\n\n${hn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n var point = (uniforms.view * vec4f(vertexInputs.position, 1.0)).xyz;\n // A swept trail lays its vertices out on the CPU and gives them no width.\n if (vertexInputs.width > 0.0) {\n let previousPoint = (uniforms.view * vec4f(vertexInputs.previous, 1.0)).xyz;\n let nextPoint = (uniforms.view * vec4f(vertexInputs.next, 1.0)).xyz;\n point += trailSide(previousPoint, point, nextPoint) * (0.5 * vertexInputs.width * vertexInputs.side);\n }\n let clipPosition = uniforms.projection * vec4f(point, 1.0);\n vertexOutputs.position = clipPosition;\n${ln("point")}\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(point.z);\n#endif\n vertexOutputs.vUV = vertexInputs.uv;\n#ifdef UV1\n vertexOutputs.vUV1 = vertexInputs.uv2;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;const kn=["position","uv","offset","color","size","rotation","uvTile"],qn=["position","previous","next","side","width","uv","color"],Jn=["vFogInfos","vFogColor"];function Wn(t){return t===exports.RenderMode.StretchedBillBoard||t===exports.RenderMode.Beam}const Gn=new Set([r.Constants.ALPHA_SUBTRACT,r.Constants.ALPHA_MAXIMIZED,r.Constants.ALPHA_ONEONE,r.Constants.ALPHA_PREMULTIPLIED,r.Constants.ALPHA_PREMULTIPLIED_PORTERDUFF,r.Constants.ALPHA_SCREENMODE,r.Constants.ALPHA_ONEONE_ONEONE,r.Constants.ALPHA_ALPHATOCOLOR,r.Constants.ALPHA_REVERSEONEMINUS,r.Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA,r.Constants.ALPHA_ONEONE_ONEZERO,r.Constants.ALPHA_EXCLUSION,r.Constants.ALPHA_MAX]),Qn=new Set([r.Constants.ALPHA_MULTIPLY,r.Constants.ALPHA_MIN]),jn=new Set([r.Constants.ALPHA_COMBINE,r.Constants.ALPHA_PREMULTIPLIED,r.Constants.ALPHA_PREMULTIPLIED_PORTERDUFF,r.Constants.ALPHA_INTERPOLATE,r.Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA,r.Constants.ALPHA_LAYER_ACCUMULATE,r.Constants.ALPHA_REPLACE_COLOR]);function Hn(t){const e=t.materialBlendMode;if(!t.materialTransparent||e===r.Constants.ALPHA_DISABLE)return{output:"straight",fogTarget:"color"};const s=Gn.has(e)?"premultiply":Qn.has(e)?"multiply":"straight";return{output:s,fogTarget:"multiply"===s?"white":jn.has(e)||"straight"===s&&e!==r.Constants.ALPHA_ADD?"color":"black"}}function Yn(t,e){return t.renderMode===exports.RenderMode.Trail?function(t,e){const s=Xn(t),i=[...qn],n=["view","projection",...Jn],r=[];null!==t.texture&&(s.push("USE_MAP"),r.push("map"));Kn(t,s,n,r),Zn(t,e,s,n,r),Pi(t)&&i.push("uv2");return{name:"quarksTrail",vertex:{glsl:Dn,wgsl:Ln},fragment:{glsl:Un,wgsl:Rn},defines:s,attributes:i,uniforms:n,samplers:r}}(t,e):function(t,e){const s=t.renderMode,i=s===exports.RenderMode.Mesh,n=`quarksParticle_${s}`;let r,o;i?(r={glsl:vn,wgsl:xn},o={glsl:En,wgsl:Cn}):Wn(s)?(r={glsl:Nn,wgsl:Bn},o={glsl:Pn,wgsl:$n}):(r={glsl:Fn,wgsl:In},o={glsl:Pn,wgsl:$n});const a=Xn(t),h=[...kn],l=["world","view","projection",...Jn],c=[];(function(t){return null!==t.texture||t.renderMode===exports.RenderMode.Mesh})(t)&&(a.push("USE_MAP"),c.push("map"));const u=i&&null!==t.reflectionAtlas&&e.envAtlasReady;u&&(a.push("USE_ENVMAP_ATLAS"),c.push("envAtlas"),l.push("reflectionLevel"));Ji(t)&&(a.push("UV_TILE"),l.push("tileCountX","tileCountY"),t.blendTiles&&a.push("TILE_BLEND"));Zn(t,e,a,l,c),s===exports.RenderMode.VerticalBillBoard&&a.push("VERTICAL");s===exports.RenderMode.HorizontalBillBoard&&a.push("HORIZONTAL");s===exports.RenderMode.Beam&&a.push("BEAM");qi(s)&&(t.pivot&&(a.push("PIVOT"),l.push("pivot")),Wi(t)&&(a.push("SIZE_LIMITS"),l.push("sizeLimits")));const d=i&&"unlit"!==(t.lighting??"fixed");i&&!d&&a.push("MESH_UNLIT");d&&l.push("lightDirection","lightColor","ambientColor");const f=i?t.rim:void 0;f&&(a.push("MESH_RIM"),"fade"===f.mode?a.push("MESH_RIM_FADE"):"mix"===f.mode&&a.push("MESH_RIM_MIX"),l.push("rimColor","rimParams"));(u||f)&&l.push("eyePosition");Kn(t,a,l,c),i&&(h.push("normal"),Pi(t)&&e.meshUV2&&(a.push("MESH_UV2"),h.push("uv2")));Wn(s)&&h.push("velocity");return{name:n,vertex:r,fragment:o,defines:a,attributes:h,uniforms:l,samplers:c}}(t,e)}function Xn(t){const{output:e,fogTarget:s}=Hn(t),i=[];return"premultiply"===e?i.push("BLEND_PREMULTIPLY"):"multiply"===e&&i.push("BLEND_MULTIPLY"),t.applyFog&&(i.push("FOG"),"black"===s?i.push("FOG_ADDITIVE"):"white"===s&&i.push("FOG_MULTIPLY")),i}function Zn(t,e,s,i,n){t.softParticles&&null!==e.depth&&(s.push("SOFT_PARTICLES"),e.depth.packed&&s.push("SOFT_DEPTH_PACKED"),i.push("softParams","projParams"),n.push("depthTexture")),t.materialAlphaTest>0&&(s.push("USE_ALPHATEST"),i.push("alphaTest"))}function Kn(t,e,s,i){const{mapUV:n,uvDistortion:r,gradientMap:o,erosion:a}=t;Pi(t)&&e.push("UV1"),n&&(e.push("MAP_TRANSFORM"),1===n.channel&&e.push("MAP_UV1"),s.push("mapTransform")),r&&(e.push("UV_DISTORTION"),1===r.mapUV.channel&&e.push("UV_DISTORTION_UV1"),i.push("distortionMap"),s.push("distortionTransform","distortionStrength")),o&&(e.push("GRADIENT_MAP"),i.push("gradientMap"),s.push("gradientMapRange","gradientMapChannel")),a&&(e.push("EROSION"),s.push("erosionParams","erosionEdgeColor"),a.mask&&(e.push("EROSION_MASK"),1===a.maskUV.channel&&e.push("EROSION_MASK_UV1"),i.push("erosionMask"),s.push("erosionMaskTransform")))}function tr(t){return t.isWebGPU?m.ShaderLanguage.WGSL:m.ShaderLanguage.GLSL}function er(t,e,s,i){if(i===m.ShaderLanguage.WGSL)return f.ShaderStore.ShadersStoreWGSL[t+"VertexShader"]=e.wgsl,void(f.ShaderStore.ShadersStoreWGSL[t+"FragmentShader"]=s.wgsl);p.Effect.ShadersStore[t+"VertexShader"]=e.glsl,p.Effect.ShadersStore[t+"FragmentShader"]=s.glsl}class sr{constructor(t,e,s=null){this.parentNode=null,this.visibleSystems=[],this.boundsMin_=new et,this.boundsMax_=new et,this.time=0,this.underusedFills=0,this.scene=e,this.depth=s,this.maxParticles=0,this.systems=new Set,this.settings=Gi(t)}attachTo(t){this.parentNode=t,this.mesh.parent=t}configureMesh(){const t=this.mesh;t.alwaysSelectAsActiveMesh=!0,t.doNotSyncBoundingInfo=!0,t.parent=this.parentNode,t.freezeWorldMatrix(a.Matrix.Identity());const e=t.getWorldMatrix();t.computeWorldMatrix=()=>e,t.setBoundingInfo(new y.BoundingInfo(a.Vector3.Zero(),a.Vector3.Zero())),t.layerMask=this.settings.layerMask,t.renderingGroupId=this.settings.renderingGroupId,t.alphaIndex=this.settings.renderOrder,t.applyFog=!1,t.isPickable=!1,t.checkCollisions=!1,t.doNotSerialize=!0}refreshBoundingInfo(){const t=this.boundsMin_,e=this.boundsMax_;let s=1/0,i=1/0,n=1/0,r=-1/0,o=-1/0,a=-1/0,h=!1;const l=this.visibleSystems;for(let c=0;c<l.length;c++){const u=l[c];if(0!==u.particleNum&&"function"==typeof u.getWorldBounds){if(!u.getWorldBounds(t,e))return void(this.mesh.alwaysSelectAsActiveMesh=!0);h=!0,t.x<s&&(s=t.x),t.y<i&&(i=t.y),t.z<n&&(n=t.z),e.x>r&&(r=e.x),e.y>o&&(o=e.y),e.z>a&&(a=e.z)}}if(!h)return;const c=this.mesh.getBoundingInfo(),u=c.minimum,d=c.maximum;u.x===s&&u.y===i&&u.z===n&&d.x===r&&d.y===o&&d.z===a||(u.set(s,i,n),d.set(r,o,a),c.reConstruct(u,d)),this.mesh.alwaysSelectAsActiveMesh=!1}static writeBound(t,e){e(t);const s=t.getEffect();s?.isReady()&&e(s)}bindFog(t){if(!this.settings.applyFog)return;const e=this.scene;t.onBindObservable.add(()=>{const s=t.getEffect();if(!s)return;const i=e.fogEnabled?e.fogMode:v.Scene.FOGMODE_NONE;s.setFloat4("vFogInfos",i,e.fogStart,e.fogEnd,e.fogDensity),s.setColor3("vFogColor",e.fogColor)})}usesUV1(){return Pi(this.settings)}bindSurface(t){const{mapUV:e,uvDistortion:s,gradientMap:i,erosion:n}=this.settings;if(s?.map&&t.setTexture("distortionMap",s.map),i?.ramp&&t.setTexture("gradientMap",i.ramp),n?.mask&&t.setTexture("erosionMask",n.mask),this.writeSurfaceParams(t),!(e||s||n?.mask||i))return;const r=t=>t-2*Math.floor(t/2),o=new a.Vector4,h=new a.Vector4,l=new a.Vector4,c=new a.Vector2(0,1),u=(t,e,s)=>s.set(t.tiling[0],t.tiling[1],t.offset[0]+r(t.scroll[0]*e),t.offset[1]+r(t.scroll[1]*e)),d=()=>{const e=this.time,s=t.getEffect(),{mapUV:i,uvDistortion:n,gradientMap:r,erosion:a}=this.settings;if(i&&(u(i,e,o),t.setVector4("mapTransform",o),s?.setVector4("mapTransform",o)),n&&(u(n.mapUV,e,h),t.setVector4("distortionTransform",h),s?.setVector4("distortionTransform",h)),a?.mask&&(u(a.maskUV,e,l),t.setVector4("erosionMaskTransform",l),s?.setVector4("erosionMaskTransform",l)),r?.ramp){const e=r.ramp.getSize().width,i=e>0?.5/e:0;c.set(i,1-i),t.setVector2("gradientMapRange",c),s?.setVector2("gradientMapRange",c)}};d(),t.onBindObservable.add(d)}writeSurfaceParams(t){const{uvDistortion:e,gradientMap:s,erosion:i}=this.settings;if(e?.map&&t.setFloat("distortionStrength",e.strength),s?.ramp){const[e,i,n,r]=wi[s.channel];t.setVector4("gradientMapChannel",new a.Vector4(e,i,n,r))}i&&(t.setVector2("erosionParams",new a.Vector2(i.softness,i.edgeWidth)),t.setVector3("erosionEdgeColor",new a.Vector3(i.edgeColor[0],i.edgeColor[1],i.edgeColor[2])))}applyLiveSettings(t){Object.assign(this.settings,t);const e=this.mesh.material;e instanceof l.ShaderMaterial&&this.writeLiveUniforms(e)}writeLiveUniforms(t){this.writeSoftParams(t),this.writeSurfaceParams(t)}addSystem(t){this.systems.add(t)}removeSystem(t){this.systems.delete(t)}getVisibleSystems(){const t=this.visibleSystems;let e=0;for(const s of this.systems)s.emitter.visible&&!0!==s.culled&&(t[e++]=s);return t.length=e,t}applyDepthTexture(t){t instanceof g.BaseTexture&&(t={texture:t,encoding:"linear",packed:!1});const e=this.depth;if(this.depth=t,!this.settings.softParticles)return;if(!e!=!t||e?.packed!==t?.packed)return void this.rebuildMaterial();const s=this.mesh.material;t&&s instanceof l.ShaderMaterial&&s.setTexture("depthTexture",t.texture)}bindSoft(t){if(this.writeSoftParams(t),this.drawsSoft()){t.setTexture("depthTexture",this.depth.texture);const e=new a.Vector4(1,0,0,1);t.onBindObservable.add(()=>{const s=this.scene.activeCamera;s&&this.depth&&(Ki(s,this.depth.encoding,e),sr.writeBound(t,t=>t.setVector4("projParams",e)))})}}writeSoftParams(t){this.drawsSoft()&&t.setVector2("softParams",new a.Vector2(this.settings.softNearFade,1/Math.max(this.settings.softFarFade-this.settings.softNearFade,1e-4))),this.settings.materialAlphaTest>0&&t.setFloat("alphaTest",this.settings.materialAlphaTest)}drawsSoft(){return this.settings.softParticles&&null!==this.depth}applyMeshLighting(t){}fitBuffers(t){if(t>this.maxParticles)return this.underusedFills=0,void this.expandBuffers(t);this.maxParticles>this.initialCapacity&&t<this.maxParticles/4?++this.underusedFills>=sr.SHRINK_AFTER_FILLS&&(this.underusedFills=0,this.maxParticles=Math.max(this.initialCapacity,this.maxParticles/2),this.resizeBuffers()):this.underusedFills=0}dispose(){this.mesh.dispose()}}sr.SHRINK_AFTER_FILLS=300;class ir extends sr{static whiteTexture(t){let e=ir.whiteTextureByScene.get(t);if(!e){e=c.RawTexture.CreateRGBATexture(new Uint8Array([255,255,255,255]),1,1,t),e.name="quarksMeshWhite",ir.whiteTextureByScene.set(t,e);const s=e;e.onDisposeObservable.addOnce(()=>{ir.whiteTextureByScene.get(t)===s&&ir.whiteTextureByScene.delete(t)})}return e}constructor(t,e,s=null){super(t,e,s),this.shaderMaterial=null,this.cancelAtlasRebuild=null,this.disposed=!1,this.fixedLightDirection=new a.Vector3,this.fixedLightColor=new a.Vector3,this.fixedAmbientColor=new a.Vector3,this.warnedUV2=!1,this.initialCapacity=1e3,this.gatherScratch=[],this.vector_=new et,this.vector2_=new et,this.vector3_=new et,this.quaternion_=new tt,this.quaternion2_=new tt,this.quaternion3_=new tt,this.quaternion4_=new tt,this.quaternion5_=new tt,this.rotationMat_=new gt,this.rotationMat2_=new gt,this.clearedInstanceUploaded=!1,this.beamEnd_=new et,this.storeFixedLighting(gi()),this.maxParticles=this.initialCapacity,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh?.dispose(),this.mesh=new u.Mesh("spriteBatch",this.scene),this.configureMesh();const t=new d.VertexData;t.positions=this.settings.instancingGeometry,t.indices=this.settings.instancingIndices;const e=this.settings.instancingGeometry.length/3,s=this.settings.instancingUVs;s&&s.length>=2*e?t.uvs=s:t.uvs=new Float32Array(2*e),this.meshUV2()&&(t.uvs2=this.settings.instancingUVs2),this.settings.instancingNormals&&(t.normals=this.settings.instancingNormals),t.applyToMesh(this.mesh,!1),this.buildExpandableBuffers()}meshUV2(){const t=this.settings.instancingUVs2;if(this.settings.renderMode!==exports.RenderMode.Mesh||!t||!this.usesUV1())return!1;const e=this.settings.instancingGeometry.length/3*2;return t.length===e||(this.warnedUV2||(this.warnedUV2=!0,console.warn(`[babylon.quarks] instancingUVs2 has ${t.length} values for ${e/2} vertices (two per vertex expected); UV channel 1 reads the first UV set instead.`)),!1)}disposeExpandableBuffers(){this.offsetVB?.dispose(),this.colorVB?.dispose(),this.sizeVB?.dispose(),this.uvTileVB?.dispose(),this.rotationVB?.dispose(),this.velocityVB?.dispose(),this.velocityVB=void 0,this.velocityBuffer=void 0}buildExpandableBuffers(){const e=this.scene.getEngine();this.offsetBuffer=new Float32Array(3*this.maxParticles),this.offsetVB=new t.VertexBuffer(e,this.offsetBuffer,"offset",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.offsetVB),this.colorBuffer=new Float32Array(4*this.maxParticles),this.colorVB=new t.VertexBuffer(e,this.colorBuffer,"color",!0,!1,4,!0),this.mesh.setVerticesBuffer(this.colorVB),this.sizeBuffer=new Float32Array(3*this.maxParticles),this.sizeVB=new t.VertexBuffer(e,this.sizeBuffer,"size",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.sizeVB),this.uvTileBuffer=new Float32Array(this.maxParticles),this.uvTileVB=new t.VertexBuffer(e,this.uvTileBuffer,"uvTile",!0,!1,1,!0),this.mesh.setVerticesBuffer(this.uvTileVB),this.settings.renderMode===exports.RenderMode.Mesh?(this.rotationBuffer=new Float32Array(4*this.maxParticles),this.rotationVB=new t.VertexBuffer(e,this.rotationBuffer,"rotation",!0,!1,4,!0)):(this.rotationBuffer=new Float32Array(this.maxParticles),this.rotationVB=new t.VertexBuffer(e,this.rotationBuffer,"rotation",!0,!1,1,!0)),this.mesh.setVerticesBuffer(this.rotationVB),Wn(this.settings.renderMode)&&(this.velocityBuffer=new Float32Array(4*this.maxParticles),this.velocityVB=new t.VertexBuffer(e,this.velocityBuffer,"velocity",!0,!1,4,!0),this.mesh.setVerticesBuffer(this.velocityVB)),this.mesh.forcedInstanceCount=0,this.mesh.doNotSyncBoundingInfo=!0}expandBuffers(t){for(;t>=this.maxParticles;)this.maxParticles*=2;this.resizeBuffers()}resizeBuffers(){this.disposeExpandableBuffers(),this.buildExpandableBuffers(),this.sortScratch=void 0,this.gatherScratch.length=0}sizeLimits(){const{minParticleSize:t,maxParticleSize:e}=this.settings;return qi(this.settings.renderMode)&&Wi(this.settings)?new a.Vector2(Math.max(0,t),Math.min(e,1e9)):null}sortInstances(t,e,s){if(t<2)return;const i=this.sortScratch??(this.sortScratch=new sn(this.maxParticles));i.ensure(t);const n=i.keys,r=this.settings.sortMode;if("distance"===r){const e=this.scene.activeCameras?.[0]??this.scene.activeCamera;if(!e)return;const s=e.globalPosition,r=s.x,o=s.y,a=s.z,h=this.offsetBuffer;for(let e=0,s=0;e<t;e++,s+=3){const t=h[s]-r,l=h[s+1]-o,c=h[s+2]-a;n[e]=i.floatKey(t*t+l*l+c*c,!0)}}else{const e="youngestInFront"===r,s=this.visibleSystems;let o=0;for(let t=0;t<s.length;t++){const r=s[t],a=r.particleNum,h=r.store;if(0===a)continue;if(void 0===h){const t=r.particles;for(let s=0;s<a;s++)n[o++]=i.floatKey(t[s].age,e);continue}const l=h.scalars,c=Pe.SCALAR_STRIDE;for(let t=0,s=Pe.AGE;t<a;t++,s+=c)n[o++]=i.floatKey(l[s],e)}if(o!==t)return}const o=function(t,e){const s=t.keys,i=t.counts;let n=t.orderA,r=t.orderB;for(let t=0;t<e;t++)n[t]=t;for(let t=0;t<32;t+=11){i.fill(0);for(let r=0;r<e;r++)i[s[n[r]]>>>t&en]++;if(i[s[n[0]]>>>t&en]===e)continue;let o=0;for(let t=0;t<tn;t++){const e=i[t];i[t]=o,o+=e}for(let o=0;o<e;o++){const e=n[o];r[i[s[e]>>>t&en]++]=e}const a=n;n=r,r=a}return n}(i,t);this.offsetBuffer=this.gatherInto(0,this.offsetBuffer,o,t,3),this.sizeBuffer=this.gatherInto(1,this.sizeBuffer,o,t,3),this.colorBuffer=this.gatherInto(2,this.colorBuffer,o,t,4),this.uvTileBuffer=this.gatherInto(3,this.uvTileBuffer,o,t,1),this.rotationBuffer=this.gatherInto(4,this.rotationBuffer,o,t,e?4:1),s&&this.velocityBuffer&&(this.velocityBuffer=this.gatherInto(5,this.velocityBuffer,o,t,4))}gatherInto(t,e,s,i,n){let r=this.gatherScratch[t];return void 0!==r&&r.length===e.length||(r=new Float32Array(e.length)),function(t,e,s,i,n){if(1===n)for(let n=0;n<i;n++)e[n]=t[s[n]];else if(3===n)for(let n=0,r=0;n<i;n++,r+=3){const i=3*s[n];e[r]=t[i],e[r+1]=t[i+1],e[r+2]=t[i+2]}else if(4===n)for(let n=0,r=0;n<i;n++,r+=4){const i=4*s[n];e[r]=t[i],e[r+1]=t[i+1],e[r+2]=t[i+2],e[r+3]=t[i+3]}else for(let r=0;r<i;r++){const i=s[r]*n,o=r*n;for(let s=0;s<n;s++)e[o+s]=t[i+s]}}(e,r,s,i,n),this.gatherScratch[t]=e,r}rebuildMaterial(){const t=this.settings.renderMode===exports.RenderMode.Mesh,e=this.settings.texture??(t?ir.whiteTexture(this.scene):null),s=this.settings.reflectionAtlas,i=t&&!!s&&!s.isReady();if(this.cancelAtlasRebuild?.(),this.cancelAtlasRebuild=null,i&&s){const t=s.onLoadObservable;if(t){const e=t.addOnce(()=>{this.cancelAtlasRebuild=null,this.disposed||this.rebuildMaterial()});this.cancelAtlasRebuild=()=>t.remove(e)}}const n=this.usesEnvAtlas(),o=Yn(this.settings,{depth:this.depth,envAtlasReady:n,meshUV2:this.meshUV2()}),{defines:h,attributes:c,uniforms:u,samplers:d}=o,f=o.name,p=this.settings.lighting??"fixed",m=t&&"unlit"!==p,y=t?this.settings.rim:void 0,g=n||!!y,v=tr(this.scene.getEngine());er(f,o.vertex,o.fragment,v);const x=new l.ShaderMaterial(f,this.scene,{vertex:f,fragment:f},{attributes:c,uniforms:u,samplers:d,defines:h,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:v});if(e&&x.setTexture("map",e),n&&s&&x.setTexture("envAtlas",s),g){const t=new a.Vector3;x.setVector3("eyePosition",t),x.onBindObservable.add(()=>{const e=this.scene.activeCamera;e&&(t.copyFrom(e.globalPosition),sr.writeBound(x,e=>e.setVector3("eyePosition",t)))})}if(Ji(this.settings)&&(x.setFloat("tileCountX",this.settings.uTileCount),x.setFloat("tileCountY",this.settings.vTileCount)),this.bindSoft(x),this.writeSpriteParams(x,n),m&&(this.writeFixedLighting(x),"scene"===p)){const t=new a.Vector3,e=new a.Vector3,s=new a.Vector3;x.onBindObservable.add(()=>{const i=ir.readSceneLight(this.scene,t,e,s);sr.writeBound(x,n=>i?n.setVector3("lightDirection",t).setVector3("lightColor",e).setVector3("ambientColor",s):this.writeFixedLighting(n))})}this.bindFog(x),this.bindSurface(x),x.backFaceCulling="both"!==this.settings.renderFace,x.cullBackFaces="back"!==this.settings.renderFace,this.settings.materialTransparent?x.alphaMode=this.settings.materialBlendMode:x.alphaMode=r.Constants.ALPHA_DISABLE,x.needDepthPrePass=this.settings.materialDepthWrite&&this.settings.materialTransparent,x.forceDepthWrite=this.settings.materialDepthWrite,x.disableDepthWrite=!this.settings.materialDepthWrite,x.depthFunction=this.settings.materialDepthTest?0:r.Constants.ALWAYS,this.shaderMaterial?.dispose(!1,!1),this.mesh.material=x,this.shaderMaterial=x}writeSpriteParams(t,e){e&&t.setFloat("reflectionLevel",this.settings.reflectionLevel);const s=this.settings.renderMode===exports.RenderMode.Mesh?this.settings.rim:void 0;s&&(t.setVector3("rimColor",new a.Vector3(s.color[0],s.color[1],s.color[2])),t.setVector2("rimParams",new a.Vector2(s.power,s.strength)));const i=qi(this.settings.renderMode)?this.settings.pivot:void 0;i&&t.setVector3("pivot",new a.Vector3(i.x,i.y,i.z));const n=this.sizeLimits();n&&t.setVector2("sizeLimits",n)}writeLiveUniforms(t){super.writeLiveUniforms(t),this.writeSpriteParams(t,this.usesEnvAtlas())}usesEnvAtlas(){const t=this.settings.reflectionAtlas;return this.settings.renderMode===exports.RenderMode.Mesh&&!!t&&t.isReady()}applyMeshLighting(t){this.storeFixedLighting(t);const e=this.shaderMaterial;null!==e&&this.settings.renderMode===exports.RenderMode.Mesh&&"unlit"!==this.settings.lighting&&this.writeFixedLighting(e)}storeFixedLighting(t){this.fixedLightDirection.copyFrom(t.direction),this.fixedLightColor.set(t.color.r,t.color.g,t.color.b),this.fixedAmbientColor.set(t.ambient.r,t.ambient.g,t.ambient.b)}writeFixedLighting(t){t.setVector3("lightDirection",this.fixedLightDirection),t.setVector3("lightColor",this.fixedLightColor),t.setVector3("ambientColor",this.fixedAmbientColor)}static readSceneLight(t,e,s,i){const n=t.lights;for(let r=0;r<n.length;r++){const o=n[r],a=o.getClassName();if("DirectionalLight"!==a&&"HemisphericLight"!==a||!o.isEnabled())continue;const h=o.intensity,l=o.diffuse,c=t.ambientColor;s.set(l.r*h,l.g*h,l.b*h),i.set(c.r,c.g,c.b);const u=o.direction;if("DirectionalLight"===a)e.copyFrom(u);else{e.copyFrom(u).scaleInPlace(-1);const t=o.groundColor;t&&(i.x+=t.r*h,i.y+=t.g*h,i.z+=t.b*h)}return!0}return!1}update(){let t=0,e=0;const s=this.settings.renderMode,i=s===exports.RenderMode.Mesh,n=s===exports.RenderMode.StretchedBillBoard,r=s===exports.RenderMode.Beam,o=n||r,a=qi(s),h=this.getVisibleSystems();for(let t=0;t<h.length;t++)e+=h[t].particleNum;this.fitBuffers(e);for(let e=0;e<h.length;e++){const s=h[e],o=s.particleNum;if(0===o)continue;const l=s.particles,c=this.quaternion2_,u=this.vector2_,d=this.vector3_,f=s.worldSpace,p=s.emitter.matrixWorld;if(i&&!f)p.decompose(u,c,d);else{const t=p.elements;d.set(Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),Math.sqrt(t[4]*t[4]+t[5]*t[5]+t[6]*t[6]),Math.sqrt(t[8]*t[8]+t[9]*t[9]+t[10]*t[10]))}n&&!f&&this.rotationMat_.setFromMatrix4(p);const m=Math.abs(d.x),y=Math.abs(d.y),g=Math.abs(d.z),v=n?s.rendererEmitterSettings:void 0,x=void 0===v||0===v.speedFactor?.001:v.speedFactor,S=v?.lengthFactor??0,b=s.store,w=void 0!==b,M=void 0!==b&&!0!==s.onlyUsedByOther,z=s.simulationResidual??0,_=0===z?0:z/(s.simulationStep??z);w&&(0!==_&&o>0&&b.previousColor!==b.color?ir.continueColor(this.colorBuffer,4*t,b,o,_):this.colorBuffer.set(b.color.subarray(0,4*o),4*t));let V=!1;if(void 0!==b&&f)0!==_&&o>0?ir.extrapolate(this.offsetBuffer,3*t,b,o,_):this.offsetBuffer.set(b.position.subarray(0,3*o),3*t),0!==_&&o>0&&b.previousSize!==b.size?ir.continueVector3(this.sizeBuffer,3*t,b.size,b.previousSize,o,_):this.sizeBuffer.set(b.size.subarray(0,3*o),3*t),V=!0;else if(M&&o>0){const e=3*t,s=e+3*o,i=this.offsetBuffer;0!==_?ir.extrapolate(i,e,b,o,_):i.set(b.position.subarray(0,3*o),e);const n=p.elements,r=n[0],a=n[1],h=n[2],l=n[3],c=n[4],u=n[5],d=n[6],f=n[7],v=n[8],x=n[9],S=n[10],w=n[11],M=n[12],z=n[13],A=n[14],T=n[15];for(let t=e;t<s;t+=3){const e=i[t],s=i[t+1],n=i[t+2],o=1/(l*e+f*s+w*n+T);i[t]=(r*e+c*s+v*n+M)*o,i[t+1]=(a*e+u*s+x*n+z)*o,i[t+2]=(h*e+d*s+S*n+A)*o}const O=this.sizeBuffer;0!==_&&b.previousSize!==b.size?ir.continueVector3(O,e,b.size,b.previousSize,o,_):O.set(b.size.subarray(0,3*o),e);for(let t=e;t<s;t+=3)O[t]*=m,O[t+1]*=y,O[t+2]*=g;V=!0}const A=t;if(M&&!i){const e=b;this.uvTileBuffer.set(e.uvTile.subarray(0,o),A);const s=this.rotationBuffer;if(s.set(e.rotation.subarray(0,o),A),0!==z){const t=e.angularVelocity;for(let e=0;e<o;e++)s[A+e]+=t[e]*z}n&&this.velocityBuffer&&ir.writeVelocities(this.velocityBuffer,4*A,e,o,_,f?null:this.rotationMat_,x,S),t+=o}else if(M&&b.rotationQuaternion.length>0){const e=b;this.uvTileBuffer.set(e.uvTile.subarray(0,o),A),ir.writeQuaternions(this.rotationBuffer,4*A,e,o,_,f?null:c),t+=o}else for(let e=0;e<o;e++,t++){const s=l[e];if(i){let e=s.rotation;const i=s.angularVelocity;let n;if(0!==_&&i instanceof tt&&(e=this.quaternion4_.copy(e).multiply(ir.partialTurn(i,_,this.quaternion5_))),f)n=e;else{let t;t=s.parentMatrix?this.quaternion3_.setFromRotationMatrix(s.parentMatrix):c,n=this.quaternion_,n.copy(t).multiply(e)}const r=4*t;this.rotationBuffer[r]=n.x,this.rotationBuffer[r+1]=n.y,this.rotationBuffer[r+2]=n.z,this.rotationBuffer[r+3]=n.w}else{const e=s.angularVelocity;this.rotationBuffer[t]=s.rotation+("number"==typeof e?e*z:0)}if(!V){const e=s.position,i=s.previousPosition;let n=e.x+(e.x-i.x)*_,r=e.y+(e.y-i.y)*_,o=e.z+(e.z-i.z)*_;if(!f){const t=(s.parentMatrix??p).elements,e=1/(t[3]*n+t[7]*r+t[11]*o+t[15]),i=(t[0]*n+t[4]*r+t[8]*o+t[12])*e,a=(t[1]*n+t[5]*r+t[9]*o+t[13])*e;o=(t[2]*n+t[6]*r+t[10]*o+t[14])*e,n=i,r=a}const a=3*t;this.offsetBuffer[a]=n,this.offsetBuffer[a+1]=r,this.offsetBuffer[a+2]=o;const h=s.size,l=3*t;f||s.parentMatrix?(this.sizeBuffer[l]=h.x,this.sizeBuffer[l+1]=h.y,this.sizeBuffer[l+2]=h.z):(this.sizeBuffer[l]=h.x*m,this.sizeBuffer[l+1]=h.y*y,this.sizeBuffer[l+2]=h.z*g)}if(!w){const e=s.color,i=4*t;this.colorBuffer[i]=e.x,this.colorBuffer[i+1]=e.y,this.colorBuffer[i+2]=e.z,this.colorBuffer[i+3]=e.w}if(this.uvTileBuffer[t]=s.uvTile,n&&this.velocityBuffer){const e=s.velocity,i=s.previousVelocity,n=e.x+(e.x-i.x)*_,r=e.y+(e.y-i.y)*_,o=e.z+(e.z-i.z)*_,a=this.vector_;a.set(n,r,o),f||(s.parentMatrix?(this.rotationMat2_.setFromMatrix4(s.parentMatrix),a.applyMatrix3(this.rotationMat2_)):a.applyMatrix3(this.rotationMat_));const h=4*t;this.velocityBuffer[h]=a.x*x,this.velocityBuffer[h+1]=a.y*x,this.velocityBuffer[h+2]=a.z*x,this.velocityBuffer[h+3]=S}}const T=s.tint;void 0!==T&&t>A&&ir.applyTint(this.colorBuffer,4*A,t-A,T),a&&void 0!==s.flip&&(void 0!==b?ir.applyFlip(this.sizeBuffer,3*A,b.flip,o):ir.applyFlipFromParticles(this.sizeBuffer,3*A,l,o)),r&&this.velocityBuffer&&this.writeBeams(s,A,t-A)}this.mesh.forcedInstanceCount=t,this.refreshBoundingInfo(),0!==t?(this.clearedInstanceUploaded=!1,"none"!==this.settings.sortMode&&this.sortInstances(t,i,o),this.offsetVB.update(this.offsetBuffer.subarray(0,3*t)),this.sizeVB.update(this.sizeBuffer.subarray(0,3*t)),this.colorVB.update(this.colorBuffer.subarray(0,4*t)),this.uvTileVB.update(this.uvTileBuffer.subarray(0,t)),this.rotationVB.update(this.rotationBuffer.subarray(0,i?4*t:t)),o&&this.velocityVB&&this.velocityBuffer&&this.velocityVB.update(this.velocityBuffer.subarray(0,4*t))):this.clearedInstanceUploaded||(this.uploadClearedInstance(i,o),this.clearedInstanceUploaded=!0)}writeBeams(t,e,s){const i=this.velocityBuffer,n=this.offsetBuffer,r=this.beamEnd_,o="function"==typeof t.getBeamEnd&&t.getBeamEnd(r);for(let t=e;t<e+s;t++){const e=3*t,s=4*t;i[s]=o?r.x-n[e]:0,i[s+1]=o?r.y-n[e+1]:0,i[s+2]=o?r.z-n[e+2]:0,i[s+3]=0}}static applyTint(t,e,s,i){for(let n=0,r=e;n<s;n++,r+=4)t[r]*=i.x,t[r+1]*=i.y,t[r+2]*=i.z,t[r+3]*=i.w}static applyFlip(t,e,s,i){for(let n=0,r=e;n<i;n++,r+=3){const e=s[n];0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static applyFlipFromParticles(t,e,s,i){for(let n=0,r=e;n<i;n++,r+=3){const e=s[n].flip;0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static writeQuaternions(t,e,s,i,n,r){const o=s.rotationQuaternion,a=s.angularVelocityQuaternion,h=null!==r,l=h?r.x:0,c=h?r.y:0,u=h?r.z:0,d=h?r.w:1;for(let s=0,r=0,f=e;s<i;s++,r+=4,f+=4){let e=o[r],s=o[r+1],i=o[r+2],p=o[r+3];if(0!==n){const t=a[r]*n,o=a[r+1]*n,h=a[r+2]*n,l=1+(a[r+3]-1)*n,c=1/Math.sqrt(t*t+o*o+h*h+l*l),u=t*c,d=o*c,f=h*c,m=l*c,y=e*m+p*u+s*f-i*d,g=s*m+p*d+i*u-e*f,v=i*m+p*f+e*d-s*u;p=p*m-e*u-s*d-i*f,e=y,s=g,i=v}if(h){const t=l*p+d*e+c*i-u*s,n=c*p+d*s+u*e-l*i,r=u*p+d*i+l*s-c*e;p=d*p-l*e-c*s-u*i,e=t,s=n,i=r}t[f]=e,t[f+1]=s,t[f+2]=i,t[f+3]=p}}static writeVelocities(t,e,s,i,n,r,o,a){const h=s.velocity,l=s.previousVelocity.length>=3*i?s.previousVelocity:h,c=null!==r?r.elements:null;for(let s=0,r=0,u=e;s<i;s++,r+=3,u+=4){let e=h[r],s=h[r+1],i=h[r+2];if(0!==n&&(e+=(e-l[r])*n,s+=(s-l[r+1])*n,i+=(i-l[r+2])*n),null!==c){const t=c[0]*e+c[3]*s+c[6]*i,n=c[1]*e+c[4]*s+c[7]*i;i=c[2]*e+c[5]*s+c[8]*i,e=t,s=n}t[u]=e*o,t[u+1]=s*o,t[u+2]=i*o,t[u+3]=a}}static partialTurn(t,e,s){const i=t.x*e,n=t.y*e,r=t.z*e,o=1+(t.w-1)*e,a=1/Math.sqrt(i*i+n*n+r*r+o*o);return s.x=i*a,s.y=n*a,s.z=r*a,s.w=o*a,s}static continueVector3(t,e,s,i,n,r){for(let o=0,a=0;o<n;o++,a+=3){const n=s[a]+(s[a]-i[a])*r,o=s[a+1]+(s[a+1]-i[a+1])*r,h=s[a+2]+(s[a+2]-i[a+2])*r;t[e+a]=n>0?n:0,t[e+a+1]=o>0?o:0,t[e+a+2]=h>0?h:0}}static continueColor(t,e,s,i,n){const r=s.color,o=s.previousColor;for(let s=0,a=0;s<i;s++,a+=4){const s=r[a]+(r[a]-o[a])*n,i=r[a+1]+(r[a+1]-o[a+1])*n,h=r[a+2]+(r[a+2]-o[a+2])*n,l=r[a+3]+(r[a+3]-o[a+3])*n;t[e+a]=s>0?s:0,t[e+a+1]=i>0?i:0,t[e+a+2]=h>0?h:0,t[e+a+3]=l>0?l:0}}static extrapolate(t,e,s,i,n){const r=s.position,o=s.previousPosition;for(let s=0,a=0;s<i;s++,a+=3){const s=r[a],i=r[a+1],h=r[a+2];t[e+a]=s+(s-o[a])*n,t[e+a+1]=i+(i-o[a+1])*n,t[e+a+2]=h+(h-o[a+2])*n}}uploadClearedInstance(t,e){this.colorBuffer[3]=0,this.sizeBuffer[0]=0,this.sizeBuffer[1]=0,this.sizeBuffer[2]=0,this.colorVB.update(this.colorBuffer.subarray(0,4)),this.sizeVB.update(this.sizeBuffer.subarray(0,3)),this.offsetVB.update(this.offsetBuffer.subarray(0,3)),this.uvTileVB.update(this.uvTileBuffer.subarray(0,1)),t?this.rotationVB.update(this.rotationBuffer.subarray(0,4)):this.rotationVB.update(this.rotationBuffer.subarray(0,1)),e&&this.velocityVB&&this.velocityBuffer&&this.velocityVB.update(this.velocityBuffer.subarray(0,4))}dispose(){this.disposed=!0,this.cancelAtlasRebuild?.(),this.cancelAtlasRebuild=null,this.mesh.material&&this.mesh.material.dispose(),super.dispose()}}ir.whiteTextureByScene=new WeakMap;function nr(t){const e=Math.round(Number(t?.tessellation)||0);return Math.min(16,Math.max(0,e))}function rr(t){const e=Number(t?.curveTension)||0;return Math.min(1,Math.max(0,e))}const or=["stretch","tile","distributePerSegment","repeatPerSegment"];function ar(t){const e=t?.textureMode;return void 0!==e&&or.includes(e)?e:"stretch"}function hr(t){const e=Number(t?.textureScale);return Number.isFinite(e)&&e>0?e:1}function lr(t){const e=Number(t?.minVertexDistance);return Number.isFinite(e)&&e>0?e:0}function cr(t){const e=Number(t?.lifetime);return Number.isFinite(e)&&e>0?e:1/0}class ur{constructor(){this.position=new Float32Array(0),this.side=new Float32Array(0),this.size=new Float32Array(0),this.color=new Float32Array(0),this.distance=new Float32Array(0)}reserve(t){if(t>this.size.length){const e=Math.max(t,2*this.size.length,64);this.position=new Float32Array(3*e),this.side=new Float32Array(3*e),this.size=new Float32Array(e),this.color=new Float32Array(4*e),this.distance=new Float32Array(e)}return this}writePoint(t,e,s,i,n){const r=3*t;if(n){const t=1/(n[3]*e+n[7]*s+n[11]*i+n[15]);this.position[r]=(n[0]*e+n[4]*s+n[8]*i+n[12])*t,this.position[r+1]=(n[1]*e+n[5]*s+n[9]*i+n[13])*t,this.position[r+2]=(n[2]*e+n[6]*s+n[10]*i+n[14])*t}else this.position[r]=e,this.position[r+1]=s,this.position[r+2]=i}writeSide(t,e,s,i,n){const r=3*t;n?(this.side[r]=n[0]*e+n[4]*s+n[8]*i,this.side[r+1]=n[1]*e+n[5]*s+n[9]*i,this.side[r+2]=n[2]*e+n[6]*s+n[10]*i):(this.side[r]=e,this.side[r+1]=s,this.side[r+2]=i)}writeColor(t,e,s,i,n){const r=4*t;this.color[r]=e,this.color[r+1]=s,this.color[r+2]=i,this.color[r+3]=n}}function dr(t,e,s){return Math.sqrt(Math.sqrt((t[s]-t[e])**2+(t[s+1]-t[e+1])**2+(t[s+2]-t[e+2])**2))}class fr extends sr{constructor(t,e,s=null){super(t,e,s),this.uv1Buffer=null,this.drawsNothing=!1,this.initialCapacity=1024,this.vector2_=new et,this.vector3_=new et,this.quaternion_=new tt,this.samples_=new ur,this.curve_=new ur,this.cutScratch_=new ur,this.maxParticles=this.initialCapacity,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh?.dispose(),this.mesh=new u.Mesh("trailBatch",this.scene),this.configureMesh(),this.buildGeometryBuffers()}buildGeometryBuffers(){const e=this.maxParticles;this.positionBuffer=new Float32Array(3*e),this.previousBuffer=new Float32Array(3*e),this.nextBuffer=new Float32Array(3*e),this.uvBuffer=new Float32Array(2*e),this.uv1Buffer=this.usesUV1()?new Float32Array(2*e):null,this.sideBuffer=new Float32Array(e),this.widthBuffer=new Float32Array(e),this.colorBuffer=new Float32Array(4*e),this.indexBuffer=new Uint32Array(3*e);for(let t=0;t<this.sideBuffer.length;t+=2)this.sideBuffer[t]=1,this.sideBuffer[t+1]=-1;this.positionBuffer[0]=0,this.positionBuffer[1]=0,this.positionBuffer[2]=0,this.positionBuffer[3]=1,this.positionBuffer[4]=0,this.positionBuffer[5]=0,this.positionBuffer[6]=0,this.positionBuffer[7]=1,this.positionBuffer[8]=0,this.positionBuffer[9]=1,this.positionBuffer[10]=1,this.positionBuffer[11]=0,this.indexBuffer[0]=0,this.indexBuffer[1]=1,this.indexBuffer[2]=2,this.indexBuffer[3]=1,this.indexBuffer[4]=3,this.indexBuffer[5]=2,this.mesh.setVerticesData(t.VertexBuffer.PositionKind,this.positionBuffer,!0),this.mesh.setVerticesData(t.VertexBuffer.UVKind,this.uvBuffer,!0),this.uv1Buffer&&this.mesh.setVerticesData(t.VertexBuffer.UV2Kind,this.uv1Buffer,!0),this.mesh.setVerticesData(t.VertexBuffer.ColorKind,this.colorBuffer,!0,4),this.mesh.setIndices(this.indexBuffer,null,!0),this.drawsNothing=!1,this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.mesh.subMeshes[0].indexCount=6);const s=this.scene.getEngine();this.previousVB=new t.VertexBuffer(s,this.previousBuffer,"previous",!0,!1,3,!1),this.nextVB=new t.VertexBuffer(s,this.nextBuffer,"next",!0,!1,3,!1),this.sideVB=new t.VertexBuffer(s,this.sideBuffer,"side",!0,!1,1,!1),this.widthVB=new t.VertexBuffer(s,this.widthBuffer,"width",!0,!1,1,!1),this.mesh.setVerticesBuffer(this.previousVB),this.mesh.setVerticesBuffer(this.nextVB),this.mesh.setVerticesBuffer(this.sideVB),this.mesh.setVerticesBuffer(this.widthVB),this.mesh.subMeshes&&this.adoptMeshBounds()}expandBuffers(t){for(;t>=this.maxParticles;)this.maxParticles*=2;this.resizeBuffers()}resizeBuffers(){this.previousVB?.dispose(),this.nextVB?.dispose(),this.sideVB?.dispose(),this.widthVB?.dispose(),this.buildGeometryBuffers()}rebuildMaterial(){const t=Yn(this.settings,{depth:this.depth,envAtlasReady:!1,meshUV2:!1}),{defines:e,attributes:s,uniforms:i,samplers:n}=t,o=t.name,a=tr(this.scene.getEngine());er(o,t.vertex,t.fragment,a);const h=new l.ShaderMaterial(o,this.scene,{vertex:o,fragment:o},{attributes:s,uniforms:i,samplers:n,defines:e,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:a});this.settings.texture&&h.setTexture("map",this.settings.texture),this.bindFog(h),this.bindSoft(h),this.bindSurface(h),h.backFaceCulling=!1,this.settings.materialTransparent?h.alphaMode=this.settings.materialBlendMode:h.alphaMode=r.Constants.ALPHA_DISABLE,h.needDepthPrePass=this.settings.materialDepthWrite&&this.settings.materialTransparent,h.forceDepthWrite=this.settings.materialDepthWrite,h.disableDepthWrite=!this.settings.materialDepthWrite,h.depthFunction=this.settings.materialDepthTest?0:r.Constants.ALWAYS,this.mesh.material?.dispose(!1,!1),this.mesh.material=h}trailSamples(t){return this.samples_.reserve(t)}cutLastSegment(t,e,s,i,n){const r=e-1-s,o=this.cutScratch_.reserve(s+1);o.position.set(t.position.subarray(3*r,3*e)),o.side.set(t.side.subarray(3*r,3*e)),o.size.set(t.size.subarray(r,e)),o.color.set(t.color.subarray(4*r,4*e)),o.distance.set(t.distance.subarray(r,e));for(let e=1;e<=s;e++){const a=i*e,h=Math.min(s-1,Math.floor(a)),l=a-h,c=r+e;for(let e=0;e<3;e++)t.position[3*c+e]=o.position[3*h+e]*(1-l)+o.position[3*h+3+e]*l,n&&(t.side[3*c+e]=o.side[3*h+e]*(1-l)+o.side[3*h+3+e]*l);t.size[c]=o.size[h]*(1-l)+o.size[h+1]*l,t.distance[c]=o.distance[h]*(1-l)+o.distance[h+1]*l;for(let e=0;e<4;e++)t.color[4*c+e]=o.color[4*h+e]*(1-l)+o.color[4*h+4+e]*l}}tessellate(t,e,s,i,n,r){const o=this.curve_.reserve((s-1)*(i+1)+1),a=t.position,h=t.side,l=o.position,c=o.side,u=1-n;let d=0;for(let n=0;n+1<s;n++){const s=3*n,f=s+3;let p=0,m=0,y=0,g=0,v=0,x=0,S=s,b=f;if(n+1<e){S=3*(n>0?n-1:n),b=3*(n+2<e?n+2:n+1);const t=dr(a,s,f);if(t>1e-6){const e=dr(a,S,s),i=dr(a,f,b);y=u,g=u,e>1e-6&&(p=u*t/e,m=-u*t/(e+t)),i>1e-6&&(v=-u*t/(t+i),x=u*t/i)}}const w=0===p&&0===m&&0===y&&0===g&&0===v&&0===x,M=r?Math.sqrt(h[s]*h[s]+h[s+1]*h[s+1]+h[s+2]*h[s+2]):0,z=r?Math.sqrt(h[f]*h[f]+h[f+1]*h[f+1]+h[f+2]*h[f+2]):0;for(let e=0;e<=i;e++,d++){const u=e/(i+1),_=u*u,V=_*u,A=w?1-u:2*V-3*_+1,T=V-2*_+u,O=w?u:-2*V+3*_,P=V-_,$=3*d;for(let t=0;t<3;t++){const e=a[s+t],i=a[f+t],n=p*(e-a[S+t])+m*(i-a[S+t])+y*(i-e),r=g*(i-e)+v*(a[b+t]-e)+x*(a[b+t]-i);l[$+t]=A*e+T*n+O*i+P*r}if(r){let t=0,e=0,i=0;for(let n=0;n<3;n++){const r=h[s+n],o=h[f+n],a=A*r+T*(p*(r-h[S+n])+m*(o-h[S+n])+y*(o-r))+O*o+P*(g*(o-r)+v*(h[b+n]-r)+x*(h[b+n]-o));0===n?t=a:1===n?e=a:i=a}let n=Math.sqrt(t*t+e*e+i*i);if(n<=1e-6*Math.max(M,z,1e-6)){const r=u<.5?s:f;t=h[r],e=h[r+1],i=h[r+2],n=u<.5?M:z}const r=n>0?(M+(z-M)*u)/n:0;c[$]=t*r,c[$+1]=e*r,c[$+2]=i*r}o.size[d]=t.size[n]+(t.size[n+1]-t.size[n])*u,o.distance[d]=t.distance[n]+(t.distance[n+1]-t.distance[n])*u;const E=4*n,C=4*d;for(let e=0;e<4;e++)o.color[C+e]=t.color[E+e]+(t.color[E+4+e]-t.color[E+e])*u}}const f=3*(s-1),p=3*d;for(let t=0;t<3;t++)l[p+t]=a[f+t],c[p+t]=h[f+t];o.size[d]=t.size[s-1],o.distance[d]=t.distance[s-1];for(let e=0;e<4;e++)o.color[4*d+e]=t.color[4*(s-1)+e];return o}writeSweptPair(t,e,s,i,n,r,o,a){const h=this.positionBuffer;h[t]=e+n*a,h[t+1]=s+r*a,h[t+2]=i+o*a,h[t+3]=e-n*a,h[t+4]=s-r*a,h[t+5]=i-o*a}static ensureWorldMatrix(t){const e=t.emitter;!e.computeWorldMatrix||e.isSynchronized&&e.isSynchronized()||e.computeWorldMatrix(!0)}update(){let t=0,e=0,s=0;const i=this.getVisibleSystems();for(let t=0;t<i.length;t++){const e=i[t],n=e.particles,r=nr(e.rendererEmitterSettings);for(let t=0;t<e.particleNum;t++){const e=n[t].historyCount;0!==e&&(s+=2*(e*(r+1)+1))}}this.fitBuffers(s);for(let s=0;s<i.length;s++){const n=i[s],r=t;fr.ensureWorldMatrix(n);const o=this.quaternion_,a=this.vector2_,h=this.vector3_,l=n.emitter.matrixWorld;l.decompose(a,o,h);const c=n.particles,u=n.particleNum,d=this.settings.uTileCount,f=this.settings.vTileCount,p=1/d,m=1/f,y=n.worldSpace,g=(Math.abs(h.x)+Math.abs(h.y)+Math.abs(h.z))/3,v=n.rendererEmitterSettings,x=Boolean(v.uvFromHead),S=this.uv1Buffer,b=Boolean(v.colorFromParticle),w=y||Boolean(v.recordWorldSpace),M=v.sideAxis,z=v.followLocalOrigin?0:n.simulationResidual??0,_=0===z?0:z/(n.simulationStep??z),V=Math.abs(_)<1e-4?0:_,A=nr(v),T=rr(v),O=ar(v),P="stretch"===O?0:"tile"===O?1:"repeatPerSegment"===O?3:2,$=hr(v),E=lr(v)>0;for(let s=0;s<u;s++){const i=c[s],n=i.historyCount;if(0===n)continue;const r=i.historyCapacity,o=i.historyPositions,a=i.historySizes,h=i.historyDistances,u=i.historySides,v=void 0!==M&&u.length>=3*r,z=b?i.store.color:i.historyColors,_=4*i.storeIndex,{column:O,row:C}=dn(i.uvTile,d,f),F=(i.parentMatrix??l).elements,I=y||i.parentMatrix?1:g,N=w||i.parentMatrix?1:g,B=i.age<i.life,U=B&&V>0,R=n+(U?1:0),D=this.trailSamples(R);let L=i.getHistoryIndex(0);for(let t=0;t<n;t++){const e=o;if(D.writePoint(t,e[3*L],e[3*L+1],e[3*L+2],w?null:F),v){const e=u;D.writeSide(t,e[3*L],e[3*L+1],e[3*L+2],w?null:F)}D.size[t]=a[L],D.distance[t]=h[L];const s=b?_:4*L;D.writeColor(t,z[s],z[s+1],z[s+2],z[s+3]),L=L+1===r?0:L+1}if(U){const t=i.previousPosition,e=i.position,s=n;let r=e.x+(e.x-t.x)*V,a=e.y+(e.y-t.y)*V,h=e.z+(e.z-t.z)*V;if(D.writePoint(s,r,a,h,y?null:F),w&&!y){const t=1/(F[3]*r+F[7]*a+F[11]*h+F[15]),e=(F[0]*r+F[4]*a+F[8]*h+F[12])*t,s=(F[1]*r+F[5]*a+F[9]*h+F[13])*t;h=(F[2]*r+F[6]*a+F[10]*h+F[14])*t,r=e,a=s}const l=3*i.getHistoryIndex(n-1),c=r-o[l],u=a-o[l+1],d=h-o[l+2];D.distance[s]=D.distance[s-1]+Math.sqrt(c*c+u*u+d*d),v&&D.writeSide(s,M.x,M.y,M.z,F),D.size[s]=D.size[s-1];const f=i.color;D.writeColor(s,f.x,f.y,f.z,f.w)}const k=A>0?this.tessellate(D,n,R,A,T,v):D,q=A>0?(R-1)*(A+1)+1:R,J=A+1,W=B&&V<0&&n>1;let G=1+V;if(W&&E){const t=k.distance,e=t[q-1]-t[q-1-J];if(e>1e-9){const t=i.previousPosition,s=i.position;let n=s.x-t.x,r=s.y-t.y,o=s.z-t.z;if(w&&!y){const t=F[0]*n+F[4]*r+F[8]*o,e=F[1]*n+F[5]*r+F[9]*o;o=F[2]*n+F[6]*r+F[10]*o,n=t,r=e}const a=Math.sqrt(n*n+r*r+o*o);G=1+V*Math.min(1,a/e)}}W&&this.cutLastSegment(k,q,J,G,v);const Q=n-1+(U?V:W?G-1:0),j=1/Math.max(.001,Q),H=(R-2)*J,Y=k.position,X=k.distance,Z=X[0],K=X[q-1],tt=0===P&&K-Z>1e-6,et=1/Math.max(1e-6,K-Z),st=N*$,it=Math.floor(Z*st),nt=(f-C-1)*m,rt=(f-C)*m;for(let s=0;s<q;s++,t+=2){const i=3*s,r=s>0?i-3:i,o=s+1<q?i+3:i,a=Y[i],h=Y[i+1],l=Y[i+2],c=k.size[s],u=3*t;if(v){const e=k.side;this.writeSweptPair(u,a,h,l,e[i],e[i+1],e[i+2],.5*c),this.widthBuffer[t]=0,this.widthBuffer[t+1]=0}else this.positionBuffer[u]=a,this.positionBuffer[u+1]=h,this.positionBuffer[u+2]=l,this.positionBuffer[u+3]=a,this.positionBuffer[u+4]=h,this.positionBuffer[u+5]=l,this.widthBuffer[t]=c*I,this.widthBuffer[t+1]=c*I;this.previousBuffer[u]=Y[r],this.previousBuffer[u+1]=Y[r+1],this.previousBuffer[u+2]=Y[r+2],this.previousBuffer[u+3]=Y[r],this.previousBuffer[u+4]=Y[r+1],this.previousBuffer[u+5]=Y[r+2],this.nextBuffer[u]=Y[o],this.nextBuffer[u+1]=Y[o+1],this.nextBuffer[u+2]=Y[o+2],this.nextBuffer[u+3]=Y[o],this.nextBuffer[u+4]=Y[o+1],this.nextBuffer[u+5]=Y[o+2];const d=2*t;let f;if(tt){const t=(X[s]-Z)*et;f=(x?1-t:t)*$}else if(1===P)f=x?(K-X[s])*st:X[s]*st-it;else{let t=s/J;if(s>H&&(U||W)){const e=(s-H)/J;t=U?n-1+V*e:n-2+G*e}if(3!==P){const e=Math.min(1,t*j);f=(x?1-e:e)*$}else f=(x?Q-t:t)*$}const m=(f+O)*p;this.uvBuffer[d]=m,this.uvBuffer[d+1]=nt,this.uvBuffer[d+2]=m,this.uvBuffer[d+3]=rt,S&&(S[d]=f,S[d+1]=0,S[d+2]=f,S[d+3]=1);const y=k.color,g=4*s,b=4*t;this.colorBuffer[b]=y[g],this.colorBuffer[b+1]=y[g+1],this.colorBuffer[b+2]=y[g+2],this.colorBuffer[b+3]=y[g+3],this.colorBuffer[b+4]=y[g],this.colorBuffer[b+5]=y[g+1],this.colorBuffer[b+6]=y[g+2],this.colorBuffer[b+7]=y[g+3],s+1<q&&(this.indexBuffer[3*e]=t,this.indexBuffer[3*e+1]=t+1,this.indexBuffer[3*e+2]=t+2,e++,this.indexBuffer[3*e]=t+2,this.indexBuffer[3*e+1]=t+1,this.indexBuffer[3*e+2]=t+3,e++)}}const C=n.tint;if(void 0!==C){const e=this.colorBuffer;for(let s=4*r,i=4*t;s<i;s+=4)e[s]*=C.x,e[s+1]*=C.y,e[s+2]*=C.z,e[s+3]*=C.w}this.measureSystemBounds(n,r,t)}this.refreshBoundingInfo(),this.uploadGeometry(t,e)}measureSystemBounds(t,e,s){if(s<=e||"function"!=typeof t.setWorldBounds)return;const i=this.positionBuffer;let n=1/0,r=1/0,o=1/0,a=-1/0,h=-1/0,l=-1/0;for(let t=3*e,c=3*s;t<c;t+=3){const e=i[t],s=i[t+1],c=i[t+2];e<n&&(n=e),e>a&&(a=e),s<r&&(r=s),s>h&&(h=s),c<o&&(o=c),c>l&&(l=c)}const c=this.widthBuffer;let u=0;for(let t=e;t<s;t+=2){const e=c[t];e>u&&(u=e)}t.setWorldBounds(n,r,o,a,h,l,u)}uploadGeometry(e,s){const i=this.mesh.geometry,n=i?.getIndexBuffer();if(e>0&&s>0){this.mesh.updateVerticesData(t.VertexBuffer.PositionKind,this.positionBuffer.subarray(0,3*e)),this.mesh.updateVerticesData(t.VertexBuffer.UVKind,this.uvBuffer.subarray(0,2*e)),this.uv1Buffer&&this.mesh.updateVerticesData(t.VertexBuffer.UV2Kind,this.uv1Buffer.subarray(0,2*e)),n&&this.scene.getEngine().updateDynamicIndexBuffer(n,this.indexBuffer.subarray(0,3*s),0),this.previousVB.update(this.previousBuffer.subarray(0,3*e)),this.nextVB.update(this.nextBuffer.subarray(0,3*e)),this.widthVB.update(this.widthBuffer.subarray(0,e));const i=this.mesh.getVertexBuffer(t.VertexBuffer.ColorKind);i&&i.update(this.colorBuffer.subarray(0,4*e)),this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.mesh.subMeshes[0].indexCount=3*s,this.mesh.subMeshes[0].verticesCount=e),this.drawsNothing=!1}else this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.drawsNothing||(this.indexBuffer.fill(0,0,6),n&&this.scene.getEngine().updateDynamicIndexBuffer(n,this.indexBuffer.subarray(0,6),0),this.drawsNothing=!0),this.mesh.subMeshes[0].indexCount=6,this.mesh.subMeshes[0].verticesCount=1)}adoptMeshBounds(){const t=this.mesh.getBoundingInfo();for(const e of this.mesh.subMeshes)e.setBoundingInfo(t)}dispose(){this.mesh.material&&this.mesh.material.dispose(),super.dispose()}}class pr extends n.TransformNode{get batches(){return this.batchList}get systemToBatchIndex(){return this.batchIndexOf}constructor(t,e){super(t,e),this.batchList=[],this.batchIndexOf=new Map,this.elapsed=0,this.depth=null,this.systems=[],this.orderedSystems=[],this.orderedSystemsStale=!0,this.batchEmptyFrames=[],this.adaptivePerformanceState={enabled:!1,targetFrameMs:16.7,minQuality:.35,maxQuality:1,decreaseStep:.08,increaseStep:.02,currentQuality:1,lastFrameCpuMs:0},this.lastAppliedQuality=Number.NaN,this.meshLighting=gi(),this.cullingEnabled=!0,this.catchUpBudgetMs=2,this.simulationBudgetMs=1/0,this.cameraPlanes=[],this.cameraMasks=[],this.cameraCount=0,this.boundsMin=new et,this.boundsMax=new et}collectCameras(){var t;const e=this.getScene(),n=e.activeCameras,r=e.activeCamera,o=n&&n.length>0?n:r?[r]:[];for(let e=0;e<o.length;e++){const n=o[e];n.getViewMatrix(),n.getProjectionMatrix();const r=(t=this.cameraPlanes)[e]??(t[e]=[0,1,2,3,4,5].map(()=>new i.Plane(0,0,0,0)));s.Frustum.GetPlanesToRef(n.getTransformationMatrix(),r),this.cameraMasks[e]=n.layerMask}return this.cameraCount=o.length,o.length}isSystemInView(t){const e=this.boundsMin,s=this.boundsMax;if(!t.getWorldBounds(e,s))return!0;const i=t.layers.mask;for(let t=0;t<this.cameraCount;t++){if(0===(this.cameraMasks[t]&i))continue;const n=this.cameraPlanes[t];let r=!0;for(let t=0;t<6;t++){const i=n[t],o=i.normal,a=o.x>=0?s.x:e.x,h=o.y>=0?s.y:e.y,l=o.z>=0?s.z:e.z;if(o.x*a+o.y*h+o.z*l+i.d<0){r=!1;break}}if(r)return!0}return!1}static clamp(t,e,s){return Math.max(e,Math.min(s,t))}addSystem(t){if(this.isDisposed())throw new Error("BatchedRenderer.addSystem: the renderer has been disposed");const e=t;if(e.emitter.getScene()!==this.getScene())throw new Error("BatchedRenderer.addSystem: the system belongs to another scene");const s=e._renderer;void 0!==s&&s!==this&&s.deleteSystem(t),e._renderer=this,this.removeFromBatch(t),-1===this.systems.indexOf(t)&&(this.systems.push(t),this.orderedSystemsStale=!0),this.adaptivePerformanceState.enabled&&e.setQualityFactor(this.adaptivePerformanceState.currentQuality),this.assignToBatch(e)}assignToBatch(t){const e=t,s=t.getRendererSettings(),i=Gi(s);for(let t=0;t<this.batchList.length;t++)if(Hi(this.batchList[t].settings,i))return this.batchList[t].addSystem(e),void this.batchIndexOf.set(e,t);let n;const r=this.getScene();switch(s.renderMode){case exports.RenderMode.Trail:n=new fr(s,r,this.depth);break;case exports.RenderMode.Mesh:case exports.RenderMode.BillBoard:case exports.RenderMode.VerticalBillBoard:case exports.RenderMode.HorizontalBillBoard:case exports.RenderMode.StretchedBillBoard:case exports.RenderMode.Beam:n=new ir(s,r,this.depth);break;default:throw new Error(`Unsupported render mode: ${s.renderMode}`)}n.attachTo(this),n.applyMeshLighting(this.meshLighting),n.addSystem(e),this.batchList.push(n),this.batchEmptyFrames.push(0),this.batchIndexOf.set(e,this.batchList.length-1)}deleteSystem(t){const e=this.removeFromBatch(t),s=this.systems.indexOf(t);-1!==s&&(this.systems.splice(s,1),this.orderedSystemsStale=!0);const i=this.orderedSystems.indexOf(t);return-1!==i&&this.orderedSystems.splice(i,1),e}removeFromBatch(t){const e=this.batchIndexOf.get(t);return void 0!==e&&(this.batchList[e].removeSystem(t),this.batchIndexOf.delete(t),!0)}updateSystem(t){const e=this.batchIndexOf.get(t);if(void 0!==e){const s=this.batchList[e],i=Gi(t.getRendererSettings());if(1===s.systems.size&&Qi(s.settings,i)&&!this.batchList.some(t=>t!==s&&Hi(t.settings,i)))return void s.applyLiveSettings(i)}this.removeFromBatch(t),this.addSystem(t)}setDepthTexture(t,e={}){this.depth=t?Zi(t,e):null;for(const t of this.batchList)t.applyDepthTexture(this.depth)}get depthTexture(){return this.depth?.texture??null}set depthTexture(t){this.setDepthTexture(t)}get depthEncoding(){return this.depth?.encoding??null}setMeshLighting(t){const e=this.meshLighting;t.direction&&(e.direction=t.direction.clone()),t.color&&(e.color=t.color.clone()),t.ambient&&(e.ambient=t.ambient.clone());for(const t of this.batchList)t.applyMeshLighting(e)}getMeshLighting(){const t=this.meshLighting;return{direction:t.direction.clone(),color:t.color.clone(),ambient:t.ambient.clone()}}configureAdaptivePerformance(t={}){const e=this.adaptivePerformanceState,s=pr.clamp(t.minQuality??e.minQuality,.1,1),i=pr.clamp(t.maxQuality??e.maxQuality,s,1);e.targetFrameMs=Math.max(t.targetFrameMs??e.targetFrameMs,.1),e.minQuality=s,e.maxQuality=i,e.decreaseStep=Math.max(t.decreaseStep??e.decreaseStep,.001),e.increaseStep=Math.max(t.increaseStep??e.increaseStep,.001),e.currentQuality=pr.clamp(e.currentQuality,e.minQuality,e.maxQuality),e.enabled=!0,this.lastAppliedQuality=Number.NaN}disableAdaptivePerformance(t=!0){this.adaptivePerformanceState.enabled=!1,t&&(this.adaptivePerformanceState.currentQuality=this.adaptivePerformanceState.maxQuality,this.applyAdaptiveQuality())}getAdaptivePerformanceState(){return{...this.adaptivePerformanceState}}applyAdaptiveQuality(){const t=this.adaptivePerformanceState.currentQuality;if(t!==this.lastAppliedQuality){for(let e=0;e<this.systems.length;e++)this.systems[e].setQualityFactor(t);this.lastAppliedQuality=t}}_invalidateUpdateOrder(){this.orderedSystemsStale=!0}orderSystems(){if(!this.orderedSystemsStale)return this.orderedSystems;const t=[],e=new Set,s=new Set,i=new Set(this.systems),n=r=>{if(!s.has(r)&&!e.has(r)){e.add(r);for(const t of(t=>{const e=[];for(const s of t.behaviors??[]){if("EmitSubParticleSystem"!==s.type)continue;const t=s.subParticleSystem,n="object"==typeof t?t.system:void 0;void 0!==n&&i.has(n)&&e.push(n)}return e})(r))n(t);e.delete(r),s.add(r),t.push(r)}};for(const t of this.systems)n(t);return t.reverse(),this.orderedSystems=t,this.orderedSystemsStale=!1,t}update(t){this.elapsed+=t;const e=this.adaptivePerformanceState,s=e.enabled?performance.now():0;e.enabled&&this.applyAdaptiveQuality();const i=this.orderSystems(),n=this.cullingEnabled?this.collectCameras():0,r=this.simulationBudgetMs!==1/0||this.catchUpBudgetMs!==1/0?performance.now():0,o=this.simulationBudgetMs===1/0?1/0:r+this.simulationBudgetMs,a=this.catchUpBudgetMs===1/0?1/0:r+this.catchUpBudgetMs;for(let e=0;e<i.length;e++){const s=i[e];s.emitter.visible&&(s.culled=n>0&&"always"!==s.cullingMode&&!0!==s.onlyUsedByOther&&!this.isSystemInView(s),s.update(t,o,a)),i[e]!==s&&e--}this.refreshBatches(),e.enabled&&(e.lastFrameCpuMs=performance.now()-s,e.lastFrameCpuMs>e.targetFrameMs?e.currentQuality=pr.clamp(e.currentQuality-e.decreaseStep,e.minQuality,e.maxQuality):e.currentQuality=pr.clamp(e.currentQuality+e.increaseStep,e.minQuality,e.maxQuality))}refreshBatches(){const t=this.batchEmptyFrames;for(let e=0;e<this.batchList.length;e++){const s=this.batchList[e];if(s.time=this.elapsed,s.systems.size>0){t[e]=0,s.update();continue}const i=(t[e]??0)+1;t[e]=i,1===i?s.update():i>pr.EMPTY_BATCH_GRACE_FRAMES&&(this.removeBatch(e),e--)}}removeBatch(t){this.batchList[t].dispose(),this.batchList.splice(t,1),this.batchEmptyFrames.splice(t,1);for(const[e,s]of this.batchIndexOf)s>t&&this.batchIndexOf.set(e,s-1)}getBatchRenderStats(){return this.batchList.map((t,e)=>{let s=0;const i=[];for(const e of t.systems){const t=e;s+=t.particleNum,i.push(t.emitter.name)}return{batchIndex:e,renderMode:t.settings.renderMode,instanceCount:t.mesh.forcedInstanceCount??0,particleCount:s,systemNames:i}})}dispose(){for(const t of this.batchList)t.dispose();this.batchList.length=0,this.batchEmptyFrames.length=0;for(const t of this.systems)t._renderer===this&&(t._renderer=void 0);this.systems.length=0,this.orderedSystems=[],this.orderedSystemsStale=!0,this.batchIndexOf.clear(),super.dispose()}}pr.EMPTY_BATCH_GRACE_FRAMES=120;const mr=new WeakMap,yr=new WeakMap;function gr(t,e,s){if(mr.has(t))return;const i={textures:new Set(e),materials:new Set(s)};for(const t of[...i.textures,...i.materials])yr.set(t,(yr.get(t)??0)+1);mr.set(t,i),t.onDisposeObservable.addOnce(()=>vr(t))}function vr(t){const e=mr.get(t);if(void 0!==e){mr.delete(t);for(const t of[...e.materials,...e.textures]){const e=(yr.get(t)??1)-1;e>0?yr.set(t,e):(yr.delete(t),t.dispose())}}}function xr(t){t.dispose(),vr(t)}let Sr=0;class br extends n.TransformNode{get matrixWorld(){const t=this.getWorldMatrix(),e=t.updateFlag;if(e===this._matrixWorldFlag)return this._matrixWorld;this._matrixWorldFlag=e;const s=this._matrixWorld.elements,i=t.m;return s[0]=i[0],s[1]=i[1],s[2]=i[2],s[3]=i[3],s[4]=i[4],s[5]=i[5],s[6]=i[6],s[7]=i[7],s[8]=i[8],s[9]=i[9],s[10]=i[10],s[11]=i[11],s[12]=i[12],s[13]=i[13],s[14]=i[14],s[15]=i[15],this._matrixWorld}get visible(){return this.isEnabled()}set visible(t){this.setEnabled(t)}get uuid(){return di(this)}constructor(t,e){super("particleEmitter",e||void 0),this._matrixWorld=new ot,this._matrixWorldFlag=-1,this.system=t}dispose(t,e=!1){this.isDisposed()||(super.dispose(t,e),Sr>0||this.system.dispose?.())}clone(t){const e=this.system.clone().emitter;return e.name=t??this.name,e.position.copyFrom(this.position),e.rotation.copyFrom(this.rotation),e.scaling.copyFrom(this.scaling),this.rotationQuaternion&&(e.rotationQuaternion=this.rotationQuaternion.clone()),e.setEnabled(this.isEnabled(!1)),e}toJSON(t,e={}){return{uuid:di(this),type:"ParticleEmitter",name:this.name,position:[this.position.x,this.position.y,this.position.z],rotation:[this.rotation.x,this.rotation.y,this.rotation.z],quaternion:this.rotationQuaternion?[this.rotationQuaternion.x,this.rotationQuaternion.y,this.rotationQuaternion.z,this.rotationQuaternion.w]:void 0,scale:[this.scaling.x,this.scaling.y,this.scaling.z],visible:this.isEnabled(!1),ps:this.system.toJSON(t,e)}}}class wr{static runOnAllParticleEmitters(t,e){wr.traverseNode(t,t=>{t instanceof br&&e(t)})}static addToBatchRenderer(t,e){wr.runOnAllParticleEmitters(t,t=>{e.addSystem(t.system)})}static play(t){wr.runOnAllParticleEmitters(t,t=>{t.system.play()})}static resume(t){wr.runOnAllParticleEmitters(t,t=>{t.system.resume()})}static stop(t){wr.runOnAllParticleEmitters(t,t=>{t.system.stop()})}static pause(t){wr.runOnAllParticleEmitters(t,t=>{t.system.pause()})}static restart(t){wr.runOnAllParticleEmitters(t,t=>{t.system.restart()})}static setAutoDestroy(t,e){wr.runOnAllParticleEmitters(t,t=>{t.system.autoDestroy=e})}static endEmit(t){wr.runOnAllParticleEmitters(t,t=>{t.system.endEmit()})}static isEffectFinished(t){let e=!1,s=!0;return wr.runOnAllParticleEmitters(t,t=>{e=!0,t.system.isFinished()||(s=!1)}),e&&s}static instantiate(t,e){const s=new Map,i=new Map,r=new Set([t,...t.getDescendants(!1)]),o=t=>{let e=i.get(t);return void 0===e&&(e=t.clone(t.name,null,!0),e.setEnabled(t.isEnabled(!1)),i.set(t,e)),e},a=(t,e,i)=>{let h;if(t instanceof br)h=t.clone(i),s.set(t,h);else if(t instanceof u.Mesh)h=o(t),void 0!==i&&(h.name=i);else if(t instanceof x.InstancedMesh){const e=r.has(t.sourceMesh)?o(t.sourceMesh):void 0;h=t.clone(i??t.name,null,!0,e),h.setEnabled(t.isEnabled(!1))}else{if(!(t instanceof n.TransformNode))return null;h=new n.TransformNode(i??t.name,t.getScene()),h.position.copyFrom(t.position),h.rotation.copyFrom(t.rotation),h.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(h.rotationQuaternion=t.rotationQuaternion.clone()),h.setEnabled(t.isEnabled(!1))}h.parent=e;for(const e of t.getChildren())a(e,h);return h},h=a(t,null,e);!function(t,e){for(let s=t;null!==s;s=s.parent){const t=mr.get(s);if(void 0!==t)return void gr(e,t.textures,t.materials)}}(t,h);for(const t of s.values()){const e=t.system;for(const t of e.behaviors)if(t instanceof Ge){const e=s.get(t.subParticleSystem);void 0!==e&&(t.subParticleSystem=e)}const n=e.emitterShape;if(n instanceof pi&&void 0!==n.mesh){const t=i.get(n.mesh);void 0!==t&&(n.mesh=t)}}return h}static getDuration(t){const e=[];wr.runOnAllParticleEmitters(t,t=>{e.push(t.system)});const s=new Map;for(let t=0;t<e.length;t++){const i=e[t];for(const t of i.behaviors){if(!(t instanceof Ge))continue;const n=t.subParticleSystem?.system;if(void 0!==n&&"object"==typeof n){e.includes(n)||e.push(n);const t=s.get(n)??[];t.push(i),s.set(n,t)}}}const i=new Map,n=t=>{const e=i.get(t);if(void 0!==e)return e;i.set(t,1/0);const r=t.playbackSpeed,o=wr.maxOf(t.startLife)/r;let a;if(r>0)if(t.onlyUsedByOther){a=0;for(const e of s.get(t)??[])a=Math.max(a,n(e));a+=t.duration/r+o}else a=t.looping?1/0:(wr.maxOf(t.startDelay,0)+t.duration)/r+o;else a=1/0;return i.set(t,a),a};let r=0;for(const t of e)r=Math.max(r,n(t));return r}static maxOf(t,e){if(t instanceof Yt)return t.value;if(t instanceof Xt)return Math.max(t.a,t.b);let s=-1/0;for(let i=0;i<=32;i++){const n=[];t.startGen(n);const r="function"===t.type?t.genValue(n,e??i/32):t.genValue(n);s=Math.max(s,r)}return s}static traverseNode(t,e){e(t);const s=t.getChildren();for(const t of s)wr.traverseNode(t,e)}}const Mr=new WeakMap,zr=new WeakMap,_r=new WeakSet,Vr=new WeakMap,Ar=new WeakSet,Tr=new WeakSet;function Or(t){if(!t?.isCube)return null;const e=t.files??t._files;return 6===e?.length?e.slice():null}function Pr(t){return t.getScene?.()??null}function $r(t,e=Pr(t)){return e&&Mr.get(t)?.get(e)||null}function Er(t,e){Vr.delete(t);const s=Mr.get(t);if(s)for(const[t,i]of[...s])e&&t!==e||(s.delete(t),_r.has(i)&&i.dispose())}function Cr(t,e,s){let i=Mr.get(t);i||(i=new Map,Mr.set(t,i)),i.set(e,s),!Ar.has(s)&&s.onDisposeObservable&&(Ar.add(s),s.onDisposeObservable.addOnce(()=>{Mr.get(t)?.get(e)===s&&Mr.get(t).delete(e)})),!Tr.has(t)&&t.onDisposeObservable&&(Tr.add(t),t.onDisposeObservable.addOnce(()=>{Tr.delete(t),Er(t)}))}async function Fr(t,e){if("undefined"==typeof document||"undefined"==typeof Image)throw new Error("createEnvAtlasFromFaceUrls requires a DOM Image/canvas environment");const s=await Promise.all(t.map(t=>function(t){return new Promise((e,s)=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>e(i),i.onerror=()=>s(new Error(`Failed to load env face ${t}`)),i.src=t})}(t))),i=s[0].width||s[0].naturalWidth;if(!i)throw new Error("Env atlas face image has zero size");const n=document.createElement("canvas");n.width=3*i,n.height=2*i;const r=n.getContext("2d");if(!r)throw new Error("Could not create env atlas canvas");for(let t=0;t<6;t++)r.drawImage(s[t],t%3*i,Math.floor(t/3)*i,i,i);const o=new S.Texture(n.toDataURL("image/jpeg",.92),e,{noMipmap:!0,invertY:!1,samplingMode:S.Texture.LINEAR_LINEAR});return o.name="quarksEnvAtlas",o}const Ir={createFromFaceUrls:Fr};function Nr(t,e,s){const i=$r(t,e);if(i)return s(i),i;let n=zr.get(t);n||(n=new Map,zr.set(t,n));const r=n,o=()=>{const i=r.get(e);if(i)return void i.then(t=>{t&&s(t)});const n=Or(t);if(!n||Vr.get(t)===n.join("\n"))return;let o=!1;const a=t.onDisposeObservable?.addOnce(()=>o=!0),h=()=>{r.delete(e),a&&t.onDisposeObservable.remove(a)},l=Ir.createFromFaceUrls(n,e).then(i=>(h(),o||e.isDisposed?(i.dispose(),null):(_r.add(i),Cr(t,e,i),s(i),i))).catch(e=>(h(),Vr.set(t,n.join("\n")),console.warn("[babylon.quarks] Failed to build env atlas from cubemap faces",e),null));r.set(e,l)};if(t.isReady())o();else{const e=t.onLoadObservable;e?e.addOnce(()=>o()):o()}return $r(t,e)}const Br=new Set(["SizeOverLife","SizeBySpeed"]),Ur=new Set(["ColorOverLife","ColorBySpeed"]),Rr=new Set(["ApplyForce","Noise","TurbulenceField","GravityForce","RotationOverLife","Rotation3DOverLife","RotationBySpeed","SpeedOverLife","FrameOverLife","ForceOverLife","VelocityOverLife","InheritVelocity","OrbitOverLife","WidthOverLength","ChangeEmitDirection","EmitSubParticleSystem","LimitSpeedOverLife","ApplyCollision"]);class Dr{constructor(){this.fusionSteps=[],this.changesSize=!0,this.changesColor=!0}steps(t){const e=this.plan;if(void 0!==e&&e.length===t.length){let s=!0;for(let i=0;i<t.length;i++)if(e[i]!==t[i]){s=!1;break}if(s)return this.fusionSteps}this.plan=t.slice(),this.fusionSteps=Js(t);let s=!1,i=!1;for(let e=0;e<t.length;e++){const n=t[e].type;Br.has(n)?s=!0:Ur.has(n)?i=!0:Rr.has(n)||(s=!0,i=!0)}return this.changesSize=s,this.changesColor=i,this.fusionSteps}}function Lr(t){return Math.sqrt(Math.max(t[0]*t[0]+t[1]*t[1]+t[2]*t[2],t[4]*t[4]+t[5]*t[5]+t[6]*t[6],t[8]*t[8]+t[9]*t[9]+t[10]*t[10]))}class kr{constructor(){this.min=new et,this.max=new et,this.padding=0,this.valid=!1,this.stepsSince=0,this.maxSize=0,this.maxSpeedSq=0,this.inWorld=!1,this.geometryRadius=1}get due(){return this.stepsSince>=4||!this.valid}store(t,e,s,i,n,r,o,a,h,l,c,u,d,f){if(0===t)return void(this.valid=!1);this.stepsSince=e?0:this.stepsSince+1,this.maxSize=h,this.maxSpeedSq=l;const p=Math.sqrt(l),m=c.renderMode;let y=p*f*(this.stepsSince+1);if(m===exports.RenderMode.Mesh)y+=h*this.meshGeometryRadius(c.instancingGeometry);else if(m===exports.RenderMode.StretchedBillBoard){const t=u;y+=h*(1+(t.lengthFactor??0)+p*(t.speedFactor??0))}else{const t=c.pivot;y+=h*(.75+(void 0===t?0:Math.abs(t.x)+Math.abs(t.y)+Math.abs(t.z)))}this.min.set(s,i,n),this.max.set(r,o,a),this.padding=y,this.inWorld=d,this.valid=!0}setWorld(t,e,s,i,n,r,o){this.min.set(t,e,s),this.max.set(i,n,r),this.padding=o,this.inWorld=!0,this.valid=!0}worldPadding(t){return this.inWorld?this.padding:this.padding*Lr(t.matrixWorld.elements)}toWorld(t,e,s){if(!this.valid)return!1;const i=this.min,n=this.max;if(this.inWorld){const s=this.padding;return t.set(i.x-s,i.y-s,i.z-s),e.set(n.x+s,n.y+s,n.z+s),!0}const r=s.matrixWorld.elements,o=this.padding*Lr(r);let a=1/0,h=1/0,l=1/0,c=-1/0,u=-1/0,d=-1/0;for(let t=0;t<8;t++){const e=1&t?n.x:i.x,s=2&t?n.y:i.y,o=4&t?n.z:i.z,f=1/(r[3]*e+r[7]*s+r[11]*o+r[15]),p=(r[0]*e+r[4]*s+r[8]*o+r[12])*f,m=(r[1]*e+r[5]*s+r[9]*o+r[13])*f,y=(r[2]*e+r[6]*s+r[10]*o+r[14])*f;p<a&&(a=p),p>c&&(c=p),m<h&&(h=m),m>u&&(u=m),y<l&&(l=y),y>d&&(d=y)}return t.set(a-o,h-o,l-o),e.set(c+o,u+o,d+o),!0}meshGeometryRadius(t){if(t!==this.geometryRadiusFor){let e=0;for(let s=0;s+2<t.length;s+=3){const i=t[s]*t[s]+t[s+1]*t[s+1]+t[s+2]*t[s+2];i>e&&(e=i)}this.geometryRadius=Math.sqrt(e),this.geometryRadiusFor=t}return this.geometryRadius}}function qr(t){return t.cycle>=1?Math.floor(t.cycle):1}function Jr(t){return t.interval>0?t.interval:0}class Wr{constructor(t,e){this.system=t,this.spawner=e,this.memory=[],this.pathMatrix=new ot,this.temp=new et}rollGenerators(){const t=this.system,e=this.memory;t.emissionBursts.forEach(t=>t.count.startGen(e)),t.emissionOverDistance.startGen(e),t.startDelay.startGen(e);const s=t.startDelay.genValue(e,0);return t.emissionOverTime.startGen(e),s}hasPendingEmission(){const t=this.system;if(t.isEmitEnded)return!1;if(t.looping)return!0;if(t.onlyUsedByOther)return!1;const e=t.emissionState;if(e.waitEmiting>0)return!0;if(e.burstIndex<t.emissionBursts.length)return!0;if(this.hasPendingBurstWaves(e))return!0;if(e.time>=t.duration)return!1;const s=e.time/t.duration;return this.emitsFrom(t.emissionOverTime,s)||this.emitsFrom(t.emissionOverDistance,s)}emitsFrom(t,e){if(t.genValue(this.memory,e)>0)return!0;if("function"!==t.type)return!1;if(t instanceof te){for(let s=0;s<t.functions.length;s++)if(t.getEndX(s)>e&&t.functions[s][0].p.some(t=>t>0))return!0;return!1}for(let s=1;s<=64;s++)if(t.genValue(this.memory,e+(1-e)*s/64)>0)return!0;return!1}hasPendingBurstWaves(t){const e=t.burstWaves;if(void 0===e)return!1;const s=this.system.emissionBursts,i=this.system.duration;for(let n=0;n<t.burstIndex&&n<s.length;n++){const t=s[n],r=e[n]??0;if(r<qr(t)&&(0===r||t.time+r*Jr(t)<=i))return!0}return!1}emit(t,e,s){const i=this.system;if(i.isDisposed)return;const n=i.duration,r=i.isEmitEnded&&e===i.emissionState;e.time>n&&(i.looping?(e.time-=n,e.burstIndex=0,void 0!==e.burstWaves&&(e.burstWaves.length=0)):i.isEmitEnded||i.onlyUsedByOther||i.endEmit()),i.worldSpace&&this.spawner.normalMatrix.getNormalMatrix(s);const o=i.emissionFactor();i.emissionBursts.length>0&&!r&&this.emitBursts(e,s);let a=0,h=0,l=0,c=0;const u=e.previousWorldPos;if(!i.isEmitEnded){const r=e.time/n;if(e.waitEmiting+=t*i.emissionOverTime.genValue(this.memory,r)*o,void 0!==u){this.temp.set(s.elements[12],s.elements[13],s.elements[14]),c=u.distanceTo(this.temp);const t=i.emissionOverDistance.genValue(this.memory,r)*o;if(t>0){l=e.travelDistance,e.travelDistance+=c;const s=Math.floor(e.travelDistance*t);s>0&&(e.travelDistance-=s/t,i.worldSpace&&c>0?(a=s,h=1/t):e.waitEmiting+=s)}else e.travelDistance=0}}const d=Math.floor(e.waitEmiting);d>0&&(this.spawner.spawn(d,e,s),e.waitEmiting-=d),a>0&&this.spawnAlongPath(a,e,s,u,l,h,c),void 0===e.previousWorldPos&&(e.previousWorldPos=new et),e.previousWorldPos.set(s.elements[12],s.elements[13],s.elements[14]),e.time+=t}emitBursts(t,e){const s=this.system.emissionBursts,i=this.system.duration,n=s.length,r=t.time,o=t.burstWaves??(t.burstWaves=[]);for(;t.burstIndex<n&&s[t.burstIndex].time<=r;)o[t.burstIndex]=0,t.burstIndex++;const a=t.burstIndex;for(let n=0;n<a;n++){const a=s[n],h=qr(a);let l=o[n]??0;if(l>=h)continue;const c=Jr(a);for(;l<h;){const s=a.time+l*c;if(l>0&&s>i){l=h;break}if(s>r)break;t.burstWaveIndex=l,this.fireBurstWave(a,t,e),l++}o[n]=l}}fireBurstWave(t,e,s){if(M()>=t.probability)return;const i=t.count.genValue(this.memory,e.time/this.system.duration),n=this.system.emissionFactor(),r=Math.abs(n-1)<.001?i:Math.floor(i*n+M());e.isBursting=!0,e.burstParticleCount=r,this.spawner.spawn(r,e,s),e.isBursting=!1}spawnAlongPath(t,e,s,i,n,r,o){const a=this.pathMatrix.copy(s),h=s.elements,l=a.elements,c=h[12],u=h[13],d=h[14];for(let s=1;s<=t;s++){const t=s*r-n,h=t<=0?0:t>=o?1:t/o;l[12]=i.x+(c-i.x)*h,l[13]=i.y+(u-i.y)*h,l[14]=i.z+(d-i.z)*h,this.spawner.spawn(1,e,a)}}}class Gr{constructor(){this.listeners={}}add(t,e){this.listeners[t]=[...this.listeners[t]??[],e]}removeAll(t){if(void 0!==t)delete this.listeners[t];else for(const t of Object.keys(this.listeners))delete this.listeners[t]}remove(t,e){const s=this.listeners[t];if(void 0===s)return;const i=s.indexOf(e);-1!==i&&(this.listeners[t]=s.filter((t,e)=>e!==i))}has(t){const e=this.listeners[t];return void 0!==e&&e.length>0}fire(t){const e=this.listeners[t.type];if(void 0!==e)for(let s=0;s<e.length;s++)e[s](t)}}const Qr=new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]),jr=new Float32Array([0,0,1,0,1,1,0,1]),Hr=new Uint32Array([0,1,2,0,2,3]),Yr=new WeakMap,Xr=new WeakMap;function Zr(t){let e=Yr.get(t);return void 0!==e&&e.length===t.length/3*2||(e=new Float32Array(t.length/3*2),Yr.set(t,e)),e}function Kr(t){let e=Xr.get(t);if(!e){e=new Float32Array(t.length);for(let t=2;t<e.length;t+=3)e[t]=1;Xr.set(t,e)}return e}function to(t){return t?t instanceof Float32Array?t:new Float32Array(t):void 0}const eo=1/60;class so{constructor(){this.accumulator=0,this.pendingCatchUp=0,this.delayLeft=0}reset(){this.accumulator=0,this.pendingCatchUp=0}setStartDelay(t){this.delayLeft=t>0?t:0}get delaying(){return this.delayLeft>0}static frameSeconds(t,e){if(!(t>0))return 0;return(t>.1?.1:t)*e}consumeStartDelay(t){if(this.delayLeft<=0)return t;if(this.delayLeft-=t,this.delayLeft>=0)return 0;const e=Math.min(-this.delayLeft,.1);return this.delayLeft=0,e}accrue(t,e=1){this.accumulator+=t;const s=e>1?Math.ceil(8*e):8,i=Math.min(s,Math.max(0,Math.round(this.accumulator/eo-1e-9)));return this.accumulator-=i*eo,i}get residual(){return this.accumulator>eo?eo:this.accumulator<-eo?-eo:this.accumulator}deferCatchUp(t){this.pendingCatchUp=Math.min(2,this.pendingCatchUp+t)}get owesCatchUp(){return this.pendingCatchUp>0}takeCatchUpSteps(){const t=Math.floor(this.pendingCatchUp/eo);return this.pendingCatchUp=0,t}}const io=new et;function no(t,e,s,i){const n=t[s],r=t[i];return t[s]=r,t[i]=n,s!==i&&(e.swapRows(s,i),r.setStoreIndex(s),n.setStoreIndex(i)),n}function ro(t){return t?.getScene()?t:null}const oo=new et(0,0,1),ao=new tt,ho=new tt,lo=new et,co=new et;class uo{constructor(t){this.system=t,this.normalMatrix=new gt}rebind(){const t=this.system.particles;for(let e=0;e<t.length;e++)t[e].rebind()}grow(t){const e=this.system,s=e.particles.length;e.store.ensureCapacity(s+1)&&this.rebind(),e.particles.push(t?new Ie(e.store,s):new Ce(e.store,s))}spawn(t,e,s){const i=this.system,n=lo,r=co;s.decompose(n,ho,r);const o=i.behaviors,a=o.length,h=i.rendererSettings.renderMode,l=h===exports.RenderMode.Trail,c=!l,u=h===exports.RenderMode.Mesh,d=i.startRotation,f=i.startSize,p="rotation"===d.type,m="vec3function"===f.type,y=e.time/i.duration,g=l?i.rendererEmitterSettings:void 0,v=Boolean(g?.followLocalOrigin),x=i.worldSpace,S="hierarchy"===i.scalingMode,b=i.particles;void 0!==i.maxParticles&&(t=Math.min(t,Math.max(0,i.maxParticles-i.particleNum)));for(let n=0;n<t;n++){e.burstParticleIndex=n,i.particleNum++,b.length<i.particleNum&&this.grow(l);const t=b[i.particleNum-1];if(t.reset(),t.serial=(t.serial??0)+1,t.speedModifier=1,i.finishedEventFired=!1,i.startColor.startGen(t.memory),i.startColor.genColor(t.memory,t.startColor,y),t.color.copy(t.startColor),i.startSpeed.startGen(t.memory),t.startSpeed=i.startSpeed.genValue(t.memory,y),i.startLife.startGen(t.memory),t.life=i.startLife.genValue(t.memory,y),t.age=0,f.startGen(t.memory),m)f.genValue(t.memory,t.startSize,y);else{const e=f.genValue(t.memory,y);t.startSize.set(e,e,e)}if(i.startTileIndex.startGen(t.memory),t.uvTile=i.startTileIndex.genValue(t.memory),t.size.copy(t.startSize),c){const e=t;if(d.startGen(t.memory),u)e.rotation instanceof tt||(e.rotation=ao),e.angularVelocity instanceof tt&&e.angularVelocity.set(0,0,0,1),p?d.genValue(t.memory,e.rotation,1,y):e.rotation.setFromAxisAngle(oo,d.genValue(e.memory,y));else{e.rotation=p?0:d.genValue(e.memory,y),e.angularVelocity=0;const t=i.flip;e.flip=void 0===t?0:(M()<t.x?1:0)|(M()<t.y?2:0)}}else if(g){const e=t;g.startLength.startGen(e.memory),e.length=g.startLength.genValue(e.memory,y),e.ensureHistoryCapacity(Math.max(1,Math.ceil(e.length))),e.resetHistory()}i.emitterShape.initialize(t,e),i.alignToDirection&&c&&fo(t,u);const h=e.particle,w=e.inherit;if(void 0!==h&&void 0!==w&&0!==w&&po(t,h,w,c),l&&v){const e=t;e.localPosition||(e.localPosition=new et),e.localPosition.copy(e.position)}x?(t.position.applyMatrix4(s),t.startSize.multiply(r).abs(),t.size.copy(t.startSize),S?t.velocity.multiply(i.hierarchyScale).applyQuaternion(ho):t.velocity.multiply(r).applyMatrix3(this.normalMatrix),t.rotation&&t.rotation instanceof tt&&t.rotation.multiplyQuaternions(ho,t.rotation)):i.onlyUsedByOther&&(t.parentMatrix=s);for(let e=0;e<a;e++)o[e].initialize(t,i);i.store.recordMemory(t.storeIndex,t.memory)}}}function fo(t,e){const s=t.velocity,i=s.x*s.x+s.y*s.y+s.z*s.z;if(0!==i)if(e){const e=t.rotation;lo.copy(s).divideScalar(Math.sqrt(i)),ho.setFromUnitVectors(oo,lo),e.multiplyQuaternions(ho,e)}else 0===s.x&&0===s.y||(t.rotation=t.rotation+Math.atan2(-s.x,s.y))}function po(t,e,s,i){if(s&Je.color&&(t.startColor.multiply(e.color),t.color.copy(t.startColor)),s&Je.size&&(t.startSize.multiply(e.size),t.size.copy(t.startSize)),s&Je.rotation&&i){const s=t,i=e.rotation;"number"==typeof s.rotation?"number"==typeof i&&(s.rotation+=i):i instanceof tt&&s.rotation.multiplyQuaternions(i,s.rotation)}s&Je.lifetime&&e.life>0&&(t.life*=Math.max(0,1-e.age/e.life))}function mo(t,e,s,i,n={}){return{param:t,json:n.json,get:e,isDefault:t=>t===s,toJSON:t=>t,fromJSON:i,clone:t=>t}}function yo(t){return"number"==typeof t?t:void 0}function go(t){return"number"==typeof t?Bi(t):void 0}function vo(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:void 0}function xo(t){return"number"==typeof t?0!==t:"boolean"==typeof t?t:void 0}function So(t,e,s,i,n=!0){const r=JSON.stringify(s().toJSON());return{param:t,always:n,get:e,isDefault:t=>JSON.stringify(t.toJSON())===r,toJSON:t=>t.toJSON(),fromJSON:t=>"number"==typeof t?new Yt(t):i(t),clone:t=>t.clone()}}function bo(t){const e=t;if(void 0!==e)return void 0===e.z?[e.x,e.y]:[e.x,e.y,e.z]}const wo=[mo("autoDestroy",t=>t.autoDestroy,!1,xo),mo("looping",t=>t.looping,!0,xo),mo("prewarm",t=>t.prewarm,!1,xo),mo("prewarmTime",t=>t.prewarmTime,0,yo),mo("duration",t=>t.duration,1,yo),So("startDelay",t=>t.startDelay,()=>new Yt(0),ee,!1),So("startLife",t=>t.startLife,()=>new Yt(5),ee),So("startSpeed",t=>t.startSpeed,()=>new Yt(0),ee),So("startRotation",t=>t.startRotation,()=>new Yt(0),t=>ve(t)),So("startSize",t=>t.startSize,()=>new Yt(1),t=>ve(t)),So("startColor",t=>t.startColor,()=>new ue(new Vt(1,1,1,1)),t=>de(t)),So("emissionOverTime",t=>t.emissionOverTime,()=>new Yt(10),ee),So("emissionOverDistance",t=>t.emissionOverDistance,()=>new Yt(0),ee),{param:"emissionBursts",get:t=>t.emissionBursts,isDefault:t=>0===t.length,toJSON:t=>t.map(t=>({time:t.time,count:t.count.toJSON(),probability:t.probability,interval:t.interval,cycle:t.cycle})),fromJSON:t=>Array.isArray(t)?Di(t.map(t=>({time:t.time,count:"number"==typeof t.count?new Yt(t.count):ee(t.count),probability:t.probability,interval:t.interval,cycle:t.cycle??t.cycleCount}))):void 0,clone:t=>t.map(t=>({...t,count:t.count.clone()}))},mo("maxParticles",t=>t.maxParticles,void 0,yo),mo("onlyUsedByOther",t=>t.onlyUsedByOther,!1,xo),mo("renderMode",t=>t.renderMode,exports.RenderMode.BillBoard,yo),mo("renderOrder",t=>t.renderOrder,0,yo),mo("renderingGroupId",t=>t.renderingGroupId,0,yo),mo("applyFog",t=>t.applyFog,!0,t=>!1!==t),mo("playbackSpeed",t=>t.playbackSpeed,1,yo),mo("cullingMode",t=>t.cullingMode,"always",Fi),mo("scalingMode",t=>t.scalingMode,"shape",t=>"hierarchy"===t?"hierarchy":"shape"),mo("seed",t=>t.seed,void 0,yo),mo("sortMode",t=>t.sortMode,"none",Ei),mo("renderFace",t=>t.renderFace,"both",Ci),mo("alignToDirection",t=>t.alignToDirection,!1,t=>!0===t),mo("minParticleSize",t=>t.minParticleSize,0,yo),mo("maxParticleSize",t=>t.maxParticleSize,1/0,yo),mo("layerMask",t=>t.layers.mask,268435455,yo,{json:"layers"}),So("startTileIndex",t=>t.startTileIndex,()=>new Yt(0),ee),mo("uTileCount",t=>t.uTileCount,1,go),mo("vTileCount",t=>t.vTileCount,1,go),mo("blendTiles",t=>t.blendTiles,!1,xo),mo("softParticles",t=>t.softParticles,!1,xo),mo("softFarFade",t=>t.softFarFade,1,vo),mo("softNearFade",t=>t.softNearFade,0,vo),mo("blendMode",t=>t.blending,r.Constants.ALPHA_ADD,yo,{json:"blending"}),mo("transparent",t=>t.transparent,!0,xo),mo("depthTest",t=>t.depthTest,!0,xo),mo("depthWrite",t=>t.depthWrite,!1,xo),mo("alphaTest",t=>t.alphaTest,0,yo),mo("worldSpace",t=>t.worldSpace,!1,xo),{param:"pivot",get:t=>t.pivot,isDefault:t=>void 0===t,toJSON:bo,fromJSON:t=>Array.isArray(t)?new et(t[0]??0,t[1]??0,t[2]??0):void 0,clone:t=>t?.clone()},{param:"flip",get:t=>t.flip,isDefault:t=>void 0===t,toJSON:bo,fromJSON:t=>Array.isArray(t)?new wt(t[0]??0,t[1]??0):void 0,clone:t=>t?.clone()}];function Mo(t){return t.json??t.param}function zo(t){const e={};for(const s of wo){const i=s.get(t);!s.always&&s.isDefault(i)||(e[Mo(s)]=s.toJSON(i))}return e}function _o(t){const e={};for(const s of wo)e[s.param]=s.clone(s.get(t));return e}const Vo=new WeakMap,Ao=new WeakMap,To=new WeakMap;function Oo(t,e){const s=(Vo.get(t)??0)+1;return Vo.set(t,s),`${e}_${s}`}function Po(t){const e={};return t?.uvFromHead&&(e.uvFromHead=!0),t?.colorFromParticle&&(e.colorFromParticle=!0),t?.dieWithParticle&&(e.dieWithParticle=!0),t?.recordWorldSpace&&(e.recordWorldSpace=!0),e}function $o(t){const e={},s=nr(t),i=rr(t);return s>0&&(e.tessellation=s),i>0&&(e.curveTension=i),e}function Eo(t){const e={},s=ar(t),i=hr(t),n=lr(t),r=cr(t);return"stretch"!==s&&(e.textureMode=s),1!==i&&(e.textureScale=i),n>0&&(e.minVertexDistance=n),r!==1/0&&(e.lifetime=r),e}function Co(t){return t?.followLocalOrigin?{followLocalOrigin:!0}:{}}function Fo(t){const e=t?.sideAxis;return e?{sideAxis:[e.x,e.y,e.z]}:{}}function Io(t){if(null==t)return{};let e,s,i;Array.isArray(t)?[e,s,i]=t:"object"==typeof t&&({x:e,y:s,z:i}=t);const n=t=>"number"==typeof t?t:"string"==typeof t&&""!==t.trim()?Number(t):NaN,[r,o,a]=[n(e),n(s),n(i)];return Number.isFinite(r)&&Number.isFinite(o)&&Number.isFinite(a)&&r*r+o*o+a*a>0?{sideAxis:new et(r,o,a)}:(Wt(`sideAxis ${JSON.stringify(t)} is not a direction and is ignored`),{})}function No(t,e){const s=void 0===e||"string"==typeof e?{geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}}:e,i=function(t,e){const s=t.rendererSettings,i=[s.instancingGeometry,s.instancingIndices,s.instancingUVs,s.instancingUVs2,s.instancingNormals];let n=Ao.get(e);void 0===n&&(n=[],Ao.set(e,n));const r=n.find(t=>t.arrays.every((t,e)=>t===i[e]));if(void 0!==r)return r.uuid;const o=Oo(e,"quarks_geometry");return n.push({arrays:i,uuid:o}),e.geometries[o]={uuid:o,type:"QuarksGeometry",positions:Array.from(t.rendererSettings.instancingGeometry),indices:Array.from(t.rendererSettings.instancingIndices),uvs:t.rendererSettings.instancingUVs?Array.from(t.rendererSettings.instancingUVs):void 0,...t.rendererSettings.instancingUVs2?{uvs2:Array.from(t.rendererSettings.instancingUVs2)}:{},normals:t.rendererSettings.instancingNormals?Array.from(t.rendererSettings.instancingNormals):void 0},o}(t,s),n=function(t,e){let s=To.get(e);void 0===s&&(s=new Map,To.set(e,s));const i=s,n=(t,s=!1,n="texture")=>{if(!(t instanceof S.Texture||s&&t))return void(t&&console.warn(`[quarks] ${n} is not a url-backed Texture and is not written to the file`));let r=i.get(t);return void 0===r&&(r=Oo(e,"quarks_texture"),i.set(t,r),e.textures[r]=t),r},r=n(t.rendererSettings.texture,!0),o=n(t.rendererSettings.reflectionAtlas),a=t.erosion,h=t.uvDistortion,l=t.gradientMap,c=(t,e)=>void 0!==e?{[t]:e}:{},u=Oo(e,"quarks_material");return e.materials[u]={uuid:u,type:"QuarksMaterial",transparent:t.rendererSettings.materialTransparent,alphaMode:t.rendererSettings.materialBlendMode,depthTest:t.rendererSettings.materialDepthTest,depthWrite:t.rendererSettings.materialDepthWrite,alphaTest:t.rendererSettings.materialAlphaTest,texture:r,reflectionAtlas:o,reflectionLevel:t.rendererSettings.reflectionLevel,..."fixed"!==t.lighting?{lighting:t.lighting}:{},...t.rim?{rim:{...t.rim,color:[...t.rim.color]}}:{},...c("mapUV",t.mapUV?bi(t.mapUV):void 0),...l?{gradientMap:{ramp:n(l.ramp,!1,"gradientMap.ramp"),..."r"!==l.channel?{channel:l.channel}:{}}}:{},...a?{erosion:{...c("mask",n(a.mask,!1,"erosion.mask")),...c("maskUV",bi(a.maskUV)),...a.softness!==zi?{softness:a.softness}:{},...0!==a.edgeWidth?{edgeWidth:a.edgeWidth}:{},...a.edgeColor.some(t=>1!==t)?{edgeColor:[...a.edgeColor]}:{}}}:{},...h?{uvDistortion:{map:n(h.map,!1,"uvDistortion.map"),...c("mapUV",bi(h.mapUV,Vi)),...h.strength!==Ai?{strength:h.strength}:{}}}:{},sourceMaterial:t.material??void 0},u}(t,s),r=function(t){if(t.renderMode===exports.RenderMode.Trail){const e=t.rendererEmitterSettings;return{startLength:e.startLength.toJSON(),...Co(e),...Po(e),...$o(e),...Eo(e),...Fo(e)}}if(t.renderMode===exports.RenderMode.StretchedBillBoard)return{speedFactor:t.rendererEmitterSettings.speedFactor,lengthFactor:t.rendererEmitterSettings.lengthFactor};return}(t);return{version:"3.0",shape:ai(t.emitterShape),...zo(t),instancingGeometry:i,...r?{rendererEmitterSettings:r}:{},material:n,behaviors:t.behaviors.map(e=>Ps(e,t))}}function Bo(t,e,s){const i=t.shape?qt("shape",()=>oi(t.shape,e)):void 0;let n;if(t.renderMode===exports.RenderMode.Trail){const e=t.rendererEmitterSettings;n={startLength:void 0!==e?.startLength?ee(e.startLength):new Yt(30),followLocalOrigin:Boolean(e?.followLocalOrigin),...Po(e),...$o(e),...Eo(e),...Io(e?.sideAxis)}}else if(t.renderMode===exports.RenderMode.StretchedBillBoard){const e={...t.rendererEmitterSettings};void 0!==t.speedFactor&&(e.speedFactor=t.speedFactor),n=e}else n={};const o=t.material?e.materials?.[t.material]:void 0,a=t=>"string"==typeof t?e.textures?.[t]??null:t??null,h=a(o?.texture??t.texture),l=h instanceof S.Texture?h:null,c=o?.sourceMaterial??(o?{...o,reflectionAtlas:a(o.reflectionAtlas)}:void 0),u=o?.erosion,d=o?.gradientMap,f=o?.uvDistortion,p=function(t){if(t&&"positions"in t&&t.positions){const e=to(t.positions);return{positions:e,indices:ci(e,t.indices instanceof Uint16Array||t.indices instanceof Uint32Array?t.indices:t.indices?new Uint32Array(t.indices):void 0),uvs:to(t.uvs),uvs2:to(t.uvs2),normals:to(t.normals)}}const e=t&&"data"in t?t.data:t,s=e&&"attributes"in e?e.attributes:void 0,i=s?.position?.array;if(e&&"attributes"in e&&s&&i){const t=new Float32Array(i);let n;return e.index?.array&&(n=new("Uint16Array"===e.index.type?Uint16Array:Uint32Array)(e.index.array)),{positions:t,indices:ci(t,n),uvs:to(s.uv?.array),uvs2:to((s.uv1??s.uv2)?.array),normals:to(s.normal?.array)}}return{positions:Qr,indices:Hr,uvs:jr}}("string"==typeof t.instancingGeometry?e.geometries?.[t.instancingGeometry]:t.instancingGeometry),m=function(t){const e={},s=t;for(const t of wo){const i=s[Mo(t)];if(null==i)continue;const n=qt(Mo(t),()=>t.fromJSON(i));void 0!==n&&(e[t.param]=n)}return e}(t);return{...m,scene:s,shape:i,instancingGeometry:p.positions,instancingIndices:p.indices,instancingUVs:p.uvs,instancingUVs2:p.uvs2,instancingNormals:p.normals,rendererEmitterSettings:n,texture:l,material:c,blendMode:o?.alphaMode??m.blendMode??r.Constants.ALPHA_ADD,transparent:o?.transparent??m.transparent??!0,depthTest:o?.depthTest??m.depthTest??!0,depthWrite:o?.depthWrite??m.depthWrite??!1,alphaTest:o?.alphaTest??m.alphaTest??0,behaviors:[],lighting:o?.lighting,rim:o?.rim,mapUV:o?.mapUV,gradientMap:d&&"object"==typeof d?{...d,ramp:a(d.ramp)}:void 0,erosion:u&&"object"==typeof u?{...u,mask:a(u.mask)}:void 0,uvDistortion:f&&"object"==typeof f?{...f,map:a(f.map)}:void 0}}const Uo=new et,Ro=new tt,Do=new et,Lo=new et,ko=new tt,qo=new et,Jo=new et,Wo=new tt,Go=new et;class Qo{get prewarmTime(){return this.prewarmTimeValue}set prewarmTime(t){this.prewarmTimeValue=t>0?t:0}get duration(){return this.durationValue}set duration(t){this.durationValue=t>eo?t:eo}set time(t){const e=this.duration;let s=Number.isFinite(t)&&t>0?t:0;s>=e&&(s=this.looping?s%e:e);const i=this.emissionState;i.time=s,i.isBursting=!1,i.burstIndex=0,i.burstWaveIndex=0,i.burstWaves=void 0,this.markBurstsBefore(s)}get time(){return this.emissionState.time}get isEmitEnded(){return this.emitEnded}hasPendingEmission(){return this.emission.hasPendingEmission()}isFinished(){return!(this.particleNum>0)&&(!!this.onlyUsedByOther||(this.looping?this.emitEnded:!this.hasPendingEmission()))}get layers(){return this.layerMaskProxy}get texture(){return this.rendererSettings.texture}set texture(t){this.rendererSettings.texture=t,this.neededToUpdateRender=!0}get material(){return this.materialRef}set material(t){this.materialRef=t,this.applyMaterialSettings(t)}get uTileCount(){return this.rendererSettings.uTileCount}set uTileCount(t){this.rendererSettings.uTileCount=Bi(t),this.neededToUpdateRender=!0}get vTileCount(){return this.rendererSettings.vTileCount}set vTileCount(t){this.rendererSettings.vTileCount=Bi(t),this.neededToUpdateRender=!0}get blendTiles(){return this.rendererSettings.blendTiles}set blendTiles(t){this.rendererSettings.blendTiles=t,this.neededToUpdateRender=!0}get softParticles(){return this.rendererSettings.softParticles}set softParticles(t){this.rendererSettings.softParticles=t,this.neededToUpdateRender=!0}get sortMode(){return this.rendererSettings.sortMode??"none"}set sortMode(t){this.rendererSettings.sortMode=Ei(t),this.neededToUpdateRender=!0}get renderFace(){return this.rendererSettings.renderFace??"both"}set renderFace(t){this.rendererSettings.renderFace=Ci(t),this.neededToUpdateRender=!0}get minParticleSize(){return this.rendererSettings.minParticleSize??0}set minParticleSize(t){this.rendererSettings.minParticleSize=Math.max(0,t),this.neededToUpdateRender=!0}get maxParticleSize(){return this.rendererSettings.maxParticleSize??1/0}set maxParticleSize(t){this.rendererSettings.maxParticleSize=t>0?t:1/0,this.neededToUpdateRender=!0}get pivot(){return this.rendererSettings.pivot}set pivot(t){this.rendererSettings.pivot=Ii(t),this.neededToUpdateRender=!0}get lighting(){return this.rendererSettings.lighting??"fixed"}set lighting(t){this.rendererSettings.lighting=$i(t),this.neededToUpdateRender=!0}get rim(){return this.rendererSettings.rim}set rim(t){this.rendererSettings.rim=vi(t),this.neededToUpdateRender=!0}get mapUV(){return this.rendererSettings.mapUV}set mapUV(t){this.rendererSettings.mapUV=Oi(t),this.neededToUpdateRender=!0}get gradientMap(){return this.rendererSettings.gradientMap}set gradientMap(t){this.rendererSettings.gradientMap=Mi(t),this.neededToUpdateRender=!0}get erosion(){return this.rendererSettings.erosion}set erosion(t){this.rendererSettings.erosion=_i(t),this.neededToUpdateRender=!0}get uvDistortion(){return this.rendererSettings.uvDistortion}set uvDistortion(t){this.rendererSettings.uvDistortion=Ti(t),this.neededToUpdateRender=!0}measureMotionScale(t){if("hierarchy"!==this.scalingMode||!this.worldSpace)return this.hierarchyScale.set(1,1,1),1;const e=t.elements,s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),i=Math.sqrt(e[4]*e[4]+e[5]*e[5]+e[6]*e[6]),n=Math.sqrt(e[8]*e[8]+e[9]*e[9]+e[10]*e[10]);return this.hierarchyScale.set(s,i,n),(s+i+n)/3}get softNearFade(){return this.rendererSettings.softNearFade}set softNearFade(t){this.rendererSettings.softNearFade=Ui(t,0),this.neededToUpdateRender=!0}get softFarFade(){return this.rendererSettings.softFarFade}set softFarFade(t){this.rendererSettings.softFarFade=Ui(t,1),this.neededToUpdateRender=!0}get instancingGeometry(){return this.rendererSettings.instancingGeometry}set instancingGeometry(t){this.restartKeepingPause();const e=this.rendererSettings,s=t.length/3*2,i=e.instancingGeometry;var n,r;e.instancingGeometry=t,t.length===i.length&&function(t,e){for(let s=0;s<t.length;s++)if(t[s]>=e)return!1;return!0}(e.instancingIndices,t.length/3)||(e.instancingIndices=ci(t)),e.instancingUVs?.length===s&&(n=e.instancingUVs,r=i,void 0===n||n!==Yr.get(r))||(e.instancingUVs=Zr(t)),e.instancingNormals&&(e.instancingNormals.length!==t.length||function(t,e){return void 0!==t&&t===Xr.get(e)}(e.instancingNormals,i))&&(e.instancingNormals=Kr(t)),e.instancingUVs2&&e.instancingUVs2.length!==s&&(e.instancingUVs2=void 0),this.ensureMeshNormals(),this.neededToUpdateRender=!0}ensureMeshNormals(){const t=this.rendererSettings;t.renderMode!==exports.RenderMode.Mesh||t.instancingNormals||(t.instancingNormals=Kr(t.instancingGeometry))}restartKeepingPause(){const t=this.paused;this.restart(),this.particles.length=0,this.paused=t}get instancingIndices(){return this.rendererSettings.instancingIndices}set instancingIndices(t){this.rendererSettings.instancingIndices=t,this.neededToUpdateRender=!0}get instancingUVs(){return this.rendererSettings.instancingUVs??Zr(this.rendererSettings.instancingGeometry)}set instancingUVs(t){this.rendererSettings.instancingUVs=t,this.neededToUpdateRender=!0}get instancingUVs2(){return this.rendererSettings.instancingUVs2}set instancingUVs2(t){this.rendererSettings.instancingUVs2=t,this.neededToUpdateRender=!0}get blending(){return this.rendererSettings.materialBlendMode}set blending(t){this.rendererSettings.materialBlendMode=t,this.neededToUpdateRender=!0}get transparent(){return this.rendererSettings.materialTransparent}set transparent(t){this.rendererSettings.materialTransparent=t,this.neededToUpdateRender=!0}get depthTest(){return this.rendererSettings.materialDepthTest}set depthTest(t){this.rendererSettings.materialDepthTest=t,this.neededToUpdateRender=!0}get depthWrite(){return this.rendererSettings.materialDepthWrite}set depthWrite(t){this.rendererSettings.materialDepthWrite=t,this.neededToUpdateRender=!0}get alphaTest(){return this.rendererSettings.materialAlphaTest}set alphaTest(t){this.rendererSettings.materialAlphaTest=Ni(t),this.neededToUpdateRender=!0}get renderMode(){return this.rendererSettings.renderMode}set renderMode(t){if(this.rendererSettings.renderMode!==t){let e=!1;switch(this.rendererSettings.renderMode===exports.RenderMode.Trail&&(e=!0),this.rendererSettings.renderMode===exports.RenderMode.Mesh&&(this.startRotation=new Yt(0)),t){case exports.RenderMode.Trail:this.rendererEmitterSettings={startLength:new Yt(30),followLocalOrigin:!1},e=!0;break;case exports.RenderMode.Mesh:this.rendererEmitterSettings={},this.startRotation=new ie(new et(0,1,0),new Yt(0));break;case exports.RenderMode.StretchedBillBoard:this.rendererEmitterSettings={speedFactor:0,lengthFactor:2};break;case exports.RenderMode.BillBoard:case exports.RenderMode.VerticalBillBoard:case exports.RenderMode.HorizontalBillBoard:case exports.RenderMode.Beam:this.rendererEmitterSettings={}}this.rendererSettings.renderMode=t,e&&this.restartKeepingPause(),this.ensureMeshNormals(),this.neededToUpdateRender=!0}}get renderOrder(){return this.rendererSettings.renderOrder}set renderOrder(t){this.rendererSettings.renderOrder=t,this.neededToUpdateRender=!0}get renderingGroupId(){return this.rendererSettings.renderingGroupId}set renderingGroupId(t){this.rendererSettings.renderingGroupId=t,this.neededToUpdateRender=!0}get applyFog(){return this.rendererSettings.applyFog}set applyFog(t){this.rendererSettings.applyFog=t,this.neededToUpdateRender=!0}get playbackSpeed(){return this.playbackSpeedValue}set playbackSpeed(t){this.playbackSpeedValue=t>0&&t<1/0?t:0}get timeDilation(){return this.timeDilationValue}set timeDilation(t){this.timeDilationValue=t>0&&t<1/0?t:0}get emissionMultiplier(){return this.emissionMultiplierValue}set emissionMultiplier(t){this.emissionMultiplierValue=Number.isFinite(t)&&t>=0?t:0}get seed(){return this.seedValue}set seed(t){this.seedValue=t,this.rng=void 0===t?void 0:V(t),void 0!==this.emissionState&&0===this.emissionState.time&&0===this.particleNum&&(this.emission.memory.length=0,this.initSystemGenerators())}constructor(t){var e,s;if(this.prewarmTimeValue=0,this.durationValue=1,this.store=new Pe(64),this.emitterVelocity=new et,this.finishedEventFired=!1,this.clock=new so,this.tempEmitterPos=new et,this.stepMatrix=new ot,this.spawner=new uo(this),this.emission=new Wr(this,this.spawner),this.events=new Gr,this.materialRef=null,this.qualityFactor=1,this.destroyed=!1,this.behaviorPlan=new Dr,this.hierarchyScale=new et(1,1,1),this.playbackSpeedValue=1,this.timeDilationValue=1,this.emissionMultiplierValue=1,this.cullingMode="always",this.scalingMode="shape",this.motionScale=1,this.alignToDirection=!1,this.culled=!1,this.bounds=new kr,this.firstTimeUpdate=!0,this.beamEndScratch=new et,this.rebindParticles=()=>this.spawner.rebind(),this.particleDiedEvent={type:"particleDied",particleSystem:this},this.fireParticleDied=t=>{const e=this.particleDiedEvent;e.particle=t,this.events.fire(e),e.particle=void 0},this.sceneRef=t.scene,this.layerMaskProxy={mask:t.layerMask??268435455},Object.defineProperty(this.layerMaskProxy,"mask",{enumerable:!0,get:()=>this.rendererSettings.layerMask,set:t=>{this.rendererSettings.layerMask=t,this.neededToUpdateRender=!0}}),this.autoDestroy=t.autoDestroy??!1,this.duration=t.duration??1,this.startDelay=t.startDelay??new Yt(0),this.looping=t.looping??!0,this.prewarm=t.prewarm??!1,this.prewarmTime=t.prewarmTime??0,this.startLife=t.startLife??new Yt(5),this.startSpeed=t.startSpeed??new Yt(0),this.startRotation=t.startRotation??new Yt(0),this.startSize=t.startSize??new Yt(1),this.startColor=t.startColor??new ue(new Vt(1,1,1,1)),this.emissionOverTime=t.emissionOverTime??new Yt(10),this.emissionOverDistance=t.emissionOverDistance??new Yt(0),this.emissionBursts=Di(t.emissionBursts),this.maxParticles="number"==typeof(e=t.maxParticles)&&e>=0&&e<1/0?Math.floor(e):void 0,this.onlyUsedByOther=t.onlyUsedByOther??!1,this.emitterShape=t.shape??new ii,this.behaviors=t.behaviors??[],this.worldSpace=t.worldSpace??!1,this.rendererEmitterSettings=t.rendererEmitterSettings??{},t.renderMode===exports.RenderMode.Trail){const t={...this.rendererEmitterSettings};this.rendererEmitterSettings=t,t.startLength=t.startLength??new Yt(30),t.followLocalOrigin=t.followLocalOrigin??!1}if(t.renderMode===exports.RenderMode.StretchedBillBoard){const e={...this.rendererEmitterSettings};this.rendererEmitterSettings=e,void 0!==t.speedFactor&&(e.speedFactor=t.speedFactor),e.speedFactor=e.speedFactor??0,e.lengthFactor=e.lengthFactor??0}this.rendererSettings={instancingGeometry:t.instancingGeometry??Qr,instancingIndices:t.instancingIndices??Hr,instancingUVs:t.instancingUVs??(t.instancingGeometry?Zr(t.instancingGeometry):jr),instancingUVs2:t.instancingUVs2,instancingNormals:t.instancingNormals,renderMode:t.renderMode??exports.RenderMode.BillBoard,renderOrder:t.renderOrder??0,uTileCount:Bi(t.uTileCount),vTileCount:Bi(t.vTileCount),blendTiles:t.blendTiles??!1,softParticles:t.softParticles??!1,softNearFade:Ui(t.softNearFade,0),softFarFade:Ui(t.softFarFade,1),materialBlendMode:t.blendMode??r.Constants.ALPHA_ADD,materialTransparent:t.transparent??!0,materialDepthTest:t.depthTest??!0,materialDepthWrite:t.depthWrite??!1,materialAlphaTest:Ni(t.alphaTest),texture:t.texture??null,reflectionTexture:null,reflectionLevel:1,reflectionAtlas:null,layerMask:t.layerMask??268435455,pivot:Ii(t.pivot),sortMode:Ei(t.sortMode),renderFace:Ci(t.renderFace),minParticleSize:Math.max(0,t.minParticleSize??0),maxParticleSize:t.maxParticleSize??1/0,renderingGroupId:t.renderingGroupId??0,applyFog:t.applyFog??!0,lighting:$i(t.lighting),rim:vi(t.rim),mapUV:Oi(t.mapUV),gradientMap:Mi(t.gradientMap),erosion:_i(t.erosion),uvDistortion:Ti(t.uvDistortion)},this.flip=(s=t.flip)&&(s.x>0||s.y>0)?s.clone():void 0,this.playbackSpeed=t.playbackSpeed??1,this.cullingMode=Fi(t.cullingMode),this.scalingMode="hierarchy"===t.scalingMode?"hierarchy":"shape",this.alignToDirection=!0===t.alignToDirection,this.seed=t.seed,this.ensureMeshNormals(),this.materialRef=t.material??null,this.applyMaterialSettings(this.materialRef,{blendMode:t.blendMode,transparent:t.transparent,depthTest:t.depthTest,depthWrite:t.depthWrite,alphaTest:t.alphaTest,texture:t.texture,layerMask:t.layerMask}),this.neededToUpdateRender=!0,this.particles=[],this.startTileIndex=t.startTileIndex||new Yt(0),this.emitter=new br(this,t.scene),this.paused=!1,this.particleNum=0,this.emissionState={isBursting:!1,burstParticleIndex:0,burstParticleCount:0,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,travelDistance:0},this.initSystemGenerators(),this.emitEnded=!1,this.prewarmed=!1}watchEnvAtlas(t,e){t?.onDisposeObservable.addOnce(()=>{if(this.destroyed||this.rendererSettings.reflectionAtlas!==t)return;this.rendererSettings.reflectionAtlas=null,e?.reflectionAtlas===t&&(e.reflectionAtlas=null),this.neededToUpdateRender=!0;const s=this.rendererSettings.reflectionTexture;s?.isCube&&s.getScene()&&this.sceneRef&&Nr(s,this.sceneRef,t=>{this.destroyed||this.rendererSettings.reflectionTexture!==s||(this.rendererSettings.reflectionAtlas=t,e&&null==e.reflectionAtlas&&(e.reflectionAtlas=t),this.watchEnvAtlas(t,e),this.neededToUpdateRender=!0)})})}applyMaterialSettings(t,e={}){if(!this.rendererSettings)return;const s=function(t,e,s){const i=void 0!==e.texture?e.texture:[t?.albedoTexture,t?.diffuseTexture,t?.emissiveTexture,t?.opacityTexture,t?.baseTexture].find(t=>t instanceof S.Texture)??s.texture??null,n=t?.reflectionTexture??t?.environmentTexture??s.reflectionTexture??null,r="number"==typeof n?.level?n.level:1,o=e.blendMode??("number"==typeof t?.alphaMode?t.alphaMode:s.materialBlendMode),a=e.transparent??("function"==typeof t?.needAlphaBlending?t.needAlphaBlending():"number"==typeof t?.alpha?t.alpha<1:s.materialTransparent),h=e.depthTest??("boolean"==typeof t?.disableDepthTest?!t.disableDepthTest:s.materialDepthTest),l=e.depthWrite??("boolean"==typeof t?.disableDepthWrite?!t.disableDepthWrite:"boolean"==typeof t?.forceDepthWrite?t.forceDepthWrite:s.materialDepthWrite),c=e.alphaTest??(()=>{const e=t?.transparencyMode,i=1===e||3===e;return i&&"number"==typeof t?.alphaCutOff?t.alphaCutOff:i&&"number"==typeof t?.alphaCutOffValue?t.alphaCutOffValue:t?0:s.materialAlphaTest})();return{texture:i,reflectionTexture:n,reflectionLevel:"number"==typeof t?.reflectionLevel?t.reflectionLevel:r,reflectionAtlas:ro(t?.reflectionAtlas)??ro(e.reflectionAtlas)??ro(s.reflectionAtlas),blendMode:o,transparent:a,depthTest:h,depthWrite:l,alphaTest:c}}(t,e,this.rendererSettings);this.rendererSettings.texture=s.texture,this.rendererSettings.reflectionTexture=s.reflectionTexture,this.rendererSettings.reflectionLevel=s.reflectionLevel;let i=s.reflectionAtlas;const n=s.reflectionTexture;!i&&n?.isCube&&(i=$r(n,this.sceneRef),!i&&this.sceneRef&&(Nr(n,this.sceneRef,e=>{this.rendererSettings.reflectionAtlas!==e&&(this.rendererSettings.reflectionAtlas=e,t&&!ro(t.reflectionAtlas)&&(t.reflectionAtlas=e),this.watchEnvAtlas(e,t),this.neededToUpdateRender=!0)}),i=$r(n,this.sceneRef))),this.rendererSettings.reflectionAtlas=i,this.watchEnvAtlas(i,t),this.rendererSettings.materialBlendMode=s.blendMode,this.rendererSettings.materialTransparent=s.transparent,this.rendererSettings.materialDepthTest=s.depthTest,this.rendererSettings.materialDepthWrite=s.depthWrite,this.rendererSettings.materialAlphaTest=Ni(s.alphaTest),void 0!==e.layerMask&&(this.rendererSettings.layerMask=e.layerMask),this.neededToUpdateRender=!0}pause(){this.paused=!0}play(){this.destroyed||(this.isFinished()&&this.restart(),this.resume())}resume(){this.destroyed||(this.paused=!1,this.previousEmitterMatrix=void 0)}stop(){this.restart(),this.pause()}clear(){this.particleNum=0,this.bounds.valid=!1;for(const t of this.behaviors)t instanceof Ge&&t.clearEmissions()}clearTrails(){if(this.rendererSettings.renderMode===exports.RenderMode.Trail)for(let t=0;t<this.particleNum;t++)this.particles[t].resetHistory()}setQualityFactor(t){this.qualityFactor=Math.max(.1,Math.min(1,t))}emissionFactor(){return this.qualityFactor*this.emissionMultiplierValue}endEmit(){this.emitEnded=!0,this.events.fire({type:"emitEnd",particleSystem:this})}get isDisposed(){return this.destroyed}dispose(){this.destroyed||(this.destroyed=!0,this.particleNum=0,this._renderer&&this._renderer.deleteSystem(this),function(t){Sr++;try{t.dispose()}finally{Sr--}}(this.emitter),this.events.fire({type:"destroy",particleSystem:this}))}initSystemGenerators(){const t=this.rng,e=void 0===t?void 0:_(t);try{this.clock.setStartDelay(this.emission.rollGenerators())}finally{void 0!==t&&_(e??null)}}restart(){this.destroyed||(this.emission.memory.length=0,this.paused=!1,this.particleNum=0,this.bounds.valid=!1,this.clock.reset(),void 0!==this.seedValue&&(this.rng=V(this.seedValue)),this.emissionState.isBursting=!1,this.emissionState.burstIndex=0,this.emissionState.burstWaveIndex=0,this.emissionState.burstWaves=void 0,this.emissionState.time=0,this.emissionState.waitEmiting=0,this.emissionState.travelDistance=0,this.emissionState.previousWorldPos=void 0,this.emissionState.burstParticleIndex=0,this.emissionState.burstParticleCount=0,this.emissionBursts.forEach(t=>Object.assign(t,Ri(t))),this.emissionBursts.sort((t,e)=>t.time-e.time),this.behaviors.forEach(t=>t.reset()),this.emitterShape.reset?.(),this.emitEnded=!1,this.finishedEventFired=!1,this.prewarmed=!1,this.initSystemGenerators(),this.previousEmitterPos=void 0,this.previousEmitterMatrix=void 0,this.emitterVelocity.set(0,0,0))}update(t,e=1/0,s){if(this.paused||this.destroyed)return;const i=this.playbackSpeed*this.timeDilationValue;if(t=so.frameSeconds(t,i),this.culled)return"pauseAndCatchUp"===this.cullingMode&&this.clock.deferCatchUp(t),void(this.previousEmitterMatrix=void 0);if(this.clock.owesCatchUp){if(this.catchUp(s??performance.now()+Qo.catchUpBudgetMs),this.paused||this.destroyed)return;(this.previousEmitterMatrix??(this.previousEmitterMatrix=new ot)).copy(this.emitter.matrixWorld)}if(this.firstTimeUpdate&&(this.firstTimeUpdate=!1,this.emitter.computeWorldMatrix(!0)),!this.looping&&this.finishedEventFired&&0===this.particleNum)return void this.clock.accrue(t,i);if(this.looping&&this.prewarm&&!this.prewarmed&&(this.runPrewarm(),this.paused||this.destroyed))return;this.neededToUpdateRender&&(this._renderer&&this._renderer.updateSystem(this),this.neededToUpdateRender=!1);const n=this.emitter.matrixWorld.elements;if(this.tempEmitterPos.set(n[12],n[13],n[14]),void 0!==this.previousEmitterPos&&t>0&&this.emitterVelocity.copy(this.tempEmitterPos).sub(this.previousEmitterPos).divideScalar(t),(this.previousEmitterPos??(this.previousEmitterPos=new et)).copy(this.tempEmitterPos),this.clock.delaying&&(!this.prewarm||!this.looping)&&0===(t=this.clock.consumeStartDelay(t)))return;const r=this.clock.accrue(t,i);if(0===r)return;const o=this.emitter.matrixWorld,a=this.previousEmitterMatrix,h=r>1&&void 0!==a&&!a.equals(o);h&&(a.decompose(Uo,Ro,Do),o.decompose(Lo,ko,qo));let l=o;for(let t=0;t<r;t++){if(h&&t+1<r){const e=(t+1)/r;Jo.copy(Uo).lerp(Lo,e),Wo.copy(Ro).slerp(ko,e),Go.copy(Do).lerp(qo,e),l=this.stepMatrix.compose(Jo,Wo,Go)}else l=o;if(this.simulateStep(eo,l),this.paused||this.destroyed)break;if(e!==1/0&&t+1<r&&performance.now()>=e)break}this.destroyed||(this.previousEmitterMatrix??(this.previousEmitterMatrix=new ot)).copy(l)}catchUp(t){let e=this.clock.takeCatchUpSteps();for(;e-- >0&&(this.simulateStep(eo),!this.paused&&!this.destroyed)&&!(e>0&&performance.now()>=t););}markBurstsBefore(t){const e=this.emissionState,s=this.emissionBursts,i=e.burstWaves??(e.burstWaves=[]);for(;e.burstIndex<s.length&&s[e.burstIndex].time<t;){const n=s[e.burstIndex],r=qr(n),o=Jr(n);let a=0;if(o>0)for(;a<r&&n.time+a*o<t;)a++;else a=r;i[e.burstIndex]=a,e.burstIndex++}}runPrewarm(){this.prewarmed=!0;const t=this.prewarmTime>0?this.prewarmTime:this.duration,e=Math.min(this.duration,t,Math.max(0,Qo.maxPrewarmSeconds)),s=Math.round(e/eo);if(e<this.duration){const t=this.emissionState;t.time=this.duration-s*eo,this.markBurstsBefore(t.time)}for(let t=0;t<s;t++)if(this.simulateStep(eo),this.paused||this.destroyed)return}getWorldBounds(t,e){if(!this.bounds.toWorld(t,e,this.emitter))return!1;if(this.rendererSettings.renderMode===exports.RenderMode.Beam){const s=this.beamEndScratch;if(!this.getBeamEnd(s))return!0;const i=this.bounds.worldPadding(this.emitter);t.set(Math.min(t.x,s.x-i),Math.min(t.y,s.y-i),Math.min(t.z,s.z-i)),e.set(Math.max(e.x,s.x+i),Math.max(e.y,s.y+i),Math.max(e.z,s.z+i))}return!0}getBeamEnd(t){const e=this.beamEnd;if(void 0===e)return!1;const s=e;if("function"==typeof s.getAbsolutePosition){const e=s.getAbsolutePosition();t.set(e.x,e.y,e.z)}else{const s=e;t.set(s.x,s.y,s.z)}return!0}setWorldBounds(t,e,s,i,n,r,o){this.bounds.setWorld(t,e,s,i,n,r,o)}get simulationStep(){return eo}get simulationResidual(){return this.paused?0:this.clock.residual}simulateStep(t,e=this.emitter.matrixWorld){const s=this.rng;if(void 0===s)return void this.stepOnce(t,e);const i=_(s);try{this.stepOnce(t,e)}finally{_(i)}}stepOnce(t,e){if(this.destroyed)return;this.motionScale=this.measureMotionScale(e),this.onlyUsedByOther||this.emission.emit(t,this.emissionState,e);const s=this.particles,i=this.behaviors,n=this.particleNum,r=this.store,o=this.rendererSettings.renderMode,a=o===exports.RenderMode.Trail,h=this.behaviorPlan.steps(i),l=this.behaviorPlan.changesSize,c=this.behaviorPlan.changesColor;!function(t,e,s,i,n,r){const o=3*e;t.useSizeSnapshot(s),t.useColorSnapshot(i),t.previousPosition.set(t.position.subarray(0,o)),s&&t.previousSize.set(t.size.subarray(0,o)),n&&(t.keepPreviousVelocity()&&r(),t.previousVelocity.set(t.velocity.subarray(0,o))),i&&t.previousColor.set(t.color.subarray(0,4*e))}(r,n,l,c,o===exports.RenderMode.StretchedBillBoard,this.rebindParticles),this.emitterShape.update(this,t),function(t,e,s,i,n,r){for(let o=0;o<t.length;o++){const a=t[o],h=a.behaviors;for(let t=0;t<h.length;t++)h[t].frameUpdate(n);if(0===i)continue;if(void 0!==a.run){a.run(e,s,i,n,r);continue}const l=h[0];if(void 0===l.updateAll)for(let t=0;t<i;t++){const e=s[t];e.age<e.life&&l.update(e,n)}else l.updateAll(s,i,n)}}(h,i,s,n,t,r);const u=this.events.has("particleDied")?this.fireParticleDied:void 0;let d=this.particleNum;if(a){const i=this.rendererEmitterSettings;!function(t,e,s,i){const n=t.scalars,r=Pe.SCALAR_STRIDE,o=t.previousSize,a=t.size,h=t.previousColor,l=t.color;for(let t=0,c=0,u=0,d=0;t<e;t++,c+=3,u+=4,d+=r)0===n[d+Pe.AGE]&&(s&&(o[c]=a[c],o[c+1]=a[c+1],o[c+2]=a[c+2]),i&&(h[u]=l[u],h[u+1]=l[u+1],h[u+2]=l[u+2],h[u+3]=l[u+3]))}(r,n,l,c),function(t,e,s,i,n,r){if(n){for(let s=0;s<i;s++){const i=e[s];i.localPosition?(i.position.copy(i.localPosition),i.position.applyMatrix4(i.parentMatrix??r)):i.position.addScaledVector(i.velocity,t*i.speedModifier),i.age+=t}return}const o=s.scalars,a=Pe.SCALAR_STRIDE,h=s.position,l=s.velocity;for(let e=0,s=0,n=0;e<i;e++,s+=3,n+=a){const e=t*o[n+Pe.SPEED_MODIFIER];h[s]+=l[s]*e,h[s+1]+=l[s+1]*e,h[s+2]+=l[s+2]*e,o[n+Pe.AGE]+=t}}(t,s,r,n,Boolean(i.followLocalOrigin),e),function(t,e,s,i,n){const r=s.dieWithParticle,o=s.recordWorldSpace&&!i,a=s.sideAxis,h=i||Boolean(s.recordWorldSpace),l=lr(s),c=cr(s);for(let s=0;s<e;s++){const e=t[s],i=e.age<e.life;if(r&&!i){e.resetHistory();continue}let u=!1;if(l>0&&i&&e.historyCount>1){const t=e.historyDistances,s=e.historyCount;u=t[e.getHistoryIndex(s-1)]-t[e.getHistoryIndex(s-2)]<l}if(e.update(u,!o),o&&i){const t=(e.historyHead+e.historyCapacity-1)%e.historyCapacity*3,s=e.historyPositions;io.set(s[t],s[t+1],s[t+2]),io.applyMatrix4(e.parentMatrix??n),s[t]=io.x,s[t+1]=io.y,s[t+2]=io.z,e.measureHeadDistance()}if(c!==1/0){const t=e.historyAges,s=e.age;for(;e.historyCount>0&&s-t[e.getHistoryIndex(0)]>c;)e.dropOldest()}if(a&&i){e.ensureSideHistory();const t=(e.historyHead+e.historyCapacity-1)%e.historyCapacity*3,s=e.historySides;let i=a.x,r=a.y,o=a.z;if(h){const t=(e.parentMatrix??n).elements,s=t[0]*i+t[4]*r+t[8]*o,a=t[1]*i+t[5]*r+t[9]*o;o=t[2]*i+t[6]*r+t[10]*o,i=s,r=a}s[t]=i,s[t+1]=r,s[t+2]=o}}}(s,n,i,this.worldSpace,e),d=function(t,e,s,i){const n=e.scalars,r=Pe.SCALAR_STRIDE;for(let o=0;o<s;o++){const a=t[o],h=o*r;n[h+Pe.AGE]>=n[h+Pe.LIFE]&&0===a.historyCount&&(no(t,e,o,s-1),s--,o--,void 0!==i&&i(a))}return s}(s,r,d,u)}else d=function(t,e,s,i,n,r,o,a,h){const l=s.scalars,c=Pe.SCALAR_STRIDE,u=s.position,d=s.velocity,f=s.previousSize,p=s.size,m=s.previousColor,y=s.color,g=o.due,v=o.min,x=o.max;let S=g?1/0:v.x,b=g?1/0:v.y,w=g?1/0:v.z,M=g?-1/0:x.x,z=g?-1/0:x.y,_=g?-1/0:x.z,V=g?0:o.maxSize,A=g?0:o.maxSpeedSq;for(let o=0;o<i;o++){const a=o*c;let v=l[a+Pe.AGE];const x=3*o,T=g||0===v;if(0===v&&(n&&(f[x]=p[x],f[x+1]=p[x+1],f[x+2]=p[x+2]),r)){const t=4*o;m[t]=y[t],m[t+1]=y[t+1],m[t+2]=y[t+2],m[t+3]=y[t+3]}const O=t*l[a+Pe.SPEED_MODIFIER],P=d[x],$=d[x+1],E=d[x+2],C=u[x]+P*O,F=u[x+1]+$*O,I=u[x+2]+E*O;if(u[x]=C,u[x+1]=F,u[x+2]=I,T&&(S=Math.min(S,C),M=Math.max(M,C),b=Math.min(b,F),z=Math.max(z,F),w=Math.min(w,I),_=Math.max(_,I),V=Math.max(V,Math.max(p[x],Math.max(p[x+1],p[x+2])))),A=Math.max(A,P*P+$*$+E*E),v+=t,l[a+Pe.AGE]=v,v>=l[a+Pe.LIFE]){const t=no(e,s,o,i-1);i--,o--,void 0!==h&&h(t)}}return o.store(i,g,S,b,w,M,z,_,V,A,a.rendererSettings,a.rendererEmitterSettings,a.worldSpace,eo),i}(t,s,r,d,l,c,this.bounds,this,u);this.particleNum=this.destroyed?0:d,this.notifyFinished()}notifyFinished(){this.isFinished()&&(this.finishedEventFired||(this.finishedEventFired=!0,this.events.fire({type:"finished",particleSystem:this})),this.autoDestroy&&this.dispose())}emit(t,e,s){this.emission.emit(t,e,s)}toJSON(t,e={}){return No(this,t)}static fromJSON(t,e,s={},i){const n=new Qo(Bo(t,e,i));return n.behaviors=(t.behaviors??[]).map((t,e)=>{const i=qt(`behaviors[${e}]`,()=>Os(t,n)),r=t.subParticleSystem;return i&&"EmitSubParticleSystem"===i.type&&"string"==typeof r&&(s[r]=i),i}).filter(t=>null!==t),n}addBehavior(t){this.behaviors.push(t),this._renderer?._invalidateUpdateOrder()}getRendererSettings(){return this.rendererSettings}addEventListener(t,e){this.events.add(t,e)}removeAllEventListeners(t){this.events.removeAll(t)}removeEventListener(t,e){this.events.remove(t,e)}clone(){const t=this.behaviors.map(t=>t.clone());let e;if(this.renderMode===exports.RenderMode.Trail){const t=this.rendererEmitterSettings;e={startLength:t.startLength.clone(),followLocalOrigin:Boolean(t.followLocalOrigin),...Po(t),...$o(t),...Eo(t),...t.sideAxis?{sideAxis:t.sideAxis.clone()}:{}}}else e=this.renderMode===exports.RenderMode.StretchedBillBoard?{lengthFactor:this.rendererEmitterSettings.lengthFactor,speedFactor:this.rendererEmitterSettings.speedFactor}:{};const s=new Qo({..._o(this),shape:this.emitterShape.clone(),instancingGeometry:this.rendererSettings.instancingGeometry,instancingIndices:this.rendererSettings.instancingIndices,instancingUVs:this.rendererSettings.instancingUVs,instancingUVs2:this.rendererSettings.instancingUVs2,instancingNormals:this.rendererSettings.instancingNormals,rendererEmitterSettings:e,material:this.materialRef,texture:this.rendererSettings.texture,behaviors:t,lighting:this.lighting,rim:this.rim,mapUV:this.mapUV,gradientMap:this.gradientMap,erosion:this.erosion,uvDistortion:this.uvDistortion,scene:this.emitter.getScene()});for(const e of t)e instanceof Ge&&(e.particleSystem=s);this.tint&&(s.tint=this.tint.clone()),s.emissionMultiplier=this.emissionMultiplier;const i=this.beamEnd;return i&&(s.beamEnd="function"==typeof i.getAbsolutePosition?i:{x:i.x,y:i.y,z:i.z}),s}}function jo(t){if("ps"===t.type&&t.target instanceof br)return t.target.system}function Ho(t){return"object"==typeof t&&null!==t}Qo.catchUpBudgetMs=2,Qo.maxPrewarmSeconds=10;class Yo extends n.TransformNode{constructor(t="QuarksPrefab",e){super(t,e),this.type="QuarksPrefab",this.animationData=[],this.isPlaying=!1,this.currentTime=-1e-5,this.duration=0,this._timeScale=1,this._tempAnimationJSON=[],this._autoUpdate=null,this._pendingEndEmit=new Set,this._pendingObserver=null,this._started=new Set,this._pausedSystems=new Set}get timeScale(){return this._timeScale}set timeScale(t){this._timeScale=t>0&&t<1/0?t:0;for(const t of this.animationData){const e=jo(t);void 0!==e&&(e.timeDilation=this._timeScale)}}get autoUpdate(){return null!==this._autoUpdate}set autoUpdate(t){t!==this.autoUpdate&&(t?this._autoUpdate=this.getScene().onBeforeRenderObservable.add(()=>this.update()):(this.getScene().onBeforeRenderObservable.remove(this._autoUpdate),this._autoUpdate=null))}registerBatchedRenderer(t){this._batchedRenderer=t}addParticleSystemAnimation(t,e=0,s=0,i=!1){const n={startTime:e,duration:s>0?s:t.system.duration,type:"ps",loop:i,target:t};return this.animationData.push(n),t.system.timeDilation=this._timeScale,this.updateDuration(),n}addThreeAnimation(t,e,s=0,i=e?.duration??0,n=!1,r){const o={startTime:s,duration:i>0?i:e?.duration??0,type:"three",loop:n,target:t,clip:e,clipUUID:r??e?.uuid};return this.animationData.push(o),this.updateDuration(),o}removeAnimation(t){const[e]=this.animationData.splice(t,1),s=e&&jo(e);void 0===s||this.animationData.some(t=>jo(t)===s)||(s.timeDilation=1,this._pendingEndEmit.delete(s)&&s.endEmit(),this._started.delete(s),this._pausedSystems.delete(s)),this.updateDuration()}play(){if(!this.isPlaying){this.isPlaying=!0;for(const t of this._pausedSystems)t.resume();this._pausedSystems.clear(),this.animationData.forEach(t=>{"three"===t.type&&this.isInside(t,this.currentTime)&&t.clip?.play?.()})}}pause(){this.isPlaying&&(this.isPlaying=!1,this.animationData.forEach(t=>{const e=jo(t);void 0===e?t.clip?.pause?.():e.paused||(e.pause(),this._pausedSystems.add(e))}))}stop(){this.pause(),this.currentTime=-1e-5,this.clearPending(),this._started.clear(),this._pausedSystems.clear(),this.animationData.forEach(t=>{const e=jo(t);void 0===e?t.clip?.stop?.():e.stop()})}update(t){if(this.flushPending(),!this.isPlaying)return;const e=t??this.getScene().getEngine().getDeltaTime()/1e3,s=this.currentTime,i=s+Math.max(e,0)*this._timeScale>=this.duration;if(this.currentTime=i?this.duration:s+Math.max(e,0)*this._timeScale,this.animationData.forEach(t=>{const e=this.isInside(t,s),n=this.isInside(t,this.currentTime),r=!e&&!n&&s<t.startTime&&this.currentTime>=t.startTime+t.duration;if(n&&!e)this.enterTrack(t);else if(r){this.enterTrack(t);const e=jo(t);void 0!==e?this.addPending(e):t.clip?.stop?.()}else e&&!n&&this.leaveTrack(t,!i)}),i){for(const t of this._started)this._pendingEndEmit.has(t)||t.isEmitEnded||t.endEmit();this._started.clear(),this.isPlaying=!1,this.currentTime=-1e-5}}setTime(t){const e=this.currentTime;this.currentTime=t,this.animationData.forEach(s=>{const i=this.isInside(s,t),n=this.isInside(s,e);if(i&&!n)this.enterTrack(s);else if(!i&&n)return void this.leaveTrack(s,!1);i&&"three"===s.type&&s.clip?.setTime?.(Math.max(t-s.startTime,0))})}dispose(t,e){this.autoUpdate=!1;for(const t of this._pendingEndEmit)t.endEmit();this.clearPending(),this._started.clear(),this._pausedSystems.clear(),super.dispose(t,e)}addPending(t){this._pendingEndEmit.add(t),this._pendingObserver??(this._pendingObserver=this.getScene().onAfterRenderObservable.add(()=>this.flushPending()))}flushPending(){for(const t of this._pendingEndEmit)(t.emissionState.time>0||t.isDisposed)&&(t.endEmit(),this._pendingEndEmit.delete(t));0===this._pendingEndEmit.size&&this.clearPending()}clearPending(){this._pendingEndEmit.clear(),null!==this._pendingObserver&&(this.getScene().onAfterRenderObservable.remove(this._pendingObserver),this._pendingObserver=null)}isInside(t,e){return e>=t.startTime&&e<t.startTime+t.duration}enterTrack(t){const e=jo(t);if(void 0!==e)return this._pendingEndEmit.delete(e),e.restart(),this._started.add(e),this.isPlaying||(e.pause(),this._pausedSystems.add(e)),void this._batchedRenderer?.addSystem(e);t.clip?.play?.()}leaveTrack(t,e){const s=jo(t);void 0===s?t.loop&&e?t.clip?.play?.():t.clip?.stop?.():t.loop&&e?s.restart():s.endEmit()}getDuration(){return this.duration}resolveReferences(t){const e={},s=t=>{var i;const r=fi(t);r?e[r]=t:e[i=t.uniqueId.toString()]??(e[i]=t);const o=t.getChildren();for(const t of o)t instanceof n.TransformNode&&s(t)};s(t),this._tempAnimationJSON.forEach(t=>{const s=e[t.targetUUID];if("ps"===t.type&&s instanceof br)this.addParticleSystemAnimation(s,t.startTime,t.duration,t.loop);else if("three"===t.type&&s){const e=this.resolveTimelineClip(s,t.clipUUID);this.addThreeAnimation(s,e,t.startTime,t.duration,t.loop,t.clipUUID)}}),this.updateDuration(),this._tempAnimationJSON=[]}toJSON(){return{type:this.type,name:this.name,...1!==this.timeScale?{timeScale:this.timeScale}:{},animationData:this.animationData.map(t=>({startTime:t.startTime,duration:t.duration,type:t.type,targetUUID:di(t.target),clipUUID:"three"===t.type?t.clipUUID??t.clip?.uuid:void 0,loop:t.loop}))}}static fromJSON(t,e){const s=new Yo(t.name||"QuarksPrefab",e);return"number"==typeof t.timeScale&&(s.timeScale=t.timeScale),Array.isArray(t.animationData)&&(s._tempAnimationJSON=t.animationData.filter(t=>"ps"===t?.type||"three"===t?.type)),s}resolveTimelineClip(t,e){const s=t,i=t.metadata,n=[s.animations,s.animationGroups,i?.animations,i?.animationGroups];for(const t of n){if(!Array.isArray(t))continue;const s=t;if(!e)return s.find(Ho);const i=s.find(t=>{return i=e,Ho(s=t)&&s.uuid===i;var s,i});if(i)return i}}updateDuration(){let t=0;this.animationData.forEach(e=>{const s=e.startTime+e.duration;s>t&&(t=s)}),this.duration=t}}const Xo=new WeakMap;function Zo(t,e,s){Xo.set(t,{source:e,loaded:s})}function Ko(t){const e=Xo.get(t);return void 0!==e&&t.url===e.loaded?e.source:void 0}const ta={[S.Texture.WRAP_ADDRESSMODE]:1e3,[S.Texture.CLAMP_ADDRESSMODE]:1001,[S.Texture.MIRROR_ADDRESSMODE]:1002};function ea(t){return!!t&&(!/^blob:/i.test(t)&&(!/^data:/i.test(t)||t.includes(",")))}function sa(t){const e=t.rotationQuaternion??a.Quaternion.FromEulerVector(t.rotation);return Array.from(a.Matrix.Compose(t.scaling,e,t.position).asArray())}class ia{constructor(t){this.options=t,this.meta={geometries:{},materials:{},textures:{}},this.meshGeometries=new Map,this.geometryIds=new Map,this.meshMaterials=[],this.meshMaterialIds=new Map,this.extraTextures=new Map,this.nextId=0}warnDanglingLinks(t){const e=new Set,s=[],i=t=>{e.add(t.uuid),s.push(t),t.children?.forEach(i)};i(t);for(const t of s)for(const[s,i]of ra(t))""===i||e.has(i)||this.warn(`"${t.name}" has ${s} on node "${i}", which is not in what is written; it loads without that link.`)}warn(t){(this.options.onWarning??(t=>console.warn(`[quarks] ${t}`)))(t)}node(t){const e=t.getChildren(t=>t instanceof n.TransformNode,!0).filter(t=>!1!==this.options.filter?.(t)).map(t=>this.node(t)),s={uuid:di(t),type:"Group",name:t.name,matrix:sa(t)};if(t.isEnabled(!1)||(s.visible=!1),t instanceof u.Mesh&&!t.isVisible&&(s.isVisible=!1),t instanceof br)s.type="ParticleEmitter",s.ps=t.system.toJSON(this.meta);else if(t instanceof Yo){const{type:e,name:i,...n}=t.toJSON();Object.assign(s,n),s.type="QuarksPrefab"}else t instanceof u.Mesh?(s.type="Mesh",s.geometry=this.meshGeometry(t),s.material=this.meshMaterial(t)):t instanceof x.InstancedMesh&&this.warn(`"${t.name}" is an instance of "${t.sourceMesh.name}"; it is written as a group.`);return e.length>0&&(s.children=e),s}id(t){return this.nextId+=1,`${t}_${this.nextId}`}meshGeometry(e){const s=e.geometry?this.geometryIds.get(e.geometry):void 0;if(void 0!==s)return s;const i=e.getVerticesData(t.VertexBuffer.PositionKind);if(!i||0===i.length)return void this.warn(`Mesh "${e.name}" has no vertices; it is written without geometry.`);const n=e.getIndices(),r=ci(i instanceof Float32Array?i:new Float32Array(i),n&&n.length>0?Uint32Array.from(n):void 0),o=t=>{const s=e.getVerticesData(t);return s?Array.from(s):void 0},a={uuid:this.id("quarks_mesh_geometry"),type:"QuarksGeometry",positions:Array.from(i),indices:Array.from(r)},h=o(t.VertexBuffer.UVKind),l=o(t.VertexBuffer.UV2Kind),c=o(t.VertexBuffer.NormalKind);return h&&(a.uvs=h),l&&(a.uvs2=l),c&&(a.normals=c),this.meshGeometries.set(a.uuid,a),e.geometry&&this.geometryIds.set(e.geometry,a.uuid),a.uuid}meshMaterial(t){const e=t.material;if(!e)return;if(!(e instanceof b.StandardMaterial))return void this.warn(`Mesh "${t.name}" has a ${e.getClassName()}; only a StandardMaterial's blend, culling and diffuse texture are written, so it loads without a material.`);let s=this.meshMaterialIds.get(e);if(void 0!==s)return s;s=this.id("quarks_mesh_material"),this.meshMaterialIds.set(e,s);const i=1===e.diffuseColor.r&&1===e.diffuseColor.g&&1===e.diffuseColor.b,n=0===e.emissiveColor.r&&0===e.emissiveColor.g&&0===e.emissiveColor.b;1===e.alpha&&i&&n||this.warn(`Mesh "${t.name}": its material's alpha and colours are not written; it loads opaque white.`);const o={uuid:s,type:"MeshBasicMaterial"};return e.alphaMode!==r.Constants.ALPHA_COMBINE&&(o.alphaMode=e.alphaMode),e.backFaceCulling&&(o.side=0),0!==e.alphaCutOff&&(o.alphaTest=e.alphaCutOff),e.disableDepthWrite||(o.depthWrite=!0),this.meshMaterials.push({json:o,map:e.diffuseTexture}),s}texture(t){for(const[e,s]of Object.entries(this.meta.textures))if(s===t)return e;let e=this.extraTextures.get(t);return void 0===e&&(e=this.id("quarks_mesh_texture"),this.extraTextures.set(t,e)),e}finish(t){const e=this.meshMaterials.map(({json:t,map:e})=>e?{...t,map:this.texture(e)}:t);this.warnDanglingLinks(t);const s=[],i=new Map,n=[],r=[...Object.entries(this.meta.textures),...[...this.extraTextures].map(([t,e])=>[e,t])];for(const[t,e]of r){if(null===e)continue;const r={uuid:t},o=e instanceof S.Texture?this.options.imageUrl?this.options.imageUrl(e):Ko(e)??e.url:null;if(ea(o)){let t=i.get(o);void 0===t&&(t=`quarks_image_${i.size+1}`,i.set(o,t),s.push({uuid:t,url:o})),r.image=t}else this.warn(`Texture "${e.name}" has no url a file can point at (made in code, a blob: url, or an image embedded in a glTF); it is written without its image and loads as no texture. Give it a file url or a data: URI before saving.`);e instanceof S.Texture&&Object.assign(r,oa(e)),n.push(r)}const o=Object.values(this.meta.materials).map(t=>{const{sourceMaterial:e,...s}=t;return s});return{metadata:{version:4.5,type:"Object3D",generator:this.options.generator??"babylon.quarks",quarksFormat:1},geometries:[...Object.values(this.meta.geometries).filter(na),...this.meshGeometries.values()],materials:[...o,...e],textures:n,images:s,object:t}}}function na(t){return"type"in t&&"QuarksGeometry"===t.type&&Array.isArray(t.positions)}function*ra(t){const e=t.ps;for(const t of e?.behaviors??[])"EmitSubParticleSystem"===t.type&&"subParticleSystem"in t&&"string"==typeof t.subParticleSystem&&(yield["a sub emitter",t.subParticleSystem]);"mesh_surface"===e?.shape?.type&&"string"==typeof e.shape.mesh&&(yield["a mesh surface shape",e.shape.mesh]);for(const e of t.animationData??[])"string"==typeof e.targetUUID&&(yield["a prefab animation",e.targetUUID])}function oa(t){const e={};return t.invertY||(e.invertY=!1),t.noMipmap&&(e.noMipmap=!0),t.samplingMode!==r.Constants.TEXTURE_TRILINEAR_SAMPLINGMODE&&(e.samplingMode=t.samplingMode),t.wrapU===S.Texture.WRAP_ADDRESSMODE&&t.wrapV===S.Texture.WRAP_ADDRESSMODE||(e.wrap=[ta[t.wrapU]??1e3,ta[t.wrapV]??1e3]),1===t.uScale&&1===t.vScale||(e.repeat=[t.uScale,t.vScale]),0===t.uOffset&&0===t.vOffset||(e.offset=[t.uOffset,t.vOffset]),0!==t.wAng&&(e.rotation=t.wAng),e}function aa(t){return null!==t&&"object"==typeof t}function ha(t){if(!Array.isArray(t))return Wt("This part is not a list; it is skipped."),[];const e=[];return t.forEach((t,s)=>{aa(t)?e.push(t):qt(`[${s}]`,()=>Wt("This entry is not an object; it is skipped."))}),e}function la(t,e){const s=aa(t)?t[e]:void 0;return Array.isArray(s)?s:[]}const ca=new WeakMap,ua=new WeakMap,da=new WeakMap,fa=new WeakMap,pa=new WeakMap;function ma(t,e){let s=t.get(e);return void 0===s&&(s=new Map,t.set(e,s)),s}const ya=new WeakMap,ga=new WeakMap;function va(t){if(!aa(t))return t;const e={...t};return Array.isArray(t.images)&&(e.images=t.images.map(t=>{if(!t||"object"!=typeof t)return t;const e={...t};if(ya.get(t)===e.url&&"string"==typeof e.url){ya.set(e,e.url);const s=ga.get(t);void 0!==s&&ga.set(e,s)}return e})),Array.isArray(t.geometries)&&(e.geometries=t.geometries.map(t=>t&&"object"==typeof t?{...t}:t)),e}const xa=new WeakMap,Sa=t=>t.reason??new Error("[QuarksLoader] The load was aborted."),ba=()=>new Error("[QuarksLoader] The scene was disposed while the effect loaded.");function wa(t,e){if(e?.aborted)throw Sa(e);if(t.isDisposed)throw ba()}function Ma(t,e,s){return wa(e,s),new Promise((i,n)=>{const r=()=>n(Sa(s));s?.addEventListener("abort",r,{once:!0});const o=e.onDisposeObservable.addOnce(()=>n(ba()));t.then(i,n).finally(()=>{s?.removeEventListener("abort",r),e.onDisposeObservable.remove(o)})})}class za{constructor(t,e={}){this.scene=t,this.options=e}async load(t,e={}){const{json:s,baseUrl:i}=await Ma(this.fetchEffectDocument(t,e.signal),this.scene,e.signal);return this.loadFromJSON(s,i,e)}async loadFromJSON(t,e,s={}){const i=s.signal;wa(this.scene,i);const n=e??this.options.baseUrl??"",r=va(t);await Ma(this.resolveResources(r,n),this.scene,i);const o=this.parseDocument(r,"");return await this.finishLoad(o,i),o.root}static disposeEffect(t){xr(t)}async finishLoad(t,e){try{if(this.options.waitForTextures){for(const e of t.textures)e.delayLoadState===r.Constants.DELAYLOADSTATE_NOTLOADED&&e.delayLoad();await Ma(Promise.all(t.textures.map(t=>xa.get(t))),this.scene,e)}wa(this.scene,e)}catch(e){throw this.scene.isDisposed||xr(t.root),e}}async loadAll(t,e={}){wa(this.scene,e.signal);const s=za.mapPool(t,e.concurrency,async(s,i)=>{wa(this.scene,e.signal);try{return await this.fetchEffectDocument(s,e.signal)}catch(n){if(!e.continueOnError||e.signal?.aborted||this.scene.isDisposed)throw n;return console.warn(`[QuarksLoader] Failed to fetch effect "${s}" (${i+1}/${t.length}):`,n),null}}),i=await Ma(s,this.scene,e.signal);return this.loadDocuments(i,e)}async loadFromJSONAll(t,e={}){const s=t.map(t=>{if(null!==t&&"object"==typeof t&&"json"in t){const e=t;return{json:va(e.json),baseUrl:e.baseUrl??this.options.baseUrl??""}}return{json:va(t),baseUrl:this.options.baseUrl??""}});return this.loadDocuments(s,e)}async resolveResources(t,e=""){await za.resolveLinkedResources(t,{baseUrl:e,resolver:this.options.resolver,scene:this.scene,onResourceError:this.options.onResourceError})}static async resolveLinkedResources(t,e={}){const s=e.baseUrl??"",i=e.resolver,n=e.scene;await za.inlineGeometryEntries(t,async t=>{const e=await za.resolveWith(i,t,"geometry",s);return za.fetchJsonWith(i,e,n)},e.onResourceError),await Promise.all(la(t,"images").map(async t=>{if(!aa(t)||"string"!=typeof t.url||!t.url)return;if(ya.get(t)===t.url)return;const e=t.url,n=await za.resolveWith(i,e,"image",s);t.url=n,ya.set(t,n),/^(data|blob):/i.test(n)||ga.set(t,e)}))}static async resolveExternalGeometries(t,e){await za.inlineGeometryEntries(t,e)}parse(t,e=""){return this.parseDocument(t,e).root}parseDocument(t,e){const{strict:s,onFormatWarning:i}=this.options,n=[],r=kt({onWarning:(t,e)=>{const r=e?`${t} (at ${e})`:t;s&&n.push(r),i?i(t,e):s||console.warn(`[quarks] ${r}`)}},()=>this.readDocument(t,e));if(n.length>0){za.disposeEffect(r.root);const t=n.length>1?` (and ${n.length-1} more)`:"";throw new Rt(`${n[0]}${t}`,n)}return r}readDocument(t,e){if(!aa(s=t)||!aa(s.object))throw new Rt('[QuarksLoader] Not an effect document: it has no "object" to load.');var s;const i=t,n=i.metadata?.quarksFormat;"number"==typeof n&&n>1&&Wt(`This effect was written in format ${n}, newer than the 1 this version of babylon.quarks reads; settings it does not know are left out.`);const r={ownedMaterials:[],images:{},imageSources:{},textures:{},geometries:{},materials:{}},{geometries:o,images:a,textures:h,materials:l}=i;o&&qt("geometries",()=>this.parseGeometries(ha(o),r)),a&&qt("images",()=>this.parseImages(ha(a),e,r)),h&&qt("textures",()=>this.parseTextures(ha(h),r)),l&&qt("materials",()=>this.parseMaterials(ha(l),r));const c=qt("object",()=>this.parseObject(i.object,r));this.linkReferences(c);const u=[...new Set(Object.values(r.textures).filter(t=>null!==t))];return gr(c,u,r.ownedMaterials),{root:c,textures:u}}parseGeometries(t,e){for(const s of t)if("PlaneGeometry"===s.type){const t=(s.width||1)/2,i=(s.height||1)/2;e.geometries[s.uuid]={positions:new Float32Array([-t,-i,0,t,-i,0,t,i,0,-t,i,0]),indices:new Uint32Array([0,1,2,0,2,3]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),normals:new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1])}}else if("SphereGeometry"===s.type)e.geometries[s.uuid]=this.parseSphereGeometry(s);else if("BufferGeometry"===s.type&&s.data){const t=this.parseBufferGeometry(s.data);e.geometries[s.uuid]=t}else"QuarksGeometry"===s.type&&("string"!=typeof s.url||s.positions||Wt(`Geometry "${s.url}" is an external file; use load(), loadFromJSON(), or resolveResources() before parse().`),e.geometries[s.uuid]=this.share({positions:new Float32Array(s.positions??[]),indices:s.indices?new Uint32Array(s.indices):new Uint32Array(0),uvs:s.uvs?new Float32Array(s.uvs):void 0,uvs2:s.uvs2?new Float32Array(s.uvs2):void 0,normals:s.normals?new Float32Array(s.normals):void 0}))}share(t){if(!1===this.options.shareResources)return t;const e=ma(fa,this.scene),s=function(t){let e=2166136261,s=2654435769;const i=[t.positions,t.indices,t.uvs,t.uvs2,t.normals];let n="";for(const t of i){if(void 0===t){n+="-,";continue}const i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n+=i.length+",";for(let t=0;t<i.length;t++)e=Math.imul(e^i[t],16777619),s=Math.imul(s^i[t],1540483477)^s>>>15}return`${n}${(e>>>0).toString(16)}${(s>>>0).toString(16)}`}(t),i=e.get(s);return void 0!==i?i:(e.set(s,t),t)}static clearSharedResources(t){da.delete(t),fa.delete(t),pa.delete(t)}static joinUrl(t,e){return/^(data|blob):/i.test(e)||/^[a-z][a-z0-9+.-]*:\/\//i.test(e)||e.startsWith("/")?e:t+e}parseSphereGeometry(t){const e=t.radius??.5,s=Math.max(3,Math.floor(t.widthSegments??16)),i=Math.max(2,Math.floor(t.heightSegments??8)),n=t.phiStart??0,r=t.phiLength??2*Math.PI,o=t.thetaStart??0,a=t.thetaLength??Math.PI,h=[],l=[],c=[],u=[],d=[];let f=0;for(let t=0;t<=i;t++){const u=[],p=t/i,m=o+p*a;for(let t=0;t<=s;t++){const i=t/s,o=n+i*r,a=-e*Math.cos(o)*Math.sin(m),d=e*Math.cos(m),y=e*Math.sin(o)*Math.sin(m);h.push(a,d,y);const g=Math.hypot(a,d,y)||1;l.push(a/g,d/g,y/g),c.push(i,1-p),u.push(f++)}d.push(u)}const p=o<=0,m=o+a>=Math.PI;for(let t=0;t<i;t++)for(let e=0;e<s;e++){const s=d[t][e+1],n=d[t][e],r=d[t+1][e],o=d[t+1][e+1];0===t&&p||u.push(s,n,o),t===i-1&&m||u.push(n,r,o)}const y=h.length/3>65535?new Uint32Array(u):new Uint16Array(u);return{positions:new Float32Array(h),indices:y,uvs:new Float32Array(c),normals:new Float32Array(l)}}parseBufferGeometry(t){let e,s,i,n=new Float32Array(0),r=new Uint32Array(0);const o=t.attributes?.uv1??t.attributes?.uv2;if(t.interleavedBuffers&&t.arrayBuffers){const r={};for(const[e,s]of Object.entries(t.interleavedBuffers)){const i=t.arrayBuffers[s.buffer];if(i){const t=new Float32Array(Array.isArray(i)?this.int32ArrayToFloat32(i):i);r[e]={data:t,stride:s.stride}}}const a=t=>{const e=t?.isInterleavedBufferAttribute&&void 0!==t.data?r[t.data]:void 0;return e?this.extractInterleavedAttribute(e.data,e.stride,t?.offset,t?.itemSize):void 0};n=a(t.attributes?.position)??n,e=a(t.attributes?.uv),s=a(o),i=a(t.attributes?.normal)}else t.attributes&&(t.attributes.position?.array&&(n=new Float32Array(t.attributes.position.array)),t.attributes.uv?.array&&(e=new Float32Array(t.attributes.uv.array)),o?.array&&(s=new Float32Array(o.array)),t.attributes.normal?.array&&(i=new Float32Array(t.attributes.normal.array)));return t.index&&(r="Uint16Array"===t.index.type?new Uint16Array(t.index.array):new Uint32Array(t.index.array)),r=ci(n,r),{positions:n,indices:r,uvs:e,uvs2:s,normals:i}}extractInterleavedAttribute(t,e,s=0,i=0){const n=Math.floor(t.length/e),r=new Float32Array(n*i);for(let o=0;o<n;o++)for(let n=0;n<i;n++)r[o*i+n]=t[o*e+s+n];return r}int32ArrayToFloat32(t){const e=new ArrayBuffer(4*t.length),s=new Int32Array(e);for(let e=0;e<t.length;e++)s[e]=t[e];return new Float32Array(e)}async resolveResourceUrl(t,e,s){return za.resolveWith(this.options.resolver,t,e,s)}async fetchEffectDocument(t,e){const s=this.options.baseUrl||t.substring(0,t.lastIndexOf("/")+1),i=await this.resolveResourceUrl(t,"effect",s);return{json:await za.fetchJsonWith(this.options.resolver,i,void 0,e),baseUrl:s}}async loadDocuments(t,e){if(0===t.length)return[];wa(this.scene,e.signal);const s=new AbortController,i=()=>s.abort(Sa(e.signal));e.signal?.addEventListener("abort",i,{once:!0});try{return await this.loadResolvedDocuments(t,e,s)}finally{e.signal?.removeEventListener("abort",i)}}async loadResolvedDocuments(t,e,s){const i=t.length,n=s.signal,r=new Array(i).fill(null),o=new Array(i).fill(!1);let a=0;const h=(t,s)=>{o[t]||n.aborted||(o[t]=!0,r[t]=s,a++,e.onProgress?.(a,i))};await Ma(Promise.all(t.map(async(s,n)=>{if(s)try{await this.resolveResources(s.json,s.baseUrl)}catch(s){if(!e.continueOnError)throw s;console.warn(`[QuarksLoader] Failed to resolve resources for effect ${n+1}/${i}:`,s),t[n]=null,h(n,null)}})),this.scene,n);const l=[],c=[];try{for(let s=0;s<i;s++){if(o[s])continue;const r=t[s];if(!r){h(s,null);continue}let a;try{a=this.parseDocument(r.json,"")}catch(t){if(!e.continueOnError)throw t;console.warn(`[QuarksLoader] Failed to parse effect ${s+1}/${i}:`,t),h(s,null);continue}l.push(a),c.push(this.finishLoad(a,n).then(()=>h(s,a.root)))}await Promise.all(c)}catch(t){throw n.aborted||s.abort(t),Promise.allSettled(c),this.scene.isDisposed||l.forEach(t=>xr(t.root)),t}return r}static async mapPool(t,e,s){if(0===t.length)return[];const i=void 0!==e&&e>0?e:t.length,n=new Array(t.length);let r=0;const o=Math.min(i,t.length);return await Promise.all(Array.from({length:o},()=>(async()=>{for(;r<t.length;){const e=r++;n[e]=await s(t[e],e)}})())),n}static async resolveWith(t,e,s,i){return t?.resolve?t.resolve(e,s,i):za.joinUrl(i,e)}static fetchJsonWith(t,e,s,i){const n=async()=>{if(t?.fetchJson)return i?t.fetchJson(e,{signal:i}):t.fetchJson(e);const s=await(i?fetch(e,{signal:i}):fetch(e));if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.json()};if(!s)return n();const r=ma(pa,s),o=`json|${e}`;let a=r.get(o);return void 0===a&&(a=n().catch(t=>{throw r.get(o)===a&&r.delete(o),t}),r.set(o,a)),a}static async inlineGeometryEntries(t,e,s=za.warnResourceError){await Promise.all(la(t,"geometries").map(async t=>{if(!aa(t)||"string"!=typeof t.url||t.positions)return;const i=t.url;try{const s=await e(i);for(const e of["positions","indices","uvs","uvs2","normals"]){const i=aa(s)?s[e]:void 0;void 0!==i&&(t[e]=Array.isArray(i)?i.slice():i)}delete t.url}catch(t){s("geometry",i,t)}}))}static warnResourceError(t,e,s){console.warn(`[QuarksLoader] Could not load ${t} "${e}":`,s)}reportResourceError(t,e,s){(this.options.onResourceError??za.warnResourceError)(t,e,s)}parseImages(t,e,s){for(const[i,n]of t.entries()){const t=n.url;t&&qt(`[${i}]`,()=>za.warnIfNotAnImageUrl(t)),s.images[n.uuid]=t?za.joinUrl(e,t):null;const r=ga.get(n)??t;r&&!/^(data|blob):/i.test(r)&&(s.imageSources[n.uuid]=r)}}static warnIfNotAnImageUrl(t){/^(data|blob):/i.test(t)||/\.(png|jpe?g|webp|gif|bmp|ktx2?|dds|env|basis)(\?|#|$)/i.test(t)||Wt(`Image "${t}" does not look like an image; its texture will fail to load. This usually means the effect was exported without embedding that texture.`)}parseTextures(t,e){for(const s of t){const t=void 0!==s.image?e.images[s.image]:void 0;if(t){const i=void 0===s.invertY||!!s.invertY,n=!!s.noMipmap,r=!1!==this.options.shareResources,o=r?[i,n,s.samplingMode,s.wrap,s.repeat,s.offset,s.rotation].join("|")+"|"+t:"",a=r?ma(da,this.scene):void 0,h=a?.get(o);if(void 0!==h){e.textures[s.uuid]=h;continue}let l;const c=new Promise(t=>l=t);let u,d=!1;const f={noMipmap:n,invertY:i,samplingMode:"number"==typeof s.samplingMode?s.samplingMode:void 0,onLoad:()=>l(),onError:(e,s)=>{d=!0,void 0!==a&&a.get(o)===u&&a.delete(o),this.reportResourceError("image",t,s??e),l()}};try{u=new S.Texture(t,this.scene,f)}catch{e.textures[s.uuid]=null;continue}xa.set(u,c);const p=void 0!==s.image?e.imageSources[s.image]:void 0;void 0!==p&&Zo(u,p,t),u.onDisposeObservable.addOnce(()=>l()),Array.isArray(s.wrap)&&(u.wrapU=this.mapWrapMode(s.wrap[0]),u.wrapV=this.mapWrapMode(s.wrap[1]??s.wrap[0])),Array.isArray(s.repeat)&&(u.uScale=s.repeat[0]??1,u.vScale=s.repeat[1]??1),Array.isArray(s.offset)&&(u.uOffset=s.offset[0]??0,u.vOffset=s.offset[1]??0),"number"==typeof s.rotation&&(u.wAng=s.rotation),void 0===a||d||(a.set(o,u),u.onDisposeObservable.addOnce(()=>{a.get(o)===u&&a.delete(o)})),e.textures[s.uuid]=u}else e.textures[s.uuid]=null}}mapWrapMode(t){switch(t){case 1001:return S.Texture.CLAMP_ADDRESSMODE;case 1002:return S.Texture.MIRROR_ADDRESSMODE;default:return S.Texture.WRAP_ADDRESSMODE}}parseMaterials(t,e){const s=t=>"string"==typeof t&&e.textures[t]||null;for(const i of t){const t={uuid:i.uuid,transparent:i.transparent??!0,blending:i.blending??1,side:i.side??2,depthTest:i.depthTest??!0,depthWrite:i.depthWrite??!1,alphaTest:i.alphaTest??0,texture:null},n=i.map??i.texture;n&&(t.texture=s(n));const o=i.reflectionAtlas;if(o&&(t.reflectionAtlas=s(o)),"number"==typeof i.reflectionLevel&&(t.reflectionLevel=i.reflectionLevel),"unlit"!==i.lighting&&"fixed"!==i.lighting&&"scene"!==i.lighting||(t.lighting=i.lighting),i.rim&&"object"==typeof i.rim&&(t.rim=i.rim),i.mapUV&&"object"==typeof i.mapUV&&(t.mapUV=i.mapUV),i.gradientMap&&"object"==typeof i.gradientMap&&(t.gradientMap={...i.gradientMap,ramp:s(i.gradientMap.ramp)}),i.erosion&&"object"==typeof i.erosion&&(t.erosion={...i.erosion,mask:s(i.erosion.mask)}),i.uvDistortion&&"object"==typeof i.uvDistortion&&(t.uvDistortion={...i.uvDistortion,map:s(i.uvDistortion.map)}),"number"==typeof i.alphaMode)t.alphaMode=i.alphaMode;else{const e={1:r.Constants.ALPHA_COMBINE,2:r.Constants.ALPHA_ADD,3:r.Constants.ALPHA_SUBTRACT,4:r.Constants.ALPHA_MULTIPLY};t.alphaMode=e[i.blending??1]||r.Constants.ALPHA_COMBINE}e.materials[i.uuid]=t}}getGeometry(t,e){if(e)return t.geometries[e]}getMaterial(t,e){if(!e)return;const s=Array.isArray(e)?e[0]:e;return t.materials[s]}createPlaceholderNode(t,e){const s=new n.TransformNode(e||t||"node",this.scene);return Object.assign(s,{quarksOriginalType:t}),s}createMeshNode(t,e){const s=new u.Mesh(t.name||t.type||"mesh",this.scene),i=this.getGeometry(e,t.geometry);if(i&&i.positions.length>0&&i.indices.length>0){const t=new d.VertexData;t.positions=i.positions,t.indices=i.indices,i.uvs&&i.uvs.length>0&&(t.uvs=i.uvs),i.uvs2&&i.uvs2.length>0&&(t.uvs2=i.uvs2),i.normals&&i.normals.length>0&&(t.normals=i.normals),t.applyToMesh(s,!0)}const n=this.getMaterial(e,t.material);if(n){const t=new b.StandardMaterial(`quarks_loader_material_${n.uuid}`,this.scene);e.ownedMaterials.push(t),t.alphaMode=n.alphaMode??r.Constants.ALPHA_COMBINE,t.backFaceCulling=2!==n.side,t.alphaCutOff=n.alphaTest??0,t.disableDepthWrite=!n.depthWrite;const i=n.texture;i&&"string"!=typeof i&&(t.diffuseTexture=i,t.opacityTexture=i),s.material=t}return s}parseObject(t,e){let s;switch(t.type){case"QuarksPrefab":s=Yo.fromJSON(t,this.scene);break;case"ParticleEmitter":if(t.ps){const i=t.ps,n=qt("ps",()=>this.parseParticleSystem(i,e));s=n.emitter;break}s=this.createPlaceholderNode(t.type,t.name);break;case"Mesh":case"SkinnedMesh":case"InstancedMesh":case"BatchedMesh":s=this.createMeshNode(t,e);break;case"Scene":case"Group":case"Object3D":case"PerspectiveCamera":case"OrthographicCamera":case"AmbientLight":case"DirectionalLight":case"PointLight":case"RectAreaLight":case"SpotLight":case"HemisphereLight":case"LightProbe":case"LOD":case"Line":case"LineSegments":case"LineLoop":case"PointCloud":case"Points":case"Sprite":case"Bone":s=this.createPlaceholderNode(t.type,t.name);break;default:s=new n.TransformNode(t.name||t.type||"node",this.scene)}if(t.uuid&&function(t,e){ui.set(t,e)}(s,t.uuid),t.name&&(s.name=t.name),t.matrix){const e=a.Matrix.FromArray(t.matrix),i=new a.Vector3(1,1,1),n=a.Quaternion.Identity(),r=new a.Vector3(0,0,0);e.decompose(i,n,r),s.position.copyFrom(r),s.scaling.copyFrom(i),s.rotationQuaternion=n}else t.position&&s.position.set(t.position[0],t.position[1],t.position[2]),t.scale&&s.scaling.set(t.scale[0],t.scale[1],t.scale[2]),t.quaternion?s.rotationQuaternion=new a.Quaternion(t.quaternion[0],t.quaternion[1],t.quaternion[2],t.quaternion[3]):t.rotation&&s.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]);if(void 0!==t.visible&&s.setEnabled(t.visible),!1===t.isVisible&&s instanceof u.Mesh&&(s.isVisible=!1),t.children){const i=t.children;Array.isArray(i)?i.forEach((t,i)=>{const n=qt(`children[${i}]`,()=>aa(t)?this.parseObject(t,e):Wt("A child is not an object; it is skipped."));n&&(n.parent=s)}):qt("children",()=>Wt('"children" is not a list; the node loads without them.'))}return s}parseParticleSystem(t,e){const s=Qo.fromJSON(t,e,{},this.scene);return"mesh_surface"===t?.shape?.type&&"string"==typeof t.shape.mesh&&ca.set(s,t.shape.mesh),ua.set(s,Jt()),s}linkReferences(t){const e={},s=t=>{const i=fi(t);i&&(e[i]=t);for(const e of t.getChildren())e instanceof n.TransformNode&&s(e)};s(t);const i=s=>{if(s instanceof Yo&&s.resolveReferences(t),s instanceof br){const t=s.system,i=ua.get(t),n=t=>i?qt(i,()=>Wt(t)):Wt(t),r=ca.get(t),o=t.emitterShape;if(r&&o instanceof pi){const t=e[r];t instanceof u.Mesh?o.mesh=t:n(`Emitter "${s.name}" has a mesh surface shape on "${r}", `+(t?"which is not a mesh":"which is not in the effect")+"; it emits nothing until a mesh is set.")}for(let i=0;i<t.behaviors.length;i++)if(t.behaviors[i]instanceof Ge){const r=t.behaviors[i],o=r.subParticleSystem;if("string"!=typeof o)continue;const a=e[o];a instanceof br?(r.subParticleSystem=a,a.system.onlyUsedByOther=!0):(r.subParticleSystem=void 0,""!==o&&n(`Emitter "${s.name}" has a sub emitter targeting "${o}", `+(a?"which is not a particle emitter":"which is not in the effect")+"; that sub emitter is skipped."))}}for(const t of s.getChildren())t instanceof n.TransformNode&&i(t)};i(t)}}const _a={};const Va={name:""},Aa=[{name:"billboard",settings:{renderMode:exports.RenderMode.BillBoard}},{name:"vertical billboard",settings:{renderMode:exports.RenderMode.VerticalBillBoard}},{name:"horizontal billboard",settings:{renderMode:exports.RenderMode.HorizontalBillBoard}},{name:"stretched",settings:{renderMode:exports.RenderMode.StretchedBillBoard}},{name:"beam",settings:{renderMode:exports.RenderMode.Beam}},{name:"mesh",settings:{renderMode:exports.RenderMode.Mesh}},{name:"mesh scene lit",settings:{renderMode:exports.RenderMode.Mesh,lighting:"scene"}},{name:"mesh unlit",settings:{renderMode:exports.RenderMode.Mesh,lighting:"unlit"}},{name:"mesh rim",settings:{renderMode:exports.RenderMode.Mesh,rim:vi({mode:"add"})}},{name:"mesh unlit rim mix",settings:{renderMode:exports.RenderMode.Mesh,lighting:"unlit",rim:vi({mode:"mix"})}},{name:"mesh unlit rim fade",settings:{renderMode:exports.RenderMode.Mesh,lighting:"unlit",rim:vi({mode:"fade"})}},{name:"mesh reflecting",settings:{renderMode:exports.RenderMode.Mesh,reflectionAtlas:_a},context:{envAtlasReady:!0}},{name:"mesh unlit reflecting rim fade",settings:{renderMode:exports.RenderMode.Mesh,lighting:"unlit",reflectionAtlas:_a,rim:vi({mode:"fade"})},context:{envAtlasReady:!0}},{name:"trail",settings:{renderMode:exports.RenderMode.Trail}}],Ta=[Va,{name:"pivot",settings:{pivot:new et(.5,0,0)}},{name:"size limits",settings:{minParticleSize:.01}},{name:"pivot size limits",settings:{pivot:new et(0,.5,.5),maxParticleSize:.5}}],Oa=[Va,{name:"sheet",settings:{uTileCount:4,vTileCount:2}},{name:"sheet blend",settings:{uTileCount:4,vTileCount:2,blendTiles:!0}}],Pa=[Va,{name:"map",settings:{texture:_a}}],$a=[Va,{name:"soft",settings:{softParticles:!0},context:{depth:{packed:!1}}},{name:"soft packed",settings:{softParticles:!0},context:{depth:{packed:!0}}}],Ea=[Va,{name:"alpha test",settings:{materialAlphaTest:.5}}],Ca=[Va,{name:"fog",settings:{applyFog:!0}},{name:"fog additive",settings:{applyFog:!0,materialBlendMode:r.Constants.ALPHA_ADD}}],Fa=[{name:"premultiplied",settings:{materialBlendMode:r.Constants.ALPHA_PREMULTIPLIED}},{name:"premultiplied fog",settings:{materialBlendMode:r.Constants.ALPHA_PREMULTIPLIED,applyFog:!0}},{name:"one-one",settings:{materialBlendMode:r.Constants.ALPHA_ONEONE}},{name:"one-one fog",settings:{materialBlendMode:r.Constants.ALPHA_ONEONE,applyFog:!0}},{name:"multiply",settings:{materialBlendMode:r.Constants.ALPHA_MULTIPLY}},{name:"multiply fog",settings:{materialBlendMode:r.Constants.ALPHA_MULTIPLY,applyFog:!0}},{name:"multiply fog alpha test",settings:{materialBlendMode:r.Constants.ALPHA_MULTIPLY,applyFog:!0,materialAlphaTest:.5}},{name:"opaque",settings:{materialTransparent:!1}}],Ia=(()=>{const t=Oi({tiling:[2,2]}),e=Oi({channel:1,tiling:[2,2]}),s=Ti({map:_a}),i=Ti({map:_a,mapUV:{channel:1}}),n=Mi({ramp:_a}),r=_i({}),o=_i({mask:_a}),a=_i({mask:_a,maskUV:{channel:1}});return[{name:"map transform",settings:{mapUV:t}},{name:"map transform uv1",settings:{mapUV:e}},{name:"gradient map",settings:{gradientMap:n}},{name:"erosion",settings:{erosion:r}},{name:"erosion mask",settings:{erosion:o}},{name:"erosion mask uv1",settings:{erosion:a}},{name:"distortion",settings:{uvDistortion:s}},{name:"distortion uv1",settings:{uvDistortion:i}},{name:"map transform distortion gradient erosion mask",settings:{mapUV:t,uvDistortion:s,gradientMap:n,erosion:o}},{name:"map transform uv1 distortion gradient erosion",settings:{mapUV:e,uvDistortion:s,gradientMap:n,erosion:r}},{name:"every effect on uv1",settings:{mapUV:e,uvDistortion:i,gradientMap:n,erosion:a}}]})(),Na=["billboard","stretched","beam","mesh","mesh unlit","mesh unlit rim mix","mesh reflecting","trail"],Ba={name:"uv2",context:{meshUV2:!0}},Ua={name:"soft packed alpha test fog one-one",settings:{softParticles:!0,materialAlphaTest:.5,applyFog:!0,materialBlendMode:r.Constants.ALPHA_ONEONE},context:{depth:{packed:!0}}};li(mi),exports.ApplyCollision=$t,exports.ApplyForce=we,exports.ApplySequences=_e,exports.AxisAngleGenerator=ie,exports.BatchedRenderer=pr,exports.BehaviorFromJSON=Os,exports.BehaviorToJSON=Ps,exports.BehaviorTypes=Ts,exports.Bezier=Zt,exports.BoxEmitter=js,exports.ChangeEmitDirection=Ve,exports.CircleEmitter=Ys,exports.ColorBySpeed=Te,exports.ColorGeneratorFromJSON=de,exports.ColorOverLife=Oe,exports.ColorRange=ne,exports.ConeEmitter=Xs,exports.ConstantColor=ue,exports.ConstantValue=Yt,exports.ContinuousLinearFunction=re,exports.DEG2RAD=O,exports.DonutEmitter=Zs,exports.EROSION_DEFAULT_SOFTNESS=zi,exports.EdgeEmitter=Ks,exports.EffectPool=class{constructor(t,e){this.template=t,this.options=e,this.idle=[],this.playing=new Set,this.systemsOf=new Map,this.restOf=new Map,this.disposed=!1,this.onSystemFinished=t=>{const e=t.particleSystem;for(const t of this.playing){const s=this.systemsOf.get(t);if(void 0!==s&&s.includes(e))return void(wr.isEffectFinished(t)&&this.release(t))}};for(let t=0;t<(e.prewarm??0);t++){const t=this.makeCopy();if(null===t)break;this.idle.push(t)}}get activeCount(){return this.playing.size}get idleCount(){return this.idle.length}acquire(t,e=null){if(this.disposed)return null;const s=this.idle.pop()??this.makeCopy();if(null===s)return null;const i=void 0===t||"number"==typeof t.x?{position:t,parent:e}:t;return this.placeCopy(s,i),s.setEnabled(!0),this.playing.add(s),wr.restart(s),wr.play(s),s}stop(t){this.playing.has(t)&&wr.endEmit(t)}release(t){this.playing.delete(t)&&(t.isDisposed()?this.forget(t):(wr.stop(t),t.setEnabled(!1),t.parent=null,this.disposed||this.idle.push(t)))}dispose(){this.disposed=!0;for(const t of[...this.playing,...this.idle])this.playing.delete(t),this.disposeCopy(t);this.idle.length=0}makeCopy(){if(this.idle.length+this.playing.size>=(this.options.maxSize??1/0))return null;const t=wr.instantiate(this.template),e=[];return wr.runOnAllParticleEmitters(t,t=>{const s=t.system;s.autoDestroy=!1,s.addEventListener("finished",this.onSystemFinished),e.push(s)}),this.systemsOf.set(t,e),this.restOf.set(t,{position:t.position.clone(),rotation:t.rotation.clone(),rotationQuaternion:t.rotationQuaternion?.clone()??null,scaling:t.scaling.clone()}),wr.addToBatchRenderer(t,this.options.renderer),t.setEnabled(!1),t.parent=null,t.onDisposeObservable.addOnce(()=>this.forget(t)),t}placeCopy(t,e){const s=this.restOf.get(t);t.parent=e.parent??null;const i=e.position??s.position,n=e.scaling??s.scaling;t.position.copyFromFloats(i.x,i.y,i.z),t.scaling.copyFromFloats(n.x,n.y,n.z),void 0!==e.rotationQuaternion?t.rotationQuaternion=e.rotationQuaternion.clone():void 0!==e.rotation?(t.rotationQuaternion=null,t.rotation.copyFromFloats(e.rotation.x,e.rotation.y,e.rotation.z)):(t.rotationQuaternion=s.rotationQuaternion?.clone()??null,t.rotation.copyFrom(s.rotation))}forget(t){for(const e of this.systemsOf.get(t)??[])e.removeEventListener("finished",this.onSystemFinished),this.options.renderer.deleteSystem(e),e.dispose();this.systemsOf.delete(t),this.restOf.delete(t),this.playing.delete(t);const e=this.idle.indexOf(t);-1!==e&&this.idle.splice(e,1)}disposeCopy(t){this.forget(t),xr(t)}},exports.EmitSubParticleSystem=Ge,exports.EmitterFrame=be,exports.EmitterFromJSON=oi,exports.EmitterShapes=ri,exports.EmitterToJSON=ai,exports.Euler=yt,exports.EulerGenerator=fe,exports.ForceOverLife=Qe,exports.FrameOverLife=je,exports.GRADIENT_MAP_WEIGHTS=wi,exports.GeneratorFromJSON=ve,exports.Gradient=ae,exports.GravityForce=He,exports.GridEmitter=ti,exports.HemisphereEmitter=ei,exports.InheritVelocity=Ye,exports.IntervalValue=Xt,exports.LimitSpeedOverLife=Xe,exports.MAX_TRAIL_TESSELLATION=16,exports.MathUtils=K,exports.Matrix3=gt,exports.Matrix4=ot,exports.MeshSurfaceEmitter=pi,exports.MeshSurfaceEmitterPlugin=mi,exports.NodeParticle=class{constructor(){this.position=new et,this.velocity=new et,this.age=0,this.life=1,this.size=new et,this.rotation=0,this.color=new Vt(1,1,1,1),this.uvTile=0,this.memory=[]}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.position.set(0,0,0),this.velocity.set(0,0,0),this.age=0,this.life=1,this.size.set(1,1,1),this.rotation=0,this.color.set(1,1,1,1),this.uvTile=0}},exports.Noise=ds,exports.OrbitOverLife=fs,exports.ParticleEmitter=br,exports.ParticleStore=Pe,exports.ParticleSystem=Qo,exports.PiecewiseBezier=te,exports.PiecewiseFunction=Kt,exports.Plugins=hi,exports.PointEmitter=si,exports.QUARKS_FORMAT_VERSION=1,exports.QuarksFormatError=Rt,exports.QuarksLoader=za,exports.QuarksPrefab=Yo,exports.QuarksUtil=wr,exports.Quaternion=tt,exports.QuaternionView=St,exports.RAD2DEG=P,exports.RandomColor=he,exports.RandomColorBetweenGradient=ce,exports.RandomQuatGenerator=pe,exports.RecordState=class{constructor(t,e,s){this.position=t,this.size=e,this.color=s}},exports.RectangleEmitter=ni,exports.Rotation3DOverLife=ms,exports.RotationBySpeed=ys,exports.RotationGeneratorFromJSON=me,exports.RotationOverLife=gs,exports.SequencerFromJSON=ze,exports.ShapeTransform=Ws,exports.SizeBySpeed=vs,exports.SizeOverLife=xs,exports.SpeedOverLife=Ss,exports.SphereEmitter=ii,exports.SpriteParticle=Ce,exports.SubEmitterInheritMask=Je,exports.TextureSequencer=Me,exports.TrailParticle=Ie,exports.TurbulenceField=ws,exports.UV_DISTORTION_DEFAULT_STRENGTH=Ai,exports.UV_DISTORTION_DEFAULT_UV=Vi,exports.VFXBatch=sr,exports.ValueGeneratorFromJSON=ee,exports.Vector2=wt,exports.Vector3=et,exports.Vector3Function=ye,exports.Vector3GeneratorFromJSON=ge,exports.Vector3View=zt,exports.Vector4=Vt,exports.Vector4View=Tt,exports.VelocityOverLife=Vs,exports.WebGLCoordinateSystem=nt,exports.WebGPUCoordinateSystem=rt,exports.WidthOverLength=As,exports.blendCategory=Hn,exports.cacheEnvAtlas=function(t,e){const s=Pr(e)??Pr(t);s?Cr(t,s,e):console.warn("[babylon.quarks] cacheEnvAtlas: neither the atlas nor the cube has a scene; not cached")},exports.ceilPowerOfTwo=j,exports.clamp=E,exports.createEnvAtlasFromFaceUrls=Fr,exports.createSeededRandom=V,exports.cubeFaceUrls=Or,exports.currentFormatPath=Jt,exports.damp=B,exports.decodeSoftDepth=function(t,e){const s=e.z*t+e.w,i=Math.abs(s)>1e-8?Math.abs((e.x*t+e.y)/s):0;return i>0?i:1e30},exports.defaultMeshLighting=gi,exports.degToRad=W,exports.denormalize=X,exports.disposeEnvAtlas=Er,exports.ensureEnvAtlasFromCube=Nr,exports.erosionEqual=function(t,e){return t===e||!(!t||!e)&&(t.mask===e.mask&&Si(t.maskUV,e.maskUV)&&t.softness===e.softness&&t.edgeWidth===e.edgeWidth&&t.edgeColor[0]===e.edgeColor[0]&&t.edgeColor[1]===e.edgeColor[1]&&t.edgeColor[2]===e.edgeColor[2])},exports.euclideanModulo=C,exports.floorPowerOfTwo=H,exports.generateUUID=$,exports.getCachedEnvAtlas=$r,exports.getPhysicsResolver=function(){return Pt},exports.getRandomSource=z,exports.getValueFromEmitterMode=Hs,exports.gradientMapEqual=function(t,e){return t===e||!!t&&!!e&&t.ramp===e.ramp&&t.channel===e.channel},exports.inverseLerp=I,exports.isPowerOfTwo=Q,exports.lerp=N,exports.loadPlugin=li,exports.mapLinear=F,exports.mapUVEqual=function(t,e){return t===e||!!t&&!!e&&Si(t,e)},exports.meshRimEqual=function(t,e){return t===e||!(!t||!e)&&(t.mode===e.mode&&t.power===e.power&&t.strength===e.strength&&t.color[0]===e.color[0]&&t.color[1]===e.color[1]&&t.color[2]===e.color[2])},exports.normalize=Z,exports.normalizeErosion=_i,exports.normalizeGradientMap=Mi,exports.normalizeMapUV=Oi,exports.normalizeMeshRim=vi,exports.normalizeTextureUV=xi,exports.normalizeUVDistortion=Ti,exports.pingpong=U,exports.planBehaviorFusion=Js,exports.quarksNodeId=di,exports.radToDeg=G,exports.randFloat=k,exports.randFloatSpread=q,exports.randInt=L,exports.random=M,exports.readBehaviorSpace=xe,exports.readFormat=kt,exports.readFormatPart=qt,exports.readsUV1=Pi,exports.seededRandom=J,exports.serializeEffect=function(t,e={}){const s=new ia(e);let i;if(Array.isArray(t)){const n=e.name??"effect";i={uuid:`${n}-root`,type:"Group",name:n,matrix:a.Matrix.Identity().asArray().slice(),children:t.map(t=>s.node(t))}}else i=s.node(t);return s.finish(i)},exports.setPhysicsResolver=function(t){Pt=t},exports.setQuaternionFromProperEuler=Y,exports.setRandomSource=_,exports.shaderProgram=Yn,exports.shaderVariants=function(){const t=new Set,e=[],s=s=>{const i={renderMode:n=exports.RenderMode.BillBoard,texture:null,reflectionAtlas:null,uTileCount:1,vTileCount:1,blendTiles:!1,softParticles:!1,materialAlphaTest:0,materialTransparent:!0,materialBlendMode:r.Constants.ALPHA_COMBINE,applyFog:!1,pivot:void 0,minParticleSize:0,maxParticleSize:1/0,lighting:n===exports.RenderMode.Mesh?"fixed":void 0,rim:void 0,mapUV:void 0,uvDistortion:void 0,gradientMap:void 0,erosion:void 0};var n;const o={depth:null,envAtlasReady:!1,meshUV2:!1};for(const t of s)Object.assign(i,t.settings),Object.assign(o,t.context);const a=Yn(i,o),h=a.name+" "+a.defines.join(",");if(t.has(h))return;t.add(h);const l=s.map(t=>t.name).filter(t=>""!==t);e.push({name:`${l.join(", ")} [${a.defines.join(",")||"none"}]`,program:a})};for(const t of Aa)for(const e of Ta)for(const i of Oa)for(const n of Pa)for(const r of $a)for(const o of Ea)for(const a of Ca)s([t,e,i,n,r,o,a]);for(const t of Aa)for(const e of Fa)for(const i of $a.slice(0,2))for(const n of Pa)s([t,e,i,n]);for(const t of Aa.filter(t=>Na.includes(t.name)))for(const e of t.settings?.renderMode===exports.RenderMode.Mesh?[Va,Ba]:[Va])for(const i of Ia)for(const n of Pa)for(const r of[Va,Oa[2]])for(const o of[Va,Ua])s([t,e,i,n,r,o]);return e},exports.smootherstep=D,exports.smoothstep=R,exports.softDepthParams=Ki,exports.speedFraction=Ae,exports.subEmitterInheritMask=We,exports.textureSourceUrl=Ko,exports.textureUVEqual=Si,exports.textureUVToJSON=bi,exports.trailCurveTension=rr,exports.trailLifetime=cr,exports.trailMinVertexDistance=lr,exports.trailTessellation=nr,exports.trailTextureMode=ar,exports.trailTextureScale=hr,exports.unloadPlugin=function(t){const e=hi.findIndex(e=>e.id===t);if(e<0)return;const s=hi[e];hi.splice(e,1);for(const t of s.emitterShapes)ri[t.type]===t&&delete ri[t.type];for(const t of s.behaviors)Ts[t.type]===t&&delete Ts[t.type]},exports.uvDistortionEqual=function(t,e){return t===e||!(!t||!e)&&(t.map===e.map&&t.strength===e.strength&&Si(t.mapUV,e.mapUV))},exports.warnFormat=Wt,exports.withRandomSource=function(t,e){const s=_(t);try{return e()}finally{_(s)}};
|
|
1
|
+
"use strict";var t=require("@babylonjs/core/Buffers/buffer.js"),e=require("@babylonjs/core/Misc/guid.js"),s=require("@babylonjs/core/Maths/math.frustum.js"),i=require("@babylonjs/core/Maths/math.plane.js"),n=require("@babylonjs/core/Meshes/transformNode.js"),r=require("@babylonjs/core/Engines/constants.js"),o=require("@babylonjs/core/Maths/math.color.js"),a=require("@babylonjs/core/Maths/math.vector.js"),h=require("@babylonjs/core/Cameras/camera.js"),l=require("@babylonjs/core/Materials/shaderMaterial.js"),c=require("@babylonjs/core/Materials/Textures/rawTexture.js"),u=require("@babylonjs/core/Meshes/mesh.js"),d=require("@babylonjs/core/Meshes/mesh.vertexData.js"),f=require("@babylonjs/core/Materials/imageProcessingConfiguration.functions.js"),p=require("@babylonjs/core/Engines/shaderStore.js");require("@babylonjs/core/Shaders/ShadersInclude/helperFunctions.js"),require("@babylonjs/core/Shaders/ShadersInclude/imageProcessingDeclaration.js"),require("@babylonjs/core/Shaders/ShadersInclude/imageProcessingFunctions.js"),require("@babylonjs/core/ShadersWGSL/ShadersInclude/helperFunctions.js"),require("@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingDeclaration.js"),require("@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingFunctions.js");var m=require("@babylonjs/core/Materials/effect.js"),y=require("@babylonjs/core/Materials/shaderLanguage.js"),g=require("@babylonjs/core/Culling/boundingInfo.js"),v=require("@babylonjs/core/Materials/Textures/baseTexture.js"),x=require("@babylonjs/core/scene.js"),S=require("@babylonjs/core/Meshes/instancedMesh.js"),b=require("@babylonjs/core/Materials/Textures/texture.js"),w=require("@babylonjs/core/Materials/standardMaterial.js");let M=null;function z(){return null===M?Math.random():M()}function _(){return M??Math.random}function A(t){const e=_();return M=t,e}function P(t){let e=t>>>0||2654435769;return()=>{e=e+1831565813|0;let t=e;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296}}const O=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let T=1234567;const V=Math.PI/180,E=180/Math.PI;function C(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(O[255&t]+O[t>>8&255]+O[t>>16&255]+O[t>>24&255]+"-"+O[255&e]+O[e>>8&255]+"-"+O[e>>16&15|64]+O[e>>24&255]+"-"+O[63&s|128]+O[s>>8&255]+"-"+O[s>>16&255]+O[s>>24&255]+O[255&i]+O[i>>8&255]+O[i>>16&255]+O[i>>24&255]).toLowerCase()}function $(t,e,s){return Math.max(e,Math.min(s,t))}function I(t,e){return(t%e+e)%e}function N(t,e,s,i,n){return i+(t-e)*(n-i)/(s-e)}function F(t,e,s){return t!==e?(s-t)/(e-t):0}function R(t,e,s){return(1-s)*t+s*e}function B(t,e,s,i){return R(t,e,1-Math.exp(-s*i))}function U(t,e=1){return e-Math.abs(I(t,2*e)-e)}function L(t,e,s){return t<=e?0:t>=s?1:(t=(t-e)/(s-e))*t*(3-2*t)}function D(t,e,s){return t<=e?0:t>=s?1:(t=(t-e)/(s-e))*t*t*(t*(6*t-15)+10)}function k(t,e){return t+Math.floor(z()*(e-t+1))}function q(t,e){return t+z()*(e-t)}function G(t){return t*(.5-z())}function J(t){void 0!==t&&(T=t);let e=T+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}function W(t){return t*V}function j(t){return t*E}function Q(t){return!(t&t-1)&&0!==t}function H(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function Y(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function X(t,e,s,i,n){const r=Math.cos,o=Math.sin,a=r(s/2),h=o(s/2),l=r((e+i)/2),c=o((e+i)/2),u=r((e-i)/2),d=o((e-i)/2),f=r((i-e)/2),p=o((i-e)/2);switch(n){case"XYX":t.set(a*c,h*u,h*d,a*l);break;case"YZY":t.set(h*d,a*c,h*u,a*l);break;case"ZXZ":t.set(h*u,h*d,a*c,a*l);break;case"XZX":t.set(a*c,h*p,h*f,a*l);break;case"YXY":t.set(h*f,a*c,h*p,a*l);break;case"ZYZ":t.set(h*p,h*f,a*c,a*l);break;default:console.warn("../math.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function Z(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function K(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const tt={DEG2RAD:V,RAD2DEG:E,generateUUID:C,clamp:$,euclideanModulo:I,mapLinear:N,inverseLerp:F,lerp:R,damp:B,pingpong:U,smoothstep:L,smootherstep:D,randInt:k,randFloat:q,randFloatSpread:G,seededRandom:J,degToRad:W,radToDeg:j,isPowerOfTwo:Q,ceilPowerOfTwo:H,floorPowerOfTwo:Y,setQuaternionFromProperEuler:X,normalize:K,denormalize:Z};class et{constructor(t=0,e=0,s=0,i=1){this._x=t,this._y=e,this._z=s,this._w=i}static slerpFlat(t,e,s,i,n,r,o){let a=s[i+0],h=s[i+1],l=s[i+2],c=s[i+3];const u=n[r+0],d=n[r+1],f=n[r+2],p=n[r+3];if(0===o)return t[e+0]=a,t[e+1]=h,t[e+2]=l,void(t[e+3]=c);if(1===o)return t[e+0]=u,t[e+1]=d,t[e+2]=f,void(t[e+3]=p);if(c!==p||a!==u||h!==d||l!==f){let t=1-o;const e=a*u+h*d+l*f+c*p,s=e>=0?1:-1,i=1-e*e;if(i>Number.EPSILON){const n=Math.sqrt(i),r=Math.atan2(n,e*s);t=Math.sin(t*r)/n,o=Math.sin(o*r)/n}const n=o*s;if(a=a*t+u*n,h=h*t+d*n,l=l*t+f*n,c=c*t+p*n,t===1-o){const t=1/Math.sqrt(a*a+h*h+l*l+c*c);a*=t,h*=t,l*=t,c*=t}}t[e]=a,t[e+1]=h,t[e+2]=l,t[e+3]=c}static multiplyQuaternionsFlat(t,e,s,i,n,r){const o=s[i],a=s[i+1],h=s[i+2],l=s[i+3],c=n[r],u=n[r+1],d=n[r+2],f=n[r+3];return t[e]=o*f+l*c+a*d-h*u,t[e+1]=a*f+l*u+h*c-o*d,t[e+2]=h*f+l*d+o*u-a*c,t[e+3]=l*f-o*c-a*u-h*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,s,i){return this._x=t,this._y=e,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new et(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const s=t._x,i=t._y,n=t._z,r=t._order,o=Math.cos,a=Math.sin,h=o(s/2),l=o(i/2),c=o(n/2),u=a(s/2),d=a(i/2),f=a(n/2);switch(r){case"XYZ":this._x=u*l*c+h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c-u*d*f;break;case"YXZ":this._x=u*l*c+h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c+u*d*f;break;case"ZXY":this._x=u*l*c-h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c-u*d*f;break;case"ZYX":this._x=u*l*c-h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c+u*d*f;break;case"YZX":this._x=u*l*c+h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c-u*d*f;break;case"XZY":this._x=u*l*c-h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c+u*d*f;break;default:console.warn("../math.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return!0===e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const s=e/2,i=Math.sin(s);return this._x=t.x*i,this._y=t.y*i,this._z=t.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,s=e[0],i=e[4],n=e[8],r=e[1],o=e[5],a=e[9],h=e[2],l=e[6],c=e[10],u=s+o+c;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(l-a)*t,this._y=(n-h)*t,this._z=(r-i)*t}else if(s>o&&s>c){const t=2*Math.sqrt(1+s-o-c);this._w=(l-a)/t,this._x=.25*t,this._y=(i+r)/t,this._z=(n+h)/t}else if(o>c){const t=2*Math.sqrt(1+o-s-c);this._w=(n-h)/t,this._x=(i+r)/t,this._y=.25*t,this._z=(a+l)/t}else{const t=2*Math.sqrt(1+c-s-o);this._w=(r-i)/t,this._x=(n+h)/t,this._y=(a+l)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let s=t.dot(e)+1;return s<Number.EPSILON?(s=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=s):(this._x=0,this._y=-t.z,this._z=t.y,this._w=s)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=s),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs($(this.dot(t),-1,1)))}rotateTowards(t,e){const s=this.angleTo(t);if(0===s)return this;const i=Math.min(1,e/s);return this.slerp(t,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const s=t._x,i=t._y,n=t._z,r=t._w,o=e._x,a=e._y,h=e._z,l=e._w;return this._x=s*l+r*o+i*h-n*a,this._y=i*l+r*a+n*o-s*h,this._z=n*l+r*h+s*a-i*o,this._w=r*l-s*o-i*a-n*h,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const s=this._x,i=this._y,n=this._z,r=this._w;let o=r*t._w+s*t._x+i*t._y+n*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=r,this._x=s,this._y=i,this._z=n,this;const a=1-o*o;if(a<=Number.EPSILON){const t=1-e;return this._w=t*r+e*this._w,this._x=t*s+e*this._x,this._y=t*i+e*this._y,this._z=t*n+e*this._z,this.normalize(),this}const h=Math.sqrt(a),l=Math.atan2(h,o),c=Math.sin((1-e)*l)/h,u=Math.sin(e*l)/h;return this._w=r*c+this._w*u,this._x=s*c+this._x*u,this._y=i*c+this._y*u,this._z=n*c+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,s){return this.copy(t).slerp(e,s)}random(){const t=2*Math.PI*z(),e=2*Math.PI*z(),s=z(),i=Math.sqrt(1-s),n=Math.sqrt(s);return this.set(i*Math.sin(t),i*Math.cos(t),n*Math.sin(e),n*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}Object.defineProperty(et.prototype,"isQuaternion",{value:!0});class st{constructor(t=0,e=0,s=0){this.x=t,this.y=e,this.z=s}set(t,e,s){return void 0===s&&(s=this.z),this.x=t,this.y=e,this.z=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new st(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(nt.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(nt.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,s=this.y,i=this.z,n=t.elements;return this.x=n[0]*e+n[3]*s+n[6]*i,this.y=n[1]*e+n[4]*s+n[7]*i,this.z=n[2]*e+n[5]*s+n[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,s=this.y,i=this.z,n=t.elements,r=1/(n[3]*e+n[7]*s+n[11]*i+n[15]);return this.x=(n[0]*e+n[4]*s+n[8]*i+n[12])*r,this.y=(n[1]*e+n[5]*s+n[9]*i+n[13])*r,this.z=(n[2]*e+n[6]*s+n[10]*i+n[14])*r,this}applyQuaternion(t){const e=this.x,s=this.y,i=this.z,n=t.x,r=t.y,o=t.z,a=t.w,h=2*(r*i-o*s),l=2*(o*e-n*i),c=2*(n*s-r*e);return this.x=e+a*h+r*c-o*l,this.y=s+a*l+o*h-n*c,this.z=i+a*c+n*l-r*h,this}transformDirection(t){const e=this.x,s=this.y,i=this.z,n=t.elements;return this.x=n[0]*e+n[4]*s+n[8]*i,this.y=n[1]*e+n[5]*s+n[9]*i,this.z=n[2]*e+n[6]*s+n[10]*i,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(t,Math.min(e,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,s){return this.x=t.x+(e.x-t.x)*s,this.y=t.y+(e.y-t.y)*s,this.z=t.z+(e.z-t.z)*s,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const s=t.x,i=t.y,n=t.z,r=e.x,o=e.y,a=e.z;return this.x=i*a-n*o,this.y=n*r-s*a,this.z=s*o-i*r,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const s=t.dot(this)/e;return this.copy(t).multiplyScalar(s)}projectOnPlane(t){return it.copy(this).projectOnVector(t),this.sub(it)}reflect(t){return this.sub(it.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const s=this.dot(t)/e;return Math.acos($(s,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,s=this.y-t.y,i=this.z-t.z;return e*e+s*s+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSphericalCoords(t,e,s){const i=Math.sin(e)*t;return this.x=i*Math.sin(s),this.y=Math.cos(e)*t,this.z=i*Math.cos(s),this}setFromCylindricalCoords(t,e,s){return this.x=t*Math.sin(e),this.y=s,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),s=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=s,this.z=i,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}random(){return this.x=z(),this.y=z(),this.z=z(),this}randomDirection(){const t=z()*Math.PI*2,e=2*z()-1,s=Math.sqrt(1-e*e);return this.x=s*Math.cos(t),this.y=e,this.z=s*Math.sin(t),this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this.z=Math.abs(this.z),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}Object.defineProperty(st.prototype,"isVector3",{value:!0});const it=new st,nt=new et,rt=2e3,ot=2001;class at{constructor(t,e,s,i,n,r,o,a,h,l,c,u,d,f,p,m){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,s,i,n,r,o,a,h,l,c,u,d,f,p,m)}extractPosition(t){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(t)}multiplyToArray(t,e,s){return console.error("THREE.Matrix4: .multiplyToArray() has been removed."),this}setRotationFromQuaternion(t){return this.makeRotationFromQuaternion(t)}set(t,e,s,i,n,r,o,a,h,l,c,u,d,f,p,m){const y=this.elements;return y[0]=t,y[4]=e,y[8]=s,y[12]=i,y[1]=n,y[5]=r,y[9]=o,y[13]=a,y[2]=h,y[6]=l,y[10]=c,y[14]=u,y[3]=d,y[7]=f,y[11]=p,y[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new at).fromArray(this.elements)}copy(t){const e=this.elements,s=t.elements;return e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=s[3],e[4]=s[4],e[5]=s[5],e[6]=s[6],e[7]=s[7],e[8]=s[8],e[9]=s[9],e[10]=s[10],e[11]=s[11],e[12]=s[12],e[13]=s[13],e[14]=s[14],e[15]=s[15],this}copyPosition(t){const e=this.elements,s=t.elements;return e[12]=s[12],e[13]=s[13],e[14]=s[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,s){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this}makeBasis(t,e,s){return this.set(t.x,e.x,s.x,0,t.y,e.y,s.y,0,t.z,e.z,s.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,s=t.elements,i=1/ht.setFromMatrixColumn(t,0).length(),n=1/ht.setFromMatrixColumn(t,1).length(),r=1/ht.setFromMatrixColumn(t,2).length();return e[0]=s[0]*i,e[1]=s[1]*i,e[2]=s[2]*i,e[3]=0,e[4]=s[4]*n,e[5]=s[5]*n,e[6]=s[6]*n,e[7]=0,e[8]=s[8]*r,e[9]=s[9]*r,e[10]=s[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,s=t.x,i=t.y,n=t.z,r=Math.cos(s),o=Math.sin(s),a=Math.cos(i),h=Math.sin(i),l=Math.cos(n),c=Math.sin(n);if("XYZ"===t.order){const t=r*l,s=r*c,i=o*l,n=o*c;e[0]=a*l,e[4]=-a*c,e[8]=h,e[1]=s+i*h,e[5]=t-n*h,e[9]=-o*a,e[2]=n-t*h,e[6]=i+s*h,e[10]=r*a}else if("YXZ"===t.order){const t=a*l,s=a*c,i=h*l,n=h*c;e[0]=t+n*o,e[4]=i*o-s,e[8]=r*h,e[1]=r*c,e[5]=r*l,e[9]=-o,e[2]=s*o-i,e[6]=n+t*o,e[10]=r*a}else if("ZXY"===t.order){const t=a*l,s=a*c,i=h*l,n=h*c;e[0]=t-n*o,e[4]=-r*c,e[8]=i+s*o,e[1]=s+i*o,e[5]=r*l,e[9]=n-t*o,e[2]=-r*h,e[6]=o,e[10]=r*a}else if("ZYX"===t.order){const t=r*l,s=r*c,i=o*l,n=o*c;e[0]=a*l,e[4]=i*h-s,e[8]=t*h+n,e[1]=a*c,e[5]=n*h+t,e[9]=s*h-i,e[2]=-h,e[6]=o*a,e[10]=r*a}else if("YZX"===t.order){const t=r*a,s=r*h,i=o*a,n=o*h;e[0]=a*l,e[4]=n-t*c,e[8]=i*c+s,e[1]=c,e[5]=r*l,e[9]=-o*l,e[2]=-h*l,e[6]=s*c+i,e[10]=t-n*c}else if("XZY"===t.order){const t=r*a,s=r*h,i=o*a,n=o*h;e[0]=a*l,e[4]=-c,e[8]=h*l,e[1]=t*c+n,e[5]=r*l,e[9]=s*c-i,e[2]=i*c-s,e[6]=o*l,e[10]=n*c+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(ct,t,ut)}lookAt(t,e,s){const i=this.elements;return pt.subVectors(t,e),0===pt.lengthSq()&&(pt.z=1),pt.normalize(),dt.crossVectors(s,pt),0===dt.lengthSq()&&(1===Math.abs(s.z)?pt.x+=1e-4:pt.z+=1e-4,pt.normalize(),dt.crossVectors(s,pt)),dt.normalize(),ft.crossVectors(pt,dt),i[0]=dt.x,i[4]=ft.x,i[8]=pt.x,i[1]=dt.y,i[5]=ft.y,i[9]=pt.y,i[2]=dt.z,i[6]=ft.z,i[10]=pt.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const s=t.elements,i=e.elements,n=this.elements,r=s[0],o=s[4],a=s[8],h=s[12],l=s[1],c=s[5],u=s[9],d=s[13],f=s[2],p=s[6],m=s[10],y=s[14],g=s[3],v=s[7],x=s[11],S=s[15],b=i[0],w=i[4],M=i[8],z=i[12],_=i[1],A=i[5],P=i[9],O=i[13],T=i[2],V=i[6],E=i[10],C=i[14],$=i[3],I=i[7],N=i[11],F=i[15];return n[0]=r*b+o*_+a*T+h*$,n[4]=r*w+o*A+a*V+h*I,n[8]=r*M+o*P+a*E+h*N,n[12]=r*z+o*O+a*C+h*F,n[1]=l*b+c*_+u*T+d*$,n[5]=l*w+c*A+u*V+d*I,n[9]=l*M+c*P+u*E+d*N,n[13]=l*z+c*O+u*C+d*F,n[2]=f*b+p*_+m*T+y*$,n[6]=f*w+p*A+m*V+y*I,n[10]=f*M+p*P+m*E+y*N,n[14]=f*z+p*O+m*C+y*F,n[3]=g*b+v*_+x*T+S*$,n[7]=g*w+v*A+x*V+S*I,n[11]=g*M+v*P+x*E+S*N,n[15]=g*z+v*O+x*C+S*F,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],s=t[4],i=t[8],n=t[12],r=t[1],o=t[5],a=t[9],h=t[13],l=t[2],c=t[6],u=t[10],d=t[14];return t[3]*(+n*a*c-i*h*c-n*o*u+s*h*u+i*o*d-s*a*d)+t[7]*(+e*a*d-e*h*u+n*r*u-i*r*d+i*h*l-n*a*l)+t[11]*(+e*h*c-e*o*d-n*r*c+s*r*d+n*o*l-s*h*l)+t[15]*(-i*o*l-e*a*c+e*o*u+i*r*c-s*r*u+s*a*l)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,s){const i=this.elements;return"number"==typeof t?(i[12]=t,i[13]=e,i[14]=s):(i[12]=t.x,i[13]=t.y,i[14]=t.z),this}invert(){const t=this.elements,e=t[0],s=t[1],i=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],c=t[9],u=t[10],d=t[11],f=t[12],p=t[13],m=t[14],y=t[15],g=c*m*h-p*u*h+p*a*d-o*m*d-c*a*y+o*u*y,v=f*u*h-l*m*h-f*a*d+r*m*d+l*a*y-r*u*y,x=l*p*h-f*c*h+f*o*d-r*p*d-l*o*y+r*c*y,S=f*c*a-l*p*a-f*o*u+r*p*u+l*o*m-r*c*m,b=e*g+s*v+i*x+n*S;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/b;return t[0]=g*w,t[1]=(p*u*n-c*m*n-p*i*d+s*m*d+c*i*y-s*u*y)*w,t[2]=(o*m*n-p*a*n+p*i*h-s*m*h-o*i*y+s*a*y)*w,t[3]=(c*a*n-o*u*n-c*i*h+s*u*h+o*i*d-s*a*d)*w,t[4]=v*w,t[5]=(l*m*n-f*u*n+f*i*d-e*m*d-l*i*y+e*u*y)*w,t[6]=(f*a*n-r*m*n-f*i*h+e*m*h+r*i*y-e*a*y)*w,t[7]=(r*u*n-l*a*n+l*i*h-e*u*h-r*i*d+e*a*d)*w,t[8]=x*w,t[9]=(f*c*n-l*p*n-f*s*d+e*p*d+l*s*y-e*c*y)*w,t[10]=(r*p*n-f*o*n+f*s*h-e*p*h-r*s*y+e*o*y)*w,t[11]=(l*o*n-r*c*n-l*s*h+e*c*h+r*s*d-e*o*d)*w,t[12]=S*w,t[13]=(l*p*i-f*c*i+f*s*u-e*p*u-l*s*m+e*c*m)*w,t[14]=(f*o*i-r*p*i-f*s*a+e*p*a+r*s*m-e*o*m)*w,t[15]=(r*c*i-l*o*i+l*s*a-e*c*a-r*s*u+e*o*u)*w,this}scale(t){const e=this.elements,s=t.x,i=t.y,n=t.z;return e[0]*=s,e[4]*=i,e[8]*=n,e[1]*=s,e[5]*=i,e[9]*=n,e[2]*=s,e[6]*=i,e[10]*=n,e[3]*=s,e[7]*=i,e[11]*=n,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],s=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,s,i))}makeTranslation(t,e,s){return"number"==typeof t?this.set(1,0,0,t,0,1,0,e,0,0,1,s,0,0,0,1):this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),s=Math.sin(t);return this.set(1,0,0,0,0,e,-s,0,0,s,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),s=Math.sin(t);return this.set(e,0,s,0,0,1,0,0,-s,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),s=Math.sin(t);return this.set(e,-s,0,0,s,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const s=Math.cos(e),i=Math.sin(e),n=1-s,r=t.x,o=t.y,a=t.z,h=n*r,l=n*o;return this.set(h*r+s,h*o-i*a,h*a+i*o,0,h*o+i*a,l*o+s,l*a-i*r,0,h*a-i*o,l*a+i*r,n*a*a+s,0,0,0,0,1),this}makeScale(t,e,s){return this.set(t,0,0,0,0,e,0,0,0,0,s,0,0,0,0,1),this}makeShear(t,e,s,i,n,r){return this.set(1,s,n,0,t,1,r,0,e,i,1,0,0,0,0,1),this}compose(t,e,s){const i=this.elements,n=e._x,r=e._y,o=e._z,a=e._w,h=n+n,l=r+r,c=o+o,u=n*h,d=n*l,f=n*c,p=r*l,m=r*c,y=o*c,g=a*h,v=a*l,x=a*c,S=s.x,b=s.y,w=s.z;return i[0]=(1-(p+y))*S,i[1]=(d+x)*S,i[2]=(f-v)*S,i[3]=0,i[4]=(d-x)*b,i[5]=(1-(u+y))*b,i[6]=(m+g)*b,i[7]=0,i[8]=(f+v)*w,i[9]=(m-g)*w,i[10]=(1-(u+p))*w,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,s){const i=this.elements;let n=ht.set(i[0],i[1],i[2]).length();const r=ht.set(i[4],i[5],i[6]).length(),o=ht.set(i[8],i[9],i[10]).length();this.determinant()<0&&(n=-n),t.x=i[12],t.y=i[13],t.z=i[14],lt.copy(this);const a=1/n,h=1/r,l=1/o;return lt.elements[0]*=a,lt.elements[1]*=a,lt.elements[2]*=a,lt.elements[4]*=h,lt.elements[5]*=h,lt.elements[6]*=h,lt.elements[8]*=l,lt.elements[9]*=l,lt.elements[10]*=l,e.setFromRotationMatrix(lt),s.x=n,s.y=r,s.z=o,this}makePerspective(t,e,s,i,n,r,o=2e3){const a=this.elements,h=2*n/(e-t),l=2*n/(s-i),c=(e+t)/(e-t),u=(s+i)/(s-i);let d,f;if(o===rt)d=-(r+n)/(r-n),f=-2*r*n/(r-n);else{if(o!==ot)throw new Error("Matrix4.makePerspective(): Invalid coordinate system: "+o);d=-r/(r-n),f=-r*n/(r-n)}return a[0]=h,a[4]=0,a[8]=c,a[12]=0,a[1]=0,a[5]=l,a[9]=u,a[13]=0,a[2]=0,a[6]=0,a[10]=d,a[14]=f,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(t,e,s,i,n,r,o=2e3){const a=this.elements,h=1/(e-t),l=1/(s-i),c=1/(r-n),u=(e+t)*h,d=(s+i)*l;let f,p;if(o===rt)f=(r+n)*c,p=-2*c;else{if(o!==ot)throw new Error("../math.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);f=n*c,p=-1*c}return a[0]=2*h,a[4]=0,a[8]=0,a[12]=-u,a[1]=0,a[5]=2*l,a[9]=0,a[13]=-d,a[2]=0,a[6]=0,a[10]=p,a[14]=-f,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(t){const e=this.elements,s=t.elements;for(let t=0;t<16;t++)if(e[t]!==s[t])return!1;return!0}fromArray(t,e=0){for(let s=0;s<16;s++)this.elements[s]=t[s+e];return this}toArray(t=[],e=0){const s=this.elements;return t[e]=s[0],t[e+1]=s[1],t[e+2]=s[2],t[e+3]=s[3],t[e+4]=s[4],t[e+5]=s[5],t[e+6]=s[6],t[e+7]=s[7],t[e+8]=s[8],t[e+9]=s[9],t[e+10]=s[10],t[e+11]=s[11],t[e+12]=s[12],t[e+13]=s[13],t[e+14]=s[14],t[e+15]=s[15],t}}Object.defineProperty(at.prototype,"isMatrix4",{value:!0});const ht=new st,lt=new at,ct=new st(0,0,0),ut=new st(1,1,1),dt=new st,ft=new st,pt=new st,mt=new at,yt=new et;class gt{constructor(t=0,e=0,s=0,i=gt.DEFAULT_ORDER){this._x=t,this._y=e,this._z=s,this._order=i}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,s,i=this._order){return this._x=t,this._y=e,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new gt(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,s=!0){const i=t.elements,n=i[0],r=i[4],o=i[8],a=i[1],h=i[5],l=i[9],c=i[2],u=i[6],d=i[10];switch(e){case"XYZ":this._y=Math.asin($(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,d),this._z=Math.atan2(-r,n)):(this._x=Math.atan2(u,h),this._z=0);break;case"YXZ":this._x=Math.asin(-$(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,h)):(this._y=Math.atan2(-c,n),this._z=0);break;case"ZXY":this._x=Math.asin($(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-r,h)):(this._y=0,this._z=Math.atan2(a,n));break;case"ZYX":this._y=Math.asin(-$(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(a,n)):(this._x=0,this._z=Math.atan2(-r,h));break;case"YZX":this._z=Math.asin($(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-l,h),this._y=Math.atan2(-c,n)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-$(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(u,h),this._y=Math.atan2(o,n)):(this._x=Math.atan2(-l,d),this._y=0);break;default:console.warn("../math.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===s&&this._onChangeCallback(),this}setFromQuaternion(t,e,s){return mt.makeRotationFromQuaternion(t),this.setFromRotationMatrix(mt,e,s)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return yt.setFromEuler(this),this.setFromQuaternion(yt,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(t){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}gt.DEFAULT_ORDER="XYZ",Object.defineProperty(gt.prototype,"isEuler",{value:!0});class vt{constructor(t,e,s,i,n,r,o,a,h){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,s,i,n,r,o,a,h)}set(t,e,s,i,n,r,o,a,h){const l=this.elements;return l[0]=t,l[1]=i,l[2]=o,l[3]=e,l[4]=n,l[5]=a,l[6]=s,l[7]=r,l[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,s=t.elements;return e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=s[3],e[4]=s[4],e[5]=s[5],e[6]=s[6],e[7]=s[7],e[8]=s[8],this}extractBasis(t,e,s){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const s=t.elements,i=e.elements,n=this.elements,r=s[0],o=s[3],a=s[6],h=s[1],l=s[4],c=s[7],u=s[2],d=s[5],f=s[8],p=i[0],m=i[3],y=i[6],g=i[1],v=i[4],x=i[7],S=i[2],b=i[5],w=i[8];return n[0]=r*p+o*g+a*S,n[3]=r*m+o*v+a*b,n[6]=r*y+o*x+a*w,n[1]=h*p+l*g+c*S,n[4]=h*m+l*v+c*b,n[7]=h*y+l*x+c*w,n[2]=u*p+d*g+f*S,n[5]=u*m+d*v+f*b,n[8]=u*y+d*x+f*w,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],s=t[1],i=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return e*r*l-e*o*h-s*n*l+s*o*a+i*n*h-i*r*a}invert(){const t=this.elements,e=t[0],s=t[1],i=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],c=l*r-o*h,u=o*a-l*n,d=h*n-r*a,f=e*c+s*u+i*d;if(0===f)return this.set(0,0,0,0,0,0,0,0,0);const p=1/f;return t[0]=c*p,t[1]=(i*h-l*s)*p,t[2]=(o*s-i*r)*p,t[3]=u*p,t[4]=(l*e-i*a)*p,t[5]=(i*n-o*e)*p,t[6]=d*p,t[7]=(s*a-h*e)*p,t[8]=(r*e-s*n)*p,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,s,i,n,r,o){const a=Math.cos(n),h=Math.sin(n);return this.set(s*a,s*h,-s*(a*r+h*o)+r+t,-i*h,i*a,-i*(-h*r+a*o)+o+e,0,0,1),this}scale(t,e){return this.premultiply(xt.makeScale(t,e)),this}rotate(t){return this.premultiply(xt.makeRotation(-t)),this}translate(t,e){return this.premultiply(xt.makeTranslation(t,e)),this}makeTranslation(t,e){return"number"==typeof t?this.set(1,0,t,0,1,e,0,0,1):this.set(1,0,t.x,0,1,t.y,0,0,1),this}makeRotation(t){const e=Math.cos(t),s=Math.sin(t);return this.set(e,-s,0,s,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,s=t.elements;for(let t=0;t<9;t++)if(e[t]!==s[t])return!1;return!0}fromArray(t,e=0){for(let s=0;s<9;s++)this.elements[s]=t[s+e];return this}toArray(t=[],e=0){const s=this.elements;return t[e]=s[0],t[e+1]=s[1],t[e+2]=s[2],t[e+3]=s[3],t[e+4]=s[4],t[e+5]=s[5],t[e+6]=s[6],t[e+7]=s[7],t[e+8]=s[8],t}clone(){return(new vt).fromArray(this.elements)}}Object.defineProperty(vt.prototype,"isMatrix3",{value:!0});const xt=new vt,St=new Float32Array(4);class bt extends et{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const wt=bt.prototype;wt.data=St,wt.offset=0,Object.defineProperties(bt.prototype,{_x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},_y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},_z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}},_w:{get(){return this.data[this.offset+3]},set(t){this.data[this.offset+3]=t}}});class Mt{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new Mt(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,s=this.y,i=t.elements;return this.x=i[0]*e+i[3]*s+i[6],this.y=i[1]*e+i[4]*s+i[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(t,Math.min(e,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const s=this.dot(t)/e;return Math.acos($(s,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,s=this.y-t.y;return e*e+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,s){return this.x=t.x+(e.x-t.x)*s,this.y=t.y+(e.y-t.y)*s,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}rotateAround(t,e){const s=Math.cos(e),i=Math.sin(e),n=this.x-t.x,r=this.y-t.y;return this.x=n*s-r*i+t.x,this.y=n*i+r*s+t.y,this}random(){return this.x=z(),this.y=z(),this}*[Symbol.iterator](){yield this.x,yield this.y}}Object.defineProperty(Mt.prototype,"isVector2",{value:!0});const zt=new Float32Array(3);class _t extends st{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const At=_t.prototype;At.data=zt,At.offset=0,Object.defineProperties(_t.prototype,{x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}}});class Pt{constructor(t=0,e=0,s=0,i=1){this.x=t,this.y=e,this.z=s,this.w=i}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,s,i){return this.x=t,this.y=e,this.z=s,this.w=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new Pt(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,s=this.y,i=this.z,n=this.w,r=t.elements;return this.x=r[0]*e+r[4]*s+r[8]*i+r[12]*n,this.y=r[1]*e+r[5]*s+r[9]*i+r[13]*n,this.z=r[2]*e+r[6]*s+r[10]*i+r[14]*n,this.w=r[3]*e+r[7]*s+r[11]*i+r[15]*n,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,s,i,n;const r=.01,o=.1,a=t.elements,h=a[0],l=a[4],c=a[8],u=a[1],d=a[5],f=a[9],p=a[2],m=a[6],y=a[10];if(Math.abs(l-u)<r&&Math.abs(c-p)<r&&Math.abs(f-m)<r){if(Math.abs(l+u)<o&&Math.abs(c+p)<o&&Math.abs(f+m)<o&&Math.abs(h+d+y-3)<o)return this.set(1,0,0,0),this;e=Math.PI;const t=(h+1)/2,a=(d+1)/2,g=(y+1)/2,v=(l+u)/4,x=(c+p)/4,S=(f+m)/4;return t>a&&t>g?t<r?(s=0,i=.707106781,n=.707106781):(s=Math.sqrt(t),i=v/s,n=x/s):a>g?a<r?(s=.707106781,i=0,n=.707106781):(i=Math.sqrt(a),s=v/i,n=S/i):g<r?(s=.707106781,i=.707106781,n=0):(n=Math.sqrt(g),s=x/n,i=S/n),this.set(s,i,n,e),this}let g=Math.sqrt((m-f)*(m-f)+(c-p)*(c-p)+(u-l)*(u-l));return Math.abs(g)<.001&&(g=1),this.x=(m-f)/g,this.y=(c-p)/g,this.z=(u-l)/g,this.w=Math.acos((h+d+y-1)/2),this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(t,Math.min(e,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,s){return this.x=t.x+(e.x-t.x)*s,this.y=t.y+(e.y-t.y)*s,this.z=t.z+(e.z-t.z)*s,this.w=t.w+(e.w-t.w)*s,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}random(){return this.x=z(),this.y=z(),this.z=z(),this.w=z(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}Object.defineProperty(Pt.prototype,"isVector4",{value:!0});const Ot=new Float32Array(4);class Tt extends Pt{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const Vt=Tt.prototype;let Et;Vt.data=Ot,Vt.offset=0,Object.defineProperties(Tt.prototype,{x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}},w:{get(){return this.data[this.offset+3]},set(t){this.data[this.offset+3]=t}}});class Ct{constructor(t,e){this.resolver=t,this.bounce=e,this.type="ApplyCollision",this.tempV=new st}initialize(t){}update(t,e){const s=this.resolver??Et;void 0!==s&&s.resolve(t.position,this.tempV)&&t.velocity.reflect(this.tempV).multiplyScalar(this.bounce)}frameUpdate(t){}toJSON(){return{type:this.type,bounce:this.bounce}}static fromJSON(t){return new Ct(void 0,"number"==typeof t.bounce?t.bounce:1)}clone(){return new Ct(this.resolver,this.bounce)}reset(){}}const $t=t=>({r:t.x,g:t.y,b:t.z,a:t.w}),It=t=>new Pt(t.r,t.g,t.b,t.a);function Nt(t,e){if("number"==typeof t)return t;switch(e){case"Color":return{r:t.x,g:t.y,b:t.z};case"Vector4":return t instanceof Pt?{x:t.x,y:t.y,z:t.z,w:t.w}:{...Ft(t),w:0};default:return Ft(t)}}const Ft=t=>({x:t.x,y:t.y,z:t.z}),Rt=t=>"number"==typeof t?t:0;function Bt(t){return"number"==typeof t?new st:"r"in t?new st(t.r,t.g,t.b):new st(t.x,t.y,t.z)}function Ut(t){return"number"==typeof t||"r"in t?new Pt:new Pt(t.x,t.y,t.z,"w"in t?t.w:0)}class Lt extends Error{constructor(t,e=[t]){super(t),this.name="QuarksFormatError",this.problems=e}}let Dt={};const kt=[];function qt(t,e){const s=Dt,i=kt.splice(0);Dt=t;try{return e()}finally{Dt=s,kt.splice(0,kt.length,...i)}}function Gt(t,e){kt.push(t);try{return e()}finally{kt.pop()}}function Jt(){return kt.reduce((t,e)=>t&&!e.startsWith("[")?`${t}.${e}`:t+e,"")}const Wt=t=>{const e=Jt();if(Dt.strict)throw new Lt(e?`${t} (at ${e})`:t);Dt.onWarning?Dt.onWarning(t,e):console.warn(`[quarks] ${t}${e?` (at ${e})`:""}`)},jt=(t,e)=>Array.isArray(t)?new st(t[0]??e.x,t[1]??e.y,t[2]??e.z):e,Qt=(t,e)=>{const s=e?.type;return null==e?`Missing ${t}`:void 0===s?`${t[0].toUpperCase()}${t.slice(1)} without a type`:`Unknown ${t} ${JSON.stringify(s)}`};function Ht(t,e){if(t===e)return!0;if("object"!=typeof t||"object"!=typeof e||null===t||null===e)return"number"==typeof t&&"number"==typeof e&&Number.isNaN(t)&&Number.isNaN(e);if(Array.isArray(t)!==Array.isArray(e))return!1;const s=new Set([...Object.keys(t),...Object.keys(e)]);for(const i of s)if(!Ht(t[i],e[i]))return!1;return!0}function Yt(t,e){if(null===t||"object"!=typeof t||"string"!=typeof t.type)return t;const s=t=>{let s=!1;try{return{out:qt({onWarning:()=>s=!0},()=>e(t)),warned:s}}catch{return{out:void 0,warned:!0}}},i=s({type:t.type}).out;if(null==i||"object"!=typeof i)return t;const n={type:t.type};for(const[e,s]of Object.entries(t))"type"===e||void 0===s||Ht(s,i[e])||(n[e]=s);if(Object.keys(n).length===Object.keys(t).length)return t;const r=s(n);return!r.warned&&Ht(r.out,t)?n:t}class Xt{constructor(t){this.value=t,this.type="value"}startGen(t){}genValue(t){return this.value}toJSON(){return{type:"ConstantValue",value:this.value}}static fromJSON(t){return new Xt(t.value)}clone(){return new Xt(this.value)}}class Zt{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(z())}genValue(t){return-1===this.indexCount&&this.startGen(t),tt.lerp(this.a,this.b,t[this.indexCount])}toJSON(){return{type:"IntervalValue",a:this.a,b:this.b}}static fromJSON(t){return new Zt(t.a,t.b)}clone(){return new Zt(this.a,this.b)}}class Kt{constructor(t,e,s,i){this.p=[t,e,s,i]}genValue(t){const e=this.p,s=t*t,i=1-t,n=i*i;return e[0]*n*i+e[1]*n*t*3+e[2]*i*s*3+e[3]*s*t}derivativeCoefficients(t){const e=[];for(let s=t,i=s.length-1;i>0;i--){const t=[];for(let e=0;e<i;e++){const n=i*(s[e+1]-s[e]);t.push(n)}e.push(t),s=t}return e}getSlope(t){const e=this.derivativeCoefficients(this.p)[0],s=1-t,i=s*t*2,n=t*t;return s*s*e[0]+i*e[1]+n*e[2]}controlCurve(t,e){this.p[1]=t/3+this.p[0],this.p[2]=this.p[3]-e/3}hull(t){let e=this.p;const s=[e[0],e[1],e[2],e[3]];for(;e.length>1;){const i=[];for(let n=0;n<e.length-1;n++){const r=(1-t)*e[n]+t*e[n+1];s.push(r),i.push(r)}e=i}return s}split(t){const e=this.hull(t);return{left:new Kt(e[0],e[4],e[7],e[9]),right:new Kt(e[9],e[8],e[6],e[3]),span:e}}clone(){return new Kt(this.p[0],this.p[1],this.p[2],this.p[3])}toJSON(){return{p0:this.p[0],p1:this.p[1],p2:this.p[2],p3:this.p[3]}}static fromJSON(t){return new Kt(t.p0,t.p1,t.p2,t.p3)}}class te{constructor(){this.functions=new Array}findFunction(t){const e=this.functions,s=e.length-1;if(s<=0)return 0===s&&t>=e[0][1]&&t<=1?0:-1;let i=0,n=s;for(;i+1<n;){const s=i+n>>1;if(t<e[s][1])n=s-1;else{if(!(t>this.getEndX(s)))return s;i=s+1}}for(let s=i;s<=n;s++)if(t>=e[s][1]&&t<=this.getEndX(s))return s;return-1}getStartX(t){return this.functions[t][1]}setStartX(t,e){t>0&&(this.functions[t][1]=e)}getEndX(t){return t+1<this.functions.length?this.functions[t+1][1]:1}setEndX(t,e){t+1<this.functions.length&&(this.functions[t+1][1]=e)}insertFunction(t,e){const s=Math.min(Math.max(t,0),1);let i=this.functions.findIndex(([,t])=>t>s);-1===i&&(i=this.functions.length),this.functions.splice(i,0,[e,s])}removeFunction(t){return this.functions.splice(t,1)[0][0]}getFunction(t){return this.functions[t][0]}setFunction(t,e){this.functions[t][0]=e}get numOfFunctions(){return this.functions.length}}class ee extends te{constructor(t=[[new Kt(0,1/3,1/3*2,1),0]]){super(),this.table=null,this.tableSignature=null,this.type="function",this.functions=t}refreshTable(){const t=this.functions,e=t.length;if(0===e)return this.table=null,void(this.tableSignature=null);const s=5*e;let i=this.tableSignature,n=null===i||i.length!==s;n&&(i=new Float64Array(s));for(let s=0,r=0;s<e;s++,r+=5){const e=t[s][0].p,o=t[s][1];n||(n=i[r]!==e[0]||i[r+1]!==e[1]||i[r+2]!==e[2]||i[r+3]!==e[3]||i[r+4]!==o),n&&(i[r]=e[0],i[r+1]=e[1],i[r+2]=e[2],i[r+3]=e[3],i[r+4]=o)}if(!n&&null!==this.table)return;this.tableSignature=i;const r=ee.TABLE_SIZE,o=null!==this.table&&this.table.length===r?this.table:new Float32Array(r),a=1/(r-1);for(let t=0;t<r;t++)o[t]=this.genValueExact(t*a);this.table=o}sampledTable(){return this.table}clearTable(){this.table=null,this.tableSignature=null}genValue(t,e=0){const s=this.table;if(null!==s){const t=s.length-1;if(e<=0)return s[0];if(e>=1)return s[t];const i=e*t,n=0|i,r=i-n,o=s[n];return o+(s[n+1]-o)*r}return this.genValueExact(e)}genValueExact(t){const e=this.functions,s=e.length;if(0===s)return 0;const i=this.findFunction(t);if(-1===i)return t<e[0][1]?e[0][0].genValue(0):e[s-1][0].genValue(1);const n=e[i][1],r=(i+1<s?e[i+1][1]:1)-n;return e[i][0].genValue(r>0?(t-n)/r:0)}toSVG(t,e){if(e<1||0===this.functions.length)return"";let s=["M",0,this.functions[0][0].p[0]].join(" ");for(let i=1/e;i<=1;i+=1/e)s=[s,"L",i*t,this.genValueExact(i)].join(" ");return s}toJSON(){return{type:"PiecewiseBezier",functions:this.functions.map(([t,e])=>({function:t.toJSON(),start:e}))}}static fromJSON(t){return new ee(t.functions.map(t=>[Kt.fromJSON(t.function),t.start]))}clone(){return new ee(this.functions.map(([t,e])=>[t.clone(),e]))}startGen(t){}}ee.TABLE_SIZE=257;class se{constructor(t,e){this.curve1=t,this.curve2=e,this.type="function",this.indexCount=-1}startGen(t){this.indexCount=t.length,t.push(z())}refreshTable(){this.curve1.refreshTable(),this.curve2.refreshTable()}genValue(t,e=0){-1===this.indexCount&&this.startGen(t);const s=t[this.indexCount],i=void 0===s?.5:s,n=this.curve1.genValue(t,e);return n+(this.curve2.genValue(t,e)-n)*i}toJSON(){return{type:"RandomBetweenCurves",curve1:this.curve1.toJSON(),curve2:this.curve2.toJSON()}}static fromJSON(t){return new se(ie(t.curve1,"curve1"),ie(t.curve2,"curve2"))}clone(){return new se(this.curve1.clone(),this.curve2.clone())}}function ie(t,e){return"PiecewiseBezier"===t?.type&&Array.isArray(t.functions)?ee.fromJSON(t):(Wt(`RandomBetweenCurves ${e}: ${Qt("curve",t)}; using a flat 0 curve.`),new ee([[new Kt(0,0,0,0),0]]))}function ne(t){switch(t?.type){case"ConstantValue":return Xt.fromJSON(t);case"IntervalValue":return Zt.fromJSON(t);case"PiecewiseBezier":return ee.fromJSON(t);case"RandomBetweenCurves":return se.fromJSON(t);default:return Wt(`${Qt("value generator",t)}; using 0.`),new Xt(0)}}const re=new st;class oe{constructor(t,e){this.axis=t,this.angle=e,this.type="rotation"}startGen(t){this.angle.startGen(t)}genValue(t,e,s,i){const n=this.axis,r=n.lengthSq();return 0===r?re.set(0,0,1):re.copy(n).multiplyScalar(1/Math.sqrt(r)),e.setFromAxisAngle(re,this.angle.genValue(t,i)*s)}toJSON(){return{type:"AxisAngle",axis:{x:this.axis.x,y:this.axis.y,z:this.axis.z},angle:this.angle.toJSON()}}static fromJSON(t){return new oe(new st(t.axis.x,t.axis.y,t.axis.z),ne(t.angle))}clone(){return new oe(this.axis.clone(),this.angle.clone())}}class ae{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(z())}genColor(t,e){return-1===this.indexCount&&this.startGen(t),e.copy(this.a).lerp(this.b,t[this.indexCount])}toJSON(){return{type:"ColorRange",a:$t(this.a),b:$t(this.b)}}static fromJSON(t){return new ae(It(t.a),It(t.b))}clone(){return new ae(this.a.clone(),this.b.clone())}}class he{constructor(t,e){this.subType=e,this.type="function",this.keys=t}findKey(t){const e=this.keys,s=e.length-1;if(s<0||t<e[0][1])return-1;if(t>=e[s][1])return s;if(1===s)return 0;let i=0,n=s;for(;i+1<n;){const s=i+n>>1;if(t<e[s][1])n=s-1;else{if(!(t>this.getEndX(s)))return s;i=s+1}}for(let s=i;s<=n;s++)if(t>=e[s][1]&&t<=this.getEndX(s))return s;return-1}getStartX(t){return this.keys[t][1]}getEndX(t){return t+1<this.keys.length?this.keys[t+1][1]:1}genValue(t,e){const s=this.keys,i=this.findKey(e),n=s.length-1;if("Number"===this.subType){if(-1===i)return s[0][0];if(i>=n)return s[n][0];const t=s[i][1],r=s[i][0],o=s[i+1][1]-t;return(s[i+1][0]-r)*(o>0?(e-t)/o:0)+r}{if(-1===i)return t.copy(s[0][0]);if(i>=n)return t.copy(s[n][0]);const r=s[i][1],o=s[i+1][1]-r;return t.copy(s[i][0]).lerp(s[i+1][0],o>0?(e-r)/o:0)}}toJSON(){return{type:"CLinearFunction",subType:this.subType,keys:this.keys.map(([t,e])=>({value:Nt(t,this.subType),pos:e}))}}static fromJSON(t){switch(t.subType){case"Number":return new he(t.keys.map(t=>[Rt(t.value),t.pos]),t.subType);case"Vector4":return new he(t.keys.map(t=>[Ut(t.value),t.pos]),t.subType);default:return new he(t.keys.map(t=>[Bt(t.value),t.pos]),t.subType)}}clone(){return"Number"===this.subType?new he(this.keys.map(([t,e])=>[t,e]),this.subType):new he(this.keys.map(([t,e])=>[t.clone(),e]),this.subType)}}const le=new Pt;class ce{constructor(t=[[new st(1,1,1),0],[new st(1,1,1),1]],e=[[1,0],[1,1]]){this.table=null,this.tableSignature=null,this.type="function",this.color=new he(t,"Color"),this.alpha=new he(e,"Number")}refreshTable(){const t=this.color.keys,e=this.alpha.keys,s=4*t.length+2*e.length;let i=this.tableSignature,n=null===i||i.length!==s;n&&(i=new Float64Array(s));let r=0;for(let e=0;e<t.length;e++,r+=4){const s=t[e][0],o=t[e][1];n||(n=i[r]!==s.x||i[r+1]!==s.y||i[r+2]!==s.z||i[r+3]!==o),n&&(i[r]=s.x,i[r+1]=s.y,i[r+2]=s.z,i[r+3]=o)}for(let t=0;t<e.length;t++,r+=2){const s=e[t][0],o=e[t][1];n||(n=i[r]!==s||i[r+1]!==o),n&&(i[r]=s,i[r+1]=o)}if(!n&&null!==this.table)return;this.tableSignature=i;const o=ce.TABLE_SIZE,a=null!==this.table&&this.table.length===4*o?this.table:new Float32Array(4*o),h=1/(o-1),l=le;for(let t=0;t<o;t++){this.genColorExact(l,t*h);const e=4*t;a[e]=l.x,a[e+1]=l.y,a[e+2]=l.z,a[e+3]=l.w}this.table=a}sampledTable(){return this.table}clearTable(){this.table=null,this.tableSignature=null}genColor(t,e,s){const i=this.table;if(null!==i){const t=ce.TABLE_SIZE-1;if(s<=0)return e.x=i[0],e.y=i[1],e.z=i[2],e.w=i[3],e;if(s>=1){const s=4*t;return e.x=i[s],e.y=i[s+1],e.z=i[s+2],e.w=i[s+3],e}const n=s*t,r=0|n,o=n-r,a=4*r,h=a+4;return e.x=i[a]+(i[h]-i[a])*o,e.y=i[a+1]+(i[h+1]-i[a+1])*o,e.z=i[a+2]+(i[h+2]-i[a+2])*o,e.w=i[a+3]+(i[h+3]-i[a+3])*o,e}return this.genColorExact(e,s)}genColorExact(t,e){const s=this.color.keys,i=s.length-1,n=this.color.findKey(e);let r,o,a;if(-1===n||n>=i){const t=s[-1===n?0:i][0];r=t.x,o=t.y,a=t.z}else{const t=s[n][0],i=s[n+1][0],h=s[n][1],l=s[n+1][1]-h,c=l>0?(e-h)/l:0;r=t.x+(i.x-t.x)*c,o=t.y+(i.y-t.y)*c,a=t.z+(i.z-t.z)*c}const h=this.alpha.keys,l=h.length-1,c=this.alpha.findKey(e);let u;if(-1===c||c>=l)u=h[-1===c?0:l][0];else{const t=h[c][1],s=h[c][0],i=h[c+1][1]-t;u=s+(h[c+1][0]-s)*(i>0?(e-t)/i:0)}return t.x=r,t.y=o,t.z=a,t.w=u,t}toJSON(){return{type:"Gradient",color:this.color.toJSON(),alpha:this.alpha.toJSON()}}static fromJSON(t){if(t.functions){const e=t.functions.map(({function:t,start:e})=>[ae.fromJSON(t),e]),s=e.map(([t,e])=>[t.a,e]);return e.length>0&&s.push([e[e.length-1][0].b,1]),new ce(s.map(([t,e])=>[new st(t.x,t.y,t.z),e]),s.map(([t,e])=>[t.w,e]))}{const e=new ce;return t.alpha?e.alpha=he.fromJSON(t.alpha):Wt("Gradient has no alpha keys; it is opaque."),t.color?e.color=he.fromJSON(t.color):Wt("Gradient has no color keys; it is white."),e}}clone(){const t=new ce;return t.alpha=this.alpha.clone(),t.color=this.color.clone(),t}startGen(t){}}ce.TABLE_SIZE=257;class ue{constructor(t,e){this.a=t,this.b=e,this.type="value"}startGen(t){}genColor(t,e){const s=z();return e.copy(this.a).lerp(this.b,s)}toJSON(){return{type:"RandomColor",a:$t(this.a),b:$t(this.b)}}static fromJSON(t){return new ue(It(t.a),It(t.b))}clone(){return new ue(this.a.clone(),this.b.clone())}}const de=new Pt;class fe{constructor(t,e){this.indexCount=-1,this.type="function",this.gradient1=t,this.gradient2=e}startGen(t){this.indexCount=t.length,t.push(z())}genColor(t,e,s){return-1===this.indexCount&&this.startGen(t),this.gradient1.genColor(t,e,s),this.gradient2.genColor(t,de,s),e.lerp(de,t[this.indexCount])}toJSON(){return{type:"RandomColorBetweenGradient",gradient1:this.gradient1.toJSON(),gradient2:this.gradient2.toJSON()}}static fromJSON(t){return new fe(ce.fromJSON(t.gradient1),ce.fromJSON(t.gradient2))}clone(){return new fe(this.gradient1.clone(),this.gradient2.clone())}}class pe{constructor(t){this.color=t,this.type="value"}startGen(t){}genColor(t,e){return e.copy(this.color)}toJSON(){return{type:"ConstantColor",color:$t(this.color)}}static fromJSON(t){return new pe(It(t.color))}clone(){return new pe(this.color.clone())}}function me(t){switch(t?.type){case"ConstantColor":return pe.fromJSON(t);case"ColorRange":return ae.fromJSON(t);case"RandomColor":return ue.fromJSON(t);case"Gradient":return ce.fromJSON(t);case"RandomColorBetweenGradient":return fe.fromJSON(t);default:return Wt(`${Qt("colour generator",t)}; using white.`),new pe(new Pt(1,1,1,1))}}class ye{get eular(){return this.euler}set eular(t){this.euler=t}constructor(t,e,s,i){this.angleX=t,this.angleY=e,this.angleZ=s,this.type="rotation",this.euler=new gt(0,0,0,i)}startGen(t){this.angleX.startGen(t),this.angleY.startGen(t),this.angleZ.startGen(t)}genValue(t,e,s,i){return this.euler.set(this.angleX.genValue(t,i)*s,this.angleY.genValue(t,i)*s,this.angleZ.genValue(t,i)*s),e.setFromEuler(this.euler)}toJSON(){return{type:"Euler",angleX:this.angleX.toJSON(),angleY:this.angleY.toJSON(),angleZ:this.angleZ.toJSON(),eulerOrder:this.euler.order}}static fromJSON(t){return new ye(ne(t.angleX),ne(t.angleY),ne(t.angleZ),t.eulerOrder)}clone(){return new ye(this.angleX.clone(),this.angleY.clone(),this.angleZ.clone(),this.euler.order)}}class ge{constructor(){this.indexCount=-1,this.type="rotation"}startGen(t){let e,s,i,n,r,o;this.indexCount=t.length;do{e=2*z()-1,s=2*z()-1,i=e*e+s*s}while(i>1);do{n=2*z()-1,r=2*z()-1,o=n*n+r*r}while(o>1);const a=Math.sqrt((1-i)/o);t.push(e,s,a*n,a*r)}genValue(t,e,s,i){-1===this.indexCount&&this.startGen(t);const n=this.indexCount;return e.set(t[n],t[n+1],t[n+2],t[n+3]),e}toJSON(){return{type:"RandomQuat"}}static fromJSON(t){return new ge}clone(){return new ge}}function ve(t){switch(t?.type){case"AxisAngle":return oe.fromJSON(t);case"Euler":return ye.fromJSON(t);case"RandomQuat":return ge.fromJSON(t);default:return Wt(`${Qt("rotation generator",t)}; using a random rotation.`),new ge}}class xe{constructor(t,e,s){this.x=t,this.y=e,this.z=s,this.type="vec3function"}startGen(t){this.x.startGen(t),this.y.startGen(t),this.z.startGen(t)}genValue(t,e,s){return e.set(this.x.genValue(t,s),this.y.genValue(t,s),this.z.genValue(t,s))}toJSON(){return{type:"Vector3Function",x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new xe(ne(t.x),ne(t.y),ne(t.z))}clone(){return new xe(this.x.clone(),this.y.clone(),this.z.clone())}}function Se(t){return"Vector3Function"===t?.type?xe.fromJSON(t):(Wt(`${Qt("vector generator",t)}; using a zero vector.`),new xe(new Xt(0),new Xt(0),new Xt(0)))}function be(t){switch(t?.type){case"ConstantValue":case"IntervalValue":case"PiecewiseBezier":case"RandomBetweenCurves":return ne(t);case"AxisAngle":case"RandomQuat":case"Euler":return ve(t);case"Vector3Function":return Se(t);default:return Wt(`${Qt("generator",t)}; using 0.`),new Xt(0)}}const we=[new st,new st,new st],Me=new at,ze=new st(1,0,0),_e=new st(0,1,0),Ae=[!1,!1,!1];function Pe(t,e){return"world"===t||"local"===t?t:e}function Oe(t){return 0===t?0:1/t}class Te{constructor(){this.position=new st,this.quaternion=new et,this.scale=new st(1,1,1),this.quaternionInverse=new et,this.scaleInverse=new st(1,1,1)}refresh(t){const e=t.emitter.matrixWorld;e.decompose(this.position,this.quaternion,this.scale),0!==this.scale.x&&0!==this.scale.y&&0!==this.scale.z||function(t,e){t.extractBasis(we[0],we[1],we[2]);let s=0;for(let t=0;t<3;t++)Ae[t]=we[t].lengthSq()>0,Ae[t]&&(we[t].normalize(),s++);if(0===s)return e.set(0,0,0,1);if(1===s){const t=Ae.indexOf(!0),e=(t+1)%3,s=we[t],i=Math.abs(s.x)<.9?ze:_e;we[e].crossVectors(s,i).normalize(),Ae[e]=!0}const i=Ae.indexOf(!1);we[i].crossVectors(we[(i+1)%3],we[(i+2)%3]).normalize(),e.setFromRotationMatrix(Me.makeBasis(we[0],we[1],we[2]))}(e,this.quaternion),this.quaternionInverse.copy(this.quaternion).invert(),this.scaleInverse.set(Oe(this.scale.x),Oe(this.scale.y),Oe(this.scale.z))}toSimulation(t,e,s){return s&&"local"===e?t.multiply(this.scale).applyQuaternion(this.quaternion):s||"world"!==e||t.applyQuaternion(this.quaternionInverse).multiply(this.scaleInverse),t}fromSimulation(t,e,s){return s&&"local"===e?t.applyQuaternion(this.quaternionInverse).multiply(this.scaleInverse):s||"world"!==e||t.multiply(this.scale).applyQuaternion(this.quaternion),t}pointToSimulation(t,e,s){return s&&"local"===e?t.multiply(this.scale).applyQuaternion(this.quaternion).add(this.position):s||"world"!==e||t.sub(this.position).applyQuaternion(this.quaternionInverse).multiply(this.scaleInverse),t}}class Ve{constructor(t,e,s="world"){this.direction=t,this.magnitude=e,this.space=s,this.type="ApplyForce",this._frame=new Te,this._direction=new st,this._direction.copy(t)}initialize(t,e){this.ps=e,this.magnitude.startGen(t.memory)}_step(t){const e=this.ps;return(void 0===e||e.worldSpace)&&"world"===this.space?t*(e?.motionScale??1):t}update(t,e){const s=this.magnitude.genValue(t.memory)*this._step(e),i=this._direction,n=t.velocity;n.x+=i.x*s,n.y+=i.y*s,n.z+=i.z*s}updateAll(t,e,s){const i=this.magnitude,n=this._direction,r=this._step(s),o=i instanceof Xt,a=o?i.value*r:0;for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const h=o?a:i.genValue(e.memory)*r,l=e.velocity;l.x+=n.x*h,l.y+=n.y*h,l.z+=n.z*h}}frameUpdate(t){this._direction.copy(this.direction),void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)&&(this._frame.refresh(this.ps),this._frame.toSimulation(this._direction,this.space,this.ps.worldSpace))}toJSON(){return{type:this.type,direction:[this.direction.x,this.direction.y,this.direction.z],magnitude:this.magnitude.toJSON(),..."world"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new Ve(jt(t.direction,new st(0,0,0)),ne(t.magnitude??t.force),Pe(t.space,"world"))}clone(){return new Ve(this.direction.clone(),this.magnitude.clone(),this.space)}reset(){}}class Ee{constructor(t=0,e=0,s=new st){this.scaleX=t,this.scaleY=e,this.position=s,this.locations=[]}transform(t,e){const s=this.locations.length;if(0===s)return;const i=this.locations[e%s];t.x=i.x*this.scaleX+this.position.x,t.y=i.y*this.scaleY+this.position.y,t.z=this.position.z}static fromJSON(t){const e=t.position,s=Array.isArray(e)?new st(e[0],e[1],e[2]):new st(e?.x??0,e?.y??0,e?.z??0),i=new Ee(t.scaleX??0,t.scaleY??0,s);return i.locations=(t.locations??[]).map(t=>new Mt(t.x,t.y)),i}clone(){const t=new Ee(this.scaleX,this.scaleY,this.position.clone());return t.locations=this.locations.map(t=>t.clone()),t}toJSON(){return{type:"TextureSequencer",scaleX:this.scaleX,scaleY:this.scaleY,position:[this.position.x,this.position.y,this.position.z],locations:this.locations.map(t=>({x:t.x,y:t.y}))}}fromImage(t,e){const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const i=s.getContext("2d");if(!i)return;i.drawImage(t,0,0);const n=i.getImageData(0,0,s.width,s.height,{colorSpace:"srgb"});s.remove(),this.locations.length=0;for(let t=0;t<n.height;t++)for(let s=0;s<n.width;s++)n.data[4*(t*n.width+s)+3]>e&&this.locations.push(new Mt(s,n.height-t))}}function Ce(t){switch(t?.type){case void 0:return null==t?void Wt(`${Qt("sequencer",t)}; skipping it.`):Ee.fromJSON(t);case"TextureSequencer":return Ee.fromJSON(t);default:return void Wt(`${Qt("sequencer",t)}; skipping it.`)}}class $e{constructor(t){this.type="ApplySequences",this.sequencers=[],this.time=0,this.index=0,this.pCount=0,this.tempV=new st,this.states=new WeakMap,this.delay=t}initialize(t){const e=this.states.get(t);e?(e.id=this.pCount,e.inMotion=!1):this.states.set(t,{id:this.pCount,begin:new st,dst:new st,inMotion:!1}),this.pCount++}reset(){this.time=0,this.index=0,this.pCount=0}update(t,e){const s=this.sequencers[this.index];if(void 0===s)return;const i=this.states.get(t);if(void 0===i)return;const[n,r]=s,o=i.id*this.delay;if(this.time>=n.a+o&&this.time<=n.b+o){i.inMotion||(i.inMotion=!0,i.begin.copy(t.position),r.transform(i.dst,i.id));const e=n.b-n.a;t.position.lerpVectors(i.begin,i.dst,$e.BEZIER.genValue(e>0?(this.time-n.a-o)/e:1))}else this.time>n.b+o&&(i.inMotion=!1)}frameUpdate(t){for(;this.index+1<this.sequencers.length&&this.time>=this.sequencers[this.index+1][0].a;)this.index++;this.time+=t}appendSequencer(t,e){this.sequencers.push([t,e])}toJSON(){return{type:this.type,delay:this.delay,sequencers:this.sequencers.map(([t,e])=>({range:t.toJSON(),sequencer:e.toJSON()}))}}static fromJSON(t){const e=new $e("number"==typeof t.delay?t.delay:0);return(Array.isArray(t.sequencers)?t.sequencers:[]).forEach(t=>{const s=Ce(t.sequencer);void 0!==s&&e.sequencers.push([ne(t.range),s])}),e}clone(){const t=new $e(this.delay);return t.sequencers=this.sequencers.map(t=>[t[0].clone(),t[1].clone()]),t}}$e.BEZIER=new Kt(0,0,1,1);class Ie{constructor(t){this.angle=t,this.type="ChangeEmitDirection",this._temp=new st,this._q=new et,this.memory=[]}initialize(t){const e=t.velocity.length();0!=e&&(t.velocity.normalize(),0===t.velocity.x&&0===t.velocity.y?this._temp.set(0,t.velocity.z,0):this._temp.set(-t.velocity.y,t.velocity.x,0),this.memory.length=0,this.angle.startGen(this.memory),this._q.setFromAxisAngle(this._temp.normalize(),this.angle.genValue(this.memory)),this._temp.copy(t.velocity),t.velocity.applyQuaternion(this._q),this._q.setFromAxisAngle(this._temp,z()*Math.PI*2),t.velocity.applyQuaternion(this._q),t.velocity.setLength(e))}update(t,e){}frameUpdate(t){}toJSON(){return{type:this.type,angle:this.angle.toJSON()}}static fromJSON(t){return new Ie(ne(t.angle))}clone(){return new Ie(this.angle.clone())}reset(){this.memory.length=0}}function Ne(t,e){const s=t.velocity.length()*t.speedModifier,i=e.b-e.a;if(0===i)return s>=e.a?1:0;const n=(s-e.a)/i;return n<0?0:n>1?1:n}class Fe{constructor(t,e){this.color=t,this.speedRange=e,this.type="ColorBySpeed"}initialize(t){this.color.startGen(t.memory)}update(t,e){const s=Ne(t,this.speedRange);this.color.genColor(t.memory,t.color,s),t.color.x*=t.startColor.x,t.color.y*=t.startColor.y,t.color.z*=t.startColor.z,t.color.w*=t.startColor.w}frameUpdate(t){}toJSON(){return{type:this.type,color:this.color.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new Fe(me(t.color),t.speedRange?Zt.fromJSON(t.speedRange):new Zt(0,1))}clone(){return new Fe(this.color.clone(),this.speedRange.clone())}reset(){}}class Re{constructor(t){this.color=t,this.type="ColorOverLife"}initialize(t){this.color.startGen(t.memory)}update(t,e){const s=t.color,i=t.startColor;this.color.genColor(t.memory,s,t.age/t.life),s.x*=i.x,s.y*=i.y,s.z*=i.z,s.w*=i.w}updateAll(t,e,s){const i=this.color;for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const n=e.color,r=e.startColor;i.genColor(e.memory,n,e.age/e.life),n.x*=r.x,n.y*=r.y,n.z*=r.z,n.w*=r.w}}frameUpdate(t){this.color.refreshTable?.()}toJSON(){return{type:this.type,color:this.color.toJSON()}}static fromJSON(t){return new Re(me(t.color))}clone(){return new Re(this.color.clone())}reset(){}}class Be{constructor(t=64){this.previousVelocity=Be.EMPTY,this.rotationQuaternion=Be.EMPTY,this.angularVelocityQuaternion=Be.EMPTY,this.memory=new Float64Array(0),this.memoryStride=0,this.capacity=Math.max(1,t),this.position=new Float32Array(3*this.capacity),this.previousPosition=new Float32Array(3*this.capacity),this.previousSize=new Float32Array(3*this.capacity),this.previousColor=new Float32Array(4*this.capacity),this.velocity=new Float32Array(3*this.capacity),this.size=new Float32Array(3*this.capacity),this.startSize=new Float32Array(3*this.capacity),this.color=new Float32Array(4*this.capacity),this.startColor=new Float32Array(4*this.capacity),this.scalars=new Float64Array(this.capacity*Be.SCALAR_STRIDE),this.rotation=new Float32Array(this.capacity),this.angularVelocity=new Float32Array(this.capacity),this.uvTile=new Float32Array(this.capacity),this.startSpeed=new Float32Array(this.capacity),this.flip=new Uint8Array(this.capacity)}ensureCapacity(t){if(t<=this.capacity)return!1;let e=this.capacity;for(;e<t;)e*=2;this.position=Be.grow(this.position,3*e),this.previousPosition=Be.grow(this.previousPosition,3*e);const s=this.previousSize===this.size,i=this.previousColor===this.color;if(s||(this.previousSize=Be.grow(this.previousSize,3*e)),this.previousVelocity.length>0&&(this.previousVelocity=Be.grow(this.previousVelocity,3*e)),this.rotationQuaternion.length>0){const t=this.rotationQuaternion.length;this.rotationQuaternion=Be.grow(this.rotationQuaternion,4*e),this.angularVelocityQuaternion=Be.grow(this.angularVelocityQuaternion,4*e);for(let s=t+3;s<4*e;s+=4)this.rotationQuaternion[s]=1,this.angularVelocityQuaternion[s]=1}if(i||(this.previousColor=Be.grow(this.previousColor,4*e)),this.velocity=Be.grow(this.velocity,3*e),this.size=Be.grow(this.size,3*e),this.startSize=Be.grow(this.startSize,3*e),this.color=Be.grow(this.color,4*e),s&&(this.previousSize=this.size),i&&(this.previousColor=this.color),this.startColor=Be.grow(this.startColor,4*e),this.scalars=Be.growDouble(this.scalars,e*Be.SCALAR_STRIDE),this.memoryStride>0){const t=new Float64Array(e*this.memoryStride);t.fill(NaN),t.set(this.memory),this.memory=t}this.rotation=Be.grow(this.rotation,e),this.angularVelocity=Be.grow(this.angularVelocity,e),this.uvTile=Be.grow(this.uvTile,e),this.startSpeed=Be.grow(this.startSpeed,e);const n=new Uint8Array(e);return n.set(this.flip),this.flip=n,this.capacity=e,!0}keepPreviousVelocity(){return!(this.previousVelocity.length>=3*this.capacity)&&(this.previousVelocity=new Float32Array(3*this.capacity),!0)}recordMemory(t,e){const s=e.length;let i=this.memoryStride;if(s>i||this.memory.length<this.capacity*i){i=Math.max(i,s);const t=new Float64Array(this.capacity*i);t.fill(NaN);const e=this.memoryStride,n=this.memory,r=e>0?n.length/e:0;for(let s=0,o=0,a=0;s<r;s++,o+=e,a+=i)for(let s=0;s<e;s++)t[a+s]=n[o+s];this.memory=t,this.memoryStride=i}const n=t*i;for(let t=0;t<i;t++){const i=t<s?e[t]:void 0;this.memory[n+t]="number"==typeof i?i:NaN}}useSizeSnapshot(t){t?this.previousSize===this.size&&(this.previousSize=new Float32Array(this.size)):this.previousSize=this.size}useColorSnapshot(t){t?this.previousColor===this.color&&(this.previousColor=new Float32Array(this.color)):this.previousColor=this.color}ensureQuaternionColumns(){if(this.rotationQuaternion.length>=4*this.capacity)return!1;this.rotationQuaternion=new Float32Array(4*this.capacity),this.angularVelocityQuaternion=new Float32Array(4*this.capacity);for(let t=3;t<this.rotationQuaternion.length;t+=4)this.rotationQuaternion[t]=1,this.angularVelocityQuaternion[t]=1;return!0}swapRows(t,e){if(t===e)return;const s=3*t,i=3*e;Be.swap3(this.position,s,i),Be.swap3(this.previousPosition,s,i),this.previousSize!==this.size&&Be.swap3(this.previousSize,s,i),this.previousVelocity.length>0&&Be.swap3(this.previousVelocity,s,i),Be.swap3(this.velocity,s,i),Be.swap3(this.size,s,i),Be.swap3(this.startSize,s,i);const n=4*t,r=4*e;Be.swap4(this.color,n,r),this.previousColor!==this.color&&Be.swap4(this.previousColor,n,r),Be.swap4(this.startColor,n,r),this.rotationQuaternion.length>0&&(Be.swap4(this.rotationQuaternion,n,r),Be.swap4(this.angularVelocityQuaternion,n,r)),Be.swap3(this.scalars,t*Be.SCALAR_STRIDE,e*Be.SCALAR_STRIDE);const o=this.memoryStride;if(o>0){const s=this.memory;for(let i=0,n=t*o,r=e*o;i<o;i++,n++,r++){const t=s[n];s[n]=s[r],s[r]=t}}Be.swap1(this.rotation,t,e),Be.swap1(this.angularVelocity,t,e),Be.swap1(this.uvTile,t,e),Be.swap1(this.startSpeed,t,e),Be.swap1(this.flip,t,e)}static swap1(t,e,s){const i=t[e];t[e]=t[s],t[s]=i}static growDouble(t,e){const s=new Float64Array(e);return s.set(t),s}static swap3(t,e,s){let i=t[e];t[e]=t[s],t[s]=i,i=t[e+1],t[e+1]=t[s+1],t[s+1]=i,i=t[e+2],t[e+2]=t[s+2],t[s+2]=i}static swap4(t,e,s){Be.swap3(t,e,s);const i=t[e+3];t[e+3]=t[s+3],t[s+3]=i}static grow(t,e){const s=new Float32Array(e);return s.set(t),s}}Be.EMPTY=new Float32Array(0),Be.SCALAR_STRIDE=3,Be.AGE=0,Be.LIFE=1,Be.SPEED_MODIFIER=2;class Ue{constructor(t){this.data=t,this.next=null,this.prev=null}hasPrev(){return null!==this.prev}hasNext(){return null!==this.next}}class Le{constructor(){this.length=0,this.head=this.tail=null}isEmpty(){return null===this.head}clear(){this.length=0,this.head=this.tail=null}front(){return null===this.head?null:this.head.data}back(){return null===this.tail?null:this.tail.data}dequeue(){if(this.head){const t=this.head.data;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,t}}pop(){if(this.tail){const t=this.tail.data;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,t}}queue(t){const e=new Ue(t);this.tail||(this.tail=e),this.head&&(this.head.prev=e,e.next=this.head),this.head=e,this.length++}push(t){const e=new Ue(t);this.head||(this.head=e),this.tail&&(this.tail.next=e,e.prev=this.tail),this.tail=e,this.length++}insertBefore(t,e){const s=new Ue(e);s.next=t,s.prev=t.prev,null!==s.prev&&(s.prev.next=s),s.next.prev=s,t==this.head&&(this.head=s),this.length++}remove(t){if(null===this.head||null===this.tail)return;let e=this.head;for(t===this.head.data&&(this.head=this.head.next),t===this.tail.data&&(this.tail=this.tail.prev);null!==e.next&&e.data!==t;)e=e.next;e.data===t&&(null!==e.prev&&(e.prev.next=e.next),null!==e.next&&(e.next.prev=e.prev),this.length--)}*values(){let t=this.head;for(;null!==t;)yield t.data,t=t.next}}class De{get startSpeed(){return this.store.startSpeed[this.storeIndex]}set startSpeed(t){this.store.startSpeed[this.storeIndex]=t}get age(){return this.scalars[this.scalarOffset]}set age(t){this.scalars[this.scalarOffset]=t}get life(){return this.scalars[this.scalarOffset+1]}set life(t){this.scalars[this.scalarOffset+1]=t}get speedModifier(){return this.scalars[this.scalarOffset+2]}set speedModifier(t){this.scalars[this.scalarOffset+2]=t}get angularVelocity(){const t=this.angularVelocityQuaternion;return void 0!==t?t:this.store.angularVelocity[this.storeIndex]}set angularVelocity(t){if("number"==typeof t)this.angularVelocityQuaternion=void 0,this.store.angularVelocity[this.storeIndex]=t;else if(void 0===t)this.angularVelocityQuaternion=void 0,this.store.angularVelocity[this.storeIndex]=0;else{let e=this.angularVelocityQuaternion;void 0===e&&(this.store.ensureQuaternionColumns(),e=new bt(this.store.angularVelocityQuaternion,4*this.storeIndex),this.angularVelocityQuaternion=e),e!==t&&e.copy(t)}}get rotation(){const t=this.rotationQuaternion;return void 0!==t?t:this.store.rotation[this.storeIndex]}set rotation(t){if("number"==typeof t)this.rotationQuaternion=void 0,this.store.rotation[this.storeIndex]=t;else{let e=this.rotationQuaternion;void 0===e&&(this.store.ensureQuaternionColumns(),e=new bt(this.store.rotationQuaternion,4*this.storeIndex),this.rotationQuaternion=e),e!==t&&e.copy(t)}}get uvTile(){return this.store.uvTile[this.storeIndex]}set uvTile(t){this.store.uvTile[this.storeIndex]=t}get flip(){return this.store.flip[this.storeIndex]}set flip(t){this.store.flip[this.storeIndex]=t}constructor(t=new Be(1),e=0){this.rotationQuaternion=void 0,this.angularVelocityQuaternion=void 0,this.memory=[],this.store=t,this.storeIndex=e;const s=3*e,i=4*e;this.position=new _t(t.position,s),this.previousPosition=new _t(t.previousPosition,s),this.previousVelocity=new _t(t.previousVelocity,s),this.velocity=new _t(t.velocity,s),this.size=new _t(t.size,s),this.startSize=new _t(t.startSize,s),this.color=new Tt(t.color,i),this.startColor=new Tt(t.startColor,i),this.scalars=t.scalars,this.scalarOffset=e*Be.SCALAR_STRIDE,this.size.set(1,1,1),this.startSize.set(1,1,1),this.life=1,this.speedModifier=1}setStoreIndex(t){this.storeIndex=t,this.rebind()}rebind(){const t=this.store,e=3*this.storeIndex,s=4*this.storeIndex;this.position.bind(t.position,e),this.previousPosition.bind(t.previousPosition,e),this.previousVelocity.bind(t.previousVelocity,e),this.velocity.bind(t.velocity,e),this.size.bind(t.size,e),this.startSize.bind(t.startSize,e),this.color.bind(t.color,s),this.startColor.bind(t.startColor,s),this.rotationQuaternion?.bind(t.rotationQuaternion,s),this.angularVelocityQuaternion?.bind(t.angularVelocityQuaternion,s),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*Be.SCALAR_STRIDE}get died(){return this.age>=this.life}reset(){this.memory.length=0}}const ke=new Float32Array(0);class qe{get startSpeed(){return this.store.startSpeed[this.storeIndex]}set startSpeed(t){this.store.startSpeed[this.storeIndex]=t}get age(){return this.scalars[this.scalarOffset]}set age(t){this.scalars[this.scalarOffset]=t}get life(){return this.scalars[this.scalarOffset+1]}set life(t){this.scalars[this.scalarOffset+1]=t}get speedModifier(){return this.scalars[this.scalarOffset+2]}set speedModifier(t){this.scalars[this.scalarOffset+2]=t}get previous(){return this._previous??(this._previous=new Le)}set previous(t){this._previous=t}get uvTile(){return this.store.uvTile[this.storeIndex]}set uvTile(t){this.store.uvTile[this.storeIndex]=t}constructor(t=new Be(1),e=0){this.length=30,this._previous=void 0,this.historyPositions=ke,this.historySizes=ke,this.historyBaseSizes=ke,this.headWidthScale=1,this.historyColors=ke,this.historySides=ke,this.historyAges=ke,this.historyDistances=ke,this.historyCapacity=0,this.historyHead=0,this.historyCount=0,this.memory=[],this.store=t,this.storeIndex=e;const s=3*e,i=4*e;this.position=new _t(t.position,s),this.previousPosition=new _t(t.previousPosition,s),this.previousVelocity=new _t(t.previousVelocity,s),this.velocity=new _t(t.velocity,s),this.size=new _t(t.size,s),this.startSize=new _t(t.startSize,s),this.color=new Tt(t.color,i),this.startColor=new Tt(t.startColor,i),this.scalars=t.scalars,this.scalarOffset=e*Be.SCALAR_STRIDE,this.size.set(1,1,1),this.startSize.set(1,1,1),this.life=1,this.speedModifier=1}setStoreIndex(t){this.storeIndex=t,this.rebind()}rebind(){const t=this.store,e=3*this.storeIndex,s=4*this.storeIndex;this.position.bind(t.position,e),this.previousPosition.bind(t.previousPosition,e),this.previousVelocity.bind(t.previousVelocity,e),this.velocity.bind(t.velocity,e),this.size.bind(t.size,e),this.startSize.bind(t.startSize,e),this.color.bind(t.color,s),this.startColor.bind(t.startColor,s),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*Be.SCALAR_STRIDE}ensureHistoryCapacity(t){this.historyCapacity!==t&&(this.historyCapacity=t,this.historySizes.length<t&&(this.historyPositions=new Float32Array(3*t),this.historySizes=new Float32Array(t),this.historyBaseSizes=new Float32Array(t),this.historyColors=new Float32Array(4*t),this.historyAges=new Float32Array(t),this.historyDistances=new Float32Array(t),this.historySides.length>0&&(this.historySides=new Float32Array(3*t))),this.historyHead=0,this.historyCount=0)}ensureSideHistory(){this.historySides.length<3*this.historyCapacity&&(this.historySides=new Float32Array(3*this.historyCapacity))}resetHistory(){this.historyHead=0,this.historyCount=0}getHistoryIndex(t){const e=this.historyCapacity;return(this.historyHead-this.historyCount+e+t)%e}update(t=!1,e=!0){0===this.historyCapacity&&this.ensureHistoryCapacity(Math.max(1,Math.ceil(this.length)));const s=this.historyCapacity,i=this.store,n=this.storeIndex,r=n*Be.SCALAR_STRIDE,o=i.scalars[r+Be.AGE];if(o>=i.scalars[r+Be.LIFE])return void this.dropOldest();const a=t&&this.historyCount>0,h=a?(this.historyHead+s-1)%s:this.historyHead,l=3*h,c=this.historyPositions,u=i.position,d=3*n;c[l]=u[d],c[l+1]=u[d+1],c[l+2]=u[d+2];const f=i.size[d];this.historyBaseSizes[h]=f,this.historySizes[h]=f*this.headWidthScale;const p=4*h,m=this.historyColors,y=i.color,g=4*n;m[p]=y[g],m[p+1]=y[g+1],m[p+2]=y[g+2],m[p+3]=y[g+3],this.historyAges[h]=o,a||(this.historyHead=(h+1)%s,this.historyCount<s&&this.historyCount++),e&&this.measureHeadDistance()}measureHeadDistance(){const t=this.historyCount;if(0===t)return;const e=this.historyCapacity,s=(this.historyHead+e-1)%e;if(1===t)return void(this.historyDistances[s]=0);const i=(s+e-1)%e,n=this.historyPositions,r=n[3*s]-n[3*i],o=n[3*s+1]-n[3*i+1],a=n[3*s+2]-n[3*i+2];this.historyDistances[s]=this.historyDistances[i]+Math.sqrt(r*r+o*o+a*a)}dropOldest(){this.historyCount>0&&this.historyCount--}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.headWidthScale=1,this.resetHistory()}}function Ge(t,e){return Math.floor(z()*(e-t))+t}function Je(t,e){const s=Number.isNaN(t)?0:1-tt.clamp(t,0,1),i=tt.lerp(Math.pow(s,e),1,z());return 2===e?Math.sqrt(i):Math.cbrt(i)}const We=new st(0,1,0),je=new st(0,0,0),Qe=new st(1,1,1),He=new st(0,0,1),Ye=1e-6;var Xe;exports.SubParticleEmitMode=void 0,(Xe=exports.SubParticleEmitMode||(exports.SubParticleEmitMode={}))[Xe.Death=0]="Death",Xe[Xe.Birth=1]="Birth",Xe[Xe.Frame=2]="Frame";const Ze={color:1,size:2,rotation:4,lifetime:8};function Ke(t){let e=0;for(const s of t)e|=Ze[s]??0;return e}class ts{constructor(t,e,s,i=exports.SubParticleEmitMode.Frame,n=1,r=[]){this.particleSystem=t,this.useVelocityAsBasis=e,this.subParticleSystem=s,this.mode=i,this.emitProbability=n,this.inherit=r,this.type="EmitSubParticleSystem",this.q_=new et,this.v_=new st,this.v2_=new st,this.v3_=new st,this.subEmissions=new Array,this.spareEmissions=new Array;const o=this.target;o&&(o.onlyUsedByOther=!0)}initialize(t){}update(t,e){(this.mode===exports.SubParticleEmitMode.Frame||this.mode===exports.SubParticleEmitMode.Birth&&0===t.age||this.mode===exports.SubParticleEmitMode.Death&&t.age+e>=t.life&&!this.particleSystem.ringBufferActive)&&this.emit(t,e)}hasPendingEmission(){const t=this.target;if(void 0===t)return!1;for(let e=0;e<this.subEmissions.length;e++)if(t.hasPendingEmission(this.subEmissions[e]))return!0;return!1}get targetSystem(){return this.target}get target(){const t=this.subParticleSystem;if(null===t||"object"!=typeof t)return;const e=t.system;return e?.isDisposed?void 0:e}emit(t,e){if(!this.target)return;if(z()>this.emitProbability)return;const s=this.spareEmissions.pop(),i=void 0!==s?s:{burstParticleCount:0,burstParticleIndex:0,isBursting:!1,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,matrix:new at,travelDistance:0,particle:void 0,serial:void 0,previousWorldPos:void 0};i.burstParticleCount=0,i.burstParticleIndex=0,i.isBursting=!1,i.burstIndex=0,i.burstWaveIndex=0,i.time=0,i.waitEmiting=0,i.travelDistance=0,this.mode===exports.SubParticleEmitMode.Death?(i.particle=ts.copyInto(i.ghost??(i.ghost=new De),t),i.serial=void 0):(i.particle=t,i.serial=t.serial),i.inherit=Ke(this.inherit),this.mode===exports.SubParticleEmitMode.Death&&(i.inherit&=~Ze.lifetime),i.previousWorldPos=void 0,this.setMatrixFromParticle(i.matrix,t),this.subEmissions.push(i)}frameUpdate(t){const e=this.target;if(e)for(let s=0;s<this.subEmissions.length;s++)if(this.subEmissions[s].time>=e.duration){const t=this.subEmissions[s];t.particle=void 0,t.matrix=new at,this.spareEmissions.push(t),this.subEmissions[s]=this.subEmissions[this.subEmissions.length-1],this.subEmissions.length=this.subEmissions.length-1,s--}else{const i=this.subEmissions[s],n=i.particle;void 0!==n&&n===i.ghost||(void 0!==n&&n.age<n.life&&n.serial===i.serial?this.setMatrixFromParticle(i.matrix,n):i.particle=void 0),e.emit(t,i,i.matrix)}else this.clearEmissions()}toJSON(){return{type:this.type,subParticleSystem:"string"==typeof this.subParticleSystem?this.subParticleSystem:this.subParticleSystem?this.subParticleSystem.uuid:"",useVelocityAsBasis:this.useVelocityAsBasis,mode:this.mode,emitProbability:this.emitProbability,...this.inherit.length>0?{inherit:this.inherit.slice()}:{}}}static fromJSON(t,e){return new ts(e,Boolean(t.useVelocityAsBasis),t.subParticleSystem,t.mode,t.emitProbability,ts.validInherit(t.inherit))}clone(){return new ts(this.particleSystem,this.useVelocityAsBasis,this.subParticleSystem,this.mode,this.emitProbability,this.inherit.slice())}reset(){this.clearEmissions()}clearEmissions(){for(const t of this.subEmissions)t.particle=void 0,this.spareEmissions.push(t);this.subEmissions.length=0}static copyInto(t,e){return t.position.copy(e.position),t.velocity.copy(e.velocity),t.color.copy(e.color),t.size.copy(e.size),t.rotation=e.rotation??0,t.age=e.age,t.life=e.life,t}static validInherit(t){return Array.isArray(t)?t.filter(t=>t in Ze):[]}setMatrixFromParticle(t,e){let s;if(void 0===e.rotation||this.useVelocityAsBasis){const s=e.position,i=this.v3_.copy(e.velocity),n=i.length(),r=this.v_,o=this.v2_;if(n<Ye)r.set(1,0,0),o.set(0,1,0),i.set(0,0,1);else if(i.divideScalar(n),Math.abs(i.x)<Ye&&Math.abs(i.y)<Ye){const t=i.z>0?1:-1;r.set(1,0,0),o.set(0,t,0),i.set(0,0,t)}else r.copy(He).cross(i).normalize(),o.copy(i).cross(r);t.set(r.x,o.x,i.x,s.x,r.y,o.y,i.y,s.y,r.z,o.z,i.z,s.z,0,0,0,1)}else e.rotation instanceof et?s=e.rotation:(this.q_.setFromAxisAngle(He,e.rotation),s=this.q_),t.compose(e.position,s,Qe);this.particleSystem.worldSpace||t.multiplyMatrices(this.particleSystem.emitter.matrixWorld,t)}}class es{initialize(t,e){this.ps=e,this.x.startGen(t.memory),this.y.startGen(t.memory),this.z.startGen(t.memory)}constructor(t,e,s,i="world"){this.x=t,this.y=e,this.z=s,this.space=i,this.type="ForceOverLife",this._temp=new st,this._frame=new Te}_step(t){const e=this.ps;return(void 0===e||e.worldSpace)&&"world"===this.space?t*(e?.motionScale??1):t}update(t,e){const s=t.age/t.life;this._temp.set(this.x.genValue(t.memory,s),this.y.genValue(t.memory,s),this.z.genValue(t.memory,s));const i=void 0===this.ps||this.ps.worldSpace;this._frame.toSimulation(this._temp,this.space,i),t.velocity.addScaledVector(this._temp,this._step(e))}updateAll(t,e,s){const i=this._temp,n=this.x,r=this.y,o=this.z,a=this._frame,h=this.space,l=void 0===this.ps||this.ps.worldSpace,c=l!==("world"===h),u=this._step(s);for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const d=e.memory,f=e.age/e.life;i.set(n.genValue(d,f),r.genValue(d,f),o.genValue(d,f)),c&&a.toSimulation(i,h,l),e.velocity.addScaledVector(i,u)}}toJSON(){return{type:this.type,x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON(),..."world"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new es(ne(t.x),ne(t.y),ne(t.z),Pe(t.space,"world"))}frameUpdate(t){void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)&&this._frame.refresh(this.ps)}clone(){return new es(this.x.clone(),this.y.clone(),this.z.clone(),this.space)}reset(){}}class ss{constructor(t,e={}){this.type="FrameOverLife",this.salt=new Zt(0,1),this.frame=t,this.fps=e.fps??0,this.cycles=e.cycles??1,this.frameCount=e.frameCount??0,this.loop=e.loop??!0,this.random=e.random??!1,this.startFrame=e.startFrame}get frame(){return this._frame}set frame(t){this._frame=t}isPlain(){return!(this.fps>0)&&1===this.cycles&&void 0===this.startFrame}initialize(t){this._frame.startGen(t.memory),this.startFrame?.startGen(t.memory),this.salt.startGen(t.memory)}update(t,e){t.uvTile=this.frameAt(t,t.age,t.age/t.life)}updateAll(t,e,s){for(let s=0;s<e;s++){const e=t[s];e.age>=e.life||(e.uvTile=this.frameAt(e,e.age,e.age/e.life))}}frameAt(t,e,s){if(this.fps>0){const i=this.sampleFrame(t,s),n=this.frameCount;let r=Math.floor(e*this.fps)+this.offset(t);return this.random&&n>0?i+Math.floor(ss.hash(r,this.saltOf(t))*n):(n>0&&(r=this.loop?ss.wrap(r,n):Math.min(r,n-1)),i+r)}let i;if(1!==this.cycles&&this.cycles>0){const e=s*this.cycles;i=this.sampleFrame(t,s>=1?1:e-Math.floor(e))}else i=this.sampleFrame(t,s);return void 0!==this.startFrame&&(i+=this.offset(t),this.frameCount>0&&(i=ss.wrap(i,this.frameCount))),i}offset(t){return void 0!==this.startFrame?Math.floor(this.startFrame.genValue(t.memory)):0}saltOf(t){const e=t.memory[this.salt.indexCount];return"number"==typeof e?e:0}static hash(t,e){const s=43758.5453*Math.sin(12.9898*t+7833.233*e);return Math.min(s-Math.floor(s),.999999)}static wrap(t,e){return(t%e+e)%e}sampleFrame(t,e){return"function"===this._frame.type?this._frame.genValue(t.memory,e):this._frame.genValue(t.memory)}frameUpdate(t){this._frame.refreshTable?.()}toJSON(){return{type:this.type,frame:this.frame.toJSON(),...this.fps>0?{fps:this.fps}:{},...1!==this.cycles?{cycles:this.cycles}:{},...this.frameCount>0?{frameCount:this.frameCount}:{},...this.loop?{}:{loop:!1},...this.random?{random:!0}:{},...void 0!==this.startFrame?{startFrame:this.startFrame.toJSON()}:{}}}static fromJSON(t){return new ss(ne(t.frame),{fps:"number"==typeof t.fps?t.fps:void 0,cycles:"number"==typeof t.cycles?t.cycles:void 0,frameCount:"number"==typeof t.frameCount?t.frameCount:void 0,loop:"boolean"==typeof t.loop?t.loop:void 0,random:!0===t.random,startFrame:void 0!==t.startFrame?ne(t.startFrame):void 0})}clone(){return new ss(this.frame.clone(),{fps:this.fps,cycles:this.cycles,frameCount:this.frameCount,loop:this.loop,random:this.random,startFrame:this.startFrame?.clone()})}reset(){}}class is{constructor(t,e){this.center=t,this.magnitude=e,this.type="GravityForce",this.temp=new st}initialize(t){}update(t,e){const s=t.position.distanceToSquared(this.center);0!==s&&(this.temp.copy(this.center).sub(t.position).normalize(),t.velocity.addScaledVector(this.temp,this.magnitude/s*e))}updateAll(t,e,s){const i=this.center.x,n=this.center.y,r=this.center.z,o=this.magnitude*s;for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const a=e.position,h=i-a.x,l=n-a.y,c=r-a.z,u=h*h+l*l+c*c;if(0===u)continue;const d=o/(u*Math.sqrt(u)),f=e.velocity;f.x+=h*d,f.y+=l*d,f.z+=c*d}}frameUpdate(t){}toJSON(){return{type:this.type,center:[this.center.x,this.center.y,this.center.z],magnitude:this.magnitude}}static fromJSON(t){return new is(jt(t.center,new st(0,0,0)),"number"==typeof t.magnitude?t.magnitude:0)}clone(){return new is(this.center.clone(),this.magnitude)}reset(){}}class ns{constructor(t=new Xt(1),e="initial"){this.multiplier=t,this.mode=e,this.type="InheritVelocity",this._temp=new st,this._tempPos=new st,this._tempQInv=new et,this._tempScaleInv=new st(1,1,1)}initialize(t,e){this.ps=e,this.multiplier.startGen(t.memory),"initial"===this.mode&&e.emitterVelocity&&(this._temp.copy(e.emitterVelocity),e.worldSpace||(this.decomposeInverse(e),this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv)),t.velocity.addScaledVector(this._temp,this.multiplier.genValue(t.memory,0)))}frameUpdate(t){this.ps&&!this.ps.worldSpace&&this.decomposeInverse(this.ps)}update(t,e){"current"===this.mode&&void 0!==this.ps&&this.ps.emitterVelocity&&(this._temp.copy(this.ps.emitterVelocity),this.ps.worldSpace||this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv),t.position.addScaledVector(this._temp,this.multiplier.genValue(t.memory,t.age/t.life)*e))}decomposeInverse(t){t.emitter.matrixWorld.decompose(this._tempPos,this._tempQInv,this._tempScaleInv),this._tempQInv.invert(),this._tempScaleInv.set(1/this._tempScaleInv.x,1/this._tempScaleInv.y,1/this._tempScaleInv.z)}toJSON(){return{type:this.type,multiplier:this.multiplier.toJSON(),mode:this.mode}}static fromJSON(t){return new ns(t.multiplier?ne(t.multiplier):new Xt(1),"current"===t.mode?"current":"initial")}clone(){return new ns(this.multiplier.clone(),this.mode)}reset(){}}class rs{initialize(t,e){void 0!==e&&(this.ps=e),this.speed.startGen(t.memory)}motionScale(){const t=this.ps;return void 0!==t&&t.worldSpace?t.motionScale??1:1}constructor(t,e,s="local"){this.speed=t,this.dampen=e,this.space=s,this.type="LimitSpeedOverLife",this._frame=new Te,this._limit=new st,this._velocity=new st}_convertsSpace(){const t=void 0===this.ps||this.ps.worldSpace;return this.speed instanceof xe&&t!==("world"===this.space)}_limitAxes(t,e,s,i,n){const r=this.speed.genValue(t.memory,this._limit,e),o=this._velocity.copy(t.velocity),a=void 0===this.ps||this.ps.worldSpace;n&&this._frame.fromSimulation(o,this.space,a);const h="world"===this.space?i:1,l=os(o.x,r.x*h),c=os(o.y,r.y*h),u=os(o.z,r.z*h);0===l&&0===c&&0===u||(o.set(-l*s,-c*s,-u*s),n&&this._frame.toSimulation(o,this.space,a),t.velocity.add(o))}dampenStep(t){const e=this.dampen>1?1:this.dampen>0?this.dampen:0;return 1-Math.pow(1-e/3,60*t)}update(t,e){if(this.speed instanceof xe){const s=t.age/t.life;return void this._limitAxes(t,s,this.dampenStep(e),this.motionScale(),this._convertsSpace())}const s=t.velocity.length(),i=this.speed.genValue(t.memory,t.age/t.life)*this.motionScale();if(s>i){const n=(s-i)/s;t.velocity.multiplyScalar(1-n*this.dampenStep(e))}}updateAll(t,e,s){const i=this.speed,n=this.dampenStep(s),r=this.motionScale();if(i instanceof xe){const s=this._convertsSpace();for(let i=0;i<e;i++){const e=t[i];e.age<e.life&&this._limitAxes(e,e.age/e.life,n,r,s)}return}for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const o=e.velocity,a=o.length(),h=i.genValue(e.memory,e.age/e.life)*r;a>h&&o.multiplyScalar(1-(a-h)/a*n)}}toJSON(){return{type:this.type,speed:this.speed.toJSON(),dampen:this.dampen,..."local"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new rs("Vector3Function"===t.speed?.type?xe.fromJSON(t.speed):ne(t.speed),"number"==typeof t.dampen?t.dampen:1,Pe(t.space,"local"))}frameUpdate(t){const e=this.speed;e instanceof xe?(e.x.refreshTable?.(),e.y.refreshTable?.(),e.z.refreshTable?.(),void 0!==this.ps&&this._convertsSpace()&&this._frame.refresh(this.ps)):e.refreshTable?.()}clone(){return new rs(this.speed.clone(),this.dampen,this.space)}reset(){}}function os(t,e){const s=e>0?e:0;return t>s?t-s:t<-s?t+s:0}const as=.5*(Math.sqrt(3)-1),hs=(3-Math.sqrt(3))/6,ls=1/3,cs=1/6,us=(Math.sqrt(5)-1)/4,ds=(5-Math.sqrt(5))/20,fs=new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),ps=new Float32Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);class ms{constructor(t=e){const e="function"==typeof t?t:function(t){let e=0,s=0,i=0,n=1;const r=function(){let t=4022871197;return function(e){e=e.toString();for(let s=0;s<e.length;s++){t+=e.charCodeAt(s);let i=.02519603282416938*t;t=i>>>0,i-=t,i*=t,t=i>>>0,i-=t,t+=4294967296*i}return 2.3283064365386963e-10*(t>>>0)}}();e=r(" "),s=r(" "),i=r(" "),e-=r(t),e<0&&(e+=1);s-=r(t),s<0&&(s+=1);i-=r(t),i<0&&(i+=1);return function(){const t=2091639*e+2.3283064365386963e-10*n;return e=s,s=i,i=t-(n=0|t)}}(t);this.p=function(t){const e=new Uint8Array(256);for(let t=0;t<256;t++)e[t]=t;for(let s=0;s<255;s++){const i=s+~~(t()*(256-s)),n=e[s];e[s]=e[i],e[i]=n}return e}(e),this.perm=new Uint8Array(512),this.permMod12=new Uint8Array(512);for(let t=0;t<512;t++)this.perm[t]=this.p[255&t],this.permMod12[t]=this.perm[t]%12}noise2D(t,e){const s=this.permMod12,i=this.perm;let n=0,r=0,o=0;const a=(t+e)*as,h=Math.floor(t+a),l=Math.floor(e+a),c=(h+l)*hs,u=t-(h-c),d=e-(l-c);let f,p;u>d?(f=1,p=0):(f=0,p=1);const m=u-f+hs,y=d-p+hs,g=u-1+2*hs,v=d-1+2*hs,x=255&h,S=255&l;let b=.5-u*u-d*d;if(b>=0){const t=3*s[x+i[S]];b*=b,n=b*b*(fs[t]*u+fs[t+1]*d)}let w=.5-m*m-y*y;if(w>=0){const t=3*s[x+f+i[S+p]];w*=w,r=w*w*(fs[t]*m+fs[t+1]*y)}let M=.5-g*g-v*v;if(M>=0){const t=3*s[x+1+i[S+1]];M*=M,o=M*M*(fs[t]*g+fs[t+1]*v)}return 70*(n+r+o)}noise3D(t,e,s){const i=this.permMod12,n=this.perm;let r,o,a,h;const l=(t+e+s)*ls,c=Math.floor(t+l),u=Math.floor(e+l),d=Math.floor(s+l),f=(c+u+d)*cs,p=t-(c-f),m=e-(u-f),y=s-(d-f);let g,v,x,S,b,w;p>=m?m>=y?(g=1,v=0,x=0,S=1,b=1,w=0):p>=y?(g=1,v=0,x=0,S=1,b=0,w=1):(g=0,v=0,x=1,S=1,b=0,w=1):m<y?(g=0,v=0,x=1,S=0,b=1,w=1):p<y?(g=0,v=1,x=0,S=0,b=1,w=1):(g=0,v=1,x=0,S=1,b=1,w=0);const M=p-g+cs,z=m-v+cs,_=y-x+cs,A=p-S+2*cs,P=m-b+2*cs,O=y-w+2*cs,T=p-1+.5,V=m-1+.5,E=y-1+.5,C=255&c,$=255&u,I=255&d;let N=.6-p*p-m*m-y*y;if(N<0)r=0;else{const t=3*i[C+n[$+n[I]]];N*=N,r=N*N*(fs[t]*p+fs[t+1]*m+fs[t+2]*y)}let F=.6-M*M-z*z-_*_;if(F<0)o=0;else{const t=3*i[C+g+n[$+v+n[I+x]]];F*=F,o=F*F*(fs[t]*M+fs[t+1]*z+fs[t+2]*_)}let R=.6-A*A-P*P-O*O;if(R<0)a=0;else{const t=3*i[C+S+n[$+b+n[I+w]]];R*=R,a=R*R*(fs[t]*A+fs[t+1]*P+fs[t+2]*O)}let B=.6-T*T-V*V-E*E;if(B<0)h=0;else{const t=3*i[C+1+n[$+1+n[I+1]]];B*=B,h=B*B*(fs[t]*T+fs[t+1]*V+fs[t+2]*E)}return 32*(r+o+a+h)}noise4D(t,e,s,i){const n=this.perm;let r,o,a,h,l;const c=(t+e+s+i)*us,u=Math.floor(t+c),d=Math.floor(e+c),f=Math.floor(s+c),p=Math.floor(i+c),m=(u+d+f+p)*ds,y=t-(u-m),g=e-(d-m),v=s-(f-m),x=i-(p-m);let S=0,b=0,w=0,M=0;y>g?S++:b++,y>v?S++:w++,y>x?S++:M++,g>v?b++:w++,g>x?b++:M++,v>x?w++:M++;const z=S>=3?1:0,_=b>=3?1:0,A=w>=3?1:0,P=M>=3?1:0,O=S>=2?1:0,T=b>=2?1:0,V=w>=2?1:0,E=M>=2?1:0,C=S>=1?1:0,$=b>=1?1:0,I=w>=1?1:0,N=M>=1?1:0,F=y-z+ds,R=g-_+ds,B=v-A+ds,U=x-P+ds,L=y-O+2*ds,D=g-T+2*ds,k=v-V+2*ds,q=x-E+2*ds,G=y-C+3*ds,J=g-$+3*ds,W=v-I+3*ds,j=x-N+3*ds,Q=y-1+4*ds,H=g-1+4*ds,Y=v-1+4*ds,X=x-1+4*ds,Z=255&u,K=255&d,tt=255&f,et=255&p;let st=.6-y*y-g*g-v*v-x*x;if(st<0)r=0;else{const t=n[Z+n[K+n[tt+n[et]]]]%32*4;st*=st,r=st*st*(ps[t]*y+ps[t+1]*g+ps[t+2]*v+ps[t+3]*x)}let it=.6-F*F-R*R-B*B-U*U;if(it<0)o=0;else{const t=n[Z+z+n[K+_+n[tt+A+n[et+P]]]]%32*4;it*=it,o=it*it*(ps[t]*F+ps[t+1]*R+ps[t+2]*B+ps[t+3]*U)}let nt=.6-L*L-D*D-k*k-q*q;if(nt<0)a=0;else{const t=n[Z+O+n[K+T+n[tt+V+n[et+E]]]]%32*4;nt*=nt,a=nt*nt*(ps[t]*L+ps[t+1]*D+ps[t+2]*k+ps[t+3]*q)}let rt=.6-G*G-J*J-W*W-j*j;if(rt<0)h=0;else{const t=n[Z+C+n[K+$+n[tt+I+n[et+N]]]]%32*4;rt*=rt,h=rt*rt*(ps[t]*G+ps[t+1]*J+ps[t+2]*W+ps[t+3]*j)}let ot=.6-Q*Q-H*H-Y*Y-X*X;if(ot<0)l=0;else{const t=n[Z+1+n[K+1+n[tt+1+n[et+1]]]]%32*4;ot*=ot,l=ot*ot*(ps[t]*Q+ps[t+1]*H+ps[t+2]*Y+ps[t+3]*X)}return 27*(r+o+a+h+l)}}const ys=100,gs=new Array(ys),vs=new st,xs=new et;function Ss(t){let e=gs[t];return void 0===e&&(e=new ms(t),gs[t]=e),e}class bs{constructor(t,e,s=new Xt(1),i=new Xt(0),n=new Xt(0),r){this.frequency=t,this.power=e,this.positionAmount=s,this.rotationAmount=i,this.scrollSpeed=n,this.remap=r,this.type="Noise",this.duration=0,this.scrollOffset=0,this.scrollMemory=[],this._frequency=NaN,this._power=NaN,this._positionAmount=NaN,this._rotationAmount=NaN,this.scrollSpeed.startGen(this.scrollMemory)}sample(t,e,s){const i=t.noise2D(0,e),n=this.remap;return void 0===n?i:n.genValue(s,.5*(i+1))}initialize(t){const e=t.memory;this.frequency.startGen(e),this.power.startGen(e),this.positionAmount.startGen(e),this.rotationAmount.startGen(e),this.remap?.startGen(e);const s="number"==typeof t.rotation;let i=t._noiseState;if(void 0===i)return i={lastPos:new st,lastRot:0,lastRotQ:s?null:new et,generatorX:Ss(Ge(0,ys)),generatorY:Ss(Ge(0,ys)),generatorZ:Ss(Ge(0,ys)),generatorW:Ss(Ge(0,ys))},void(t._noiseState=i);i.lastPos.set(0,0,0),i.lastRot=0,s?i.lastRotQ=null:null===i.lastRotQ?i.lastRotQ=new et:i.lastRotQ.set(0,0,0,1),i.generatorX=Ss(Ge(0,ys)),i.generatorY=Ss(Ge(0,ys)),i.generatorZ=Ss(Ge(0,ys)),i.generatorW=Ss(Ge(0,ys))}static constantOf(t){return t instanceof Xt?t.value:NaN}rotateByNoise(t,e,s,i,n){const r=e.lastRotQ;t.multiply(r.invert()),vs.set(this.sample(e.generatorX,s,n),this.sample(e.generatorY,s,n),this.sample(e.generatorZ,s,n));const o=vs.length();o>0?(vs.multiplyScalar(1/o),xs.setFromAxisAngle(vs,this.sample(e.generatorW,s,n)*Math.PI*i)):xs.set(0,0,0,1),t.multiply(xs),r.copy(xs)}update(t,e){const s=t._noiseState;if(void 0===s)return;const i=t.memory,n=t.age/t.life,r=this._frequency,o=r==r?r:this.frequency.genValue(i,n),a=this._power,h=a==a?a:this.power.genValue(i,n),l=this._positionAmount,c=l==l?l:this.positionAmount.genValue(i,n),u=this._rotationAmount,d=u==u?u:this.rotationAmount.genValue(i,n),f=t.age*o+this.scrollOffset;if(c>0){const e=h*c;t.position.sub(s.lastPos),vs.set(this.sample(s.generatorX,f,i)*e,this.sample(s.generatorY,f,i)*e,this.sample(s.generatorZ,f,i)*e),t.position.add(vs),s.lastPos.copy(vs)}if(d>0){const e=h*d;if("number"==typeof t.rotation){const n=this.sample(s.generatorW,f,i)*Math.PI*e;t.rotation=t.rotation-s.lastRot+n,s.lastRot=n}else null!==s.lastRotQ&&this.rotateByNoise(t.rotation,s,f,e,i)}}updateAll(t,e,s){const i=e>0?t[0].store:void 0;if(void 0===i){for(let i=0;i<e;i++){const e=t[i];e.age<e.life&&this.update(e,s)}return}const n=i.position,r=i.rotation,o=i.scalars,a=Be.SCALAR_STRIDE,h=this._frequency,l=this._power,c=this._positionAmount,u=this._rotationAmount;for(let s=0,i=0,d=0;s<e;s++,i+=3,d+=a){const e=o[d],a=o[d+1];if(e>=a)continue;const f=t[s],p=f._noiseState;if(void 0===p)continue;const m=f.memory,y=e/a,g=h==h?h:this.frequency.genValue(m,y),v=l==l?l:this.power.genValue(m,y),x=c==c?c:this.positionAmount.genValue(m,y),S=u==u?u:this.rotationAmount.genValue(m,y),b=e*g+this.scrollOffset;if(x>0){const t=v*x,e=p.lastPos,s=this.sample(p.generatorX,b,m)*t,r=this.sample(p.generatorY,b,m)*t,o=this.sample(p.generatorZ,b,m)*t;n[i]=Math.fround(n[i]-e.x)+s,n[i+1]=Math.fround(n[i+1]-e.y)+r,n[i+2]=Math.fround(n[i+2]-e.z)+o,e.set(s,r,o)}if(S>0){const t=v*S;if("number"==typeof f.rotation){const e=this.sample(p.generatorW,b,m)*Math.PI*t;r[s]=r[s]-p.lastRot+e,p.lastRot=e}else null!==p.lastRotQ&&this.rotateByNoise(f.rotation,p,b,t,m)}}}toJSON(){return{type:this.type,frequency:this.frequency.toJSON(),power:this.power.toJSON(),positionAmount:this.positionAmount.toJSON(),rotationAmount:this.rotationAmount.toJSON(),scrollSpeed:this.scrollSpeed.toJSON(),...void 0!==this.remap?{remap:this.remap.toJSON()}:{}}}frameUpdate(t){this.duration+=t,this.scrollOffset+=this.scrollSpeed.genValue(this.scrollMemory,0)*t,this._frequency=bs.constantOf(this.frequency),this._power=bs.constantOf(this.power),this._positionAmount=bs.constantOf(this.positionAmount),this._rotationAmount=bs.constantOf(this.rotationAmount)}static fromJSON(t){return new bs(ne(t.frequency),ne(t.power),t.positionAmount?ne(t.positionAmount):void 0,t.rotationAmount?ne(t.rotationAmount):void 0,t.scrollSpeed?ne(t.scrollSpeed):new Xt(0),t.remap?ne(t.remap):void 0)}clone(){return new bs(this.frequency.clone(),this.power.clone(),this.positionAmount.clone(),this.rotationAmount.clone(),this.scrollSpeed.clone(),this.remap?.clone())}reset(){this.scrollOffset=0}}class ws{constructor(t,e=new st(0,1,0),s="local"){this.orbitSpeed=t,this.axis=e,this.space=s,this.type="OrbitOverLife",this.temp=new st,this._frame=new Te,this._axis=new st(0,1,0),this._center=new st,this.rotation=new et,this.refreshAxis()}initialize(t,e){this.ps=e,this.orbitSpeed.startGen(t.memory)}refreshAxis(){const t=this._axis.copy(this.axis),e=this._center.set(0,0,0);if(void 0!==this.ps){const s=this.ps.worldSpace;this._frame.toSimulation(t,this.space,s),this._frame.pointToSimulation(e,this.space,s)}const s=t.length();s>0?t.multiplyScalar(1/s):t.set(0,0,0)}converts(){return void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)}update(t,e){const s=this._axis;if(0===s.x&&0===s.y&&0===s.z)return;const i=t.position;i.sub(this._center),this.temp.copy(i).projectOnVector(s),this.rotation.setFromAxisAngle(s,this.orbitSpeed.genValue(t.memory,t.age/t.life)*e),i.sub(this.temp),i.applyQuaternion(this.rotation),i.add(this.temp),i.add(this._center)}updateAll(t,e,s){const i=this._axis;if(0===i.x&&0===i.y&&0===i.z)return;const n=this.orbitSpeed,r=this._center,o=this.temp,a=this.rotation;for(let h=0;h<e;h++){const e=t[h];if(e.age>=e.life)continue;const l=e.position;l.sub(r),o.copy(l).projectOnVector(i),a.setFromAxisAngle(i,n.genValue(e.memory,e.age/e.life)*s),l.sub(o),l.applyQuaternion(a),l.add(o),l.add(r)}}frameUpdate(t){this.converts()&&this._frame.refresh(this.ps),this.refreshAxis()}toJSON(){return{type:this.type,orbitSpeed:this.orbitSpeed.toJSON(),axis:[this.axis.x,this.axis.y,this.axis.z],..."local"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new ws(ne(t.orbitSpeed),t.axis?new st(t.axis[0],t.axis[1],t.axis[2]):void 0,Pe(t.space,"local"))}clone(){return new ws(this.orbitSpeed.clone(),this.axis.clone(),this.space)}reset(){}}const Ms=new et;class zs{constructor(t){this.angularVelocity=t,this.type="Rotation3DOverLife",this.tempQuat=new et}initialize(t){t.rotation instanceof et&&(t.angularVelocity=t instanceof De?Ms:new et,this.angularVelocity.startGen(t.memory))}update(t,e){if(t.rotation instanceof et){this.angularVelocity.genValue(t.memory,this.tempQuat,e,t.age/t.life),t.rotation.multiply(this.tempQuat);const s=t.angularVelocity;s instanceof et&&s.copy(this.tempQuat)}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new zs(ve(t.angularVelocity))}frameUpdate(t){}clone(){return new zs(this.angularVelocity.clone())}reset(){}}class _s{constructor(t,e){this.angularVelocity=t,this.speedRange=e,this.type="RotationBySpeed",this.tempQuat=new et}initialize(t){"number"==typeof t.rotation&&this.angularVelocity.startGen(t.memory)}update(t,e){if("number"==typeof t.rotation){const s=Ne(t,this.speedRange),i=this.angularVelocity.genValue(t.memory,s);t.rotation+=e*i,t.angularVelocity=i}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new _s(ne(t.angularVelocity),t.speedRange?Zt.fromJSON(t.speedRange):new Zt(0,1))}frameUpdate(t){}clone(){return new _s(this.angularVelocity.clone(),this.speedRange.clone())}reset(){}}class As{constructor(t){this.angularVelocity=t,this.type="RotationOverLife",this.tempQuat=new et}initialize(t){"number"==typeof t.rotation?this.angularVelocity.startGen(t.memory):t.rotation instanceof et&&(this.angularVelocity.startGen(t.memory),t.angularVelocity instanceof et||(t.angularVelocity=new et))}update(t,e){if("number"==typeof t.rotation){const s=this.angularVelocity.genValue(t.memory,t.age/t.life);t.rotation+=e*s,t.angularVelocity=s}else if(t.rotation instanceof et){const s=this.angularVelocity.genValue(t.memory,t.age/t.life);this.turnAboutZ(t,t.rotation,s*e)}}updateAll(t,e,s){const i=this.angularVelocity;for(let n=0;n<e;n++){const e=t[n];if(e.age>=e.life)continue;const r=e.rotation;if("number"==typeof r){const t=i.genValue(e.memory,e.age/e.life);e.rotation=r+s*t,e.angularVelocity=t}else if(r instanceof et){const t=i.genValue(e.memory,e.age/e.life);this.turnAboutZ(e,r,t*s)}}}turnAboutZ(t,e,s){const i=this.tempQuat.setFromAxisAngle(He,s);e.multiply(i);const n=t.angularVelocity;n instanceof et&&n.copy(i)}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new As(ne(t.angularVelocity))}frameUpdate(t){this.angularVelocity.refreshTable?.()}clone(){return new As(this.angularVelocity.clone())}reset(){}}class Ps{initialize(t){this.size.startGen(t.memory)}constructor(t,e){this.size=t,this.speedRange=e,this.type="SizeBySpeed"}update(t){const e=Ne(t,this.speedRange);this.size instanceof xe?this.size.genValue(t.memory,t.size,e).multiply(t.startSize):t.size.copy(t.startSize).multiplyScalar(this.size.genValue(t.memory,e))}toJSON(){return{type:this.type,size:this.size.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new Ps(be(t.size),t.speedRange?Zt.fromJSON(t.speedRange):new Zt(0,1))}frameUpdate(t){}clone(){return new Ps(this.size.clone(),this.speedRange.clone())}reset(){}}class Os{constructor(t){this.type="SizeOverLife",this._sizeIsVector3=!1,this.size=t}get size(){return this._size}set size(t){this._size=t,this._sizeIsVector3=t instanceof xe}initialize(t){this._size.startGen(t.memory)}update(t){const e=t.age/t.life;if(this._sizeIsVector3)this._size.genValue(t.memory,t.size,e).multiply(t.startSize);else{const s=this._size.genValue(t.memory,e),i=t.size,n=t.startSize;i.x=n.x*s,i.y=n.y*s,i.z=n.z*s}}updateAll(t,e,s){if(this._sizeIsVector3){const s=this._size;for(let i=0;i<e;i++){const e=t[i];e.age>=e.life||s.genValue(e.memory,e.size,e.age/e.life).multiply(e.startSize)}return}const i=this._size;for(let s=0;s<e;s++){const e=t[s];if(e.age>=e.life)continue;const n=i.genValue(e.memory,e.age/e.life),r=e.size,o=e.startSize;r.x=o.x*n,r.y=o.y*n,r.z=o.z*n}}toJSON(){return{type:this.type,size:this.size.toJSON()}}static fromJSON(t){return new Os(be(t.size))}frameUpdate(t){this._size.refreshTable?.()}clone(){return new Os(this.size.clone())}reset(){}}class Ts{initialize(t){this.speed.startGen(t.memory)}constructor(t){this.speed=t,this.type="SpeedOverLife"}update(t){t.speedModifier=this.speed.genValue(t.memory,t.age/t.life)}updateAll(t,e,s){const i=this.speed;for(let s=0;s<e;s++){const e=t[s];e.age>=e.life||(e.speedModifier=i.genValue(e.memory,e.age/e.life))}}toJSON(){return{type:this.type,speed:this.speed.toJSON()}}static fromJSON(t){return new Ts(ne(t.speed))}frameUpdate(t){this.speed.refreshTable?.()}clone(){return new Ts(this.speed.clone())}reset(){}}function Vs(t){return 0===t?0:1/t}class Es{constructor(t,e,s,i,n=0){this.scale=t,this.octaves=e,this.velocityMultiplier=s,this.timeScale=i,this.seed=n,this.type="TurbulenceField",this.timeOffset=new st,this.initialOffset=new st,this.temp=new st,this.temp2=new st;const r=P(n);this.generator=new ms(r),this.initialOffset.set(r()*Vs(t.x)*i.x,r()*Vs(t.y)*i.y,r()*Vs(t.z)*i.z),this.timeOffset.copy(this.initialOffset)}initialize(t){}update(t,e){const s=t.position.x*Vs(this.scale.x),i=t.position.y*Vs(this.scale.y),n=t.position.z*Vs(this.scale.z);this.temp.set(0,0,0);let r=1;for(let t=0;t<this.octaves;t++)this.temp2.set(this.generator.noise4D(s*r,i*r,n*r,this.timeOffset.x*r)/r,this.generator.noise4D(s*r,i*r,n*r,this.timeOffset.y*r)/r,this.generator.noise4D(s*r,i*r,n*r,this.timeOffset.z*r)/r),this.temp.add(this.temp2),r*=2;this.temp.multiply(this.velocityMultiplier),t.velocity.addScaledVector(this.temp,e)}updateAll(t,e,s){const i=e>0?t[0].store:void 0;if(void 0===i){for(let i=0;i<e;i++){const e=t[i];e.age<e.life&&this.update(e,s)}return}const n=i.position,r=i.velocity,o=i.scalars,a=Be.SCALAR_STRIDE,h=this.generator,l=this.octaves,c=Vs(this.scale.x),u=Vs(this.scale.y),d=Vs(this.scale.z),f=this.velocityMultiplier.x*s,p=this.velocityMultiplier.y*s,m=this.velocityMultiplier.z*s,y=this.timeOffset.x,g=this.timeOffset.y,v=this.timeOffset.z;for(let t=0,s=0,i=0;t<e;t++,s+=3,i+=a){if(o[i]>=o[i+1])continue;const t=n[s]*c,e=n[s+1]*u,a=n[s+2]*d;let x=0,S=0,b=0,w=1;for(let s=0;s<l;s++){const s=t*w,i=e*w,n=a*w;x+=h.noise4D(s,i,n,y*w)/w,S+=h.noise4D(s,i,n,g*w)/w,b+=h.noise4D(s,i,n,v*w)/w,w*=2}r[s]+=x*f,r[s+1]+=S*p,r[s+2]+=b*m}}toJSON(){return{type:this.type,scale:[this.scale.x,this.scale.y,this.scale.z],octaves:this.octaves,velocityMultiplier:[this.velocityMultiplier.x,this.velocityMultiplier.y,this.velocityMultiplier.z],timeScale:[this.timeScale.x,this.timeScale.y,this.timeScale.z],...0!==this.seed?{seed:this.seed}:{}}}frameUpdate(t){this.timeOffset.x+=t*this.timeScale.x,this.timeOffset.y+=t*this.timeScale.y,this.timeOffset.z+=t*this.timeScale.z}static fromJSON(t){return new Es(jt(t.scale,new st(1,1,1)),"number"==typeof t.octaves?t.octaves:1,jt(t.velocityMultiplier,new st(1,1,1)),jt(t.timeScale,new st(1,1,1)),"number"==typeof t.seed?t.seed:0)}clone(){return new Es(this.scale.clone(),this.octaves,this.velocityMultiplier.clone(),this.timeScale.clone(),this.seed)}reset(){this.timeOffset.copy(this.initialOffset)}}const Cs=new st(1,0,0),$s=new st(0,1,0),Is=new st(0,0,1);class Ns{constructor(t=new Xt(0),e=new Xt(0),s=new Xt(0),i=new Xt(0),n=new Xt(0),r=new Xt(0),o="local",a=new Xt(0),h=new st){this.linearX=t,this.linearY=e,this.linearZ=s,this.orbitalX=i,this.orbitalY=n,this.orbitalZ=r,this.space=o,this.radial=a,this.orbitalOffset=h,this.type="VelocityOverLife",this._temp=new st,this._tempEmitterPos=new st,this._tempQ=new et,this._tempQInv=new et,this._tempScale=new st(1,1,1),this._tempScaleInv=new st(1,1,1),this._tempRot=new et,this._axisX=new st(1,0,0),this._axisY=new st(0,1,0),this._axisZ=new st(0,0,1),this._center=new st}initialize(t,e){this.ps=e,this.linearX.startGen(t.memory),this.linearY.startGen(t.memory),this.linearZ.startGen(t.memory),this.orbitalX.startGen(t.memory),this.orbitalY.startGen(t.memory),this.orbitalZ.startGen(t.memory),this.radial.startGen(t.memory)}frameUpdate(t){this.ps&&(this.ps.emitter.matrixWorld.decompose(this._tempEmitterPos,this._tempQ,this._tempScale),this._tempQInv.copy(this._tempQ).invert(),this._tempScaleInv.set(1/this._tempScale.x,1/this._tempScale.y,1/this._tempScale.z),this._axisX.copy(Cs),this._axisY.copy($s),this._axisZ.copy(Is),this._center.copy(this.orbitalOffset),this.ps.worldSpace&&(this._axisX.applyQuaternion(this._tempQ),this._axisY.applyQuaternion(this._tempQ),this._axisZ.applyQuaternion(this._tempQ),this._center.multiply(this._tempScale).applyQuaternion(this._tempQ).add(this._tempEmitterPos)))}update(t,e){const s=t.age/t.life;this._temp.set(this.linearX.genValue(t.memory,s),this.linearY.genValue(t.memory,s),this.linearZ.genValue(t.memory,s));const i=void 0!==this.ps&&this.ps.worldSpace;i&&"local"===this.space?this._temp.multiply(this._tempScale).applyQuaternion(this._tempQ):i||"world"!==this.space||this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv),t.position.addScaledVector(this._temp,e);const n=this.radial.genValue(t.memory,s);if(0!==n){this._temp.copy(t.position).sub(this._center);const s=this._temp.length();s>0&&t.position.addScaledVector(this._temp,n*e/s)}const r=this.orbitalX.genValue(t.memory,s)*e,o=this.orbitalY.genValue(t.memory,s)*e,a=this.orbitalZ.genValue(t.memory,s)*e;0===r&&0===o&&0===a||(t.position.sub(this._center),this.orbit(t.position,this._axisX,r),this.orbit(t.position,this._axisY,o),this.orbit(t.position,this._axisZ,a),t.position.add(this._center))}orbit(t,e,s){0!==s&&(this._tempRot.setFromAxisAngle(e,s),t.applyQuaternion(this._tempRot))}toJSON(){return{type:this.type,linearX:this.linearX.toJSON(),linearY:this.linearY.toJSON(),linearZ:this.linearZ.toJSON(),orbitalX:this.orbitalX.toJSON(),orbitalY:this.orbitalY.toJSON(),orbitalZ:this.orbitalZ.toJSON(),space:this.space,radial:this.radial.toJSON(),orbitalOffset:[this.orbitalOffset.x,this.orbitalOffset.y,this.orbitalOffset.z]}}static fromJSON(t){const e=t=>t?ne(t):new Xt(0);return new Ns(e(t.linearX),e(t.linearY),e(t.linearZ),e(t.orbitalX),e(t.orbitalY),e(t.orbitalZ),"world"===t.space?"world":"local",e(t.radial),Array.isArray(t.orbitalOffset)?new st(t.orbitalOffset[0]??0,t.orbitalOffset[1]??0,t.orbitalOffset[2]??0):new st)}clone(){return new Ns(this.linearX.clone(),this.linearY.clone(),this.linearZ.clone(),this.orbitalX.clone(),this.orbitalY.clone(),this.orbitalZ.clone(),this.space,this.radial.clone(),this.orbitalOffset.clone())}reset(){}}class Fs{initialize(t){this.width.startGen(t.memory)}constructor(t,e=!1){this.width=t,this.absolute=e,this.type="WidthOverLength"}update(t){if(!(t instanceof qe))return;const e=t.memory;t.headWidthScale=this.absolute?1:this.width.genValue(e,0);const s=t.historyCount;if(0===s)return;const i=t.historyCapacity,n=t.historySizes,r=t.historyBaseSizes,o=1/s,a=this.absolute;let h=t.getHistoryIndex(0);for(let t=0;t<s;t++){const l=this.width.genValue(e,(s-t)*o);n[h]=a?l:r[h]*l,h++,h===i&&(h=0)}}frameUpdate(t){}toJSON(){return{type:this.type,width:this.width.toJSON(),absolute:this.absolute}}static fromJSON(t){return new Fs(ne(t.width),t.absolute??!0)}clone(){return new Fs(this.width.clone(),this.absolute)}reset(){}}const Rs={ApplyForce:{type:"ApplyForce",constructor:Ve,params:[["direction",["vec3"]],["magnitude",["value"]],["space",["string"]]],loadJSON:Ve.fromJSON},Noise:{type:"Noise",constructor:bs,params:[["frequency",["value"]],["power",["value"]],["positionAmount",["value"]],["rotationAmount",["value"]],["scrollSpeed",["value"]],["remap",["valueFunc"]]],loadJSON:bs.fromJSON},TurbulenceField:{type:"TurbulenceField",constructor:Es,params:[["scale",["vec3"]],["octaves",["number"]],["velocityMultiplier",["vec3"]],["timeScale",["vec3"]],["seed",["number"]]],loadJSON:Es.fromJSON},GravityForce:{type:"GravityForce",constructor:is,params:[["center",["vec3"]],["magnitude",["number"]]],loadJSON:is.fromJSON},ColorOverLife:{type:"ColorOverLife",constructor:Re,params:[["color",["colorFunc"]]],loadJSON:Re.fromJSON},RotationOverLife:{type:"RotationOverLife",constructor:As,params:[["angularVelocity",["value","valueFunc"]]],loadJSON:As.fromJSON},Rotation3DOverLife:{type:"Rotation3DOverLife",constructor:zs,params:[["angularVelocity",["rotationFunc"]]],loadJSON:zs.fromJSON},SizeOverLife:{type:"SizeOverLife",constructor:Os,params:[["size",["value","valueFunc","vec3Func"]]],loadJSON:Os.fromJSON},ColorBySpeed:{type:"ColorBySpeed",constructor:Fe,params:[["color",["colorFunc"]],["speedRange",["range"]]],loadJSON:Fe.fromJSON},RotationBySpeed:{type:"RotationBySpeed",constructor:_s,params:[["angularVelocity",["value","valueFunc"]],["speedRange",["range"]]],loadJSON:_s.fromJSON},SizeBySpeed:{type:"SizeBySpeed",constructor:Ps,params:[["size",["value","valueFunc","vec3Func"]],["speedRange",["range"]]],loadJSON:Ps.fromJSON},SpeedOverLife:{type:"SpeedOverLife",constructor:Ts,params:[["speed",["value","valueFunc"]]],loadJSON:Ts.fromJSON},FrameOverLife:{type:"FrameOverLife",constructor:ss,params:[["frame",["value","valueFunc"]],["fps",["number"]],["cycles",["number"]],["frameCount",["number"]],["loop",["boolean"]],["random",["boolean"]],["startFrame",["value"]]],loadJSON:ss.fromJSON},ForceOverLife:{type:"ForceOverLife",constructor:es,params:[["x",["value","valueFunc"]],["y",["value","valueFunc"]],["z",["value","valueFunc"]],["space",["string"]]],loadJSON:es.fromJSON},VelocityOverLife:{type:"VelocityOverLife",constructor:Ns,params:[["linearX",["value","valueFunc"]],["linearY",["value","valueFunc"]],["linearZ",["value","valueFunc"]],["orbitalX",["value","valueFunc"]],["orbitalY",["value","valueFunc"]],["orbitalZ",["value","valueFunc"]],["space",["string"]],["radial",["value","valueFunc"]],["orbitalOffset",["vec3"]]],loadJSON:Ns.fromJSON},InheritVelocity:{type:"InheritVelocity",constructor:ns,params:[["multiplier",["value","valueFunc"]],["mode",["string"]]],loadJSON:ns.fromJSON},OrbitOverLife:{type:"OrbitOverLife",constructor:ws,params:[["orbitSpeed",["value","valueFunc"]],["axis",["vec3"]],["space",["string"]]],loadJSON:ws.fromJSON},WidthOverLength:{type:"WidthOverLength",constructor:Fs,params:[["width",["value","valueFunc"]],["absolute",["boolean"]]],loadJSON:Fs.fromJSON},ChangeEmitDirection:{type:"ChangeEmitDirection",constructor:Ie,params:[["angle",["value"]]],loadJSON:Ie.fromJSON},ApplySequences:{type:"ApplySequences",constructor:$e,params:[["delay",["number"]]],loadJSON:$e.fromJSON},EmitSubParticleSystem:{type:"EmitSubParticleSystem",constructor:ts,params:[["particleSystem",["self"]],["useVelocityAsBasis",["boolean"]],["subParticleSystem",["particleSystem"]],["mode",["number"]],["emitProbability",["number"]],["inherit",["subEmitterInherit"]]],loadJSON:ts.fromJSON},LimitSpeedOverLife:{type:"LimitSpeedOverLife",constructor:rs,params:[["speed",["value","valueFunc","vec3Func"]],["dampen",["number"]],["space",["string"]]],loadJSON:rs.fromJSON},ApplyCollision:{type:"ApplyCollision",constructor:Ct,params:[["bounce",["number"]]],loadJSON:Ct.fromJSON}};function Bs(t,e){const s=t?Rs[t.type]:void 0;return s?s.loadJSON(t,e):(Wt(`${Qt("behavior",t)}; it is skipped.`),null)}function Us(t,e){const s=t.toJSON(),i=Rs[s?.type];return i?Yt(s,t=>i.loadJSON(t,e).toJSON()):s}const Ls={PiecewiseBezier:ee,Vector3Function:xe,Quaternion:et,ConstantValue:Xt,Gradient:ce,Vector4View:Tt,AxisAngleGenerator:oe,IntervalValue:Zt,ColorRange:ae};function Ds(t,e){return`const ${t} = ${e};\n const ${t}_tbl = ${t} instanceof deps.PiecewiseBezier ? ${t}.sampledTable() : null;\n const ${t}_last = ${t}_tbl !== null ? ${t}_tbl.length - 1 : 0;\n const ${t}_const = ${t} instanceof deps.ConstantValue;\n const ${t}_cv = ${t}_const ? ${t}.value : 0;\n const ${t}_iv = ${t} instanceof deps.IntervalValue;\n const ${t}_slot = ${t}_iv ? ${t}.indexCount : -1;\n const ${t}_col = ${t}_slot >= 0 && ${t}_slot < ms;\n const ${t}_a = ${t}_iv ? ${t}.a : 0, ${t}_b = ${t}_iv ? ${t}.b : 0;`}function ks(t){return`const vx = vel[o3], vy = vel[o3 + 1], vz = vel[o3 + 2];\n const speed = Math.sqrt(vx * vx + vy * vy + vz * vz) * scalars[s + 2];\n let ts = span${t} === 0 ? (speed >= lo${t} ? 1 : 0) : (speed - lo${t}) / span${t};\n ts = ts < 0 ? 0 : ts > 1 ? 1 : ts;`}function qs(t,e,s){return`let ${e};\n if (${t}_tbl !== null) {\n const tt = ${s};\n if (tt <= 0) ${e} = ${t}_tbl[0];\n else if (tt >= 1) ${e} = ${t}_tbl[${t}_last];\n else {\n const x = tt * ${t}_last;\n const ix = x | 0;\n const v0 = ${t}_tbl[ix];\n ${e} = v0 + (${t}_tbl[ix + 1] - v0) * (x - ix);\n }\n } else if (${t}_const) ${e} = ${t}_cv;\n else if (${t}_iv) {\n // The particle's own sample, from the memory column when it holds it.\n let r = ${t}_col ? mem[row * ms + ${t}_slot] : NaN;\n if (r !== r) r = p.memory[${t}_slot];\n ${e} = (1 - r) * ${t}_a + r * ${t}_b;\n } else ${e} = ${t}.genValue(p.memory, ${s});`}function Gs(t,e){return`const ${t} = ${e};\n const ${t}_tbl = ${t} instanceof deps.Gradient ? ${t}.sampledTable() : null;\n const ${t}_last = ${t}_tbl !== null ? ${t}_tbl.length / 4 - 1 : 0;\n const ${t}_cr = ${t} instanceof deps.ColorRange;\n const ${t}_slot = ${t}_cr ? ${t}.indexCount : -1;\n const ${t}_col = ${t}_slot >= 0 && ${t}_slot < ms;\n // Rounded to float32 as copying the colour into the particle does.\n const ${t}_ax = ${t}_cr ? Math.fround(${t}.a.x) : 0, ${t}_ay = ${t}_cr ? Math.fround(${t}.a.y) : 0;\n const ${t}_az = ${t}_cr ? Math.fround(${t}.a.z) : 0, ${t}_aw = ${t}_cr ? Math.fround(${t}.a.w) : 0;\n const ${t}_bx = ${t}_cr ? ${t}.b.x : 0, ${t}_by = ${t}_cr ? ${t}.b.y : 0;\n const ${t}_bz = ${t}_cr ? ${t}.b.z : 0, ${t}_bw = ${t}_cr ? ${t}.b.w : 0;`}function Js(t,e){return`if (${t}_tbl !== null) {\n const tt = ${e};\n const tbl = ${t}_tbl;\n let r, g, b, a;\n if (tt <= 0) {\n r = tbl[0]; g = tbl[1]; b = tbl[2]; a = tbl[3];\n } else if (tt >= 1) {\n const o = ${t}_last * 4;\n r = tbl[o]; g = tbl[o + 1]; b = tbl[o + 2]; a = tbl[o + 3];\n } else {\n const x = tt * ${t}_last;\n const ix = x | 0;\n const fr = x - ix;\n const o = ix * 4;\n const nx = o + 4;\n r = tbl[o] + (tbl[nx] - tbl[o]) * fr;\n g = tbl[o + 1] + (tbl[nx + 1] - tbl[o + 1]) * fr;\n b = tbl[o + 2] + (tbl[nx + 2] - tbl[o + 2]) * fr;\n a = tbl[o + 3] + (tbl[nx + 3] - tbl[o + 3]) * fr;\n }\n color[o4] = Math.fround(r) * startColor[o4];\n color[o4 + 1] = Math.fround(g) * startColor[o4 + 1];\n color[o4 + 2] = Math.fround(b) * startColor[o4 + 2];\n color[o4 + 3] = Math.fround(a) * startColor[o4 + 3];\n } else if (${t}_cr) {\n let r = ${t}_col ? mem[row * ms + ${t}_slot] : NaN;\n if (r !== r) r = p.memory[${t}_slot];\n color[o4] = Math.fround(${t}_ax + (${t}_bx - ${t}_ax) * r) * startColor[o4];\n color[o4 + 1] = Math.fround(${t}_ay + (${t}_by - ${t}_ay) * r) * startColor[o4 + 1];\n color[o4 + 2] = Math.fround(${t}_az + (${t}_bz - ${t}_az) * r) * startColor[o4 + 2];\n color[o4 + 3] = Math.fround(${t}_aw + (${t}_bw - ${t}_aw) * r) * startColor[o4 + 3];\n } else {\n ${t}.genColor(p.memory, tmpColor, ${e});\n color[o4] = tmpColor.x * startColor[o4];\n color[o4 + 1] = tmpColor.y * startColor[o4 + 1];\n color[o4 + 2] = tmpColor.z * startColor[o4 + 2];\n color[o4 + 3] = tmpColor.w * startColor[o4 + 3];\n }`}function Ws(t,e,s,i,n,r,o){return`{\n const cx = 2 * (${n} * ${s} - ${r} * ${e});\n const cy = 2 * (${r} * ${t} - ${i} * ${s});\n const cz = 2 * (${i} * ${e} - ${n} * ${t});\n const nx = ${t} + ${o} * cx + ${n} * cz - ${r} * cy;\n const ny = ${e} + ${o} * cy + ${r} * cx - ${i} * cz;\n ${s} = ${s} + ${o} * cz + ${i} * cy - ${n} * cx;\n ${t} = nx;\n ${e} = ny;\n }`}function js(t,e){return`const ${t}_q = ${e};\n const ${t}x = ${t}_q.x, ${t}y = ${t}_q.y, ${t}z = ${t}_q.z, ${t}w = ${t}_q.w;`}function Qs(t,e){return`const ${t}_v = ${e};\n const ${t}x = ${t}_v.x, ${t}y = ${t}_v.y, ${t}z = ${t}_v.z;`}function Hs(t,e,s,i){return`{\n const half = ${t} / 2;\n const sn = Math.sin(half);\n const qx = ${e} * sn, qy = ${s} * sn, qz = ${i} * sn, qw = Math.cos(half);\n ${Ws("px","py","pz","qx","qy","qz","qw")}\n px = Math.fround(px); py = Math.fround(py); pz = Math.fround(pz);\n }`}function Ys(t,e){switch(t.type){case"ColorOverLife":return{setup:Gs(`g${e}`,`behaviors[${e}].color`),body:`{${Js(`g${e}`,"t")}}`};case"SizeOverLife":return{setup:`const g${e} = behaviors[${e}].size;\n const vec3_${e} = g${e} instanceof deps.Vector3Function;\n ${Ds(`sg${e}`,`g${e}`)}`,body:`if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, t).multiply(p.startSize);\n } else {\n ${qs(`sg${e}`,"v","t")}\n size[o3] = startSize[o3] * v;\n size[o3 + 1] = startSize[o3 + 1] * v;\n size[o3 + 2] = startSize[o3 + 2] * v;\n }`};case"ApplyForce":return{setup:`const b${e} = behaviors[${e}];\n const d${e} = b${e}._direction;\n const dx${e} = d${e}.x, dy${e} = d${e}.y, dz${e} = d${e}.z;\n const step${e} = b${e}._step(delta);\n ${Ds(`g${e}`,`b${e}.magnitude`)}`,body:`{\n ${qs(`g${e}`,"m","t")}\n const s = m * step${e};\n vel[o3] += dx${e} * s; vel[o3 + 1] += dy${e} * s; vel[o3 + 2] += dz${e} * s;\n }`};case"RotationOverLife":return{setup:`${Ds(`g${e}`,`behaviors[${e}].angularVelocity`)}\n const rotation_${e} = count > 0 ? particles[0].rotation : undefined;\n const angle_${e} = typeof rotation_${e} === 'number';\n const rq${e} = store.rotationQuaternion, aq${e} = store.angularVelocityQuaternion;\n const quat_${e} = !angle_${e} && rq${e}.length > 0 && rotation_${e} instanceof deps.Quaternion;`,body:`if (angle_${e}) {\n ${qs(`g${e}`,"rate","t")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n } else if (quat_${e}) {\n ${qs(`g${e}`,"rate","t")}\n const half = (rate * delta) / 2;\n const qz = Math.sin(half), qw = Math.cos(half);\n const ax = rq${e}[o4], ay = rq${e}[o4 + 1], az = rq${e}[o4 + 2], aw = rq${e}[o4 + 3];\n rq${e}[o4] = ax * qw + ay * qz;\n rq${e}[o4 + 1] = ay * qw - ax * qz;\n rq${e}[o4 + 2] = az * qw + aw * qz;\n rq${e}[o4 + 3] = aw * qw - az * qz;\n aq${e}[o4] = 0; aq${e}[o4 + 1] = 0; aq${e}[o4 + 2] = qz; aq${e}[o4 + 3] = qw;\n }`};case"FrameOverLife":return{setup:`${Ds(`g${e}`,`behaviors[${e}].frame`)}\n const b${e} = behaviors[${e}];\n const plain${e} = typeof b${e}.isPlain !== 'function' || b${e}.isPlain();`,body:`if (plain${e}) {${qs(`g${e}`,"v","t")} uvTile[row] = v;}\n else uvTile[row] = b${e}.frameAt(p, age, t);`};case"SpeedOverLife":return{setup:Ds(`g${e}`,`behaviors[${e}].speed`),body:`{${qs(`g${e}`,"v","t")} scalars[s + 2] = v;}`};case"ForceOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Ds(`gx${e}`,`b${e}.x`)}\n ${Ds(`gy${e}`,`b${e}.y`)}\n ${Ds(`gz${e}`,`b${e}.z`)}\n const world${e} = b${e}.ps === undefined || b${e}.ps.worldSpace;\n const toWorld${e} = world${e} && b${e}.space === 'local';\n const toLocal${e} = !world${e} && b${e}.space === 'world';\n const step${e} = b${e}._step(delta);\n const fr${e} = b${e}._frame;\n ${Qs(`sc${e}`,`toWorld${e} ? fr${e}.scale : fr${e}.scaleInverse`)}\n ${js(`q${e}`,`toWorld${e} ? fr${e}.quaternion : fr${e}.quaternionInverse`)}`,body:`{\n ${qs(`gx${e}`,"fx","t")}\n ${qs(`gy${e}`,"fy","t")}\n ${qs(`gz${e}`,"fz","t")}\n if (toWorld${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${Ws("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n } else if (toLocal${e}) {\n ${Ws("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n }\n vel[o3] += fx * step${e}; vel[o3 + 1] += fy * step${e}; vel[o3 + 2] += fz * step${e};}`};case"LimitSpeedOverLife":return{setup:`const b${e} = behaviors[${e}];\n const vec3_${e} = b${e}.speed instanceof deps.Vector3Function;\n ${Ds(`g${e}`,`b${e}.speed`)}\n const dampen${e} = b${e}.dampenStep(delta);\n const ms${e} = typeof b${e}.motionScale === 'function' ? b${e}.motionScale() : 1;\n const conv${e} = vec3_${e} && b${e}._convertsSpace();`,body:`if (vec3_${e}) b${e}._limitAxes(p, t, dampen${e}, ms${e}, conv${e});\n else {const vx = vel[o3], vy = vel[o3 + 1], vz = vel[o3 + 2];\n const speed = Math.sqrt(vx * vx + vy * vy + vz * vz);\n ${qs(`g${e}`,"limitBase","t")}\n const limit = limitBase * ms${e};\n if (speed > limit) {\n const f = 1 - ((speed - limit) / speed) * dampen${e};\n vel[o3] = vx * f; vel[o3 + 1] = vy * f; vel[o3 + 2] = vz * f;\n }}`};case"GravityForce":return{setup:`const b${e} = behaviors[${e}];\n const cx${e} = b${e}.center.x, cy${e} = b${e}.center.y, cz${e} = b${e}.center.z;\n const gm${e} = b${e}.magnitude * delta;`,body:`{const dx = cx${e} - pos[o3], dy = cy${e} - pos[o3 + 1], dz = cz${e} - pos[o3 + 2];\n const d2 = dx * dx + dy * dy + dz * dz;\n if (d2 > 0) {\n const f = gm${e} / (d2 * Math.sqrt(d2));\n vel[o3] += dx * f; vel[o3 + 1] += dy * f; vel[o3 + 2] += dz * f;\n }}`};case"ColorBySpeed":return{setup:`const b${e} = behaviors[${e}];\n ${Gs(`g${e}`,`b${e}.color`)}\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};`,body:`{${ks(e)}\n ${Js(`g${e}`,"ts")}}`};case"SizeBySpeed":return{setup:`const b${e} = behaviors[${e}];\n const g${e} = b${e}.size;\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};\n const vec3_${e} = g${e} instanceof deps.Vector3Function;\n ${Ds(`sg${e}`,`g${e}`)}`,body:`{${ks(e)}\n if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, ts).multiply(p.startSize);\n } else {\n ${qs(`sg${e}`,"v","ts")}\n size[o3] = startSize[o3] * v;\n size[o3 + 1] = startSize[o3 + 1] * v;\n size[o3 + 2] = startSize[o3 + 2] * v;\n }}`};case"RotationBySpeed":return{setup:`const b${e} = behaviors[${e}];\n ${Ds(`g${e}`,`b${e}.angularVelocity`)}\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};\n const angle_${e} = count > 0 && typeof particles[0].rotation === 'number';`,body:`if (angle_${e}) {\n ${ks(e)}\n ${qs(`g${e}`,"rate","ts")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n }`};case"OrbitOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Ds(`g${e}`,`b${e}.orbitSpeed`)}\n ${Qs(`ax${e}`,`b${e}._axis`)}\n ${Qs(`c${e}`,`b${e}._center`)}\n const alen${e} = ax${e}x * ax${e}x + ax${e}y * ax${e}y + ax${e}z * ax${e}z;\n const orbit${e} = alen${e} !== 0;\n const chalf${e} = (g${e}_cv * delta) / 2;\n const csn${e} = Math.sin(chalf${e});\n const cqx${e} = ax${e}x * csn${e}, cqy${e} = ax${e}y * csn${e}, cqz${e} = ax${e}z * csn${e};\n const cqw${e} = Math.cos(chalf${e});`,body:`if (orbit${e}) {\n let px = Math.fround(pos[o3] - c${e}x), py = Math.fround(pos[o3 + 1] - c${e}y), pz = Math.fround(pos[o3 + 2] - c${e}z);\n // Divided by the squared length as projectOnVector does, so the bits match.\n const f = (ax${e}x * px + ax${e}y * py + ax${e}z * pz) / alen${e};\n const tx = ax${e}x * f, ty = ax${e}y * f, tz = ax${e}z * f;\n let qx, qy, qz, qw;\n if (g${e}_const) {\n qx = cqx${e}; qy = cqy${e}; qz = cqz${e}; qw = cqw${e};\n } else {\n ${qs(`g${e}`,"sp","t")}\n const half = (sp * delta) / 2;\n const sn = Math.sin(half);\n qx = ax${e}x * sn; qy = ax${e}y * sn; qz = ax${e}z * sn; qw = Math.cos(half);\n }\n px = Math.fround(px - tx); py = Math.fround(py - ty); pz = Math.fround(pz - tz);\n ${Ws("px","py","pz","qx","qy","qz","qw")}\n px = Math.fround(Math.fround(px) + tx); py = Math.fround(Math.fround(py) + ty); pz = Math.fround(Math.fround(pz) + tz);\n pos[o3] = px + c${e}x;\n pos[o3 + 1] = py + c${e}y;\n pos[o3 + 2] = pz + c${e}z;}`};case"Rotation3DOverLife":return{setup:`const b${e} = behaviors[${e}];\n const g${e} = b${e}.angularVelocity;\n const q${e} = b${e}.tempQuat;\n const rq${e} = store.rotationQuaternion, aq${e} = store.angularVelocityQuaternion;\n const quat_${e} = rq${e}.length > 0 && count > 0 && particles[0].rotation instanceof deps.Quaternion;\n const fixed_${e} = g${e} instanceof deps.AxisAngleGenerator && g${e}.angle instanceof deps.ConstantValue;\n let cqx${e} = 0, cqy${e} = 0, cqz${e} = 0, cqw${e} = 1;\n if (fixed_${e}) {\n g${e}.genValue(undefined, q${e}, delta, 0);\n cqx${e} = q${e}.x; cqy${e} = q${e}.y; cqz${e} = q${e}.z; cqw${e} = q${e}.w;\n }`,body:`if (quat_${e}) {\n let qx, qy, qz, qw;\n if (fixed_${e}) {\n qx = cqx${e}; qy = cqy${e}; qz = cqz${e}; qw = cqw${e};\n } else {\n g${e}.genValue(p.memory, q${e}, delta, t);\n qx = q${e}.x; qy = q${e}.y; qz = q${e}.z; qw = q${e}.w;\n }\n const ax = rq${e}[o4], ay = rq${e}[o4 + 1], az = rq${e}[o4 + 2], aw = rq${e}[o4 + 3];\n rq${e}[o4] = ax * qw + aw * qx + ay * qz - az * qy;\n rq${e}[o4 + 1] = ay * qw + aw * qy + az * qx - ax * qz;\n rq${e}[o4 + 2] = az * qw + aw * qz + ax * qy - ay * qx;\n rq${e}[o4 + 3] = aw * qw - ax * qx - ay * qy - az * qz;\n aq${e}[o4] = qx; aq${e}[o4 + 1] = qy; aq${e}[o4 + 2] = qz; aq${e}[o4 + 3] = qw;\n }`};case"VelocityOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Ds(`lx${e}`,`b${e}.linearX`)}\n ${Ds(`ly${e}`,`b${e}.linearY`)}\n ${Ds(`lz${e}`,`b${e}.linearZ`)}\n ${Ds(`ox${e}`,`b${e}.orbitalX`)}\n ${Ds(`oy${e}`,`b${e}.orbitalY`)}\n ${Ds(`oz${e}`,`b${e}.orbitalZ`)}\n ${Qs(`aX${e}`,`b${e}._axisX`)}\n ${Qs(`aY${e}`,`b${e}._axisY`)}\n ${Qs(`aZ${e}`,`b${e}._axisZ`)}\n ${Ds(`rd${e}`,`b${e}.radial`)}\n ${Qs(`ce${e}`,`b${e}._center`)}\n const world${e} = b${e}.ps !== undefined && b${e}.ps.worldSpace;\n const toWorld${e} = world${e} && b${e}.space === 'local';\n const convert${e} = toWorld${e} || (!world${e} && b${e}.space === 'world');\n ${Qs(`sc${e}`,`toWorld${e} ? b${e}._tempScale : b${e}._tempScaleInv`)}\n ${js(`q${e}`,`toWorld${e} ? b${e}._tempQ : b${e}._tempQInv`)}`,body:`{\n ${qs(`lx${e}`,"fx","t")}\n ${qs(`ly${e}`,"fy","t")}\n ${qs(`lz${e}`,"fz","t")}\n if (convert${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${Ws("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n }\n let px = Math.fround(pos[o3] + fx * delta);\n let py = Math.fround(pos[o3 + 1] + fy * delta);\n let pz = Math.fround(pos[o3 + 2] + fz * delta);\n ${qs(`rd${e}`,"radial","t")}\n if (radial !== 0) {\n // Away from the centre, along the line through the particle.\n const dx = px - ce${e}x, dy = py - ce${e}y, dz = pz - ce${e}z;\n const length = Math.sqrt(dx * dx + dy * dy + dz * dz);\n if (length > 0) {\n const f = (radial * delta) / length;\n px = Math.fround(px + dx * f); py = Math.fround(py + dy * f); pz = Math.fround(pz + dz * f);\n }\n }\n ${qs(`ox${e}`,"rx","t")}\n ${qs(`oy${e}`,"ry","t")}\n ${qs(`oz${e}`,"rz","t")}\n rx *= delta; ry *= delta; rz *= delta;\n if (rx !== 0 || ry !== 0 || rz !== 0) {\n px = Math.fround(px - ce${e}x); py = Math.fround(py - ce${e}y); pz = Math.fround(pz - ce${e}z);\n if (rx !== 0) ${Hs("rx",`aX${e}x`,`aX${e}y`,`aX${e}z`)}\n if (ry !== 0) ${Hs("ry",`aY${e}x`,`aY${e}y`,`aY${e}z`)}\n if (rz !== 0) ${Hs("rz",`aZ${e}x`,`aZ${e}y`,`aZ${e}z`)}\n px = Math.fround(px + ce${e}x); py = Math.fround(py + ce${e}y); pz = Math.fround(pz + ce${e}z);\n }\n pos[o3] = px; pos[o3 + 1] = py; pos[o3 + 2] = pz;}`};case"InheritVelocity":return{setup:`const b${e} = behaviors[${e}];\n const ps${e} = b${e}.ps;\n const ev${e} = b${e}.mode === 'current' && ps${e} !== undefined ? ps${e}.emitterVelocity : undefined;\n const active${e} = ev${e} !== undefined;\n let ivx${e} = 0, ivy${e} = 0, ivz${e} = 0;\n if (active${e}) {\n ivx${e} = ev${e}.x; ivy${e} = ev${e}.y; ivz${e} = ev${e}.z;\n if (!ps${e}.worldSpace) {\n ${Qs(`sc${e}`,`b${e}._tempScaleInv`)}\n ${js(`q${e}`,`b${e}._tempQInv`)}\n ivx${e} *= sc${e}x; ivy${e} *= sc${e}y; ivz${e} *= sc${e}z;\n ${Ws(`ivx${e}`,`ivy${e}`,`ivz${e}`,`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n }\n }\n ${Ds(`gm${e}`,`b${e}.multiplier`)}`,body:`if (active${e}) {\n ${qs(`gm${e}`,"m","t")}\n const f = m * delta;\n pos[o3] += ivx${e} * f; pos[o3 + 1] += ivy${e} * f; pos[o3 + 2] += ivz${e} * f;\n }`};default:return null}}const Xs=new Map;function Zs(t,e,s){const i=Xs.get(s);if(void 0!==i)return i??void 0;const n=function(t,e){const s=`\n if (count === 0) return;\n if (store === undefined) {\n store = particles[0].store;\n if (store === undefined) {\n // Particles of some other implementation, without columns: run the behaviors as they are.\n for (const k of [${e.join(", ")}]) {\n const b = behaviors[k];\n for (let i = 0; i < count; i++) {\n const p = particles[i];\n if (p.age < p.life) b.update(p, delta);\n }\n }\n return;\n }\n }\n const pos = store.position, vel = store.velocity;\n const size = store.size, startSize = store.startSize;\n const color = store.color, startColor = store.startColor;\n const scalars = store.scalars;\n const rot = store.rotation, angVel = store.angularVelocity;\n const uvTile = store.uvTile, startSpeed = store.startSpeed;\n const mem = store.memory, ms = store.memoryStride;\n ${t.map(t=>t.setup).join("\n")}\n // The system keeps particles[i] on row i. Anything else (a hand-built\n // list) is caught by its ends and read through each particle's row.\n const mapped = particles[0].storeIndex !== 0 || particles[count - 1].storeIndex !== count - 1;\n for (let i = 0; i < count; i++) {\n const p = particles[i];\n const row = mapped ? p.storeIndex : i;\n const s = row * 3;\n const age = scalars[s], life = scalars[s + 1];\n if (age >= life) continue;\n const t = age / life;\n const o3 = row * 3, o4 = row * 4;\n ${t.map(t=>t.body).join("\n")}\n }`;try{return new Function("deps",`const tmpColor = new deps.Vector4View(new Float32Array(4), 0);\n return function (behaviors, particles, count, delta, store) {${s}};`)(Ls)}catch(t){return}}(t,e);return Xs.set(s,n??null),n}function Ks(t){const e=[];let s=[],i=[],n=[],r=0;const o=()=>{if(0===i.length)return;const t=`${r}:${s.map(t=>t.type).join(",")}`,o=Zs(i,n,t);if(void 0!==o)e.push({behaviors:s,run:o});else for(const t of s)e.push({behaviors:[t]});s=[],i=[],n=[]};for(let a=0;a<t.length;a++){const h=t[a],l=Ys(h,a);null!==l?(0===i.length&&(r=a),s.push(h),i.push(l),n.push(a)):(o(),e.push({behaviors:[h]}))}return o(),e}class ti{constructor(t,e,s){this.position=t??new st,this.rotation=e??new et,this.scale=s??new st(1,1,1)}apply(t){t.position.multiply(this.scale).applyQuaternion(this.rotation).add(this.position);const e=t.velocity,s=e.length();if(0===s)return;e.multiply(this.scale).applyQuaternion(this.rotation);const i=e.length();i>0&&e.multiplyScalar(s/i)}isIdentity(){const{position:t,rotation:e,scale:s}=this;return 0===t.x&&0===t.y&&0===t.z&&0===e.x&&0===e.y&&0===e.z&&1===e.w&&1===s.x&&1===s.y&&1===s.z}toJSON(){const t={},{position:e,rotation:s,scale:i}=this;return 0===e.x&&0===e.y&&0===e.z||(t.position=[e.x,e.y,e.z]),0===s.x&&0===s.y&&0===s.z&&1===s.w||(t.rotation=[s.x,s.y,s.z,s.w]),1===i.x&&1===i.y&&1===i.z||(t.scale=[i.x,i.y,i.z]),t}static fromJSON(t){if(!t)return;const{position:e,rotation:s,scale:i}=t;return new ti(e?new st(e[0],e[1],e[2]):void 0,s?new et(s[0],s[1],s[2],s[3]).normalize():void 0,i?new st(i[0],i[1],i[2]):void 0)}static toShapeJSON(t){return t&&!t.isIdentity()?{transform:t.toJSON()}:{}}clone(){return new ti(this.position.clone(),this.rotation.clone(),this.scale.clone())}}var ei,si;exports.BoxEmitFrom=void 0,(ei=exports.BoxEmitFrom||(exports.BoxEmitFrom={}))[ei.Volume=0]="Volume",ei[ei.Shell=1]="Shell",ei[ei.Edge=2]="Edge";class ii{constructor(t={}){this.type="box",this._point=[0,0,0],this.width=t.width??1,this.height=t.height??1,this.depth=t.depth??1,this.emitFrom=t.emitFrom??exports.BoxEmitFrom.Volume,this.boxThickness=t.boxThickness?[...t.boxThickness]:[0,0,0],this.transform=t.transform}update(t,e){}initialize(t,e){const s=this._point;for(let t=0;t<3;t++)s[t]=2*z()-1;const i=Math.floor(3*z())%3;this.emitFrom===exports.BoxEmitFrom.Shell?s[i]=this.onSurface(i):this.emitFrom===exports.BoxEmitFrom.Edge&&(s[(i+1)%3]=this.onSurface((i+1)%3),s[(i+2)%3]=this.onSurface((i+2)%3)),t.position.set(s[0]*this.width/2,s[1]*this.height/2,s[2]*this.depth/2),t.velocity.set(0,0,t.startSpeed),this.transform?.apply(t)}onSurface(t){const e=z()<.5?-1:1,s=Math.min(this.boxThickness[t],1);return s<=0||z()<.5?e:e*(1-2*s*z())}toJSON(){return{type:"box",width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:[...this.boxThickness],...ti.toShapeJSON(this.transform)}}static fromJSON(t){return new ii({width:t.width,height:t.height,depth:t.depth,emitFrom:t.emitFrom,boxThickness:Array.isArray(t.boxThickness)?[Number(t.boxThickness[0])||0,Number(t.boxThickness[1])||0,Number(t.boxThickness[2])||0]:void 0,transform:ti.fromJSON(t.transform)})}clone(){return new ii({width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:this.boxThickness,transform:this.transform?.clone()})}}function ni(t,e,s,i){let n;switch(t){case exports.EmitterMode.Loop:n=e-Math.floor(e);break;case exports.EmitterMode.PingPong:{const t=e-2*Math.floor(e/2);n=1-Math.abs(t-1);break}case exports.EmitterMode.Burst:n=i.isBursting&&i.burstParticleCount>0?i.burstParticleIndex/i.burstParticleCount:z();break;default:n=z()}return s>0&&(n=Math.floor(n/s)*s),n}exports.EmitterMode=void 0,(si=exports.EmitterMode||(exports.EmitterMode={}))[si.Random=0]="Random",si[si.Loop=1]="Loop",si[si.PingPong=2]="PingPong",si[si.Burst=3]="Burst";class ri{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="circle",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Xt(1),this.memory=[],this.transform=t.transform}update(t,e){exports.EmitterMode.Random!==this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=ni(this.mode,this.currentValue,this.spread,e),i=Je(this.thickness,2),n=s*this.arc;t.position.x=Math.cos(n),t.position.y=Math.sin(n),t.position.z=0,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)*i),this.transform?.apply(t)}toJSON(){return{type:"circle",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...ti.toShapeJSON(this.transform)}}static fromJSON(t){return new ri({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?ne(t.speed):void 0,transform:ti.fromJSON(t.transform),spread:t.spread})}clone(){return new ri({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}const oi=Math.cos(89*Math.PI/180);var ai,hi;exports.ConeEmitFrom=void 0,(ai=exports.ConeEmitFrom||(exports.ConeEmitFrom={}))[ai.Base=0]="Base",ai[ai.Volume=1]="Volume";class li{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="cone",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.angle=t.angle??Math.PI/6,this.emitFrom=t.emitFrom??exports.ConeEmitFrom.Base,this.length=t.length??5,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Xt(1),this.memory=[],this.transform=t.transform}update(t,e){exports.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=ni(this.mode,this.currentValue,this.spread,e),i=Je(this.thickness,2),n=s*this.arc,r=Math.sin(n),o=Math.cos(n);t.position.x=i*o,t.position.y=i*r,t.position.z=0;const a=Math.min(Math.max(this.angle,0),Math.PI/2),h=i>0?Math.atan(i*Math.tan(a)):0,l=Math.sin(h),c=Math.cos(h);if(t.velocity.set(l*o,l*r,c).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)),this.emitFrom===exports.ConeEmitFrom.Volume){const e=Number.isFinite(this.length)?Math.max(0,this.length):0,s=z()*e/Math.max(c,oi);t.position.x+=l*o*s,t.position.y+=l*r*s,t.position.z=c*s}this.transform?.apply(t)}toJSON(){return{type:"cone",radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,emitFrom:this.emitFrom,length:this.length,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...ti.toShapeJSON(this.transform)}}static fromJSON(t){return new li({radius:t.radius,arc:t.arc,thickness:t.thickness,angle:t.angle,emitFrom:t.emitFrom,length:t.length,mode:t.mode,speed:t.speed?ne(t.speed):void 0,transform:ti.fromJSON(t.transform),spread:t.spread})}clone(){return new li({radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,emitFrom:this.emitFrom,length:this.length,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class ci{constructor(t={}){this.type="donut",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.donutRadius=t.donutRadius??.2*this.radius,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Xt(1),this.memory=[],this.transform=t.transform,this._m1=new at}reset(){this.currentValue=0,this.memory.length=0}update(t,e){exports.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=ni(this.mode,this.currentValue,this.spread,e),i=z(),n=Je(this.thickness,2),r=s*this.arc,o=i*Math.PI*2,a=Math.sin(r),h=Math.cos(r),l=Math.max(0,this.radius),c=Math.max(0,this.donutRadius)*n;if(t.velocity.set(Math.cos(o)*h,Math.cos(o)*a,Math.sin(o)),t.position.set(l*h,l*a,0).addScaledVector(t.velocity,c),t.velocity.multiplyScalar(t.startSpeed),t.rotation instanceof et){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(je,t.velocity,We),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"donut",radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...ti.toShapeJSON(this.transform)}}static fromJSON(t){return new ci({radius:t.radius,arc:t.arc,thickness:t.thickness,donutRadius:t.donutRadius,mode:t.mode,speed:t.speed?ne(t.speed):void 0,transform:ti.fromJSON(t.transform),spread:t.spread})}clone(){return new ci({radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class ui{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="edge",this.currentValue=0,this.radius=t.radius??1,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Xt(1),this.memory=[],this.transform=t.transform}update(t,e){exports.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=ni(this.mode,this.currentValue,this.spread,e);t.position.set((2*s-1)*this.radius,0,0),t.velocity.set(0,t.startSpeed,0),this.transform?.apply(t)}toJSON(){return{type:"edge",radius:this.radius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...ti.toShapeJSON(this.transform)}}static fromJSON(t){return new ui({radius:t.radius,mode:t.mode,speed:t.speed?ne(t.speed):void 0,spread:t.spread,transform:ti.fromJSON(t.transform)})}clone(){return new ui({radius:this.radius,mode:this.mode,speed:this.speed.clone(),spread:this.spread,transform:this.transform?.clone()})}}exports.GridSampling=void 0,(hi=exports.GridSampling||(exports.GridSampling={}))[hi.Random=0]="Random",hi[hi.Sequential=1]="Sequential";class di{constructor(t={}){this.type="grid",this.nextCell=0,this.width=t.width??1,this.height=t.height??1,this.column=t.column??10,this.row=t.row??10,this.sampling=t.sampling??exports.GridSampling.Random,this.transform=t.transform}initialize(t){const e=Number.isFinite(this.row)?Math.max(1,Math.floor(this.row)):1,s=Number.isFinite(this.column)?Math.max(1,Math.floor(this.column)):1;let i,n;if(this.sampling===exports.GridSampling.Sequential){const t=this.nextCell%(e*s);this.nextCell=t+1,i=Math.floor(t/s),n=t%s}else i=Math.floor(z()*e),n=Math.floor(z()*s);t.position.x=((n+.5)/s-.5)*this.width,t.position.y=((i+.5)/e-.5)*this.height,t.position.z=0,t.velocity.set(0,0,t.startSpeed),this.transform?.apply(t)}toJSON(){return{type:"grid",width:this.width,height:this.height,column:this.column,row:this.row,sampling:this.sampling,...ti.toShapeJSON(this.transform)}}static fromJSON(t){return new di({width:t.width,height:t.height,column:t.column,row:t.row,sampling:t.sampling,transform:ti.fromJSON(t.transform)})}clone(){return new di({width:this.width,height:this.height,column:this.column,row:this.row,sampling:this.sampling,transform:this.transform?.clone()})}update(t,e){}reset(){this.nextCell=0}}class fi{constructor(t={}){this.type="hemisphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Xt(1),this.memory=[],this.transform=t.transform,this._m1=new at}reset(){this.currentValue=0,this.memory.length=0}update(t,e){exports.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=ni(this.mode,this.currentValue,this.spread,e),i=z(),n=Je(this.thickness,3),r=s*this.arc,o=Math.acos(i),a=Math.sin(r),h=Math.cos(r),l=Math.sin(o),c=Math.cos(o);if(t.position.x=l*h,t.position.y=l*a,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)*n),t.rotation instanceof et){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(je,t.position,We),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"hemisphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...ti.toShapeJSON(this.transform)}}static fromJSON(t){return new fi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?ne(t.speed):void 0,transform:ti.fromJSON(t.transform),spread:t.spread})}clone(){return new fi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class pi{constructor(t){this.type="point",this._m1=new at,this.transform=t}update(t,e){}initialize(t){const e=z(),s=z(),i=e*Math.PI*2,n=2*s-1,r=Math.sqrt(Math.max(0,1-n*n));if(t.velocity.x=r*Math.cos(i),t.velocity.y=r*Math.sin(i),t.velocity.z=n,t.velocity.multiplyScalar(t.startSpeed),t.position.setScalar(0),t.rotation instanceof et){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(je,t.velocity,We),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"point",...ti.toShapeJSON(this.transform)}}static fromJSON(t){return new pi(ti.fromJSON(t?.transform))}clone(){return new pi(this.transform?.clone())}}class mi{constructor(t={}){this.type="sphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Xt(1),this.memory=[],this.transform=t.transform,this._m1=new at}reset(){this.currentValue=0,this.memory.length=0}update(t,e){exports.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=ni(this.mode,this.currentValue,this.spread,e),i=z(),n=Je(this.thickness,3),r=s*this.arc,o=Math.acos(2*i-1),a=Math.sin(r),h=Math.cos(r),l=Math.sin(o),c=Math.cos(o);if(t.position.x=l*h,t.position.y=l*a,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)*n),t.rotation instanceof et){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(je,t.position,We),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"sphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...ti.toShapeJSON(this.transform)}}static fromJSON(t){return new mi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?ne(t.speed):void 0,transform:ti.fromJSON(t.transform),spread:t.spread})}clone(){return new mi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class yi{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="rectangle",this.currentValue=0,this.width=t.width??10,this.height=t.height??10,this.thickness=t.thickness??1,this.mode=t.mode??exports.EmitterMode.Random,this.spread=t.spread??0,this.speed=t.speed??new Xt(1),this.memory=[],this.transform=t.transform,this._m1=new at}update(t,e){exports.EmitterMode.Random!==this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const s=ni(this.mode,this.currentValue,this.spread,e);z();const i=Math.max(0,this.width),n=Math.max(0,this.height),r=2*s*(i+n);let o,a,h,l;r<i?(o=r-i/2,a=-n/2,h=0,l=-1):r<i+n?(o=i/2,a=r-i-n/2,h=1,l=0):r<2*i+n?(o=i/2-(r-i-n),a=n/2,h=0,l=1):(o=-i/2,a=n/2-(r-2*i-n),h=-1,l=0);const c=Je(this.thickness,2);if(t.position.set(o*c,a*c,0),0===o&&0===a?t.velocity.set(h,l,0):t.velocity.set(o,a,0).normalize(),t.velocity.multiplyScalar(t.startSpeed),t.rotation instanceof et){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(je,t.velocity,We),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"rectangle",width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...ti.toShapeJSON(this.transform)}}static fromJSON(t){return new yi({width:t.width,height:t.height,thickness:t.thickness,mode:t.mode,speed:t.speed?ne(t.speed):void 0,transform:ti.fromJSON(t.transform),spread:t.spread})}clone(){return new yi({width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}const gi={box:{type:"box",params:[["width",["number"]],["height",["number"]],["depth",["number"]],["emitFrom",["boxEmitFrom"]],["boxThickness",["vec3"]],["transform",["shapeTransform"]]],constructor:ii,loadJSON:ii.fromJSON},circle:{type:"circle",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:ri,loadJSON:ri.fromJSON},cone:{type:"cone",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["emitFrom",["coneEmitFrom"]],["length",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:li,loadJSON:li.fromJSON},donut:{type:"donut",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["donutRadius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:ci,loadJSON:ci.fromJSON},edge:{type:"edge",params:[["radius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:ui,loadJSON:ui.fromJSON},point:{type:"point",params:[["transform",["shapeTransform"]]],constructor:pi,loadJSON:pi.fromJSON},sphere:{type:"sphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:mi,loadJSON:mi.fromJSON},hemisphere:{type:"hemisphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:fi,loadJSON:fi.fromJSON},grid:{type:"grid",params:[["width",["number"]],["height",["number"]],["column",["number"]],["row",["number"]],["sampling",["gridSampling"]],["transform",["shapeTransform"]]],constructor:di,loadJSON:di.fromJSON},rectangle:{type:"rectangle",params:[["width",["number"]],["height",["number"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:yi,loadJSON:yi.fromJSON}};function vi(t,e){const s=t?gi[t.type]:void 0;return s?s.loadJSON(t,e):(Wt(`${Qt("emitter shape",t)}; using a point emitter.`),new pi)}function xi(t,e={}){const s=t.toJSON(),i=gi[s?.type];return i?Yt(s,t=>i.loadJSON(t,e).toJSON()):s}const Si=[];function bi(t){if(!Si.find(e=>e.id===t.id)){t.initialize(),Si.push(t);for(const e of t.emitterShapes)gi[e.type]||(gi[e.type]=e);for(const e of t.behaviors)Rs[e.type]||(Rs[e.type]=e)}}function wi(t,e){if(e&&e.length>0)return e;const s=t.length/3,i=new Uint32Array(s);for(let t=0;t<s;t++)i[t]=t;return i}const Mi=new WeakMap;function zi(t){let s=Mi.get(t);return void 0===s&&(s=e.RandomGUID(),Mi.set(t,s)),s}function _i(t){return Mi.get(t)}class Ai{get mesh(){return this._mesh}set mesh(e){if(this._mesh=e,this._positions=void 0,this._indices=void 0,this._triangleIndexToArea.length=0,!e)return;const s=e.getVerticesData(t.VertexBuffer.PositionKind);if(!s||s.length<9)return;const i=new Float32Array(s),n=e.getIndices(),r=wi(i,n&&n.length>0?Uint32Array.from(n):void 0),o=Math.floor(r.length/3);if(0===o)return;this._positions=i,this._indices=new Int32Array(r.subarray(0,3*o));let a=0;this._triangleIndexToArea.push(0);const h=new st,l=new st,c=new st,u=new st;for(let t=0;t<o;t++){const e=r[3*t],i=r[3*t+1],n=r[3*t+2];h.set(s[3*e],s[3*e+1],s[3*e+2]),l.set(s[3*i],s[3*i+1],s[3*i+2]),c.set(s[3*n],s[3*n+1],s[3*n+2]),l.sub(h),c.sub(h),u.crossVectors(l,c),a+=.5*u.length(),this._triangleIndexToArea.push(a)}}constructor(t,e,s){this.type="mesh_surface",this._triangleIndexToArea=[],this._meshReferenceId=e,this.transform=s,t&&(this.mesh=t)}initialize(t){if(!this._positions||!this._indices)return t.position.set(0,0,0),t.velocity.set(0,0,1).multiplyScalar(t.startSpeed),void this.transform?.apply(t);const e=this._triangleIndexToArea.length-1;let s=0,i=e;const n=z()*this._triangleIndexToArea[e];for(;s+1<i;){const t=Math.floor((s+i)/2);n<this._triangleIndexToArea[t]?i=t:s=t}let r=z(),o=z();r+o>1&&(r=1-r,o=1-o);const a=this._indices[3*s],h=this._indices[3*s+1],l=this._indices[3*s+2],c=this._positions[3*a],u=this._positions[3*a+1],d=this._positions[3*a+2],f=this._positions[3*h]-c,p=this._positions[3*h+1]-u,m=this._positions[3*h+2]-d,y=this._positions[3*l]-c,g=this._positions[3*l+1]-u,v=this._positions[3*l+2]-d;t.position.set(c+f*r+y*o,u+p*r+g*o,d+m*r+v*o);const x=p*v-m*g,S=m*y-f*v,b=f*g-p*y,w=Math.sqrt(x*x+S*S+b*b)||1;t.velocity.set(x/w,S/w,b/w).multiplyScalar(t.startSpeed),this.transform?.apply(t)}toJSON(){return{type:"mesh_surface",mesh:this._mesh?zi(this._mesh):this._meshReferenceId??"",...ti.toShapeJSON(this.transform)}}static fromJSON(t){return new Ai(void 0,t?.mesh,ti.fromJSON(t?.transform))}clone(){return new Ai(this._mesh,this._meshReferenceId,this.transform?.clone())}update(t,e){}}const Pi={id:"babylon.quarks",initialize:()=>{},emitterShapes:[{type:"mesh_surface",params:[["mesh",["mesh"]]],constructor:Ai,loadJSON:t=>Ai.fromJSON(t)}],behaviors:[]};var Oi;function Ti(){return{direction:new a.Vector3(.4,-1,.6),color:new o.Color3(1,1,1),ambient:new o.Color3(.35,.35,.35)}}function Vi(t){if(!t||"object"!=typeof t)return;const e=Array.isArray(t.color)?t.color:[1,1,1],s=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e;return{color:[s(e[0],1),s(e[1],1),s(e[2],1)],power:Math.max(.01,s(t.power,2)),strength:Math.max(0,s(t.strength,1)),mode:"mix"===t.mode||"fade"===t.mode?t.mode:"add"}}function Ei(t,e={}){const s=t&&"object"==typeof t?t:{},i=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e,n=(t,e)=>Array.isArray(t)?[i(t[0],e[0]),i(t[1],e[1])]:[e[0],e[1]];return{channel:1===(s.channel??e.channel)?1:0,tiling:n(s.tiling,e.tiling??[1,1]),offset:n(s.offset,e.offset??[0,0]),scroll:n(s.scroll,e.scroll??[0,0])}}function Ci(t,e){return t===e||t.channel===e.channel&&t.tiling[0]===e.tiling[0]&&t.tiling[1]===e.tiling[1]&&t.offset[0]===e.offset[0]&&t.offset[1]===e.offset[1]&&t.scroll[0]===e.scroll[0]&&t.scroll[1]===e.scroll[1]}function $i(t,e={}){const s=Ei(void 0,e),i={};return t.channel!==s.channel&&(i.channel=t.channel),t.tiling[0]===s.tiling[0]&&t.tiling[1]===s.tiling[1]||(i.tiling=[...t.tiling]),t.offset[0]===s.offset[0]&&t.offset[1]===s.offset[1]||(i.offset=[...t.offset]),t.scroll[0]===s.scroll[0]&&t.scroll[1]===s.scroll[1]||(i.scroll=[...t.scroll]),Object.keys(i).length>0?i:void 0}exports.RenderMode=void 0,(Oi=exports.RenderMode||(exports.RenderMode={}))[Oi.BillBoard=0]="BillBoard",Oi[Oi.StretchedBillBoard=1]="StretchedBillBoard",Oi[Oi.Mesh=2]="Mesh",Oi[Oi.Trail=3]="Trail",Oi[Oi.HorizontalBillBoard=4]="HorizontalBillBoard",Oi[Oi.VerticalBillBoard=5]="VerticalBillBoard",Oi[Oi.Beam=6]="Beam";const Ii={r:[1,0,0,0],g:[0,1,0,0],b:[0,0,1,0],a:[0,0,0,1],luminance:[.2126,.7152,.0722,0]};function Ni(t){if(!t||"object"!=typeof t||!t.ramp)return;const e=t.channel;return{ramp:t.ramp,channel:void 0!==e&&e in Ii?e:"r"}}const Fi=.05;function Ri(t){if(!t||"object"!=typeof t)return;const e=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e,s=Array.isArray(t.edgeColor)?t.edgeColor:[1,1,1];return{mask:t.mask??null,maskUV:Ei(t.maskUV),softness:Math.max(1e-4,e(t.softness,Fi)),edgeWidth:Math.max(0,e(t.edgeWidth,0)),edgeColor:[e(s[0],1),e(s[1],1),e(s[2],1)]}}const Bi={scroll:[0,.5]},Ui=.05;function Li(t){if(!t||"object"!=typeof t||!t.map)return;const e=t.strength;return{map:t.map,mapUV:Ei(t.mapUV,Bi),strength:Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:Ui)}}function Di(t){if(!t||"object"!=typeof t)return;const e=Ei(t);return void 0===$i(e)?void 0:e}function ki(t){const{mapUV:e,uvDistortion:s,erosion:i}=t;return 1===e?.channel||1===s?.mapUV.channel||!!i?.mask&&1===i.maskUV.channel}function qi(t){return"unlit"===t||"scene"===t?t:"fixed"}function Gi(t){return"distance"===t||"oldestInFront"===t||"youngestInFront"===t?t:"none"}function Ji(t){return"front"===t||"back"===t?t:"both"}function Wi(t){return"pause"===t||"pauseAndCatchUp"===t?t:"always"}function ji(t){return"disable"===t||"destroy"===t?t:"none"}function Qi(t){return"pauseUntilReplaced"===t||"loopUntilReplaced"===t?t:"disabled"}function Hi(t){const e=(t,e)=>"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):e,s=e(t?.x,0),i=e(t?.y,1);return new Mt(Math.min(s,i),Math.max(s,i))}function Yi(t){return"hierarchy"===t||"shape"===t?t:"local"}function Xi(t){return!t||0===t.x&&0===t.y&&0===t.z?void 0:t.clone()}function Zi(t){return"number"==typeof t&&t>0?Math.min(t,1):0}function Ki(t){return"number"==typeof t&&Number.isFinite(t)&&t>=1?Math.floor(t):1}function tn(t,e){return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:e}function en(t){const e=t.count,s="number"==typeof t.time&&Number.isFinite(t.time)&&t.time>0?t.time:0,i="number"==typeof t.cycle&&Number.isFinite(t.cycle)&&t.cycle>=1?t.cycle:1,n="number"==typeof t.interval&&Number.isFinite(t.interval)?Math.max(0,t.interval):.1,r="number"==typeof t.probability&&Number.isFinite(t.probability)?Math.min(1,Math.max(0,t.probability)):1;return{time:s,count:"number"==typeof e?new Xt(e):null!=e?e:new Xt(0),cycle:i,interval:n,probability:r}}function sn(t){return(t??[]).map(en).sort((t,e)=>t.time-e.time)}const nn=new Float32Array(0),rn=new Uint16Array(0);function on(t){return t===exports.RenderMode.BillBoard||t===exports.RenderMode.StretchedBillBoard||t===exports.RenderMode.VerticalBillBoard||t===exports.RenderMode.HorizontalBillBoard}function an(t){return t.uTileCount>1||t.vTileCount>1}function hn(t){return t.minParticleSize>0||t.maxParticleSize!==1/0}function ln(t){const e=t.renderMode,s=e===exports.RenderMode.Mesh,i=e===exports.RenderMode.Trail,n=on(e),o=t.softParticles,a=t.materialTransparent,h=t.pivot,l=Di(t.mapUV),c=Li(t.uvDistortion),u=Ni(t.gradientMap),d=Ri(t.erosion),f=Ki(t.uTileCount),p=Ki(t.vTileCount);var m;return{renderMode:e,instancingGeometry:i?nn:t.instancingGeometry,instancingIndices:i?rn:t.instancingIndices,instancingUVs:i?void 0:t.instancingUVs,instancingUVs2:s&&ki({mapUV:l,uvDistortion:c,erosion:d})?t.instancingUVs2:void 0,instancingNormals:s?t.instancingNormals:void 0,renderOrder:t.renderOrder,uTileCount:f,vTileCount:p,blendTiles:!i&&t.blendTiles&&an({uTileCount:f,vTileCount:p}),softParticles:o,softNearFade:o?tn(t.softNearFade,0):0,softFarFade:o?tn(t.softFarFade,1):0,materialBlendMode:a?t.materialBlendMode:r.Constants.ALPHA_DISABLE,materialTransparent:a,materialDepthTest:t.materialDepthTest,materialDepthWrite:t.materialDepthWrite,materialAlphaTest:t.materialAlphaTest>0?t.materialAlphaTest:0,texture:t.texture,reflectionTexture:s?t.reflectionTexture??null:null,reflectionLevel:s?t.reflectionLevel??1:1,reflectionAtlas:s?t.reflectionAtlas??null:null,layerMask:t.layerMask,renderingGroupId:t.renderingGroupId??0,applyFog:t.applyFog??!0,applyImageProcessing:t.applyImageProcessing??!0,pivot:n&&h&&(0!==h.x||0!==h.y||0!==h.z)?h.clone():void 0,sortMode:t.sortMode??"none",renderFace:s?Ji(t.renderFace):"both",minParticleSize:n?Math.max(0,t.minParticleSize??0):0,maxParticleSize:n?(m=t.maxParticleSize,void 0!==m&&m>0?m:1/0):1/0,lighting:s?t.lighting??"fixed":"fixed",rim:s?Vi(t.rim):void 0,mapUV:l,uvDistortion:c,gradientMap:u,erosion:d}}function cn(t,e){return t.renderMode===e.renderMode&&t.instancingGeometry===e.instancingGeometry&&t.instancingIndices===e.instancingIndices&&t.instancingUVs===e.instancingUVs&&t.instancingUVs2===e.instancingUVs2&&t.instancingNormals===e.instancingNormals&&t.texture===e.texture&&t.reflectionTexture===e.reflectionTexture&&t.reflectionAtlas===e.reflectionAtlas&&t.lighting===e.lighting&&t.rim?.mode===e.rim?.mode&&t.uTileCount===e.uTileCount&&t.vTileCount===e.vTileCount&&t.blendTiles===e.blendTiles&&t.softParticles===e.softParticles&&t.materialBlendMode===e.materialBlendMode&&t.materialTransparent===e.materialTransparent&&t.materialDepthTest===e.materialDepthTest&&t.materialDepthWrite===e.materialDepthWrite&&t.materialAlphaTest>0==e.materialAlphaTest>0&&t.layerMask===e.layerMask&&t.renderingGroupId===e.renderingGroupId&&t.renderOrder===e.renderOrder&&t.applyFog===e.applyFog&&t.applyImageProcessing===e.applyImageProcessing&&t.sortMode===e.sortMode&&t.renderFace===e.renderFace&&!t.pivot==!e.pivot&&hn(t)===hn(e)&&t.mapUV?.channel===e.mapUV?.channel&&t.uvDistortion?.map===e.uvDistortion?.map&&t.uvDistortion?.mapUV.channel===e.uvDistortion?.mapUV.channel&&!t.gradientMap==!e.gradientMap&&t.gradientMap?.ramp===e.gradientMap?.ramp&&!t.erosion==!e.erosion&&t.erosion?.mask===e.erosion?.mask&&t.erosion?.maskUV.channel===e.erosion?.maskUV.channel}function un(t,e){return t.softNearFade===e.softNearFade&&t.softFarFade===e.softFarFade&&t.materialAlphaTest===e.materialAlphaTest&&t.reflectionLevel===e.reflectionLevel&&function(t,e){return(t?.x??0)===(e?.x??0)&&(t?.y??0)===(e?.y??0)&&(t?.z??0)===(e?.z??0)}(t.pivot,e.pivot)&&t.minParticleSize===e.minParticleSize&&t.maxParticleSize===e.maxParticleSize&&function(t,e){if(!t||!e)return!t==!e;return t.power===e.power&&t.strength===e.strength&&fn(t.color,e.color)}(t.rim,e.rim)&&pn(t.mapUV,e.mapUV)&&t.uvDistortion?.strength===e.uvDistortion?.strength&&pn(t.uvDistortion?.mapUV,e.uvDistortion?.mapUV)&&t.gradientMap?.channel===e.gradientMap?.channel&&t.erosion?.softness===e.erosion?.softness&&t.erosion?.edgeWidth===e.erosion?.edgeWidth&&fn(t.erosion?.edgeColor,e.erosion?.edgeColor)&&pn(t.erosion?.maskUV,e.erosion?.maskUV)}function dn(t,e){return cn(t,e)&&un(t,e)}function fn(t,e){return t&&e?t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]:!t==!e}function pn(t,e){return t&&e?t.tiling[0]===e.tiling[0]&&t.tiling[1]===e.tiling[1]&&t.offset[0]===e.offset[0]&&t.offset[1]===e.offset[1]&&t.scroll[0]===e.scroll[0]&&t.scroll[1]===e.scroll[1]:!t==!e}function mn(t,e={}){const s=function(t,e){if(s=t,"function"==typeof s?.getDepthMap){const s=t,i=s._storeCameraSpaceZ?"viewZ":s._storeNonLinearDepth?"nonLinear":"linear";return{texture:t.getDepthMap(),encoding:e.encoding??i,packed:e.packed??t.isPacked}}var s;return{texture:t,encoding:e.encoding??"linear",packed:e.packed??!1}}(t,e);if(s.packed&&"viewZ"===s.encoding)throw new Error("[babylon.quarks] A packed view-Z depth cannot be decoded; use a float depth texture");return s}function yn(t,e,s){if("viewZ"===e)return s.set(1,0,0,1);const i=t.getEngine(),n=i.useReverseDepthBuffer,r=i.isNDCHalfZRange,o=t.getProjectionMatrix().m,a=o[10],l=o[11],c=o[14],u=o[15];if("linear"===e){let e,i;t.mode===h.Camera.ORTHOGRAPHIC_CAMERA?(e=!n&&r?0:1,i=n&&r?0:1):(e=n&&r?t.minZ:r?0:t.minZ,i=n&&r?0:t.maxZ);const o=n?-1:1,l=e+i;return s.set(o*l/a,(-o*e-c)/a,0,1)}const d=r?1:2,f=r?0:-1;return s.set(-d*u,c-f*u,d*l,f*l-a)}const gn=2048,vn=2047;class xn{constructor(t){this.counts=new Uint32Array(gn),this.floatView=new Float32Array(1),this.uintView=new Uint32Array(this.floatView.buffer),this.keys=new Uint32Array(t),this.orderA=new Uint32Array(t),this.orderB=new Uint32Array(t)}ensure(t){this.keys.length<t&&(this.keys=new Uint32Array(t),this.orderA=new Uint32Array(t),this.orderB=new Uint32Array(t))}floatKey(t,e){this.floatView[0]=t;const s=this.uintView[0];return e?~s>>>0:s}}const Sn="\n#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n";function bn(t){return`\n#ifdef FOG\n vFogDistance = ${t};\n#endif\n`}const wn="\n#ifdef FOG\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\n\nfloat quarksFogFactor() {\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n float fogDistance = length(vFogDistance);\n if (vFogInfos.x == 3.0) {\n // A zero-width band is a cut at its distance, not a division by zero.\n fogCoeff = (fogEnd - fogDistance) / max(fogEnd - fogStart, 1e-6);\n } else if (vFogInfos.x == 1.0) {\n fogCoeff = exp(-fogDistance * fogDensity);\n } else if (vFogInfos.x == 2.0) {\n fogCoeff = exp(-fogDistance * fogDistance * fogDensity * fogDensity);\n }\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n";function Mn(t){return`\n#ifdef FOG\n {\n float fogFactor = quarksFogFactor();\n#if defined(FOG_ADDITIVE)\n ${t} *= fogFactor;\n#elif defined(FOG_MULTIPLY)\n ${t} = mix(vec3(1.0), ${t}, fogFactor);\n#else\n ${t} = mix(vFogColor, ${t}, fogFactor);\n#endif\n }\n#endif\n`}const zn="\n#ifdef FOG\nvarying vFogDistance: vec3f;\n#endif\n";function _n(t){return`\n#ifdef FOG\n vertexOutputs.vFogDistance = ${t};\n#endif\n`}const An="\n#ifdef FOG\nuniform vFogInfos: vec4f;\nuniform vFogColor: vec3f;\nvarying vFogDistance: vec3f;\n\nfn quarksFog(rgb: vec3f, fogDistanceVector: vec3f) -> vec3f {\n var fogCoeff = 1.0;\n let fogStart = uniforms.vFogInfos.y;\n let fogEnd = uniforms.vFogInfos.z;\n let fogDensity = uniforms.vFogInfos.w;\n let fogDistance = length(fogDistanceVector);\n if (uniforms.vFogInfos.x == 3.0) {\n // A zero-width band is a cut at its distance, not a division by zero.\n fogCoeff = (fogEnd - fogDistance) / max(fogEnd - fogStart, 1e-6);\n } else if (uniforms.vFogInfos.x == 1.0) {\n fogCoeff = exp(-fogDistance * fogDensity);\n } else if (uniforms.vFogInfos.x == 2.0) {\n fogCoeff = exp(-fogDistance * fogDistance * fogDensity * fogDensity);\n }\n let fogFactor = clamp(fogCoeff, 0.0, 1.0);\n#if defined(FOG_ADDITIVE)\n return rgb * fogFactor;\n#elif defined(FOG_MULTIPLY)\n return mix(vec3f(1.0), rgb, fogFactor);\n#else\n return mix(uniforms.vFogColor, rgb, fogFactor);\n#endif\n}\n#endif\n";function Pn(t){return`\n#ifdef FOG\n ${t} = vec4f(quarksFog(${t}.rgb, fragmentInputs.vFogDistance), ${t}.a);\n#endif\n`}function On(t,e,s){const i=e*s,n=Tn(Math.floor(t),i);return{column:Tn(n,e),row:Math.floor(n/e)}}function Tn(t,e){return t-e*Math.floor(t/e)}const Vn="\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n";function En(t){return`\n#ifdef UV_TILE\n {\n vec2 tc = vec2(tileCountX, tileCountY);\n float tileTotal = tc.x * tc.y;\n float baseTile = mod(floor(uvTile), tileTotal);\n vec2 tileUV = vec2(mod(baseTile, tc.x), tc.y - 1.0 - floor(baseTile / tc.x)) / tc;\n vUV = ${t} / tc + tileUV;\n#ifdef TILE_BLEND\n float nextTile = mod(baseTile + 1.0, tileTotal);\n vec2 nextUV = vec2(mod(nextTile, tc.x), tc.y - 1.0 - floor(nextTile / tc.x)) / tc;\n vUV2 = ${t} / tc + nextUV;\n vTileBlend = fract(uvTile);\n#endif\n }\n#else\n vUV = ${t};\n#endif\n`}const Cn="\n#ifdef UV_TILE\nuniform tileCountX: f32;\nuniform tileCountY: f32;\n\n// A floored modulo, as GLSL's mod: never negative for a positive divisor.\nfn quarksWrap(value: f32, divisor: f32) -> f32 {\n return value - divisor * floor(value / divisor);\n}\n#endif\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n";function $n(t){return`\n#ifdef UV_TILE\n {\n let tc = vec2f(uniforms.tileCountX, uniforms.tileCountY);\n let tileTotal = tc.x * tc.y;\n let baseTile = quarksWrap(floor(vertexInputs.uvTile), tileTotal);\n let tileUV = vec2f(quarksWrap(baseTile, tc.x), tc.y - 1.0 - floor(baseTile / tc.x)) / tc;\n vertexOutputs.vUV = ${t} / tc + tileUV;\n#ifdef TILE_BLEND\n let nextTile = quarksWrap(baseTile + 1.0, tileTotal);\n let nextUV = vec2f(quarksWrap(nextTile, tc.x), tc.y - 1.0 - floor(nextTile / tc.x)) / tc;\n vertexOutputs.vUV2 = ${t} / tc + nextUV;\n vertexOutputs.vTileBlend = fract(vertexInputs.uvTile);\n#endif\n }\n#else\n vertexOutputs.vUV = ${t};\n#endif\n`}var In=`\nattribute vec3 position;\nattribute vec2 uv;\nattribute vec3 normal;\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute vec4 rotation;\nattribute float uvTile;\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${Vn}\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n#ifdef MESH_UV2\n// The mesh's second UV set.\nattribute vec2 uv2;\n#endif\n// UV channel 1: the mesh's second UV set, or its first when it has none.\nvarying vec2 vUV1;\n#endif\nvarying vec3 vNormal;\nvarying vec3 vWorldPos;\n\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\nvec3 applyQuaternion(vec3 v, vec4 q) {\n vec3 qVec = q.xyz;\n float qW = q.w;\n vec3 t = 2.0 * cross(qVec, v);\n return v + qW * t + cross(qVec, t);\n}\n\n${Sn}\nvoid main() {\n vec3 scaledPosition = position * size;\n vec3 rotatedPosition = applyQuaternion(scaledPosition, rotation);\n // A normal scales by the inverse of the size, so a stretched mesh keeps its normals\n // perpendicular; a flat size counts as a sliver rather than dividing by zero.\n vec3 safeSize = vec3(\n abs(size.x) > 1e-6 ? size.x : 1e-6,\n abs(size.y) > 1e-6 ? size.y : 1e-6,\n abs(size.z) > 1e-6 ? size.z : 1e-6);\n // A mirrored size (an odd number of negative components) turns the winding inside out, so the\n // normal is turned with it and the fragment's front-face test agrees with the geometry.\n vec3 rotatedNormal = normalize(applyQuaternion(normal / safeSize, rotation)) * sign(safeSize.x * safeSize.y * safeSize.z);\n vec3 localPos = rotatedPosition + offset;\n\n vec4 worldPos = world * vec4(localPos, 1.0);\n vec4 viewPos = view * worldPos;\n gl_Position = projection * viewPos;\n${bn("viewPos.xyz")}\n\n vWorldPos = worldPos.xyz;\n vNormal = normalize((world * vec4(rotatedNormal, 0.0)).xyz);\n\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(viewPos.z);\n#endif\n\n${En("uv")}\n\n#ifdef UV1\n#ifdef MESH_UV2\n vUV1 = uv2;\n#else\n vUV1 = uv;\n#endif\n#endif\n vColor = color;\n}\n`,Nn=`\nattribute position: vec3f;\nattribute uv: vec2f;\nattribute normal: vec3f;\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: vec4f;\nattribute uvTile: f32;\n\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${Cn}\n\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n#ifdef MESH_UV2\n// The mesh's second UV set.\nattribute uv2: vec2f;\n#endif\n// UV channel 1: the mesh's second UV set, or its first when it has none.\nvarying vUV1: vec2f;\n#endif\nvarying vNormal: vec3f;\nvarying vWorldPos: vec3f;\n\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\nfn applyQuaternion(v: vec3f, q: vec4f) -> vec3f {\n let qVec = q.xyz;\n let qW = q.w;\n let t = 2.0 * cross(qVec, v);\n return v + qW * t + cross(qVec, t);\n}\n\n${zn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let size = vertexInputs.size;\n let scaledPosition = vertexInputs.position * size;\n let rotatedPosition = applyQuaternion(scaledPosition, vertexInputs.rotation);\n // A normal scales by the inverse of the size, so a stretched mesh keeps its normals\n // perpendicular; a flat size counts as a sliver rather than dividing by zero.\n let safeSize = vec3f(\n select(1e-6, size.x, abs(size.x) > 1e-6),\n select(1e-6, size.y, abs(size.y) > 1e-6),\n select(1e-6, size.z, abs(size.z) > 1e-6));\n // A mirrored size (an odd number of negative components) turns the winding inside out, so the\n // normal is turned with it and the fragment's front-face test agrees with the geometry.\n let rotatedNormal = normalize(applyQuaternion(vertexInputs.normal / safeSize, vertexInputs.rotation)) * sign(safeSize.x * safeSize.y * safeSize.z);\n let localPos = rotatedPosition + vertexInputs.offset;\n\n let worldPos = uniforms.world * vec4f(localPos, 1.0);\n let viewPos = uniforms.view * worldPos;\n let clipPosition = uniforms.projection * viewPos;\n vertexOutputs.position = clipPosition;\n${_n("viewPos.xyz")}\n\n vertexOutputs.vWorldPos = worldPos.xyz;\n vertexOutputs.vNormal = normalize((uniforms.world * vec4f(rotatedNormal, 0.0)).xyz);\n\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(viewPos.z);\n#endif\n\n${$n("vertexInputs.uv")}\n\n#ifdef UV1\n#ifdef MESH_UV2\n vertexOutputs.vUV1 = vertexInputs.uv2;\n#else\n vertexOutputs.vUV1 = vertexInputs.uv;\n#endif\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;const Fn="textureSample(txColorTransform,txColorTransformSampler,colorTransformInput,uniforms.colorTransformSettings.yz).rgb",Rn=p.ShaderStore.IncludesShadersStoreWGSL.imageProcessingFunctions,Bn=Rn.includes(Fn);p.ShaderStore.IncludesShadersStoreWGSL.quarksImageProcessingFunctions=Bn?"\n#if defined(COLORGRADING) && !defined(COLORGRADING3D)\nfn quarksSampleTexture3D(colorTransform: texture_2d<f32>, colorTransformSampler: sampler, colorIn: vec3f, sampler3dSetting: vec2f) -> vec3f {\n let sliceSize = 2.0 * sampler3dSetting.x;\n#ifdef SAMPLER3DGREENDEPTH\n let sliceContinuous = (colorIn.g - sampler3dSetting.x) * sampler3dSetting.y;\n var sliceUV = colorIn.rb;\n#else\n let sliceContinuous = (colorIn.b - sampler3dSetting.x) * sampler3dSetting.y;\n var sliceUV = colorIn.rg;\n#endif\n let sliceInteger = floor(sliceContinuous);\n let sliceFraction = sliceContinuous - sliceInteger;\n sliceUV.x = sliceUV.x * sliceSize + sliceInteger * sliceSize;\n let slice0Color = textureSample(colorTransform, colorTransformSampler, clamp(sliceUV, vec2f(0.0), vec2f(1.0)));\n let slice1Color = textureSample(colorTransform, colorTransformSampler, clamp(sliceUV + vec2f(sliceSize, 0.0), vec2f(0.0), vec2f(1.0)));\n let result = mix(slice0Color.rgb, slice1Color.rgb, sliceFraction);\n#ifdef SAMPLER3DBGRMAP\n return result.rgb;\n#else\n return result.bgr;\n#endif\n}\n#endif\n"+Rn.replace(Fn,"quarksSampleTexture3D(txColorTransform,txColorTransformSampler,colorTransformInput,uniforms.colorTransformSettings.yz)"):Rn;const Un="\n#if defined(IMAGEPROCESSING) || defined(IMAGEPROCESSINGPOSTPROCESS)\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#endif\n";const Ln="\n#if defined(IMAGEPROCESSING) || defined(IMAGEPROCESSINGPOSTPROCESS)\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<quarksImageProcessingFunctions>\n#endif\n";function Dn(t){return`${function(t){return`\n#if defined(IMAGEPROCESSINGPOSTPROCESS) && !defined(BLEND_MULTIPLY)\n ${t}.rgb = toLinearSpace(${t}.rgb);\n#elif defined(IMAGEPROCESSING)\n ${t}.rgb = toLinearSpace(${t}.rgb);\n ${t} = applyImageProcessing(${t});\n#endif\n`}(t)}\n#if defined(BLEND_PREMULTIPLY)\n ${t}.rgb *= ${t}.a;\n#elif defined(BLEND_MULTIPLY)\n ${t}.rgb = mix(vec3(1.0), ${t}.rgb, ${t}.a);\n#endif\n${function(t){return`\n#if defined(IMAGEPROCESSINGPOSTPROCESS) && defined(BLEND_MULTIPLY)\n ${t}.rgb = toLinearSpace(${t}.rgb);\n#endif\n`}(t)}`}function kn(t){return`${function(t){return`\n#if defined(IMAGEPROCESSINGPOSTPROCESS) && !defined(BLEND_MULTIPLY)\n ${t} = vec4f(toLinearSpaceVec3(${t}.rgb), ${t}.a);\n#elif defined(IMAGEPROCESSING)\n ${t} = applyImageProcessing(vec4f(toLinearSpaceVec3(${t}.rgb), ${t}.a));\n#endif\n`}(t)}\n#if defined(BLEND_PREMULTIPLY)\n ${t} = vec4f(${t}.rgb * ${t}.a, ${t}.a);\n#elif defined(BLEND_MULTIPLY)\n ${t} = vec4f(mix(vec3f(1.0), ${t}.rgb, ${t}.a), ${t}.a);\n#endif\n${function(t){return`\n#if defined(IMAGEPROCESSINGPOSTPROCESS) && defined(BLEND_MULTIPLY)\n ${t} = vec4f(toLinearSpaceVec3(${t}.rgb), ${t}.a);\n#endif\n`}(t)}`}const qn="\n#ifdef SOFT_PARTICLES\nuniform sampler2D depthTexture;\nuniform vec2 softParams;\nuniform vec4 projParams;\nvarying vec4 projPosition;\nvarying float linearDepth;\n\nfloat quarksSceneDepth(vec4 texel) {\n#ifdef SOFT_DEPTH_PACKED\n float d = dot(texel, vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0));\n#else\n float d = texel.r;\n#endif\n float denominator = projParams.z * d + projParams.w;\n float depth = abs(denominator) > 1e-8 ? abs((projParams.x * d + projParams.y) / denominator) : 0.0;\n // Nothing drawn there reads as infinitely far.\n return depth > 0.0 ? depth : 1e30;\n}\n#endif\n";function Gn(t){return`\n#ifdef SOFT_PARTICLES\n {\n vec2 softUV = 0.5 * (projPosition.xy / projPosition.w) + 0.5;\n float sceneDepth = quarksSceneDepth(texture2D(depthTexture, softUV));\n ${t}.a *= clamp(softParams.y * ((sceneDepth - softParams.x) - linearDepth), 0.0, 1.0);\n }\n#endif\n`}const Jn="\n#ifdef SOFT_PARTICLES\nvar depthTextureSampler: sampler;\nvar depthTexture: texture_2d<f32>;\nuniform softParams: vec2f;\nuniform projParams: vec4f;\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n\nfn quarksSceneDepth(texel: vec4f) -> f32 {\n#ifdef SOFT_DEPTH_PACKED\n let d = dot(texel, vec4f(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0));\n#else\n let d = texel.r;\n#endif\n let denominator = uniforms.projParams.z * d + uniforms.projParams.w;\n let depth = select(0.0, abs((uniforms.projParams.x * d + uniforms.projParams.y) / denominator), abs(denominator) > 1e-8);\n // Nothing drawn there reads as infinitely far.\n return select(1e30, depth, depth > 0.0);\n}\n#endif\n";function Wn(t){return`\n#ifdef SOFT_PARTICLES\n {\n let softUV = 0.5 * (fragmentInputs.projPosition.xy / fragmentInputs.projPosition.w) + 0.5;\n let sceneDepth = quarksSceneDepth(textureSample(depthTexture, depthTextureSampler, softUV));\n ${t}.a *= clamp(uniforms.softParams.y * ((sceneDepth - uniforms.softParams.x) - fragmentInputs.linearDepth), 0.0, 1.0);\n }\n#endif\n`}const jn="\n#ifdef MAP_TRANSFORM\nuniform vec4 mapTransform;\n#endif\n#ifdef UV_DISTORTION\nuniform sampler2D distortionMap;\nuniform vec4 distortionTransform;\nuniform float distortionStrength;\n#endif\n#ifdef GRADIENT_MAP\nuniform sampler2D gradientMap;\nuniform vec2 gradientMapRange;\nuniform vec4 gradientMapChannel;\n#endif\n#ifdef EROSION\nuniform vec2 erosionParams;\nuniform vec3 erosionEdgeColor;\n#ifdef EROSION_MASK\nuniform sampler2D erosionMask;\nuniform vec4 erosionMaskTransform;\n#endif\n\nvec4 quarksErode(vec4 color, float level, float mask) {\n float softness = erosionParams.x;\n float edgeWidth = erosionParams.y;\n // At level 1 the cut sits below the lowest mask value by the soft band\n // and the edge band, so nothing is cut and no edge shows; at level 0 above\n // the highest. The edge then grows in as the cut rises, rather than popping.\n float cut = mix(-(softness + edgeWidth), 1.0, 1.0 - level);\n float visible = smoothstep(cut, cut + softness, mask);\n if (edgeWidth > 0.0) {\n float edge = 1.0 - smoothstep(cut + softness, cut + softness + edgeWidth, mask);\n color.rgb += erosionEdgeColor * edge;\n }\n color.a *= visible;\n return color;\n}\n#endif\n";function Qn(t){return`\n vec4 baseColor = vColor;\n#if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n vec2 mapUV = vUV1 * mapTransform.xy + mapTransform.zw;\n#elif defined(MAP_TRANSFORM)\n vec2 mapUV = vUV * mapTransform.xy + mapTransform.zw;\n#else\n vec2 mapUV = vUV;\n#endif\n#ifdef UV_DISTORTION\n #ifdef UV_DISTORTION_UV1\n vec2 distortionUV = vUV1;\n #else\n vec2 distortionUV = vUV;\n #endif\n vec2 distortion = (texture2D(distortionMap, distortionUV * distortionTransform.xy + distortionTransform.zw).rg - 0.5) * 2.0 * distortionStrength;\n mapUV += distortion;\n#endif\n#ifdef EROSION\n float erosionLevel = baseColor.a;\n baseColor.a = 1.0;\n float erosionMaskValue = 1.0;\n#endif\n#if defined(USE_MAP) || defined(GRADIENT_MAP)\n#ifdef USE_MAP\n vec4 texColor = texture2D(map, mapUV);\n ${t?"#ifdef TILE_BLEND\n #if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n vec2 mapUV2 = mapUV;\n #else\n #ifdef MAP_TRANSFORM\n vec2 mapUV2 = vUV2 * mapTransform.xy + mapTransform.zw;\n #else\n vec2 mapUV2 = vUV2;\n #endif\n #ifdef UV_DISTORTION\n mapUV2 += distortion;\n #endif\n #endif\n vec4 texColor2 = texture2D(map, mapUV2);\n texColor = mix(texColor, texColor2, vTileBlend);\n #endif":""}\n#else\n // No map: the ramp is looked up at white, its far end.\n vec4 texColor = vec4(1.0);\n#endif\n #ifdef GRADIENT_MAP\n float rampAt = clamp(dot(texColor, gradientMapChannel), 0.0, 1.0);\n vec4 ramp = texture2D(gradientMap, vec2(mix(gradientMapRange.x, gradientMapRange.y, rampAt), 0.5));\n texColor = vec4(ramp.rgb, ramp.a * mix(texColor.a, 1.0, gradientMapChannel.a));\n #endif\n #ifdef EROSION\n erosionMaskValue = texColor.a;\n #endif\n baseColor *= texColor;\n#endif\n#ifdef EROSION\n #ifdef EROSION_MASK\n #ifdef EROSION_MASK_UV1\n vec2 erosionUV = vUV1;\n #else\n vec2 erosionUV = vUV;\n #endif\n erosionMaskValue = texture2D(erosionMask, erosionUV * erosionMaskTransform.xy + erosionMaskTransform.zw).r;\n #endif\n baseColor = quarksErode(baseColor, erosionLevel, erosionMaskValue);\n#endif\n`}const Hn="\n#ifdef MAP_TRANSFORM\nuniform mapTransform: vec4f;\n#endif\n#ifdef UV_DISTORTION\nvar distortionMapSampler: sampler;\nvar distortionMap: texture_2d<f32>;\nuniform distortionTransform: vec4f;\nuniform distortionStrength: f32;\n#endif\n#ifdef GRADIENT_MAP\nvar gradientMapSampler: sampler;\nvar gradientMap: texture_2d<f32>;\nuniform gradientMapRange: vec2f;\nuniform gradientMapChannel: vec4f;\n#endif\n#ifdef EROSION\nuniform erosionParams: vec2f;\nuniform erosionEdgeColor: vec3f;\n#ifdef EROSION_MASK\nvar erosionMaskSampler: sampler;\nvar erosionMask: texture_2d<f32>;\nuniform erosionMaskTransform: vec4f;\n#endif\n\nfn quarksErode(colorIn: vec4f, level: f32, mask: f32) -> vec4f {\n var color = colorIn;\n let softness = uniforms.erosionParams.x;\n let edgeWidth = uniforms.erosionParams.y;\n let cut = mix(-(softness + edgeWidth), 1.0, 1.0 - level);\n let visible = smoothstep(cut, cut + softness, mask);\n if (edgeWidth > 0.0) {\n let edge = 1.0 - smoothstep(cut + softness, cut + softness + edgeWidth, mask);\n color = vec4f(color.rgb + uniforms.erosionEdgeColor * edge, color.a);\n }\n color.a *= visible;\n return color;\n}\n#endif\n";function Yn(t){return`\n var baseColor = fragmentInputs.vColor;\n#if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n var mapUV = fragmentInputs.vUV1 * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n#elif defined(MAP_TRANSFORM)\n var mapUV = fragmentInputs.vUV * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n#else\n var mapUV = fragmentInputs.vUV;\n#endif\n#ifdef UV_DISTORTION\n #ifdef UV_DISTORTION_UV1\n let distortionUV = fragmentInputs.vUV1;\n #else\n let distortionUV = fragmentInputs.vUV;\n #endif\n let distortion = (textureSample(distortionMap, distortionMapSampler, distortionUV * uniforms.distortionTransform.xy + uniforms.distortionTransform.zw).rg - 0.5) * 2.0 * uniforms.distortionStrength;\n mapUV += distortion;\n#endif\n#ifdef EROSION\n let erosionLevel = baseColor.a;\n baseColor.a = 1.0;\n var erosionMaskValue = 1.0;\n#endif\n#if defined(USE_MAP) || defined(GRADIENT_MAP)\n#ifdef USE_MAP\n var texColor = textureSample(map, mapSampler, mapUV);\n ${t?"#ifdef TILE_BLEND\n #if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n let mapUV2 = mapUV;\n #else\n #ifdef MAP_TRANSFORM\n var mapUV2 = fragmentInputs.vUV2 * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n #else\n var mapUV2 = fragmentInputs.vUV2;\n #endif\n #ifdef UV_DISTORTION\n mapUV2 += distortion;\n #endif\n #endif\n let texColor2 = textureSample(map, mapSampler, mapUV2);\n texColor = mix(texColor, texColor2, fragmentInputs.vTileBlend);\n #endif":""}\n#else\n // No map: the ramp is looked up at white, its far end.\n var texColor = vec4f(1.0);\n#endif\n #ifdef GRADIENT_MAP\n let rampAt = clamp(dot(texColor, uniforms.gradientMapChannel), 0.0, 1.0);\n let ramp = textureSample(gradientMap, gradientMapSampler, vec2f(mix(uniforms.gradientMapRange.x, uniforms.gradientMapRange.y, rampAt), 0.5));\n texColor = vec4f(ramp.rgb, ramp.a * mix(texColor.a, 1.0, uniforms.gradientMapChannel.a));\n #endif\n #ifdef EROSION\n erosionMaskValue = texColor.a;\n #endif\n baseColor *= texColor;\n#endif\n#ifdef EROSION\n #ifdef EROSION_MASK\n #ifdef EROSION_MASK_UV1\n let erosionUV = fragmentInputs.vUV1;\n #else\n let erosionUV = fragmentInputs.vUV;\n #endif\n erosionMaskValue = textureSample(erosionMask, erosionMaskSampler, erosionUV * uniforms.erosionMaskTransform.xy + uniforms.erosionMaskTransform.zw).r;\n #endif\n baseColor = quarksErode(baseColor, erosionLevel, erosionMaskValue);\n#endif\n`}var Xn=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\n\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${wn}\n${Un}\n${qn}\n${jn}\nvoid main() {\n${Qn(!0)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${Mn("baseColor.rgb")}\n${Gn("baseColor")}\n${Dn("baseColor")}\n gl_FragColor = baseColor;\n}\n`,Zn=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\n\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${An}\n${Ln}\n${Jn}\n${Hn}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${Yn(!0)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n${Pn("baseColor")}\n${Wn("baseColor")}\n${kn("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,Kn=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\nvarying vec3 vNormal;\nvarying vec3 vWorldPos;\n\n#ifndef MESH_UNLIT\nuniform vec3 lightDirection;\nuniform vec3 lightColor;\nuniform vec3 ambientColor;\n#endif\n\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n#if defined(USE_ENVMAP_ATLAS) || defined(MESH_RIM)\nuniform vec3 eyePosition;\n#endif\n\n#ifdef MESH_RIM\nuniform vec3 rimColor;\nuniform vec2 rimParams;\n#endif\n\n// One 3×2 atlas (px py pz / nx ny nz). Avoids samplerCube and multi-face\n// sampler bindings that raise GL_INVALID_OPERATION on iOS WebKit.\n#ifdef USE_ENVMAP_ATLAS\nuniform sampler2D envAtlas;\nuniform float reflectionLevel;\n\nvec3 sampleEnvAtlas(vec3 r) {\n vec3 a = abs(r);\n vec2 localUV;\n float cellX;\n float cellY;\n // Atlas layout: +X +Y +Z on row 0, -X -Y -Z on row 1.\n if (a.x >= a.y && a.x >= a.z) {\n cellX = 0.0;\n if (r.x >= 0.0) {\n cellY = 0.0;\n localUV = vec2(-r.z, -r.y) / a.x * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(r.z, -r.y) / a.x * 0.5 + 0.5;\n }\n } else if (a.y >= a.z) {\n cellX = 1.0;\n if (r.y >= 0.0) {\n cellY = 0.0;\n localUV = vec2(r.x, r.z) / a.y * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(r.x, -r.z) / a.y * 0.5 + 0.5;\n }\n } else {\n cellX = 2.0;\n if (r.z >= 0.0) {\n cellY = 0.0;\n localUV = vec2(r.x, -r.y) / a.z * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(-r.x, -r.y) / a.z * 0.5 + 0.5;\n }\n }\n vec2 uv = (vec2(cellX, cellY) + clamp(localUV, 0.0, 1.0)) / vec2(3.0, 2.0);\n return texture2D(envAtlas, uv).rgb;\n}\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${wn}\n${Un}\n${qn}\n${jn}\nvoid main() {\n${Qn(!0)}\n // A back face lights, reflects and rims as the face the camera sees.\n vec3 N = normalize(vNormal) * (gl_FrontFacing ? 1.0 : -1.0);\n#ifdef MESH_UNLIT\n vec3 color = baseColor.rgb;\n#else\n vec3 L = normalize(-lightDirection);\n float NdotL = max(dot(N, L), 0.0);\n vec3 litColor = ambientColor + lightColor * NdotL;\n\n vec3 color = baseColor.rgb * litColor;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\n vec3 viewDir = normalize(vWorldPos - eyePosition);\n vec3 reflectionCoords = reflect(viewDir, N);\n color += sampleEnvAtlas(reflectionCoords) * reflectionLevel;\n#endif\n\n#ifdef MESH_RIM\n // Fresnel: strongest where the surface turns away from the camera.\n vec3 V = normalize(eyePosition - vWorldPos);\n float edgeTerm = pow(1.0 - abs(dot(N, V)), rimParams.x);\n #if defined(MESH_RIM_FADE)\n // Faces turned to the camera fade by the strength; edges stay.\n baseColor.a *= clamp(1.0 - rimParams.y * (1.0 - edgeTerm), 0.0, 1.0);\n #elif defined(MESH_RIM_MIX)\n color = mix(color, rimColor, clamp(edgeTerm * rimParams.y, 0.0, 1.0));\n #else\n color += rimColor * edgeTerm * rimParams.y;\n #endif\n#endif\n\n // After the rim, so a fade that empties a face can discard it.\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${Mn("color")}\n vec4 finalColor = vec4(color, baseColor.a);\n${Gn("finalColor")}\n${Dn("finalColor")}\n gl_FragColor = finalColor;\n}\n`,tr=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\nvarying vNormal: vec3f;\nvarying vWorldPos: vec3f;\n\n#ifndef MESH_UNLIT\nuniform lightDirection: vec3f;\nuniform lightColor: vec3f;\nuniform ambientColor: vec3f;\n#endif\n\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n#if defined(USE_ENVMAP_ATLAS) || defined(MESH_RIM)\nuniform eyePosition: vec3f;\n#endif\n\n#ifdef MESH_RIM\nuniform rimColor: vec3f;\nuniform rimParams: vec2f;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\nvar envAtlasSampler: sampler;\nvar envAtlas: texture_2d<f32>;\nuniform reflectionLevel: f32;\n\nfn sampleEnvAtlas(r: vec3f) -> vec3f {\n let a = abs(r);\n var localUV: vec2f;\n var cellX: f32;\n var cellY: f32;\n if (a.x >= a.y && a.x >= a.z) {\n cellX = 0.0;\n if (r.x >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(-r.z, -r.y) / a.x * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(r.z, -r.y) / a.x * 0.5 + 0.5;\n }\n } else if (a.y >= a.z) {\n cellX = 1.0;\n if (r.y >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(r.x, r.z) / a.y * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(r.x, -r.z) / a.y * 0.5 + 0.5;\n }\n } else {\n cellX = 2.0;\n if (r.z >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(r.x, -r.y) / a.z * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(-r.x, -r.y) / a.z * 0.5 + 0.5;\n }\n }\n let uv = (vec2f(cellX, cellY) + clamp(localUV, vec2f(0.0), vec2f(1.0))) / vec2f(3.0, 2.0);\n return textureSample(envAtlas, envAtlasSampler, uv).rgb;\n}\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${An}\n${Ln}\n${Jn}\n${Hn}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${Yn(!0)}\n // A back face lights, reflects and rims as the face the camera sees.\n let N = normalize(fragmentInputs.vNormal) * select(-1.0, 1.0, fragmentInputs.frontFacing);\n#ifdef MESH_UNLIT\n var color = baseColor.rgb;\n#else\n let L = normalize(-uniforms.lightDirection);\n let NdotL = max(dot(N, L), 0.0);\n let litColor = uniforms.ambientColor + uniforms.lightColor * NdotL;\n\n var color = baseColor.rgb * litColor;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\n let viewDir = normalize(fragmentInputs.vWorldPos - uniforms.eyePosition);\n let reflectionCoords = reflect(viewDir, N);\n color += sampleEnvAtlas(reflectionCoords) * uniforms.reflectionLevel;\n#endif\n\n#ifdef MESH_RIM\n // Fresnel: strongest where the surface turns away from the camera.\n let V = normalize(uniforms.eyePosition - fragmentInputs.vWorldPos);\n let edgeTerm = pow(1.0 - abs(dot(N, V)), uniforms.rimParams.x);\n #if defined(MESH_RIM_FADE)\n // Faces turned to the camera fade by the strength; edges stay.\n baseColor.a *= clamp(1.0 - uniforms.rimParams.y * (1.0 - edgeTerm), 0.0, 1.0);\n #elif defined(MESH_RIM_MIX)\n color = mix(color, uniforms.rimColor, clamp(edgeTerm * uniforms.rimParams.y, 0.0, 1.0));\n #else\n color += uniforms.rimColor * edgeTerm * uniforms.rimParams.y;\n #endif\n#endif\n\n // After the rim, so a fade that empties a face can discard it.\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n var finalColor = vec4f(color, baseColor.a);\n\n${Pn("finalColor")}\n${Wn("finalColor")}\n${kn("finalColor")}\n fragmentOutputs.color = finalColor;\n}\n`,er=`\n// Per-vertex attributes\nattribute vec3 position;\nattribute vec2 uv;\n\n// Per-instance attributes\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute float rotation;\nattribute float uvTile;\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${Vn}\n\n#ifdef PIVOT\n// Quad offset in particle-size units: xy in the quad's plane, z toward the camera.\nuniform vec3 pivot;\n#endif\n\n// Varyings\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vec2 vUV1;\n#endif\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform vec2 sizeLimits;\n#endif\n${Sn}\nvoid main() {\n float c = cos(rotation);\n float s = sin(rotation);\n\n#ifdef SIZE_LIMITS\n // The particle's size on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n vec4 limitCenter = view * world * vec4(offset, 1.0);\n float limitDepth = abs(projection[2][3]) > 0.0 ? abs(limitCenter.z) : 1.0;\n float screenSize = max(abs(size.x), abs(size.y)) * projection[1][1] / (2.0 * limitDepth);\n float sizeScale = screenSize > 0.0 ? clamp(screenSize, sizeLimits.x, sizeLimits.y) / screenSize : 1.0;\n vec3 limitedSize = size * sizeScale;\n#else\n vec3 limitedSize = size;\n#endif\n // A negative size mirrors the quad, which is how flipped particles arrive.\n vec2 alignedPosition = position.xy * limitedSize.xy;\n#ifdef PIVOT\n // The pivot turns with the particle but is not mirrored with it.\n alignedPosition += pivot.xy * abs(limitedSize.xy);\n#endif\n vec2 rotatedPosition;\n rotatedPosition.x = c * alignedPosition.x - s * alignedPosition.y;\n rotatedPosition.y = s * alignedPosition.x + c * alignedPosition.y;\n\n#ifdef HORIZONTAL\n vec4 mvPosition = world * vec4(offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.z -= rotatedPosition.y;\n#ifdef PIVOT\n mvPosition.y += pivot.z * abs(limitedSize.x);\n#endif\n mvPosition = view * mvPosition;\n#elif defined(VERTICAL)\n vec4 mvPosition = world * vec4(offset, 1.0);\n mvPosition.y += rotatedPosition.y;\n mvPosition = view * mvPosition;\n mvPosition.x += rotatedPosition.x;\n#else\n vec4 mvPosition = view * world * vec4(offset, 1.0);\n mvPosition.xy += rotatedPosition;\n#endif\n#ifdef PIVOT\n#ifndef HORIZONTAL\n // Toward the camera along its view axis, whichever way the view space\n // faces: anything in front of the camera has the sign of the far side.\n mvPosition.z -= sign(mvPosition.z) * pivot.z * abs(limitedSize.x);\n#endif\n#endif\n\n gl_Position = projection * mvPosition;\n${bn("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(mvPosition.z);\n#endif\n\n${En("uv")}\n\n#ifdef UV1\n vUV1 = uv;\n#endif\n vColor = color;\n}\n`,sr=`\n// Per-vertex attributes\nattribute position: vec3f;\nattribute uv: vec2f;\n\n// Per-instance attributes\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: f32;\nattribute uvTile: f32;\n\n// Uniforms\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${Cn}\n\n#ifdef PIVOT\n// Quad offset in particle-size units: xy in the quad's plane, z toward the camera.\nuniform pivot: vec3f;\n#endif\n\n// Varyings\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vUV1: vec2f;\n#endif\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform sizeLimits: vec2f;\n#endif\n${zn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let c = cos(vertexInputs.rotation);\n let s = sin(vertexInputs.rotation);\n\n#ifdef SIZE_LIMITS\n // The particle's size on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n let limitCenter = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n let limitDepth = select(1.0, abs(limitCenter.z), abs(uniforms.projection[2][3]) > 0.0);\n let screenSize = max(abs(vertexInputs.size.x), abs(vertexInputs.size.y)) * uniforms.projection[1][1] / (2.0 * limitDepth);\n let sizeScale = select(1.0, clamp(screenSize, uniforms.sizeLimits.x, uniforms.sizeLimits.y) / screenSize, screenSize > 0.0);\n let limitedSize = vertexInputs.size * sizeScale;\n#else\n let limitedSize = vertexInputs.size;\n#endif\n // A negative size mirrors the quad, which is how flipped particles arrive.\n var alignedPosition = vertexInputs.position.xy * limitedSize.xy;\n#ifdef PIVOT\n // The pivot turns with the particle but is not mirrored with it.\n alignedPosition += uniforms.pivot.xy * abs(limitedSize.xy);\n#endif\n let rotatedPosition = vec2f(\n c * alignedPosition.x - s * alignedPosition.y,\n s * alignedPosition.x + c * alignedPosition.y);\n\n#ifdef HORIZONTAL\n var mvPosition = uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.z -= rotatedPosition.y;\n#ifdef PIVOT\n mvPosition.y += uniforms.pivot.z * abs(limitedSize.x);\n#endif\n mvPosition = uniforms.view * mvPosition;\n#elif defined(VERTICAL)\n var mvPosition = uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.y += rotatedPosition.y;\n mvPosition = uniforms.view * mvPosition;\n mvPosition.x += rotatedPosition.x;\n#else\n var mvPosition = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.y += rotatedPosition.y;\n#endif\n#ifdef PIVOT\n#ifndef HORIZONTAL\n // Toward the camera along its view axis, whichever way the view space\n // faces: anything in front of the camera has the sign of the far side.\n mvPosition.z -= sign(mvPosition.z) * uniforms.pivot.z * abs(limitedSize.x);\n#endif\n#endif\n\n let clipPosition = uniforms.projection * mvPosition;\n vertexOutputs.position = clipPosition;\n${_n("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(mvPosition.z);\n#endif\n\n${$n("vertexInputs.uv")}\n\n#ifdef UV1\n vertexOutputs.vUV1 = vertexInputs.uv;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`,ir=`\n// Per-vertex attributes\nattribute vec3 position;\nattribute vec2 uv;\n\n// Per-instance attributes\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute float rotation;\nattribute float uvTile;\nattribute vec4 velocity;\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${Vn}\n\n#ifdef PIVOT\n// Streak offset in particle-size units: x from head to tail, y across.\nuniform vec3 pivot;\n#endif\n\n// Varyings\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vec2 vUV1;\n#endif\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform vec2 sizeLimits;\n#endif\n\n${Sn}\nvoid main() {\n float lengthFactor = velocity.w;\n // A flipped particle arrives with a negative size: the streak keeps its\n // extent and mirrors its texture instead (see quadUV below).\n float avgSize = (abs(size.x) + abs(size.y)) * 0.5;\n vec4 mvPosition = view * world * vec4(offset, 1.0);\n vec3 viewVelocity = mat3(view * world) * velocity.xyz;\n float vlength = length(viewVelocity);\n // Stretch direction is the velocity direction; only a genuinely motionless particle has none.\n // Deriving it via normalize keeps the stretch aligned even when the speed contribution is ~0\n // (e.g. a speed factor of 0), instead of collapsing the whole burst onto a fixed screen axis.\n vec3 vdir = vlength > 0.000001 ? viewVelocity / vlength : vec3(0.0, 0.0, 1.0);\n // Seen straight along its length a streak has no side to face; any will do.\n vec3 sideRaw = cross(mvPosition.xyz, vdir);\n vec3 side = dot(sideRaw, sideRaw) > 1e-12 ? normalize(sideRaw) : vec3(1.0, 0.0, 0.0);\n#ifdef SIZE_LIMITS\n // The streak's width on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n float limitDepth = abs(projection[2][3]) > 0.0 ? abs(mvPosition.z) : 1.0;\n float screenSize = avgSize * projection[1][1] / (2.0 * limitDepth);\n if (screenSize > 0.0) {\n avgSize *= clamp(screenSize, sizeLimits.x, sizeLimits.y) / screenSize;\n }\n#endif\n mvPosition.xyz += position.y * side * avgSize;\n#ifdef BEAM\n // The vector runs from the particle to the beam's end: the quad spans it\n // exactly, U from the particle (0) to the end (1), as wide as the size.\n mvPosition.xyz += (position.x + 0.5) * viewVelocity;\n#else\n // Equivalent to viewVelocity * (1.0 + lengthFactor / vlength) for moving particles, but the\n // size-based term (vdir * lengthFactor) survives when the velocity contribution vanishes.\n mvPosition.xyz -= (position.x + 0.5) * (viewVelocity + vdir * lengthFactor) * avgSize;\n#endif\n#ifdef PIVOT\n // In particle-size units along the quad's own axes: x from head to tail, y across.\n mvPosition.xyz += (pivot.y * side - pivot.x * vdir) * avgSize;\n#endif\n gl_Position = projection * mvPosition;\n${bn("mvPosition.xyz")}\n vec2 quadUV = vec2(size.x < 0.0 ? 1.0 - uv.x : uv.x, size.y < 0.0 ? 1.0 - uv.y : uv.y);\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(mvPosition.z);\n#endif\n\n${En("quadUV")}\n\n#ifdef UV1\n vUV1 = quadUV;\n#endif\n vColor = color;\n}\n`,nr=`\n// Per-vertex attributes\nattribute position: vec3f;\nattribute uv: vec2f;\n\n// Per-instance attributes\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: f32;\nattribute uvTile: f32;\nattribute velocity: vec4f;\n\n// Uniforms\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${Cn}\n\n#ifdef PIVOT\n// Streak offset in particle-size units: x from head to tail, y across.\nuniform pivot: vec3f;\n#endif\n\n// Varyings\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vUV1: vec2f;\n#endif\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform sizeLimits: vec2f;\n#endif\n\n${zn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let lengthFactor = vertexInputs.velocity.w;\n // A flipped particle arrives with a negative size: the streak keeps its\n // extent and mirrors its texture instead (see quadUV below).\n var avgSize = (abs(vertexInputs.size.x) + abs(vertexInputs.size.y)) * 0.5;\n var mvPosition = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n let viewWorld = uniforms.view * uniforms.world;\n let viewWorld3 = mat3x3f(viewWorld[0].xyz, viewWorld[1].xyz, viewWorld[2].xyz);\n let viewVelocity = viewWorld3 * vertexInputs.velocity.xyz;\n let vlength = length(viewVelocity);\n // Stretch direction is the velocity direction; only a genuinely motionless particle has none.\n // Deriving it via normalize keeps the stretch aligned even when the speed contribution is ~0\n // (e.g. a speed factor of 0), instead of collapsing the whole burst onto a fixed screen axis.\n var vdir = vec3f(0.0, 0.0, 1.0);\n if (vlength > 0.000001) {\n vdir = viewVelocity / vlength;\n }\n // Seen straight along its length a streak has no side to face; any will do.\n let sideRaw = cross(mvPosition.xyz, vdir);\n var side = vec3f(1.0, 0.0, 0.0);\n if (dot(sideRaw, sideRaw) > 1e-12) {\n side = normalize(sideRaw);\n }\n#ifdef SIZE_LIMITS\n // The streak's width on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n let limitDepth = select(1.0, abs(mvPosition.z), abs(uniforms.projection[2][3]) > 0.0);\n let screenSize = avgSize * uniforms.projection[1][1] / (2.0 * limitDepth);\n if (screenSize > 0.0) {\n avgSize *= clamp(screenSize, uniforms.sizeLimits.x, uniforms.sizeLimits.y) / screenSize;\n }\n#endif\n let widthOffset = vertexInputs.position.y * side * avgSize;\n // Equivalent to viewVelocity * (1.0 + lengthFactor / vlength) for moving particles, but the\n // size-based term (vdir * lengthFactor) survives when the velocity contribution vanishes.\n#ifdef BEAM\n // The vector runs from the particle to the beam's end: the quad spans it\n // exactly, U from the particle (0) to the end (1), as wide as the size.\n var stretched = mvPosition.xyz + widthOffset + (vertexInputs.position.x + 0.5) * viewVelocity;\n#else\n let lengthOffset = (vertexInputs.position.x + 0.5) * (viewVelocity + vdir * lengthFactor) * avgSize;\n var stretched = mvPosition.xyz + widthOffset - lengthOffset;\n#endif\n#ifdef PIVOT\n // In particle-size units along the quad's own axes: x from head to tail, y across.\n stretched += (uniforms.pivot.y * side - uniforms.pivot.x * vdir) * avgSize;\n#endif\n mvPosition.x = stretched.x;\n mvPosition.y = stretched.y;\n mvPosition.z = stretched.z;\n\n let clipPosition = uniforms.projection * mvPosition;\n vertexOutputs.position = clipPosition;\n${_n("mvPosition.xyz")}\n let quadUV = select(vertexInputs.uv, 1.0 - vertexInputs.uv, vertexInputs.size.xy < vec2f(0.0));\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(mvPosition.z);\n#endif\n\n${$n("quadUV")}\n\n#ifdef UV1\n vertexOutputs.vUV1 = quadUV;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`,rr=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${wn}\n${Un}\n${qn}\n${jn}\nvoid main() {\n${Qn(!1)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${Mn("baseColor.rgb")}\n${Gn("baseColor")}\n${Dn("baseColor")}\n gl_FragColor = baseColor;\n}\n`,or=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${An}\n${Ln}\n${Jn}\n${Hn}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${Yn(!1)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n${Pn("baseColor")}\n${Wn("baseColor")}\n${kn("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,ar=`\nattribute vec3 position;\nattribute vec3 previous;\nattribute vec3 next;\nattribute float side;\nattribute float width;\nattribute vec2 uv;\nattribute vec4 color;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// Along the trail and across it, without the sheet's cell (UV channel 1).\nattribute vec2 uv2;\nvarying vec2 vUV1;\n#endif\n\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n// The unit tangent of a segment, or zero for a segment of no length.\nvec3 trailDirection(vec3 d) {\n float l = dot(d, d);\n return l > 1e-12 ? d * inversesqrt(l) : vec3(0.0);\n}\n\n// The direction a ribbon point is widened along, in view space: across the trail's tangent and\n// the line of sight, as Unity's View alignment and Niagara's ribbon facing do. Stays finite at\n// repeated points, at a hairpin and for a segment pointing at the camera.\nvec3 trailSide(vec3 previousPoint, vec3 point, vec3 nextPoint) {\n vec3 incoming = trailDirection(point - previousPoint);\n vec3 outgoing = trailDirection(nextPoint - point);\n vec3 tangent = incoming + outgoing;\n if (dot(tangent, tangent) < 1e-6) {\n // A hairpin turns the two directions against each other: face the way it now goes.\n tangent = dot(outgoing, outgoing) > 0.0 ? outgoing : incoming;\n }\n // The line of sight: to the point for a perspective camera, the view axis for an orthographic one.\n vec3 sight = projection[3][3] > 0.5 ? vec3(0.0, 0.0, 1.0) : point;\n vec3 side = cross(tangent, sight);\n if (dot(side, side) < 1e-12) {\n side = cross(tangent, vec3(0.0, 0.0, 1.0));\n }\n if (dot(side, side) < 1e-12) {\n side = vec3(1.0, 0.0, 0.0);\n }\n return normalize(side);\n}\n\n${Sn}\nvoid main() {\n vec3 point = (view * vec4(position, 1.0)).xyz;\n // A swept trail lays its vertices out on the CPU and gives them no width.\n if (width > 0.0) {\n vec3 previousPoint = (view * vec4(previous, 1.0)).xyz;\n vec3 nextPoint = (view * vec4(next, 1.0)).xyz;\n point += trailSide(previousPoint, point, nextPoint) * (0.5 * width * side);\n }\n gl_Position = projection * vec4(point, 1.0);\n${bn("point")}\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(point.z);\n#endif\n vUV = uv;\n#ifdef UV1\n vUV1 = uv2;\n#endif\n vColor = color;\n}\n`,hr=`\nattribute position: vec3f;\nattribute previous: vec3f;\nattribute next: vec3f;\nattribute side: f32;\nattribute width: f32;\nattribute uv: vec2f;\nattribute color: vec4f;\n\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// Along the trail and across it, without the sheet's cell (UV channel 1).\nattribute uv2: vec2f;\nvarying vUV1: vec2f;\n#endif\n\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n// The unit tangent of a segment, or zero for a segment of no length.\nfn trailDirection(d: vec3f) -> vec3f {\n let l = dot(d, d);\n return select(vec3f(0.0), d * inverseSqrt(max(l, 1e-24)), l > 1e-12);\n}\n\n// The direction a ribbon point is widened along, in view space: across the trail's tangent and\n// the line of sight, as Unity's View alignment and Niagara's ribbon facing do. Stays finite at\n// repeated points, at a hairpin and for a segment pointing at the camera.\nfn trailSide(previousPoint: vec3f, point: vec3f, nextPoint: vec3f) -> vec3f {\n let incoming = trailDirection(point - previousPoint);\n let outgoing = trailDirection(nextPoint - point);\n var tangent = incoming + outgoing;\n if (dot(tangent, tangent) < 1e-6) {\n // A hairpin turns the two directions against each other: face the way it now goes.\n tangent = select(incoming, outgoing, dot(outgoing, outgoing) > 0.0);\n }\n // The line of sight: to the point for a perspective camera, the view axis for an orthographic one.\n let sight = select(point, vec3f(0.0, 0.0, 1.0), uniforms.projection[3][3] > 0.5);\n var side = cross(tangent, sight);\n if (dot(side, side) < 1e-12) {\n side = cross(tangent, vec3f(0.0, 0.0, 1.0));\n }\n if (dot(side, side) < 1e-12) {\n side = vec3f(1.0, 0.0, 0.0);\n }\n return normalize(side);\n}\n\n${zn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n var point = (uniforms.view * vec4f(vertexInputs.position, 1.0)).xyz;\n // A swept trail lays its vertices out on the CPU and gives them no width.\n if (vertexInputs.width > 0.0) {\n let previousPoint = (uniforms.view * vec4f(vertexInputs.previous, 1.0)).xyz;\n let nextPoint = (uniforms.view * vec4f(vertexInputs.next, 1.0)).xyz;\n point += trailSide(previousPoint, point, nextPoint) * (0.5 * vertexInputs.width * vertexInputs.side);\n }\n let clipPosition = uniforms.projection * vec4f(point, 1.0);\n vertexOutputs.position = clipPosition;\n${_n("point")}\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(point.z);\n#endif\n vertexOutputs.vUV = vertexInputs.uv;\n#ifdef UV1\n vertexOutputs.vUV1 = vertexInputs.uv2;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;const lr=["IMAGEPROCESSING","WHITEBALANCE","VIGNETTE","VIGNETTEBLENDMODEMULTIPLY","VIGNETTEBLENDMODEOPAQUE","TONEMAPPING","CONTRAST","COLORCURVES","COLORGRADING","COLORGRADING3D","SAMPLER3DGREENDEPTH","SAMPLER3DBGRMAP","DITHER","IMAGEPROCESSINGPOSTPROCESS","EXPOSURE","SKIPFINALCOLORCLAMP"],cr=["position","uv","offset","color","size","rotation","uvTile"],ur=["position","previous","next","side","width","uv","color"],dr=["vFogInfos","vFogColor"];function fr(t){return t===exports.RenderMode.StretchedBillBoard||t===exports.RenderMode.Beam}const pr=new Set([r.Constants.ALPHA_SUBTRACT,r.Constants.ALPHA_MAXIMIZED,r.Constants.ALPHA_ONEONE,r.Constants.ALPHA_PREMULTIPLIED,r.Constants.ALPHA_PREMULTIPLIED_PORTERDUFF,r.Constants.ALPHA_SCREENMODE,r.Constants.ALPHA_ONEONE_ONEONE,r.Constants.ALPHA_ALPHATOCOLOR,r.Constants.ALPHA_REVERSEONEMINUS,r.Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA,r.Constants.ALPHA_ONEONE_ONEZERO,r.Constants.ALPHA_EXCLUSION,r.Constants.ALPHA_MAX]),mr=new Set([r.Constants.ALPHA_MULTIPLY,r.Constants.ALPHA_MIN]),yr=new Set([r.Constants.ALPHA_COMBINE,r.Constants.ALPHA_PREMULTIPLIED,r.Constants.ALPHA_PREMULTIPLIED_PORTERDUFF,r.Constants.ALPHA_INTERPOLATE,r.Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA,r.Constants.ALPHA_LAYER_ACCUMULATE,r.Constants.ALPHA_REPLACE_COLOR]);function gr(t){const e=t.materialBlendMode;if(!t.materialTransparent||e===r.Constants.ALPHA_DISABLE)return{output:"straight",fogTarget:"color"};const s=pr.has(e)?"premultiply":mr.has(e)?"multiply":"straight";return{output:s,fogTarget:"multiply"===s?"white":yr.has(e)||"straight"===s&&e!==r.Constants.ALPHA_ADD?"color":"black"}}function vr(t,e){return t.renderMode===exports.RenderMode.Trail?function(t,e){const s=xr(t),i=[...ur],n=["view","projection",...dr],r=[];null!==t.texture&&(s.push("USE_MAP"),r.push("map"));Mr(t,s,n,r),wr(t,e,s,n,r),br(t,e,s,n,r),ki(t)&&i.push("uv2");return{name:"quarksTrail",vertex:{glsl:ar,wgsl:hr},fragment:{glsl:rr,wgsl:or},defines:s,attributes:i,uniforms:n,samplers:r}}(t,e):function(t,e){const s=t.renderMode,i=s===exports.RenderMode.Mesh,n=`quarksParticle_${s}`;let r,o;i?(r={glsl:In,wgsl:Nn},o={glsl:Kn,wgsl:tr}):fr(s)?(r={glsl:ir,wgsl:nr},o={glsl:Xn,wgsl:Zn}):(r={glsl:er,wgsl:sr},o={glsl:Xn,wgsl:Zn});const a=xr(t),h=[...cr],l=["world","view","projection",...dr],c=[];(function(t){return null!==t.texture||t.renderMode===exports.RenderMode.Mesh})(t)&&(a.push("USE_MAP"),c.push("map"));const u=i&&null!==t.reflectionAtlas&&e.envAtlasReady;u&&(a.push("USE_ENVMAP_ATLAS"),c.push("envAtlas"),l.push("reflectionLevel"));an(t)&&(a.push("UV_TILE"),l.push("tileCountX","tileCountY"),t.blendTiles&&a.push("TILE_BLEND"));wr(t,e,a,l,c),s===exports.RenderMode.VerticalBillBoard&&a.push("VERTICAL");s===exports.RenderMode.HorizontalBillBoard&&a.push("HORIZONTAL");s===exports.RenderMode.Beam&&a.push("BEAM");on(s)&&(t.pivot&&(a.push("PIVOT"),l.push("pivot")),hn(t)&&(a.push("SIZE_LIMITS"),l.push("sizeLimits")));const d=i&&"unlit"!==(t.lighting??"fixed");i&&!d&&a.push("MESH_UNLIT");d&&l.push("lightDirection","lightColor","ambientColor");const f=i?t.rim:void 0;f&&(a.push("MESH_RIM"),"fade"===f.mode?a.push("MESH_RIM_FADE"):"mix"===f.mode&&a.push("MESH_RIM_MIX"),l.push("rimColor","rimParams"));(u||f)&&l.push("eyePosition");Mr(t,a,l,c),br(t,e,a,l,c),i&&(h.push("normal"),ki(t)&&e.meshUV2&&(a.push("MESH_UV2"),h.push("uv2")));fr(s)&&h.push("velocity");return{name:n,vertex:r,fragment:o,defines:a,attributes:h,uniforms:l,samplers:c}}(t,e)}function xr(t){const{output:e,fogTarget:s}=gr(t),i=[];return"premultiply"===e?i.push("BLEND_PREMULTIPLY"):"multiply"===e&&i.push("BLEND_MULTIPLY"),t.applyFog&&(i.push("FOG"),"black"===s?i.push("FOG_ADDITIVE"):"white"===s&&i.push("FOG_MULTIPLY")),i}function Sr(t,e){const s={defines:[],uniforms:[],samplers:[]};if(!e||!function(t,e){return!(!1===t.applyImageProcessing||!e)&&(!!e.IMAGEPROCESSINGPOSTPROCESS||e.IMAGEPROCESSING&&"multiply"!==gr(t).output)}(t,e))return s;for(const t of lr){const i=e[t];"number"==typeof i?s.defines.push(`${t} ${i}`):i&&s.defines.push(t)}return f.PrepareUniformsForImageProcessing(s.uniforms,e),f.PrepareSamplersForImageProcessing(s.samplers,e),s}function br(t,e,s,i,n){const r=Sr(t,e.imageProcessing);s.push(...r.defines),i.push(...r.uniforms),n.push(...r.samplers)}function wr(t,e,s,i,n){t.softParticles&&null!==e.depth&&(s.push("SOFT_PARTICLES"),e.depth.packed&&s.push("SOFT_DEPTH_PACKED"),i.push("softParams","projParams"),n.push("depthTexture")),t.materialAlphaTest>0&&(s.push("USE_ALPHATEST"),i.push("alphaTest"))}function Mr(t,e,s,i){const{mapUV:n,uvDistortion:r,gradientMap:o,erosion:a}=t;ki(t)&&e.push("UV1"),n&&(e.push("MAP_TRANSFORM"),1===n.channel&&e.push("MAP_UV1"),s.push("mapTransform")),r&&(e.push("UV_DISTORTION"),1===r.mapUV.channel&&e.push("UV_DISTORTION_UV1"),i.push("distortionMap"),s.push("distortionTransform","distortionStrength")),o&&(e.push("GRADIENT_MAP"),i.push("gradientMap"),s.push("gradientMapRange","gradientMapChannel")),a&&(e.push("EROSION"),s.push("erosionParams","erosionEdgeColor"),a.mask&&(e.push("EROSION_MASK"),1===a.maskUV.channel&&e.push("EROSION_MASK_UV1"),i.push("erosionMask"),s.push("erosionMaskTransform")))}function zr(t){return t.isWebGPU?y.ShaderLanguage.WGSL:y.ShaderLanguage.GLSL}function _r(t,e,s,i){if(i===y.ShaderLanguage.WGSL)return p.ShaderStore.ShadersStoreWGSL[t+"VertexShader"]=e.wgsl,void(p.ShaderStore.ShadersStoreWGSL[t+"FragmentShader"]=s.wgsl);m.Effect.ShadersStore[t+"VertexShader"]=e.glsl,m.Effect.ShadersStore[t+"FragmentShader"]=s.glsl}class Ar{constructor(t,e,s=null){this.parentNode=null,this.visibleSystems=[],this.boundsMin_=new st,this.boundsMax_=new st,this.imageProcessingObserver=null,this.time=0,this.underusedFills=0,this.scene=e,this.depth=s,this.maxParticles=0,this.systems=new Set,this.settings=ln(t)}attachTo(t){this.parentNode=t,this.mesh.parent=t}configureMesh(){const t=this.mesh;t.alwaysSelectAsActiveMesh=!0,t.doNotSyncBoundingInfo=!0,t.parent=this.parentNode,t.freezeWorldMatrix(a.Matrix.Identity());const e=t.getWorldMatrix();t.computeWorldMatrix=()=>e,t.setBoundingInfo(new g.BoundingInfo(a.Vector3.Zero(),a.Vector3.Zero())),t.layerMask=this.settings.layerMask,t.renderingGroupId=this.settings.renderingGroupId,t.alphaIndex=this.settings.renderOrder,t.applyFog=!1,t.isPickable=!1,t.checkCollisions=!1,t.doNotSerialize=!0}refreshBoundingInfo(){const t=this.boundsMin_,e=this.boundsMax_;let s=1/0,i=1/0,n=1/0,r=-1/0,o=-1/0,a=-1/0,h=!1;const l=this.visibleSystems;for(let c=0;c<l.length;c++){const u=l[c];if(0!==u.particleNum&&"function"==typeof u.getWorldBounds){if(!u.getWorldBounds(t,e))return void(this.mesh.alwaysSelectAsActiveMesh=!0);h=!0,t.x<s&&(s=t.x),t.y<i&&(i=t.y),t.z<n&&(n=t.z),e.x>r&&(r=e.x),e.y>o&&(o=e.y),e.z>a&&(a=e.z)}}if(!h)return;const c=this.mesh.getBoundingInfo(),u=c.minimum,d=c.maximum;u.x===s&&u.y===i&&u.z===n&&d.x===r&&d.y===o&&d.z===a||(u.set(s,i,n),d.set(r,o,a),c.reConstruct(u,d)),this.mesh.alwaysSelectAsActiveMesh=!1}static writeBound(t,e){e(t);const s=t.getEffect();s?.isReady()&&e(s)}bindFog(t){if(!this.settings.applyFog)return;const e=this.scene;t.onBindObservable.add(()=>{const s=t.getEffect();if(!s)return;const i=e.fogEnabled?e.fogMode:x.Scene.FOGMODE_NONE;s.setFloat4("vFogInfos",i,e.fogStart,e.fogEnd,e.fogDensity),s.setColor3("vFogColor",e.fogColor)})}imageProcessing(){if(!1===this.settings.applyImageProcessing)return null;const t={IMAGEPROCESSING:!1,WHITEBALANCE:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,EXPOSURE:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,SKIPFINALCOLORCLAMP:!1};return this.scene.imageProcessingConfiguration.prepareDefines(t),t}bindImageProcessing(t,e){if(this.releaseImageProcessing(),!1===this.settings.applyImageProcessing)return;const s=this.scene.imageProcessingConfiguration;let i=e,n=Sr(this.settings,i),r=n.defines.join("\n");const o=()=>{n.samplers.includes("txColorTransform")&&s.colorGradingTexture?t.setTexture("txColorTransform",s.colorGradingTexture):t.removeTexture("txColorTransform")};o(),this.imageProcessingObserver=s.onUpdateParameters.add(()=>{const e=this.imageProcessing(),s=Sr(this.settings,e),a=s.defines.join("\n");if(a!==r){const o=t.options;Pr(o.defines,n.defines,s.defines),Pr(o.uniforms,n.uniforms,s.uniforms),Pr(o.samplers,n.samplers,s.samplers),i=e,n=s,r=a}o()}),t.onBindObservable.add(()=>{if(!i?.IMAGEPROCESSING||i.IMAGEPROCESSINGPOSTPROCESS||0===n.defines.length)return;const e=t.getEffect();e&&s.bind(e)})}releaseImageProcessing(){this.imageProcessingObserver?.remove(),this.imageProcessingObserver=null}usesUV1(){return ki(this.settings)}bindSurface(t){const{mapUV:e,uvDistortion:s,gradientMap:i,erosion:n}=this.settings;if(s?.map&&t.setTexture("distortionMap",s.map),i?.ramp&&t.setTexture("gradientMap",i.ramp),n?.mask&&t.setTexture("erosionMask",n.mask),this.writeSurfaceParams(t),!(e||s||n?.mask||i))return;const r=t=>t-2*Math.floor(t/2),o=new a.Vector4,h=new a.Vector4,l=new a.Vector4,c=new a.Vector2(0,1),u=(t,e,s)=>s.set(t.tiling[0],t.tiling[1],t.offset[0]+r(t.scroll[0]*e),t.offset[1]+r(t.scroll[1]*e)),d=()=>{const e=this.time,s=t.getEffect(),{mapUV:i,uvDistortion:n,gradientMap:r,erosion:a}=this.settings;if(i&&(u(i,e,o),t.setVector4("mapTransform",o),s?.setVector4("mapTransform",o)),n&&(u(n.mapUV,e,h),t.setVector4("distortionTransform",h),s?.setVector4("distortionTransform",h)),a?.mask&&(u(a.maskUV,e,l),t.setVector4("erosionMaskTransform",l),s?.setVector4("erosionMaskTransform",l)),r?.ramp){const e=r.ramp.getSize().width,i=e>0?.5/e:0;c.set(i,1-i),t.setVector2("gradientMapRange",c),s?.setVector2("gradientMapRange",c)}};d(),t.onBindObservable.add(d)}writeSurfaceParams(t){const{uvDistortion:e,gradientMap:s,erosion:i}=this.settings;if(e?.map&&t.setFloat("distortionStrength",e.strength),s?.ramp){const[e,i,n,r]=Ii[s.channel];t.setVector4("gradientMapChannel",new a.Vector4(e,i,n,r))}i&&(t.setVector2("erosionParams",new a.Vector2(i.softness,i.edgeWidth)),t.setVector3("erosionEdgeColor",new a.Vector3(i.edgeColor[0],i.edgeColor[1],i.edgeColor[2])))}applyLiveSettings(t){Object.assign(this.settings,t);const e=this.mesh.material;e instanceof l.ShaderMaterial&&this.writeLiveUniforms(e)}writeLiveUniforms(t){this.writeSoftParams(t),this.writeSurfaceParams(t)}addSystem(t){this.systems.add(t)}removeSystem(t){this.systems.delete(t)}getVisibleSystems(){const t=this.visibleSystems;let e=0;for(const s of this.systems)s.emitter.visible&&!0!==s.culled&&(t[e++]=s);return t.length=e,t}applyDepthTexture(t){t instanceof v.BaseTexture&&(t={texture:t,encoding:"linear",packed:!1});const e=this.depth;if(this.depth=t,!this.settings.softParticles)return;if(!e!=!t||e?.packed!==t?.packed)return void this.rebuildMaterial();const s=this.mesh.material;t&&s instanceof l.ShaderMaterial&&s.setTexture("depthTexture",t.texture)}bindSoft(t){if(this.writeSoftParams(t),this.drawsSoft()){t.setTexture("depthTexture",this.depth.texture);const e=new a.Vector4(1,0,0,1);t.onBindObservable.add(()=>{const s=this.scene.activeCamera;s&&this.depth&&(yn(s,this.depth.encoding,e),Ar.writeBound(t,t=>t.setVector4("projParams",e)))})}}writeSoftParams(t){this.drawsSoft()&&t.setVector2("softParams",new a.Vector2(this.settings.softNearFade,1/Math.max(this.settings.softFarFade-this.settings.softNearFade,1e-4))),this.settings.materialAlphaTest>0&&t.setFloat("alphaTest",this.settings.materialAlphaTest)}drawsSoft(){return this.settings.softParticles&&null!==this.depth}applyMeshLighting(t){}fitBuffers(t){if(t>this.maxParticles)return this.underusedFills=0,void this.expandBuffers(t);this.maxParticles>this.initialCapacity&&t<this.maxParticles/4?++this.underusedFills>=Ar.SHRINK_AFTER_FILLS&&(this.underusedFills=0,this.maxParticles=Math.max(this.initialCapacity,this.maxParticles/2),this.resizeBuffers()):this.underusedFills=0}dispose(){this.releaseImageProcessing(),this.mesh.dispose()}}function Pr(t,e,s){for(const s of e){const e=t.lastIndexOf(s);-1!==e&&t.splice(e,1)}t.push(...s)}Ar.SHRINK_AFTER_FILLS=300;class Or extends Ar{static whiteTexture(t){let e=Or.whiteTextureByScene.get(t);if(!e){e=c.RawTexture.CreateRGBATexture(new Uint8Array([255,255,255,255]),1,1,t),e.name="quarksMeshWhite",Or.whiteTextureByScene.set(t,e);const s=e;e.onDisposeObservable.addOnce(()=>{Or.whiteTextureByScene.get(t)===s&&Or.whiteTextureByScene.delete(t)})}return e}constructor(t,e,s=null){super(t,e,s),this.shaderMaterial=null,this.cancelAtlasRebuild=null,this.disposed=!1,this.fixedLightDirection=new a.Vector3,this.fixedLightColor=new a.Vector3,this.fixedAmbientColor=new a.Vector3,this.warnedUV2=!1,this.initialCapacity=1e3,this.gatherScratch=[],this.vector_=new st,this.vector2_=new st,this.vector3_=new st,this.quaternion_=new et,this.quaternion2_=new et,this.quaternion3_=new et,this.quaternion4_=new et,this.quaternion5_=new et,this.rotationMat_=new vt,this.rotationMat2_=new vt,this.clearedInstanceUploaded=!1,this.beamEnd_=new st,this.storeFixedLighting(Ti()),this.maxParticles=this.initialCapacity,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh?.dispose(),this.mesh=new u.Mesh("spriteBatch",this.scene),this.configureMesh();const t=new d.VertexData;t.positions=this.settings.instancingGeometry,t.indices=this.settings.instancingIndices;const e=this.settings.instancingGeometry.length/3,s=this.settings.instancingUVs;s&&s.length>=2*e?t.uvs=s:t.uvs=new Float32Array(2*e),this.meshUV2()&&(t.uvs2=this.settings.instancingUVs2),this.settings.instancingNormals&&(t.normals=this.settings.instancingNormals),t.applyToMesh(this.mesh,!1),this.buildExpandableBuffers()}meshUV2(){const t=this.settings.instancingUVs2;if(this.settings.renderMode!==exports.RenderMode.Mesh||!t||!this.usesUV1())return!1;const e=this.settings.instancingGeometry.length/3*2;return t.length===e||(this.warnedUV2||(this.warnedUV2=!0,console.warn(`[babylon.quarks] instancingUVs2 has ${t.length} values for ${e/2} vertices (two per vertex expected); UV channel 1 reads the first UV set instead.`)),!1)}disposeExpandableBuffers(){this.offsetVB?.dispose(),this.colorVB?.dispose(),this.sizeVB?.dispose(),this.uvTileVB?.dispose(),this.rotationVB?.dispose(),this.velocityVB?.dispose(),this.velocityVB=void 0,this.velocityBuffer=void 0}buildExpandableBuffers(){const e=this.scene.getEngine();this.offsetBuffer=new Float32Array(3*this.maxParticles),this.offsetVB=new t.VertexBuffer(e,this.offsetBuffer,"offset",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.offsetVB),this.colorBuffer=new Float32Array(4*this.maxParticles),this.colorVB=new t.VertexBuffer(e,this.colorBuffer,"color",!0,!1,4,!0),this.mesh.setVerticesBuffer(this.colorVB),this.sizeBuffer=new Float32Array(3*this.maxParticles),this.sizeVB=new t.VertexBuffer(e,this.sizeBuffer,"size",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.sizeVB),this.uvTileBuffer=new Float32Array(this.maxParticles),this.uvTileVB=new t.VertexBuffer(e,this.uvTileBuffer,"uvTile",!0,!1,1,!0),this.mesh.setVerticesBuffer(this.uvTileVB),this.settings.renderMode===exports.RenderMode.Mesh?(this.rotationBuffer=new Float32Array(4*this.maxParticles),this.rotationVB=new t.VertexBuffer(e,this.rotationBuffer,"rotation",!0,!1,4,!0)):(this.rotationBuffer=new Float32Array(this.maxParticles),this.rotationVB=new t.VertexBuffer(e,this.rotationBuffer,"rotation",!0,!1,1,!0)),this.mesh.setVerticesBuffer(this.rotationVB),fr(this.settings.renderMode)&&(this.velocityBuffer=new Float32Array(4*this.maxParticles),this.velocityVB=new t.VertexBuffer(e,this.velocityBuffer,"velocity",!0,!1,4,!0),this.mesh.setVerticesBuffer(this.velocityVB)),this.mesh.forcedInstanceCount=0,this.mesh.doNotSyncBoundingInfo=!0}expandBuffers(t){for(;t>=this.maxParticles;)this.maxParticles*=2;this.resizeBuffers()}resizeBuffers(){this.disposeExpandableBuffers(),this.buildExpandableBuffers(),this.sortScratch=void 0,this.gatherScratch.length=0}sizeLimits(){const{minParticleSize:t,maxParticleSize:e}=this.settings;return on(this.settings.renderMode)&&hn(this.settings)?new a.Vector2(Math.max(0,t),Math.min(e,1e9)):null}sortInstances(t,e,s){if(t<2)return;const i=this.sortScratch??(this.sortScratch=new xn(this.maxParticles));i.ensure(t);const n=i.keys,r=this.settings.sortMode;if("distance"===r){const e=this.scene.activeCameras?.[0]??this.scene.activeCamera;if(!e)return;const s=e.globalPosition,r=s.x,o=s.y,a=s.z,h=this.offsetBuffer;for(let e=0,s=0;e<t;e++,s+=3){const t=h[s]-r,l=h[s+1]-o,c=h[s+2]-a;n[e]=i.floatKey(t*t+l*l+c*c,!0)}}else{const e="youngestInFront"===r,s=this.visibleSystems;let o=0;for(let t=0;t<s.length;t++){const r=s[t],a=r.particleNum,h=r.store;if(0===a)continue;if(void 0===h){const t=r.particles;for(let s=0;s<a;s++)n[o++]=i.floatKey(t[s].age,e);continue}const l=h.scalars,c=Be.SCALAR_STRIDE;for(let t=0,s=Be.AGE;t<a;t++,s+=c)n[o++]=i.floatKey(l[s],e)}if(o!==t)return}const o=function(t,e){const s=t.keys,i=t.counts;let n=t.orderA,r=t.orderB;for(let t=0;t<e;t++)n[t]=t;for(let t=0;t<32;t+=11){i.fill(0);for(let r=0;r<e;r++)i[s[n[r]]>>>t&vn]++;if(i[s[n[0]]>>>t&vn]===e)continue;let o=0;for(let t=0;t<gn;t++){const e=i[t];i[t]=o,o+=e}for(let o=0;o<e;o++){const e=n[o];r[i[s[e]>>>t&vn]++]=e}const a=n;n=r,r=a}return n}(i,t);this.offsetBuffer=this.gatherInto(0,this.offsetBuffer,o,t,3),this.sizeBuffer=this.gatherInto(1,this.sizeBuffer,o,t,3),this.colorBuffer=this.gatherInto(2,this.colorBuffer,o,t,4),this.uvTileBuffer=this.gatherInto(3,this.uvTileBuffer,o,t,1),this.rotationBuffer=this.gatherInto(4,this.rotationBuffer,o,t,e?4:1),s&&this.velocityBuffer&&(this.velocityBuffer=this.gatherInto(5,this.velocityBuffer,o,t,4))}gatherInto(t,e,s,i,n){let r=this.gatherScratch[t];return void 0!==r&&r.length===e.length||(r=new Float32Array(e.length)),function(t,e,s,i,n){if(1===n)for(let n=0;n<i;n++)e[n]=t[s[n]];else if(3===n)for(let n=0,r=0;n<i;n++,r+=3){const i=3*s[n];e[r]=t[i],e[r+1]=t[i+1],e[r+2]=t[i+2]}else if(4===n)for(let n=0,r=0;n<i;n++,r+=4){const i=4*s[n];e[r]=t[i],e[r+1]=t[i+1],e[r+2]=t[i+2],e[r+3]=t[i+3]}else for(let r=0;r<i;r++){const i=s[r]*n,o=r*n;for(let s=0;s<n;s++)e[o+s]=t[i+s]}}(e,r,s,i,n),this.gatherScratch[t]=e,r}rebuildMaterial(){const t=this.settings.renderMode===exports.RenderMode.Mesh,e=this.settings.texture??(t?Or.whiteTexture(this.scene):null),s=this.settings.reflectionAtlas,i=t&&!!s&&!s.isReady();if(this.cancelAtlasRebuild?.(),this.cancelAtlasRebuild=null,i&&s){const t=s.onLoadObservable;if(t){const e=t.addOnce(()=>{this.cancelAtlasRebuild=null,this.disposed||this.rebuildMaterial()});this.cancelAtlasRebuild=()=>t.remove(e)}}const n=this.usesEnvAtlas(),o=this.imageProcessing(),h=vr(this.settings,{depth:this.depth,envAtlasReady:n,meshUV2:this.meshUV2(),imageProcessing:o}),{defines:c,attributes:u,uniforms:d,samplers:f}=h,p=h.name,m=this.settings.lighting??"fixed",y=t&&"unlit"!==m,g=t?this.settings.rim:void 0,v=n||!!g,x=zr(this.scene.getEngine());_r(p,h.vertex,h.fragment,x);const S=new l.ShaderMaterial(p,this.scene,{vertex:p,fragment:p},{attributes:u,uniforms:d,samplers:f,defines:c,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:x});if(e&&S.setTexture("map",e),n&&s&&S.setTexture("envAtlas",s),v){const t=new a.Vector3;S.setVector3("eyePosition",t),S.onBindObservable.add(()=>{const e=this.scene.activeCamera;e&&(t.copyFrom(e.globalPosition),Ar.writeBound(S,e=>e.setVector3("eyePosition",t)))})}if(an(this.settings)&&(S.setFloat("tileCountX",this.settings.uTileCount),S.setFloat("tileCountY",this.settings.vTileCount)),this.bindSoft(S),this.writeSpriteParams(S,n),y&&(this.writeFixedLighting(S),"scene"===m)){const t=new a.Vector3,e=new a.Vector3,s=new a.Vector3;S.onBindObservable.add(()=>{const i=Or.readSceneLight(this.scene,t,e,s);Ar.writeBound(S,n=>i?n.setVector3("lightDirection",t).setVector3("lightColor",e).setVector3("ambientColor",s):this.writeFixedLighting(n))})}this.bindFog(S),this.bindImageProcessing(S,o),this.bindSurface(S),S.backFaceCulling="both"!==this.settings.renderFace,S.cullBackFaces="back"!==this.settings.renderFace,this.settings.materialTransparent?S.alphaMode=this.settings.materialBlendMode:S.alphaMode=r.Constants.ALPHA_DISABLE,S.needDepthPrePass=this.settings.materialDepthWrite&&this.settings.materialTransparent,S.forceDepthWrite=this.settings.materialDepthWrite,S.disableDepthWrite=!this.settings.materialDepthWrite,S.depthFunction=this.settings.materialDepthTest?0:r.Constants.ALWAYS,this.shaderMaterial?.dispose(!1,!1),this.mesh.material=S,this.shaderMaterial=S}writeSpriteParams(t,e){e&&t.setFloat("reflectionLevel",this.settings.reflectionLevel);const s=this.settings.renderMode===exports.RenderMode.Mesh?this.settings.rim:void 0;s&&(t.setVector3("rimColor",new a.Vector3(s.color[0],s.color[1],s.color[2])),t.setVector2("rimParams",new a.Vector2(s.power,s.strength)));const i=on(this.settings.renderMode)?this.settings.pivot:void 0;i&&t.setVector3("pivot",new a.Vector3(i.x,i.y,i.z));const n=this.sizeLimits();n&&t.setVector2("sizeLimits",n)}writeLiveUniforms(t){super.writeLiveUniforms(t),this.writeSpriteParams(t,this.usesEnvAtlas())}usesEnvAtlas(){const t=this.settings.reflectionAtlas;return this.settings.renderMode===exports.RenderMode.Mesh&&!!t&&t.isReady()}applyMeshLighting(t){this.storeFixedLighting(t);const e=this.shaderMaterial;null!==e&&this.settings.renderMode===exports.RenderMode.Mesh&&"unlit"!==this.settings.lighting&&this.writeFixedLighting(e)}storeFixedLighting(t){this.fixedLightDirection.copyFrom(t.direction),this.fixedLightColor.set(t.color.r,t.color.g,t.color.b),this.fixedAmbientColor.set(t.ambient.r,t.ambient.g,t.ambient.b)}writeFixedLighting(t){t.setVector3("lightDirection",this.fixedLightDirection),t.setVector3("lightColor",this.fixedLightColor),t.setVector3("ambientColor",this.fixedAmbientColor)}static readSceneLight(t,e,s,i){const n=t.lights;for(let r=0;r<n.length;r++){const o=n[r],a=o.getClassName();if("DirectionalLight"!==a&&"HemisphericLight"!==a||!o.isEnabled())continue;const h=o.intensity,l=o.diffuse,c=t.ambientColor;s.set(l.r*h,l.g*h,l.b*h),i.set(c.r,c.g,c.b);const u=o.direction;if("DirectionalLight"===a)e.copyFrom(u);else{e.copyFrom(u).scaleInPlace(-1);const t=o.groundColor;t&&(i.x+=t.r*h,i.y+=t.g*h,i.z+=t.b*h)}return!0}return!1}update(){let t=0,e=0;const s=this.settings.renderMode,i=s===exports.RenderMode.Mesh,n=s===exports.RenderMode.StretchedBillBoard,r=s===exports.RenderMode.Beam,o=n||r,a=on(s),h=this.getVisibleSystems();for(let t=0;t<h.length;t++)e+=h[t].particleNum;this.fitBuffers(e);for(let e=0;e<h.length;e++){const s=h[e],o=s.particleNum;if(0===o)continue;const l=s.particles,c=this.quaternion2_,u=this.vector2_,d=this.vector3_,f=s.worldSpace,p=s.emitter.matrixWorld;if(i&&!f)p.decompose(u,c,d);else{const t=p.elements;d.set(Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),Math.sqrt(t[4]*t[4]+t[5]*t[5]+t[6]*t[6]),Math.sqrt(t[8]*t[8]+t[9]*t[9]+t[10]*t[10]))}n&&!f&&this.rotationMat_.setFromMatrix4(p);const m=Math.abs(d.x),y=Math.abs(d.y),g=Math.abs(d.z),v=n?s.rendererEmitterSettings:void 0,x=void 0===v||0===v.speedFactor?.001:v.speedFactor,S=v?.lengthFactor??0,b=s.store,w=void 0!==b,M=void 0!==b&&!0!==s.onlyUsedByOther,z=s.simulationResidual??0,_=0===z?0:z/(s.simulationStep??z);w&&(0!==_&&o>0&&b.previousColor!==b.color?Or.continueColor(this.colorBuffer,4*t,b,o,_):this.colorBuffer.set(b.color.subarray(0,4*o),4*t));let A=!1;if(void 0!==b&&f)0!==_&&o>0?Or.extrapolate(this.offsetBuffer,3*t,b,o,_):this.offsetBuffer.set(b.position.subarray(0,3*o),3*t),0!==_&&o>0&&b.previousSize!==b.size?Or.continueVector3(this.sizeBuffer,3*t,b.size,b.previousSize,o,_):this.sizeBuffer.set(b.size.subarray(0,3*o),3*t),A=!0;else if(M&&o>0){const e=3*t,s=e+3*o,i=this.offsetBuffer;0!==_?Or.extrapolate(i,e,b,o,_):i.set(b.position.subarray(0,3*o),e);const n=p.elements,r=n[0],a=n[1],h=n[2],l=n[3],c=n[4],u=n[5],d=n[6],f=n[7],v=n[8],x=n[9],S=n[10],w=n[11],M=n[12],z=n[13],P=n[14],O=n[15];for(let t=e;t<s;t+=3){const e=i[t],s=i[t+1],n=i[t+2],o=1/(l*e+f*s+w*n+O);i[t]=(r*e+c*s+v*n+M)*o,i[t+1]=(a*e+u*s+x*n+z)*o,i[t+2]=(h*e+d*s+S*n+P)*o}const T=this.sizeBuffer;0!==_&&b.previousSize!==b.size?Or.continueVector3(T,e,b.size,b.previousSize,o,_):T.set(b.size.subarray(0,3*o),e);for(let t=e;t<s;t+=3)T[t]*=m,T[t+1]*=y,T[t+2]*=g;A=!0}const P=t;if(M&&!i){const e=b;this.uvTileBuffer.set(e.uvTile.subarray(0,o),P);const s=this.rotationBuffer;if(s.set(e.rotation.subarray(0,o),P),0!==z){const t=e.angularVelocity;for(let e=0;e<o;e++)s[P+e]+=t[e]*z}n&&this.velocityBuffer&&Or.writeVelocities(this.velocityBuffer,4*P,e,o,_,f?null:this.rotationMat_,x,S),t+=o}else if(M&&b.rotationQuaternion.length>0){const e=b;this.uvTileBuffer.set(e.uvTile.subarray(0,o),P),Or.writeQuaternions(this.rotationBuffer,4*P,e,o,_,f?null:c),t+=o}else for(let e=0;e<o;e++,t++){const s=l[e];if(i){let e=s.rotation;const i=s.angularVelocity;let n;if(0!==_&&i instanceof et&&(e=this.quaternion4_.copy(e).multiply(Or.partialTurn(i,_,this.quaternion5_))),f)n=e;else{let t;t=s.parentMatrix?this.quaternion3_.setFromRotationMatrix(s.parentMatrix):c,n=this.quaternion_,n.copy(t).multiply(e)}const r=4*t;this.rotationBuffer[r]=n.x,this.rotationBuffer[r+1]=n.y,this.rotationBuffer[r+2]=n.z,this.rotationBuffer[r+3]=n.w}else{const e=s.angularVelocity;this.rotationBuffer[t]=s.rotation+("number"==typeof e?e*z:0)}if(!A){const e=s.position,i=s.previousPosition;let n=e.x+(e.x-i.x)*_,r=e.y+(e.y-i.y)*_,o=e.z+(e.z-i.z)*_;if(!f){const t=(s.parentMatrix??p).elements,e=1/(t[3]*n+t[7]*r+t[11]*o+t[15]),i=(t[0]*n+t[4]*r+t[8]*o+t[12])*e,a=(t[1]*n+t[5]*r+t[9]*o+t[13])*e;o=(t[2]*n+t[6]*r+t[10]*o+t[14])*e,n=i,r=a}const a=3*t;this.offsetBuffer[a]=n,this.offsetBuffer[a+1]=r,this.offsetBuffer[a+2]=o;const h=s.size,l=3*t;f||s.parentMatrix?(this.sizeBuffer[l]=h.x,this.sizeBuffer[l+1]=h.y,this.sizeBuffer[l+2]=h.z):(this.sizeBuffer[l]=h.x*m,this.sizeBuffer[l+1]=h.y*y,this.sizeBuffer[l+2]=h.z*g)}if(!w){const e=s.color,i=4*t;this.colorBuffer[i]=e.x,this.colorBuffer[i+1]=e.y,this.colorBuffer[i+2]=e.z,this.colorBuffer[i+3]=e.w}if(this.uvTileBuffer[t]=s.uvTile,n&&this.velocityBuffer){const e=s.velocity,i=s.previousVelocity,n=e.x+(e.x-i.x)*_,r=e.y+(e.y-i.y)*_,o=e.z+(e.z-i.z)*_,a=this.vector_;a.set(n,r,o),f||(s.parentMatrix?(this.rotationMat2_.setFromMatrix4(s.parentMatrix),a.applyMatrix3(this.rotationMat2_)):a.applyMatrix3(this.rotationMat_));const h=4*t;this.velocityBuffer[h]=a.x*x,this.velocityBuffer[h+1]=a.y*x,this.velocityBuffer[h+2]=a.z*x,this.velocityBuffer[h+3]=S}}const O=s.tint;void 0!==O&&t>P&&Or.applyTint(this.colorBuffer,4*P,t-P,O),a&&void 0!==s.flip&&(void 0!==b?Or.applyFlip(this.sizeBuffer,3*P,b.flip,o):Or.applyFlipFromParticles(this.sizeBuffer,3*P,l,o)),r&&this.velocityBuffer&&this.writeBeams(s,P,t-P)}this.mesh.forcedInstanceCount=t,this.refreshBoundingInfo(),0!==t?(this.clearedInstanceUploaded=!1,"none"!==this.settings.sortMode&&this.sortInstances(t,i,o),this.offsetVB.update(this.offsetBuffer.subarray(0,3*t)),this.sizeVB.update(this.sizeBuffer.subarray(0,3*t)),this.colorVB.update(this.colorBuffer.subarray(0,4*t)),this.uvTileVB.update(this.uvTileBuffer.subarray(0,t)),this.rotationVB.update(this.rotationBuffer.subarray(0,i?4*t:t)),o&&this.velocityVB&&this.velocityBuffer&&this.velocityVB.update(this.velocityBuffer.subarray(0,4*t))):this.clearedInstanceUploaded||(this.uploadClearedInstance(i,o),this.clearedInstanceUploaded=!0)}writeBeams(t,e,s){const i=this.velocityBuffer,n=this.offsetBuffer,r=this.beamEnd_,o="function"==typeof t.getBeamEnd&&t.getBeamEnd(r);for(let t=e;t<e+s;t++){const e=3*t,s=4*t;i[s]=o?r.x-n[e]:0,i[s+1]=o?r.y-n[e+1]:0,i[s+2]=o?r.z-n[e+2]:0,i[s+3]=0}}static applyTint(t,e,s,i){for(let n=0,r=e;n<s;n++,r+=4)t[r]*=i.x,t[r+1]*=i.y,t[r+2]*=i.z,t[r+3]*=i.w}static applyFlip(t,e,s,i){for(let n=0,r=e;n<i;n++,r+=3){const e=s[n];0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static applyFlipFromParticles(t,e,s,i){for(let n=0,r=e;n<i;n++,r+=3){const e=s[n].flip;0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static writeQuaternions(t,e,s,i,n,r){const o=s.rotationQuaternion,a=s.angularVelocityQuaternion,h=null!==r,l=h?r.x:0,c=h?r.y:0,u=h?r.z:0,d=h?r.w:1;for(let s=0,r=0,f=e;s<i;s++,r+=4,f+=4){let e=o[r],s=o[r+1],i=o[r+2],p=o[r+3];if(0!==n){const t=a[r]*n,o=a[r+1]*n,h=a[r+2]*n,l=1+(a[r+3]-1)*n,c=1/Math.sqrt(t*t+o*o+h*h+l*l),u=t*c,d=o*c,f=h*c,m=l*c,y=e*m+p*u+s*f-i*d,g=s*m+p*d+i*u-e*f,v=i*m+p*f+e*d-s*u;p=p*m-e*u-s*d-i*f,e=y,s=g,i=v}if(h){const t=l*p+d*e+c*i-u*s,n=c*p+d*s+u*e-l*i,r=u*p+d*i+l*s-c*e;p=d*p-l*e-c*s-u*i,e=t,s=n,i=r}t[f]=e,t[f+1]=s,t[f+2]=i,t[f+3]=p}}static writeVelocities(t,e,s,i,n,r,o,a){const h=s.velocity,l=s.previousVelocity.length>=3*i?s.previousVelocity:h,c=null!==r?r.elements:null;for(let s=0,r=0,u=e;s<i;s++,r+=3,u+=4){let e=h[r],s=h[r+1],i=h[r+2];if(0!==n&&(e+=(e-l[r])*n,s+=(s-l[r+1])*n,i+=(i-l[r+2])*n),null!==c){const t=c[0]*e+c[3]*s+c[6]*i,n=c[1]*e+c[4]*s+c[7]*i;i=c[2]*e+c[5]*s+c[8]*i,e=t,s=n}t[u]=e*o,t[u+1]=s*o,t[u+2]=i*o,t[u+3]=a}}static partialTurn(t,e,s){const i=t.x*e,n=t.y*e,r=t.z*e,o=1+(t.w-1)*e,a=1/Math.sqrt(i*i+n*n+r*r+o*o);return s.x=i*a,s.y=n*a,s.z=r*a,s.w=o*a,s}static continueVector3(t,e,s,i,n,r){for(let o=0,a=0;o<n;o++,a+=3){const n=s[a]+(s[a]-i[a])*r,o=s[a+1]+(s[a+1]-i[a+1])*r,h=s[a+2]+(s[a+2]-i[a+2])*r;t[e+a]=n>0?n:0,t[e+a+1]=o>0?o:0,t[e+a+2]=h>0?h:0}}static continueColor(t,e,s,i,n){const r=s.color,o=s.previousColor;for(let s=0,a=0;s<i;s++,a+=4){const s=r[a]+(r[a]-o[a])*n,i=r[a+1]+(r[a+1]-o[a+1])*n,h=r[a+2]+(r[a+2]-o[a+2])*n,l=r[a+3]+(r[a+3]-o[a+3])*n;t[e+a]=s>0?s:0,t[e+a+1]=i>0?i:0,t[e+a+2]=h>0?h:0,t[e+a+3]=l>0?l:0}}static extrapolate(t,e,s,i,n){const r=s.position,o=s.previousPosition;for(let s=0,a=0;s<i;s++,a+=3){const s=r[a],i=r[a+1],h=r[a+2];t[e+a]=s+(s-o[a])*n,t[e+a+1]=i+(i-o[a+1])*n,t[e+a+2]=h+(h-o[a+2])*n}}uploadClearedInstance(t,e){this.colorBuffer[3]=0,this.sizeBuffer[0]=0,this.sizeBuffer[1]=0,this.sizeBuffer[2]=0,this.colorVB.update(this.colorBuffer.subarray(0,4)),this.sizeVB.update(this.sizeBuffer.subarray(0,3)),this.offsetVB.update(this.offsetBuffer.subarray(0,3)),this.uvTileVB.update(this.uvTileBuffer.subarray(0,1)),t?this.rotationVB.update(this.rotationBuffer.subarray(0,4)):this.rotationVB.update(this.rotationBuffer.subarray(0,1)),e&&this.velocityVB&&this.velocityBuffer&&this.velocityVB.update(this.velocityBuffer.subarray(0,4))}dispose(){this.disposed=!0,this.cancelAtlasRebuild?.(),this.cancelAtlasRebuild=null,this.mesh.material&&this.mesh.material.dispose(),super.dispose()}}Or.whiteTextureByScene=new WeakMap;function Tr(t){const e=Math.round(Number(t?.tessellation)||0);return Math.min(16,Math.max(0,e))}function Vr(t){const e=Number(t?.curveTension)||0;return Math.min(1,Math.max(0,e))}const Er=["stretch","tile","distributePerSegment","repeatPerSegment"];function Cr(t){const e=t?.textureMode;return void 0!==e&&Er.includes(e)?e:"stretch"}function $r(t){const e=Number(t?.textureScale);return Number.isFinite(e)&&e>0?e:1}function Ir(t){const e=Number(t?.minVertexDistance);return Number.isFinite(e)&&e>0?e:0}function Nr(t){const e=Number(t?.lifetime);return Number.isFinite(e)&&e>0?e:1/0}class Fr{constructor(){this.position=new Float32Array(0),this.side=new Float32Array(0),this.size=new Float32Array(0),this.color=new Float32Array(0),this.distance=new Float32Array(0)}reserve(t){if(t>this.size.length){const e=Math.max(t,2*this.size.length,64);this.position=new Float32Array(3*e),this.side=new Float32Array(3*e),this.size=new Float32Array(e),this.color=new Float32Array(4*e),this.distance=new Float32Array(e)}return this}writePoint(t,e,s,i,n){const r=3*t;if(n){const t=1/(n[3]*e+n[7]*s+n[11]*i+n[15]);this.position[r]=(n[0]*e+n[4]*s+n[8]*i+n[12])*t,this.position[r+1]=(n[1]*e+n[5]*s+n[9]*i+n[13])*t,this.position[r+2]=(n[2]*e+n[6]*s+n[10]*i+n[14])*t}else this.position[r]=e,this.position[r+1]=s,this.position[r+2]=i}writeSide(t,e,s,i,n){const r=3*t;n?(this.side[r]=n[0]*e+n[4]*s+n[8]*i,this.side[r+1]=n[1]*e+n[5]*s+n[9]*i,this.side[r+2]=n[2]*e+n[6]*s+n[10]*i):(this.side[r]=e,this.side[r+1]=s,this.side[r+2]=i)}writeColor(t,e,s,i,n){const r=4*t;this.color[r]=e,this.color[r+1]=s,this.color[r+2]=i,this.color[r+3]=n}}function Rr(t,e,s){return Math.sqrt(Math.sqrt((t[s]-t[e])**2+(t[s+1]-t[e+1])**2+(t[s+2]-t[e+2])**2))}class Br extends Ar{constructor(t,e,s=null){super(t,e,s),this.uv1Buffer=null,this.drawsNothing=!1,this.initialCapacity=1024,this.vector2_=new st,this.vector3_=new st,this.quaternion_=new et,this.samples_=new Fr,this.curve_=new Fr,this.cutScratch_=new Fr,this.maxParticles=this.initialCapacity,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh?.dispose(),this.mesh=new u.Mesh("trailBatch",this.scene),this.configureMesh(),this.buildGeometryBuffers()}buildGeometryBuffers(){const e=this.maxParticles;this.positionBuffer=new Float32Array(3*e),this.previousBuffer=new Float32Array(3*e),this.nextBuffer=new Float32Array(3*e),this.uvBuffer=new Float32Array(2*e),this.uv1Buffer=this.usesUV1()?new Float32Array(2*e):null,this.sideBuffer=new Float32Array(e),this.widthBuffer=new Float32Array(e),this.colorBuffer=new Float32Array(4*e),this.indexBuffer=new Uint32Array(3*e);for(let t=0;t<this.sideBuffer.length;t+=2)this.sideBuffer[t]=1,this.sideBuffer[t+1]=-1;this.positionBuffer[0]=0,this.positionBuffer[1]=0,this.positionBuffer[2]=0,this.positionBuffer[3]=1,this.positionBuffer[4]=0,this.positionBuffer[5]=0,this.positionBuffer[6]=0,this.positionBuffer[7]=1,this.positionBuffer[8]=0,this.positionBuffer[9]=1,this.positionBuffer[10]=1,this.positionBuffer[11]=0,this.indexBuffer[0]=0,this.indexBuffer[1]=1,this.indexBuffer[2]=2,this.indexBuffer[3]=1,this.indexBuffer[4]=3,this.indexBuffer[5]=2,this.mesh.setVerticesData(t.VertexBuffer.PositionKind,this.positionBuffer,!0),this.mesh.setVerticesData(t.VertexBuffer.UVKind,this.uvBuffer,!0),this.uv1Buffer&&this.mesh.setVerticesData(t.VertexBuffer.UV2Kind,this.uv1Buffer,!0),this.mesh.setVerticesData(t.VertexBuffer.ColorKind,this.colorBuffer,!0,4),this.mesh.setIndices(this.indexBuffer,null,!0),this.drawsNothing=!1,this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.mesh.subMeshes[0].indexCount=6);const s=this.scene.getEngine();this.previousVB=new t.VertexBuffer(s,this.previousBuffer,"previous",!0,!1,3,!1),this.nextVB=new t.VertexBuffer(s,this.nextBuffer,"next",!0,!1,3,!1),this.sideVB=new t.VertexBuffer(s,this.sideBuffer,"side",!0,!1,1,!1),this.widthVB=new t.VertexBuffer(s,this.widthBuffer,"width",!0,!1,1,!1),this.mesh.setVerticesBuffer(this.previousVB),this.mesh.setVerticesBuffer(this.nextVB),this.mesh.setVerticesBuffer(this.sideVB),this.mesh.setVerticesBuffer(this.widthVB),this.mesh.subMeshes&&this.adoptMeshBounds()}expandBuffers(t){for(;t>=this.maxParticles;)this.maxParticles*=2;this.resizeBuffers()}resizeBuffers(){this.previousVB?.dispose(),this.nextVB?.dispose(),this.sideVB?.dispose(),this.widthVB?.dispose(),this.buildGeometryBuffers()}rebuildMaterial(){const t=this.imageProcessing(),e=vr(this.settings,{depth:this.depth,envAtlasReady:!1,meshUV2:!1,imageProcessing:t}),{defines:s,attributes:i,uniforms:n,samplers:o}=e,a=e.name,h=zr(this.scene.getEngine());_r(a,e.vertex,e.fragment,h);const c=new l.ShaderMaterial(a,this.scene,{vertex:a,fragment:a},{attributes:i,uniforms:n,samplers:o,defines:s,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:h});this.settings.texture&&c.setTexture("map",this.settings.texture),this.bindFog(c),this.bindImageProcessing(c,t),this.bindSoft(c),this.bindSurface(c),c.backFaceCulling=!1,this.settings.materialTransparent?c.alphaMode=this.settings.materialBlendMode:c.alphaMode=r.Constants.ALPHA_DISABLE,c.needDepthPrePass=this.settings.materialDepthWrite&&this.settings.materialTransparent,c.forceDepthWrite=this.settings.materialDepthWrite,c.disableDepthWrite=!this.settings.materialDepthWrite,c.depthFunction=this.settings.materialDepthTest?0:r.Constants.ALWAYS,this.mesh.material?.dispose(!1,!1),this.mesh.material=c}trailSamples(t){return this.samples_.reserve(t)}cutLastSegment(t,e,s,i,n){const r=e-1-s,o=this.cutScratch_.reserve(s+1);o.position.set(t.position.subarray(3*r,3*e)),o.side.set(t.side.subarray(3*r,3*e)),o.size.set(t.size.subarray(r,e)),o.color.set(t.color.subarray(4*r,4*e)),o.distance.set(t.distance.subarray(r,e));for(let e=1;e<=s;e++){const a=i*e,h=Math.min(s-1,Math.floor(a)),l=a-h,c=r+e;for(let e=0;e<3;e++)t.position[3*c+e]=o.position[3*h+e]*(1-l)+o.position[3*h+3+e]*l,n&&(t.side[3*c+e]=o.side[3*h+e]*(1-l)+o.side[3*h+3+e]*l);t.size[c]=o.size[h]*(1-l)+o.size[h+1]*l,t.distance[c]=o.distance[h]*(1-l)+o.distance[h+1]*l;for(let e=0;e<4;e++)t.color[4*c+e]=o.color[4*h+e]*(1-l)+o.color[4*h+4+e]*l}}tessellate(t,e,s,i,n,r){const o=this.curve_.reserve((s-1)*(i+1)+1),a=t.position,h=t.side,l=o.position,c=o.side,u=1-n;let d=0;for(let n=0;n+1<s;n++){const s=3*n,f=s+3;let p=0,m=0,y=0,g=0,v=0,x=0,S=s,b=f;if(n+1<e){S=3*(n>0?n-1:n),b=3*(n+2<e?n+2:n+1);const t=Rr(a,s,f);if(t>1e-6){const e=Rr(a,S,s),i=Rr(a,f,b);y=u,g=u,e>1e-6&&(p=u*t/e,m=-u*t/(e+t)),i>1e-6&&(v=-u*t/(t+i),x=u*t/i)}}const w=0===p&&0===m&&0===y&&0===g&&0===v&&0===x,M=r?Math.sqrt(h[s]*h[s]+h[s+1]*h[s+1]+h[s+2]*h[s+2]):0,z=r?Math.sqrt(h[f]*h[f]+h[f+1]*h[f+1]+h[f+2]*h[f+2]):0;for(let e=0;e<=i;e++,d++){const u=e/(i+1),_=u*u,A=_*u,P=w?1-u:2*A-3*_+1,O=A-2*_+u,T=w?u:-2*A+3*_,V=A-_,E=3*d;for(let t=0;t<3;t++){const e=a[s+t],i=a[f+t],n=p*(e-a[S+t])+m*(i-a[S+t])+y*(i-e),r=g*(i-e)+v*(a[b+t]-e)+x*(a[b+t]-i);l[E+t]=P*e+O*n+T*i+V*r}if(r){let t=0,e=0,i=0;for(let n=0;n<3;n++){const r=h[s+n],o=h[f+n],a=P*r+O*(p*(r-h[S+n])+m*(o-h[S+n])+y*(o-r))+T*o+V*(g*(o-r)+v*(h[b+n]-r)+x*(h[b+n]-o));0===n?t=a:1===n?e=a:i=a}let n=Math.sqrt(t*t+e*e+i*i);if(n<=1e-6*Math.max(M,z,1e-6)){const r=u<.5?s:f;t=h[r],e=h[r+1],i=h[r+2],n=u<.5?M:z}const r=n>0?(M+(z-M)*u)/n:0;c[E]=t*r,c[E+1]=e*r,c[E+2]=i*r}o.size[d]=t.size[n]+(t.size[n+1]-t.size[n])*u,o.distance[d]=t.distance[n]+(t.distance[n+1]-t.distance[n])*u;const C=4*n,$=4*d;for(let e=0;e<4;e++)o.color[$+e]=t.color[C+e]+(t.color[C+4+e]-t.color[C+e])*u}}const f=3*(s-1),p=3*d;for(let t=0;t<3;t++)l[p+t]=a[f+t],c[p+t]=h[f+t];o.size[d]=t.size[s-1],o.distance[d]=t.distance[s-1];for(let e=0;e<4;e++)o.color[4*d+e]=t.color[4*(s-1)+e];return o}writeSweptPair(t,e,s,i,n,r,o,a){const h=this.positionBuffer;h[t]=e+n*a,h[t+1]=s+r*a,h[t+2]=i+o*a,h[t+3]=e-n*a,h[t+4]=s-r*a,h[t+5]=i-o*a}static ensureWorldMatrix(t){const e=t.emitter;!e.computeWorldMatrix||e.isSynchronized&&e.isSynchronized()||e.computeWorldMatrix(!0)}update(){let t=0,e=0,s=0;const i=this.getVisibleSystems();for(let t=0;t<i.length;t++){const e=i[t],n=e.particles,r=Tr(e.rendererEmitterSettings);for(let t=0;t<e.particleNum;t++){const e=n[t].historyCount;0!==e&&(s+=2*(e*(r+1)+1))}}this.fitBuffers(s);for(let s=0;s<i.length;s++){const n=i[s],r=t;Br.ensureWorldMatrix(n);const o=this.quaternion_,a=this.vector2_,h=this.vector3_,l=n.emitter.matrixWorld;l.decompose(a,o,h);const c=n.particles,u=n.particleNum,d=this.settings.uTileCount,f=this.settings.vTileCount,p=1/d,m=1/f,y=n.worldSpace,g=(Math.abs(h.x)+Math.abs(h.y)+Math.abs(h.z))/3,v=n.rendererEmitterSettings,x=Boolean(v.uvFromHead),S=this.uv1Buffer,b=Boolean(v.colorFromParticle),w=y||Boolean(v.recordWorldSpace),M=v.sideAxis,z=v.followLocalOrigin?0:n.simulationResidual??0,_=0===z?0:z/(n.simulationStep??z),A=Math.abs(_)<1e-4?0:_,P=Tr(v),O=Vr(v),T=Cr(v),V="stretch"===T?0:"tile"===T?1:"repeatPerSegment"===T?3:2,E=$r(v),C=Ir(v)>0;for(let s=0;s<u;s++){const i=c[s],n=i.historyCount;if(0===n)continue;const r=i.historyCapacity,o=i.historyPositions,a=i.historySizes,h=i.historyDistances,u=i.historySides,v=void 0!==M&&u.length>=3*r,z=b?i.store.color:i.historyColors,_=4*i.storeIndex,{column:T,row:$}=On(i.uvTile,d,f),I=(i.parentMatrix??l).elements,N=y||i.parentMatrix?1:g,F=w||i.parentMatrix?1:g,R=i.age<i.life,B=R&&A>0,U=n+(B?1:0),L=this.trailSamples(U);let D=i.getHistoryIndex(0);for(let t=0;t<n;t++){const e=o;if(L.writePoint(t,e[3*D],e[3*D+1],e[3*D+2],w?null:I),v){const e=u;L.writeSide(t,e[3*D],e[3*D+1],e[3*D+2],w?null:I)}L.size[t]=a[D],L.distance[t]=h[D];const s=b?_:4*D;L.writeColor(t,z[s],z[s+1],z[s+2],z[s+3]),D=D+1===r?0:D+1}if(B){const t=i.previousPosition,e=i.position,s=n;let r=e.x+(e.x-t.x)*A,a=e.y+(e.y-t.y)*A,h=e.z+(e.z-t.z)*A;if(L.writePoint(s,r,a,h,y?null:I),w&&!y){const t=1/(I[3]*r+I[7]*a+I[11]*h+I[15]),e=(I[0]*r+I[4]*a+I[8]*h+I[12])*t,s=(I[1]*r+I[5]*a+I[9]*h+I[13])*t;h=(I[2]*r+I[6]*a+I[10]*h+I[14])*t,r=e,a=s}const l=3*i.getHistoryIndex(n-1),c=r-o[l],u=a-o[l+1],d=h-o[l+2];L.distance[s]=L.distance[s-1]+Math.sqrt(c*c+u*u+d*d),v&&L.writeSide(s,M.x,M.y,M.z,I),L.size[s]=L.size[s-1];const f=i.color;L.writeColor(s,f.x,f.y,f.z,f.w)}const k=P>0?this.tessellate(L,n,U,P,O,v):L,q=P>0?(U-1)*(P+1)+1:U,G=P+1,J=R&&A<0&&n>1;let W=1+A;if(J&&C){const t=k.distance,e=t[q-1]-t[q-1-G];if(e>1e-9){const t=i.previousPosition,s=i.position;let n=s.x-t.x,r=s.y-t.y,o=s.z-t.z;if(w&&!y){const t=I[0]*n+I[4]*r+I[8]*o,e=I[1]*n+I[5]*r+I[9]*o;o=I[2]*n+I[6]*r+I[10]*o,n=t,r=e}const a=Math.sqrt(n*n+r*r+o*o);W=1+A*Math.min(1,a/e)}}J&&this.cutLastSegment(k,q,G,W,v);const j=n-1+(B?A:J?W-1:0),Q=1/Math.max(.001,j),H=(U-2)*G,Y=k.position,X=k.distance,Z=X[0],K=X[q-1],tt=0===V&&K-Z>1e-6,et=1/Math.max(1e-6,K-Z),st=F*E,it=Math.floor(Z*st),nt=(f-$-1)*m,rt=(f-$)*m;for(let s=0;s<q;s++,t+=2){const i=3*s,r=s>0?i-3:i,o=s+1<q?i+3:i,a=Y[i],h=Y[i+1],l=Y[i+2],c=k.size[s],u=3*t;if(v){const e=k.side;this.writeSweptPair(u,a,h,l,e[i],e[i+1],e[i+2],.5*c),this.widthBuffer[t]=0,this.widthBuffer[t+1]=0}else this.positionBuffer[u]=a,this.positionBuffer[u+1]=h,this.positionBuffer[u+2]=l,this.positionBuffer[u+3]=a,this.positionBuffer[u+4]=h,this.positionBuffer[u+5]=l,this.widthBuffer[t]=c*N,this.widthBuffer[t+1]=c*N;this.previousBuffer[u]=Y[r],this.previousBuffer[u+1]=Y[r+1],this.previousBuffer[u+2]=Y[r+2],this.previousBuffer[u+3]=Y[r],this.previousBuffer[u+4]=Y[r+1],this.previousBuffer[u+5]=Y[r+2],this.nextBuffer[u]=Y[o],this.nextBuffer[u+1]=Y[o+1],this.nextBuffer[u+2]=Y[o+2],this.nextBuffer[u+3]=Y[o],this.nextBuffer[u+4]=Y[o+1],this.nextBuffer[u+5]=Y[o+2];const d=2*t;let f;if(tt){const t=(X[s]-Z)*et;f=(x?1-t:t)*E}else if(1===V)f=x?(K-X[s])*st:X[s]*st-it;else{let t=s/G;if(s>H&&(B||J)){const e=(s-H)/G;t=B?n-1+A*e:n-2+W*e}if(3!==V){const e=Math.min(1,t*Q);f=(x?1-e:e)*E}else f=(x?j-t:t)*E}const m=(f+T)*p;this.uvBuffer[d]=m,this.uvBuffer[d+1]=nt,this.uvBuffer[d+2]=m,this.uvBuffer[d+3]=rt,S&&(S[d]=f,S[d+1]=0,S[d+2]=f,S[d+3]=1);const y=k.color,g=4*s,b=4*t;this.colorBuffer[b]=y[g],this.colorBuffer[b+1]=y[g+1],this.colorBuffer[b+2]=y[g+2],this.colorBuffer[b+3]=y[g+3],this.colorBuffer[b+4]=y[g],this.colorBuffer[b+5]=y[g+1],this.colorBuffer[b+6]=y[g+2],this.colorBuffer[b+7]=y[g+3],s+1<q&&(this.indexBuffer[3*e]=t,this.indexBuffer[3*e+1]=t+1,this.indexBuffer[3*e+2]=t+2,e++,this.indexBuffer[3*e]=t+2,this.indexBuffer[3*e+1]=t+1,this.indexBuffer[3*e+2]=t+3,e++)}}const $=n.tint;if(void 0!==$){const e=this.colorBuffer;for(let s=4*r,i=4*t;s<i;s+=4)e[s]*=$.x,e[s+1]*=$.y,e[s+2]*=$.z,e[s+3]*=$.w}this.measureSystemBounds(n,r,t)}this.refreshBoundingInfo(),this.uploadGeometry(t,e)}measureSystemBounds(t,e,s){if(s<=e||"function"!=typeof t.setWorldBounds)return;const i=this.positionBuffer;let n=1/0,r=1/0,o=1/0,a=-1/0,h=-1/0,l=-1/0;for(let t=3*e,c=3*s;t<c;t+=3){const e=i[t],s=i[t+1],c=i[t+2];e<n&&(n=e),e>a&&(a=e),s<r&&(r=s),s>h&&(h=s),c<o&&(o=c),c>l&&(l=c)}const c=this.widthBuffer;let u=0;for(let t=e;t<s;t+=2){const e=c[t];e>u&&(u=e)}t.setWorldBounds(n,r,o,a,h,l,u)}uploadGeometry(e,s){const i=this.mesh.geometry,n=i?.getIndexBuffer();if(e>0&&s>0){this.mesh.updateVerticesData(t.VertexBuffer.PositionKind,this.positionBuffer.subarray(0,3*e)),this.mesh.updateVerticesData(t.VertexBuffer.UVKind,this.uvBuffer.subarray(0,2*e)),this.uv1Buffer&&this.mesh.updateVerticesData(t.VertexBuffer.UV2Kind,this.uv1Buffer.subarray(0,2*e)),n&&this.scene.getEngine().updateDynamicIndexBuffer(n,this.indexBuffer.subarray(0,3*s),0),this.previousVB.update(this.previousBuffer.subarray(0,3*e)),this.nextVB.update(this.nextBuffer.subarray(0,3*e)),this.widthVB.update(this.widthBuffer.subarray(0,e));const i=this.mesh.getVertexBuffer(t.VertexBuffer.ColorKind);i&&i.update(this.colorBuffer.subarray(0,4*e)),this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.mesh.subMeshes[0].indexCount=3*s,this.mesh.subMeshes[0].verticesCount=e),this.drawsNothing=!1}else this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.drawsNothing||(this.indexBuffer.fill(0,0,6),n&&this.scene.getEngine().updateDynamicIndexBuffer(n,this.indexBuffer.subarray(0,6),0),this.drawsNothing=!0),this.mesh.subMeshes[0].indexCount=6,this.mesh.subMeshes[0].verticesCount=1)}adoptMeshBounds(){const t=this.mesh.getBoundingInfo();for(const e of this.mesh.subMeshes)e.setBoundingInfo(t)}dispose(){this.mesh.material&&this.mesh.material.dispose(),super.dispose()}}class Ur extends n.TransformNode{get batches(){return this.batchList}get systemToBatchIndex(){return this.batchIndexOf}constructor(t,e){super(t,e),this.batchList=[],this.batchIndexOf=new Map,this.elapsed=0,this.depth=null,this.systems=[],this.orderedSystems=[],this.orderedSystemsStale=!0,this.batchEmptyFrames=[],this.adaptivePerformanceState={enabled:!1,targetFrameMs:16.7,minQuality:.35,maxQuality:1,decreaseStep:.08,increaseStep:.02,currentQuality:1,lastFrameCpuMs:0},this.lastAppliedQuality=Number.NaN,this.meshLighting=Ti(),this.cullingEnabled=!0,this.catchUpBudgetMs=2,this.simulationBudgetMs=1/0,this.cameraPlanes=[],this.cameraMasks=[],this.cameraCount=0,this.boundsMin=new st,this.boundsMax=new st}collectCameras(){var t;const e=this.getScene(),n=e.activeCameras,r=e.activeCamera,o=n&&n.length>0?n:r?[r]:[];for(let e=0;e<o.length;e++){const n=o[e];n.getViewMatrix(),n.getProjectionMatrix();const r=(t=this.cameraPlanes)[e]??(t[e]=[0,1,2,3,4,5].map(()=>new i.Plane(0,0,0,0)));s.Frustum.GetPlanesToRef(n.getTransformationMatrix(),r),this.cameraMasks[e]=n.layerMask}return this.cameraCount=o.length,o.length}isSystemInView(t){const e=this.boundsMin,s=this.boundsMax;if(!t.getWorldBounds(e,s))return!0;const i=t.layers.mask;for(let t=0;t<this.cameraCount;t++){if(0===(this.cameraMasks[t]&i))continue;const n=this.cameraPlanes[t];let r=!0;for(let t=0;t<6;t++){const i=n[t],o=i.normal,a=o.x>=0?s.x:e.x,h=o.y>=0?s.y:e.y,l=o.z>=0?s.z:e.z;if(o.x*a+o.y*h+o.z*l+i.d<0){r=!1;break}}if(r)return!0}return!1}static clamp(t,e,s){return Math.max(e,Math.min(s,t))}addSystem(t){if(this.isDisposed())throw new Error("BatchedRenderer.addSystem: the renderer has been disposed");const e=t;if(e.emitter.getScene()!==this.getScene())throw new Error("BatchedRenderer.addSystem: the system belongs to another scene");const s=e._renderer;void 0!==s&&s!==this&&s.deleteSystem(t),e._renderer=this,this.removeFromBatch(t),-1===this.systems.indexOf(t)&&(this.systems.push(t),this.orderedSystemsStale=!0),this.adaptivePerformanceState.enabled&&e.setQualityFactor(this.adaptivePerformanceState.currentQuality),this.assignToBatch(e)}assignToBatch(t){const e=t,s=t.getRendererSettings(),i=ln(s);for(let t=0;t<this.batchList.length;t++)if(dn(this.batchList[t].settings,i))return this.batchList[t].addSystem(e),void this.batchIndexOf.set(e,t);let n;const r=this.getScene();switch(s.renderMode){case exports.RenderMode.Trail:n=new Br(s,r,this.depth);break;case exports.RenderMode.Mesh:case exports.RenderMode.BillBoard:case exports.RenderMode.VerticalBillBoard:case exports.RenderMode.HorizontalBillBoard:case exports.RenderMode.StretchedBillBoard:case exports.RenderMode.Beam:n=new Or(s,r,this.depth);break;default:throw new Error(`Unsupported render mode: ${s.renderMode}`)}n.attachTo(this),n.applyMeshLighting(this.meshLighting),n.addSystem(e),this.batchList.push(n),this.batchEmptyFrames.push(0),this.batchIndexOf.set(e,this.batchList.length-1)}deleteSystem(t){const e=this.removeFromBatch(t),s=this.systems.indexOf(t);-1!==s&&(this.systems.splice(s,1),this.orderedSystemsStale=!0);const i=this.orderedSystems.indexOf(t);return-1!==i&&this.orderedSystems.splice(i,1),e}removeFromBatch(t){const e=this.batchIndexOf.get(t);return void 0!==e&&(this.batchList[e].removeSystem(t),this.batchIndexOf.delete(t),!0)}updateSystem(t){const e=this.batchIndexOf.get(t);if(void 0!==e){const s=this.batchList[e],i=ln(t.getRendererSettings());if(1===s.systems.size&&cn(s.settings,i)&&!this.batchList.some(t=>t!==s&&dn(t.settings,i)))return void s.applyLiveSettings(i)}this.removeFromBatch(t),this.addSystem(t)}setDepthTexture(t,e={}){this.depth=t?mn(t,e):null;for(const t of this.batchList)t.applyDepthTexture(this.depth)}get depthTexture(){return this.depth?.texture??null}set depthTexture(t){this.setDepthTexture(t)}get depthEncoding(){return this.depth?.encoding??null}setMeshLighting(t){const e=this.meshLighting;t.direction&&(e.direction=t.direction.clone()),t.color&&(e.color=t.color.clone()),t.ambient&&(e.ambient=t.ambient.clone());for(const t of this.batchList)t.applyMeshLighting(e)}getMeshLighting(){const t=this.meshLighting;return{direction:t.direction.clone(),color:t.color.clone(),ambient:t.ambient.clone()}}configureAdaptivePerformance(t={}){const e=this.adaptivePerformanceState,s=Ur.clamp(t.minQuality??e.minQuality,.1,1),i=Ur.clamp(t.maxQuality??e.maxQuality,s,1);e.targetFrameMs=Math.max(t.targetFrameMs??e.targetFrameMs,.1),e.minQuality=s,e.maxQuality=i,e.decreaseStep=Math.max(t.decreaseStep??e.decreaseStep,.001),e.increaseStep=Math.max(t.increaseStep??e.increaseStep,.001),e.currentQuality=Ur.clamp(e.currentQuality,e.minQuality,e.maxQuality),e.enabled=!0,this.lastAppliedQuality=Number.NaN}disableAdaptivePerformance(t=!0){this.adaptivePerformanceState.enabled=!1,t&&(this.adaptivePerformanceState.currentQuality=this.adaptivePerformanceState.maxQuality,this.applyAdaptiveQuality())}getAdaptivePerformanceState(){return{...this.adaptivePerformanceState}}applyAdaptiveQuality(){const t=this.adaptivePerformanceState.currentQuality;if(t!==this.lastAppliedQuality){for(let e=0;e<this.systems.length;e++)this.systems[e].setQualityFactor(t);this.lastAppliedQuality=t}}_invalidateUpdateOrder(){this.orderedSystemsStale=!0}orderSystems(){if(!this.orderedSystemsStale)return this.orderedSystems;const t=[],e=new Set,s=new Set,i=new Set(this.systems),n=r=>{if(!s.has(r)&&!e.has(r)){e.add(r);for(const t of(t=>{const e=[];for(const s of t.behaviors??[]){if("EmitSubParticleSystem"!==s.type)continue;const t=s.subParticleSystem,n="object"==typeof t?t.system:void 0;void 0!==n&&i.has(n)&&e.push(n)}return e})(r))n(t);e.delete(r),s.add(r),t.push(r)}};for(const t of this.systems)n(t);return t.reverse(),this.orderedSystems=t,this.orderedSystemsStale=!1,t}update(t){this.elapsed+=t;const e=this.adaptivePerformanceState,s=e.enabled?performance.now():0;e.enabled&&this.applyAdaptiveQuality();const i=this.orderSystems(),n=this.cullingEnabled?this.collectCameras():0,r=this.simulationBudgetMs!==1/0||this.catchUpBudgetMs!==1/0?performance.now():0,o=this.simulationBudgetMs===1/0?1/0:r+this.simulationBudgetMs,a=this.catchUpBudgetMs===1/0?1/0:r+this.catchUpBudgetMs;for(let e=0;e<i.length;e++){const s=i[e];s.emitter.visible&&(s.culled=n>0&&"always"!==s.cullingMode&&!0!==s.onlyUsedByOther&&!this.isSystemInView(s),s.update(t,o,a)),i[e]!==s&&e--}this.refreshBatches(),e.enabled&&(e.lastFrameCpuMs=performance.now()-s,e.lastFrameCpuMs>e.targetFrameMs?e.currentQuality=Ur.clamp(e.currentQuality-e.decreaseStep,e.minQuality,e.maxQuality):e.currentQuality=Ur.clamp(e.currentQuality+e.increaseStep,e.minQuality,e.maxQuality))}refreshBatches(){const t=this.batchEmptyFrames;for(let e=0;e<this.batchList.length;e++){const s=this.batchList[e];if(s.time=this.elapsed,s.systems.size>0){t[e]=0,s.update();continue}const i=(t[e]??0)+1;t[e]=i,1===i?s.update():i>Ur.EMPTY_BATCH_GRACE_FRAMES&&(this.removeBatch(e),e--)}}removeBatch(t){this.batchList[t].dispose(),this.batchList.splice(t,1),this.batchEmptyFrames.splice(t,1);for(const[e,s]of this.batchIndexOf)s>t&&this.batchIndexOf.set(e,s-1)}getBatchRenderStats(){return this.batchList.map((t,e)=>{let s=0;const i=[];for(const e of t.systems){const t=e;s+=t.particleNum,i.push(t.emitter.name)}return{batchIndex:e,renderMode:t.settings.renderMode,instanceCount:t.mesh.forcedInstanceCount??0,particleCount:s,systemNames:i}})}dispose(){for(const t of this.batchList)t.dispose();this.batchList.length=0,this.batchEmptyFrames.length=0;for(const t of this.systems)t._renderer===this&&(t._renderer=void 0);this.systems.length=0,this.orderedSystems=[],this.orderedSystemsStale=!0,this.batchIndexOf.clear(),super.dispose()}}Ur.EMPTY_BATCH_GRACE_FRAMES=120;const Lr=new WeakMap,Dr=new WeakMap;function kr(t,e,s){if(Lr.has(t))return;const i={textures:new Set(e),materials:new Set(s)};for(const t of[...i.textures,...i.materials])Dr.set(t,(Dr.get(t)??0)+1);Lr.set(t,i),t.onDisposeObservable.addOnce(()=>qr(t))}function qr(t){const e=Lr.get(t);if(void 0!==e){Lr.delete(t);for(const t of[...e.materials,...e.textures]){const e=(Dr.get(t)??1)-1;e>0?Dr.set(t,e):(Dr.delete(t),t.dispose())}}}function Gr(t){t.dispose(),qr(t)}const Jr=[0,0,0],Wr=new st,jr=new st,Qr=1e-12;function Hr(t,e,s,i){const n=4*e,r=s[e];if(r>Qr){const e=i/r;return t[n]*=e,t[n+1]*=e,void(t[n+2]*=e)}const o=(e+1)%3,a=(e+2)%3;s[o]>Qr&&s[a]>Qr?(Wr.set(t[4*o],t[4*o+1],t[4*o+2]),jr.set(t[4*a],t[4*a+1],t[4*a+2]),Wr.cross(jr).normalize().multiplyScalar(i),t[n]=Wr.x,t[n+1]=Wr.y,t[n+2]=Wr.z):(t[n]=0===e?i:0,t[n+1]=1===e?i:0,t[n+2]=2===e?i:0)}let Yr=0;class Xr extends n.TransformNode{get matrixWorld(){const t=this.getWorldMatrix(),e=t.updateFlag,s=this.system?.scalingMode??"hierarchy";if(e===this._matrixWorldFlag&&s===this._matrixWorldMode)return this._matrixWorld;this._matrixWorldFlag=e,this._matrixWorldMode=s;const i=this._matrixWorld.elements,n=t.m;for(let t=0;t<16;t++)i[t]=n[t];if(this._shapeScale.set(1,1,1),"hierarchy"===s||"local"===s&&!this.parent)return this._matrixWorld;const r=this.scaling,o=this.scalingDeterminant,a=Jr;for(let t=0;t<3;t++){const e=4*t;a[t]=Math.sqrt(i[e]*i[e]+i[e+1]*i[e+1]+i[e+2]*i[e+2])}for(let t=0;t<3;t++){const e="local"===s?Math.abs((0===t?r.x:1===t?r.y:r.z)*o):1;"shape"===s&&this._shapeScale.setComponent(t,a[t]),Hr(i,t,a,e)}return this._matrixWorld}get shapeScale(){return this._shapeScale}get visible(){return this.isEnabled()}set visible(t){this.setEnabled(t)}get uuid(){return zi(this)}constructor(t,e){super("particleEmitter",e||void 0),this._matrixWorld=new at,this._matrixWorldFlag=-1,this._shapeScale=new st(1,1,1),this.system=t}dispose(t,e=!1){this.isDisposed()||(super.dispose(t,e),Yr>0||this.system.dispose?.())}clone(t){const e=this.system.clone().emitter;return e.name=t??this.name,e.position.copyFrom(this.position),e.rotation.copyFrom(this.rotation),e.scaling.copyFrom(this.scaling),this.rotationQuaternion&&(e.rotationQuaternion=this.rotationQuaternion.clone()),e.setEnabled(this.isEnabled(!1)),e}toJSON(t,e={}){return{uuid:zi(this),type:"ParticleEmitter",name:this.name,position:[this.position.x,this.position.y,this.position.z],rotation:[this.rotation.x,this.rotation.y,this.rotation.z],quaternion:this.rotationQuaternion?[this.rotationQuaternion.x,this.rotationQuaternion.y,this.rotationQuaternion.z,this.rotationQuaternion.w]:void 0,scale:[this.scaling.x,this.scaling.y,this.scaling.z],visible:this.isEnabled(!1),ps:this.system.toJSON(t,e)}}}class Zr{static runOnAllParticleEmitters(t,e){Zr.traverseNode(t,t=>{t instanceof Xr&&e(t)})}static addToBatchRenderer(t,e){Zr.runOnAllParticleEmitters(t,t=>{e.addSystem(t.system)})}static play(t){Zr.runOnAllParticleEmitters(t,t=>{t.system.play()})}static resume(t){Zr.runOnAllParticleEmitters(t,t=>{t.system.resume()})}static stop(t){Zr.runOnAllParticleEmitters(t,t=>{t.system.stop()})}static pause(t){Zr.runOnAllParticleEmitters(t,t=>{t.system.pause()})}static restart(t){Zr.runOnAllParticleEmitters(t,t=>{t.system.restart()})}static setStopAction(t,e){Zr.runOnAllParticleEmitters(t,t=>{t.system.stopAction=e})}static setAutoDestroy(t,e){Zr.runOnAllParticleEmitters(t,t=>{t.system.autoDestroy=e})}static endEmit(t){Zr.runOnAllParticleEmitters(t,t=>{t.system.endEmit()})}static isEffectFinished(t){let e=!1,s=!0;return Zr.runOnAllParticleEmitters(t,t=>{e=!0,t.system.isFinished()||(s=!1)}),e&&s}static instantiate(t,e){const s=new Map,i=new Map,r=new Set([t,...t.getDescendants(!1)]),o=t=>{let e=i.get(t);return void 0===e&&(e=t.clone(t.name,null,!0),e.setEnabled(t.isEnabled(!1)),i.set(t,e)),e},a=(t,e,i)=>{let h;if(t instanceof Xr)h=t.clone(i),s.set(t,h);else if(t instanceof u.Mesh)h=o(t),void 0!==i&&(h.name=i);else if(t instanceof S.InstancedMesh){const e=r.has(t.sourceMesh)?o(t.sourceMesh):void 0;h=t.clone(i??t.name,null,!0,e),h.setEnabled(t.isEnabled(!1))}else{if(!(t instanceof n.TransformNode))return null;h=new n.TransformNode(i??t.name,t.getScene()),h.position.copyFrom(t.position),h.rotation.copyFrom(t.rotation),h.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(h.rotationQuaternion=t.rotationQuaternion.clone()),h.setEnabled(t.isEnabled(!1))}h.parent=e;for(const e of t.getChildren())a(e,h);return h},h=a(t,null,e);!function(t,e){for(let s=t;null!==s;s=s.parent){const t=Lr.get(s);if(void 0!==t)return void kr(e,t.textures,t.materials)}}(t,h);for(const t of s.values()){const e=t.system;for(const t of e.behaviors)if(t instanceof ts){const e=s.get(t.subParticleSystem);void 0!==e&&(t.subParticleSystem=e)}const n=e.emitterShape;if(n instanceof Ai&&void 0!==n.mesh){const t=i.get(n.mesh);void 0!==t&&(n.mesh=t)}}return h}static getDuration(t){const e=[];Zr.runOnAllParticleEmitters(t,t=>{e.push(t.system)});const s=new Map;for(let t=0;t<e.length;t++){const i=e[t];for(const t of i.behaviors){if(!(t instanceof ts))continue;const n=t.subParticleSystem?.system;if(void 0!==n&&"object"==typeof n){e.includes(n)||e.push(n);const t=s.get(n)??[];t.push(i),s.set(n,t)}}}const i=new Map,n=t=>{const e=i.get(t);if(void 0!==e)return e;i.set(t,1/0);const r=t.playbackSpeed,o=Zr.maxOf(t.startLife)/r;let a;if(r>0)if(t.onlyUsedByOther){a=0;for(const e of s.get(t)??[])a=Math.max(a,n(e));a+=t.duration/r+o}else a=t.looping?1/0:(Zr.maxOf(t.startDelay,0)+t.duration)/r+o;else a=1/0;return i.set(t,a),a};let r=0;for(const t of e)r=Math.max(r,n(t));return r}static maxOf(t,e){if(t instanceof Xt)return t.value;if(t instanceof Zt)return Math.max(t.a,t.b);if(t instanceof se)return Math.max(Zr.maxOf(t.curve1,e),Zr.maxOf(t.curve2,e));let s=-1/0;for(let i=0;i<=32;i++){const n=[];t.startGen(n);const r="function"===t.type?t.genValue(n,e??i/32):t.genValue(n);s=Math.max(s,r)}return s}static traverseNode(t,e){e(t);const s=t.getChildren();for(const t of s)Zr.traverseNode(t,e)}}const Kr=new WeakMap,to=new WeakMap,eo=new WeakSet,so=new WeakMap,io=new WeakSet,no=new WeakSet;function ro(t){if(!t?.isCube)return null;const e=t.files??t._files;return 6===e?.length?e.slice():null}function oo(t){return t.getScene?.()??null}function ao(t,e=oo(t)){return e&&Kr.get(t)?.get(e)||null}function ho(t,e){so.delete(t);const s=Kr.get(t);if(s)for(const[t,i]of[...s])e&&t!==e||(s.delete(t),eo.has(i)&&i.dispose())}function lo(t,e,s){let i=Kr.get(t);i||(i=new Map,Kr.set(t,i)),i.set(e,s),!io.has(s)&&s.onDisposeObservable&&(io.add(s),s.onDisposeObservable.addOnce(()=>{Kr.get(t)?.get(e)===s&&Kr.get(t).delete(e)})),!no.has(t)&&t.onDisposeObservable&&(no.add(t),t.onDisposeObservable.addOnce(()=>{no.delete(t),ho(t)}))}async function co(t,e){if("undefined"==typeof document||"undefined"==typeof Image)throw new Error("createEnvAtlasFromFaceUrls requires a DOM Image/canvas environment");const s=await Promise.all(t.map(t=>function(t){return new Promise((e,s)=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>e(i),i.onerror=()=>s(new Error(`Failed to load env face ${t}`)),i.src=t})}(t))),i=s[0].width||s[0].naturalWidth;if(!i)throw new Error("Env atlas face image has zero size");const n=document.createElement("canvas");n.width=3*i,n.height=2*i;const r=n.getContext("2d");if(!r)throw new Error("Could not create env atlas canvas");for(let t=0;t<6;t++)r.drawImage(s[t],t%3*i,Math.floor(t/3)*i,i,i);const o=new b.Texture(n.toDataURL("image/jpeg",.92),e,{noMipmap:!0,invertY:!1,samplingMode:b.Texture.LINEAR_LINEAR});return o.name="quarksEnvAtlas",o}const uo={createFromFaceUrls:co};function fo(t,e,s){const i=ao(t,e);if(i)return s(i),i;let n=to.get(t);n||(n=new Map,to.set(t,n));const r=n,o=()=>{const i=r.get(e);if(i)return void i.then(t=>{t&&s(t)});const n=ro(t);if(!n||so.get(t)===n.join("\n"))return;let o=!1;const a=t.onDisposeObservable?.addOnce(()=>o=!0),h=()=>{r.delete(e),a&&t.onDisposeObservable.remove(a)},l=uo.createFromFaceUrls(n,e).then(i=>(h(),o||e.isDisposed?(i.dispose(),null):(eo.add(i),lo(t,e,i),s(i),i))).catch(e=>(h(),so.set(t,n.join("\n")),console.warn("[babylon.quarks] Failed to build env atlas from cubemap faces",e),null));r.set(e,l)};if(t.isReady())o();else{const e=t.onLoadObservable;e?e.addOnce(()=>o()):o()}return ao(t,e)}const po=new Set(["SizeOverLife","SizeBySpeed"]),mo=new Set(["ColorOverLife","ColorBySpeed"]),yo=new Set(["ApplyForce","Noise","TurbulenceField","GravityForce","RotationOverLife","Rotation3DOverLife","RotationBySpeed","SpeedOverLife","FrameOverLife","ForceOverLife","VelocityOverLife","InheritVelocity","OrbitOverLife","WidthOverLength","ChangeEmitDirection","EmitSubParticleSystem","LimitSpeedOverLife","ApplyCollision"]);class go{constructor(){this.fusionSteps=[],this.changesSize=!0,this.changesColor=!0}steps(t){const e=this.plan;if(void 0!==e&&e.length===t.length){let s=!0;for(let i=0;i<t.length;i++)if(e[i]!==t[i]){s=!1;break}if(s)return this.fusionSteps}this.plan=t.slice(),this.fusionSteps=Ks(t);let s=!1,i=!1;for(let e=0;e<t.length;e++){const n=t[e].type;po.has(n)?s=!0:mo.has(n)?i=!0:yo.has(n)||(s=!0,i=!0)}return this.changesSize=s,this.changesColor=i,this.fusionSteps}}function vo(t){return Math.sqrt(Math.max(t[0]*t[0]+t[1]*t[1]+t[2]*t[2],t[4]*t[4]+t[5]*t[5]+t[6]*t[6],t[8]*t[8]+t[9]*t[9]+t[10]*t[10]))}class xo{constructor(){this.min=new st,this.max=new st,this.padding=0,this.valid=!1,this.stepsSince=0,this.maxSize=0,this.maxSpeedSq=0,this.inWorld=!1,this.geometryRadius=1}get due(){return this.stepsSince>=4||!this.valid}store(t,e,s,i,n,r,o,a,h,l,c,u,d,f){if(0===t)return void(this.valid=!1);this.stepsSince=e?0:this.stepsSince+1,this.maxSize=h,this.maxSpeedSq=l;const p=Math.sqrt(l),m=c.renderMode;let y=p*f*(this.stepsSince+1);if(m===exports.RenderMode.Mesh)y+=h*this.meshGeometryRadius(c.instancingGeometry);else if(m===exports.RenderMode.StretchedBillBoard){const t=u;y+=h*(1+(t.lengthFactor??0)+p*(t.speedFactor??0))}else{const t=c.pivot;y+=h*(.75+(void 0===t?0:Math.abs(t.x)+Math.abs(t.y)+Math.abs(t.z)))}this.min.set(s,i,n),this.max.set(r,o,a),this.padding=y,this.inWorld=d,this.valid=!0}setWorld(t,e,s,i,n,r,o){this.min.set(t,e,s),this.max.set(i,n,r),this.padding=o,this.inWorld=!0,this.valid=!0}worldPadding(t){return this.inWorld?this.padding:this.padding*vo(t.matrixWorld.elements)}toWorld(t,e,s){if(!this.valid)return!1;const i=this.min,n=this.max;if(this.inWorld){const s=this.padding;return t.set(i.x-s,i.y-s,i.z-s),e.set(n.x+s,n.y+s,n.z+s),!0}const r=s.matrixWorld.elements,o=this.padding*vo(r);let a=1/0,h=1/0,l=1/0,c=-1/0,u=-1/0,d=-1/0;for(let t=0;t<8;t++){const e=1&t?n.x:i.x,s=2&t?n.y:i.y,o=4&t?n.z:i.z,f=1/(r[3]*e+r[7]*s+r[11]*o+r[15]),p=(r[0]*e+r[4]*s+r[8]*o+r[12])*f,m=(r[1]*e+r[5]*s+r[9]*o+r[13])*f,y=(r[2]*e+r[6]*s+r[10]*o+r[14])*f;p<a&&(a=p),p>c&&(c=p),m<h&&(h=m),m>u&&(u=m),y<l&&(l=y),y>d&&(d=y)}return t.set(a-o,h-o,l-o),e.set(c+o,u+o,d+o),!0}meshGeometryRadius(t){if(t!==this.geometryRadiusFor){let e=0;for(let s=0;s+2<t.length;s+=3){const i=t[s]*t[s]+t[s+1]*t[s+1]+t[s+2]*t[s+2];i>e&&(e=i)}this.geometryRadius=Math.sqrt(e),this.geometryRadiusFor=t}return this.geometryRadius}}function So(t){return t.cycle>=1?Math.floor(t.cycle):1}function bo(t){return t.interval>0?t.interval:0}class wo{constructor(t,e){this.system=t,this.spawner=e,this.memory=[],this.pathMatrix=new at,this.temp=new st}rollGenerators(){const t=this.system,e=this.memory;t.emissionBursts.forEach(t=>t.count.startGen(e)),t.emissionOverDistance.startGen(e),t.startDelay.startGen(e);const s=t.startDelay.genValue(e,0);return t.emissionOverTime.startGen(e),s}hasPendingEmission(t){const e=this.system;if(void 0===t||t===e.emissionState){if(e.isEmitEnded)return!1;if(e.looping)return!0;if(e.onlyUsedByOther)return!1;t=e.emissionState}if(t.waitEmiting>0)return!0;if(t.burstIndex<e.emissionBursts.length)return!0;if(this.hasPendingBurstWaves(t))return!0;if(t.time>=e.duration)return!1;const s=t.time/e.duration;return this.emitsFrom(e.emissionOverTime,s)||this.emitsFrom(e.emissionOverDistance,s)}emitsFrom(t,e){if(t.genValue(this.memory,e)>0)return!0;if("function"!==t.type)return!1;if(t instanceof se)return this.emitsFrom(t.curve1,e)||this.emitsFrom(t.curve2,e);if(t instanceof ee){for(let s=0;s<t.functions.length;s++)if(t.getEndX(s)>e&&t.functions[s][0].p.some(t=>t>0))return!0;return!1}for(let s=1;s<=64;s++)if(t.genValue(this.memory,e+(1-e)*s/64)>0)return!0;return!1}hasPendingBurstWaves(t){const e=t.burstWaves;if(void 0===e)return!1;const s=this.system.emissionBursts,i=this.system.duration;for(let n=0;n<t.burstIndex&&n<s.length;n++){const t=s[n],r=e[n]??0;if(r<So(t)&&(0===r||t.time+r*bo(t)<=i))return!0}return!1}emit(t,e,s){const i=this.system;if(i.isDisposed)return;const n=i.duration,r=i.isEmitEnded&&e===i.emissionState;e.time>n&&(i.looping?(e.time-=n,e.burstIndex=0,void 0!==e.burstWaves&&(e.burstWaves.length=0)):i.isEmitEnded||i.onlyUsedByOther||i.endEmit());const o=i.emissionFactor();i.emissionBursts.length>0&&!r&&this.emitBursts(e,s);let a=0,h=0,l=0,c=0;const u=e.previousWorldPos;if(!i.isEmitEnded){const r=e.time/n;if(e.waitEmiting+=t*i.emissionOverTime.genValue(this.memory,r)*o,void 0!==u){this.temp.set(s.elements[12],s.elements[13],s.elements[14]),c=u.distanceTo(this.temp);const t=i.emissionOverDistance.genValue(this.memory,r)*o;if(t>0){l=e.travelDistance,e.travelDistance+=c;const s=Math.floor(e.travelDistance*t);s>0&&(e.travelDistance-=s/t,i.worldSpace&&c>0?(a=s,h=1/t):e.waitEmiting+=s)}else e.travelDistance=0}}const d=Math.floor(e.waitEmiting);d>0&&(this.spawner.spawn(d,e,s),e.waitEmiting-=d),a>0&&this.spawnAlongPath(a,e,s,u,l,h,c),void 0===e.previousWorldPos&&(e.previousWorldPos=new st),e.previousWorldPos.set(s.elements[12],s.elements[13],s.elements[14]),e.time+=t}emitBursts(t,e){const s=this.system.emissionBursts,i=this.system.duration,n=s.length,r=t.time,o=t.burstWaves??(t.burstWaves=[]);for(;t.burstIndex<n&&s[t.burstIndex].time<=r;)o[t.burstIndex]=0,t.burstIndex++;const a=t.burstIndex;for(let n=0;n<a;n++){const a=s[n],h=So(a);let l=o[n]??0;if(l>=h)continue;const c=bo(a);for(;l<h;){const s=a.time+l*c;if(l>0&&s>i){l=h;break}if(s>r)break;t.burstWaveIndex=l,this.fireBurstWave(a,t,e),l++}o[n]=l}}fireBurstWave(t,e,s){if(z()>=t.probability)return;const i=t.count.genValue(this.memory,e.time/this.system.duration),n=this.system.emissionFactor(),r=Math.abs(n-1)<.001?i:Math.floor(i*n+z());e.isBursting=!0,e.burstParticleCount=r,this.spawner.spawn(r,e,s),e.isBursting=!1}spawnAlongPath(t,e,s,i,n,r,o){const a=this.pathMatrix.copy(s),h=s.elements,l=a.elements,c=h[12],u=h[13],d=h[14];for(let s=1;s<=t;s++){const t=s*r-n,h=t<=0?0:t>=o?1:t/o;l[12]=i.x+(c-i.x)*h,l[13]=i.y+(u-i.y)*h,l[14]=i.z+(d-i.z)*h,this.spawner.spawn(1,e,a)}}}class Mo{constructor(){this.listeners={}}add(t,e){this.listeners[t]=[...this.listeners[t]??[],e]}removeAll(t){if(void 0!==t)delete this.listeners[t];else for(const t of Object.keys(this.listeners))delete this.listeners[t]}remove(t,e){const s=this.listeners[t];if(void 0===s)return;const i=s.indexOf(e);-1!==i&&(this.listeners[t]=s.filter((t,e)=>e!==i))}has(t){const e=this.listeners[t];return void 0!==e&&e.length>0}fire(t){const e=this.listeners[t.type];if(void 0!==e)for(let s=0;s<e.length;s++)e[s](t)}}const zo=new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]),_o=new Float32Array([0,0,1,0,1,1,0,1]),Ao=new Uint32Array([0,1,2,0,2,3]),Po=new WeakMap,Oo=new WeakMap;function To(t){let e=Po.get(t);return void 0!==e&&e.length===t.length/3*2||(e=new Float32Array(t.length/3*2),Po.set(t,e)),e}function Vo(t){let e=Oo.get(t);if(!e){e=new Float32Array(t.length);for(let t=2;t<e.length;t+=3)e[t]=1;Oo.set(t,e)}return e}function Eo(t){return t?t instanceof Float32Array?t:new Float32Array(t):void 0}const Co=1/60;class $o{constructor(){this.accumulator=0,this.pendingCatchUp=0,this.delayLeft=0}reset(){this.accumulator=0,this.pendingCatchUp=0}setStartDelay(t){this.delayLeft=t>0?t:0}get delaying(){return this.delayLeft>0}static frameSeconds(t,e){if(!(t>0))return 0;return(t>.1?.1:t)*e}consumeStartDelay(t){if(this.delayLeft<=0)return t;if(this.delayLeft-=t,this.delayLeft>=0)return 0;const e=Math.min(-this.delayLeft,.1);return this.delayLeft=0,e}accrue(t,e=1){this.accumulator+=t;const s=e>1?Math.ceil(8*e):8,i=Math.min(s,Math.max(0,Math.round(this.accumulator/Co-1e-9)));return this.accumulator-=i*Co,i}get residual(){return this.accumulator>Co?Co:this.accumulator<-Co?-Co:this.accumulator}deferCatchUp(t){this.pendingCatchUp=Math.min(2,this.pendingCatchUp+t)}get owesCatchUp(){return this.pendingCatchUp>0}takeCatchUpSteps(){const t=Math.floor(this.pendingCatchUp/Co);return this.pendingCatchUp=0,t}}const Io=new st;function No(t,e,s,i){const n=t[s],r=t[i];return t[s]=r,t[i]=n,s!==i&&(e.swapRows(s,i),r.setStoreIndex(s),n.setStoreIndex(i)),n}const Fo=1e-6;function Ro(t,e){return t.loopEnd>t.loopStart?1/0:Math.max(t.loopEnd,Fo)*e}function Bo(t){return t?.getScene()?t:null}const Uo=new st(0,0,1),Lo=new et,Do=new et,ko=new st,qo=new st,Go=new vt;class Jo{constructor(t){this.system=t,this.ringCursor=0}swapRows(t,e){const s=this.system.particles,i=s[t],n=s[e];s[t]=n,s[e]=i,this.system.store.swapRows(t,e),n.setStoreIndex(t),i.setStoreIndex(e)}reverseRows(t,e){for(;t<e;t++,e--)this.swapRows(t,e)}rotateRows(t,e){t<=0||t>=e||(this.reverseRows(0,t-1),this.reverseRows(t,e-1),this.reverseRows(0,e-1))}fitRing(){const t=this.system,e=t.maxParticles,s=t.particleNum;void 0===e||s<=e||"disabled"===t.ringBufferMode||t.rendererSettings.renderMode!==exports.RenderMode.Trail&&(this.rotateRows((this.ringCursor+s-e)%s,s),t.particleNum=e,this.ringCursor=0)}rebind(){const t=this.system.particles;for(let e=0;e<t.length;e++)t[e].rebind()}grow(t){const e=this.system,s=e.particles.length;e.store.ensureCapacity(s+1)&&this.rebind(),e.particles.push(t?new qe(e.store,s):new De(e.store,s))}spawn(t,e,s){const i=this.system,n=ko,r=qo;s.decompose(n,Do,r);const o=Go.setFromMatrix4(s),a=i.behaviors,h=a.length,l=i.rendererSettings.renderMode,c=l===exports.RenderMode.Trail,u=!c,d=l===exports.RenderMode.Mesh,f=i.startRotation,p=i.startSize,m="rotation"===f.type,y="vec3function"===p.type,g=e.time/i.duration,v=c?i.rendererEmitterSettings:void 0,x=Boolean(v?.followLocalOrigin),S=i.worldSpace,b="shape"===i.scalingMode?i.emitter.shapeScale:void 0,w=i.particles,M=i.maxParticles,_=void 0!==M&&"disabled"!==i.ringBufferMode&&!c;void 0!==M&&(t=_?Math.min(t,M):Math.min(t,Math.max(0,M-i.particleNum)));for(let n=0;n<t;n++){let t;if(e.burstParticleIndex=n,_&&i.particleNum>=M?(this.ringCursor>=i.particleNum&&(this.ringCursor=0),t=w[this.ringCursor],this.ringCursor=(this.ringCursor+1)%i.particleNum):(_&&0!==this.ringCursor&&(this.rotateRows(this.ringCursor,i.particleNum),this.ringCursor=0),i.particleNum++,w.length<i.particleNum&&this.grow(c),t=w[i.particleNum-1]),t.reset(),t.serial=(t.serial??0)+1,t.speedModifier=1,i.finishedEventFired=!1,i.startColor.startGen(t.memory),i.startColor.genColor(t.memory,t.startColor,g),t.color.copy(t.startColor),i.startSpeed.startGen(t.memory),t.startSpeed=i.startSpeed.genValue(t.memory,g),i.startLife.startGen(t.memory),t.life=i.startLife.genValue(t.memory,g),t.age=0,p.startGen(t.memory),y)p.genValue(t.memory,t.startSize,g);else{const e=p.genValue(t.memory,g);t.startSize.set(e,e,e)}if(i.startTileIndex.startGen(t.memory),t.uvTile=i.startTileIndex.genValue(t.memory),t.size.copy(t.startSize),u){const e=t;if(f.startGen(t.memory),d)e.rotation instanceof et||(e.rotation=Lo),e.angularVelocity instanceof et&&e.angularVelocity.set(0,0,0,1),m?f.genValue(t.memory,e.rotation,1,g):e.rotation.setFromAxisAngle(Uo,f.genValue(e.memory,g));else{e.rotation=m?0:f.genValue(e.memory,g),e.angularVelocity=0;const t=i.flip;e.flip=void 0===t?0:(z()<t.x?1:0)|(z()<t.y?2:0)}}else if(v){const e=t;v.startLength.startGen(e.memory),e.length=v.startLength.genValue(e.memory,g),e.ensureHistoryCapacity(Math.max(1,Math.ceil(e.length))),e.resetHistory()}i.emitterShape.initialize(t,e),void 0!==b&&t.position.multiply(b),i.alignToDirection&&u&&Wo(t,d);const l=e.particle,A=e.inherit;if(void 0!==l&&void 0!==A&&0!==A&&jo(t,l,A,u),c&&x){const e=t;e.localPosition||(e.localPosition=new st),e.localPosition.copy(e.position)}S?(t.position.applyMatrix4(s),t.startSize.multiply(r).abs(),t.size.copy(t.startSize),t.velocity.applyMatrix3(o),t.rotation&&t.rotation instanceof et&&t.rotation.multiplyQuaternions(Do,t.rotation)):i.onlyUsedByOther&&(t.parentMatrix=s);for(let e=0;e<h;e++)a[e].initialize(t,i);i.store.recordMemory(t.storeIndex,t.memory)}}}function Wo(t,e){const s=t.velocity,i=s.x*s.x+s.y*s.y+s.z*s.z;if(0!==i)if(e){const e=t.rotation;ko.copy(s).divideScalar(Math.sqrt(i)),Do.setFromUnitVectors(Uo,ko),e.multiplyQuaternions(Do,e)}else 0===s.x&&0===s.y||(t.rotation=t.rotation+Math.atan2(-s.x,s.y))}function jo(t,e,s,i){if(s&Ze.color&&(t.startColor.multiply(e.color),t.color.copy(t.startColor)),s&Ze.size&&(t.startSize.multiply(e.size),t.size.copy(t.startSize)),s&Ze.rotation&&i){const s=t,i=e.rotation;"number"==typeof s.rotation?"number"==typeof i&&(s.rotation+=i):i instanceof et&&s.rotation.multiplyQuaternions(i,s.rotation)}s&Ze.lifetime&&e.life>0&&(t.life*=Math.max(0,1-e.age/e.life))}function Qo(t,e,s,i,n={}){return{param:t,json:n.json,get:e,isDefault:t=>t===s,toJSON:t=>t,fromJSON:i,clone:t=>t}}function Ho(t){return"number"==typeof t?t:void 0}function Yo(t){return"number"==typeof t?Ki(t):void 0}function Xo(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:void 0}function Zo(t){return"number"==typeof t?0!==t:"boolean"==typeof t?t:void 0}function Ko(t,e,s,i,n=!0){const r=JSON.stringify(s().toJSON());return{param:t,always:n,get:e,isDefault:t=>JSON.stringify(t.toJSON())===r,toJSON:t=>t.toJSON(),fromJSON:t=>"number"==typeof t?new Xt(t):i(t),clone:t=>t.clone()}}function ta(t){const e=t;if(void 0!==e)return void 0===e.z?[e.x,e.y]:[e.x,e.y,e.z]}const ea=[Qo("stopAction",t=>t.stopAction,"none",ji),Qo("looping",t=>t.looping,!0,Zo),Qo("prewarm",t=>t.prewarm,!1,Zo),Qo("prewarmTime",t=>t.prewarmTime,0,Ho),Qo("duration",t=>t.duration,1,Ho),Ko("startDelay",t=>t.startDelay,()=>new Xt(0),ne,!1),Ko("startLife",t=>t.startLife,()=>new Xt(5),ne),Ko("startSpeed",t=>t.startSpeed,()=>new Xt(0),ne),Ko("startRotation",t=>t.startRotation,()=>new Xt(0),t=>be(t)),Ko("startSize",t=>t.startSize,()=>new Xt(1),t=>be(t)),Ko("startColor",t=>t.startColor,()=>new pe(new Pt(1,1,1,1)),t=>me(t)),Ko("emissionOverTime",t=>t.emissionOverTime,()=>new Xt(10),ne),Ko("emissionOverDistance",t=>t.emissionOverDistance,()=>new Xt(0),ne),{param:"emissionBursts",get:t=>t.emissionBursts,isDefault:t=>0===t.length,toJSON:t=>t.map(t=>({time:t.time,count:t.count.toJSON(),probability:t.probability,interval:t.interval,cycle:t.cycle})),fromJSON:t=>Array.isArray(t)?sn(t.map(t=>({time:t.time,count:"number"==typeof t.count?new Xt(t.count):ne(t.count),probability:t.probability,interval:t.interval,cycle:t.cycle??t.cycleCount}))):void 0,clone:t=>t.map(t=>({...t,count:t.count.clone()}))},Qo("maxParticles",t=>t.maxParticles,void 0,Ho),Qo("ringBufferMode",t=>t.ringBufferMode,"disabled",Qi),{param:"ringBufferLoopRange",get:t=>t.ringBufferLoopRange,isDefault:t=>0===t.x&&1===t.y,toJSON:ta,fromJSON:t=>Array.isArray(t)?Hi(new Mt(t[0],t[1])):void 0,clone:t=>t.clone()},Qo("onlyUsedByOther",t=>t.onlyUsedByOther,!1,Zo),Qo("renderMode",t=>t.renderMode,exports.RenderMode.BillBoard,Ho),Qo("renderOrder",t=>t.renderOrder,0,Ho),Qo("renderingGroupId",t=>t.renderingGroupId,0,Ho),Qo("applyFog",t=>t.applyFog,!0,t=>!1!==t),Qo("applyImageProcessing",t=>t.applyImageProcessing,!0,t=>!1!==t),Qo("playbackSpeed",t=>t.playbackSpeed,1,Ho),Qo("cullingMode",t=>t.cullingMode,"always",Wi),Qo("scalingMode",t=>t.scalingMode,"local",Yi),Qo("seed",t=>t.seed,void 0,Ho),Qo("sortMode",t=>t.sortMode,"none",Gi),Qo("renderFace",t=>t.renderFace,"both",Ji),Qo("alignToDirection",t=>t.alignToDirection,!1,t=>!0===t),Qo("minParticleSize",t=>t.minParticleSize,0,Ho),Qo("maxParticleSize",t=>t.maxParticleSize,1/0,Ho),Qo("layerMask",t=>t.layers.mask,268435455,Ho,{json:"layers"}),Ko("startTileIndex",t=>t.startTileIndex,()=>new Xt(0),ne),Qo("uTileCount",t=>t.uTileCount,1,Yo),Qo("vTileCount",t=>t.vTileCount,1,Yo),Qo("blendTiles",t=>t.blendTiles,!1,Zo),Qo("softParticles",t=>t.softParticles,!1,Zo),Qo("softFarFade",t=>t.softFarFade,1,Xo),Qo("softNearFade",t=>t.softNearFade,0,Xo),Qo("blendMode",t=>t.blending,r.Constants.ALPHA_ADD,Ho,{json:"blending"}),Qo("transparent",t=>t.transparent,!0,Zo),Qo("depthTest",t=>t.depthTest,!0,Zo),Qo("depthWrite",t=>t.depthWrite,!1,Zo),Qo("alphaTest",t=>t.alphaTest,0,Ho),Qo("worldSpace",t=>t.worldSpace,!1,Zo),{param:"pivot",get:t=>t.pivot,isDefault:t=>void 0===t,toJSON:ta,fromJSON:t=>Array.isArray(t)?new st(t[0]??0,t[1]??0,t[2]??0):void 0,clone:t=>t?.clone()},{param:"flip",get:t=>t.flip,isDefault:t=>void 0===t,toJSON:ta,fromJSON:t=>Array.isArray(t)?new Mt(t[0]??0,t[1]??0):void 0,clone:t=>t?.clone()}];function sa(t){return t.json??t.param}function ia(t){const e={};for(const s of ea){const i=s.get(t);!s.always&&s.isDefault(i)||(e[sa(s)]=s.toJSON(i))}return e}function na(t){const e={};for(const s of ea)e[s.param]=s.clone(s.get(t));return e}const ra=new WeakMap,oa=new WeakMap,aa=new WeakMap;function ha(t,e){const s=(ra.get(t)??0)+1;return ra.set(t,s),`${e}_${s}`}function la(t){const e={};return t?.uvFromHead&&(e.uvFromHead=!0),t?.colorFromParticle&&(e.colorFromParticle=!0),t?.dieWithParticle&&(e.dieWithParticle=!0),t?.recordWorldSpace&&(e.recordWorldSpace=!0),e}function ca(t){const e={},s=Tr(t),i=Vr(t);return s>0&&(e.tessellation=s),i>0&&(e.curveTension=i),e}function ua(t){const e={},s=Cr(t),i=$r(t),n=Ir(t),r=Nr(t);return"stretch"!==s&&(e.textureMode=s),1!==i&&(e.textureScale=i),n>0&&(e.minVertexDistance=n),r!==1/0&&(e.lifetime=r),e}function da(t){return t?.followLocalOrigin?{followLocalOrigin:!0}:{}}function fa(t){const e=t?.sideAxis;return e?{sideAxis:[e.x,e.y,e.z]}:{}}function pa(t){if(null==t)return{};let e,s,i;Array.isArray(t)?[e,s,i]=t:"object"==typeof t&&({x:e,y:s,z:i}=t);const n=t=>"number"==typeof t?t:"string"==typeof t&&""!==t.trim()?Number(t):NaN,[r,o,a]=[n(e),n(s),n(i)];return Number.isFinite(r)&&Number.isFinite(o)&&Number.isFinite(a)&&r*r+o*o+a*a>0?{sideAxis:new st(r,o,a)}:(Wt(`sideAxis ${JSON.stringify(t)} is not a direction and is ignored`),{})}function ma(t,e){const s=void 0===e||"string"==typeof e?{geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}}:e,i=function(t,e){const s=t.rendererSettings,i=[s.instancingGeometry,s.instancingIndices,s.instancingUVs,s.instancingUVs2,s.instancingNormals];let n=oa.get(e);void 0===n&&(n=[],oa.set(e,n));const r=n.find(t=>t.arrays.every((t,e)=>t===i[e]));if(void 0!==r)return r.uuid;const o=ha(e,"quarks_geometry");return n.push({arrays:i,uuid:o}),e.geometries[o]={uuid:o,type:"QuarksGeometry",positions:Array.from(t.rendererSettings.instancingGeometry),indices:Array.from(t.rendererSettings.instancingIndices),uvs:t.rendererSettings.instancingUVs?Array.from(t.rendererSettings.instancingUVs):void 0,...t.rendererSettings.instancingUVs2?{uvs2:Array.from(t.rendererSettings.instancingUVs2)}:{},normals:t.rendererSettings.instancingNormals?Array.from(t.rendererSettings.instancingNormals):void 0},o}(t,s),n=function(t,e){let s=aa.get(e);void 0===s&&(s=new Map,aa.set(e,s));const i=s,n=(t,s=!1,n="texture")=>{if(!(t instanceof b.Texture||s&&t))return void(t&&console.warn(`[quarks] ${n} is not a url-backed Texture and is not written to the file`));let r=i.get(t);return void 0===r&&(r=ha(e,"quarks_texture"),i.set(t,r),e.textures[r]=t),r},r=n(t.rendererSettings.texture,!0),o=n(t.rendererSettings.reflectionAtlas),a=t.erosion,h=t.uvDistortion,l=t.gradientMap,c=(t,e)=>void 0!==e?{[t]:e}:{},u=ha(e,"quarks_material");return e.materials[u]={uuid:u,type:"QuarksMaterial",transparent:t.rendererSettings.materialTransparent,alphaMode:t.rendererSettings.materialBlendMode,depthTest:t.rendererSettings.materialDepthTest,depthWrite:t.rendererSettings.materialDepthWrite,alphaTest:t.rendererSettings.materialAlphaTest,texture:r,reflectionAtlas:o,reflectionLevel:t.rendererSettings.reflectionLevel,..."fixed"!==t.lighting?{lighting:t.lighting}:{},...t.rim?{rim:{...t.rim,color:[...t.rim.color]}}:{},...c("mapUV",t.mapUV?$i(t.mapUV):void 0),...l?{gradientMap:{ramp:n(l.ramp,!1,"gradientMap.ramp"),..."r"!==l.channel?{channel:l.channel}:{}}}:{},...a?{erosion:{...c("mask",n(a.mask,!1,"erosion.mask")),...c("maskUV",$i(a.maskUV)),...a.softness!==Fi?{softness:a.softness}:{},...0!==a.edgeWidth?{edgeWidth:a.edgeWidth}:{},...a.edgeColor.some(t=>1!==t)?{edgeColor:[...a.edgeColor]}:{}}}:{},...h?{uvDistortion:{map:n(h.map,!1,"uvDistortion.map"),...c("mapUV",$i(h.mapUV,Bi)),...h.strength!==Ui?{strength:h.strength}:{}}}:{},sourceMaterial:t.material??void 0},u}(t,s),r=function(t){if(t.renderMode===exports.RenderMode.Trail){const e=t.rendererEmitterSettings;return{startLength:e.startLength.toJSON(),...da(e),...la(e),...ca(e),...ua(e),...fa(e)}}if(t.renderMode===exports.RenderMode.StretchedBillBoard)return{speedFactor:t.rendererEmitterSettings.speedFactor,lengthFactor:t.rendererEmitterSettings.lengthFactor};return}(t);return{version:"3.0",shape:xi(t.emitterShape),...ia(t),instancingGeometry:i,...r?{rendererEmitterSettings:r}:{},material:n,behaviors:t.behaviors.map(e=>Us(e,t))}}function ya(t,e,s){const i=t.shape?Gt("shape",()=>vi(t.shape,e)):void 0;let n;if(t.renderMode===exports.RenderMode.Trail){const e=t.rendererEmitterSettings;n={startLength:void 0!==e?.startLength?ne(e.startLength):new Xt(30),followLocalOrigin:Boolean(e?.followLocalOrigin),...la(e),...ca(e),...ua(e),...pa(e?.sideAxis)}}else if(t.renderMode===exports.RenderMode.StretchedBillBoard){const e={...t.rendererEmitterSettings};void 0!==t.speedFactor&&(e.speedFactor=t.speedFactor),n=e}else n={};const o=t.material?e.materials?.[t.material]:void 0,a=t=>"string"==typeof t?e.textures?.[t]??null:t??null,h=a(o?.texture??t.texture),l=h instanceof b.Texture?h:null,c=o?.sourceMaterial??(o?{...o,reflectionAtlas:a(o.reflectionAtlas)}:void 0),u=o?.erosion,d=o?.gradientMap,f=o?.uvDistortion,p=function(t){if(t&&"positions"in t&&t.positions){const e=Eo(t.positions);return{positions:e,indices:wi(e,t.indices instanceof Uint16Array||t.indices instanceof Uint32Array?t.indices:t.indices?new Uint32Array(t.indices):void 0),uvs:Eo(t.uvs),uvs2:Eo(t.uvs2),normals:Eo(t.normals)}}const e=t&&"data"in t?t.data:t,s=e&&"attributes"in e?e.attributes:void 0,i=s?.position?.array;if(e&&"attributes"in e&&s&&i){const t=new Float32Array(i);let n;return e.index?.array&&(n=new("Uint16Array"===e.index.type?Uint16Array:Uint32Array)(e.index.array)),{positions:t,indices:wi(t,n),uvs:Eo(s.uv?.array),uvs2:Eo((s.uv1??s.uv2)?.array),normals:Eo(s.normal?.array)}}return{positions:zo,indices:Ao,uvs:_o}}("string"==typeof t.instancingGeometry?e.geometries?.[t.instancingGeometry]:t.instancingGeometry),m=function(t){const e={},s=t;for(const t of ea){const i=s[sa(t)];if(null==i)continue;const n=Gt(sa(t),()=>t.fromJSON(i));void 0!==n&&(e[t.param]=n)}return void 0===e.stopAction&&!0===s.autoDestroy&&(e.stopAction="destroy"),e}(t);return{...m,scene:s,shape:i,instancingGeometry:p.positions,instancingIndices:p.indices,instancingUVs:p.uvs,instancingUVs2:p.uvs2,instancingNormals:p.normals,rendererEmitterSettings:n,texture:l,material:c,blendMode:o?.alphaMode??m.blendMode??r.Constants.ALPHA_ADD,transparent:o?.transparent??m.transparent??!0,depthTest:o?.depthTest??m.depthTest??!0,depthWrite:o?.depthWrite??m.depthWrite??!1,alphaTest:o?.alphaTest??m.alphaTest??0,behaviors:[],lighting:o?.lighting,rim:o?.rim,mapUV:o?.mapUV,gradientMap:d&&"object"==typeof d?{...d,ramp:a(d.ramp)}:void 0,erosion:u&&"object"==typeof u?{...u,mask:a(u.mask)}:void 0,uvDistortion:f&&"object"==typeof f?{...f,map:a(f.map)}:void 0}}const ga=new st,va=new et,xa=new st,Sa=new st,ba=new et,wa=new st,Ma=new st,za=new et,_a=new st;class Aa{get autoDestroy(){return"destroy"===this.stopAction}set autoDestroy(t){t?this.stopAction="destroy":"destroy"===this.stopAction&&(this.stopAction="none")}get prewarmTime(){return this.prewarmTimeValue}set prewarmTime(t){this.prewarmTimeValue=t>0?t:0}get duration(){return this.durationValue}set duration(t){this.durationValue=t>Co?t:Co}set time(t){const e=this.duration;let s=Number.isFinite(t)&&t>0?t:0;s>=e&&(s=this.looping?s%e:e);const i=this.emissionState;i.time=s,i.isBursting=!1,i.burstIndex=0,i.burstWaveIndex=0,i.burstWaves=void 0,this.markBurstsBefore(s)}get time(){return this.emissionState.time}get isEmitEnded(){return this.emitEnded}hasPendingEmission(t){return this.emission.hasPendingEmission(t)}isFinished(){return!(this.particleNum>0||this.hasPendingSubEmission())&&(!!this.onlyUsedByOther||(this.looping?this.emitEnded:!this.hasPendingEmission()))}get layers(){return this.layerMaskProxy}get texture(){return this.rendererSettings.texture}set texture(t){this.rendererSettings.texture=t,this.neededToUpdateRender=!0}get material(){return this.materialRef}set material(t){this.materialRef=t,this.applyMaterialSettings(t)}get uTileCount(){return this.rendererSettings.uTileCount}set uTileCount(t){this.rendererSettings.uTileCount=Ki(t),this.neededToUpdateRender=!0}get vTileCount(){return this.rendererSettings.vTileCount}set vTileCount(t){this.rendererSettings.vTileCount=Ki(t),this.neededToUpdateRender=!0}get blendTiles(){return this.rendererSettings.blendTiles}set blendTiles(t){this.rendererSettings.blendTiles=t,this.neededToUpdateRender=!0}get softParticles(){return this.rendererSettings.softParticles}set softParticles(t){this.rendererSettings.softParticles=t,this.neededToUpdateRender=!0}get sortMode(){return this.rendererSettings.sortMode??"none"}set sortMode(t){this.rendererSettings.sortMode=Gi(t),this.neededToUpdateRender=!0}get renderFace(){return this.rendererSettings.renderFace??"both"}set renderFace(t){this.rendererSettings.renderFace=Ji(t),this.neededToUpdateRender=!0}get minParticleSize(){return this.rendererSettings.minParticleSize??0}set minParticleSize(t){this.rendererSettings.minParticleSize=Math.max(0,t),this.neededToUpdateRender=!0}get maxParticleSize(){return this.rendererSettings.maxParticleSize??1/0}set maxParticleSize(t){this.rendererSettings.maxParticleSize=t>0?t:1/0,this.neededToUpdateRender=!0}get pivot(){return this.rendererSettings.pivot}set pivot(t){this.rendererSettings.pivot=Xi(t),this.neededToUpdateRender=!0}get lighting(){return this.rendererSettings.lighting??"fixed"}set lighting(t){this.rendererSettings.lighting=qi(t),this.neededToUpdateRender=!0}get rim(){return this.rendererSettings.rim}set rim(t){this.rendererSettings.rim=Vi(t),this.neededToUpdateRender=!0}get mapUV(){return this.rendererSettings.mapUV}set mapUV(t){this.rendererSettings.mapUV=Di(t),this.neededToUpdateRender=!0}get gradientMap(){return this.rendererSettings.gradientMap}set gradientMap(t){this.rendererSettings.gradientMap=Ni(t),this.neededToUpdateRender=!0}get erosion(){return this.rendererSettings.erosion}set erosion(t){this.rendererSettings.erosion=Ri(t),this.neededToUpdateRender=!0}get uvDistortion(){return this.rendererSettings.uvDistortion}set uvDistortion(t){this.rendererSettings.uvDistortion=Li(t),this.neededToUpdateRender=!0}measureMotionScale(t){if(!this.worldSpace)return 1;const e=t.elements;return(Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2])+Math.sqrt(e[4]*e[4]+e[5]*e[5]+e[6]*e[6])+Math.sqrt(e[8]*e[8]+e[9]*e[9]+e[10]*e[10]))/3}get softNearFade(){return this.rendererSettings.softNearFade}set softNearFade(t){this.rendererSettings.softNearFade=tn(t,0),this.neededToUpdateRender=!0}get softFarFade(){return this.rendererSettings.softFarFade}set softFarFade(t){this.rendererSettings.softFarFade=tn(t,1),this.neededToUpdateRender=!0}get instancingGeometry(){return this.rendererSettings.instancingGeometry}set instancingGeometry(t){this.restartKeepingPause();const e=this.rendererSettings,s=t.length/3*2,i=e.instancingGeometry;var n,r;e.instancingGeometry=t,t.length===i.length&&function(t,e){for(let s=0;s<t.length;s++)if(t[s]>=e)return!1;return!0}(e.instancingIndices,t.length/3)||(e.instancingIndices=wi(t)),e.instancingUVs?.length===s&&(n=e.instancingUVs,r=i,void 0===n||n!==Po.get(r))||(e.instancingUVs=To(t)),e.instancingNormals&&(e.instancingNormals.length!==t.length||function(t,e){return void 0!==t&&t===Oo.get(e)}(e.instancingNormals,i))&&(e.instancingNormals=Vo(t)),e.instancingUVs2&&e.instancingUVs2.length!==s&&(e.instancingUVs2=void 0),this.ensureMeshNormals(),this.neededToUpdateRender=!0}ensureMeshNormals(){const t=this.rendererSettings;t.renderMode!==exports.RenderMode.Mesh||t.instancingNormals||(t.instancingNormals=Vo(t.instancingGeometry))}restartKeepingPause(){const t=this.paused;this.restart(),this.particles.length=0,this.paused=t}get instancingIndices(){return this.rendererSettings.instancingIndices}set instancingIndices(t){this.rendererSettings.instancingIndices=t,this.neededToUpdateRender=!0}get instancingUVs(){return this.rendererSettings.instancingUVs??To(this.rendererSettings.instancingGeometry)}set instancingUVs(t){this.rendererSettings.instancingUVs=t,this.neededToUpdateRender=!0}get instancingUVs2(){return this.rendererSettings.instancingUVs2}set instancingUVs2(t){this.rendererSettings.instancingUVs2=t,this.neededToUpdateRender=!0}get blending(){return this.rendererSettings.materialBlendMode}set blending(t){this.rendererSettings.materialBlendMode=t,this.neededToUpdateRender=!0}get transparent(){return this.rendererSettings.materialTransparent}set transparent(t){this.rendererSettings.materialTransparent=t,this.neededToUpdateRender=!0}get depthTest(){return this.rendererSettings.materialDepthTest}set depthTest(t){this.rendererSettings.materialDepthTest=t,this.neededToUpdateRender=!0}get depthWrite(){return this.rendererSettings.materialDepthWrite}set depthWrite(t){this.rendererSettings.materialDepthWrite=t,this.neededToUpdateRender=!0}get alphaTest(){return this.rendererSettings.materialAlphaTest}set alphaTest(t){this.rendererSettings.materialAlphaTest=Zi(t),this.neededToUpdateRender=!0}get renderMode(){return this.rendererSettings.renderMode}set renderMode(t){if(this.rendererSettings.renderMode!==t){let e=!1;switch(this.rendererSettings.renderMode===exports.RenderMode.Trail&&(e=!0),this.rendererSettings.renderMode===exports.RenderMode.Mesh&&(this.startRotation=new Xt(0)),t){case exports.RenderMode.Trail:this.rendererEmitterSettings={startLength:new Xt(30),followLocalOrigin:!1},e=!0;break;case exports.RenderMode.Mesh:this.rendererEmitterSettings={},this.startRotation=new oe(new st(0,1,0),new Xt(0));break;case exports.RenderMode.StretchedBillBoard:this.rendererEmitterSettings={speedFactor:0,lengthFactor:2};break;case exports.RenderMode.BillBoard:case exports.RenderMode.VerticalBillBoard:case exports.RenderMode.HorizontalBillBoard:case exports.RenderMode.Beam:this.rendererEmitterSettings={}}this.rendererSettings.renderMode=t,e&&this.restartKeepingPause(),this.ensureMeshNormals(),this.neededToUpdateRender=!0}}get renderOrder(){return this.rendererSettings.renderOrder}set renderOrder(t){this.rendererSettings.renderOrder=t,this.neededToUpdateRender=!0}get renderingGroupId(){return this.rendererSettings.renderingGroupId}set renderingGroupId(t){this.rendererSettings.renderingGroupId=t,this.neededToUpdateRender=!0}get applyFog(){return this.rendererSettings.applyFog}set applyFog(t){this.rendererSettings.applyFog=t,this.neededToUpdateRender=!0}get applyImageProcessing(){return!1!==this.rendererSettings.applyImageProcessing}set applyImageProcessing(t){this.rendererSettings.applyImageProcessing=t,this.neededToUpdateRender=!0}get playbackSpeed(){return this.playbackSpeedValue}set playbackSpeed(t){this.playbackSpeedValue=t>0&&t<1/0?t:0}get timeDilation(){return this.timeDilationValue}set timeDilation(t){this.timeDilationValue=t>0&&t<1/0?t:0}get emissionMultiplier(){return this.emissionMultiplierValue}set emissionMultiplier(t){this.emissionMultiplierValue=Number.isFinite(t)&&t>=0?t:0}get seed(){return this.seedValue}set seed(t){this.seedValue=t,this.rng=void 0===t?void 0:P(t),void 0!==this.emissionState&&0===this.emissionState.time&&0===this.particleNum&&(this.emission.memory.length=0,this.initSystemGenerators())}constructor(t){var e,s;if(this.ignoreStopAction=!1,this.prewarmTimeValue=0,this.durationValue=1,this.store=new Be(64),this.emitterVelocity=new st,this.finishedEventFired=!1,this.clock=new $o,this.tempEmitterPos=new st,this.stepMatrix=new at,this.spawner=new Jo(this),this.emission=new wo(this,this.spawner),this.events=new Mo,this.materialRef=null,this.qualityFactor=1,this.destroyed=!1,this.behaviorPlan=new go,this.playbackSpeedValue=1,this.timeDilationValue=1,this.emissionMultiplierValue=1,this.cullingMode="always",this.scalingMode="local",this.motionScale=1,this.alignToDirection=!1,this.culled=!1,this.bounds=new xo,this.firstTimeUpdate=!0,this.beamEndScratch=new st,this.rebindParticles=()=>this.spawner.rebind(),this.particleDiedEvent={type:"particleDied",particleSystem:this},this.fireParticleDied=t=>{const e=this.particleDiedEvent;e.particle=t,this.events.fire(e),e.particle=void 0},this.ringStep={pause:!0,loopStart:0,loopEnd:1},this.stopActionPending=!1,this.sceneRef=t.scene,this.layerMaskProxy={mask:t.layerMask??268435455},Object.defineProperty(this.layerMaskProxy,"mask",{enumerable:!0,get:()=>this.rendererSettings.layerMask,set:t=>{this.rendererSettings.layerMask=t,this.neededToUpdateRender=!0}}),this.stopAction=ji(t.stopAction??(!0===t.autoDestroy?"destroy":void 0)),this.duration=t.duration??1,this.startDelay=t.startDelay??new Xt(0),this.looping=t.looping??!0,this.prewarm=t.prewarm??!1,this.prewarmTime=t.prewarmTime??0,this.startLife=t.startLife??new Xt(5),this.startSpeed=t.startSpeed??new Xt(0),this.startRotation=t.startRotation??new Xt(0),this.startSize=t.startSize??new Xt(1),this.startColor=t.startColor??new pe(new Pt(1,1,1,1)),this.emissionOverTime=t.emissionOverTime??new Xt(10),this.emissionOverDistance=t.emissionOverDistance??new Xt(0),this.emissionBursts=sn(t.emissionBursts),this.maxParticles="number"==typeof(e=t.maxParticles)&&e>=0&&e<1/0?Math.floor(e):void 0,this.ringBufferMode=Qi(t.ringBufferMode),this.ringBufferLoopRange=Hi(t.ringBufferLoopRange),this.onlyUsedByOther=t.onlyUsedByOther??!1,this.emitterShape=t.shape??new mi,this.behaviors=t.behaviors??[],this.worldSpace=t.worldSpace??!1,this.rendererEmitterSettings=t.rendererEmitterSettings??{},t.renderMode===exports.RenderMode.Trail){const t={...this.rendererEmitterSettings};this.rendererEmitterSettings=t,t.startLength=t.startLength??new Xt(30),t.followLocalOrigin=t.followLocalOrigin??!1}if(t.renderMode===exports.RenderMode.StretchedBillBoard){const e={...this.rendererEmitterSettings};this.rendererEmitterSettings=e,void 0!==t.speedFactor&&(e.speedFactor=t.speedFactor),e.speedFactor=e.speedFactor??0,e.lengthFactor=e.lengthFactor??0}this.rendererSettings={instancingGeometry:t.instancingGeometry??zo,instancingIndices:t.instancingIndices??Ao,instancingUVs:t.instancingUVs??(t.instancingGeometry?To(t.instancingGeometry):_o),instancingUVs2:t.instancingUVs2,instancingNormals:t.instancingNormals,renderMode:t.renderMode??exports.RenderMode.BillBoard,renderOrder:t.renderOrder??0,uTileCount:Ki(t.uTileCount),vTileCount:Ki(t.vTileCount),blendTiles:t.blendTiles??!1,softParticles:t.softParticles??!1,softNearFade:tn(t.softNearFade,0),softFarFade:tn(t.softFarFade,1),materialBlendMode:t.blendMode??r.Constants.ALPHA_ADD,materialTransparent:t.transparent??!0,materialDepthTest:t.depthTest??!0,materialDepthWrite:t.depthWrite??!1,materialAlphaTest:Zi(t.alphaTest),texture:t.texture??null,reflectionTexture:null,reflectionLevel:1,reflectionAtlas:null,layerMask:t.layerMask??268435455,pivot:Xi(t.pivot),sortMode:Gi(t.sortMode),renderFace:Ji(t.renderFace),minParticleSize:Math.max(0,t.minParticleSize??0),maxParticleSize:t.maxParticleSize??1/0,renderingGroupId:t.renderingGroupId??0,applyFog:t.applyFog??!0,applyImageProcessing:t.applyImageProcessing??!0,lighting:qi(t.lighting),rim:Vi(t.rim),mapUV:Di(t.mapUV),gradientMap:Ni(t.gradientMap),erosion:Ri(t.erosion),uvDistortion:Li(t.uvDistortion)},this.flip=(s=t.flip)&&(s.x>0||s.y>0)?s.clone():void 0,this.playbackSpeed=t.playbackSpeed??1,this.cullingMode=Wi(t.cullingMode),this.scalingMode=Yi(t.scalingMode),this.alignToDirection=!0===t.alignToDirection,this.seed=t.seed,this.ensureMeshNormals(),this.materialRef=t.material??null,this.applyMaterialSettings(this.materialRef,{blendMode:t.blendMode,transparent:t.transparent,depthTest:t.depthTest,depthWrite:t.depthWrite,alphaTest:t.alphaTest,texture:t.texture,layerMask:t.layerMask}),this.neededToUpdateRender=!0,this.particles=[],this.startTileIndex=t.startTileIndex||new Xt(0),this.emitter=new Xr(this,t.scene),this.paused=!1,this.particleNum=0,this.emissionState={isBursting:!1,burstParticleIndex:0,burstParticleCount:0,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,travelDistance:0},this.initSystemGenerators(),this.emitEnded=!1,this.prewarmed=!1}watchEnvAtlas(t,e){t?.onDisposeObservable.addOnce(()=>{if(this.destroyed||this.rendererSettings.reflectionAtlas!==t)return;this.rendererSettings.reflectionAtlas=null,e?.reflectionAtlas===t&&(e.reflectionAtlas=null),this.neededToUpdateRender=!0;const s=this.rendererSettings.reflectionTexture;s?.isCube&&s.getScene()&&this.sceneRef&&fo(s,this.sceneRef,t=>{this.destroyed||this.rendererSettings.reflectionTexture!==s||(this.rendererSettings.reflectionAtlas=t,e&&null==e.reflectionAtlas&&(e.reflectionAtlas=t),this.watchEnvAtlas(t,e),this.neededToUpdateRender=!0)})})}applyMaterialSettings(t,e={}){if(!this.rendererSettings)return;const s=function(t,e,s){const i=void 0!==e.texture?e.texture:[t?.albedoTexture,t?.diffuseTexture,t?.emissiveTexture,t?.opacityTexture,t?.baseTexture].find(t=>t instanceof b.Texture)??s.texture??null,n=t?.reflectionTexture??t?.environmentTexture??s.reflectionTexture??null,r="number"==typeof n?.level?n.level:1,o=e.blendMode??("number"==typeof t?.alphaMode?t.alphaMode:s.materialBlendMode),a=e.transparent??("function"==typeof t?.needAlphaBlending?t.needAlphaBlending():"number"==typeof t?.alpha?t.alpha<1:s.materialTransparent),h=e.depthTest??("boolean"==typeof t?.disableDepthTest?!t.disableDepthTest:s.materialDepthTest),l=e.depthWrite??("boolean"==typeof t?.disableDepthWrite?!t.disableDepthWrite:"boolean"==typeof t?.forceDepthWrite?t.forceDepthWrite:s.materialDepthWrite),c=e.alphaTest??(()=>{const e=t?.transparencyMode,i=1===e||3===e;return i&&"number"==typeof t?.alphaCutOff?t.alphaCutOff:i&&"number"==typeof t?.alphaCutOffValue?t.alphaCutOffValue:t?0:s.materialAlphaTest})();return{texture:i,reflectionTexture:n,reflectionLevel:"number"==typeof t?.reflectionLevel?t.reflectionLevel:r,reflectionAtlas:Bo(t?.reflectionAtlas)??Bo(e.reflectionAtlas)??Bo(s.reflectionAtlas),blendMode:o,transparent:a,depthTest:h,depthWrite:l,alphaTest:c}}(t,e,this.rendererSettings);this.rendererSettings.texture=s.texture,this.rendererSettings.reflectionTexture=s.reflectionTexture,this.rendererSettings.reflectionLevel=s.reflectionLevel;let i=s.reflectionAtlas;const n=s.reflectionTexture;!i&&n?.isCube&&(i=ao(n,this.sceneRef),!i&&this.sceneRef&&(fo(n,this.sceneRef,e=>{this.rendererSettings.reflectionAtlas!==e&&(this.rendererSettings.reflectionAtlas=e,t&&!Bo(t.reflectionAtlas)&&(t.reflectionAtlas=e),this.watchEnvAtlas(e,t),this.neededToUpdateRender=!0)}),i=ao(n,this.sceneRef))),this.rendererSettings.reflectionAtlas=i,this.watchEnvAtlas(i,t),this.rendererSettings.materialBlendMode=s.blendMode,this.rendererSettings.materialTransparent=s.transparent,this.rendererSettings.materialDepthTest=s.depthTest,this.rendererSettings.materialDepthWrite=s.depthWrite,this.rendererSettings.materialAlphaTest=Zi(s.alphaTest),void 0!==e.layerMask&&(this.rendererSettings.layerMask=e.layerMask),this.neededToUpdateRender=!0}pause(){this.paused=!0}play(){this.destroyed||(this.isFinished()&&this.restart(),this.resume())}resume(){this.destroyed||(this.paused=!1,this.previousEmitterMatrix=void 0)}stop(){this.restart(),this.pause()}clear(){this.particleNum=0,this.bounds.valid=!1;for(const t of this.behaviors)t instanceof ts&&t.clearEmissions()}clearTrails(){if(this.rendererSettings.renderMode===exports.RenderMode.Trail)for(let t=0;t<this.particleNum;t++)this.particles[t].resetHistory()}setQualityFactor(t){this.qualityFactor=Math.max(.1,Math.min(1,t))}emissionFactor(){return this.qualityFactor*this.emissionMultiplierValue}endEmit(){this.emitEnded=!0,this.events.fire({type:"emitEnd",particleSystem:this})}get isDisposed(){return this.destroyed}dispose(){this.destroyed||(this.destroyed=!0,this.particleNum=0,this._renderer&&this._renderer.deleteSystem(this),function(t){Yr++;try{t.dispose()}finally{Yr--}}(this.emitter),this.events.fire({type:"destroy",particleSystem:this}))}initSystemGenerators(){const t=this.rng,e=void 0===t?void 0:A(t);try{this.clock.setStartDelay(this.emission.rollGenerators())}finally{void 0!==t&&A(e??null)}}restart(){this.destroyed||(this.emission.memory.length=0,this.paused=!1,this.particleNum=0,this.bounds.valid=!1,this.clock.reset(),void 0!==this.seedValue&&(this.rng=P(this.seedValue)),this.emissionState.isBursting=!1,this.emissionState.burstIndex=0,this.emissionState.burstWaveIndex=0,this.emissionState.burstWaves=void 0,this.emissionState.time=0,this.emissionState.waitEmiting=0,this.emissionState.travelDistance=0,this.emissionState.previousWorldPos=void 0,this.emissionState.burstParticleIndex=0,this.emissionState.burstParticleCount=0,this.emissionBursts.forEach(t=>Object.assign(t,en(t))),this.emissionBursts.sort((t,e)=>t.time-e.time),this.behaviors.forEach(t=>t.reset()),this.emitterShape.reset?.(),this.emitEnded=!1,this.finishedEventFired=!1,this.stopActionPending=!1,this.prewarmed=!1,this.initSystemGenerators(),this.previousEmitterPos=void 0,this.previousEmitterMatrix=void 0,this.emitterVelocity.set(0,0,0))}update(t,e=1/0,s){if(this.paused||this.destroyed)return;const i=this.playbackSpeed*this.timeDilationValue;if(t=$o.frameSeconds(t,i),this.culled)return"pauseAndCatchUp"===this.cullingMode&&this.clock.deferCatchUp(t),void(this.previousEmitterMatrix=void 0);if(this.clock.owesCatchUp){if(this.catchUp(s??performance.now()+Aa.catchUpBudgetMs),this.paused||this.destroyed)return;(this.previousEmitterMatrix??(this.previousEmitterMatrix=new at)).copy(this.emitter.matrixWorld)}if(this.firstTimeUpdate&&(this.firstTimeUpdate=!1,this.emitter.computeWorldMatrix(!0)),!this.looping&&this.finishedEventFired&&0===this.particleNum){if(this.applyStopAction(),this.destroyed)return;return void this.clock.accrue(t,i)}if(this.looping&&this.prewarm&&!this.prewarmed&&(this.runPrewarm(),this.paused||this.destroyed))return;this.neededToUpdateRender&&(this._renderer&&this._renderer.updateSystem(this),this.neededToUpdateRender=!1);const n=this.emitter.matrixWorld.elements;if(this.tempEmitterPos.set(n[12],n[13],n[14]),void 0!==this.previousEmitterPos&&t>0&&this.emitterVelocity.copy(this.tempEmitterPos).sub(this.previousEmitterPos).divideScalar(t),(this.previousEmitterPos??(this.previousEmitterPos=new st)).copy(this.tempEmitterPos),this.clock.delaying&&(!this.prewarm||!this.looping)&&0===(t=this.clock.consumeStartDelay(t)))return;const r=this.clock.accrue(t,i);if(0===r)return;const o=this.emitter.matrixWorld,a=this.previousEmitterMatrix,h=r>1&&void 0!==a&&!a.equals(o);h&&(a.decompose(ga,va,xa),o.decompose(Sa,ba,wa));let l=o;for(let t=0;t<r;t++){if(h&&t+1<r){const e=(t+1)/r;Ma.copy(ga).lerp(Sa,e),za.copy(va).slerp(ba,e),_a.copy(xa).lerp(wa,e),l=this.stepMatrix.compose(Ma,za,_a)}else l=o;if(this.simulateStep(Co,l),this.paused||this.destroyed)break;if(e!==1/0&&t+1<r&&performance.now()>=e)break}this.destroyed||(this.previousEmitterMatrix??(this.previousEmitterMatrix=new at)).copy(l)}catchUp(t){let e=this.clock.takeCatchUpSteps();for(;e-- >0&&(this.simulateStep(Co),!this.paused&&!this.destroyed)&&!(e>0&&performance.now()>=t););}markBurstsBefore(t){const e=this.emissionState,s=this.emissionBursts,i=e.burstWaves??(e.burstWaves=[]);for(;e.burstIndex<s.length&&s[e.burstIndex].time<t;){const n=s[e.burstIndex],r=So(n),o=bo(n);let a=0;if(o>0)for(;a<r&&n.time+a*o<t;)a++;else a=r;i[e.burstIndex]=a,e.burstIndex++}}runPrewarm(){this.prewarmed=!0;const t=this.prewarmTime>0?this.prewarmTime:this.duration,e=Math.min(this.duration,t,Math.max(0,Aa.maxPrewarmSeconds)),s=Math.round(e/Co);if(e<this.duration){const t=this.emissionState;t.time=this.duration-s*Co,this.markBurstsBefore(t.time)}for(let t=0;t<s;t++)if(this.simulateStep(Co),this.paused||this.destroyed)return}getWorldBounds(t,e){if(!this.bounds.toWorld(t,e,this.emitter))return!1;if(this.rendererSettings.renderMode===exports.RenderMode.Beam){const s=this.beamEndScratch;if(!this.getBeamEnd(s))return!0;const i=this.bounds.worldPadding(this.emitter);t.set(Math.min(t.x,s.x-i),Math.min(t.y,s.y-i),Math.min(t.z,s.z-i)),e.set(Math.max(e.x,s.x+i),Math.max(e.y,s.y+i),Math.max(e.z,s.z+i))}return!0}getBeamEnd(t){const e=this.beamEnd;if(void 0===e)return!1;const s=e;if("function"==typeof s.getAbsolutePosition){const e=s.getAbsolutePosition();t.set(e.x,e.y,e.z)}else{const s=e;t.set(s.x,s.y,s.z)}return!0}setWorldBounds(t,e,s,i,n,r,o){this.bounds.setWorld(t,e,s,i,n,r,o)}get simulationStep(){return Co}get simulationResidual(){return this.paused?0:this.clock.residual}simulateStep(t,e=this.emitter.matrixWorld){const s=this.rng;if(void 0===s)return void this.stepOnce(t,e);const i=A(s);try{this.stepOnce(t,e)}finally{A(i)}}stepOnce(t,e){if(this.destroyed)return;this.spawner.fitRing(),this.motionScale=this.measureMotionScale(e),this.onlyUsedByOther||this.emission.emit(t,this.emissionState,e);const s=this.particles,i=this.behaviors,n=this.particleNum,r=this.store,o=this.rendererSettings.renderMode,a=o===exports.RenderMode.Trail,h=this.behaviorPlan.steps(i),l=this.behaviorPlan.changesSize,c=this.behaviorPlan.changesColor;!function(t,e,s,i,n,r){const o=3*e;t.useSizeSnapshot(s),t.useColorSnapshot(i),t.previousPosition.set(t.position.subarray(0,o)),s&&t.previousSize.set(t.size.subarray(0,o)),n&&(t.keepPreviousVelocity()&&r(),t.previousVelocity.set(t.velocity.subarray(0,o))),i&&t.previousColor.set(t.color.subarray(0,4*e))}(r,n,l,c,o===exports.RenderMode.StretchedBillBoard,this.rebindParticles),this.emitterShape.update(this,t),function(t,e,s,i,n,r){for(let o=0;o<t.length;o++){const a=t[o],h=a.behaviors;for(let t=0;t<h.length;t++)h[t].frameUpdate(n);if(0===i)continue;if(void 0!==a.run){a.run(e,s,i,n,r);continue}const l=h[0];if(void 0===l.updateAll)for(let t=0;t<i;t++){const e=s[t];e.age<e.life&&l.update(e,n)}else l.updateAll(s,i,n)}}(h,i,s,n,t,r);const u=this.events.has("particleDied")?this.fireParticleDied:void 0;let d=this.particleNum;if(a){const i=this.rendererEmitterSettings;!function(t,e,s,i){const n=t.scalars,r=Be.SCALAR_STRIDE,o=t.previousSize,a=t.size,h=t.previousColor,l=t.color;for(let t=0,c=0,u=0,d=0;t<e;t++,c+=3,u+=4,d+=r)0===n[d+Be.AGE]&&(s&&(o[c]=a[c],o[c+1]=a[c+1],o[c+2]=a[c+2]),i&&(h[u]=l[u],h[u+1]=l[u+1],h[u+2]=l[u+2],h[u+3]=l[u+3]))}(r,n,l,c),function(t,e,s,i,n,r){if(n){for(let s=0;s<i;s++){const i=e[s];i.localPosition?(i.position.copy(i.localPosition),i.position.applyMatrix4(i.parentMatrix??r)):i.position.addScaledVector(i.velocity,t*i.speedModifier),i.age+=t}return}const o=s.scalars,a=Be.SCALAR_STRIDE,h=s.position,l=s.velocity;for(let e=0,s=0,n=0;e<i;e++,s+=3,n+=a){const e=t*o[n+Be.SPEED_MODIFIER];h[s]+=l[s]*e,h[s+1]+=l[s+1]*e,h[s+2]+=l[s+2]*e,o[n+Be.AGE]+=t}}(t,s,r,n,Boolean(i.followLocalOrigin),e),function(t,e,s,i,n){const r=s.dieWithParticle,o=s.recordWorldSpace&&!i,a=s.sideAxis,h=i||Boolean(s.recordWorldSpace),l=Ir(s),c=Nr(s);for(let s=0;s<e;s++){const e=t[s],i=e.age<e.life;if(r&&!i){e.resetHistory();continue}let u=!1;if(l>0&&i&&e.historyCount>1){const t=e.historyDistances,s=e.historyCount;u=t[e.getHistoryIndex(s-1)]-t[e.getHistoryIndex(s-2)]<l}if(e.update(u,!o),o&&i){const t=(e.historyHead+e.historyCapacity-1)%e.historyCapacity*3,s=e.historyPositions;Io.set(s[t],s[t+1],s[t+2]),Io.applyMatrix4(e.parentMatrix??n),s[t]=Io.x,s[t+1]=Io.y,s[t+2]=Io.z,e.measureHeadDistance()}if(c!==1/0){const t=e.historyAges,s=e.age;for(;e.historyCount>0&&s-t[e.getHistoryIndex(0)]>c;)e.dropOldest()}if(a&&i){e.ensureSideHistory();const t=(e.historyHead+e.historyCapacity-1)%e.historyCapacity*3,s=e.historySides;let i=a.x,r=a.y,o=a.z;if(h){const t=(e.parentMatrix??n).elements,s=t[0]*i+t[4]*r+t[8]*o,a=t[1]*i+t[5]*r+t[9]*o;o=t[2]*i+t[6]*r+t[10]*o,i=s,r=a}s[t]=i,s[t+1]=r,s[t+2]=o}}}(s,n,i,this.worldSpace,e),d=function(t,e,s,i){const n=e.scalars,r=Be.SCALAR_STRIDE;for(let o=0;o<s;o++){const a=t[o],h=o*r;n[h+Be.AGE]>=n[h+Be.LIFE]&&0===a.historyCount&&(No(t,e,o,s-1),s--,o--,void 0!==i&&i(a))}return s}(s,r,d,u)}else d=function(t,e,s,i,n,r,o,a,h,l){const c=s.scalars,u=void 0!==l&&l.pause,d=Be.SCALAR_STRIDE,f=s.position,p=s.velocity,m=s.previousSize,y=s.size,g=s.previousColor,v=s.color,x=o.due,S=o.min,b=o.max;let w=x?1/0:S.x,M=x?1/0:S.y,z=x?1/0:S.z,_=x?-1/0:b.x,A=x?-1/0:b.y,P=x?-1/0:b.z,O=x?0:o.maxSize,T=x?0:o.maxSpeedSq;for(let o=0;o<i;o++){const a=o*d;let S=c[a+Be.AGE];const b=3*o,V=x||0===S;if(0===S&&(n&&(m[b]=y[b],m[b+1]=y[b+1],m[b+2]=y[b+2]),r)){const t=4*o;g[t]=v[t],g[t+1]=v[t+1],g[t+2]=v[t+2],g[t+3]=v[t+3]}const E=c[a+Be.LIFE],C=void 0===l?1/0:u?E:Ro(l,E),$=S>=C,I=$?0:t*c[a+Be.SPEED_MODIFIER],N=p[b],F=p[b+1],R=p[b+2],B=f[b]+N*I,U=f[b+1]+F*I,L=f[b+2]+R*I;if(f[b]=B,f[b+1]=U,f[b+2]=L,V&&(w=Math.min(w,B),_=Math.max(_,B),M=Math.min(M,U),A=Math.max(A,U),z=Math.min(z,L),P=Math.max(P,L),O=Math.max(O,Math.max(y[b],Math.max(y[b+1],y[b+2])))),!$)if(T=Math.max(T,N*N+F*F+R*R),S+=t,c[a+Be.AGE]=S,void 0!==l){if(S>C)c[a+Be.AGE]=C;else if(!u&&C===1/0&&S>=l.loopEnd*E){const t=l.loopStart*E+(S-l.loopEnd*E)%((l.loopEnd-l.loopStart)*E);c[a+Be.AGE]=t>0?t:Fo*E,m[b]=y[b],m[b+1]=y[b+1],m[b+2]=y[b+2];const e=4*o;g[e]=v[e],g[e+1]=v[e+1],g[e+2]=v[e+2],g[e+3]=v[e+3]}}else if(S>=E){const t=No(e,s,o,i-1);i--,o--,void 0!==h&&h(t)}}return o.store(i,x,w,M,z,_,A,P,O,T,a.rendererSettings,a.rendererEmitterSettings,a.worldSpace,Co),i}(t,s,r,d,l,c,this.bounds,this,u,this.ringBufferStep());this.particleNum=this.destroyed?0:d,this.notifyFinished()}hasPendingSubEmission(){for(const t of this.behaviors)if(t instanceof ts&&t.hasPendingEmission())return!0;return!1}isAlive(t=!0){return!this.isFinished()||t&&this.subEmittersAlive(new Set([this]))}subEmittersAlive(t){for(const e of this.behaviors){if(!(e instanceof ts))continue;const s=e.targetSystem;if(s instanceof Aa&&!t.has(s)&&(t.add(s),s.particleNum>0||s.hasPendingSubEmission()||s.subEmittersAlive(t)))return!0}return!1}get ringBufferActive(){return"disabled"!==this.ringBufferMode&&void 0!==this.maxParticles&&this.rendererSettings.renderMode!==exports.RenderMode.Trail}ringBufferStep(){if(!this.ringBufferActive)return;const t=this.ringStep;t.pause="pauseUntilReplaced"===this.ringBufferMode;const{x:e,y:s}=this.ringBufferLoopRange,i=Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,n=Number.isFinite(s)?Math.min(1,Math.max(0,s)):1;return t.loopStart=Math.min(i,n),t.loopEnd=Math.max(i,n),t}notifyFinished(){this.isFinished()&&(this.finishedEventFired||(this.finishedEventFired=!0,this.stopActionPending=!0,this.events.fire({type:"finished",particleSystem:this})),this.applyStopAction())}applyStopAction(){this.stopActionPending&&("none"===this.stopAction||this.ignoreStopAction||this.onlyUsedByOther||this.destroyed?this.stopActionPending=!1:this.subEmittersAlive(new Set([this]))||(this.stopActionPending=!1,"disable"===this.stopAction?this.emitter.setEnabled(!1):this.dispose()))}emit(t,e,s){this.emission.emit(t,e,s)}toJSON(t,e={}){return ma(this,t)}static fromJSON(t,e,s={},i){const n=new Aa(ya(t,e,i));return n.behaviors=(t.behaviors??[]).map((t,e)=>{const i=Gt(`behaviors[${e}]`,()=>Bs(t,n)),r=t.subParticleSystem;return i&&"EmitSubParticleSystem"===i.type&&"string"==typeof r&&(s[r]=i),i}).filter(t=>null!==t),n}addBehavior(t){this.behaviors.push(t),this._renderer?._invalidateUpdateOrder()}getRendererSettings(){return this.rendererSettings}addEventListener(t,e){this.events.add(t,e)}removeAllEventListeners(t){this.events.removeAll(t)}removeEventListener(t,e){this.events.remove(t,e)}clone(){const t=this.behaviors.map(t=>t.clone());let e;if(this.renderMode===exports.RenderMode.Trail){const t=this.rendererEmitterSettings;e={startLength:t.startLength.clone(),followLocalOrigin:Boolean(t.followLocalOrigin),...la(t),...ca(t),...ua(t),...t.sideAxis?{sideAxis:t.sideAxis.clone()}:{}}}else e=this.renderMode===exports.RenderMode.StretchedBillBoard?{lengthFactor:this.rendererEmitterSettings.lengthFactor,speedFactor:this.rendererEmitterSettings.speedFactor}:{};const s=new Aa({...na(this),shape:this.emitterShape.clone(),instancingGeometry:this.rendererSettings.instancingGeometry,instancingIndices:this.rendererSettings.instancingIndices,instancingUVs:this.rendererSettings.instancingUVs,instancingUVs2:this.rendererSettings.instancingUVs2,instancingNormals:this.rendererSettings.instancingNormals,rendererEmitterSettings:e,material:this.materialRef,texture:this.rendererSettings.texture,behaviors:t,lighting:this.lighting,rim:this.rim,mapUV:this.mapUV,gradientMap:this.gradientMap,erosion:this.erosion,uvDistortion:this.uvDistortion,scene:this.emitter.getScene()});for(const e of t)e instanceof ts&&(e.particleSystem=s);this.tint&&(s.tint=this.tint.clone()),s.emissionMultiplier=this.emissionMultiplier;const i=this.beamEnd;return i&&(s.beamEnd="function"==typeof i.getAbsolutePosition?i:{x:i.x,y:i.y,z:i.z}),s}}function Pa(t){if("ps"===t.type&&t.target instanceof Xr)return t.target.system}function Oa(t){return"object"==typeof t&&null!==t}Aa.catchUpBudgetMs=2,Aa.maxPrewarmSeconds=10;class Ta extends n.TransformNode{constructor(t="QuarksPrefab",e){super(t,e),this.type="QuarksPrefab",this.animationData=[],this.isPlaying=!1,this.currentTime=-1e-5,this.duration=0,this._timeScale=1,this._tempAnimationJSON=[],this._autoUpdate=null,this._pendingEndEmit=new Set,this._pendingObserver=null,this._started=new Set,this._pausedSystems=new Set}get timeScale(){return this._timeScale}set timeScale(t){this._timeScale=t>0&&t<1/0?t:0;for(const t of this.animationData){const e=Pa(t);void 0!==e&&(e.timeDilation=this._timeScale)}}get autoUpdate(){return null!==this._autoUpdate}set autoUpdate(t){t!==this.autoUpdate&&(t?this._autoUpdate=this.getScene().onBeforeRenderObservable.add(()=>this.update()):(this.getScene().onBeforeRenderObservable.remove(this._autoUpdate),this._autoUpdate=null))}registerBatchedRenderer(t){this._batchedRenderer=t}addParticleSystemAnimation(t,e=0,s=0,i=!1){const n={startTime:e,duration:s>0?s:t.system.duration,type:"ps",loop:i,target:t};return this.animationData.push(n),t.system.timeDilation=this._timeScale,this.updateDuration(),n}addThreeAnimation(t,e,s=0,i=e?.duration??0,n=!1,r){const o={startTime:s,duration:i>0?i:e?.duration??0,type:"three",loop:n,target:t,clip:e,clipUUID:r??e?.uuid};return this.animationData.push(o),this.updateDuration(),o}removeAnimation(t){const[e]=this.animationData.splice(t,1),s=e&&Pa(e);void 0===s||this.animationData.some(t=>Pa(t)===s)||(s.timeDilation=1,this._pendingEndEmit.delete(s)&&s.endEmit(),this._started.delete(s),this._pausedSystems.delete(s)),this.updateDuration()}play(){if(!this.isPlaying){this.isPlaying=!0;for(const t of this._pausedSystems)t.resume();this._pausedSystems.clear(),this.animationData.forEach(t=>{"three"===t.type&&this.isInside(t,this.currentTime)&&t.clip?.play?.()})}}pause(){this.isPlaying&&(this.isPlaying=!1,this.animationData.forEach(t=>{const e=Pa(t);void 0===e?t.clip?.pause?.():e.paused||(e.pause(),this._pausedSystems.add(e))}))}stop(){this.pause(),this.currentTime=-1e-5,this.clearPending(),this._started.clear(),this._pausedSystems.clear(),this.animationData.forEach(t=>{const e=Pa(t);void 0===e?t.clip?.stop?.():e.stop()})}update(t){if(this.flushPending(),!this.isPlaying)return;const e=t??this.getScene().getEngine().getDeltaTime()/1e3,s=this.currentTime,i=s+Math.max(e,0)*this._timeScale>=this.duration;if(this.currentTime=i?this.duration:s+Math.max(e,0)*this._timeScale,this.animationData.forEach(t=>{const e=this.isInside(t,s),n=this.isInside(t,this.currentTime),r=!e&&!n&&s<t.startTime&&this.currentTime>=t.startTime+t.duration;if(n&&!e)this.enterTrack(t);else if(r){this.enterTrack(t);const e=Pa(t);void 0!==e?this.addPending(e):t.clip?.stop?.()}else e&&!n&&this.leaveTrack(t,!i)}),i){for(const t of this._started)this._pendingEndEmit.has(t)||t.isEmitEnded||t.endEmit();this._started.clear(),this.isPlaying=!1,this.currentTime=-1e-5}}setTime(t){const e=this.currentTime;this.currentTime=t,this.animationData.forEach(s=>{const i=this.isInside(s,t),n=this.isInside(s,e);if(i&&!n)this.enterTrack(s);else if(!i&&n)return void this.leaveTrack(s,!1);i&&"three"===s.type&&s.clip?.setTime?.(Math.max(t-s.startTime,0))})}dispose(t,e){this.autoUpdate=!1;for(const t of this._pendingEndEmit)t.endEmit();this.clearPending(),this._started.clear(),this._pausedSystems.clear(),super.dispose(t,e)}addPending(t){this._pendingEndEmit.add(t),this._pendingObserver??(this._pendingObserver=this.getScene().onAfterRenderObservable.add(()=>this.flushPending()))}flushPending(){for(const t of this._pendingEndEmit)(t.emissionState.time>0||t.isDisposed)&&(t.endEmit(),this._pendingEndEmit.delete(t));0===this._pendingEndEmit.size&&this.clearPending()}clearPending(){this._pendingEndEmit.clear(),null!==this._pendingObserver&&(this.getScene().onAfterRenderObservable.remove(this._pendingObserver),this._pendingObserver=null)}isInside(t,e){return e>=t.startTime&&e<t.startTime+t.duration}enterTrack(t){const e=Pa(t);if(void 0!==e)return this._pendingEndEmit.delete(e),e.restart(),this._started.add(e),this.isPlaying||(e.pause(),this._pausedSystems.add(e)),void this._batchedRenderer?.addSystem(e);t.clip?.play?.()}leaveTrack(t,e){const s=Pa(t);void 0===s?t.loop&&e?t.clip?.play?.():t.clip?.stop?.():t.loop&&e?s.restart():s.endEmit()}getDuration(){return this.duration}resolveReferences(t){const e={},s=t=>{var i;const r=_i(t);r?e[r]=t:e[i=t.uniqueId.toString()]??(e[i]=t);const o=t.getChildren();for(const t of o)t instanceof n.TransformNode&&s(t)};s(t),this._tempAnimationJSON.forEach(t=>{const s=e[t.targetUUID];if("ps"===t.type&&s instanceof Xr)this.addParticleSystemAnimation(s,t.startTime,t.duration,t.loop);else if("three"===t.type&&s){const e=this.resolveTimelineClip(s,t.clipUUID);this.addThreeAnimation(s,e,t.startTime,t.duration,t.loop,t.clipUUID)}}),this.updateDuration(),this._tempAnimationJSON=[]}toJSON(){return{type:this.type,name:this.name,...1!==this.timeScale?{timeScale:this.timeScale}:{},animationData:this.animationData.map(t=>({startTime:t.startTime,duration:t.duration,type:t.type,targetUUID:zi(t.target),clipUUID:"three"===t.type?t.clipUUID??t.clip?.uuid:void 0,loop:t.loop}))}}static fromJSON(t,e){const s=new Ta(t.name||"QuarksPrefab",e);return"number"==typeof t.timeScale&&(s.timeScale=t.timeScale),Array.isArray(t.animationData)&&(s._tempAnimationJSON=t.animationData.filter(t=>"ps"===t?.type||"three"===t?.type)),s}resolveTimelineClip(t,e){const s=t,i=t.metadata,n=[s.animations,s.animationGroups,i?.animations,i?.animationGroups];for(const t of n){if(!Array.isArray(t))continue;const s=t;if(!e)return s.find(Oa);const i=s.find(t=>{return i=e,Oa(s=t)&&s.uuid===i;var s,i});if(i)return i}}updateDuration(){let t=0;this.animationData.forEach(e=>{const s=e.startTime+e.duration;s>t&&(t=s)}),this.duration=t}}const Va=new WeakMap;function Ea(t,e,s){Va.set(t,{source:e,loaded:s})}function Ca(t){const e=Va.get(t);return void 0!==e&&t.url===e.loaded?e.source:void 0}const $a={[b.Texture.WRAP_ADDRESSMODE]:1e3,[b.Texture.CLAMP_ADDRESSMODE]:1001,[b.Texture.MIRROR_ADDRESSMODE]:1002};function Ia(t){return!!t&&(!/^blob:/i.test(t)&&(!/^data:/i.test(t)||t.includes(",")))}function Na(t){const e=t.rotationQuaternion??a.Quaternion.FromEulerVector(t.rotation);return Array.from(a.Matrix.Compose(t.scaling,e,t.position).asArray())}class Fa{constructor(t){this.options=t,this.meta={geometries:{},materials:{},textures:{}},this.meshGeometries=new Map,this.geometryIds=new Map,this.meshMaterials=[],this.meshMaterialIds=new Map,this.extraTextures=new Map,this.nextId=0}warnDanglingLinks(t){const e=new Set,s=[],i=t=>{e.add(t.uuid),s.push(t),t.children?.forEach(i)};i(t);for(const t of s)for(const[s,i]of Ba(t))""===i||e.has(i)||this.warn(`"${t.name}" has ${s} on node "${i}", which is not in what is written; it loads without that link.`)}warn(t){(this.options.onWarning??(t=>console.warn(`[quarks] ${t}`)))(t)}node(t){const e=t.getChildren(t=>t instanceof n.TransformNode,!0).filter(t=>!1!==this.options.filter?.(t)).map(t=>this.node(t)),s={uuid:zi(t),type:"Group",name:t.name,matrix:Na(t)};if(t.isEnabled(!1)||(s.visible=!1),t instanceof u.Mesh&&!t.isVisible&&(s.isVisible=!1),t instanceof Xr)s.type="ParticleEmitter",s.ps=t.system.toJSON(this.meta);else if(t instanceof Ta){const{type:e,name:i,...n}=t.toJSON();Object.assign(s,n),s.type="QuarksPrefab"}else t instanceof u.Mesh?(s.type="Mesh",s.geometry=this.meshGeometry(t),s.material=this.meshMaterial(t)):t instanceof S.InstancedMesh&&this.warn(`"${t.name}" is an instance of "${t.sourceMesh.name}"; it is written as a group.`);return e.length>0&&(s.children=e),s}id(t){return this.nextId+=1,`${t}_${this.nextId}`}meshGeometry(e){const s=e.geometry?this.geometryIds.get(e.geometry):void 0;if(void 0!==s)return s;const i=e.getVerticesData(t.VertexBuffer.PositionKind);if(!i||0===i.length)return void this.warn(`Mesh "${e.name}" has no vertices; it is written without geometry.`);const n=e.getIndices(),r=wi(i instanceof Float32Array?i:new Float32Array(i),n&&n.length>0?Uint32Array.from(n):void 0),o=t=>{const s=e.getVerticesData(t);return s?Array.from(s):void 0},a={uuid:this.id("quarks_mesh_geometry"),type:"QuarksGeometry",positions:Array.from(i),indices:Array.from(r)},h=o(t.VertexBuffer.UVKind),l=o(t.VertexBuffer.UV2Kind),c=o(t.VertexBuffer.NormalKind);return h&&(a.uvs=h),l&&(a.uvs2=l),c&&(a.normals=c),this.meshGeometries.set(a.uuid,a),e.geometry&&this.geometryIds.set(e.geometry,a.uuid),a.uuid}meshMaterial(t){const e=t.material;if(!e)return;if(!(e instanceof w.StandardMaterial))return void this.warn(`Mesh "${t.name}" has a ${e.getClassName()}; only a StandardMaterial's blend, culling and diffuse texture are written, so it loads without a material.`);let s=this.meshMaterialIds.get(e);if(void 0!==s)return s;s=this.id("quarks_mesh_material"),this.meshMaterialIds.set(e,s);const i=1===e.diffuseColor.r&&1===e.diffuseColor.g&&1===e.diffuseColor.b,n=0===e.emissiveColor.r&&0===e.emissiveColor.g&&0===e.emissiveColor.b;1===e.alpha&&i&&n||this.warn(`Mesh "${t.name}": its material's alpha and colours are not written; it loads opaque white.`);const o={uuid:s,type:"MeshBasicMaterial"};return e.alphaMode!==r.Constants.ALPHA_COMBINE&&(o.alphaMode=e.alphaMode),e.backFaceCulling&&(o.side=0),0!==e.alphaCutOff&&(o.alphaTest=e.alphaCutOff),e.disableDepthWrite||(o.depthWrite=!0),this.meshMaterials.push({json:o,map:e.diffuseTexture}),s}texture(t){for(const[e,s]of Object.entries(this.meta.textures))if(s===t)return e;let e=this.extraTextures.get(t);return void 0===e&&(e=this.id("quarks_mesh_texture"),this.extraTextures.set(t,e)),e}finish(t){const e=this.meshMaterials.map(({json:t,map:e})=>e?{...t,map:this.texture(e)}:t);this.warnDanglingLinks(t);const s=[],i=new Map,n=[],r=[...Object.entries(this.meta.textures),...[...this.extraTextures].map(([t,e])=>[e,t])];for(const[t,e]of r){if(null===e)continue;const r={uuid:t},o=e instanceof b.Texture?this.options.imageUrl?this.options.imageUrl(e):Ca(e)??e.url:null;if(Ia(o)){let t=i.get(o);void 0===t&&(t=`quarks_image_${i.size+1}`,i.set(o,t),s.push({uuid:t,url:o})),r.image=t}else this.warn(`Texture "${e.name}" has no url a file can point at (made in code, a blob: url, or an image embedded in a glTF); it is written without its image and loads as no texture. Give it a file url or a data: URI before saving.`);e instanceof b.Texture&&Object.assign(r,Ua(e)),n.push(r)}const o=Object.values(this.meta.materials).map(t=>{const{sourceMaterial:e,...s}=t;return s});return{metadata:{version:4.5,type:"Object3D",generator:this.options.generator??"babylon.quarks",quarksFormat:2},geometries:[...Object.values(this.meta.geometries).filter(Ra),...this.meshGeometries.values()],materials:[...o,...e],textures:n,images:s,object:t}}}function Ra(t){return"type"in t&&"QuarksGeometry"===t.type&&Array.isArray(t.positions)}function*Ba(t){const e=t.ps;for(const t of e?.behaviors??[])"EmitSubParticleSystem"===t.type&&"subParticleSystem"in t&&"string"==typeof t.subParticleSystem&&(yield["a sub emitter",t.subParticleSystem]);"mesh_surface"===e?.shape?.type&&"string"==typeof e.shape.mesh&&(yield["a mesh surface shape",e.shape.mesh]);for(const e of t.animationData??[])"string"==typeof e.targetUUID&&(yield["a prefab animation",e.targetUUID])}function Ua(t){const e={};return t.invertY||(e.invertY=!1),t.noMipmap&&(e.noMipmap=!0),t.samplingMode!==r.Constants.TEXTURE_TRILINEAR_SAMPLINGMODE&&(e.samplingMode=t.samplingMode),t.wrapU===b.Texture.WRAP_ADDRESSMODE&&t.wrapV===b.Texture.WRAP_ADDRESSMODE||(e.wrap=[$a[t.wrapU]??1e3,$a[t.wrapV]??1e3]),1===t.uScale&&1===t.vScale||(e.repeat=[t.uScale,t.vScale]),0===t.uOffset&&0===t.vOffset||(e.offset=[t.uOffset,t.vOffset]),0!==t.wAng&&(e.rotation=t.wAng),e}function La(t){return null!==t&&"object"==typeof t}function Da(t){if(!Array.isArray(t))return Wt("This part is not a list; it is skipped."),[];const e=[];return t.forEach((t,s)=>{La(t)?e.push(t):Gt(`[${s}]`,()=>Wt("This entry is not an object; it is skipped."))}),e}function ka(t,e){const s=La(t)?t[e]:void 0;return Array.isArray(s)?s:[]}const qa=new WeakMap,Ga=new WeakMap,Ja=new WeakMap,Wa=new WeakMap,ja=new WeakMap;function Qa(t,e){let s=t.get(e);return void 0===s&&(s=new Map,t.set(e,s)),s}const Ha=new WeakMap,Ya=new WeakMap;function Xa(t){if(!La(t))return t;const e={...t};return Array.isArray(t.images)&&(e.images=t.images.map(t=>{if(!t||"object"!=typeof t)return t;const e={...t};if(Ha.get(t)===e.url&&"string"==typeof e.url){Ha.set(e,e.url);const s=Ya.get(t);void 0!==s&&Ya.set(e,s)}return e})),Array.isArray(t.geometries)&&(e.geometries=t.geometries.map(t=>t&&"object"==typeof t?{...t}:t)),e}const Za=new WeakMap,Ka=t=>t.reason??new Error("[QuarksLoader] The load was aborted."),th=()=>new Error("[QuarksLoader] The scene was disposed while the effect loaded.");function eh(t,e){if(e?.aborted)throw Ka(e);if(t.isDisposed)throw th()}function sh(t,e,s){return eh(e,s),new Promise((i,n)=>{const r=()=>n(Ka(s));s?.addEventListener("abort",r,{once:!0});const o=e.onDisposeObservable.addOnce(()=>n(th()));t.then(i,n).finally(()=>{s?.removeEventListener("abort",r),e.onDisposeObservable.remove(o)})})}class ih{constructor(t,e={}){this.scene=t,this.options=e}async load(t,e={}){const{json:s,baseUrl:i}=await sh(this.fetchEffectDocument(t,e.signal),this.scene,e.signal);return this.loadFromJSON(s,i,e)}async loadFromJSON(t,e,s={}){const i=s.signal;eh(this.scene,i);const n=e??this.options.baseUrl??"",r=Xa(t);await sh(this.resolveResources(r,n),this.scene,i);const o=this.parseDocument(r,"");return await this.finishLoad(o,i),o.root}static disposeEffect(t){Gr(t)}async finishLoad(t,e){try{if(this.options.waitForTextures){for(const e of t.textures)e.delayLoadState===r.Constants.DELAYLOADSTATE_NOTLOADED&&e.delayLoad();await sh(Promise.all(t.textures.map(t=>Za.get(t))),this.scene,e)}eh(this.scene,e)}catch(e){throw this.scene.isDisposed||Gr(t.root),e}}async loadAll(t,e={}){eh(this.scene,e.signal);const s=ih.mapPool(t,e.concurrency,async(s,i)=>{eh(this.scene,e.signal);try{return await this.fetchEffectDocument(s,e.signal)}catch(n){if(!e.continueOnError||e.signal?.aborted||this.scene.isDisposed)throw n;return console.warn(`[QuarksLoader] Failed to fetch effect "${s}" (${i+1}/${t.length}):`,n),null}}),i=await sh(s,this.scene,e.signal);return this.loadDocuments(i,e)}async loadFromJSONAll(t,e={}){const s=t.map(t=>{if(null!==t&&"object"==typeof t&&"json"in t){const e=t;return{json:Xa(e.json),baseUrl:e.baseUrl??this.options.baseUrl??""}}return{json:Xa(t),baseUrl:this.options.baseUrl??""}});return this.loadDocuments(s,e)}async resolveResources(t,e=""){await ih.resolveLinkedResources(t,{baseUrl:e,resolver:this.options.resolver,scene:this.scene,onResourceError:this.options.onResourceError})}static async resolveLinkedResources(t,e={}){const s=e.baseUrl??"",i=e.resolver,n=e.scene;await ih.inlineGeometryEntries(t,async t=>{const e=await ih.resolveWith(i,t,"geometry",s);return ih.fetchJsonWith(i,e,n)},e.onResourceError),await Promise.all(ka(t,"images").map(async t=>{if(!La(t)||"string"!=typeof t.url||!t.url)return;if(Ha.get(t)===t.url)return;const e=t.url,n=await ih.resolveWith(i,e,"image",s);t.url=n,Ha.set(t,n),/^(data|blob):/i.test(n)||Ya.set(t,e)}))}static async resolveExternalGeometries(t,e){await ih.inlineGeometryEntries(t,e)}parse(t,e=""){return this.parseDocument(t,e).root}parseDocument(t,e){const{strict:s,onFormatWarning:i}=this.options,n=[],r=qt({onWarning:(t,e)=>{const r=e?`${t} (at ${e})`:t;s&&n.push(r),i?i(t,e):s||console.warn(`[quarks] ${r}`)}},()=>this.readDocument(t,e));if(n.length>0){ih.disposeEffect(r.root);const t=n.length>1?` (and ${n.length-1} more)`:"";throw new Lt(`${n[0]}${t}`,n)}return r}readDocument(t,e){if(!La(s=t)||!La(s.object))throw new Lt('[QuarksLoader] Not an effect document: it has no "object" to load.');var s;const i=t,n=i.metadata?.quarksFormat;"number"==typeof n&&n>2&&Wt(`This effect was written in format ${n}, newer than the 2 this version of babylon.quarks reads; settings it does not know are left out.`);const r={ownedMaterials:[],images:{},imageSources:{},textures:{},geometries:{},materials:{},format:"number"==typeof n?n:0},{geometries:o,images:a,textures:h,materials:l}=i;o&&Gt("geometries",()=>this.parseGeometries(Da(o),r)),a&&Gt("images",()=>this.parseImages(Da(a),e,r)),h&&Gt("textures",()=>this.parseTextures(Da(h),r)),l&&Gt("materials",()=>this.parseMaterials(Da(l),r));const c=Gt("object",()=>this.parseObject(i.object,r));this.linkReferences(c);const u=[...new Set(Object.values(r.textures).filter(t=>null!==t))];return kr(c,u,r.ownedMaterials),{root:c,textures:u}}parseGeometries(t,e){for(const s of t)if("PlaneGeometry"===s.type){const t=(s.width||1)/2,i=(s.height||1)/2;e.geometries[s.uuid]={positions:new Float32Array([-t,-i,0,t,-i,0,t,i,0,-t,i,0]),indices:new Uint32Array([0,1,2,0,2,3]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),normals:new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1])}}else if("SphereGeometry"===s.type)e.geometries[s.uuid]=this.parseSphereGeometry(s);else if("BufferGeometry"===s.type&&s.data){const t=this.parseBufferGeometry(s.data);e.geometries[s.uuid]=t}else"QuarksGeometry"===s.type&&("string"!=typeof s.url||s.positions||Wt(`Geometry "${s.url}" is an external file; use load(), loadFromJSON(), or resolveResources() before parse().`),e.geometries[s.uuid]=this.share({positions:new Float32Array(s.positions??[]),indices:s.indices?new Uint32Array(s.indices):new Uint32Array(0),uvs:s.uvs?new Float32Array(s.uvs):void 0,uvs2:s.uvs2?new Float32Array(s.uvs2):void 0,normals:s.normals?new Float32Array(s.normals):void 0}))}share(t){if(!1===this.options.shareResources)return t;const e=Qa(Wa,this.scene),s=function(t){let e=2166136261,s=2654435769;const i=[t.positions,t.indices,t.uvs,t.uvs2,t.normals];let n="";for(const t of i){if(void 0===t){n+="-,";continue}const i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n+=i.length+",";for(let t=0;t<i.length;t++)e=Math.imul(e^i[t],16777619),s=Math.imul(s^i[t],1540483477)^s>>>15}return`${n}${(e>>>0).toString(16)}${(s>>>0).toString(16)}`}(t),i=e.get(s);return void 0!==i?i:(e.set(s,t),t)}static clearSharedResources(t){Ja.delete(t),Wa.delete(t),ja.delete(t)}static joinUrl(t,e){return/^(data|blob):/i.test(e)||/^[a-z][a-z0-9+.-]*:\/\//i.test(e)||e.startsWith("/")?e:t+e}parseSphereGeometry(t){const e=t.radius??.5,s=Math.max(3,Math.floor(t.widthSegments??16)),i=Math.max(2,Math.floor(t.heightSegments??8)),n=t.phiStart??0,r=t.phiLength??2*Math.PI,o=t.thetaStart??0,a=t.thetaLength??Math.PI,h=[],l=[],c=[],u=[],d=[];let f=0;for(let t=0;t<=i;t++){const u=[],p=t/i,m=o+p*a;for(let t=0;t<=s;t++){const i=t/s,o=n+i*r,a=-e*Math.cos(o)*Math.sin(m),d=e*Math.cos(m),y=e*Math.sin(o)*Math.sin(m);h.push(a,d,y);const g=Math.hypot(a,d,y)||1;l.push(a/g,d/g,y/g),c.push(i,1-p),u.push(f++)}d.push(u)}const p=o<=0,m=o+a>=Math.PI;for(let t=0;t<i;t++)for(let e=0;e<s;e++){const s=d[t][e+1],n=d[t][e],r=d[t+1][e],o=d[t+1][e+1];0===t&&p||u.push(s,n,o),t===i-1&&m||u.push(n,r,o)}const y=h.length/3>65535?new Uint32Array(u):new Uint16Array(u);return{positions:new Float32Array(h),indices:y,uvs:new Float32Array(c),normals:new Float32Array(l)}}parseBufferGeometry(t){let e,s,i,n=new Float32Array(0),r=new Uint32Array(0);const o=t.attributes?.uv1??t.attributes?.uv2;if(t.interleavedBuffers&&t.arrayBuffers){const r={};for(const[e,s]of Object.entries(t.interleavedBuffers)){const i=t.arrayBuffers[s.buffer];if(i){const t=new Float32Array(Array.isArray(i)?this.int32ArrayToFloat32(i):i);r[e]={data:t,stride:s.stride}}}const a=t=>{const e=t?.isInterleavedBufferAttribute&&void 0!==t.data?r[t.data]:void 0;return e?this.extractInterleavedAttribute(e.data,e.stride,t?.offset,t?.itemSize):void 0};n=a(t.attributes?.position)??n,e=a(t.attributes?.uv),s=a(o),i=a(t.attributes?.normal)}else t.attributes&&(t.attributes.position?.array&&(n=new Float32Array(t.attributes.position.array)),t.attributes.uv?.array&&(e=new Float32Array(t.attributes.uv.array)),o?.array&&(s=new Float32Array(o.array)),t.attributes.normal?.array&&(i=new Float32Array(t.attributes.normal.array)));return t.index&&(r="Uint16Array"===t.index.type?new Uint16Array(t.index.array):new Uint32Array(t.index.array)),r=wi(n,r),{positions:n,indices:r,uvs:e,uvs2:s,normals:i}}extractInterleavedAttribute(t,e,s=0,i=0){const n=Math.floor(t.length/e),r=new Float32Array(n*i);for(let o=0;o<n;o++)for(let n=0;n<i;n++)r[o*i+n]=t[o*e+s+n];return r}int32ArrayToFloat32(t){const e=new ArrayBuffer(4*t.length),s=new Int32Array(e);for(let e=0;e<t.length;e++)s[e]=t[e];return new Float32Array(e)}async resolveResourceUrl(t,e,s){return ih.resolveWith(this.options.resolver,t,e,s)}async fetchEffectDocument(t,e){const s=this.options.baseUrl||t.substring(0,t.lastIndexOf("/")+1),i=await this.resolveResourceUrl(t,"effect",s);return{json:await ih.fetchJsonWith(this.options.resolver,i,void 0,e),baseUrl:s}}async loadDocuments(t,e){if(0===t.length)return[];eh(this.scene,e.signal);const s=new AbortController,i=()=>s.abort(Ka(e.signal));e.signal?.addEventListener("abort",i,{once:!0});try{return await this.loadResolvedDocuments(t,e,s)}finally{e.signal?.removeEventListener("abort",i)}}async loadResolvedDocuments(t,e,s){const i=t.length,n=s.signal,r=new Array(i).fill(null),o=new Array(i).fill(!1);let a=0;const h=(t,s)=>{o[t]||n.aborted||(o[t]=!0,r[t]=s,a++,e.onProgress?.(a,i))};await sh(Promise.all(t.map(async(s,n)=>{if(s)try{await this.resolveResources(s.json,s.baseUrl)}catch(s){if(!e.continueOnError)throw s;console.warn(`[QuarksLoader] Failed to resolve resources for effect ${n+1}/${i}:`,s),t[n]=null,h(n,null)}})),this.scene,n);const l=[],c=[];try{for(let s=0;s<i;s++){if(o[s])continue;const r=t[s];if(!r){h(s,null);continue}let a;try{a=this.parseDocument(r.json,"")}catch(t){if(!e.continueOnError)throw t;console.warn(`[QuarksLoader] Failed to parse effect ${s+1}/${i}:`,t),h(s,null);continue}l.push(a),c.push(this.finishLoad(a,n).then(()=>h(s,a.root)))}await Promise.all(c)}catch(t){throw n.aborted||s.abort(t),Promise.allSettled(c),this.scene.isDisposed||l.forEach(t=>Gr(t.root)),t}return r}static async mapPool(t,e,s){if(0===t.length)return[];const i=void 0!==e&&e>0?e:t.length,n=new Array(t.length);let r=0;const o=Math.min(i,t.length);return await Promise.all(Array.from({length:o},()=>(async()=>{for(;r<t.length;){const e=r++;n[e]=await s(t[e],e)}})())),n}static async resolveWith(t,e,s,i){return t?.resolve?t.resolve(e,s,i):ih.joinUrl(i,e)}static fetchJsonWith(t,e,s,i){const n=async()=>{if(t?.fetchJson)return i?t.fetchJson(e,{signal:i}):t.fetchJson(e);const s=await(i?fetch(e,{signal:i}):fetch(e));if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.json()};if(!s)return n();const r=Qa(ja,s),o=`json|${e}`;let a=r.get(o);return void 0===a&&(a=n().catch(t=>{throw r.get(o)===a&&r.delete(o),t}),r.set(o,a)),a}static async inlineGeometryEntries(t,e,s=ih.warnResourceError){await Promise.all(ka(t,"geometries").map(async t=>{if(!La(t)||"string"!=typeof t.url||t.positions)return;const i=t.url;try{const s=await e(i);for(const e of["positions","indices","uvs","uvs2","normals"]){const i=La(s)?s[e]:void 0;void 0!==i&&(t[e]=Array.isArray(i)?i.slice():i)}delete t.url}catch(t){s("geometry",i,t)}}))}static warnResourceError(t,e,s){console.warn(`[QuarksLoader] Could not load ${t} "${e}":`,s)}reportResourceError(t,e,s){(this.options.onResourceError??ih.warnResourceError)(t,e,s)}parseImages(t,e,s){for(const[i,n]of t.entries()){const t=n.url;t&&Gt(`[${i}]`,()=>ih.warnIfNotAnImageUrl(t)),s.images[n.uuid]=t?ih.joinUrl(e,t):null;const r=Ya.get(n)??t;r&&!/^(data|blob):/i.test(r)&&(s.imageSources[n.uuid]=r)}}static warnIfNotAnImageUrl(t){/^(data|blob):/i.test(t)||/\.(png|jpe?g|webp|gif|bmp|ktx2?|dds|env|basis)(\?|#|$)/i.test(t)||Wt(`Image "${t}" does not look like an image; its texture will fail to load. This usually means the effect was exported without embedding that texture.`)}parseTextures(t,e){for(const s of t){const t=void 0!==s.image?e.images[s.image]:void 0;if(t){const i=void 0===s.invertY||!!s.invertY,n=!!s.noMipmap,r=!1!==this.options.shareResources,o=r?[i,n,s.samplingMode,s.wrap,s.repeat,s.offset,s.rotation].join("|")+"|"+t:"",a=r?Qa(Ja,this.scene):void 0,h=a?.get(o);if(void 0!==h){e.textures[s.uuid]=h;continue}let l;const c=new Promise(t=>l=t);let u,d=!1;const f={noMipmap:n,invertY:i,samplingMode:"number"==typeof s.samplingMode?s.samplingMode:void 0,onLoad:()=>l(),onError:(e,s)=>{d=!0,void 0!==a&&a.get(o)===u&&a.delete(o),this.reportResourceError("image",t,s??e),l()}};try{u=new b.Texture(t,this.scene,f)}catch{e.textures[s.uuid]=null;continue}Za.set(u,c);const p=void 0!==s.image?e.imageSources[s.image]:void 0;void 0!==p&&Ea(u,p,t),u.onDisposeObservable.addOnce(()=>l()),Array.isArray(s.wrap)&&(u.wrapU=this.mapWrapMode(s.wrap[0]),u.wrapV=this.mapWrapMode(s.wrap[1]??s.wrap[0])),Array.isArray(s.repeat)&&(u.uScale=s.repeat[0]??1,u.vScale=s.repeat[1]??1),Array.isArray(s.offset)&&(u.uOffset=s.offset[0]??0,u.vOffset=s.offset[1]??0),"number"==typeof s.rotation&&(u.wAng=s.rotation),void 0===a||d||(a.set(o,u),u.onDisposeObservable.addOnce(()=>{a.get(o)===u&&a.delete(o)})),e.textures[s.uuid]=u}else e.textures[s.uuid]=null}}mapWrapMode(t){switch(t){case 1001:return b.Texture.CLAMP_ADDRESSMODE;case 1002:return b.Texture.MIRROR_ADDRESSMODE;default:return b.Texture.WRAP_ADDRESSMODE}}parseMaterials(t,e){const s=t=>"string"==typeof t&&e.textures[t]||null;for(const i of t){const t={uuid:i.uuid,transparent:i.transparent??!0,blending:i.blending??1,side:i.side??2,depthTest:i.depthTest??!0,depthWrite:i.depthWrite??!1,alphaTest:i.alphaTest??0,texture:null},n=i.map??i.texture;n&&(t.texture=s(n));const o=i.reflectionAtlas;if(o&&(t.reflectionAtlas=s(o)),"number"==typeof i.reflectionLevel&&(t.reflectionLevel=i.reflectionLevel),"unlit"!==i.lighting&&"fixed"!==i.lighting&&"scene"!==i.lighting||(t.lighting=i.lighting),i.rim&&"object"==typeof i.rim&&(t.rim=i.rim),i.mapUV&&"object"==typeof i.mapUV&&(t.mapUV=i.mapUV),i.gradientMap&&"object"==typeof i.gradientMap&&(t.gradientMap={...i.gradientMap,ramp:s(i.gradientMap.ramp)}),i.erosion&&"object"==typeof i.erosion&&(t.erosion={...i.erosion,mask:s(i.erosion.mask)}),i.uvDistortion&&"object"==typeof i.uvDistortion&&(t.uvDistortion={...i.uvDistortion,map:s(i.uvDistortion.map)}),"number"==typeof i.alphaMode)t.alphaMode=i.alphaMode;else{const e={1:r.Constants.ALPHA_COMBINE,2:r.Constants.ALPHA_ADD,3:r.Constants.ALPHA_SUBTRACT,4:r.Constants.ALPHA_MULTIPLY};t.alphaMode=e[i.blending??1]||r.Constants.ALPHA_COMBINE}e.materials[i.uuid]=t}}getGeometry(t,e){if(e)return t.geometries[e]}getMaterial(t,e){if(!e)return;const s=Array.isArray(e)?e[0]:e;return t.materials[s]}createPlaceholderNode(t,e){const s=new n.TransformNode(e||t||"node",this.scene);return Object.assign(s,{quarksOriginalType:t}),s}createMeshNode(t,e){const s=new u.Mesh(t.name||t.type||"mesh",this.scene),i=this.getGeometry(e,t.geometry);if(i&&i.positions.length>0&&i.indices.length>0){const t=new d.VertexData;t.positions=i.positions,t.indices=i.indices,i.uvs&&i.uvs.length>0&&(t.uvs=i.uvs),i.uvs2&&i.uvs2.length>0&&(t.uvs2=i.uvs2),i.normals&&i.normals.length>0&&(t.normals=i.normals),t.applyToMesh(s,!0)}const n=this.getMaterial(e,t.material);if(n){const t=new w.StandardMaterial(`quarks_loader_material_${n.uuid}`,this.scene);e.ownedMaterials.push(t),t.alphaMode=n.alphaMode??r.Constants.ALPHA_COMBINE,t.backFaceCulling=2!==n.side,t.alphaCutOff=n.alphaTest??0,t.disableDepthWrite=!n.depthWrite;const i=n.texture;i&&"string"!=typeof i&&(t.diffuseTexture=i,t.opacityTexture=i),s.material=t}return s}parseObject(t,e){let s;switch(t.type){case"QuarksPrefab":s=Ta.fromJSON(t,this.scene);break;case"ParticleEmitter":if(t.ps){const i=t.ps,n=Gt("ps",()=>this.parseParticleSystem(i,e));s=n.emitter;break}s=this.createPlaceholderNode(t.type,t.name);break;case"Mesh":case"SkinnedMesh":case"InstancedMesh":case"BatchedMesh":s=this.createMeshNode(t,e);break;case"Scene":case"Group":case"Object3D":case"PerspectiveCamera":case"OrthographicCamera":case"AmbientLight":case"DirectionalLight":case"PointLight":case"RectAreaLight":case"SpotLight":case"HemisphereLight":case"LightProbe":case"LOD":case"Line":case"LineSegments":case"LineLoop":case"PointCloud":case"Points":case"Sprite":case"Bone":s=this.createPlaceholderNode(t.type,t.name);break;default:s=new n.TransformNode(t.name||t.type||"node",this.scene)}if(t.uuid&&function(t,e){Mi.set(t,e)}(s,t.uuid),t.name&&(s.name=t.name),t.matrix){const e=a.Matrix.FromArray(t.matrix),i=new a.Vector3(1,1,1),n=a.Quaternion.Identity(),r=new a.Vector3(0,0,0);e.decompose(i,n,r),s.position.copyFrom(r),s.scaling.copyFrom(i),s.rotationQuaternion=n}else t.position&&s.position.set(t.position[0],t.position[1],t.position[2]),t.scale&&s.scaling.set(t.scale[0],t.scale[1],t.scale[2]),t.quaternion?s.rotationQuaternion=new a.Quaternion(t.quaternion[0],t.quaternion[1],t.quaternion[2],t.quaternion[3]):t.rotation&&s.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]);if(void 0!==t.visible&&s.setEnabled(t.visible),!1===t.isVisible&&s instanceof u.Mesh&&(s.isVisible=!1),t.children){const i=t.children;Array.isArray(i)?i.forEach((t,i)=>{const n=Gt(`children[${i}]`,()=>La(t)?this.parseObject(t,e):Wt("A child is not an object; it is skipped."));n&&(n.parent=s)}):Gt("children",()=>Wt('"children" is not a list; the node loads without them.'))}return s}parseParticleSystem(t,e){e.format<2&&null!==t&&"object"==typeof t&&"hierarchy"!==t.scalingMode&&(t={...t,scalingMode:"hierarchy"});const s=Aa.fromJSON(t,e,{},this.scene);return"mesh_surface"===t?.shape?.type&&"string"==typeof t.shape.mesh&&qa.set(s,t.shape.mesh),Ga.set(s,Jt()),s}linkReferences(t){const e={},s=t=>{const i=_i(t);i&&(e[i]=t);for(const e of t.getChildren())e instanceof n.TransformNode&&s(e)};s(t);const i=s=>{if(s instanceof Ta&&s.resolveReferences(t),s instanceof Xr){const t=s.system,i=Ga.get(t),n=t=>i?Gt(i,()=>Wt(t)):Wt(t),r=qa.get(t),o=t.emitterShape;if(r&&o instanceof Ai){const t=e[r];t instanceof u.Mesh?o.mesh=t:n(`Emitter "${s.name}" has a mesh surface shape on "${r}", `+(t?"which is not a mesh":"which is not in the effect")+"; it emits nothing until a mesh is set.")}for(let i=0;i<t.behaviors.length;i++)if(t.behaviors[i]instanceof ts){const r=t.behaviors[i],o=r.subParticleSystem;if("string"!=typeof o)continue;const a=e[o];a instanceof Xr?(r.subParticleSystem=a,a.system.onlyUsedByOther=!0):(r.subParticleSystem=void 0,""!==o&&n(`Emitter "${s.name}" has a sub emitter targeting "${o}", `+(a?"which is not a particle emitter":"which is not in the effect")+"; that sub emitter is skipped."))}}for(const t of s.getChildren())t instanceof n.TransformNode&&i(t)};i(t)}}const nh={};const rh={name:""},oh=[{name:"billboard",settings:{renderMode:exports.RenderMode.BillBoard}},{name:"vertical billboard",settings:{renderMode:exports.RenderMode.VerticalBillBoard}},{name:"horizontal billboard",settings:{renderMode:exports.RenderMode.HorizontalBillBoard}},{name:"stretched",settings:{renderMode:exports.RenderMode.StretchedBillBoard}},{name:"beam",settings:{renderMode:exports.RenderMode.Beam}},{name:"mesh",settings:{renderMode:exports.RenderMode.Mesh}},{name:"mesh scene lit",settings:{renderMode:exports.RenderMode.Mesh,lighting:"scene"}},{name:"mesh unlit",settings:{renderMode:exports.RenderMode.Mesh,lighting:"unlit"}},{name:"mesh rim",settings:{renderMode:exports.RenderMode.Mesh,rim:Vi({mode:"add"})}},{name:"mesh unlit rim mix",settings:{renderMode:exports.RenderMode.Mesh,lighting:"unlit",rim:Vi({mode:"mix"})}},{name:"mesh unlit rim fade",settings:{renderMode:exports.RenderMode.Mesh,lighting:"unlit",rim:Vi({mode:"fade"})}},{name:"mesh reflecting",settings:{renderMode:exports.RenderMode.Mesh,reflectionAtlas:nh},context:{envAtlasReady:!0}},{name:"mesh unlit reflecting rim fade",settings:{renderMode:exports.RenderMode.Mesh,lighting:"unlit",reflectionAtlas:nh,rim:Vi({mode:"fade"})},context:{envAtlasReady:!0}},{name:"trail",settings:{renderMode:exports.RenderMode.Trail}}],ah=[rh,{name:"pivot",settings:{pivot:new st(.5,0,0)}},{name:"size limits",settings:{minParticleSize:.01}},{name:"pivot size limits",settings:{pivot:new st(0,.5,.5),maxParticleSize:.5}}],hh=[rh,{name:"sheet",settings:{uTileCount:4,vTileCount:2}},{name:"sheet blend",settings:{uTileCount:4,vTileCount:2,blendTiles:!0}}],lh=[rh,{name:"map",settings:{texture:nh}}],ch=[rh,{name:"soft",settings:{softParticles:!0},context:{depth:{packed:!1}}},{name:"soft packed",settings:{softParticles:!0},context:{depth:{packed:!0}}}],uh=[rh,{name:"alpha test",settings:{materialAlphaTest:.5}}],dh=[rh,{name:"fog",settings:{applyFog:!0}},{name:"fog additive",settings:{applyFog:!0,materialBlendMode:r.Constants.ALPHA_ADD}}],fh=[{name:"premultiplied",settings:{materialBlendMode:r.Constants.ALPHA_PREMULTIPLIED}},{name:"premultiplied fog",settings:{materialBlendMode:r.Constants.ALPHA_PREMULTIPLIED,applyFog:!0}},{name:"one-one",settings:{materialBlendMode:r.Constants.ALPHA_ONEONE}},{name:"one-one fog",settings:{materialBlendMode:r.Constants.ALPHA_ONEONE,applyFog:!0}},{name:"multiply",settings:{materialBlendMode:r.Constants.ALPHA_MULTIPLY}},{name:"multiply fog",settings:{materialBlendMode:r.Constants.ALPHA_MULTIPLY,applyFog:!0}},{name:"multiply fog alpha test",settings:{materialBlendMode:r.Constants.ALPHA_MULTIPLY,applyFog:!0,materialAlphaTest:.5}},{name:"opaque",settings:{materialTransparent:!1}}],ph=(()=>{const t=Di({tiling:[2,2]}),e=Di({channel:1,tiling:[2,2]}),s=Li({map:nh}),i=Li({map:nh,mapUV:{channel:1}}),n=Ni({ramp:nh}),r=Ri({}),o=Ri({mask:nh}),a=Ri({mask:nh,maskUV:{channel:1}});return[{name:"map transform",settings:{mapUV:t}},{name:"map transform uv1",settings:{mapUV:e}},{name:"gradient map",settings:{gradientMap:n}},{name:"erosion",settings:{erosion:r}},{name:"erosion mask",settings:{erosion:o}},{name:"erosion mask uv1",settings:{erosion:a}},{name:"distortion",settings:{uvDistortion:s}},{name:"distortion uv1",settings:{uvDistortion:i}},{name:"map transform distortion gradient erosion mask",settings:{mapUV:t,uvDistortion:s,gradientMap:n,erosion:o}},{name:"map transform uv1 distortion gradient erosion",settings:{mapUV:e,uvDistortion:s,gradientMap:n,erosion:r}},{name:"every effect on uv1",settings:{mapUV:e,uvDistortion:i,gradientMap:n,erosion:a}}]})(),mh=["billboard","stretched","beam","mesh","mesh unlit","mesh unlit rim mix","mesh reflecting","trail"];function yh(t){return{IMAGEPROCESSING:!1,WHITEBALANCE:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,EXPOSURE:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,SKIPFINALCOLORCLAMP:!1,...t}}const gh=[{name:"post-processed",context:{imageProcessing:yh({IMAGEPROCESSINGPOSTPROCESS:!0})}},{name:"tone mapped",context:{imageProcessing:yh({IMAGEPROCESSING:!0,TONEMAPPING:1})}},{name:"aces exposure contrast",context:{imageProcessing:yh({IMAGEPROCESSING:!0,TONEMAPPING:2,EXPOSURE:!0,CONTRAST:!0})}},{name:"neutral vignette dither",context:{imageProcessing:yh({IMAGEPROCESSING:!0,TONEMAPPING:3,VIGNETTE:!0,VIGNETTEBLENDMODEMULTIPLY:!0,DITHER:!0})}},{name:"opaque vignette curves white balance grading",context:{imageProcessing:yh({IMAGEPROCESSING:!0,VIGNETTE:!0,VIGNETTEBLENDMODEOPAQUE:!0,COLORCURVES:!0,WHITEBALANCE:!0,COLORGRADING:!0,SKIPFINALCOLORCLAMP:!0})}},{name:"grading 3d green depth bgr",context:{imageProcessing:yh({IMAGEPROCESSING:!0,COLORGRADING:!0,COLORGRADING3D:!0,SAMPLER3DGREENDEPTH:!0,SAMPLER3DBGRMAP:!0})}}],vh=[rh,{name:"premultiplied",settings:{materialBlendMode:r.Constants.ALPHA_PREMULTIPLIED}},{name:"additive fog",settings:{materialBlendMode:r.Constants.ALPHA_ADD,applyFog:!0}},{name:"multiply",settings:{materialBlendMode:r.Constants.ALPHA_MULTIPLY}}],xh={name:"uv2",context:{meshUV2:!0}},Sh={name:"soft packed alpha test fog one-one",settings:{softParticles:!0,materialAlphaTest:.5,applyFog:!0,materialBlendMode:r.Constants.ALPHA_ONEONE},context:{depth:{packed:!0}}};bi(Pi),exports.ApplyCollision=Ct,exports.ApplyForce=Ve,exports.ApplySequences=$e,exports.AxisAngleGenerator=oe,exports.BatchedRenderer=Ur,exports.BehaviorFromJSON=Bs,exports.BehaviorToJSON=Us,exports.BehaviorTypes=Rs,exports.Bezier=Kt,exports.BoxEmitter=ii,exports.ChangeEmitDirection=Ie,exports.CircleEmitter=ri,exports.ColorBySpeed=Fe,exports.ColorGeneratorFromJSON=me,exports.ColorOverLife=Re,exports.ColorRange=ae,exports.ConeEmitter=li,exports.ConstantColor=pe,exports.ConstantValue=Xt,exports.ContinuousLinearFunction=he,exports.DEG2RAD=V,exports.DonutEmitter=ci,exports.EROSION_DEFAULT_SOFTNESS=Fi,exports.EdgeEmitter=ui,exports.EffectPool=class{constructor(t,e){this.template=t,this.options=e,this.idle=[],this.playing=new Set,this.systemsOf=new Map,this.restOf=new Map,this.disposed=!1,this.onSystemFinished=t=>{const e=t.particleSystem;for(const t of this.playing){const s=this.systemsOf.get(t);if(void 0!==s&&s.includes(e))return void(Zr.isEffectFinished(t)&&this.release(t))}};for(let t=0;t<(e.prewarm??0);t++){const t=this.makeCopy();if(null===t)break;this.idle.push(t)}}get activeCount(){return this.playing.size}get idleCount(){return this.idle.length}acquire(t,e=null){if(this.disposed)return null;const s=this.idle.pop()??this.makeCopy();if(null===s)return null;const i=void 0===t||"number"==typeof t.x?{position:t,parent:e}:t;return this.placeCopy(s,i),s.setEnabled(!0),this.playing.add(s),Zr.restart(s),Zr.play(s),s}stop(t){this.playing.has(t)&&Zr.endEmit(t)}release(t){this.playing.delete(t)&&(t.isDisposed()?this.forget(t):(Zr.stop(t),t.setEnabled(!1),t.parent=null,this.disposed||this.idle.push(t)))}dispose(){this.disposed=!0;for(const t of[...this.playing,...this.idle])this.playing.delete(t),this.disposeCopy(t);this.idle.length=0}makeCopy(){if(this.idle.length+this.playing.size>=(this.options.maxSize??1/0))return null;const t=Zr.instantiate(this.template),e=[];return Zr.runOnAllParticleEmitters(t,t=>{const s=t.system;s.ignoreStopAction=!0,s.addEventListener("finished",this.onSystemFinished),e.push(s)}),this.systemsOf.set(t,e),this.restOf.set(t,{position:t.position.clone(),rotation:t.rotation.clone(),rotationQuaternion:t.rotationQuaternion?.clone()??null,scaling:t.scaling.clone()}),Zr.addToBatchRenderer(t,this.options.renderer),t.setEnabled(!1),t.parent=null,t.onDisposeObservable.addOnce(()=>this.forget(t)),t}placeCopy(t,e){const s=this.restOf.get(t);t.parent=e.parent??null;const i=e.position??s.position,n=e.scaling??s.scaling;t.position.copyFromFloats(i.x,i.y,i.z),t.scaling.copyFromFloats(n.x,n.y,n.z),void 0!==e.rotationQuaternion?t.rotationQuaternion=e.rotationQuaternion.clone():void 0!==e.rotation?(t.rotationQuaternion=null,t.rotation.copyFromFloats(e.rotation.x,e.rotation.y,e.rotation.z)):(t.rotationQuaternion=s.rotationQuaternion?.clone()??null,t.rotation.copyFrom(s.rotation))}forget(t){for(const e of this.systemsOf.get(t)??[])e.removeEventListener("finished",this.onSystemFinished),this.options.renderer.deleteSystem(e),e.dispose();this.systemsOf.delete(t),this.restOf.delete(t),this.playing.delete(t);const e=this.idle.indexOf(t);-1!==e&&this.idle.splice(e,1)}disposeCopy(t){this.forget(t),Gr(t)}},exports.EmitSubParticleSystem=ts,exports.EmitterFrame=Te,exports.EmitterFromJSON=vi,exports.EmitterShapes=gi,exports.EmitterToJSON=xi,exports.Euler=gt,exports.EulerGenerator=ye,exports.ForceOverLife=es,exports.FrameOverLife=ss,exports.GRADIENT_MAP_WEIGHTS=Ii,exports.GeneratorFromJSON=be,exports.Gradient=ce,exports.GravityForce=is,exports.GridEmitter=di,exports.HemisphereEmitter=fi,exports.InheritVelocity=ns,exports.IntervalValue=Zt,exports.LimitSpeedOverLife=rs,exports.MAX_TRAIL_TESSELLATION=16,exports.MathUtils=tt,exports.Matrix3=vt,exports.Matrix4=at,exports.MeshSurfaceEmitter=Ai,exports.MeshSurfaceEmitterPlugin=Pi,exports.NodeParticle=class{constructor(){this.position=new st,this.velocity=new st,this.age=0,this.life=1,this.size=new st,this.rotation=0,this.color=new Pt(1,1,1,1),this.uvTile=0,this.memory=[]}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.position.set(0,0,0),this.velocity.set(0,0,0),this.age=0,this.life=1,this.size.set(1,1,1),this.rotation=0,this.color.set(1,1,1,1),this.uvTile=0}},exports.Noise=bs,exports.OrbitOverLife=ws,exports.ParticleEmitter=Xr,exports.ParticleStore=Be,exports.ParticleSystem=Aa,exports.PiecewiseBezier=ee,exports.PiecewiseFunction=te,exports.Plugins=Si,exports.PointEmitter=pi,exports.QUARKS_FORMAT_VERSION=2,exports.QuarksFormatError=Lt,exports.QuarksLoader=ih,exports.QuarksPrefab=Ta,exports.QuarksUtil=Zr,exports.Quaternion=et,exports.QuaternionView=bt,exports.RAD2DEG=E,exports.RandomBetweenCurves=se,exports.RandomColor=ue,exports.RandomColorBetweenGradient=fe,exports.RandomQuatGenerator=ge,exports.RecordState=class{constructor(t,e,s){this.position=t,this.size=e,this.color=s}},exports.RectangleEmitter=yi,exports.Rotation3DOverLife=zs,exports.RotationBySpeed=_s,exports.RotationGeneratorFromJSON=ve,exports.RotationOverLife=As,exports.SequencerFromJSON=Ce,exports.ShapeTransform=ti,exports.SizeBySpeed=Ps,exports.SizeOverLife=Os,exports.SpeedOverLife=Ts,exports.SphereEmitter=mi,exports.SpriteParticle=De,exports.SubEmitterInheritMask=Ze,exports.TextureSequencer=Ee,exports.TrailParticle=qe,exports.TurbulenceField=Es,exports.UV_DISTORTION_DEFAULT_STRENGTH=Ui,exports.UV_DISTORTION_DEFAULT_UV=Bi,exports.VFXBatch=Ar,exports.ValueGeneratorFromJSON=ne,exports.Vector2=Mt,exports.Vector3=st,exports.Vector3Function=xe,exports.Vector3GeneratorFromJSON=Se,exports.Vector3View=_t,exports.Vector4=Pt,exports.Vector4View=Tt,exports.VelocityOverLife=Ns,exports.WebGLCoordinateSystem=rt,exports.WebGPUCoordinateSystem=ot,exports.WidthOverLength=Fs,exports.blendCategory=gr,exports.cacheEnvAtlas=function(t,e){const s=oo(e)??oo(t);s?lo(t,s,e):console.warn("[babylon.quarks] cacheEnvAtlas: neither the atlas nor the cube has a scene; not cached")},exports.ceilPowerOfTwo=H,exports.clamp=$,exports.createEnvAtlasFromFaceUrls=co,exports.createSeededRandom=P,exports.cubeFaceUrls=ro,exports.currentFormatPath=Jt,exports.damp=B,exports.decodeSoftDepth=function(t,e){const s=e.z*t+e.w,i=Math.abs(s)>1e-8?Math.abs((e.x*t+e.y)/s):0;return i>0?i:1e30},exports.defaultMeshLighting=Ti,exports.degToRad=W,exports.denormalize=Z,exports.disposeEnvAtlas=ho,exports.ensureEnvAtlasFromCube=fo,exports.erosionEqual=function(t,e){return t===e||!(!t||!e)&&(t.mask===e.mask&&Ci(t.maskUV,e.maskUV)&&t.softness===e.softness&&t.edgeWidth===e.edgeWidth&&t.edgeColor[0]===e.edgeColor[0]&&t.edgeColor[1]===e.edgeColor[1]&&t.edgeColor[2]===e.edgeColor[2])},exports.euclideanModulo=I,exports.floorPowerOfTwo=Y,exports.generateUUID=C,exports.getCachedEnvAtlas=ao,exports.getPhysicsResolver=function(){return Et},exports.getRandomSource=_,exports.getValueFromEmitterMode=ni,exports.gradientMapEqual=function(t,e){return t===e||!!t&&!!e&&t.ramp===e.ramp&&t.channel===e.channel},exports.inverseLerp=F,exports.isPowerOfTwo=Q,exports.lerp=R,exports.loadPlugin=bi,exports.mapLinear=N,exports.mapUVEqual=function(t,e){return t===e||!!t&&!!e&&Ci(t,e)},exports.meshRimEqual=function(t,e){return t===e||!(!t||!e)&&(t.mode===e.mode&&t.power===e.power&&t.strength===e.strength&&t.color[0]===e.color[0]&&t.color[1]===e.color[1]&&t.color[2]===e.color[2])},exports.normalize=K,exports.normalizeErosion=Ri,exports.normalizeGradientMap=Ni,exports.normalizeMapUV=Di,exports.normalizeMeshRim=Vi,exports.normalizeTextureUV=Ei,exports.normalizeUVDistortion=Li,exports.pingpong=U,exports.planBehaviorFusion=Ks,exports.quarksNodeId=zi,exports.radToDeg=j,exports.randFloat=q,exports.randFloatSpread=G,exports.randInt=k,exports.random=z,exports.readBehaviorSpace=Pe,exports.readFormat=qt,exports.readFormatPart=Gt,exports.readsUV1=ki,exports.seededRandom=J,exports.serializeEffect=function(t,e={}){const s=new Fa(e);let i;if(Array.isArray(t)){const n=e.name??"effect";i={uuid:`${n}-root`,type:"Group",name:n,matrix:a.Matrix.Identity().asArray().slice(),children:t.map(t=>s.node(t))}}else i=s.node(t);return s.finish(i)},exports.setPhysicsResolver=function(t){Et=t},exports.setQuaternionFromProperEuler=X,exports.setRandomSource=A,exports.shaderProgram=vr,exports.shaderVariants=function(){const t=new Set,e=[],s=s=>{const i={renderMode:n=exports.RenderMode.BillBoard,texture:null,reflectionAtlas:null,uTileCount:1,vTileCount:1,blendTiles:!1,softParticles:!1,materialAlphaTest:0,materialTransparent:!0,materialBlendMode:r.Constants.ALPHA_COMBINE,applyFog:!1,applyImageProcessing:!0,pivot:void 0,minParticleSize:0,maxParticleSize:1/0,lighting:n===exports.RenderMode.Mesh?"fixed":void 0,rim:void 0,mapUV:void 0,uvDistortion:void 0,gradientMap:void 0,erosion:void 0};var n;const o={depth:null,envAtlasReady:!1,meshUV2:!1,imageProcessing:null};for(const t of s)Object.assign(i,t.settings),Object.assign(o,t.context);const a=vr(i,o),h=a.name+" "+a.defines.join(",");if(t.has(h))return;t.add(h);const l=s.map(t=>t.name).filter(t=>""!==t);e.push({name:`${l.join(", ")} [${a.defines.join(",")||"none"}]`,program:a})};for(const t of oh)for(const e of ah)for(const i of hh)for(const n of lh)for(const r of ch)for(const o of uh)for(const a of dh)s([t,e,i,n,r,o,a]);for(const t of oh)for(const e of fh)for(const i of ch.slice(0,2))for(const n of lh)s([t,e,i,n]);for(const t of oh.filter(t=>mh.includes(t.name)))for(const e of t.settings?.renderMode===exports.RenderMode.Mesh?[rh,xh]:[rh])for(const i of ph)for(const n of lh)for(const r of[rh,hh[2]])for(const o of[rh,Sh])s([t,e,i,n,r,o]);for(const t of oh)for(const e of gh)for(const i of vh)for(const n of lh)s([t,e,i,n]);const i=ph[ph.length-3];for(const t of oh.filter(t=>mh.includes(t.name)))for(const e of gh)s([t,e,i,lh[lh.length-1],Sh]);return e},exports.smootherstep=D,exports.smoothstep=L,exports.softDepthParams=yn,exports.speedFraction=Ne,exports.subEmitterInheritMask=Ke,exports.textureSourceUrl=Ca,exports.textureUVEqual=Ci,exports.textureUVToJSON=$i,exports.trailCurveTension=Vr,exports.trailLifetime=Nr,exports.trailMinVertexDistance=Ir,exports.trailTessellation=Tr,exports.trailTextureMode=Cr,exports.trailTextureScale=$r,exports.unloadPlugin=function(t){const e=Si.findIndex(e=>e.id===t);if(e<0)return;const s=Si[e];Si.splice(e,1);for(const t of s.emitterShapes)gi[t.type]===t&&delete gi[t.type];for(const t of s.behaviors)Rs[t.type]===t&&delete Rs[t.type]},exports.uvDistortionEqual=function(t,e){return t===e||!(!t||!e)&&(t.map===e.map&&t.strength===e.strength&&Ci(t.mapUV,e.mapUV))},exports.warnFormat=Wt,exports.withRandomSource=function(t,e){const s=A(t);try{return e()}finally{A(s)}};
|
|
2
2
|
//# sourceMappingURL=babylon.quarks.cjs.map
|