babylon.quarks 0.25.0 → 0.26.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.
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@babylonjs/core/Buffers/buffer"),require("@babylonjs/core/Maths/math.frustum"),require("@babylonjs/core/Maths/math.plane"),require("@babylonjs/core/Meshes/transformNode"),require("@babylonjs/core/Engines/constants"),require("@babylonjs/core/Materials/shaderMaterial"),require("@babylonjs/core/Materials/Textures/rawTexture"),require("@babylonjs/core/Maths/math.vector"),require("@babylonjs/core/Meshes/mesh"),require("@babylonjs/core/Meshes/mesh.vertexData"),require("@babylonjs/core/Engines/shaderStore"),require("@babylonjs/core/Materials/effect"),require("@babylonjs/core/Materials/shaderLanguage"),require("@babylonjs/core/Culling/boundingInfo"),require("@babylonjs/core/Maths/math.color"),require("@babylonjs/core/scene"),require("@babylonjs/core/Materials/Textures/texture"),require("@babylonjs/core/Materials/PBR/pbrMaterial"),require("@babylonjs/core/Materials/standardMaterial")):"function"==typeof define&&define.amd?define(["exports","@babylonjs/core/Buffers/buffer","@babylonjs/core/Maths/math.frustum","@babylonjs/core/Maths/math.plane","@babylonjs/core/Meshes/transformNode","@babylonjs/core/Engines/constants","@babylonjs/core/Materials/shaderMaterial","@babylonjs/core/Materials/Textures/rawTexture","@babylonjs/core/Maths/math.vector","@babylonjs/core/Meshes/mesh","@babylonjs/core/Meshes/mesh.vertexData","@babylonjs/core/Engines/shaderStore","@babylonjs/core/Materials/effect","@babylonjs/core/Materials/shaderLanguage","@babylonjs/core/Culling/boundingInfo","@babylonjs/core/Maths/math.color","@babylonjs/core/scene","@babylonjs/core/Materials/Textures/texture","@babylonjs/core/Materials/PBR/pbrMaterial","@babylonjs/core/Materials/standardMaterial"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).BabylonQuarks={},t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON)}(this,function(t,e,i,s,n,r,o,a,l,h,c,u,d,f,m,p,y,g,v,x){"use strict";let S=null;function b(){return null===S?Math.random():S()}function w(){return S??Math.random}function M(t){const e=w();return S=t,e}function z(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 _=["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 P=1234567;const T=Math.PI/180,O=180/Math.PI;function V(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0;return(_[255&t]+_[t>>8&255]+_[t>>16&255]+_[t>>24&255]+"-"+_[255&e]+_[e>>8&255]+"-"+_[e>>16&15|64]+_[e>>24&255]+"-"+_[63&i|128]+_[i>>8&255]+"-"+_[i>>16&255]+_[i>>24&255]+_[255&s]+_[s>>8&255]+_[s>>16&255]+_[s>>24&255]).toLowerCase()}function B(t,e,i){return Math.max(e,Math.min(i,t))}function C(t,e){return(t%e+e)%e}function A(t,e,i,s,n){return s+(t-e)*(n-s)/(i-e)}function F(t,e,i){return t!==e?(i-t)/(e-t):0}function $(t,e,i){return(1-i)*t+i*e}function I(t,e,i,s){return $(t,e,1-Math.exp(-i*s))}function E(t,e=1){return e-Math.abs(C(t,2*e)-e)}function N(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)}function L(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*t*(t*(6*t-15)+10)}function R(t,e){return t+Math.floor(b()*(e-t+1))}function D(t,e){return t+b()*(e-t)}function U(t){return t*(.5-b())}function q(t){void 0!==t&&(P=t);let e=P+=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 k(t){return t*T}function J(t){return t*O}function Q(t){return!(t&t-1)&&0!==t}function G(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function W(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function j(t,e,i,s,n){const r=Math.cos,o=Math.sin,a=r(i/2),l=o(i/2),h=r((e+s)/2),c=o((e+s)/2),u=r((e-s)/2),d=o((e-s)/2),f=r((s-e)/2),m=o((s-e)/2);switch(n){case"XYX":t.set(a*c,l*u,l*d,a*h);break;case"YZY":t.set(l*d,a*c,l*u,a*h);break;case"ZXZ":t.set(l*u,l*d,a*c,a*h);break;case"XZX":t.set(a*c,l*m,l*f,a*h);break;case"YXY":t.set(l*f,a*c,l*m,a*h);break;case"ZYZ":t.set(l*m,l*f,a*c,a*h);break;default:console.warn("../math.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function Y(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 X(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 Z={DEG2RAD:T,RAD2DEG:O,generateUUID:V,clamp:B,euclideanModulo:C,mapLinear:A,inverseLerp:F,lerp:$,damp:I,pingpong:E,smoothstep:N,smootherstep:L,randInt:R,randFloat:D,randFloatSpread:U,seededRandom:q,degToRad:k,radToDeg:J,isPowerOfTwo:Q,ceilPowerOfTwo:G,floorPowerOfTwo:W,setQuaternionFromProperEuler:j,normalize:X,denormalize:Y};class H{constructor(t=0,e=0,i=0,s=1){this._x=t,this._y=e,this._z=i,this._w=s}static slerpFlat(t,e,i,s,n,r,o){let a=i[s+0],l=i[s+1],h=i[s+2],c=i[s+3];const u=n[r+0],d=n[r+1],f=n[r+2],m=n[r+3];if(0===o)return t[e+0]=a,t[e+1]=l,t[e+2]=h,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]=m);if(c!==m||a!==u||l!==d||h!==f){let t=1-o;const e=a*u+l*d+h*f+c*m,i=e>=0?1:-1,s=1-e*e;if(s>Number.EPSILON){const n=Math.sqrt(s),r=Math.atan2(n,e*i);t=Math.sin(t*r)/n,o=Math.sin(o*r)/n}const n=o*i;if(a=a*t+u*n,l=l*t+d*n,h=h*t+f*n,c=c*t+m*n,t===1-o){const t=1/Math.sqrt(a*a+l*l+h*h+c*c);a*=t,l*=t,h*=t,c*=t}}t[e]=a,t[e+1]=l,t[e+2]=h,t[e+3]=c}static multiplyQuaternionsFlat(t,e,i,s,n,r){const o=i[s],a=i[s+1],l=i[s+2],h=i[s+3],c=n[r],u=n[r+1],d=n[r+2],f=n[r+3];return t[e]=o*f+h*c+a*d-l*u,t[e+1]=a*f+h*u+l*c-o*d,t[e+2]=l*f+h*d+o*u-a*c,t[e+3]=h*f-o*c-a*u-l*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,i,s){return this._x=t,this._y=e,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new H(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 i=t._x,s=t._y,n=t._z,r=t._order,o=Math.cos,a=Math.sin,l=o(i/2),h=o(s/2),c=o(n/2),u=a(i/2),d=a(s/2),f=a(n/2);switch(r){case"XYZ":this._x=u*h*c+l*d*f,this._y=l*d*c-u*h*f,this._z=l*h*f+u*d*c,this._w=l*h*c-u*d*f;break;case"YXZ":this._x=u*h*c+l*d*f,this._y=l*d*c-u*h*f,this._z=l*h*f-u*d*c,this._w=l*h*c+u*d*f;break;case"ZXY":this._x=u*h*c-l*d*f,this._y=l*d*c+u*h*f,this._z=l*h*f+u*d*c,this._w=l*h*c-u*d*f;break;case"ZYX":this._x=u*h*c-l*d*f,this._y=l*d*c+u*h*f,this._z=l*h*f-u*d*c,this._w=l*h*c+u*d*f;break;case"YZX":this._x=u*h*c+l*d*f,this._y=l*d*c+u*h*f,this._z=l*h*f-u*d*c,this._w=l*h*c-u*d*f;break;case"XZY":this._x=u*h*c-l*d*f,this._y=l*d*c-u*h*f,this._z=l*h*f+u*d*c,this._w=l*h*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 i=e/2,s=Math.sin(i);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],s=e[4],n=e[8],r=e[1],o=e[5],a=e[9],l=e[2],h=e[6],c=e[10],u=i+o+c;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(h-a)*t,this._y=(n-l)*t,this._z=(r-s)*t}else if(i>o&&i>c){const t=2*Math.sqrt(1+i-o-c);this._w=(h-a)/t,this._x=.25*t,this._y=(s+r)/t,this._z=(n+l)/t}else if(o>c){const t=2*Math.sqrt(1+o-i-c);this._w=(n-l)/t,this._x=(s+r)/t,this._y=.25*t,this._z=(a+h)/t}else{const t=2*Math.sqrt(1+c-i-o);this._w=(r-s)/t,this._x=(n+l)/t,this._y=(a+h)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<Number.EPSILON?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(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=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(B(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(0===i)return this;const s=Math.min(1,e/i);return this.slerp(t,s),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 i=t._x,s=t._y,n=t._z,r=t._w,o=e._x,a=e._y,l=e._z,h=e._w;return this._x=i*h+r*o+s*l-n*a,this._y=s*h+r*a+n*o-i*l,this._z=n*h+r*l+i*a-s*o,this._w=r*h-i*o-s*a-n*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const i=this._x,s=this._y,n=this._z,r=this._w;let o=r*t._w+i*t._x+s*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=i,this._y=s,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*i+e*this._x,this._y=t*s+e*this._y,this._z=t*n+e*this._z,this.normalize(),this}const l=Math.sqrt(a),h=Math.atan2(l,o),c=Math.sin((1-e)*h)/l,u=Math.sin(e*h)/l;return this._w=r*c+this._w*u,this._x=i*c+this._x*u,this._y=s*c+this._y*u,this._z=n*c+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*b(),e=2*Math.PI*b(),i=b(),s=Math.sqrt(1-i),n=Math.sqrt(i);return this.set(s*Math.sin(t),s*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}}H.prototype.isQuaternion=!0;class K{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}set(t,e,i){return void 0===i&&(i=this.z),this.x=t,this.y=e,this.z=i,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 K(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(et.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(et.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6]*s,this.y=n[1]*e+n[4]*i+n[7]*s,this.z=n[2]*e+n[5]*i+n[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=t.elements,r=1/(n[3]*e+n[7]*i+n[11]*s+n[15]);return this.x=(n[0]*e+n[4]*i+n[8]*s+n[12])*r,this.y=(n[1]*e+n[5]*i+n[9]*s+n[13])*r,this.z=(n[2]*e+n[6]*i+n[10]*s+n[14])*r,this}applyQuaternion(t){const e=this.x,i=this.y,s=this.z,n=t.x,r=t.y,o=t.z,a=t.w,l=2*(r*s-o*i),h=2*(o*e-n*s),c=2*(n*i-r*e);return this.x=e+a*l+r*c-o*h,this.y=i+a*h+o*l-n*c,this.z=s+a*c+n*h-r*l,this}transformDirection(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[4]*i+n[8]*s,this.y=n[1]*e+n[5]*i+n[9]*s,this.z=n[2]*e+n[6]*i+n[10]*s,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 i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,s=t.y,n=t.z,r=e.x,o=e.y,a=e.z;return this.x=s*a-n*o,this.y=n*r-i*a,this.z=i*o-s*r,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return tt.copy(this).projectOnVector(t),this.sub(tt)}reflect(t){return this.sub(tt.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 i=this.dot(t)/e;return Math.acos(B(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,s=this.z-t.z;return e*e+i*i+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSphericalCoords(t,e,i){const s=Math.sin(e)*t;return this.x=s*Math.sin(i),this.y=Math.cos(e)*t,this.z=s*Math.cos(i),this}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,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(),i=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=s,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=b(),this.y=b(),this.z=b(),this}randomDirection(){const t=b()*Math.PI*2,e=2*b()-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*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}}K.prototype.isVector3=!0;const tt=new K,et=new H,it=2e3,st=2001;class nt{constructor(t,e,i,s,n,r,o,a,l,h,c,u,d,f,m,p){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,i,s,n,r,o,a,l,h,c,u,d,f,m,p)}extractPosition(t){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(t)}multiplyToArray(t,e,i){return console.error("THREE.Matrix4: .multiplyToArray() has been removed."),this}setRotationFromQuaternion(t){return this.makeRotationFromQuaternion(t)}set(t,e,i,s,n,r,o,a,l,h,c,u,d,f,m,p){const y=this.elements;return y[0]=t,y[4]=e,y[8]=i,y[12]=s,y[1]=n,y[5]=r,y[9]=o,y[13]=a,y[2]=l,y[6]=h,y[10]=c,y[14]=u,y[3]=d,y[7]=f,y[11]=m,y[15]=p,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 nt).fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[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,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,i=t.elements,s=1/rt.setFromMatrixColumn(t,0).length(),n=1/rt.setFromMatrixColumn(t,1).length(),r=1/rt.setFromMatrixColumn(t,2).length();return e[0]=i[0]*s,e[1]=i[1]*s,e[2]=i[2]*s,e[3]=0,e[4]=i[4]*n,e[5]=i[5]*n,e[6]=i[6]*n,e[7]=0,e[8]=i[8]*r,e[9]=i[9]*r,e[10]=i[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,n=t.z,r=Math.cos(i),o=Math.sin(i),a=Math.cos(s),l=Math.sin(s),h=Math.cos(n),c=Math.sin(n);if("XYZ"===t.order){const t=r*h,i=r*c,s=o*h,n=o*c;e[0]=a*h,e[4]=-a*c,e[8]=l,e[1]=i+s*l,e[5]=t-n*l,e[9]=-o*a,e[2]=n-t*l,e[6]=s+i*l,e[10]=r*a}else if("YXZ"===t.order){const t=a*h,i=a*c,s=l*h,n=l*c;e[0]=t+n*o,e[4]=s*o-i,e[8]=r*l,e[1]=r*c,e[5]=r*h,e[9]=-o,e[2]=i*o-s,e[6]=n+t*o,e[10]=r*a}else if("ZXY"===t.order){const t=a*h,i=a*c,s=l*h,n=l*c;e[0]=t-n*o,e[4]=-r*c,e[8]=s+i*o,e[1]=i+s*o,e[5]=r*h,e[9]=n-t*o,e[2]=-r*l,e[6]=o,e[10]=r*a}else if("ZYX"===t.order){const t=r*h,i=r*c,s=o*h,n=o*c;e[0]=a*h,e[4]=s*l-i,e[8]=t*l+n,e[1]=a*c,e[5]=n*l+t,e[9]=i*l-s,e[2]=-l,e[6]=o*a,e[10]=r*a}else if("YZX"===t.order){const t=r*a,i=r*l,s=o*a,n=o*l;e[0]=a*h,e[4]=n-t*c,e[8]=s*c+i,e[1]=c,e[5]=r*h,e[9]=-o*h,e[2]=-l*h,e[6]=i*c+s,e[10]=t-n*c}else if("XZY"===t.order){const t=r*a,i=r*l,s=o*a,n=o*l;e[0]=a*h,e[4]=-c,e[8]=l*h,e[1]=t*c+n,e[5]=r*h,e[9]=i*c-s,e[2]=s*c-i,e[6]=o*h,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(at,t,lt)}lookAt(t,e,i){const s=this.elements;return ut.subVectors(t,e),0===ut.lengthSq()&&(ut.z=1),ut.normalize(),ht.crossVectors(i,ut),0===ht.lengthSq()&&(1===Math.abs(i.z)?ut.x+=1e-4:ut.z+=1e-4,ut.normalize(),ht.crossVectors(i,ut)),ht.normalize(),ct.crossVectors(ut,ht),s[0]=ht.x,s[4]=ct.x,s[8]=ut.x,s[1]=ht.y,s[5]=ct.y,s[9]=ut.y,s[2]=ht.z,s[6]=ct.z,s[10]=ut.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],o=i[4],a=i[8],l=i[12],h=i[1],c=i[5],u=i[9],d=i[13],f=i[2],m=i[6],p=i[10],y=i[14],g=i[3],v=i[7],x=i[11],S=i[15],b=s[0],w=s[4],M=s[8],z=s[12],_=s[1],P=s[5],T=s[9],O=s[13],V=s[2],B=s[6],C=s[10],A=s[14],F=s[3],$=s[7],I=s[11],E=s[15];return n[0]=r*b+o*_+a*V+l*F,n[4]=r*w+o*P+a*B+l*$,n[8]=r*M+o*T+a*C+l*I,n[12]=r*z+o*O+a*A+l*E,n[1]=h*b+c*_+u*V+d*F,n[5]=h*w+c*P+u*B+d*$,n[9]=h*M+c*T+u*C+d*I,n[13]=h*z+c*O+u*A+d*E,n[2]=f*b+m*_+p*V+y*F,n[6]=f*w+m*P+p*B+y*$,n[10]=f*M+m*T+p*C+y*I,n[14]=f*z+m*O+p*A+y*E,n[3]=g*b+v*_+x*V+S*F,n[7]=g*w+v*P+x*B+S*$,n[11]=g*M+v*T+x*C+S*I,n[15]=g*z+v*O+x*A+S*E,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],i=t[4],s=t[8],n=t[12],r=t[1],o=t[5],a=t[9],l=t[13],h=t[2],c=t[6],u=t[10],d=t[14];return t[3]*(+n*a*c-s*l*c-n*o*u+i*l*u+s*o*d-i*a*d)+t[7]*(+e*a*d-e*l*u+n*r*u-s*r*d+s*l*h-n*a*h)+t[11]*(+e*l*c-e*o*d-n*r*c+i*r*d+n*o*h-i*l*h)+t[15]*(-s*o*h-e*a*c+e*o*u+s*r*c-i*r*u+i*a*h)}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,i){const s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],o=t[5],a=t[6],l=t[7],h=t[8],c=t[9],u=t[10],d=t[11],f=t[12],m=t[13],p=t[14],y=t[15],g=c*p*l-m*u*l+m*a*d-o*p*d-c*a*y+o*u*y,v=f*u*l-h*p*l-f*a*d+r*p*d+h*a*y-r*u*y,x=h*m*l-f*c*l+f*o*d-r*m*d-h*o*y+r*c*y,S=f*c*a-h*m*a-f*o*u+r*m*u+h*o*p-r*c*p,b=e*g+i*v+s*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]=(m*u*n-c*p*n-m*s*d+i*p*d+c*s*y-i*u*y)*w,t[2]=(o*p*n-m*a*n+m*s*l-i*p*l-o*s*y+i*a*y)*w,t[3]=(c*a*n-o*u*n-c*s*l+i*u*l+o*s*d-i*a*d)*w,t[4]=v*w,t[5]=(h*p*n-f*u*n+f*s*d-e*p*d-h*s*y+e*u*y)*w,t[6]=(f*a*n-r*p*n-f*s*l+e*p*l+r*s*y-e*a*y)*w,t[7]=(r*u*n-h*a*n+h*s*l-e*u*l-r*s*d+e*a*d)*w,t[8]=x*w,t[9]=(f*c*n-h*m*n-f*i*d+e*m*d+h*i*y-e*c*y)*w,t[10]=(r*m*n-f*o*n+f*i*l-e*m*l-r*i*y+e*o*y)*w,t[11]=(h*o*n-r*c*n-h*i*l+e*c*l+r*i*d-e*o*d)*w,t[12]=S*w,t[13]=(h*m*s-f*c*s+f*i*u-e*m*u-h*i*p+e*c*p)*w,t[14]=(f*o*s-r*m*s-f*i*a+e*m*a+r*i*p-e*o*p)*w,t[15]=(r*c*s-h*o*s+h*i*a-e*c*a-r*i*u+e*o*u)*w,this}scale(t){const e=this.elements,i=t.x,s=t.y,n=t.z;return e[0]*=i,e[4]*=s,e[8]*=n,e[1]*=i,e[5]*=s,e[9]*=n,e[2]*=i,e[6]*=s,e[10]*=n,e[3]*=i,e[7]*=s,e[11]*=n,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,s))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),s=Math.sin(e),n=1-i,r=t.x,o=t.y,a=t.z,l=n*r,h=n*o;return this.set(l*r+i,l*o-s*a,l*a+s*o,0,l*o+s*a,h*o+i,h*a-s*r,0,l*a-s*o,h*a+s*r,n*a*a+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,s,n,r){return this.set(1,i,n,0,t,1,r,0,e,s,1,0,0,0,0,1),this}compose(t,e,i){const s=this.elements,n=e._x,r=e._y,o=e._z,a=e._w,l=n+n,h=r+r,c=o+o,u=n*l,d=n*h,f=n*c,m=r*h,p=r*c,y=o*c,g=a*l,v=a*h,x=a*c,S=i.x,b=i.y,w=i.z;return s[0]=(1-(m+y))*S,s[1]=(d+x)*S,s[2]=(f-v)*S,s[3]=0,s[4]=(d-x)*b,s[5]=(1-(u+y))*b,s[6]=(p+g)*b,s[7]=0,s[8]=(f+v)*w,s[9]=(p-g)*w,s[10]=(1-(u+m))*w,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,i){const s=this.elements;let n=rt.set(s[0],s[1],s[2]).length();const r=rt.set(s[4],s[5],s[6]).length(),o=rt.set(s[8],s[9],s[10]).length();this.determinant()<0&&(n=-n),t.x=s[12],t.y=s[13],t.z=s[14],ot.copy(this);const a=1/n,l=1/r,h=1/o;return ot.elements[0]*=a,ot.elements[1]*=a,ot.elements[2]*=a,ot.elements[4]*=l,ot.elements[5]*=l,ot.elements[6]*=l,ot.elements[8]*=h,ot.elements[9]*=h,ot.elements[10]*=h,e.setFromRotationMatrix(ot),i.x=n,i.y=r,i.z=o,this}makePerspective(t,e,i,s,n,r,o=2e3){const a=this.elements,l=2*n/(e-t),h=2*n/(i-s),c=(e+t)/(e-t),u=(i+s)/(i-s);let d,f;if(o===it)d=-(r+n)/(r-n),f=-2*r*n/(r-n);else{if(o!==st)throw new Error("Matrix4.makePerspective(): Invalid coordinate system: "+o);d=-r/(r-n),f=-r*n/(r-n)}return a[0]=l,a[4]=0,a[8]=c,a[12]=0,a[1]=0,a[5]=h,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,i,s,n,r,o=2e3){const a=this.elements,l=1/(e-t),h=1/(i-s),c=1/(r-n),u=(e+t)*l,d=(i+s)*h;let f,m;if(o===it)f=(r+n)*c,m=-2*c;else{if(o!==st)throw new Error("../math.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);f=n*c,m=-1*c}return a[0]=2*l,a[4]=0,a[8]=0,a[12]=-u,a[1]=0,a[5]=2*h,a[9]=0,a[13]=-d,a[2]=0,a[6]=0,a[10]=m,a[14]=-f,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<16;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}nt.prototype.isMatrix4=!0;const rt=new K,ot=new nt,at=new K(0,0,0),lt=new K(1,1,1),ht=new K,ct=new K,ut=new K,dt=new nt,ft=new H;class mt{constructor(t=0,e=0,i=0,s=mt.DEFAULT_ORDER){this._x=t,this._y=e,this._z=i,this._order=s}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,i,s=this._order){return this._x=t,this._y=e,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new mt(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,i=!0){const s=t.elements,n=s[0],r=s[4],o=s[8],a=s[1],l=s[5],h=s[9],c=s[2],u=s[6],d=s[10];switch(e){case"XYZ":this._y=Math.asin(B(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,d),this._z=Math.atan2(-r,n)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-B(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,l)):(this._y=Math.atan2(-c,n),this._z=0);break;case"ZXY":this._x=Math.asin(B(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-r,l)):(this._y=0,this._z=Math.atan2(a,n));break;case"ZYX":this._y=Math.asin(-B(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,l));break;case"YZX":this._z=Math.asin(B(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-c,n)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-B(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(o,n)):(this._x=Math.atan2(-h,d),this._y=0);break;default:console.warn("../math.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===i&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return dt.makeRotationFromQuaternion(t),this.setFromRotationMatrix(dt,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return ft.setFromEuler(this),this.setFromQuaternion(ft,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}}mt.DEFAULT_ORDER="XYZ",mt.prototype.isEuler=!0;class pt{constructor(t,e,i,s,n,r,o,a,l){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,i,s,n,r,o,a,l)}set(t,e,i,s,n,r,o,a,l){const h=this.elements;return h[0]=t,h[1]=s,h[2]=o,h[3]=e,h[4]=n,h[5]=a,h[6]=i,h[7]=r,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.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 i=t.elements,s=e.elements,n=this.elements,r=i[0],o=i[3],a=i[6],l=i[1],h=i[4],c=i[7],u=i[2],d=i[5],f=i[8],m=s[0],p=s[3],y=s[6],g=s[1],v=s[4],x=s[7],S=s[2],b=s[5],w=s[8];return n[0]=r*m+o*g+a*S,n[3]=r*p+o*v+a*b,n[6]=r*y+o*x+a*w,n[1]=l*m+h*g+c*S,n[4]=l*p+h*v+c*b,n[7]=l*y+h*x+c*w,n[2]=u*m+d*g+f*S,n[5]=u*p+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],i=t[1],s=t[2],n=t[3],r=t[4],o=t[5],a=t[6],l=t[7],h=t[8];return e*r*h-e*o*l-i*n*h+i*o*a+s*n*l-s*r*a}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],o=t[5],a=t[6],l=t[7],h=t[8],c=h*r-o*l,u=o*a-h*n,d=l*n-r*a,f=e*c+i*u+s*d;if(0===f)return this.set(0,0,0,0,0,0,0,0,0);const m=1/f;return t[0]=c*m,t[1]=(s*l-h*i)*m,t[2]=(o*i-s*r)*m,t[3]=u*m,t[4]=(h*e-s*a)*m,t[5]=(s*n-o*e)*m,t[6]=d*m,t[7]=(i*a-l*e)*m,t[8]=(r*e-i*n)*m,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,i,s,n,r,o){const a=Math.cos(n),l=Math.sin(n);return this.set(i*a,i*l,-i*(a*r+l*o)+r+t,-s*l,s*a,-s*(-l*r+a*o)+o+e,0,0,1),this}scale(t,e){return this.premultiply(yt.makeScale(t,e)),this}rotate(t){return this.premultiply(yt.makeRotation(-t)),this}translate(t,e){return this.premultiply(yt.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,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,i=t.elements;for(let t=0;t<9;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return(new pt).fromArray(this.elements)}}pt.prototype.isMatrix3=!0;const yt=new pt,gt=new Float32Array(4);class vt extends H{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const xt=vt.prototype;xt.data=gt,xt.offset=0,Object.defineProperties(vt.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 St{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 St(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,i=this.y,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6],this.y=s[1]*e+s[4]*i+s[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 i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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 i=this.dot(t)/e;return Math.acos(B(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}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,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,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 i=Math.cos(e),s=Math.sin(e),n=this.x-t.x,r=this.y-t.y;return this.x=n*i-r*s+t.x,this.y=n*s+r*i+t.y,this}random(){return this.x=b(),this.y=b(),this}*[Symbol.iterator](){yield this.x,yield this.y}}St.isVector2=!0;const bt=new Float32Array(3);class wt extends K{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const Mt=wt.prototype;Mt.data=bt,Mt.offset=0,Object.defineProperties(wt.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 zt{constructor(t=0,e=0,i=0,s=1){this.x=t,this.y=e,this.z=i,this.w=s}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,i,s){return this.x=t,this.y=e,this.z=i,this.w=s,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 zt(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,i=this.y,s=this.z,n=this.w,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*s+r[12]*n,this.y=r[1]*e+r[5]*i+r[9]*s+r[13]*n,this.z=r[2]*e+r[6]*i+r[10]*s+r[14]*n,this.w=r[3]*e+r[7]*i+r[11]*s+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,i,s,n;const r=.01,o=.1,a=t.elements,l=a[0],h=a[4],c=a[8],u=a[1],d=a[5],f=a[9],m=a[2],p=a[6],y=a[10];if(Math.abs(h-u)<r&&Math.abs(c-m)<r&&Math.abs(f-p)<r){if(Math.abs(h+u)<o&&Math.abs(c+m)<o&&Math.abs(f+p)<o&&Math.abs(l+d+y-3)<o)return this.set(1,0,0,0),this;e=Math.PI;const t=(l+1)/2,a=(d+1)/2,g=(y+1)/2,v=(h+u)/4,x=(c+m)/4,S=(f+p)/4;return t>a&&t>g?t<r?(i=0,s=.707106781,n=.707106781):(i=Math.sqrt(t),s=v/i,n=x/i):a>g?a<r?(i=.707106781,s=0,n=.707106781):(s=Math.sqrt(a),i=v/s,n=S/s):g<r?(i=.707106781,s=.707106781,n=0):(n=Math.sqrt(g),i=x/n,s=S/n),this.set(i,s,n,e),this}let g=Math.sqrt((p-f)*(p-f)+(c-m)*(c-m)+(u-h)*(u-h));return Math.abs(g)<.001&&(g=1),this.x=(p-f)/g,this.y=(c-m)/g,this.z=(u-h)/g,this.w=Math.acos((l+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 i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,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=b(),this.y=b(),this.z=b(),this.w=b(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}zt.prototype.isVector4=!0;const _t=new Float32Array(4);class Pt extends zt{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const Tt=Pt.prototype;let Ot;function Vt(){return Ot}Tt.data=_t,Tt.offset=0,Object.defineProperties(Pt.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 Bt{constructor(t,e){this.resolver=t,this.bounce=e,this.type="ApplyCollision",this.tempV=new K}initialize(t){}update(t,e){this.resolver&&this.resolver.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 Bt(Vt(),t.bounce)}clone(){return new Bt(this.resolver,this.bounce)}reset(){}}class Ct{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 Ct(t.value)}clone(){return new Ct(this.value)}}class At{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(b())}genValue(t){return-1===this.indexCount&&this.startGen(t),Z.lerp(this.a,this.b,t[this.indexCount])}toJSON(){return{type:"IntervalValue",a:this.a,b:this.b}}static fromJSON(t){return new At(t.a,t.b)}clone(){return new At(this.a,this.b)}}class Ft{constructor(t,e,i,s){this.p=[t,e,i,s]}genValue(t){const e=this.p,i=t*t,s=1-t,n=s*s;return e[0]*n*s+e[1]*n*t*3+e[2]*s*i*3+e[3]*i*t}derivativeCoefficients(t){const e=[];for(let i=t,s=i.length-1;s>0;s--){const t=[];for(let e=0;e<s;e++){const n=s*(i[e+1]-i[e]);t.push(n)}e.push(t),i=t}return e}getSlope(t){const e=this.derivativeCoefficients(this.p)[0],i=1-t,s=i*t*2,n=t*t;return i*i*e[0]+s*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,i=this.p,s=[],n=0,r=0,o=0;const a=[];for(a[n++]=i[0],a[n++]=i[1],a[n++]=i[2],a[n++]=i[3];i.length>1;){for(s=[],r=0,o=i.length-1;r<o;r++)e=t*i[r]+(1-t)*i[r+1],a[n++]=e,s.push(e);i=s}return a}split(t){const e=this.hull(t);return{left:new Ft(e[0],e[4],e[7],e[9]),right:new Ft(e[9],e[8],e[6],e[3]),span:e}}clone(){return new Ft(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 Ft(t.p0,t.p1,t.p2,t.p3)}}class $t{constructor(){this.functions=new Array}findFunction(t){const e=this.functions,i=e.length-1;if(i<=0)return 0===i&&t>=e[0][1]&&t<=1?0:-1;let s=0,n=i;for(;s+1<n;){const i=s+n>>1;if(t<e[i][1])n=i-1;else{if(!(t>this.getEndX(i)))return i;s=i+1}}for(let i=s;i<=n;i++)if(t>=e[i][1]&&t<=this.getEndX(i))return i;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 i=this.findFunction(t);this.functions.splice(i+1,0,[e,t])}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 It extends $t{constructor(t=[[new Ft(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 i=5*e;let s=this.tableSignature,n=null===s||s.length!==i;n&&(s=new Float64Array(i));for(let i=0,r=0;i<e;i++,r+=5){const e=t[i][0].p,o=t[i][1];n||(n=s[r]!==e[0]||s[r+1]!==e[1]||s[r+2]!==e[2]||s[r+3]!==e[3]||s[r+4]!==o),n&&(s[r]=e[0],s[r+1]=e[1],s[r+2]=e[2],s[r+3]=e[3],s[r+4]=o)}if(!n&&null!==this.table)return;this.tableSignature=s;const r=It.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 i=this.table;if(null!==i){const t=i.length-1;if(e<=0)return i[0];if(e>=1)return i[t];const s=e*t,n=0|s,r=s-n,o=i[n];return o+(i[n+1]-o)*r}return this.genValueExact(e)}genValueExact(t){const e=this.functions,i=e.length;if(0===i)return 0;const s=this.findFunction(t);if(-1===s)return t<e[0][1]?e[0][0].genValue(0):e[i-1][0].genValue(1);const n=e[s][1],r=(s+1<i?e[s+1][1]:1)-n;return e[s][0].genValue(r>0?(t-n)/r:0)}toSVG(t,e){if(e<1)return"";let i=["M",0,this.functions[0][0].p[0]].join(" ");for(let s=1/e;s<=1;s+=1/e)i=[i,"L",s*t,this.genValue(void 0,s)].join(" ");return i}toJSON(){return{type:"PiecewiseBezier",functions:this.functions.map(([t,e])=>({function:t.toJSON(),start:e}))}}static fromJSON(t){return new It(t.functions.map(t=>[Ft.fromJSON(t.function),t.start]))}clone(){return new It(this.functions.map(([t,e])=>[t.clone(),e]))}startGen(t){}}function Et(t){switch(t.type){case"ConstantValue":return Ct.fromJSON(t);case"IntervalValue":return At.fromJSON(t);case"PiecewiseBezier":return It.fromJSON(t);default:return new Ct(0)}}It.TABLE_SIZE=257;class Nt{constructor(t,e){this.axis=t,this.angle=e,this.type="rotation"}startGen(t){this.angle.startGen(t)}genValue(t,e,i,s){return e.setFromAxisAngle(this.axis,this.angle.genValue(t,s)*i)}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 Nt(new K(t.axis.x,t.axis.y,t.axis.z),Et(t.angle))}clone(){return new Nt(this.axis.clone(),this.angle.clone())}}const Lt=t=>({r:t.x,g:t.y,b:t.z,a:t.w}),Rt=t=>new zt(t.r,t.g,t.b,t.a),Dt=(t,e)=>{switch(e){case"Vector3":return new K(t.x,t.y,t.z);case"Vector4":return new zt(t.x,t.y,t.z,t.w);case"Color":return new K(t.r,t.g,t.b);default:return t}},Ut=(t,e)=>{switch(e){case"Vector3":return{x:t.x,y:t.y,z:t.z};case"Vector4":return{x:t.x,y:t.y,z:t.z,w:t.w};case"Color":return{r:t.x,g:t.y,b:t.z};default:return t}};class qt{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(b())}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:Lt(this.a),b:Lt(this.b)}}static fromJSON(t){return new qt(Rt(t.a),Rt(t.b))}clone(){return new qt(this.a.clone(),this.b.clone())}}class kt{constructor(t,e){this.subType=e,this.type="function",this.keys=t}findKey(t){const e=this.keys,i=e.length-1;if(i<=0)return 0===i&&t>=e[0][1]&&t<=1?0:-1;if(1===i)return t<e[0][1]||t>1?-1:t<=e[1][1]?0:1;let s=0,n=i;for(;s+1<n;){const i=s+n>>1;if(t<e[i][1])n=i-1;else{if(!(t>this.getEndX(i)))return i;s=i+1}}for(let i=s;i<=n;i++)if(t>=e[i][1]&&t<=this.getEndX(i))return i;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 i=this.keys,s=this.findKey(e),n=i.length-1;if("Number"===this.subType){if(-1===s)return i[0][0];if(s>=n)return i[n][0];const t=i[s][1],r=i[s][0],o=i[s+1][1]-t;return(i[s+1][0]-r)*(o>0?(e-t)/o:0)+r}{if(-1===s)return t.copy(i[0][0]);if(s>=n)return t.copy(i[n][0]);const r=i[s][1],o=i[s+1][1]-r;return t.copy(i[s][0]).lerp(i[s+1][0],o>0?(e-r)/o:0)}}toJSON(){return this.keys[0][0].constructor.name,{type:"CLinearFunction",subType:this.subType,keys:this.keys.map(([t,e])=>({value:Ut(t,this.subType),pos:e}))}}static fromJSON(t){return new kt(t.keys.map(e=>[Dt(e.value,t.subType),e.pos]),t.subType)}clone(){return"Number"===this.subType?new kt(this.keys.map(([t,e])=>[t,e]),this.subType):new kt(this.keys.map(([t,e])=>[t.clone(),e]),this.subType)}}const Jt=new zt;class Qt{constructor(t=[[new K(0,0,0),0],[new K(1,1,1),0]],e=[[1,0],[1,1]]){this.table=null,this.tableSignature=null,this.type="function",this.color=new kt(t,"Color"),this.alpha=new kt(e,"Number")}refreshTable(){const t=this.color.keys,e=this.alpha.keys,i=4*t.length+2*e.length;let s=this.tableSignature,n=null===s||s.length!==i;n&&(s=new Float64Array(i));let r=0;for(let e=0;e<t.length;e++,r+=4){const i=t[e][0],o=t[e][1];n||(n=s[r]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z||s[r+3]!==o),n&&(s[r]=i.x,s[r+1]=i.y,s[r+2]=i.z,s[r+3]=o)}for(let t=0;t<e.length;t++,r+=2){const i=e[t][0],o=e[t][1];n||(n=s[r]!==i||s[r+1]!==o),n&&(s[r]=i,s[r+1]=o)}if(!n&&null!==this.table)return;this.tableSignature=s;const o=Qt.TABLE_SIZE,a=null!==this.table&&this.table.length===4*o?this.table:new Float32Array(4*o),l=1/(o-1),h=Jt;for(let t=0;t<o;t++){this.genColorExact(h,t*l);const e=4*t;a[e]=h.x,a[e+1]=h.y,a[e+2]=h.z,a[e+3]=h.w}this.table=a}sampledTable(){return this.table}clearTable(){this.table=null,this.tableSignature=null}genColor(t,e,i){const s=this.table;if(null!==s){const t=Qt.TABLE_SIZE-1;if(i<=0)return e.x=s[0],e.y=s[1],e.z=s[2],e.w=s[3],e;if(i>=1){const i=4*t;return e.x=s[i],e.y=s[i+1],e.z=s[i+2],e.w=s[i+3],e}const n=i*t,r=0|n,o=n-r,a=4*r,l=a+4;return e.x=s[a]+(s[l]-s[a])*o,e.y=s[a+1]+(s[l+1]-s[a+1])*o,e.z=s[a+2]+(s[l+2]-s[a+2])*o,e.w=s[a+3]+(s[l+3]-s[a+3])*o,e}return this.genColorExact(e,i)}genColorExact(t,e){const i=this.color.keys,s=i.length-1,n=this.color.findKey(e);let r,o,a;if(-1===n||n>=s){const t=i[-1===n?0:s][0];r=t.x,o=t.y,a=t.z}else{const t=i[n][0],s=i[n+1][0],l=i[n][1],h=i[n+1][1]-l,c=h>0?(e-l)/h:0;r=t.x+(s.x-t.x)*c,o=t.y+(s.y-t.y)*c,a=t.z+(s.z-t.z)*c}const l=this.alpha.keys,h=l.length-1,c=this.alpha.findKey(e);let u;if(-1===c||c>=h)u=l[-1===c?0:h][0];else{const t=l[c][1],i=l[c][0],s=l[c+1][1]-t;u=i+(l[c+1][0]-i)*(s>0?(e-t)/s: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(t=>[qt.fromJSON(t.function).a,t.start]);return t.functions.length>0&&e.push([qt.fromJSON(t.functions[t.functions.length-1].function).b,1]),new Qt(e.map(t=>[new K(t[0].x,t[0].y,t[0].z),t[1]]),e.map(t=>[t[0].w,t[1]]))}{const e=new Qt;return e.alpha=kt.fromJSON(t.alpha),e.color=kt.fromJSON(t.color),e}}clone(){const t=new Qt;return t.alpha=this.alpha.clone(),t.color=this.color.clone(),t}startGen(t){}}Qt.TABLE_SIZE=257;class Gt{constructor(t,e){this.a=t,this.b=e,this.type="value"}startGen(t){}genColor(t,e){const i=b();return e.copy(this.a).lerp(this.b,i)}toJSON(){return{type:"RandomColor",a:Lt(this.a),b:Lt(this.b)}}static fromJSON(t){return new Gt(Rt(t.a),Rt(t.b))}clone(){return new Gt(this.a.clone(),this.b.clone())}}const Wt=new zt;class jt{constructor(t,e){this.indexCount=0,this.type="function",this.gradient1=t,this.gradient2=e}startGen(t){this.indexCount=t.length,t.push(b())}genColor(t,e,i){return this.gradient1.genColor(t,e,i),this.gradient2.genColor(t,Wt,i),t&&void 0!==t[this.indexCount]?e.lerp(Wt,t[this.indexCount]):e.lerp(Wt,b()),e}toJSON(){return{type:"RandomColorBetweenGradient",gradient1:this.gradient1.toJSON(),gradient2:this.gradient2.toJSON()}}static fromJSON(t){return new jt(Qt.fromJSON(t.gradient1),Qt.fromJSON(t.gradient2))}clone(){return new jt(this.gradient1.clone(),this.gradient2.clone())}}class Yt{constructor(t){this.color=t,this.type="value"}startGen(t){}genColor(t,e){return e.copy(this.color)}toJSON(){return{type:"ConstantColor",color:Lt(this.color)}}static fromJSON(t){return new Yt(Rt(t.color))}clone(){return new Yt(this.color.clone())}}function Xt(t){switch(t.type){case"ConstantColor":return Yt.fromJSON(t);case"ColorRange":return qt.fromJSON(t);case"RandomColor":return Gt.fromJSON(t);case"Gradient":return Qt.fromJSON(t);case"RandomColorBetweenGradient":return jt.fromJSON(t);default:return new Yt(new zt(1,1,1,1))}}class Zt{constructor(t,e,i,s){this.angleX=t,this.angleY=e,this.angleZ=i,this.type="rotation",this.eular=new mt(0,0,0,s)}startGen(t){this.angleX.startGen(t),this.angleY.startGen(t),this.angleZ.startGen(t)}genValue(t,e,i,s){return this.eular.set(this.angleX.genValue(t,s)*i,this.angleY.genValue(t,s)*i,this.angleZ.genValue(t,s)*i),e.setFromEuler(this.eular)}toJSON(){return{type:"Euler",angleX:this.angleX.toJSON(),angleY:this.angleY.toJSON(),angleZ:this.angleZ.toJSON(),eulerOrder:this.eular.order}}static fromJSON(t){return new Zt(Et(t.angleX),Et(t.angleY),Et(t.angleZ),t.eulerOrder)}clone(){return new Zt(this.angleX,this.angleY,this.angleZ,this.eular.order)}}class Ht{constructor(){this.indexCount=0,this.type="rotation"}startGen(t){let e,i,s,n,r,o;this.indexCount=t.length;do{e=2*b()-1,i=2*b()-1,s=e*e+i*i}while(s>1);do{n=2*b()-1,r=2*b()-1,o=n*n+r*r}while(o>1);const a=Math.sqrt((1-s)/o);t.push(e,i,a*n,a*r)}genValue(t,e,i,s){-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 Ht}clone(){return new Ht}}function Kt(t){switch(t.type){case"AxisAngle":return Nt.fromJSON(t);case"Euler":return Zt.fromJSON(t);case"RandomQuat":return Ht.fromJSON(t);default:return new Ht}}class te{constructor(t,e,i){this.x=t,this.y=e,this.z=i,this.type="vec3function"}startGen(t){this.x.startGen(t),this.y.startGen(t),this.z.startGen(t)}genValue(t,e,i){return e.set(this.x.genValue(t,i),this.y.genValue(t,i),this.z.genValue(t,i))}toJSON(){return{type:"Vector3Function",x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new te(Et(t.x),Et(t.y),Et(t.z))}clone(){return new te(this.x,this.y,this.z)}}function ee(t){return"Vector3Function"===t.type?te.fromJSON(t):new te(new Ct(0),new Ct(0),new Ct(0))}function ie(t){switch(t.type){case"ConstantValue":case"IntervalValue":case"PiecewiseBezier":return Et(t);case"AxisAngle":case"RandomQuat":case"Euler":return Kt(t);case"Vector3Function":return ee(t);default:return new Ct(0)}}class se{constructor(t,e){this.direction=t,this.magnitude=e,this.type="ApplyForce",this.memory={data:[],dataCount:0},this.magnitudeValue=this.magnitude.genValue(this.memory)}initialize(t){}update(t,e){const i=this.magnitudeValue*e,s=this.direction,n=t.velocity;n.x+=s.x*i,n.y+=s.y*i,n.z+=s.z*i}updateAll(t,e,i){const s=this.magnitudeValue*i,n=this.direction.x*s,r=this.direction.y*s,o=this.direction.z*s;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const s=e.velocity;s.x+=n,s.y+=r,s.z+=o}}frameUpdate(t){this.magnitudeValue=this.magnitude.genValue(this.memory)}toJSON(){return{type:this.type,direction:[this.direction.x,this.direction.y,this.direction.z],magnitude:this.magnitude.toJSON()}}static fromJSON(t){return new se(new K(t.direction[0],t.direction[1],t.direction[2]),Et(t.magnitude??t.force))}clone(){return new se(this.direction.clone(),this.magnitude.clone())}reset(){}}class ne{constructor(t=0,e=0,i=new K){this.scaleX=t,this.scaleY=e,this.position=i,this.locations=[]}transform(t,e){t.x=this.locations[e%this.locations.length].x*this.scaleX+this.position.x,t.y=this.locations[e%this.locations.length].y*this.scaleY+this.position.y,t.z=this.position.z}static fromJSON(t){const e=new ne(t.scaleX,t.scaleY,new K(t.position[0],t.position[1],t.position[2]));return e.locations=t.locations.map(t=>new St(t.x,t.y)),e}clone(){const t=new ne(this.scaleX,this.scaleY,this.position.clone());return t.locations=this.locations.map(t=>t.clone()),t}toJSON(){return{scaleX:this.scaleX,scaleY:this.scaleY,position:this.position,locations:this.locations.map(t=>({x:t.x,y:t.y}))}}fromImage(t,e){const i=document.createElement("canvas");i.width=t.width,i.height=t.height;const s=i.getContext("2d");if(!s)return;s.drawImage(t,0,0);const n=s.getImageData(0,0,i.width,i.height,{colorSpace:"srgb"});i.remove(),this.locations.length=0;for(let t=0;t<n.height;t++)for(let i=0;i<n.width;i++)n.data[4*(t*n.width+i)+3]>e&&this.locations.push(new St(i,n.height-t))}}function re(t){return"TextureSequencer"===t.type?ne.fromJSON(t):new ne}class oe{constructor(t){this.type="ApplySequences",this.sequencers=[],this.time=0,this.index=0,this.pCount=0,this.tempV=new K,this.delay=t}initialize(t){t.id=this.pCount,t.dst=new K,t.begin=new K,t.inMotion=!1,this.pCount++}reset(){this.time=0,this.index=0,this.pCount=0}update(t,e){const i=this.sequencers[this.index];if(void 0===i)return;const s=t.id*this.delay;this.time>=i[0].a+s&&this.time<=i[0].b+s?(t.inMotion||(t.inMotion=!0,t.begin.copy(t.position),i[1].transform(t.dst,t.id)),t.position.lerpVectors(t.begin,t.dst,oe.BEZIER.genValue((this.time-i[0].a-s)/(i[0].b-i[0].a)))):this.time>i[0].b+s&&(t.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 oe(t.delay);return t.sequencers.forEach(t=>{e.sequencers.push([Et(t.range),re(t.sequencer)])}),e}clone(){const t=new oe(this.delay);return t.sequencers=this.sequencers.map(t=>[t[0].clone(),t[1].clone()]),t}}oe.BEZIER=new Ft(0,0,1,1);class ae{constructor(t){this.angle=t,this.type="ChangeEmitDirection",this._temp=new K,this._q=new H,this.memory={data:[],dataCount:0}}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.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,b()*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 ae(Et(t.angle))}clone(){return new ae(this.angle)}reset(){}}class le{constructor(t,e){this.color=t,this.speedRange=e,this.type="ColorBySpeed"}initialize(t){this.color.startGen(t.memory)}update(t,e){const i=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a);this.color.genColor(t.memory,t.color,i),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 le(Xt(t.color),At.fromJSON(t.speedRange))}clone(){return new le(this.color.clone(),this.speedRange.clone())}reset(){}}class he{constructor(t){this.color=t,this.type="ColorOverLife"}initialize(t){this.color.startGen(t.memory)}update(t,e){const i=t.color,s=t.startColor;this.color.genColor(t.memory,i,t.age/t.life),i.x*=s.x,i.y*=s.y,i.z*=s.z,i.w*=s.w}updateAll(t,e,i){const s=this.color;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const n=e.color,r=e.startColor;s.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 he(Xt(t.color))}clone(){return new he(this.color.clone())}reset(){}}function ce(t,e){return Math.floor(b()*(e-t))+t}const ue=new K(0,1,0),de=new K(0,0,0),fe=new K(1,1,1),me=new K(0,0,1);var pe;t.SubParticleEmitMode=void 0,(pe=t.SubParticleEmitMode||(t.SubParticleEmitMode={}))[pe.Death=0]="Death",pe[pe.Birth=1]="Birth",pe[pe.Frame=2]="Frame";const ye={color:1,size:2,rotation:4,lifetime:8};function ge(t){let e=0;for(const i of t)e|=ye[i]??0;return e}class ve{constructor(e,i,s,n=t.SubParticleEmitMode.Frame,r=1,o=[]){this.particleSystem=e,this.useVelocityAsBasis=i,this.subParticleSystem=s,this.mode=n,this.emitProbability=r,this.inherit=o,this.type="EmitSubParticleSystem",this.q_=new H,this.v_=new K,this.v2_=new K,this.subEmissions=new Array,this.spareEmissions=new Array;const a=this.target;a&&(a.onlyUsedByOther=!0)}initialize(t){}update(e,i){(this.mode===t.SubParticleEmitMode.Frame||this.mode===t.SubParticleEmitMode.Birth&&0===e.age||this.mode===t.SubParticleEmitMode.Death&&e.age+i>=e.life)&&this.emit(e,i)}get target(){const t=this.subParticleSystem;if(null!==t&&"object"==typeof t)return t.system}emit(t,e){if(!this.target)return;if(b()>this.emitProbability)return;const i=this.spareEmissions.pop(),s=void 0!==i?i:{burstParticleCount:0,burstParticleIndex:0,isBursting:!1,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,matrix:new nt,travelDistance:0,particle:void 0,previousWorldPos:void 0};s.burstParticleCount=0,s.burstParticleIndex=0,s.isBursting=!1,s.burstIndex=0,s.burstWaveIndex=0,s.time=0,s.waitEmiting=0,s.travelDistance=0,s.particle=t,s.inherit=ge(this.inherit),s.previousWorldPos=void 0,this.setMatrixFromParticle(s.matrix,t),this.subEmissions.push(s)}frameUpdate(t){const e=this.target;if(e)for(let i=0;i<this.subEmissions.length;i++)if(this.subEmissions[i].time>=e.duration){const t=this.subEmissions[i];t.particle=void 0,this.spareEmissions.push(t),this.subEmissions[i]=this.subEmissions[this.subEmissions.length-1],this.subEmissions.length=this.subEmissions.length-1,i--}else{const s=this.subEmissions[i];s.particle&&s.particle.age<s.particle.life?this.setMatrixFromParticle(s.matrix,s.particle):s.particle=void 0,e.emit(t,s,s.matrix)}else this.subEmissions.length=0}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 ve(e,t.useVelocityAsBasis,t.subParticleSystem,t.mode,t.emitProbability,ve.validInherit(t.inherit))}clone(){return new ve(this.particleSystem,this.useVelocityAsBasis,this.subParticleSystem,this.mode,this.emitProbability,this.inherit.slice())}reset(){}static validInherit(t){return Array.isArray(t)?t.filter(t=>t in ye):[]}setMatrixFromParticle(t,e){let i;if(void 0===e.rotation||this.useVelocityAsBasis)if(0!==e.velocity.x||0!==e.velocity.y||1!==e.velocity.z&&0!==e.velocity.z){this.v_.copy(me).cross(e.velocity),this.v2_.copy(e.velocity).cross(this.v_);const i=this.v_.length(),s=this.v2_.length();t.set(this.v_.x/i,this.v2_.x/s,e.velocity.x,e.position.x,this.v_.y/i,this.v2_.y/s,e.velocity.y,e.position.y,this.v_.z/i,this.v2_.z/s,e.velocity.z,e.position.z,0,0,0,1)}else t.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1);else e.rotation instanceof H?i=e.rotation:(this.q_.setFromAxisAngle(me,e.rotation),i=this.q_),t.compose(e.position,i,fe);this.particleSystem.worldSpace||t.multiplyMatrices(this.particleSystem.emitter.matrixWorld,t)}}class xe{initialize(t,e){this.ps=e,this.x.startGen(t.memory),this.y.startGen(t.memory),this.z.startGen(t.memory)}constructor(t,e,i){this.x=t,this.y=e,this.z=i,this.type="ForceOverLife",this._temp=new K,this._tempScale=new K,this._tempQ=new H}update(t,e){this._temp.set(this.x.genValue(t.memory,t.age/t.life),this.y.genValue(t.memory,t.age/t.life),this.z.genValue(t.memory,t.age/t.life)),void 0===this.ps||this.ps.worldSpace?t.velocity.addScaledVector(this._temp,e*(this.ps?.motionScale??1)):(this._temp.multiply(this._tempScale).applyQuaternion(this._tempQ),t.velocity.addScaledVector(this._temp,e))}updateAll(t,e,i){const s=this.ps;if(void 0===s)return;const n=this._temp,r=this.x,o=this.y,a=this.z,l=s.worldSpace,h=l?i*(s.motionScale??1):i;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const s=e.memory,c=e.age/e.life;n.set(r.genValue(s,c),o.genValue(s,c),a.genValue(s,c)),l||n.multiply(this._tempScale).applyQuaternion(this._tempQ),e.velocity.addScaledVector(n,h)}}toJSON(){return{type:this.type,x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new xe(Et(t.x),Et(t.y),Et(t.z))}frameUpdate(t){if(this.ps&&!this.ps.worldSpace){const t=this._temp,e=this._tempQ,i=this._tempScale;this.ps.emitter.matrixWorld.decompose(t,e,i),e.invert(),i.set(1/i.x,1/i.y,1/i.z)}}clone(){return new xe(this.x.clone(),this.y.clone(),this.z.clone())}reset(){}}class Se{constructor(t,e={}){this.type="FrameOverLife",this.frame=t,this.fps=e.fps??0,this.cycles=e.cycles??1,this.frameCount=e.frameCount??0,this.loop=e.loop??!0,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)}update(t,e){t.uvTile=this.frameAt(t,t.age,t.age/t.life)}updateAll(t,e,i){for(let i=0;i<e;i++){const e=t[i];e.age>=e.life||(e.uvTile=this.frameAt(e,e.age,e.age/e.life))}}frameAt(t,e,i){if(this.fps>0){const s=this.sampleFrame(t,i),n=this.frameCount;let r=Math.floor(e*this.fps)+this.offset(t);return n>0&&(r=this.loop?Se.wrap(r,n):Math.min(r,n-1)),s+r}let s;if(1!==this.cycles&&this.cycles>0){const e=i*this.cycles;s=this.sampleFrame(t,i>=1?1:e-Math.floor(e))}else s=this.sampleFrame(t,i);return void 0!==this.startFrame&&(s+=this.offset(t),this.frameCount>0&&(s=Se.wrap(s,this.frameCount))),s}offset(t){return void 0!==this.startFrame?Math.floor(this.startFrame.genValue(t.memory)):0}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},...void 0!==this.startFrame?{startFrame:this.startFrame.toJSON()}:{}}}static fromJSON(t){return new Se(Et(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,startFrame:void 0!==t.startFrame?Et(t.startFrame):void 0})}clone(){return new Se(this.frame.clone(),{fps:this.fps,cycles:this.cycles,frameCount:this.frameCount,loop:this.loop,startFrame:this.startFrame?.clone()})}reset(){}}class be{constructor(t,e){this.center=t,this.magnitude=e,this.type="GravityForce",this.temp=new K}initialize(t){}update(t,e){const i=t.position.distanceToSquared(this.center);0!==i&&(this.temp.copy(this.center).sub(t.position).normalize(),t.velocity.addScaledVector(this.temp,this.magnitude/i*e))}updateAll(t,e,i){const s=this.center.x,n=this.center.y,r=this.center.z,o=this.magnitude*i;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const a=e.position,l=s-a.x,h=n-a.y,c=r-a.z,u=l*l+h*h+c*c;if(0===u)continue;const d=o/(u*Math.sqrt(u)),f=e.velocity;f.x+=l*d,f.y+=h*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 be(new K(t.center[0],t.center[1],t.center[2]),t.magnitude)}clone(){return new be(this.center.clone(),this.magnitude)}reset(){}}class we{constructor(t=new Ct(1),e="initial"){this.multiplier=t,this.mode=e,this.type="InheritVelocity",this._temp=new K,this._tempPos=new K,this._tempQInv=new H,this._tempScaleInv=new K(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 we(t.multiplier?Et(t.multiplier):new Ct(1),"current"===t.mode?"current":"initial")}clone(){return new we(this.multiplier.clone(),this.mode)}reset(){}}class Me{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"}update(t,e){let i=t.velocity.length(),s=this.speed.genValue(t.memory,t.age/t.life)*this.motionScale();if(i>s){const n=(i-s)/i;t.velocity.multiplyScalar(1-n*this.dampen*e*20)}}updateAll(t,e,i){const s=this.speed,n=this.dampen*i*20,r=this.motionScale();for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const o=e.velocity,a=o.length(),l=s.genValue(e.memory,e.age/e.life)*r;a>l&&o.multiplyScalar(1-(a-l)/a*n)}}toJSON(){return{type:this.type,speed:this.speed.toJSON(),dampen:this.dampen}}static fromJSON(t){return new Me(Et(t.speed),t.dampen)}frameUpdate(t){this.speed.refreshTable?.()}clone(){return new Me(this.speed.clone(),this.dampen)}reset(){}}class ze{constructor(t=64){this.previousVelocity=ze.EMPTY,this.rotationQuaternion=ze.EMPTY,this.angularVelocityQuaternion=ze.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*ze.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=ze.grow(this.position,3*e),this.previousPosition=ze.grow(this.previousPosition,3*e);const i=this.previousSize===this.size,s=this.previousColor===this.color;if(i||(this.previousSize=ze.grow(this.previousSize,3*e)),this.previousVelocity.length>0&&(this.previousVelocity=ze.grow(this.previousVelocity,3*e)),this.rotationQuaternion.length>0){const t=this.rotationQuaternion.length;this.rotationQuaternion=ze.grow(this.rotationQuaternion,4*e),this.angularVelocityQuaternion=ze.grow(this.angularVelocityQuaternion,4*e);for(let i=t+3;i<4*e;i+=4)this.rotationQuaternion[i]=1,this.angularVelocityQuaternion[i]=1}if(s||(this.previousColor=ze.grow(this.previousColor,4*e)),this.velocity=ze.grow(this.velocity,3*e),this.size=ze.grow(this.size,3*e),this.startSize=ze.grow(this.startSize,3*e),this.color=ze.grow(this.color,4*e),i&&(this.previousSize=this.size),s&&(this.previousColor=this.color),this.startColor=ze.grow(this.startColor,4*e),this.scalars=ze.growDouble(this.scalars,e*ze.SCALAR_STRIDE),this.memoryStride>0){const t=new Float64Array(e*this.memoryStride);t.fill(NaN),t.set(this.memory),this.memory=t}this.rotation=ze.grow(this.rotation,e),this.angularVelocity=ze.grow(this.angularVelocity,e),this.uvTile=ze.grow(this.uvTile,e),this.startSpeed=ze.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 i=e.length;let s=this.memoryStride;if(i>s||this.memory.length<this.capacity*s){s=Math.max(s,i);const t=new Float64Array(this.capacity*s);t.fill(NaN);const e=this.memoryStride,n=this.memory,r=e>0?n.length/e:0;for(let i=0,o=0,a=0;i<r;i++,o+=e,a+=s)for(let i=0;i<e;i++)t[a+i]=n[o+i];this.memory=t,this.memoryStride=s}const n=t*s;for(let t=0;t<s;t++){const s=t<i?e[t]:void 0;this.memory[n+t]="number"==typeof s?s: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 i=3*t,s=3*e;ze.swap3(this.position,i,s),ze.swap3(this.previousPosition,i,s),this.previousSize!==this.size&&ze.swap3(this.previousSize,i,s),this.previousVelocity.length>0&&ze.swap3(this.previousVelocity,i,s),ze.swap3(this.velocity,i,s),ze.swap3(this.size,i,s),ze.swap3(this.startSize,i,s);const n=4*t,r=4*e;ze.swap4(this.color,n,r),this.previousColor!==this.color&&ze.swap4(this.previousColor,n,r),ze.swap4(this.startColor,n,r),this.rotationQuaternion.length>0&&(ze.swap4(this.rotationQuaternion,n,r),ze.swap4(this.angularVelocityQuaternion,n,r)),ze.swap3(this.scalars,t*ze.SCALAR_STRIDE,e*ze.SCALAR_STRIDE);const o=this.memoryStride;if(o>0){const i=this.memory;for(let s=0,n=t*o,r=e*o;s<o;s++,n++,r++){const t=i[n];i[n]=i[r],i[r]=t}}ze.swap1(this.rotation,t,e),ze.swap1(this.angularVelocity,t,e),ze.swap1(this.uvTile,t,e),ze.swap1(this.startSpeed,t,e),ze.swap1(this.flip,t,e)}static swap1(t,e,i){const s=t[e];t[e]=t[i],t[i]=s}static growDouble(t,e){const i=new Float64Array(e);return i.set(t),i}static swap3(t,e,i){let s=t[e];t[e]=t[i],t[i]=s,s=t[e+1],t[e+1]=t[i+1],t[i+1]=s,s=t[e+2],t[e+2]=t[i+2],t[i+2]=s}static swap4(t,e,i){ze.swap3(t,e,i);const s=t[e+3];t[e+3]=t[i+3],t[i+3]=s}static grow(t,e){const i=new Float32Array(e);return i.set(t),i}}ze.EMPTY=new Float32Array(0),ze.SCALAR_STRIDE=3,ze.AGE=0,ze.LIFE=1,ze.SPEED_MODIFIER=2;const _e=.5*(Math.sqrt(3)-1),Pe=(3-Math.sqrt(3))/6,Te=1/3,Oe=1/6,Ve=(Math.sqrt(5)-1)/4,Be=(5-Math.sqrt(5))/20,Ce=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]),Ae=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 Fe{constructor(t=e){const e="function"==typeof t?t:function(t){let e=0,i=0,s=0,n=1;const r=function(){let t=4022871197;return function(e){e=e.toString();for(let i=0;i<e.length;i++){t+=e.charCodeAt(i);let s=.02519603282416938*t;t=s>>>0,s-=t,s*=t,t=s>>>0,s-=t,t+=4294967296*s}return 2.3283064365386963e-10*(t>>>0)}}();e=r(" "),i=r(" "),s=r(" "),e-=r(t),e<0&&(e+=1);i-=r(t),i<0&&(i+=1);s-=r(t),s<0&&(s+=1);return function(){const t=2091639*e+2.3283064365386963e-10*n;return e=i,i=s,s=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 i=0;i<255;i++){const s=i+~~(t()*(256-i)),n=e[i];e[i]=e[s],e[s]=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 i=this.permMod12,s=this.perm;let n=0,r=0,o=0;const a=(t+e)*_e,l=Math.floor(t+a),h=Math.floor(e+a),c=(l+h)*Pe,u=t-(l-c),d=e-(h-c);let f,m;u>d?(f=1,m=0):(f=0,m=1);const p=u-f+Pe,y=d-m+Pe,g=u-1+2*Pe,v=d-1+2*Pe,x=255&l,S=255&h;let b=.5-u*u-d*d;if(b>=0){const t=3*i[x+s[S]];b*=b,n=b*b*(Ce[t]*u+Ce[t+1]*d)}let w=.5-p*p-y*y;if(w>=0){const t=3*i[x+f+s[S+m]];w*=w,r=w*w*(Ce[t]*p+Ce[t+1]*y)}let M=.5-g*g-v*v;if(M>=0){const t=3*i[x+1+s[S+1]];M*=M,o=M*M*(Ce[t]*g+Ce[t+1]*v)}return 70*(n+r+o)}noise3D(t,e,i){const s=this.permMod12,n=this.perm;let r,o,a,l;const h=(t+e+i)*Te,c=Math.floor(t+h),u=Math.floor(e+h),d=Math.floor(i+h),f=(c+u+d)*Oe,m=t-(c-f),p=e-(u-f),y=i-(d-f);let g,v,x,S,b,w;m>=p?p>=y?(g=1,v=0,x=0,S=1,b=1,w=0):m>=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):p<y?(g=0,v=0,x=1,S=0,b=1,w=1):m<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=m-g+Oe,z=p-v+Oe,_=y-x+Oe,P=m-S+2*Oe,T=p-b+2*Oe,O=y-w+2*Oe,V=m-1+.5,B=p-1+.5,C=y-1+.5,A=255&c,F=255&u,$=255&d;let I=.6-m*m-p*p-y*y;if(I<0)r=0;else{const t=3*s[A+n[F+n[$]]];I*=I,r=I*I*(Ce[t]*m+Ce[t+1]*p+Ce[t+2]*y)}let E=.6-M*M-z*z-_*_;if(E<0)o=0;else{const t=3*s[A+g+n[F+v+n[$+x]]];E*=E,o=E*E*(Ce[t]*M+Ce[t+1]*z+Ce[t+2]*_)}let N=.6-P*P-T*T-O*O;if(N<0)a=0;else{const t=3*s[A+S+n[F+b+n[$+w]]];N*=N,a=N*N*(Ce[t]*P+Ce[t+1]*T+Ce[t+2]*O)}let L=.6-V*V-B*B-C*C;if(L<0)l=0;else{const t=3*s[A+1+n[F+1+n[$+1]]];L*=L,l=L*L*(Ce[t]*V+Ce[t+1]*B+Ce[t+2]*C)}return 32*(r+o+a+l)}noise4D(t,e,i,s){const n=this.perm;let r,o,a,l,h;const c=(t+e+i+s)*Ve,u=Math.floor(t+c),d=Math.floor(e+c),f=Math.floor(i+c),m=Math.floor(s+c),p=(u+d+f+m)*Be,y=t-(u-p),g=e-(d-p),v=i-(f-p),x=s-(m-p);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,P=w>=3?1:0,T=M>=3?1:0,O=S>=2?1:0,V=b>=2?1:0,B=w>=2?1:0,C=M>=2?1:0,A=S>=1?1:0,F=b>=1?1:0,$=w>=1?1:0,I=M>=1?1:0,E=y-z+Be,N=g-_+Be,L=v-P+Be,R=x-T+Be,D=y-O+2*Be,U=g-V+2*Be,q=v-B+2*Be,k=x-C+2*Be,J=y-A+3*Be,Q=g-F+3*Be,G=v-$+3*Be,W=x-I+3*Be,j=y-1+4*Be,Y=g-1+4*Be,X=v-1+4*Be,Z=x-1+4*Be,H=255&u,K=255&d,tt=255&f,et=255&m;let it=.6-y*y-g*g-v*v-x*x;if(it<0)r=0;else{const t=n[H+n[K+n[tt+n[et]]]]%32*4;it*=it,r=it*it*(Ae[t]*y+Ae[t+1]*g+Ae[t+2]*v+Ae[t+3]*x)}let st=.6-E*E-N*N-L*L-R*R;if(st<0)o=0;else{const t=n[H+z+n[K+_+n[tt+P+n[et+T]]]]%32*4;st*=st,o=st*st*(Ae[t]*E+Ae[t+1]*N+Ae[t+2]*L+Ae[t+3]*R)}let nt=.6-D*D-U*U-q*q-k*k;if(nt<0)a=0;else{const t=n[H+O+n[K+V+n[tt+B+n[et+C]]]]%32*4;nt*=nt,a=nt*nt*(Ae[t]*D+Ae[t+1]*U+Ae[t+2]*q+Ae[t+3]*k)}let rt=.6-J*J-Q*Q-G*G-W*W;if(rt<0)l=0;else{const t=n[H+A+n[K+F+n[tt+$+n[et+I]]]]%32*4;rt*=rt,l=rt*rt*(Ae[t]*J+Ae[t+1]*Q+Ae[t+2]*G+Ae[t+3]*W)}let ot=.6-j*j-Y*Y-X*X-Z*Z;if(ot<0)h=0;else{const t=n[H+1+n[K+1+n[tt+1+n[et+1]]]]%32*4;ot*=ot,h=ot*ot*(Ae[t]*j+Ae[t+1]*Y+Ae[t+2]*X+Ae[t+3]*Z)}return 27*(r+o+a+l+h)}}const $e=100,Ie=new Array($e),Ee=new K,Ne=new H;function Le(t){let e=Ie[t];return void 0===e&&(e=new Fe(t),Ie[t]=e),e}class Re{constructor(t,e,i=new Ct(1),s=new Ct(0),n=new Ct(0),r){this.frequency=t,this.power=e,this.positionAmount=i,this.rotationAmount=s,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,i){const s=t.noise2D(0,e),n=this.remap;return void 0===n?s:n.genValue(i,.5*(s+1))}initialize(t){const e="number"==typeof t.rotation;let i=t._noiseState;if(void 0===i)return i={lastPos:new K,lastRot:0,lastRotQ:e?null:new H,generatorX:Le(ce(0,$e)),generatorY:Le(ce(0,$e)),generatorZ:Le(ce(0,$e)),generatorW:Le(ce(0,$e))},void(t._noiseState=i);i.lastPos.set(0,0,0),i.lastRot=0,e?i.lastRotQ=null:null===i.lastRotQ?i.lastRotQ=new H:i.lastRotQ.set(0,0,0,1),i.generatorX=Le(ce(0,$e)),i.generatorY=Le(ce(0,$e)),i.generatorZ=Le(ce(0,$e)),i.generatorW=Le(ce(0,$e))}static constantOf(t){return t instanceof Ct?t.value:NaN}update(t,e){const i=t._noiseState;if(void 0===i)return;const s=t.memory,n=t.age/t.life,r=this._frequency,o=r==r?r:this.frequency.genValue(s,n),a=this._power,l=a==a?a:this.power.genValue(s,n),h=this._positionAmount,c=h==h?h:this.positionAmount.genValue(s,n),u=this._rotationAmount,d=u==u?u:this.rotationAmount.genValue(s,n),f=t.age*o+this.scrollOffset;if(c>0){const e=l*c;t.position.sub(i.lastPos),Ee.set(this.sample(i.generatorX,f,s)*e,this.sample(i.generatorY,f,s)*e,this.sample(i.generatorZ,f,s)*e),t.position.add(Ee),i.lastPos.copy(Ee)}if(d>0){const e=l*d;if("number"==typeof t.rotation){const n=this.sample(i.generatorW,f,s)*Math.PI*e;t.rotation=t.rotation-i.lastRot+n,i.lastRot=n}else if(null!==i.lastRotQ){const n=t.rotation;i.lastRotQ.invert(),n.multiply(i.lastRotQ),Ne.set(this.sample(i.generatorX,f,s)*e,this.sample(i.generatorY,f,s)*e,this.sample(i.generatorZ,f,s)*e,this.sample(i.generatorW,f,s)*e).normalize(),n.multiply(Ne),i.lastRotQ.copy(Ne)}}}updateAll(t,e,i){const s=e>0?t[0].store:void 0;if(void 0===s){for(let s=0;s<e;s++){const e=t[s];e.age<e.life&&this.update(e,i)}return}const n=s.position,r=s.rotation,o=s.scalars,a=ze.SCALAR_STRIDE,l=this._frequency,h=this._power,c=this._positionAmount,u=this._rotationAmount;for(let i=0,s=0,d=0;i<e;i++,s+=3,d+=a){const e=o[d],a=o[d+1];if(e>=a)continue;const f=t[i],m=f._noiseState;if(void 0===m)continue;const p=f.memory,y=e/a,g=l==l?l:this.frequency.genValue(p,y),v=h==h?h:this.power.genValue(p,y),x=c==c?c:this.positionAmount.genValue(p,y),S=u==u?u:this.rotationAmount.genValue(p,y),b=e*g+this.scrollOffset;if(x>0){const t=v*x,e=m.lastPos,i=this.sample(m.generatorX,b,p)*t,r=this.sample(m.generatorY,b,p)*t,o=this.sample(m.generatorZ,b,p)*t;n[s]=Math.fround(n[s]-e.x)+i,n[s+1]=Math.fround(n[s+1]-e.y)+r,n[s+2]=Math.fround(n[s+2]-e.z)+o,e.set(i,r,o)}if(S>0){const t=v*S;if("number"==typeof f.rotation){const e=this.sample(m.generatorW,b,p)*Math.PI*t;r[i]=r[i]-m.lastRot+e,m.lastRot=e}else if(null!==m.lastRotQ){const e=f.rotation;m.lastRotQ.invert(),e.multiply(m.lastRotQ),Ne.set(this.sample(m.generatorX,b,p)*t,this.sample(m.generatorY,b,p)*t,this.sample(m.generatorZ,b,p)*t,this.sample(m.generatorW,b,p)*t).normalize(),e.multiply(Ne),m.lastRotQ.copy(Ne)}}}}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=Re.constantOf(this.frequency),this._power=Re.constantOf(this.power),this._positionAmount=Re.constantOf(this.positionAmount),this._rotationAmount=Re.constantOf(this.rotationAmount)}static fromJSON(t){return new Re(Et(t.frequency),Et(t.power),Et(t.positionAmount),Et(t.rotationAmount),t.scrollSpeed?Et(t.scrollSpeed):new Ct(0),t.remap?Et(t.remap):void 0)}clone(){return new Re(this.frequency.clone(),this.power.clone(),this.positionAmount.clone(),this.rotationAmount.clone(),this.scrollSpeed.clone(),this.remap?.clone())}reset(){this.scrollOffset=0}}class De{constructor(t,e=new K(0,1,0)){this.orbitSpeed=t,this.axis=e,this.type="OrbitOverLife",this.temp=new K,this.rotation=new H}initialize(t){this.orbitSpeed.startGen(t.memory)}update(t,e){this.temp.copy(t.position).projectOnVector(this.axis),this.rotation.setFromAxisAngle(this.axis,this.orbitSpeed.genValue(t.memory,t.age/t.life)*e),t.position.sub(this.temp),t.position.applyQuaternion(this.rotation),t.position.add(this.temp)}updateAll(t,e,i){const s=this.orbitSpeed,n=this.axis,r=this.temp,o=this.rotation;for(let a=0;a<e;a++){const e=t[a];if(e.age>=e.life)continue;const l=e.position;r.copy(l).projectOnVector(n),o.setFromAxisAngle(n,s.genValue(e.memory,e.age/e.life)*i),l.sub(r),l.applyQuaternion(o),l.add(r)}}frameUpdate(t){}toJSON(){return{type:this.type,orbitSpeed:this.orbitSpeed.toJSON(),axis:[this.axis.x,this.axis.y,this.axis.z]}}static fromJSON(t){return new De(Et(t.orbitSpeed),t.axis?new K(t.axis[0],t.axis[1],t.axis[2]):void 0)}clone(){return new De(this.orbitSpeed.clone())}reset(){}}class Ue{constructor(t){this.angularVelocity=t,this.type="Rotation3DOverLife",this.tempQuat=new H}initialize(t){t.rotation instanceof H&&(t.angularVelocity=new H,this.angularVelocity.startGen(t.memory))}update(t,e){if(t.rotation instanceof H){this.angularVelocity.genValue(t.memory,this.tempQuat,e,t.age/t.life),t.rotation.multiply(this.tempQuat);const i=t.angularVelocity;i instanceof H&&i.copy(this.tempQuat)}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new Ue(Kt(t.angularVelocity))}frameUpdate(t){}clone(){return new Ue(this.angularVelocity.clone())}reset(){}}class qe{constructor(t,e){this.angularVelocity=t,this.speedRange=e,this.type="RotationBySpeed",this.tempQuat=new H}initialize(t){"number"==typeof t.rotation&&this.angularVelocity.startGen(t.memory)}update(t,e){if("number"==typeof t.rotation){const i=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a),s=this.angularVelocity.genValue(t.memory,i);t.rotation+=e*s,t.angularVelocity=s}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new qe(Et(t.angularVelocity),At.fromJSON(t.speedRange))}frameUpdate(t){}clone(){return new qe(this.angularVelocity.clone(),this.speedRange.clone())}reset(){}}class ke{constructor(t){this.angularVelocity=t,this.type="RotationOverLife",this.tempQuat=new H}initialize(t){"number"==typeof t.rotation?this.angularVelocity.startGen(t.memory):t.rotation instanceof H&&(this.angularVelocity.startGen(t.memory),t.angularVelocity instanceof H||(t.angularVelocity=new H))}update(t,e){if("number"==typeof t.rotation){const i=this.angularVelocity.genValue(t.memory,t.age/t.life);t.rotation+=e*i,t.angularVelocity=i}else if(t.rotation instanceof H){const i=this.angularVelocity.genValue(t.memory,t.age/t.life);this.turnAboutZ(t,t.rotation,i*e)}}updateAll(t,e,i){const s=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=s.genValue(e.memory,e.age/e.life);e.rotation=r+i*t,e.angularVelocity=t}else if(r instanceof H){const t=s.genValue(e.memory,e.age/e.life);this.turnAboutZ(e,r,t*i)}}}turnAboutZ(t,e,i){const s=this.tempQuat.setFromAxisAngle(me,i);e.multiply(s);const n=t.angularVelocity;n instanceof H&&n.copy(s)}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new ke(Et(t.angularVelocity))}frameUpdate(t){this.angularVelocity.refreshTable?.()}clone(){return new ke(this.angularVelocity.clone())}reset(){}}class Je{initialize(t){this.size.startGen(t.memory)}constructor(t,e){this.size=t,this.speedRange=e,this.type="SizeBySpeed"}update(t){const e=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a);this.size instanceof te?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 Je(ie(t.size),At.fromJSON(t.speedRange))}frameUpdate(t){}clone(){return new Je(this.size.clone(),this.speedRange.clone())}reset(){}}class Qe{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 te}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 i=this._size.genValue(t.memory,e),s=t.size,n=t.startSize;s.x=n.x*i,s.y=n.y*i,s.z=n.z*i}}updateAll(t,e,i){if(this._sizeIsVector3){const i=this._size;for(let s=0;s<e;s++){const e=t[s];e.age>=e.life||i.genValue(e.memory,e.size,e.age/e.life).multiply(e.startSize)}return}const s=this._size;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const n=s.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 Qe(ie(t.size))}frameUpdate(t){this._size.refreshTable?.()}clone(){return new Qe(this.size.clone())}reset(){}}class Ge{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,i){const s=this.speed;for(let i=0;i<e;i++){const e=t[i];e.age>=e.life||(e.speedModifier=s.genValue(e.memory,e.age/e.life))}}toJSON(){return{type:this.type,speed:this.speed.toJSON()}}static fromJSON(t){return new Ge(Et(t.speed))}frameUpdate(t){this.speed.refreshTable?.()}clone(){return new Ge(this.speed.clone())}reset(){}}class We{constructor(t,e,i,s){this.scale=t,this.octaves=e,this.velocityMultiplier=i,this.timeScale=s,this.type="TurbulenceField",this.generator=new Fe(b),this.timeOffset=new K,this.temp=new K,this.temp2=new K,this.timeOffset.x=b()/this.scale.x*this.timeScale.x,this.timeOffset.y=b()/this.scale.y*this.timeScale.y,this.timeOffset.z=b()/this.scale.z*this.timeScale.z}initialize(t){}update(t,e){const i=t.position.x/this.scale.x,s=t.position.y/this.scale.y,n=t.position.z/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(i*r,s*r,n*r,this.timeOffset.x*r)/r,this.generator.noise4D(i*r,s*r,n*r,this.timeOffset.y*r)/r,this.generator.noise4D(i*r,s*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,i){const s=e>0?t[0].store:void 0;if(void 0===s){for(let s=0;s<e;s++){const e=t[s];e.age<e.life&&this.update(e,i)}return}const n=s.position,r=s.velocity,o=s.scalars,a=ze.SCALAR_STRIDE,l=this.generator,h=this.octaves,c=1/this.scale.x,u=1/this.scale.y,d=1/this.scale.z,f=this.velocityMultiplier.x*i,m=this.velocityMultiplier.y*i,p=this.velocityMultiplier.z*i,y=this.timeOffset.x,g=this.timeOffset.y,v=this.timeOffset.z;for(let t=0,i=0,s=0;t<e;t++,i+=3,s+=a){if(o[s]>=o[s+1])continue;const t=n[i]*c,e=n[i+1]*u,a=n[i+2]*d;let x=0,S=0,b=0,w=1;for(let i=0;i<h;i++){const i=t*w,s=e*w,n=a*w;x+=l.noise4D(i,s,n,y*w)/w,S+=l.noise4D(i,s,n,g*w)/w,b+=l.noise4D(i,s,n,v*w)/w,w*=2}r[i]+=x*f,r[i+1]+=S*m,r[i+2]+=b*p}}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]}}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 We(new K(t.scale[0],t.scale[1],t.scale[2]),t.octaves,new K(t.velocityMultiplier[0],t.velocityMultiplier[1],t.velocityMultiplier[2]),new K(t.timeScale[0],t.timeScale[1],t.timeScale[2]))}clone(){return new We(this.scale.clone(),this.octaves,this.velocityMultiplier.clone(),this.timeScale.clone())}reset(){}}const je=new K(1,0,0),Ye=new K(0,1,0),Xe=new K(0,0,1);class Ze{constructor(t=new Ct(0),e=new Ct(0),i=new Ct(0),s=new Ct(0),n=new Ct(0),r=new Ct(0),o="local",a=new Ct(0),l=new K){this.linearX=t,this.linearY=e,this.linearZ=i,this.orbitalX=s,this.orbitalY=n,this.orbitalZ=r,this.space=o,this.radial=a,this.orbitalOffset=l,this.type="VelocityOverLife",this._temp=new K,this._tempEmitterPos=new K,this._tempQ=new H,this._tempQInv=new H,this._tempScale=new K(1,1,1),this._tempScaleInv=new K(1,1,1),this._tempRot=new H,this._axisX=new K(1,0,0),this._axisY=new K(0,1,0),this._axisZ=new K(0,0,1),this._center=new K}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(je),this._axisY.copy(Ye),this._axisZ.copy(Xe),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 i=t.age/t.life;this._temp.set(this.linearX.genValue(t.memory,i),this.linearY.genValue(t.memory,i),this.linearZ.genValue(t.memory,i));const s=void 0!==this.ps&&this.ps.worldSpace;s&&"local"===this.space?this._temp.multiply(this._tempScale).applyQuaternion(this._tempQ):s||"world"!==this.space||this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv),t.position.addScaledVector(this._temp,e);const n=this.radial.genValue(t.memory,i);if(0!==n){this._temp.copy(t.position).sub(this._center);const i=this._temp.length();i>0&&t.position.addScaledVector(this._temp,n*e/i)}const r=this.orbitalX.genValue(t.memory,i)*e,o=this.orbitalY.genValue(t.memory,i)*e,a=this.orbitalZ.genValue(t.memory,i)*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,i){0!==i&&(this._tempRot.setFromAxisAngle(e,i),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?Et(t):new Ct(0);return new Ze(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 K(t.orbitalOffset[0]??0,t.orbitalOffset[1]??0,t.orbitalOffset[2]??0):new K)}clone(){return new Ze(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 He{constructor(t){this.data=t,this.next=null,this.prev=null}hasPrev(){return null!==this.prev}hasNext(){return null!==this.next}}class Ke{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 He(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 He(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 i=new He(e);i.next=t,i.prev=t.prev,null!==i.prev&&(i.prev.next=i),i.next.prev=i,t==this.head&&(this.head=i),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 ti{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 vt(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 vt(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 ze(1),e=0){this.rotationQuaternion=void 0,this.angularVelocityQuaternion=void 0,this.memory=[],this.store=t,this.storeIndex=e;const i=3*e,s=4*e;this.position=new wt(t.position,i),this.previousPosition=new wt(t.previousPosition,i),this.previousVelocity=new wt(t.previousVelocity,i),this.velocity=new wt(t.velocity,i),this.size=new wt(t.size,i),this.startSize=new wt(t.startSize,i),this.color=new Pt(t.color,s),this.startColor=new Pt(t.startColor,s),this.scalars=t.scalars,this.scalarOffset=e*ze.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,i=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,i),this.startColor.bind(t.startColor,i),this.rotationQuaternion?.bind(t.rotationQuaternion,i),this.angularVelocityQuaternion?.bind(t.angularVelocityQuaternion,i),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*ze.SCALAR_STRIDE}get died(){return this.age>=this.life}reset(){this.memory.length=0}}const ei=new Float32Array(0);class ii{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 Ke)}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 ze(1),e=0){this.length=100,this._previous=void 0,this.historyPositions=ei,this.historySizes=ei,this.historyBaseSizes=ei,this.headWidthScale=1,this.historyColors=ei,this.historyCapacity=0,this.historyHead=0,this.historyCount=0,this.memory=[],this.store=t,this.storeIndex=e;const i=3*e,s=4*e;this.position=new wt(t.position,i),this.previousPosition=new wt(t.previousPosition,i),this.previousVelocity=new wt(t.previousVelocity,i),this.velocity=new wt(t.velocity,i),this.size=new wt(t.size,i),this.startSize=new wt(t.startSize,i),this.color=new Pt(t.color,s),this.startColor=new Pt(t.startColor,s),this.scalars=t.scalars,this.scalarOffset=e*ze.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,i=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,i),this.startColor.bind(t.startColor,i),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*ze.SCALAR_STRIDE}ensureHistoryCapacity(t){this.historyCapacity!==t&&(this.historyCapacity=t,this.historyPositions=new Float32Array(3*t),this.historySizes=new Float32Array(t),this.historyBaseSizes=new Float32Array(t),this.historyColors=new Float32Array(4*t),this.historyHead=0,this.historyCount=0)}resetHistory(){this.historyHead=0,this.historyCount=0}getHistoryIndex(t){const e=this.historyCapacity;return(this.historyHead-this.historyCount+e+t)%e}update(){0===this.historyCapacity&&this.ensureHistoryCapacity(Math.max(1,Math.ceil(this.length)));const t=this.historyCapacity,e=this.store,i=this.storeIndex,s=i*ze.SCALAR_STRIDE;if(e.scalars[s+ze.AGE]>e.scalars[s+ze.LIFE])return void(this.historyCount>0&&this.historyCount--);const n=this.historyHead,r=3*n,o=this.historyPositions,a=e.position,l=3*i;o[r]=a[l],o[r+1]=a[l+1],o[r+2]=a[l+2];const h=e.size[l];this.historyBaseSizes[n]=h,this.historySizes[n]=h*this.headWidthScale;const c=4*n,u=this.historyColors,d=e.color,f=4*i;u[c]=d[f],u[c+1]=d[f+1],u[c+2]=d[f+2],u[c+3]=d[f+3],this.historyHead=(n+1)%t,this.historyCount<t&&this.historyCount++}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.headWidthScale=1,this.resetHistory()}}class si{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 ii))return;const e=t.memory;t.headWidthScale=this.absolute?1:this.width.genValue(e,0);const i=t.historyCount;if(0===i)return;const s=t.historyCapacity,n=t.historySizes,r=t.historyBaseSizes,o=1/t.length,a=this.absolute;let l=t.getHistoryIndex(0);for(let t=0;t<i;t++){const h=this.width.genValue(e,(i-t)*o);n[l]=a?h:r[l]*h,l++,l===s&&(l=0)}}frameUpdate(t){}toJSON(){return{type:this.type,width:this.width.toJSON(),absolute:this.absolute}}static fromJSON(t){return new si(Et(t.width),t.absolute??!0)}clone(){return new si(this.width.clone(),this.absolute)}reset(){}}const ni={ApplyForce:{type:"ApplyForce",constructor:se,params:[["direction",["vec3"]],["magnitude",["value"]]],loadJSON:se.fromJSON},Noise:{type:"Noise",constructor:Re,params:[["frequency",["value"]],["power",["value"]],["positionAmount",["value"]],["rotationAmount",["value"]]],loadJSON:Re.fromJSON},TurbulenceField:{type:"TurbulenceField",constructor:We,params:[["scale",["vec3"]],["octaves",["number"]],["velocityMultiplier",["vec3"]],["timeScale",["vec3"]]],loadJSON:We.fromJSON},GravityForce:{type:"GravityForce",constructor:be,params:[["center",["vec3"]],["magnitude",["number"]]],loadJSON:be.fromJSON},ColorOverLife:{type:"ColorOverLife",constructor:he,params:[["color",["colorFunc"]]],loadJSON:he.fromJSON},RotationOverLife:{type:"RotationOverLife",constructor:ke,params:[["angularVelocity",["value","valueFunc"]]],loadJSON:ke.fromJSON},Rotation3DOverLife:{type:"Rotation3DOverLife",constructor:Ue,params:[["angularVelocity",["rotationFunc"]]],loadJSON:Ue.fromJSON},SizeOverLife:{type:"SizeOverLife",constructor:Qe,params:[["size",["value","valueFunc","vec3Func"]]],loadJSON:Qe.fromJSON},ColorBySpeed:{type:"ColorBySpeed",constructor:le,params:[["color",["colorFunc"]],["speedRange",["range"]]],loadJSON:le.fromJSON},RotationBySpeed:{type:"RotationBySpeed",constructor:qe,params:[["angularVelocity",["value","valueFunc"]],["speedRange",["range"]]],loadJSON:qe.fromJSON},SizeBySpeed:{type:"SizeBySpeed",constructor:Je,params:[["size",["value","valueFunc","vec3Func"]],["speedRange",["range"]]],loadJSON:Je.fromJSON},SpeedOverLife:{type:"SpeedOverLife",constructor:Ge,params:[["speed",["value","valueFunc"]]],loadJSON:Ge.fromJSON},FrameOverLife:{type:"FrameOverLife",constructor:Se,params:[["frame",["value","valueFunc"]]],loadJSON:Se.fromJSON},ForceOverLife:{type:"ForceOverLife",constructor:xe,params:[["x",["value","valueFunc"]],["y",["value","valueFunc"]],["z",["value","valueFunc"]]],loadJSON:xe.fromJSON},VelocityOverLife:{type:"VelocityOverLife",constructor:Ze,params:[["linearX",["value","valueFunc"]],["linearY",["value","valueFunc"]],["linearZ",["value","valueFunc"]],["orbitalX",["value","valueFunc"]],["orbitalY",["value","valueFunc"]],["orbitalZ",["value","valueFunc"]],["space",["string"]]],loadJSON:Ze.fromJSON},InheritVelocity:{type:"InheritVelocity",constructor:we,params:[["multiplier",["value","valueFunc"]],["mode",["string"]]],loadJSON:we.fromJSON},OrbitOverLife:{type:"OrbitOverLife",constructor:De,params:[["orbitSpeed",["value","valueFunc"]],["axis",["vec3"]]],loadJSON:De.fromJSON},WidthOverLength:{type:"WidthOverLength",constructor:si,params:[["width",["value","valueFunc"]]],loadJSON:si.fromJSON},ChangeEmitDirection:{type:"ChangeEmitDirection",constructor:ae,params:[["angle",["value"]]],loadJSON:ae.fromJSON},ApplySequences:{type:"ApplySequences",constructor:oe,params:[["delay",["number"]]],loadJSON:oe.fromJSON},EmitSubParticleSystem:{type:"EmitSubParticleSystem",constructor:ve,params:[["particleSystem",["self"]],["useVelocityAsBasis",["boolean"]],["subParticleSystem",["particleSystem"]],["mode",["number"]],["emitProbability",["number"]]],loadJSON:ve.fromJSON},LimitSpeedOverLife:{type:"LimitSpeedOverLife",constructor:Me,params:[["speed",["value","valueFunc"]],["dampen",["number"]]],loadJSON:Me.fromJSON},ApplyCollision:{type:"ApplyCollision",constructor:Bt,params:[["bounce",["number"]]],loadJSON:Bt.fromJSON}};function ri(t,e){return ni[t.type]?ni[t.type].loadJSON(t,e):null}const oi={PiecewiseBezier:It,Vector3Function:te,Quaternion:H,ConstantValue:Ct,Gradient:Qt,Vector4View:Pt,AxisAngleGenerator:Nt,IntervalValue:At,ColorRange:qt};function ai(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 li(t,e,i){return`let ${e};\n if (${t}_tbl !== null) {\n const tt = ${i};\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, ${i});`}function hi(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 ci(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 ui(t,e,i,s,n,r,o){return`{\n const cx = 2 * (${n} * ${i} - ${r} * ${e});\n const cy = 2 * (${r} * ${t} - ${s} * ${i});\n const cz = 2 * (${s} * ${e} - ${n} * ${t});\n const nx = ${t} + ${o} * cx + ${n} * cz - ${r} * cy;\n const ny = ${e} + ${o} * cy + ${r} * cx - ${s} * cz;\n ${i} = ${i} + ${o} * cz + ${s} * cy - ${n} * cx;\n ${t} = nx;\n ${e} = ny;\n }`}function di(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 fi(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 mi(t,e,i,s){return`{\n const half = ${t} / 2;\n const sn = Math.sin(half);\n const qx = ${e} * sn, qy = ${i} * sn, qz = ${s} * sn, qw = Math.cos(half);\n ${ui("px","py","pz","qx","qy","qz","qw")}\n px = Math.fround(px); py = Math.fround(py); pz = Math.fround(pz);\n }`}function pi(t,e){switch(t.type){case"ColorOverLife":return{setup:hi(`g${e}`,`behaviors[${e}].color`),body:`{${ci(`g${e}`,"t")}}`};case"SizeOverLife":return{setup:`const g${e} = behaviors[${e}].size;\n const vec3_${e} = g${e} instanceof deps.Vector3Function;\n ${ai(`sg${e}`,`g${e}`)}`,body:`if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, t).multiply(p.startSize);\n } else {\n ${li(`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 f${e} = b${e}.magnitudeValue * delta;\n const dx${e} = b${e}.direction.x * f${e};\n const dy${e} = b${e}.direction.y * f${e};\n const dz${e} = b${e}.direction.z * f${e};`,body:`vel[o3] += dx${e}; vel[o3 + 1] += dy${e}; vel[o3 + 2] += dz${e};`};case"RotationOverLife":return{setup:`${ai(`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 ${li(`g${e}`,"rate","t")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n } else if (quat_${e}) {\n ${li(`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:`${ai(`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}) {${li(`g${e}`,"v","t")} uvTile[row] = v;}\n else uvTile[row] = b${e}.frameAt(p, age, t);`};case"SpeedOverLife":return{setup:ai(`g${e}`,`behaviors[${e}].speed`),body:`{${li(`g${e}`,"v","t")} scalars[s + 2] = v;}`};case"ForceOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${ai(`gx${e}`,`b${e}.x`)}\n ${ai(`gy${e}`,`b${e}.y`)}\n ${ai(`gz${e}`,`b${e}.z`)}\n const local${e} = b${e}.ps !== undefined && !b${e}.ps.worldSpace;\n const ms${e} = !local${e} && b${e}.ps !== undefined ? (b${e}.ps.motionScale ?? 1) : 1;\n ${fi(`sc${e}`,`b${e}._tempScale`)}\n ${di(`q${e}`,`b${e}._tempQ`)}`,body:`{\n ${li(`gx${e}`,"fx","t")}\n ${li(`gy${e}`,"fy","t")}\n ${li(`gz${e}`,"fz","t")}\n if (local${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${ui("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n } else if (ms${e} !== 1) {\n fx *= ms${e}; fy *= ms${e}; fz *= ms${e};\n }\n vel[o3] += fx * delta; vel[o3 + 1] += fy * delta; vel[o3 + 2] += fz * delta;}`};case"LimitSpeedOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${ai(`g${e}`,`b${e}.speed`)}\n const dampen${e} = b${e}.dampen * delta * 20;\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 ${li(`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 ${hi(`g${e}`,`b${e}.color`)}\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};`,body:`{const ts = (startSpeed[row] - lo${e}) / span${e};\n ${ci(`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 ${ai(`sg${e}`,`g${e}`)}`,body:`{const ts = (startSpeed[row] - lo${e}) / span${e};\n if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, ts).multiply(p.startSize);\n } else {\n ${li(`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 ${ai(`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 const ts = (startSpeed[row] - lo${e}) / span${e};\n ${li(`g${e}`,"rate","ts")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n }`};case"OrbitOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${ai(`g${e}`,`b${e}.orbitSpeed`)}\n ${fi(`ax${e}`,`b${e}.axis`)}\n const alen${e} = ax${e}x * ax${e}x + ax${e}y * ax${e}y + ax${e}z * ax${e}z;\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:`{let px = pos[o3], py = pos[o3 + 1], pz = pos[o3 + 2];\n let tx = 0, ty = 0, tz = 0;\n if (alen${e} !== 0) {\n const f = (ax${e}x * px + ax${e}y * py + ax${e}z * pz) / alen${e};\n tx = ax${e}x * f; ty = ax${e}y * f; tz = ax${e}z * f;\n }\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 ${li(`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 ${ui("px","py","pz","qx","qy","qz","qw")}\n pos[o3] = Math.fround(px) + tx;\n pos[o3 + 1] = Math.fround(py) + ty;\n pos[o3 + 2] = Math.fround(pz) + tz;}`};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 ${ai(`lx${e}`,`b${e}.linearX`)}\n ${ai(`ly${e}`,`b${e}.linearY`)}\n ${ai(`lz${e}`,`b${e}.linearZ`)}\n ${ai(`ox${e}`,`b${e}.orbitalX`)}\n ${ai(`oy${e}`,`b${e}.orbitalY`)}\n ${ai(`oz${e}`,`b${e}.orbitalZ`)}\n ${fi(`aX${e}`,`b${e}._axisX`)}\n ${fi(`aY${e}`,`b${e}._axisY`)}\n ${fi(`aZ${e}`,`b${e}._axisZ`)}\n ${fi(`pv${e}`,`b${e}._tempEmitterPos`)}\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 ${fi(`sc${e}`,`toWorld${e} ? b${e}._tempScale : b${e}._tempScaleInv`)}\n ${di(`q${e}`,`toWorld${e} ? b${e}._tempQ : b${e}._tempQInv`)}`,body:`{\n ${li(`lx${e}`,"fx","t")}\n ${li(`ly${e}`,"fy","t")}\n ${li(`lz${e}`,"fz","t")}\n if (convert${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${ui("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 ${li(`ox${e}`,"rx","t")}\n ${li(`oy${e}`,"ry","t")}\n ${li(`oz${e}`,"rz","t")}\n rx *= delta; ry *= delta; rz *= delta;\n if (rx !== 0 || ry !== 0 || rz !== 0) {\n if (world${e}) {\n px = Math.fround(px - pv${e}x); py = Math.fround(py - pv${e}y); pz = Math.fround(pz - pv${e}z);\n }\n if (rx !== 0) ${mi("rx",`aX${e}x`,`aX${e}y`,`aX${e}z`)}\n if (ry !== 0) ${mi("ry",`aY${e}x`,`aY${e}y`,`aY${e}z`)}\n if (rz !== 0) ${mi("rz",`aZ${e}x`,`aZ${e}y`,`aZ${e}z`)}\n if (world${e}) {\n px = Math.fround(px + pv${e}x); py = Math.fround(py + pv${e}y); pz = Math.fround(pz + pv${e}z);\n }\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 ${fi(`sc${e}`,`b${e}._tempScaleInv`)}\n ${di(`q${e}`,`b${e}._tempQInv`)}\n ivx${e} *= sc${e}x; ivy${e} *= sc${e}y; ivz${e} *= sc${e}z;\n ${ui(`ivx${e}`,`ivy${e}`,`ivz${e}`,`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n }\n }\n ${ai(`gm${e}`,`b${e}.multiplier`)}`,body:`if (active${e}) {\n ${li(`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 yi=new Map;function gi(t,e,i){const s=yi.get(i);if(void 0!==s)return s??void 0;const n=function(t,e){const i=`\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) {${i}};`)(oi)}catch(t){return}}(t,e);return yi.set(i,n??null),n}function vi(t){const e=[];let i=[],s=[],n=[],r=0;const o=()=>{if(0===s.length)return;const t=`${r}:${i.map(t=>t.type).join(",")}`,o=gi(s,n,t);if(void 0!==o)e.push({behaviors:i,run:o});else for(const t of i)e.push({behaviors:[t]});i=[],s=[],n=[]};for(let a=0;a<t.length;a++){const l=t[a],h=pi(l,a);null!==h?(0===s.length&&(r=a),i.push(l),s.push(h),n.push(a)):(o(),e.push({behaviors:[l]}))}return o(),e}var xi,Si;t.BoxEmitFrom=void 0,(xi=t.BoxEmitFrom||(t.BoxEmitFrom={}))[xi.Volume=0]="Volume",xi[xi.Shell=1]="Shell",xi[xi.Edge=2]="Edge";class bi{constructor(e={}){this.type="box",this._point=[0,0,0],this.width=e.width??1,this.height=e.height??1,this.depth=e.depth??1,this.emitFrom=e.emitFrom??t.BoxEmitFrom.Volume,this.boxThickness=e.boxThickness?[...e.boxThickness]:[0,0,0]}update(t,e){}initialize(e,i){const s=this._point;for(let t=0;t<3;t++)s[t]=2*b()-1;const n=Math.floor(3*b())%3;this.emitFrom===t.BoxEmitFrom.Shell?s[n]=this.onSurface(n):this.emitFrom===t.BoxEmitFrom.Edge&&(s[(n+1)%3]=this.onSurface((n+1)%3),s[(n+2)%3]=this.onSurface((n+2)%3)),e.position.set(s[0]*this.width/2,s[1]*this.height/2,s[2]*this.depth/2),e.velocity.set(0,0,e.startSpeed)}onSurface(t){const e=b()<.5?-1:1,i=this.boxThickness[t];return i<=0||b()<.5?e:e*(1-2*i*b())}toJSON(){return{type:"box",width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:[...this.boxThickness]}}static fromJSON(t){return new bi({width:t.width,height:t.height,depth:t.depth,emitFrom:t.emitFrom,boxThickness:Array.isArray(t.boxThickness)?t.boxThickness:void 0})}clone(){return new bi({width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:this.boxThickness})}}function wi(e,i,s,n){let r;switch(t.EmitterMode.Random===e?i=b():t.EmitterMode.Burst===e&&n.isBursting&&(i=n.burstParticleIndex/n.burstParticleCount),r=s>0?Math.floor(i/s)*s:i,e){case t.EmitterMode.Loop:r%=1;break;case t.EmitterMode.PingPong:r=Math.abs(r%2-1)}return r}t.EmitterMode=void 0,(Si=t.EmitterMode||(t.EmitterMode={}))[Si.Random=0]="Random",Si[Si.Loop=1]="Loop",Si[Si.PingPong=2]="PingPong",Si[Si.Burst=3]="Burst";class Mi{constructor(t,e,i){this.position=t??new K,this.rotation=e??new H,this.scale=i??new K(1,1,1)}apply(t){t.position.multiply(this.scale).applyQuaternion(this.rotation).add(this.position);const e=t.velocity,i=e.length();if(0===i)return;e.multiply(this.scale).applyQuaternion(this.rotation);const s=e.length();s>0&&e.multiplyScalar(i/s)}isIdentity(){const{position:t,rotation:e,scale:i}=this;return 0===t.x&&0===t.y&&0===t.z&&0===e.x&&0===e.y&&0===e.z&&1===e.w&&1===i.x&&1===i.y&&1===i.z}toJSON(){const t={},{position:e,rotation:i,scale:s}=this;return 0===e.x&&0===e.y&&0===e.z||(t.position=[e.x,e.y,e.z]),0===i.x&&0===i.y&&0===i.z&&1===i.w||(t.rotation=[i.x,i.y,i.z,i.w]),1===s.x&&1===s.y&&1===s.z||(t.scale=[s.x,s.y,s.z]),t}static fromJSON(t){if(!t)return;const{position:e,rotation:i,scale:s}=t;return new Mi(e?new K(e[0],e[1],e[2]):void 0,i?new H(i[0],i[1],i[2],i[3]):void 0,s?new K(s[0],s[1],s[2]):void 0)}static toShapeJSON(t){return t&&!t.isIdentity()?{transform:t.toJSON()}:{}}clone(){return new Mi(this.position.clone(),this.rotation.clone(),this.scale.clone())}}class zi{constructor(e={}){this.type="circle",this.currentValue=0,this.radius=e.radius??10,this.arc=e.arc??2*Math.PI,this.thickness=e.thickness??1,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Ct(1),this.memory=[],this.transform=e.transform}update(t,e){this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e),s=Z.lerp(1-this.thickness,1,b()),n=i*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(this.radius*s),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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new zi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?Et(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new zi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class _i{constructor(e={}){this.type="cone",this.currentValue=0,this.radius=e.radius??10,this.arc=e.arc??2*Math.PI,this.thickness=e.thickness??1,this.angle=e.angle??Math.PI/6,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Ct(1),this.memory=[],this.transform=e.transform}update(e,i){t.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,e.emissionState.time/e.duration)*i)}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e),s=Z.lerp(1-this.thickness,1,b()),n=i*this.arc,r=Math.sqrt(s),o=Math.sin(n),a=Math.cos(n);t.position.x=r*a,t.position.y=r*o,t.position.z=0;const l=this.angle*r;t.velocity.set(0,0,Math.cos(l)).addScaledVector(t.position,Math.sin(l)).multiplyScalar(t.startSpeed),t.position.multiplyScalar(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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new _i({radius:t.radius,arc:t.arc,thickness:t.thickness,angle:t.angle,mode:t.mode,speed:t.speed?Et(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new _i({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 Pi{constructor(e={}){this.type="donut",this.currentValue=0,this.radius=e.radius??10,this.arc=e.arc??2*Math.PI,this.thickness=e.thickness??1,this.donutRadius=e.donutRadius??.2*this.radius,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Ct(1),this.memory=[],this.transform=e.transform,this._m1=new nt}update(e,i){t.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,e.emissionState.time/e.duration)*i)}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e),s=b(),n=Z.lerp(1-this.thickness,1,b()),r=i*this.arc,o=s*Math.PI*2,a=Math.sin(r),l=Math.cos(r);if(t.position.x=this.radius*l,t.position.y=this.radius*a,t.position.z=0,t.velocity.z=this.donutRadius*n*Math.sin(o),t.velocity.x=this.donutRadius*n*Math.cos(o)*l,t.velocity.y=this.donutRadius*n*Math.cos(o)*a,t.position.add(t.velocity),t.velocity.normalize().multiplyScalar(t.startSpeed),t.rotation instanceof H){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(de,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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Pi({radius:t.radius,arc:t.arc,thickness:t.thickness,donutRadius:t.donutRadius,mode:t.mode,speed:t.speed?Et(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new Pi({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 Ti{constructor(e={}){this.type="edge",this.currentValue=0,this.radius=e.radius??1,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Ct(1),this.memory=[]}update(e,i){t.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,e.emissionState.time/e.duration)*i)}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e);t.position.set((2*i-1)*this.radius,0,0),t.velocity.set(0,t.startSpeed,0)}toJSON(){return{type:"edge",radius:this.radius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new Ti({radius:t.radius,mode:t.mode,speed:t.speed?Et(t.speed):void 0,spread:t.spread})}clone(){return new Ti({radius:this.radius,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}class Oi{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=Math.floor(b()*this.row),i=Math.floor(b()*this.column);t.position.x=i*this.width/this.column-this.width/2,t.position.y=e*this.height/this.row-this.height/2,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,...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Oi({...t,transform:Mi.fromJSON(t.transform)})}clone(){return new Oi({width:this.width,height:this.height,column:this.column,row:this.row,transform:this.transform?.clone()})}update(t,e){}}class Vi{constructor(e={}){this.type="hemisphere",this.currentValue=0,this.radius=e.radius??10,this.arc=e.arc??2*Math.PI,this.thickness=e.thickness??1,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Ct(1),this.memory=[],this.transform=e.transform,this._m1=new nt}update(e,i){t.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,e.emissionState.time/e.duration)*i)}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e),s=b(),n=Z.lerp(1-this.thickness,1,b()),r=i*this.arc,o=Math.acos(s),a=Math.sin(r),l=Math.cos(r),h=Math.sin(o),c=Math.cos(o);if(t.position.x=h*l,t.position.y=h*a,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius*n),t.rotation instanceof H){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(de,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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Vi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?Et(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new Vi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Bi{constructor(t){this.type="point",this._m1=new nt,this.transform=t}update(t,e){}initialize(t){const e=b(),i=b(),s=e*Math.PI*2,n=Math.acos(2*i-1),r=Math.cbrt(b()),o=Math.sin(s),a=Math.cos(s),l=Math.sin(n),h=Math.cos(n);if(t.velocity.x=r*l*a,t.velocity.y=r*l*o,t.velocity.z=r*h,t.velocity.multiplyScalar(t.startSpeed),t.position.setScalar(0),t.rotation instanceof H){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(de,t.velocity,ue),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"point",...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Bi(Mi.fromJSON(t?.transform))}clone(){return new Bi(this.transform?.clone())}}class Ci{constructor(e={}){this.type="sphere",this.currentValue=0,this.radius=e.radius??10,this.arc=e.arc??2*Math.PI,this.thickness=e.thickness??1,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Ct(1),this.memory=[],this.transform=e.transform,this._m1=new nt}update(e,i){t.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,e.emissionState.time/e.duration)*i)}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e),s=b(),n=Z.lerp(1-this.thickness,1,b()),r=i*this.arc,o=Math.acos(2*s-1),a=Math.sin(r),l=Math.cos(r),h=Math.sin(o),c=Math.cos(o);if(t.position.x=h*l,t.position.y=h*a,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius*n),t.rotation instanceof H){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(de,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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Ci({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?Et(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new Ci({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Ai{constructor(e={}){this.type="rectangle",this.currentValue=0,this.width=e.width??10,this.height=e.height??10,this.thickness=e.thickness??1,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Ct(1),this.memory=[],this.transform=e.transform,this._m1=new nt}update(t,e){this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e);b();const s=i*(2*(this.width+this.height));let n,r;s<this.width?(n=s-this.width/2,r=-this.height/2):s<this.width+this.height?(n=this.width/2,r=s-this.width-this.height/2):s<2*this.width+this.height?(n=this.width/2-(s-this.width-this.height),r=this.height/2):(n=-this.width/2,r=this.height/2-(s-2*this.width-this.height));const o=b(),a=1-this.thickness*o;if(t.position.x=n*a,t.position.y=r*a,t.position.z=0,t.velocity.x=n,t.velocity.y=r,t.velocity.z=0,t.velocity.normalize().multiplyScalar(t.startSpeed),t.rotation instanceof H){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(de,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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Ai({width:t.width,height:t.height,thickness:t.thickness,mode:t.mode,speed:t.speed?Et(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new Ai({width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}const Fi={box:{type:"box",params:[["width",["number"]],["height",["number"]],["depth",["number"]],["emitFrom",["number"]],["boxThickness",["vec3"]]],constructor:bi,loadJSON:bi.fromJSON},circle:{type:"circle",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:zi,loadJSON:zi.fromJSON},cone:{type:"cone",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:_i,loadJSON:_i.fromJSON},donut:{type:"donut",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["donutRadius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Pi,loadJSON:Pi.fromJSON},edge:{type:"edge",params:[["radius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Ti,loadJSON:Ti.fromJSON},point:{type:"point",params:[],constructor:Bi,loadJSON:Bi.fromJSON},sphere:{type:"sphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Ci,loadJSON:Ci.fromJSON},hemisphere:{type:"hemisphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Vi,loadJSON:Vi.fromJSON},grid:{type:"grid",params:[["width",["number"]],["height",["number"]],["rows",["number"]],["column",["number"]]],constructor:Oi,loadJSON:Oi.fromJSON},rectangle:{type:"rectangle",params:[["width",["number"]],["height",["number"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Ai,loadJSON:Ai.fromJSON}};function $i(t,e){return Fi[t.type].loadJSON(t,e)}const Ii=[];function Ei(t){if(!Ii.find(e=>e.id===t.id)){t.initialize();for(const e of t.emitterShapes)Fi[e.type]||(Fi[e.type]=e);for(const e of t.behaviors)ni[e.type]||(ni[e.type]=e)}}class Ni{get mesh(){return this._mesh}set mesh(t){if(this._mesh=t,!t)return;const i=t.getVerticesData(e.VertexBuffer.PositionKind),s=t.getIndices();if(!i||!s)return;this._positions=new Float32Array(i),this._indices=new Int32Array(s),this._triangleIndexToArea.length=0;let n=0;const r=s.length/3;this._triangleIndexToArea.push(0);const o=new K,a=new K,l=new K;for(let t=0;t<r;t++){const e=s[3*t],r=s[3*t+1],h=s[3*t+2];o.set(i[3*e],i[3*e+1],i[3*e+2]),a.set(i[3*r],i[3*r+1],i[3*r+2]),l.set(i[3*h],i[3*h+1],i[3*h+2]),a.sub(o),l.sub(o);const c=new K;c.crossVectors(a,l),n+=.5*c.length(),this._triangleIndexToArea.push(n)}}constructor(t,e,i){this.type="mesh_surface",this._triangleIndexToArea=[],this._meshReferenceId=e,this.transform=i,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 i=0,s=e;const n=b()*this._triangleIndexToArea[e];for(;i+1<s;){const t=Math.floor((i+s)/2);n<this._triangleIndexToArea[t]?s=t:i=t}let r=b(),o=b();r+o>1&&(r=1-r,o=1-o);const a=this._indices[3*i],l=this._indices[3*i+1],h=this._indices[3*i+2],c=this._positions[3*a],u=this._positions[3*a+1],d=this._positions[3*a+2],f=this._positions[3*l]-c,m=this._positions[3*l+1]-u,p=this._positions[3*l+2]-d,y=this._positions[3*h]-c,g=this._positions[3*h+1]-u,v=this._positions[3*h+2]-d;t.position.set(c+f*r+y*o,u+m*r+g*o,d+p*r+v*o);const x=m*v-p*g,S=p*y-f*v,w=f*g-m*y,M=Math.sqrt(x*x+S*S+w*w)||1;t.velocity.set(x/M,S/M,w/M).multiplyScalar(t.startSpeed),this.transform?.apply(t)}toJSON(){return{type:"mesh_surface",mesh:this._mesh?this._mesh.uniqueId?.toString():this._meshReferenceId??"",...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Ni(void 0,t?.mesh,Mi.fromJSON(t?.transform))}clone(){return new Ni(this._mesh,this._meshReferenceId,this.transform?.clone())}update(t,e){}}const Li={id:"babylon.quarks",initialize:()=>{},emitterShapes:[{type:"mesh_surface",params:[["mesh",["mesh"]]],constructor:Ni,loadJSON:t=>Ni.fromJSON(t)}],behaviors:[]};const Ri={};let Di=!1;function Ui(){Di||(Ri.tile_pars_vertex="\n#ifdef UV_TILE\n attribute float uvTile;\n uniform vec2 tileCount;\n\n mat3 makeTileTransform(float tileIndex) {\n float col = mod(tileIndex, tileCount.x);\n float row = (tileCount.y - floor(tileIndex / tileCount.x) - 1.0);\n return mat3(\n 1.0 / tileCount.x, 0.0, 0.0,\n 0.0, 1.0 / tileCount.y, 0.0,\n col / tileCount.x, row / tileCount.y, 1.0\n );\n }\n#else\n mat3 makeTileTransform(float tileIndex) {\n return mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);\n }\n#endif\n\n#if defined(USE_UV)\n varying vec2 vUv;\n #ifdef TILE_BLEND\n varying vec2 vUvNext;\n varying float vUvBlend;\n #endif\n#endif\n",Ri.tile_vertex="\n#ifdef UV_TILE\n mat3 tileTransform = makeTileTransform(floor(uvTile));\n #ifdef TILE_BLEND\n mat3 nextTileTransform = makeTileTransform(ceil(uvTile));\n vUvBlend = fract(uvTile);\n #endif\n#else\n mat3 tileTransform = makeTileTransform(0.0);\n#endif\n\n#if defined(USE_UV)\n vUv = (tileTransform * vec3(uv, 1.0)).xy;\n #if defined(TILE_BLEND) && defined(UV_TILE)\n vUvNext = (nextTileTransform * vec3(uv, 1.0)).xy;\n #endif\n#endif\n",Ri.tile_pars_fragment="\n#if defined(USE_UV)\n varying vec2 vUv;\n #ifdef TILE_BLEND\n varying vec2 vUvNext;\n varying float vUvBlend;\n #endif\n#endif\n",Ri.tile_fragment="\n#ifdef USE_MAP\n vec4 texelColor = texture2D(map, vUv);\n #ifdef TILE_BLEND\n texelColor = mix(texelColor, texture2D(map, vUvNext), vUvBlend);\n #endif\n diffuseColor *= texelColor;\n#endif\n",Ri.soft_pars_vertex="\n#ifdef SOFT_PARTICLES\n varying vec4 projPosition;\n varying float linearDepth;\n#endif\n",Ri.soft_vertex="\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n linearDepth = -mvPosition.z;\n#endif\n",Ri.soft_pars_fragment="\n#ifdef SOFT_PARTICLES\n uniform sampler2D depthTexture;\n uniform vec4 projParams;\n uniform vec2 softParams;\n\n varying vec4 projPosition;\n varying float linearDepth;\n\n #define SOFT_NEAR_FADE softParams.x\n #define SOFT_INV_FADE_DISTANCE softParams.y\n\n #define zNear projParams.x\n #define zFar projParams.y\n\n float linearize_depth(float d) {\n return (zFar * zNear) / (zFar - d * (zFar - zNear));\n }\n#endif\n",Ri.soft_fragment="\n#ifdef SOFT_PARTICLES\n\n vec2 p2 = projPosition.xy / projPosition.w;\n p2 = 0.5 * p2 + 0.5;\n\n float readDepth = texture2D(depthTexture, p2.xy).r;\n float viewDepth = linearize_depth(readDepth);\n float softParticlesFade = saturate(SOFT_INV_FADE_DISTANCE * ((viewDepth - SOFT_NEAR_FADE) - linearDepth));\n\n gl_FragColor *= softParticlesFade;\n#endif\n",Di=!0)}const qi="\n#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n";function ki(t){return`\n#ifdef FOG\n vFogDistance = ${t};\n#endif\n`}const Ji="\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 fogCoeff = (fogEnd - fogDistance) / (fogEnd - fogStart);\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 Qi(t){return`\n#ifdef FOG\n {\n float fogFactor = quarksFogFactor();\n#ifdef FOG_ADDITIVE\n ${t} *= fogFactor;\n#else\n ${t} = mix(vFogColor, ${t}, fogFactor);\n#endif\n }\n#endif\n`}const Gi="\n#ifdef FOG\nvarying vFogDistance: vec3f;\n#endif\n";function Wi(t){return`\n#ifdef FOG\n vertexOutputs.vFogDistance = ${t};\n#endif\n`}const ji="\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 fogCoeff = (fogEnd - fogDistance) / (fogEnd - fogStart);\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#ifdef FOG_ADDITIVE\n return rgb * fogFactor;\n#else\n return mix(uniforms.vFogColor, rgb, fogFactor);\n#endif\n}\n#endif\n";function Yi(t){return`\n#ifdef FOG\n ${t} = vec4f(quarksFog(${t}.rgb, fragmentInputs.vFogDistance), ${t}.a);\n#endif\n`}var Xi=`\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\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvarying vec3 vNormal;\nvarying vec3 vWorldPos;\n\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\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${qi}\nvoid main() {\n vec3 scaledPosition = position * size;\n vec3 rotatedPosition = applyQuaternion(scaledPosition, rotation);\n vec3 rotatedNormal = normalize(applyQuaternion(normal, rotation));\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${ki("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 linearDepth = -viewPos.z;\n#endif\n\n#ifdef UV_TILE\n vec2 tc = vec2(tileCountX, tileCountY);\n float baseTile = floor(uvTile);\n float tileU = mod(baseTile, tc.x) / tc.x;\n float tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV = uv / tc + vec2(tileU, tileV);\n #ifdef TILE_BLEND\n float nextTile = ceil(uvTile);\n float nextU = mod(nextTile, tc.x) / tc.x;\n float nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV2 = uv / tc + vec2(nextU, nextV);\n vTileBlend = fract(uvTile);\n #endif\n#else\n vUV = uv;\n#endif\n\n vColor = color;\n}\n`;const Zi="\n#ifdef UV_SCROLL\nuniform vec2 uvScrollOffset;\n#endif\n#ifdef GRADIENT_MAP\nuniform sampler2D gradientMap;\nuniform vec2 gradientMapRange;\n#endif\n#ifdef EROSION\nuniform vec4 erosionParams;\nuniform vec3 erosionEdgeColor;\n#ifdef EROSION_MASK\nuniform sampler2D erosionMask;\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 Hi(t){return`\n vec4 baseColor = vColor;\n#ifdef UV_SCROLL\n vec2 mapUV = vUV + uvScrollOffset;\n#else\n vec2 mapUV = vUV;\n#endif\n#ifdef EROSION\n float erosionLevel = baseColor.a;\n baseColor.a = 1.0;\n float erosionMaskValue = 1.0;\n#endif\n#ifdef USE_MAP\n vec4 texColor = texture2D(map, mapUV);\n ${t?"#ifdef TILE_BLEND\n #ifdef UV_SCROLL\n vec4 texColor2 = texture2D(map, vUV2 + uvScrollOffset);\n #else\n vec4 texColor2 = texture2D(map, vUV2);\n #endif\n texColor = mix(texColor, texColor2, vTileBlend);\n #endif":""}\n #ifdef GRADIENT_MAP\n vec4 ramp = texture2D(gradientMap, vec2(mix(gradientMapRange.x, gradientMapRange.y, clamp(texColor.r, 0.0, 1.0)), 0.5));\n texColor = vec4(ramp.rgb, ramp.a * texColor.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 erosionMaskValue = texture2D(erosionMask, vUV + erosionParams.zw).r;\n #endif\n baseColor = quarksErode(baseColor, erosionLevel, erosionMaskValue);\n#endif\n`}const Ki="\n#ifdef UV_SCROLL\nuniform uvScrollOffset: vec2f;\n#endif\n#ifdef GRADIENT_MAP\nvar gradientMapSampler: sampler;\nvar gradientMap: texture_2d<f32>;\nuniform gradientMapRange: vec2f;\n#endif\n#ifdef EROSION\nuniform erosionParams: vec4f;\nuniform erosionEdgeColor: vec3f;\n#ifdef EROSION_MASK\nvar erosionMaskSampler: sampler;\nvar erosionMask: texture_2d<f32>;\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 ts(t){return`\n var baseColor = fragmentInputs.vColor;\n#ifdef UV_SCROLL\n let mapUV = fragmentInputs.vUV + uniforms.uvScrollOffset;\n#else\n let mapUV = fragmentInputs.vUV;\n#endif\n#ifdef EROSION\n let erosionLevel = baseColor.a;\n baseColor.a = 1.0;\n var erosionMaskValue = 1.0;\n#endif\n#ifdef USE_MAP\n var texColor = textureSample(map, mapSampler, mapUV);\n ${t?"#ifdef TILE_BLEND\n #ifdef UV_SCROLL\n let texColor2 = textureSample(map, mapSampler, fragmentInputs.vUV2 + uniforms.uvScrollOffset);\n #else\n let texColor2 = textureSample(map, mapSampler, fragmentInputs.vUV2);\n #endif\n texColor = mix(texColor, texColor2, fragmentInputs.vTileBlend);\n #endif":""}\n #ifdef GRADIENT_MAP\n let ramp = textureSample(gradientMap, gradientMapSampler, vec2f(mix(uniforms.gradientMapRange.x, uniforms.gradientMapRange.y, clamp(texColor.r, 0.0, 1.0)), 0.5));\n texColor = vec4f(ramp.rgb, ramp.a * texColor.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 erosionMaskValue = textureSample(erosionMask, erosionMaskSampler, fragmentInputs.vUV + uniforms.erosionParams.zw).r;\n #endif\n baseColor = quarksErode(baseColor, erosionLevel, erosionMaskValue);\n#endif\n`}var es=`\nvarying vec2 vUV;\nvarying vec4 vColor;\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#ifdef SOFT_PARTICLES\nuniform sampler2D depthTexture;\nuniform vec2 softParams;\nuniform vec4 projParams;\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${Ji}\n${Zi}\nvoid main() {\n${Hi(!0)}\n#ifdef USE_COLOR_AS_ALPHA\n baseColor.a *= (baseColor.r + baseColor.g + baseColor.b) / 3.0;\n#endif\n\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${Qi("baseColor.rgb")}\n gl_FragColor = baseColor;\n\n#ifdef SOFT_PARTICLES\n vec2 p2 = projPosition.xy / projPosition.w;\n p2 = 0.5 * p2 + 0.5;\n float readDepth = texture2D(depthTexture, p2.xy).r;\n float zNear = projParams.x;\n float zFar = projParams.y;\n float viewDepth = (zFar * zNear) / (zFar - readDepth * (zFar - zNear));\n float fade = clamp(softParams.y * ((viewDepth - softParams.x) - linearDepth), 0.0, 1.0);\n gl_FragColor *= fade;\n#endif\n}\n`,is=`\nvarying vec2 vUV;\nvarying vec4 vColor;\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#ifdef SOFT_PARTICLES\nuniform sampler2D depthTexture;\nuniform vec2 softParams;\nuniform vec4 projParams;\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${Ji}\n${Zi}\nvoid main() {\n${Hi(!0)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n vec3 N = normalize(vNormal);\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 rim = pow(1.0 - abs(dot(N, V)), rimParams.x) * rimParams.y;\n #ifdef MESH_RIM_MIX\n color = mix(color, rimColor, clamp(rim, 0.0, 1.0));\n #else\n color += rimColor * rim;\n #endif\n#endif\n\n${Qi("color")}\n gl_FragColor = vec4(color, baseColor.a);\n\n#ifdef SOFT_PARTICLES\n vec2 p2 = projPosition.xy / projPosition.w;\n p2 = 0.5 * p2 + 0.5;\n float readDepth = texture2D(depthTexture, p2.xy).r;\n float zNear = projParams.x;\n float zFar = projParams.y;\n float viewDepth = (zFar * zNear) / (zFar - readDepth * (zFar - zNear));\n float fade = clamp(softParams.y * ((viewDepth - softParams.x) - linearDepth), 0.0, 1.0);\n gl_FragColor *= fade;\n#endif\n}\n`,ss=`\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;\nuniform mat4 worldViewProjection;\n\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\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 TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\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${qi}\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${ki("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n linearDepth = -mvPosition.z;\n#endif\n\n #ifdef UV_TILE\n vec2 tc = vec2(tileCountX, tileCountY);\n float baseTile = floor(uvTile);\n float tileU = mod(baseTile, tc.x) / tc.x;\n float tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV = uv / tc + vec2(tileU, tileV);\n #ifdef TILE_BLEND\n float nextTile = ceil(uvTile);\n float nextU = mod(nextTile, tc.x) / tc.x;\n float nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV2 = uv / tc + vec2(nextU, nextV);\n vTileBlend = fract(uvTile);\n #endif\n #else\n vUV = uv;\n #endif\n\n vColor = color;\n}\n`,ns=`\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;\nuniform float speedFactor;\n\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\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 TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\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${qi}\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#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 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. speedFactor 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#ifdef BEAM\n // Seen straight along its length a beam 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#else\n vec3 side = normalize(cross(mvPosition.xyz, vdir));\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${ki("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 linearDepth = -mvPosition.z;\n#endif\n\n #ifdef UV_TILE\n vec2 tc = vec2(tileCountX, tileCountY);\n float baseTile = floor(uvTile);\n float tileU = mod(baseTile, tc.x) / tc.x;\n float tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV = quadUV / tc + vec2(tileU, tileV);\n #ifdef TILE_BLEND\n float nextTile = ceil(uvTile);\n float nextU = mod(nextTile, tc.x) / tc.x;\n float nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV2 = quadUV / tc + vec2(nextU, nextV);\n vTileBlend = fract(uvTile);\n #endif\n #else\n vUV = quadUV;\n #endif\n\n vColor = color;\n}\n`,rs=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n${Ji}\n${Zi}\nvoid main() {\n${Hi(!1)}\n if (baseColor.a < 0.01) discard;\n\n${Qi("baseColor.rgb")}\n gl_FragColor = baseColor;\n}\n`,os=`\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;\nuniform float lineWidth;\nuniform vec2 resolution;\nuniform float sizeAttenuation;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n\nvec2 fix(vec4 i, float aspect) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n}\n\n${qi}\nvoid main() {\n float aspect = resolution.x / resolution.y;\n vec4 finalPosition = projection * view * vec4(position, 1.0);\n vec4 prevPos = projection * view * vec4(previous, 1.0);\n vec4 nextPos = projection * view * vec4(next, 1.0);\n\n vec2 currentP = fix(finalPosition, aspect);\n vec2 prevP = fix(prevPos, aspect);\n vec2 nextP = fix(nextPos, aspect);\n\n float w = lineWidth * width;\n vec2 dir;\n if (distance(nextP, currentP) < 0.0001) {\n dir = normalize(currentP - prevP);\n } else if (distance(prevP, currentP) < 0.0001) {\n dir = normalize(nextP - currentP);\n } else {\n vec2 dir1 = normalize(currentP - prevP);\n vec2 dir2 = normalize(nextP - currentP);\n dir = normalize(dir1 + dir2);\n }\n vec4 normal = vec4(-dir.y, dir.x, 0.0, 1.0);\n normal.xy *= 0.5 * w;\n normal *= projection;\n if (sizeAttenuation == 0.0) {\n normal.xy *= finalPosition.w;\n normal.xy /= (vec4(resolution, 0.0, 1.0) * projection).xy;\n }\n finalPosition.xy += normal.xy * side;\n gl_Position = finalPosition;\n${ki("(view * vec4(position, 1.0)).xyz")}\n vUV = uv;\n vColor = color;\n}\n`;const as=2048,ls=2047;class hs{constructor(t){this.counts=new Uint32Array(as),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 i=this.uintView[0];return e?~i>>>0:i}}var cs=`\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\n#ifdef UV_TILE\nuniform tileCountX: f32;\nuniform tileCountY: f32;\n#endif\n\nvarying vUV: vec2f;\nvarying vColor: vec4f;\nvarying vNormal: vec3f;\nvarying vWorldPos: vec3f;\n\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\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${Gi}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let scaledPosition = vertexInputs.position * vertexInputs.size;\n let rotatedPosition = applyQuaternion(scaledPosition, vertexInputs.rotation);\n let rotatedNormal = normalize(applyQuaternion(vertexInputs.normal, vertexInputs.rotation));\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${Wi("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 vertexOutputs.linearDepth = -viewPos.z;\n#endif\n\n#ifdef UV_TILE\n let tc = vec2f(uniforms.tileCountX, uniforms.tileCountY);\n let baseTile = floor(vertexInputs.uvTile);\n let tileU = (baseTile % tc.x) / tc.x;\n let tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV = vertexInputs.uv / tc + vec2f(tileU, tileV);\n #ifdef TILE_BLEND\n let nextTile = ceil(vertexInputs.uvTile);\n let nextU = (nextTile % tc.x) / tc.x;\n let nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV2 = vertexInputs.uv / tc + vec2f(nextU, nextV);\n vertexOutputs.vTileBlend = fract(vertexInputs.uvTile);\n #endif\n#else\n vertexOutputs.vUV = vertexInputs.uv;\n#endif\n\n vertexOutputs.vColor = vertexInputs.color;\n}\n`,us=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\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#ifdef SOFT_PARTICLES\nvar depthTextureSampler: sampler;\nvar depthTexture: texture_2d<f32>;\nuniform softParams: vec2f;\nuniform projParams: vec4f;\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${ji}\n${Ki}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${ts(!0)}\n#ifdef USE_COLOR_AS_ALPHA\n baseColor.a *= (baseColor.r + baseColor.g + baseColor.b) / 3.0;\n#endif\n\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n#ifdef SOFT_PARTICLES\n var p2 = fragmentInputs.projPosition.xy / fragmentInputs.projPosition.w;\n p2 = 0.5 * p2 + 0.5;\n let readDepth = textureSample(depthTexture, depthTextureSampler, p2).r;\n let zNear = uniforms.projParams.x;\n let zFar = uniforms.projParams.y;\n let viewDepth = (zFar * zNear) / (zFar - readDepth * (zFar - zNear));\n let fade = clamp(uniforms.softParams.y * ((viewDepth - uniforms.softParams.x) - fragmentInputs.linearDepth), 0.0, 1.0);\n baseColor *= fade;\n#endif\n\n${Yi("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,ds=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\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#ifdef SOFT_PARTICLES\nvar depthTextureSampler: sampler;\nvar depthTexture: texture_2d<f32>;\nuniform softParams: vec2f;\nuniform projParams: vec4f;\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${ji}\n${Ki}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${ts(!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 let N = normalize(fragmentInputs.vNormal);\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 rimTerm = pow(1.0 - abs(dot(N, V)), uniforms.rimParams.x) * uniforms.rimParams.y;\n #ifdef MESH_RIM_MIX\n color = mix(color, uniforms.rimColor, clamp(rimTerm, 0.0, 1.0));\n #else\n color += uniforms.rimColor * rimTerm;\n #endif\n#endif\n\n var finalColor = vec4f(color, baseColor.a);\n\n#ifdef SOFT_PARTICLES\n var p2 = fragmentInputs.projPosition.xy / fragmentInputs.projPosition.w;\n p2 = 0.5 * p2 + 0.5;\n let readDepth = textureSample(depthTexture, depthTextureSampler, p2).r;\n let zNear = uniforms.projParams.x;\n let zFar = uniforms.projParams.y;\n let viewDepth = (zFar * zNear) / (zFar - readDepth * (zFar - zNear));\n let fade = clamp(uniforms.softParams.y * ((viewDepth - uniforms.softParams.x) - fragmentInputs.linearDepth), 0.0, 1.0);\n finalColor *= fade;\n#endif\n\n${Yi("finalColor")}\n fragmentOutputs.color = finalColor;\n}\n`,fs=`\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\n#ifdef UV_TILE\nuniform tileCountX: f32;\nuniform tileCountY: f32;\n#endif\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 TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\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${Gi}\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${Wi("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n vertexOutputs.linearDepth = -mvPosition.z;\n#endif\n\n #ifdef UV_TILE\n let tc = vec2f(uniforms.tileCountX, uniforms.tileCountY);\n let baseTile = floor(vertexInputs.uvTile);\n let tileU = (baseTile % tc.x) / tc.x;\n let tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV = vertexInputs.uv / tc + vec2f(tileU, tileV);\n #ifdef TILE_BLEND\n let nextTile = ceil(vertexInputs.uvTile);\n let nextU = (nextTile % tc.x) / tc.x;\n let nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV2 = vertexInputs.uv / tc + vec2f(nextU, nextV);\n vertexOutputs.vTileBlend = fract(vertexInputs.uvTile);\n #endif\n #else\n vertexOutputs.vUV = vertexInputs.uv;\n #endif\n\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;function ms(t){return t.isWebGPU?f.ShaderLanguage.WGSL:f.ShaderLanguage.GLSL}function ps(t,e,i,s){if(s===f.ShaderLanguage.WGSL)return u.ShaderStore.ShadersStoreWGSL[t+"VertexShader"]=e.wgsl,void(u.ShaderStore.ShadersStoreWGSL[t+"FragmentShader"]=i.wgsl);d.Effect.ShadersStore[t+"VertexShader"]=e.glsl,d.Effect.ShadersStore[t+"FragmentShader"]=i.glsl}var ys,gs=`\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;\nuniform speedFactor: f32;\n\n#ifdef UV_TILE\nuniform tileCountX: f32;\nuniform tileCountY: f32;\n#endif\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 TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\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${Gi}\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#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 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. speedFactor 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#ifdef BEAM\n // Seen straight along its length a beam 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#else\n let side = normalize(cross(mvPosition.xyz, vdir));\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${Wi("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 vertexOutputs.linearDepth = -mvPosition.z;\n#endif\n\n #ifdef UV_TILE\n let tc = vec2f(uniforms.tileCountX, uniforms.tileCountY);\n let baseTile = floor(vertexInputs.uvTile);\n let tileU = (baseTile % tc.x) / tc.x;\n let tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV = quadUV / tc + vec2f(tileU, tileV);\n #ifdef TILE_BLEND\n let nextTile = ceil(vertexInputs.uvTile);\n let nextU = (nextTile % tc.x) / tc.x;\n let nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV2 = quadUV / tc + vec2f(nextU, nextV);\n vertexOutputs.vTileBlend = fract(vertexInputs.uvTile);\n #endif\n #else\n vertexOutputs.vUV = quadUV;\n #endif\n\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;function vs(){return{direction:new l.Vector3(.4,-1,.6),color:new p.Color3(1,1,1),ambient:new p.Color3(.35,.35,.35)}}function xs(t){if(!t||"object"!=typeof t)return;const e=Array.isArray(t.color)?t.color:[1,1,1],i=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e;return{color:[i(e[0],1),i(e[1],1),i(e[2],1)],power:Math.max(.01,i(t.power,2)),strength:Math.max(0,i(t.strength,1)),mode:"mix"===t.mode?"mix":"add"}}function Ss(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])}function bs(t){if(!t||"object"!=typeof t)return;const e=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e,i=Array.isArray(t.edgeColor)?t.edgeColor:[1,1,1],s=Array.isArray(t.maskScroll)?t.maskScroll:[0,0];return{mask:t.mask??null,softness:Math.max(1e-4,e(t.softness,.05)),edgeWidth:Math.max(0,e(t.edgeWidth,0)),edgeColor:[e(i[0],1),e(i[1],1),e(i[2],1)],maskScroll:[e(s[0],0),e(s[1],0)]}}function ws(t,e){return t===e||!(!t||!e)&&(t.mask===e.mask&&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]&&t.maskScroll[0]===e.maskScroll[0]&&t.maskScroll[1]===e.maskScroll[1])}function Ms(t){if(!t||"object"!=typeof t)return;const e=Number.isFinite(t[0])?t[0]:0,i=Number.isFinite(t[1])?t[1]:0;return 0===e&&0===i?void 0:[e,i]}function zs(t,e){return t===e||!!t&&!!e&&t[0]===e[0]&&t[1]===e[1]}t.RenderMode=void 0,(ys=t.RenderMode||(t.RenderMode={}))[ys.BillBoard=0]="BillBoard",ys[ys.StretchedBillBoard=1]="StretchedBillBoard",ys[ys.Mesh=2]="Mesh",ys[ys.Trail=3]="Trail",ys[ys.HorizontalBillBoard=4]="HorizontalBillBoard",ys[ys.VerticalBillBoard=5]="VerticalBillBoard",ys[ys.Beam=6]="Beam";class _s{constructor(t,e){this.visibleSystems=[],this.boundsMin_=new K,this.boundsMax_=new K,this.time=0,this.scene=e,this.maxParticles=1e3,this.systems=new Set,this.settings={instancingGeometry:t.instancingGeometry,instancingIndices:t.instancingIndices,instancingUVs:t.instancingUVs,instancingNormals:t.instancingNormals,renderMode:t.renderMode,renderOrder:t.renderOrder,uTileCount:t.uTileCount,vTileCount:t.vTileCount,blendTiles:t.blendTiles,softParticles:t.softParticles,softNearFade:t.softNearFade,softFarFade:t.softFarFade,materialBlendMode:t.materialBlendMode,materialTransparent:t.materialTransparent,materialDepthTest:t.materialDepthTest,materialDepthWrite:t.materialDepthWrite,materialAlphaTest:t.materialAlphaTest,texture:t.texture,reflectionTexture:t.reflectionTexture??null,reflectionLevel:t.reflectionLevel??1,reflectionFaces:t.reflectionFaces??null,reflectionAtlas:t.reflectionAtlas??null,pivot:t.pivot?.clone(),sortMode:t.sortMode??"none",minParticleSize:t.minParticleSize??0,maxParticleSize:t.maxParticleSize??1/0,layerMask:t.layerMask,renderingGroupId:t.renderingGroupId??0,applyFog:t.applyFog??!0,lighting:t.lighting,rim:xs(t.rim),uvScroll:Ms(t.uvScroll),gradientMap:t.gradientMap??null,erosion:bs(t.erosion)},this.mesh=new h.Mesh("vfxBatch",e),this.configureMesh()}configureMesh(){const t=this.mesh;t.alwaysSelectAsActiveMesh=!0,t.doNotSyncBoundingInfo=!0,t.setBoundingInfo(new m.BoundingInfo(l.Vector3.Zero(),l.Vector3.Zero())),t.layerMask=this.settings.layerMask,t.renderingGroupId=this.settings.renderingGroupId,t.alphaIndex=this.settings.renderOrder,t.applyFog=!1}refreshBoundingInfo(){const t=this.boundsMin_,e=this.boundsMax_;let i=1/0,s=1/0,n=1/0,r=-1/0,o=-1/0,a=-1/0,l=!1;const h=this.visibleSystems;for(let c=0;c<h.length;c++){const u=h[c];if(0!==u.particleNum&&"function"==typeof u.getWorldBounds){if(!u.getWorldBounds(t,e))return void(this.mesh.alwaysSelectAsActiveMesh=!0);l=!0,t.x<i&&(i=t.x),t.y<s&&(s=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(!l)return;const c=this.mesh.getBoundingInfo(),u=c.minimum,d=c.maximum;u.x===i&&u.y===s&&u.z===n&&d.x===r&&d.y===o&&d.z===a||(u.set(i,s,n),d.set(r,o,a),c.reConstruct(u,d)),this.mesh.alwaysSelectAsActiveMesh=!1}fogDefines(){if(!this.settings.applyFog)return[];return this.settings.materialTransparent&&(this.settings.materialBlendMode===r.Constants.ALPHA_ADD||this.settings.materialBlendMode===r.Constants.ALPHA_ONEONE)?["FOG","FOG_ADDITIVE"]:["FOG"]}bindFog(t){if(!this.settings.applyFog)return;const e=this.scene;t.onBindObservable.add(()=>{const i=t.getEffect();if(!i)return;const s=e.fogEnabled?e.fogMode:y.Scene.FOGMODE_NONE;i.setFloat4("vFogInfos",s,e.fogStart,e.fogEnd,e.fogDensity),i.setColor3("vFogColor",e.fogColor)})}surfaceDefines(){const t=[];this.settings.uvScroll&&t.push("UV_SCROLL"),this.settings.gradientMap&&t.push("GRADIENT_MAP");const e=this.settings.erosion;return e&&(t.push("EROSION"),e.mask&&t.push("EROSION_MASK")),t}surfaceUniforms(t,e){this.settings.uvScroll&&t.push("uvScrollOffset"),this.settings.gradientMap&&(e.push("gradientMap"),t.push("gradientMapRange"));const i=this.settings.erosion;i&&(t.push("erosionParams","erosionEdgeColor"),i.mask&&e.push("erosionMask"))}bindSurface(t){const{uvScroll:e,gradientMap:i,erosion:s}=this.settings;if(i&&t.setTexture("gradientMap",i),s&&(s.mask&&t.setTexture("erosionMask",s.mask),t.setVector3("erosionEdgeColor",new l.Vector3(s.edgeColor[0],s.edgeColor[1],s.edgeColor[2]))),!e&&!s&&!i)return;const n=t=>t-Math.floor(t),r=new l.Vector2,o=new l.Vector4,a=new l.Vector2(0,1),h=()=>{const l=this.time,h=t.getEffect();if(e&&(r.set(n(e[0]*l),n(e[1]*l)),t.setVector2("uvScrollOffset",r),h?.setVector2("uvScrollOffset",r)),s&&(o.set(s.softness,s.edgeWidth,n(s.maskScroll[0]*l),n(s.maskScroll[1]*l)),t.setVector4("erosionParams",o),h?.setVector4("erosionParams",o)),i){const e=i.getSize().width,s=e>0?.5/e:0;a.set(s,1-s),t.setVector2("gradientMapRange",a),h?.setVector2("gradientMapRange",a)}};h(),t.onBindObservable.add(h)}addSystem(t){this.systems.add(t)}removeSystem(t){this.systems.delete(t)}getVisibleSystems(){const t=this.visibleSystems;let e=0;for(const i of this.systems)i.emitter.visible&&!0!==i.culled&&(t[e++]=i);return t.length=e,t}applyDepthTexture(t){const e=this.mesh.material;e&&e instanceof o.ShaderMaterial&&e.setTexture("depthTexture",t)}applyMeshLighting(t){}dispose(){this.mesh.dispose()}}_s.FOG_UNIFORMS=["vFogInfos","vFogColor"];class Ps extends _s{static whiteTexture(t){let e=Ps.whiteTextureByScene.get(t);return e||(e=a.RawTexture.CreateRGBATexture(new Uint8Array([255,255,255,255]),1,1,t),e.name="quarksMeshWhite",Ps.whiteTextureByScene.set(t,e)),e}constructor(t,e){super(t,e),this.shaderMaterial=null,this.fixedLightDirection=new l.Vector3,this.fixedLightColor=new l.Vector3,this.fixedAmbientColor=new l.Vector3,this.gatherScratch=[],this.vector_=new K,this.vector2_=new K,this.vector3_=new K,this.quaternion_=new H,this.quaternion2_=new H,this.quaternion3_=new H,this.quaternion4_=new H,this.quaternion5_=new H,this.rotationMat_=new pt,this.rotationMat2_=new pt,this.lastStretchedSpeedFactor=Number.NaN,this.clearedInstanceUploaded=!1,this.beamEnd_=new K,this.storeFixedLighting(vs()),this.maxParticles=1e3,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh.dispose(),this.mesh=new h.Mesh("spriteBatch",this.scene),this.configureMesh();const t=new c.VertexData;t.positions=this.settings.instancingGeometry,t.indices=this.settings.instancingIndices;const e=this.settings.instancingGeometry.length/3,i=this.settings.instancingUVs;i&&i.length>=2*e?t.uvs=i:t.uvs=new Float32Array(2*e),this.settings.instancingNormals&&(t.normals=this.settings.instancingNormals),t.applyToMesh(this.mesh,!1),this.buildExpandableBuffers()}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 i=this.scene.getEngine();this.offsetBuffer=new Float32Array(3*this.maxParticles),this.offsetVB=new e.VertexBuffer(i,this.offsetBuffer,"offset",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.offsetVB),this.colorBuffer=new Float32Array(4*this.maxParticles),this.colorVB=new e.VertexBuffer(i,this.colorBuffer,"color",!0,!1,4,!0),this.mesh.setVerticesBuffer(this.colorVB),this.sizeBuffer=new Float32Array(3*this.maxParticles),this.sizeVB=new e.VertexBuffer(i,this.sizeBuffer,"size",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.sizeVB),this.uvTileBuffer=new Float32Array(this.maxParticles),this.uvTileVB=new e.VertexBuffer(i,this.uvTileBuffer,"uvTile",!0,!1,1,!0),this.mesh.setVerticesBuffer(this.uvTileVB),this.settings.renderMode===t.RenderMode.Mesh?(this.rotationBuffer=new Float32Array(4*this.maxParticles),this.rotationVB=new e.VertexBuffer(i,this.rotationBuffer,"rotation",!0,!1,4,!0)):(this.rotationBuffer=new Float32Array(this.maxParticles),this.rotationVB=new e.VertexBuffer(i,this.rotationBuffer,"rotation",!0,!1,1,!0)),this.mesh.setVerticesBuffer(this.rotationVB),Ps.drawsAlongVelocity(this.settings.renderMode)&&(this.velocityBuffer=new Float32Array(4*this.maxParticles),this.velocityVB=new e.VertexBuffer(i,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.disposeExpandableBuffers(),this.buildExpandableBuffers(),this.sortScratch=void 0,this.gatherScratch.length=0}sizeLimits(){const{minParticleSize:t,maxParticleSize:e}=this.settings;return Ps.takesPivotAndFlip(this.settings.renderMode)?t<=0&&e===1/0?null:new l.Vector2(Math.max(0,t),Math.min(e,1e9)):null}sortInstances(t,e,i){if(t<2)return;const s=this.sortScratch??(this.sortScratch=new hs(this.maxParticles));s.ensure(t);const n=s.keys,r=this.settings.sortMode;if("distance"===r){const e=this.scene.activeCameras?.[0]??this.scene.activeCamera;if(!e)return;const i=e.globalPosition,r=i.x,o=i.y,a=i.z,l=this.offsetBuffer;for(let e=0,i=0;e<t;e++,i+=3){const t=l[i]-r,h=l[i+1]-o,c=l[i+2]-a;n[e]=s.floatKey(t*t+h*h+c*c,!0)}}else{const e="youngestInFront"===r,i=this.visibleSystems;let o=0;for(let t=0;t<i.length;t++){const r=i[t],a=r.particleNum,l=r.store;if(0===a)continue;if(void 0===l){const t=r.particles;for(let i=0;i<a;i++)n[o++]=s.floatKey(t[i].age,e);continue}const h=l.scalars,c=ze.SCALAR_STRIDE;for(let t=0,i=ze.AGE;t<a;t++,i+=c)n[o++]=s.floatKey(h[i],e)}if(o!==t)return}const o=function(t,e){const i=t.keys,s=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){s.fill(0);for(let r=0;r<e;r++)s[i[n[r]]>>>t&ls]++;if(s[i[n[0]]>>>t&ls]===e)continue;let o=0;for(let t=0;t<as;t++){const e=s[t];s[t]=o,o+=e}for(let o=0;o<e;o++){const e=n[o];r[s[i[e]>>>t&ls]++]=e}const a=n;n=r,r=a}return n}(s,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),i&&this.velocityBuffer&&(this.velocityBuffer=this.gatherInto(5,this.velocityBuffer,o,t,4))}gatherInto(t,e,i,s,n){let r=this.gatherScratch[t];return void 0!==r&&r.length===e.length||(r=new Float32Array(e.length)),function(t,e,i,s,n){if(1===n)for(let n=0;n<s;n++)e[n]=t[i[n]];else if(3===n)for(let n=0,r=0;n<s;n++,r+=3){const s=3*i[n];e[r]=t[s],e[r+1]=t[s+1],e[r+2]=t[s+2]}else if(4===n)for(let n=0,r=0;n<s;n++,r+=4){const s=4*i[n];e[r]=t[s],e[r+1]=t[s+1],e[r+2]=t[s+2],e[r+3]=t[s+3]}else for(let r=0;r<s;r++){const s=i[r]*n,o=r*n;for(let i=0;i<n;i++)e[o+i]=t[s+i]}}(e,r,i,s,n),this.gatherScratch[t]=e,r}rebuildMaterial(){const e=`quarksParticle_${this.settings.renderMode}`;this.lastStretchedSpeedFactor=Number.NaN;const i=this.fogDefines();let s,n;this.settings.renderMode===t.RenderMode.Mesh?(s={glsl:Xi,wgsl:cs},n={glsl:is,wgsl:ds}):Ps.drawsAlongVelocity(this.settings.renderMode)?(s={glsl:ns,wgsl:gs},n={glsl:es,wgsl:us}):(s={glsl:ss,wgsl:fs},n={glsl:es,wgsl:us});const a=this.settings.texture??(this.settings.renderMode===t.RenderMode.Mesh?Ps.whiteTexture(this.scene):null);a&&i.push("USE_MAP");const h=this.settings.reflectionAtlas;if(this.settings.renderMode===t.RenderMode.Mesh&&!!h&&!h.isReady()&&h){const t=h.onLoadObservable;t?.addOnce(()=>{this.rebuildMaterial()})}const c=this.settings.renderMode===t.RenderMode.Mesh&&!!h&&h.isReady();c&&i.push("USE_ENVMAP_ATLAS"),(this.settings.uTileCount>1||this.settings.vTileCount>1)&&i.push("UV_TILE"),this.settings.blendTiles&&i.push("TILE_BLEND"),this.settings.softParticles&&i.push("SOFT_PARTICLES"),this.settings.materialAlphaTest>0&&i.push("USE_ALPHATEST"),this.settings.renderMode===t.RenderMode.VerticalBillBoard&&i.push("VERTICAL"),this.settings.renderMode===t.RenderMode.HorizontalBillBoard&&i.push("HORIZONTAL"),this.settings.renderMode===t.RenderMode.Beam&&i.push("BEAM");const u=Ps.takesPivotAndFlip(this.settings.renderMode)?this.settings.pivot:void 0;u&&i.push("PIVOT");const d=this.sizeLimits();d&&i.push("SIZE_LIMITS");const f=this.settings.renderMode===t.RenderMode.Mesh,m=this.settings.lighting??"fixed",p=f&&"unlit"!==m;f&&!p&&i.push("MESH_UNLIT");const y=f?this.settings.rim:void 0;y&&(i.push("MESH_RIM"),"mix"===y.mode&&i.push("MESH_RIM_MIX"));const g=c||!!y;i.push(...this.surfaceDefines());const v=ms(this.scene.getEngine());ps(e,s,n,v);const x=["position","uv","offset","color","size","rotation","uvTile"];this.settings.renderMode===t.RenderMode.Mesh&&x.push("normal"),Ps.drawsAlongVelocity(this.settings.renderMode)&&x.push("velocity");const S=["world","view","projection","worldView","worldViewProjection",..._s.FOG_UNIFORMS],b=[];(this.settings.uTileCount>1||this.settings.vTileCount>1)&&(S.push("tileCountX"),S.push("tileCountY")),a&&b.push("map"),c&&(b.push("envAtlas"),S.push("reflectionLevel")),g&&S.push("eyePosition"),y&&(S.push("rimColor"),S.push("rimParams")),this.surfaceUniforms(S,b),Ps.drawsAlongVelocity(this.settings.renderMode)&&S.push("speedFactor"),this.settings.softParticles&&(S.push("softParams"),S.push("projParams"),b.push("depthTexture")),this.settings.materialAlphaTest>0&&S.push("alphaTest"),u&&S.push("pivot"),d&&S.push("sizeLimits"),p&&(S.push("lightDirection"),S.push("lightColor"),S.push("ambientColor"));const w=new o.ShaderMaterial(e,this.scene,{vertex:e,fragment:e},{attributes:x,uniforms:S,samplers:b,defines:i,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:v});if(a&&w.setTexture("map",a),c&&h&&(w.setTexture("envAtlas",h),w.setFloat("reflectionLevel",this.settings.reflectionLevel)),y&&(w.setVector3("rimColor",new l.Vector3(y.color[0],y.color[1],y.color[2])),w.setVector2("rimParams",new l.Vector2(y.power,y.strength))),g){const t=new l.Vector3;w.setVector3("eyePosition",t),w.onBindObservable.add(()=>{const e=this.scene.activeCamera;e&&(t.copyFrom(e.globalPosition),w.setVector3("eyePosition",t))})}if((this.settings.uTileCount>1||this.settings.vTileCount>1)&&(w.setFloat("tileCountX",this.settings.uTileCount),w.setFloat("tileCountY",this.settings.vTileCount)),Ps.drawsAlongVelocity(this.settings.renderMode)&&w.setFloat("speedFactor",this.settings.softNearFade>0?this.settings.softNearFade:1),this.settings.softParticles){w.setVector2("softParams",new l.Vector2(this.settings.softNearFade,1/Math.max(this.settings.softFarFade-this.settings.softNearFade,1e-4)));const t=new l.Vector4(0,0,0,0);w.onBindObservable.add(()=>{const e=this.scene.activeCamera;e&&(t.x=e.minZ,t.y=e.maxZ,w.setVector4("projParams",t))})}if(this.settings.materialAlphaTest>0&&w.setFloat("alphaTest",this.settings.materialAlphaTest),u&&w.setVector3("pivot",new l.Vector3(u.x,u.y,u.z)),d&&w.setVector2("sizeLimits",d),p&&(this.writeFixedLighting(w),"scene"===m)){const t=new l.Vector3,e=new l.Vector3,i=new l.Vector3;w.onBindObservable.add(()=>{Ps.readSceneLight(this.scene,t,e,i)?(w.setVector3("lightDirection",t),w.setVector3("lightColor",e),w.setVector3("ambientColor",i)):this.writeFixedLighting(w)})}this.bindFog(w),this.bindSurface(w),w.backFaceCulling=!1,this.settings.materialTransparent?w.alphaMode=this.settings.materialBlendMode:w.alphaMode=r.Constants.ALPHA_DISABLE,w.needDepthPrePass=this.settings.materialDepthWrite,w.forceDepthWrite=this.settings.materialDepthWrite,w.disableDepthWrite=!this.settings.materialDepthWrite,this.mesh.material=w,this.shaderMaterial=w}applyMeshLighting(e){this.storeFixedLighting(e);const i=this.shaderMaterial;null!==i&&this.settings.renderMode===t.RenderMode.Mesh&&"unlit"!==this.settings.lighting&&this.writeFixedLighting(i)}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,i,s){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 l=o.intensity,h=o.diffuse,c=t.ambientColor;i.set(h.r*l,h.g*l,h.b*l),s.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&&(s.x+=t.r*l,s.y+=t.g*l,s.z+=t.b*l)}return!0}return!1}update(){let e=0,i=0;const s=this.settings.renderMode,n=s===t.RenderMode.Mesh,r=s===t.RenderMode.StretchedBillBoard,o=s===t.RenderMode.Beam,a=r||o,l=Ps.takesPivotAndFlip(s),h=this.getVisibleSystems();for(let t=0;t<h.length;t++)i+=h[t].particleNum;i>this.maxParticles&&this.expandBuffers(i);for(let t=0;t<h.length;t++){const i=h[t],s=i.particleNum;if(0===s)continue;const a=i.particles,c=this.quaternion2_,u=this.vector2_,d=this.vector3_,f=i.worldSpace,m=i.emitter.matrixWorld;if(n&&!f)m.decompose(u,c,d);else{const t=m.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]))}r&&!f&&this.rotationMat_.setFromMatrix4(m);const p=Math.abs(d.x),y=Math.abs(d.y),g=Math.abs(d.z),v=r?i.rendererEmitterSettings:void 0,x=void 0===v||0===v.speedFactor?.001:v.speedFactor,S=v?.lengthFactor??0,b=i.store,w=void 0!==b,M=void 0!==b&&!0!==i.onlyUsedByOther,z=i.simulationResidual??0,_=0===z?0:z/(i.simulationStep??z);w&&(0!==_&&s>0&&b.previousColor!==b.color?Ps.continueColor(this.colorBuffer,4*e,b,s,_):this.colorBuffer.set(b.color.subarray(0,4*s),4*e));let P=!1;if(void 0!==b&&f)0!==_&&s>0?Ps.extrapolate(this.offsetBuffer,3*e,b,s,_):this.offsetBuffer.set(b.position.subarray(0,3*s),3*e),0!==_&&s>0&&b.previousSize!==b.size?Ps.continueVector3(this.sizeBuffer,3*e,b.size,b.previousSize,s,_):this.sizeBuffer.set(b.size.subarray(0,3*s),3*e),P=!0;else if(M&&s>0){const t=3*e,i=t+3*s,n=this.offsetBuffer;0!==_?Ps.extrapolate(n,t,b,s,_):n.set(b.position.subarray(0,3*s),t);const r=m.elements,o=r[0],a=r[1],l=r[2],h=r[3],c=r[4],u=r[5],d=r[6],f=r[7],v=r[8],x=r[9],S=r[10],w=r[11],M=r[12],z=r[13],T=r[14],O=r[15];for(let e=t;e<i;e+=3){const t=n[e],i=n[e+1],s=n[e+2],r=1/(h*t+f*i+w*s+O);n[e]=(o*t+c*i+v*s+M)*r,n[e+1]=(a*t+u*i+x*s+z)*r,n[e+2]=(l*t+d*i+S*s+T)*r}const V=this.sizeBuffer;0!==_&&b.previousSize!==b.size?Ps.continueVector3(V,t,b.size,b.previousSize,s,_):V.set(b.size.subarray(0,3*s),t);for(let e=t;e<i;e+=3)V[e]*=p,V[e+1]*=y,V[e+2]*=g;P=!0}const T=e;if(M&&!n){const t=b;this.uvTileBuffer.set(t.uvTile.subarray(0,s),T);const i=this.rotationBuffer;if(i.set(t.rotation.subarray(0,s),T),0!==z){const e=t.angularVelocity;for(let t=0;t<s;t++)i[T+t]+=e[t]*z}r&&this.velocityBuffer&&Ps.writeVelocities(this.velocityBuffer,4*T,t,s,_,f?null:this.rotationMat_,x,S),e+=s}else if(M&&b.rotationQuaternion.length>0){const t=b;this.uvTileBuffer.set(t.uvTile.subarray(0,s),T),Ps.writeQuaternions(this.rotationBuffer,4*T,t,s,_,f?null:c),e+=s}else for(let t=0;t<s;t++,e++){const i=a[t];if(n){let t=i.rotation;const s=i.angularVelocity;let n;if(0!==_&&s instanceof H&&(t=this.quaternion4_.copy(t).multiply(Ps.partialTurn(s,_,this.quaternion5_))),f)n=t;else{let e;e=i.parentMatrix?this.quaternion3_.setFromRotationMatrix(i.parentMatrix):c,n=this.quaternion_,n.copy(e).multiply(t)}const r=4*e;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 t=i.angularVelocity;this.rotationBuffer[e]=i.rotation+("number"==typeof t?t*z:0)}if(!P){const t=i.position,s=i.previousPosition;let n=t.x+(t.x-s.x)*_,r=t.y+(t.y-s.y)*_,o=t.z+(t.z-s.z)*_;if(!f){const t=(i.parentMatrix??m).elements,e=1/(t[3]*n+t[7]*r+t[11]*o+t[15]),s=(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=s,r=a}const a=3*e;this.offsetBuffer[a]=n,this.offsetBuffer[a+1]=r,this.offsetBuffer[a+2]=o;const l=i.size,h=3*e;f||i.parentMatrix?(this.sizeBuffer[h]=l.x,this.sizeBuffer[h+1]=l.y,this.sizeBuffer[h+2]=l.z):(this.sizeBuffer[h]=l.x*p,this.sizeBuffer[h+1]=l.y*y,this.sizeBuffer[h+2]=l.z*g)}if(!w){const t=i.color,s=4*e;this.colorBuffer[s]=t.x,this.colorBuffer[s+1]=t.y,this.colorBuffer[s+2]=t.z,this.colorBuffer[s+3]=t.w}if(this.uvTileBuffer[e]=i.uvTile,r&&this.velocityBuffer){const t=i.velocity,s=i.previousVelocity,n=t.x+(t.x-s.x)*_,r=t.y+(t.y-s.y)*_,o=t.z+(t.z-s.z)*_;let a=this.vector_;a.set(n,r,o),f||(i.parentMatrix?(this.rotationMat2_.setFromMatrix4(i.parentMatrix),a.applyMatrix3(this.rotationMat2_)):a.applyMatrix3(this.rotationMat_));const l=4*e;this.velocityBuffer[l]=a.x*x,this.velocityBuffer[l+1]=a.y*x,this.velocityBuffer[l+2]=a.z*x,this.velocityBuffer[l+3]=S}}l&&void 0!==i.flip&&(void 0!==b?Ps.applyFlip(this.sizeBuffer,3*T,b.flip,s):Ps.applyFlipFromParticles(this.sizeBuffer,3*T,a,s)),o&&this.velocityBuffer&&this.writeBeams(i,T,e-T)}r&&h.length>0&&this.syncStretchedSpeedFactor(h[0]),this.mesh.forcedInstanceCount=e,this.refreshBoundingInfo(),0!==e?(this.clearedInstanceUploaded=!1,"none"!==this.settings.sortMode&&this.sortInstances(e,n,a),this.offsetVB.update(this.offsetBuffer.subarray(0,3*e)),this.sizeVB.update(this.sizeBuffer.subarray(0,3*e)),this.colorVB.update(this.colorBuffer.subarray(0,4*e)),this.uvTileVB.update(this.uvTileBuffer.subarray(0,e)),this.rotationVB.update(this.rotationBuffer.subarray(0,n?4*e:e)),a&&this.velocityVB&&this.velocityBuffer&&this.velocityVB.update(this.velocityBuffer.subarray(0,4*e))):this.clearedInstanceUploaded||(this.uploadClearedInstance(n,a),this.clearedInstanceUploaded=!0)}syncStretchedSpeedFactor(t){const e=this.shaderMaterial;if(null===e)return;const i=t.rendererEmitterSettings.speedFactor??1,s=0===i?.001:i;s!==this.lastStretchedSpeedFactor&&(e.setFloat("speedFactor",s),this.lastStretchedSpeedFactor=s)}static drawsAlongVelocity(e){return e===t.RenderMode.StretchedBillBoard||e===t.RenderMode.Beam}writeBeams(t,e,i){const s=this.velocityBuffer,n=this.offsetBuffer,r=this.beamEnd_,o="function"==typeof t.getBeamEnd&&t.getBeamEnd(r);for(let t=e;t<e+i;t++){const e=3*t,i=4*t;s[i]=o?r.x-n[e]:0,s[i+1]=o?r.y-n[e+1]:0,s[i+2]=o?r.z-n[e+2]:0,s[i+3]=0}}static takesPivotAndFlip(e){return e===t.RenderMode.BillBoard||e===t.RenderMode.StretchedBillBoard||e===t.RenderMode.VerticalBillBoard||e===t.RenderMode.HorizontalBillBoard}static applyFlip(t,e,i,s){for(let n=0,r=e;n<s;n++,r+=3){const e=i[n];0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static applyFlipFromParticles(t,e,i,s){for(let n=0,r=e;n<s;n++,r+=3){const e=i[n].flip;0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static writeQuaternions(t,e,i,s,n,r){const o=i.rotationQuaternion,a=i.angularVelocityQuaternion,l=null!==r,h=l?r.x:0,c=l?r.y:0,u=l?r.z:0,d=l?r.w:1;for(let i=0,r=0,f=e;i<s;i++,r+=4,f+=4){let e=o[r],i=o[r+1],s=o[r+2],m=o[r+3];if(0!==n){const t=a[r]*n,o=a[r+1]*n,l=a[r+2]*n,h=1+(a[r+3]-1)*n,c=1/Math.sqrt(t*t+o*o+l*l+h*h),u=t*c,d=o*c,f=l*c,p=h*c,y=e*p+m*u+i*f-s*d,g=i*p+m*d+s*u-e*f,v=s*p+m*f+e*d-i*u;m=m*p-e*u-i*d-s*f,e=y,i=g,s=v}if(l){const t=h*m+d*e+c*s-u*i,n=c*m+d*i+u*e-h*s,r=u*m+d*s+h*i-c*e;m=d*m-h*e-c*i-u*s,e=t,i=n,s=r}t[f]=e,t[f+1]=i,t[f+2]=s,t[f+3]=m}}static writeVelocities(t,e,i,s,n,r,o,a){const l=i.velocity,h=i.previousVelocity.length>=3*s?i.previousVelocity:l,c=null!==r?r.elements:null;for(let i=0,r=0,u=e;i<s;i++,r+=3,u+=4){let e=l[r],i=l[r+1],s=l[r+2];if(0!==n&&(e+=(e-h[r])*n,i+=(i-h[r+1])*n,s+=(s-h[r+2])*n),null!==c){const t=c[0]*e+c[3]*i+c[6]*s,n=c[1]*e+c[4]*i+c[7]*s;s=c[2]*e+c[5]*i+c[8]*s,e=t,i=n}t[u]=e*o,t[u+1]=i*o,t[u+2]=s*o,t[u+3]=a}}static partialTurn(t,e,i){const s=t.x*e,n=t.y*e,r=t.z*e,o=1+(t.w-1)*e,a=1/Math.sqrt(s*s+n*n+r*r+o*o);return i.x=s*a,i.y=n*a,i.z=r*a,i.w=o*a,i}static continueVector3(t,e,i,s,n,r){for(let o=0,a=0;o<n;o++,a+=3){const n=i[a]+(i[a]-s[a])*r,o=i[a+1]+(i[a+1]-s[a+1])*r,l=i[a+2]+(i[a+2]-s[a+2])*r;t[e+a]=n>0?n:0,t[e+a+1]=o>0?o:0,t[e+a+2]=l>0?l:0}}static continueColor(t,e,i,s,n){const r=i.color,o=i.previousColor;for(let i=0,a=0;i<s;i++,a+=4){const i=r[a]+(r[a]-o[a])*n,s=r[a+1]+(r[a+1]-o[a+1])*n,l=r[a+2]+(r[a+2]-o[a+2])*n,h=r[a+3]+(r[a+3]-o[a+3])*n;t[e+a]=i>0?i:0,t[e+a+1]=s>0?s:0,t[e+a+2]=l>0?l:0,t[e+a+3]=h>0?h:0}}static extrapolate(t,e,i,s,n){const r=i.position,o=i.previousPosition;for(let i=0,a=0;i<s;i++,a+=3){const i=r[a],s=r[a+1],l=r[a+2];t[e+a]=i+(i-o[a])*n,t[e+a+1]=s+(s-o[a+1])*n,t[e+a+2]=l+(l-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.mesh.material&&this.mesh.material.dispose(),super.dispose()}}Ps.whiteTextureByScene=new WeakMap;var Ts=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n${ji}\n${Ki}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${ts(!1)}\n if (baseColor.a < 0.01) { discard; }\n\n${Yi("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,Os=`\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;\nuniform lineWidth: f32;\nuniform resolution: vec2f;\nuniform sizeAttenuation: f32;\n\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n\nfn fix(i: vec4f, aspect: f32) -> vec2f {\n var res = i.xy / i.w;\n res.x *= aspect;\n return res;\n}\n\n${Gi}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let aspect = uniforms.resolution.x / uniforms.resolution.y;\n var finalPosition = uniforms.projection * uniforms.view * vec4f(vertexInputs.position, 1.0);\n let prevPos = uniforms.projection * uniforms.view * vec4f(vertexInputs.previous, 1.0);\n let nextPos = uniforms.projection * uniforms.view * vec4f(vertexInputs.next, 1.0);\n\n let currentP = fix(finalPosition, aspect);\n let prevP = fix(prevPos, aspect);\n let nextP = fix(nextPos, aspect);\n\n let w = uniforms.lineWidth * vertexInputs.width;\n var dir: vec2f;\n if (distance(nextP, currentP) < 0.0001) {\n dir = normalize(currentP - prevP);\n } else if (distance(prevP, currentP) < 0.0001) {\n dir = normalize(nextP - currentP);\n } else {\n let dir1 = normalize(currentP - prevP);\n let dir2 = normalize(nextP - currentP);\n dir = normalize(dir1 + dir2);\n }\n var normal = vec4f(-dir.y, dir.x, 0.0, 1.0);\n normal.x *= 0.5 * w;\n normal.y *= 0.5 * w;\n normal = normal * uniforms.projection;\n if (uniforms.sizeAttenuation == 0.0) {\n let screen = (vec4f(uniforms.resolution, 0.0, 1.0) * uniforms.projection).xy;\n normal.x = normal.x * finalPosition.w / screen.x;\n normal.y = normal.y * finalPosition.w / screen.y;\n }\n finalPosition.x += normal.x * vertexInputs.side;\n finalPosition.y += normal.y * vertexInputs.side;\n\n vertexOutputs.position = finalPosition;\n${Wi("(uniforms.view * vec4f(vertexInputs.position, 1.0)).xyz")}\n vertexOutputs.vUV = vertexInputs.uv;\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;class Vs extends _s{constructor(t,e){super(t,e),this.drawsNothing=!1,this.vector_=new K,this.vector2_=new K,this.vector3_=new K,this.quaternion_=new H,this.maxParticles=1024,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh.dispose(),this.mesh=new h.Mesh("trailBatch",this.scene),this.configureMesh(),this.buildGeometryBuffers()}buildGeometryBuffers(){this.positionBuffer=new Float32Array(6*this.maxParticles),this.previousBuffer=new Float32Array(6*this.maxParticles),this.nextBuffer=new Float32Array(6*this.maxParticles),this.uvBuffer=new Float32Array(4*this.maxParticles),this.sideBuffer=new Float32Array(2*this.maxParticles),this.widthBuffer=new Float32Array(2*this.maxParticles),this.colorBuffer=new Float32Array(8*this.maxParticles),this.indexBuffer=new Uint32Array(6*this.maxParticles);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(e.VertexBuffer.PositionKind,this.positionBuffer,!0),this.mesh.setVerticesData(e.VertexBuffer.UVKind,this.uvBuffer,!0),this.mesh.setVerticesData(e.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 t=this.scene.getEngine();this.previousVB=new e.VertexBuffer(t,this.previousBuffer,"previous",!0,!1,3,!1),this.nextVB=new e.VertexBuffer(t,this.nextBuffer,"next",!0,!1,3,!1),this.sideVB=new e.VertexBuffer(t,this.sideBuffer,"side",!0,!1,1,!1),this.widthVB=new e.VertexBuffer(t,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.previousVB?.dispose(),this.nextVB?.dispose(),this.sideVB?.dispose(),this.widthVB?.dispose(),this.buildGeometryBuffers()}rebuildMaterial(){const t="quarksTrail",e=this.fogDefines();this.settings.texture&&e.push("USE_MAP"),e.push(...this.surfaceDefines());const i=ms(this.scene.getEngine());ps(t,{glsl:os,wgsl:Os},{glsl:rs,wgsl:Ts},i);const s=["world","view","projection","worldViewProjection","lineWidth","resolution","sizeAttenuation",..._s.FOG_UNIFORMS],n=[];this.settings.texture&&n.push("map"),this.surfaceUniforms(s,n);const a=new o.ShaderMaterial(t,this.scene,{vertex:t,fragment:t},{attributes:["position","previous","next","side","width","uv","color"],uniforms:s,samplers:n,defines:e,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:i});this.settings.texture&&a.setTexture("map",this.settings.texture);const h=this.scene.getEngine();a.setFloat("lineWidth",1);const c=new l.Vector2(h.getRenderWidth(),h.getRenderHeight());a.setVector2("resolution",c),a.setFloat("sizeAttenuation",1),a.onBindObservable.add(()=>{const t=this.scene.getEngine(),e=t.getRenderWidth(),i=t.getRenderHeight();c.x===e&&c.y===i||(c.x=e,c.y=i,a.setVector2("resolution",c))}),this.bindFog(a),this.bindSurface(a),a.backFaceCulling=!1,this.settings.materialTransparent?a.alphaMode=this.settings.materialBlendMode:a.alphaMode=r.Constants.ALPHA_DISABLE,a.needDepthPrePass=this.settings.materialDepthWrite,a.forceDepthWrite=this.settings.materialDepthWrite,a.disableDepthWrite=!this.settings.materialDepthWrite,this.mesh.material=a}static ensureWorldMatrix(t){const e=t.emitter;!e.computeWorldMatrix||e.isSynchronized&&e.isSynchronized()||e.computeWorldMatrix(!0)}update(){let t=0,e=0,i=0;const s=this.getVisibleSystems();for(let t=0;t<s.length;t++){const e=s[t],n=e.particles;for(let t=0;t<e.particleNum;t++){const e=n[t].historyCount;0!==e&&(i+=2*e+2)}}i>this.maxParticles&&this.expandBuffers(i);for(let i=0;i<s.length;i++){const n=s[i],r=t;Vs.ensureWorldMatrix(n);const o=this.quaternion_,a=this.vector2_,l=this.vector3_,h=n.emitter.matrixWorld;h.decompose(a,o,l);const c=n.particles,u=n.particleNum,d=this.settings.uTileCount,f=this.settings.vTileCount,m=1/d,p=1/f,y=n.worldSpace,g=(Math.abs(l.x)+Math.abs(l.y)+Math.abs(l.z))/3,v=n.rendererEmitterSettings,x=Boolean(v.uvFromHead),S=Boolean(v.colorFromParticle),b=y||Boolean(v.recordWorldSpace),w=v.followLocalOrigin?0:n.simulationResidual??0,M=0===w?0:w/(n.simulationStep??w);for(let i=0;i<u;i++){const s=c[i],n=s.historyCount;if(0===n)continue;const r=s.historyCapacity,o=s.historyPositions,a=s.historySizes,l=S?s.store.color:s.historyColors,u=4*s.storeIndex,d=s.uvTile%f,v=Math.floor(s.uvTile/f+.001),w=(s.parentMatrix??h).elements,z=w[0],_=w[1],P=w[2],T=w[3],O=w[4],V=w[5],B=w[6],C=w[7],A=w[8],F=w[9],$=w[10],I=w[11],E=w[12],N=w[13],L=w[14],R=w[15],D=1/(0!==M?n:Math.max(1,n-1));let U=s.getHistoryIndex(0),q=o[3*U],k=o[3*U+1],J=o[3*U+2];if(!b){const t=1/(T*q+C*k+I*J+R),e=(z*q+O*k+A*J+E)*t,i=(_*q+V*k+F*J+N)*t;J=(P*q+B*k+$*J+L)*t,q=e,k=i}let Q=q,G=k,W=J;for(let i=0;i<n;i++,t+=2){let h=q,c=k,w=J,M=U;if(i+1<n){M=U+1===r?0:U+1;const t=3*M;if(h=o[t],c=o[t+1],w=o[t+2],!b){const t=1/(T*h+C*c+I*w+R),e=(z*h+O*c+A*w+E)*t,i=(_*h+V*c+F*w+N)*t;w=(P*h+B*c+$*w+L)*t,h=e,c=i}}const j=a[U],Y=S?u:4*U,X=l[Y],Z=l[Y+1],H=l[Y+2],K=l[Y+3],tt=3*t;this.positionBuffer[tt]=q,this.positionBuffer[tt+1]=k,this.positionBuffer[tt+2]=J,this.positionBuffer[tt+3]=q,this.positionBuffer[tt+4]=k,this.positionBuffer[tt+5]=J,this.previousBuffer[tt]=Q,this.previousBuffer[tt+1]=G,this.previousBuffer[tt+2]=W,this.previousBuffer[tt+3]=Q,this.previousBuffer[tt+4]=G,this.previousBuffer[tt+5]=W,this.nextBuffer[tt]=h,this.nextBuffer[tt+1]=c,this.nextBuffer[tt+2]=w,this.nextBuffer[tt+3]=h,this.nextBuffer[tt+4]=c,this.nextBuffer[tt+5]=w,y||s.parentMatrix?(this.widthBuffer[t]=j,this.widthBuffer[t+1]=j):(this.widthBuffer[t]=j*g,this.widthBuffer[t+1]=j*g);const et=2*t,it=i*D,st=((x?1-it:it)+d)*m;this.uvBuffer[et]=st,this.uvBuffer[et+1]=(f-v-1)*p,this.uvBuffer[et+2]=st,this.uvBuffer[et+3]=(f-v)*p;const nt=4*t;this.colorBuffer[nt]=X,this.colorBuffer[nt+1]=Z,this.colorBuffer[nt+2]=H,this.colorBuffer[nt+3]=K,this.colorBuffer[nt+4]=X,this.colorBuffer[nt+5]=Z,this.colorBuffer[nt+6]=H,this.colorBuffer[nt+7]=K,i+1<n&&(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++),Q=q,G=k,W=J,q=h,k=c,J=w,U=M}if(0!==M){const i=s.previousPosition,n=s.position;let r=n.x+(n.x-i.x)*M,o=n.y+(n.y-i.y)*M,a=n.z+(n.z-i.z)*M;const l=t-2,h=this.positionBuffer[3*l],c=this.positionBuffer[3*l+1],u=this.positionBuffer[3*l+2];if(!y){const t=1/(T*r+C*o+I*a+R),e=(z*r+O*o+A*a+E)*t,i=(_*r+V*o+F*a+N)*t;a=(P*r+B*o+$*a+L)*t,r=e,o=i}const S=3*t;this.positionBuffer[S]=r,this.positionBuffer[S+1]=o,this.positionBuffer[S+2]=a,this.positionBuffer[S+3]=r,this.positionBuffer[S+4]=o,this.positionBuffer[S+5]=a,this.previousBuffer[S]=h,this.previousBuffer[S+1]=c,this.previousBuffer[S+2]=u,this.previousBuffer[S+3]=h,this.previousBuffer[S+4]=c,this.previousBuffer[S+5]=u,this.nextBuffer[S]=r,this.nextBuffer[S+1]=o,this.nextBuffer[S+2]=a,this.nextBuffer[S+3]=r,this.nextBuffer[S+4]=o,this.nextBuffer[S+5]=a;const b=3*l;this.nextBuffer[b]=r,this.nextBuffer[b+1]=o,this.nextBuffer[b+2]=a,this.nextBuffer[b+3]=r,this.nextBuffer[b+4]=o,this.nextBuffer[b+5]=a;const w=s.size.x;y||s.parentMatrix?(this.widthBuffer[t]=w,this.widthBuffer[t+1]=w):(this.widthBuffer[t]=w*g,this.widthBuffer[t+1]=w*g);const D=2*t,U=((x?0:1)+d)*m;this.uvBuffer[D]=U,this.uvBuffer[D+1]=(f-v-1)*p,this.uvBuffer[D+2]=U,this.uvBuffer[D+3]=(f-v)*p;const q=s.color,k=4*t;this.colorBuffer[k]=q.x,this.colorBuffer[k+1]=q.y,this.colorBuffer[k+2]=q.z,this.colorBuffer[k+3]=q.w,this.colorBuffer[k+4]=q.x,this.colorBuffer[k+5]=q.y,this.colorBuffer[k+6]=q.z,this.colorBuffer[k+7]=q.w,this.indexBuffer[3*e]=l,this.indexBuffer[3*e+1]=l+1,this.indexBuffer[3*e+2]=t,e++,this.indexBuffer[3*e]=t,this.indexBuffer[3*e+1]=l+1,this.indexBuffer[3*e+2]=t+1,e++,t+=2}}this.measureSystemBounds(n,r,t)}this.refreshBoundingInfo(),this.uploadGeometry(t,e)}measureSystemBounds(t,e,i){if(i<=e||"function"!=typeof t.setWorldBounds)return;const s=this.positionBuffer;let n=1/0,r=1/0,o=1/0,a=-1/0,l=-1/0,h=-1/0;for(let t=3*e,c=3*i;t<c;t+=6){const e=s[t],i=s[t+1],c=s[t+2];e<n&&(n=e),e>a&&(a=e),i<r&&(r=i),i>l&&(l=i),c<o&&(o=c),c>h&&(h=c)}const c=this.widthBuffer;let u=0;for(let t=e;t<i;t+=2){const e=c[t];e>u&&(u=e)}t.setWorldBounds(n,r,o,a,l,h,u)}uploadGeometry(t,i){const s=this.mesh.geometry,n=s?.getIndexBuffer();if(t>0&&i>0){this.mesh.updateVerticesData(e.VertexBuffer.PositionKind,this.positionBuffer.subarray(0,3*t)),this.mesh.updateVerticesData(e.VertexBuffer.UVKind,this.uvBuffer.subarray(0,2*t)),n&&this.scene.getEngine().updateDynamicIndexBuffer(n,this.indexBuffer.subarray(0,3*i),0),this.previousVB.update(this.previousBuffer.subarray(0,3*t)),this.nextVB.update(this.nextBuffer.subarray(0,3*t)),this.widthVB.update(this.widthBuffer.subarray(0,t));const s=this.mesh.getVertexBuffer(e.VertexBuffer.ColorKind);s&&s.update(this.colorBuffer.subarray(0,4*t)),this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.mesh.subMeshes[0].indexCount=3*i,this.mesh.subMeshes[0].verticesCount=t),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._boundingInfo=t}dispose(){this.mesh.material&&this.mesh.material.dispose(),super.dispose()}}class Bs extends n.TransformNode{constructor(t,e){super(t,e),this.batches=[],this.elapsed=0,this.systemToBatchIndex=new Map,this.depthTexture=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=vs(),this.cullingEnabled=!0,this.catchUpBudgetMs=2,this.simulationBudgetMs=1/0,this.frustumPlanes=[],this.boundsMin=new K,this.boundsMax=new K}collectFrustumPlanes(){const t=this.getScene(),e=this.frustumPlanes,n=t.activeCameras,r=t.activeCamera,o=n&&n.length>0?n:r?[r]:[],a=6*o.length;for(;e.length<a;)e.push(new s.Plane(0,0,0,0));e.length=a;for(let t=0;t<o.length;t++){const s=o[t];s.getViewMatrix(),s.getProjectionMatrix();const n=s.getTransformationMatrix(),r=0===t?e:e.slice(6*t,6*t+6);if(i.Frustum.GetPlanesToRef(n,r),0!==t)for(let i=0;i<6;i++)e[6*t+i]=r[i]}return e}isSystemInView(t,e){const i=this.boundsMin,s=this.boundsMax;if(!t.getWorldBounds(i,s))return!0;for(let t=0;t<e.length;t+=6){let n=!0;for(let r=t;r<t+6;r++){const t=e[r],o=t.normal,a=o.x>=0?s.x:i.x,l=o.y>=0?s.y:i.y,h=o.z>=0?s.z:i.z;if(o.x*a+o.y*l+o.z*h+t.d<0){n=!1;break}}if(n)return!0}return!1}static clamp(t,e,i){return Math.max(e,Math.min(i,t))}static equals(t,e){return t.materialBlendMode===e.materialBlendMode&&t.materialTransparent===e.materialTransparent&&t.materialDepthTest===e.materialDepthTest&&t.materialDepthWrite===e.materialDepthWrite&&t.materialAlphaTest===e.materialAlphaTest&&t.texture===e.texture&&t.reflectionTexture===e.reflectionTexture&&t.reflectionLevel===e.reflectionLevel&&function(t,e){if(t===e)return!0;if(!t||!e||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0}(t.reflectionFaces,e.reflectionFaces)&&t.reflectionAtlas===e.reflectionAtlas&&t.renderMode===e.renderMode&&t.blendTiles===e.blendTiles&&t.softParticles===e.softParticles&&t.softFarFade===e.softFarFade&&t.softNearFade===e.softNearFade&&t.uTileCount===e.uTileCount&&t.vTileCount===e.vTileCount&&t.instancingGeometry===e.instancingGeometry&&t.renderOrder===e.renderOrder&&t.layerMask===e.layerMask&&t.renderingGroupId===e.renderingGroupId&&t.applyFog===e.applyFog&&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.sortMode===(e.sortMode??"none")&&t.minParticleSize===(e.minParticleSize??0)&&t.maxParticleSize===(e.maxParticleSize??1/0)&&(t.lighting??"fixed")===(e.lighting??"fixed")&&Ss(t.rim,e.rim)&&zs(t.uvScroll,e.uvScroll)&&t.gradientMap===(e.gradientMap??null)&&ws(t.erosion,e.erosion)}addSystem(t){const e=t;e._renderer=this,this.systemToBatchIndex.has(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(e){const i=e,s=e.getRendererSettings();for(let t=0;t<this.batches.length;t++)if(Bs.equals(this.batches[t].settings,s))return this.batches[t].addSystem(i),void this.systemToBatchIndex.set(i,t);let n;const r=this.getScene();switch(s.renderMode){case t.RenderMode.Trail:n=new Vs(s,r);break;case t.RenderMode.Mesh:case t.RenderMode.BillBoard:case t.RenderMode.VerticalBillBoard:case t.RenderMode.HorizontalBillBoard:case t.RenderMode.StretchedBillBoard:case t.RenderMode.Beam:n=new Ps(s,r);break;default:throw new Error(`Unsupported render mode: ${s.renderMode}`)}n.mesh.parent=this,this.depthTexture&&n.applyDepthTexture(this.depthTexture),n.applyMeshLighting(this.meshLighting),n.addSystem(i),this.batches.push(n),this.batchEmptyFrames.push(0),this.systemToBatchIndex.set(i,this.batches.length-1)}deleteSystem(t){const e=this.removeFromBatch(t),i=this.systems.indexOf(t);-1!==i&&(this.systems.splice(i,1),this.orderedSystemsStale=!0);const s=this.orderedSystems.indexOf(t);return-1!==s&&this.orderedSystems.splice(s,1),e}removeFromBatch(t){const e=this.systemToBatchIndex.get(t);return void 0!==e&&(this.batches[e].removeSystem(t),this.systemToBatchIndex.delete(t),!0)}updateSystem(t){this.removeFromBatch(t),this.addSystem(t)}setDepthTexture(t){this.depthTexture=t;for(const e of this.batches)e.applyDepthTexture(t)}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.batches)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,i=Bs.clamp(t.minQuality??e.minQuality,.05,1),s=Bs.clamp(t.maxQuality??e.maxQuality,i,1);e.targetFrameMs=Math.max(t.targetFrameMs??e.targetFrameMs,.1),e.minQuality=i,e.maxQuality=s,e.decreaseStep=Math.max(t.decreaseStep??e.decreaseStep,.001),e.increaseStep=Math.max(t.increaseStep??e.increaseStep,.001),e.currentQuality=Bs.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,i=new Set,s=new Set(this.systems),n=r=>{if(!i.has(r)&&!e.has(r)){e.add(r);for(const t of(t=>{const e=[];for(const i of t.behaviors??[]){if("EmitSubParticleSystem"!==i.type)continue;const t=i.subParticleSystem?.system;void 0!==t&&s.has(t)&&e.push(t)}return e})(r))n(t);e.delete(r),i.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,i=e.enabled?performance.now():0;e.enabled&&this.applyAdaptiveQuality();const s=this.orderSystems(),n=this.cullingEnabled?this.collectFrustumPlanes():null,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<s.length;e++){const i=s[e];i.emitter.visible&&(i.culled=null!==n&&n.length>0&&"always"!==i.cullingMode&&!0!==i.onlyUsedByOther&&!this.isSystemInView(i,n),i.update(t,o,a)),s[e]!==i&&e--}this.refreshBatches(),e.enabled&&(e.lastFrameCpuMs=performance.now()-i,e.lastFrameCpuMs>e.targetFrameMs?e.currentQuality=Bs.clamp(e.currentQuality-e.decreaseStep,e.minQuality,e.maxQuality):e.currentQuality=Bs.clamp(e.currentQuality+e.increaseStep,e.minQuality,e.maxQuality))}refreshBatches(){const t=this.batchEmptyFrames;for(let e=0;e<this.batches.length;e++){const i=this.batches[e];if(i.time=this.elapsed,i.systems.size>0){t[e]=0,i.update();continue}const s=(t[e]??0)+1;t[e]=s,1===s?i.update():s>Bs.EMPTY_BATCH_GRACE_FRAMES&&(this.removeBatch(e),e--)}}removeBatch(t){this.batches[t].dispose(),this.batches.splice(t,1),this.batchEmptyFrames.splice(t,1);for(const[e,i]of this.systemToBatchIndex)i>t&&this.systemToBatchIndex.set(e,i-1)}getBatchRenderStats(){return this.batches.map((t,e)=>{let i=0;const s=[];for(const e of t.systems){const t=e;i+=t.particleNum,s.push(t.emitter.name)}return{batchIndex:e,renderMode:t.settings.renderMode,instanceCount:t.mesh.forcedInstanceCount??0,particleCount:i,systemNames:s}})}dispose(){for(const t of this.batches)t.dispose();this.batches=[],this.batchEmptyFrames.length=0,this.systems.length=0,this.systemToBatchIndex.clear(),super.dispose()}}Bs.EMPTY_BATCH_GRACE_FRAMES=120;const Cs=Bs;class As extends n.TransformNode{get matrixWorld(){const t=this.getWorldMatrix(),e=t.updateFlag;if(e===this._matrixWorldFlag)return this._matrixWorld;this._matrixWorldFlag=e;const i=this._matrixWorld.elements,s=t.m;return i[0]=s[0],i[1]=s[1],i[2]=s[2],i[3]=s[3],i[4]=s[4],i[5]=s[5],i[6]=s[6],i[7]=s[7],i[8]=s[8],i[9]=s[9],i[10]=s[10],i[11]=s[11],i[12]=s[12],i[13]=s[13],i[14]=s[14],i[15]=s[15],this._matrixWorld}get visible(){return this.isEnabled()}set visible(t){this.setEnabled(t)}get uuid(){return this.uniqueId.toString()}constructor(t,e){super("particleEmitter",e||void 0),this._matrixWorld=new nt,this._matrixWorldFlag=-1,this.system=t}dispose(){super.dispose()}extractFromCache(t){const e=[];for(const i in t){const s=t[i];s&&"object"==typeof s&&delete s.metadata,e.push(s)}return e}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:this._quarksUUID??this.uniqueId.toString(),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(),ps:this.system.toJSON(t,e)}}}class Fs{static runOnAllParticleEmitters(t,e){Fs.traverseNode(t,t=>{t instanceof As&&e(t)})}static addToBatchRenderer(t,e){Fs.runOnAllParticleEmitters(t,t=>{e.addSystem(t.system)})}static play(t){Fs.runOnAllParticleEmitters(t,t=>{t.system.play()})}static stop(t){Fs.runOnAllParticleEmitters(t,t=>{t.system.stop()})}static pause(t){Fs.runOnAllParticleEmitters(t,t=>{t.system.pause()})}static restart(t){Fs.runOnAllParticleEmitters(t,t=>{t.system.restart()})}static setAutoDestroy(t,e){Fs.runOnAllParticleEmitters(t,t=>{t.system.autoDestroy=e})}static endEmit(t){Fs.runOnAllParticleEmitters(t,t=>{t.system.endEmit()})}static isEffectFinished(t){let e=!1,i=!0;return Fs.runOnAllParticleEmitters(t,t=>{e=!0,t.system.isFinished()||(i=!1)}),e&&i}static instantiate(t,e){const i=new Map,s=(t,e,r)=>{let o;if(t instanceof As)o=t.clone(r),i.set(t,o);else{if(!(t instanceof n.TransformNode))return null;o=new n.TransformNode(r??t.name,t.getScene()),o.position.copyFrom(t.position),o.rotation.copyFrom(t.rotation),o.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(o.rotationQuaternion=t.rotationQuaternion.clone()),o.setEnabled(t.isEnabled(!1))}o.parent=e;for(const e of t.getChildren())s(e,o);return o},r=s(t,null,e);for(const t of i.values())for(const e of t.system.behaviors)if(e instanceof ve){const t=i.get(e.subParticleSystem);void 0!==t&&(e.subParticleSystem=t)}return r}static getDuration(t){const e=[];Fs.runOnAllParticleEmitters(t,t=>{e.push(t.system)});const i=new Map;for(let t=0;t<e.length;t++){const s=e[t];for(const t of s.behaviors){if(!(t instanceof ve))continue;const n=t.subParticleSystem?.system;if(void 0!==n&&"object"==typeof n){e.includes(n)||e.push(n);const t=i.get(n)??[];t.push(s),i.set(n,t)}}}const s=new Map,n=t=>{const e=s.get(t);if(void 0!==e)return e;s.set(t,1/0);const r=t.playbackSpeed,o=Fs.maxOf(t.startLife)/r;let a;if(r>0)if(t.onlyUsedByOther){a=0;for(const e of i.get(t)??[])a=Math.max(a,n(e));a+=t.duration/r+o}else a=t.looping?1/0:(Fs.maxOf(t.startDelay,0)+t.duration)/r+o;else a=1/0;return s.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 Ct)return t.value;if(t instanceof At)return Math.max(t.a,t.b);let i=-1/0;for(let s=0;s<=32;s++){const n=[];t.startGen(n);const r="function"===t.type?t.genValue(n,e??s/32):t.genValue(n);i=Math.max(i,r)}return i}static traverseNode(t,e){e(t);const i=t.getChildren();for(const t of i)Fs.traverseNode(t,e)}}const $s=new WeakMap,Is=new WeakMap;function Es(t){if(!t?.isCube)return null;const e=t.files??t._files;return 6===e?.length?e.slice():null}function Ns(t){return $s.get(t)??null}async function Ls(t,e){if("undefined"==typeof document||"undefined"==typeof Image)throw new Error("createEnvAtlasFromFaceUrls requires a DOM Image/canvas environment");const i=await Promise.all(t.map(t=>function(t){return new Promise((e,i)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>e(s),s.onerror=()=>i(new Error(`Failed to load env face ${t}`)),s.src=t})}(t))),s=i[0].width||i[0].naturalWidth;if(!s)throw new Error("Env atlas face image has zero size");const n=document.createElement("canvas");n.width=3*s,n.height=2*s;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(i[t],t%3*s,Math.floor(t/3)*s,s,s);const o=new g.Texture(n.toDataURL("image/jpeg",.92),e,{noMipmap:!0,invertY:!1,samplingMode:g.Texture.LINEAR_LINEAR});return o.name="quarksEnvAtlas",o}const Rs={createFromFaceUrls:Ls};function Ds(t,e,i){const s=$s.get(t);if(s)return i(s),s;const n=()=>{const s=Is.get(t);if(s)return void s.then(t=>{t&&i(t)});const n=Es(t);if(!n)return;const r=Rs.createFromFaceUrls(n,e).then(e=>($s.set(t,e),Is.delete(t),i(e),e)).catch(e=>(Is.delete(t),console.warn("[babylon.quarks] Failed to build env atlas from cubemap faces",e),null));Is.set(t,r)};if(t.isReady())n();else{const e=t.onLoadObservable;e?e.addOnce(()=>n()):n()}return $s.get(t)??null}class Us extends x.StandardMaterial{constructor(t,e,i={}){super(t,e),this.isParticleMeshStandardMaterial=!0,Object.assign(this,i)}}class qs extends v.PBRMaterial{constructor(t,e,i={}){super(t,e),this.isParticleMeshPhysicsMaterial=!0,Object.assign(this,i)}}function ks(t,e){if(e&&e.length>0)return e;const i=t.length/3,s=new Uint32Array(i);for(let t=0;t<i;t++)s[t]=t;return s}const Js=new K(0,0,1),Qs=new H,Gs=new H,Ws=new K,js=new K,Ys=1/60,Xs=new Set(["SizeOverLife","SizeBySpeed"]),Zs=new Set(["ColorOverLife","ColorBySpeed"]),Hs=new Set(["ApplyForce","Noise","TurbulenceField","GravityForce","RotationOverLife","Rotation3DOverLife","RotationBySpeed","SpeedOverLife","FrameOverLife","ForceOverLife","VelocityOverLife","InheritVelocity","OrbitOverLife","WidthOverLength","ChangeEmitDirection","EmitSubParticleSystem","LimitSpeedOverLife","ApplyCollision"]),Ks=new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]),tn=new Float32Array([0,0,1,0,1,1,0,1]);const en=new Uint32Array([0,1,2,0,2,3]);function sn(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}class nn{set time(t){this.emissionState.time=t}get time(){return this.emissionState.time}get isEmitEnded(){return this.emitEnded}hasPendingEmission(){if(this.looping)return!0;if(this.emitEnded)return!1;if(this.onlyUsedByOther)return!1;const t=this.emissionState;if(t.waitEmiting>0)return!0;if(t.burstIndex<this.emissionBursts.length)return!0;if(this.hasPendingBurstWaves(t))return!0;if(t.time>=this.duration)return!1;const e=t.time/this.duration;return this.emissionOverTime.genValue(this.memory,e)>0||this.emissionOverDistance.genValue(this.memory,e)>0}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=t,this.neededToUpdateRender=!0}get vTileCount(){return this.rendererSettings.vTileCount}set vTileCount(t){this.rendererSettings.vTileCount=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}set sortMode(t){this.rendererSettings.sortMode=nn.validSortMode(t),this.neededToUpdateRender=!0}get minParticleSize(){return this.rendererSettings.minParticleSize}set minParticleSize(t){this.rendererSettings.minParticleSize=Math.max(0,t),this.neededToUpdateRender=!0}get maxParticleSize(){return this.rendererSettings.maxParticleSize}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=nn.nonZeroPivot(t),this.neededToUpdateRender=!0}get lighting(){return this.rendererSettings.lighting??"fixed"}set lighting(t){this.rendererSettings.lighting=nn.validLighting(t),this.neededToUpdateRender=!0}get rim(){return this.rendererSettings.rim}set rim(t){this.rendererSettings.rim=xs(t),this.neededToUpdateRender=!0}get uvScroll(){return this.rendererSettings.uvScroll}set uvScroll(t){this.rendererSettings.uvScroll=Ms(t),this.neededToUpdateRender=!0}get gradientMap(){return this.rendererSettings.gradientMap??null}set gradientMap(t){this.rendererSettings.gradientMap=t??null,this.neededToUpdateRender=!0}get erosion(){return this.rendererSettings.erosion}set erosion(t){this.rendererSettings.erosion=bs(t),this.neededToUpdateRender=!0}measureMotionScale(){if("hierarchy"!==this.scalingMode||!this.worldSpace)return this.hierarchyScale.set(1,1,1),1;const t=this.emitter.matrixWorld.elements,e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),i=Math.sqrt(t[4]*t[4]+t[5]*t[5]+t[6]*t[6]),s=Math.sqrt(t[8]*t[8]+t[9]*t[9]+t[10]*t[10]);return this.hierarchyScale.set(e,i,s),(e+i+s)/3}static validLighting(t){return"unlit"===t||"scene"===t?t:"fixed"}static validSortMode(t){return"distance"===t||"oldestInFront"===t||"youngestInFront"===t?t:"none"}static validCullingMode(t){return"pause"===t||"pauseAndCatchUp"===t?t:"always"}static nonZeroPivot(t){return!t||0===t.x&&0===t.y&&0===t.z?void 0:t.clone()}static nonZeroFlip(t){return t&&(t.x>0||t.y>0)?t.clone():void 0}get softNearFade(){return this.rendererSettings.softNearFade}set softNearFade(t){this.rendererSettings.softNearFade=t,this.neededToUpdateRender=!0}get softFarFade(){return this.rendererSettings.softFarFade}set softFarFade(t){this.rendererSettings.softFarFade=t,this.neededToUpdateRender=!0}get instancingGeometry(){return this.rendererSettings.instancingGeometry}set instancingGeometry(t){this.restart(),this.particles.length=0,this.rendererSettings.instancingGeometry=t,this.neededToUpdateRender=!0}get blending(){return this.rendererSettings.materialBlendMode}set blending(t){this.rendererSettings.materialBlendMode=t,this.neededToUpdateRender=!0}get renderMode(){return this.rendererSettings.renderMode}set renderMode(e){if(this.rendererSettings.renderMode!==e){let i=!1;switch(this.rendererSettings.renderMode===t.RenderMode.Trail&&(i=!0),this.rendererSettings.renderMode===t.RenderMode.Mesh&&(this.startRotation=new Ct(0)),e){case t.RenderMode.Trail:this.rendererEmitterSettings={startLength:new Ct(30),followLocalOrigin:!1},i=!0;break;case t.RenderMode.Mesh:this.rendererEmitterSettings={},this.startRotation=new Nt(new K(0,1,0),new Ct(0));break;case t.RenderMode.StretchedBillBoard:this.rendererEmitterSettings={speedFactor:0,lengthFactor:2};break;case t.RenderMode.BillBoard:case t.RenderMode.VerticalBillBoard:case t.RenderMode.HorizontalBillBoard:case t.RenderMode.Beam:this.rendererEmitterSettings={}}this.rendererSettings.renderMode=e,i&&(this.restart(),this.particles.length=0),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 seed(){return this.seedValue}set seed(t){this.seedValue=t,this.rng=void 0===t?void 0:z(t)}constructor(e){if(this.store=new ze(64),this.emitterVelocity=new K,this.finishedEventFired=!1,this.startDelayTimeLeft=0,this.tempEmitterPos=new K,this.temp=new K,this.pathMatrix=new nt,this.normalMatrix=new pt,this.memory=[],this.listeners={},this.materialRef=null,this.qualityFactor=1,this.simulationAccumulator=0,this.destroyed=!1,this.fusionSteps=[],this.planChangesSize=!0,this.planChangesColor=!0,this.hierarchyScale=new K(1,1,1),this.playbackSpeed=1,this.emissionMultiplier=1,this.cullingMode="always",this.scalingMode="shape",this.motionScale=1,this.alignToDirection=!1,this.culled=!1,this.pendingCatchUp=0,this.boundsMin=new K,this.boundsMax=new K,this.boundsPadding=0,this.boundsValid=!1,this.stepsSinceBounds=0,this.boundsMaxSize=0,this.boundsMaxSpeedSq=0,this.boundsInWorld=!1,this.geometryRadius=1,this.firstTimeUpdate=!0,this.beamEndScratch=new K,this.sceneRef=e.scene,this.layerMaskProxy={mask:e.layerMask??268435455},Object.defineProperty(this.layerMaskProxy,"mask",{enumerable:!0,get:()=>this.rendererSettings.layerMask,set:t=>{this.rendererSettings.layerMask=t,this.neededToUpdateRender=!0}}),this.autoDestroy=e.autoDestroy??!1,this.duration=e.duration??1,this.startDelay=e.startDelay??new Ct(0),this.looping=e.looping??!0,this.prewarm=e.prewarm??!1,this.startLife=e.startLife??new Ct(5),this.startSpeed=e.startSpeed??new Ct(0),this.startRotation=e.startRotation??new Ct(0),this.startSize=e.startSize??new Ct(1),this.startColor=e.startColor??new Yt(new zt(1,1,1,1)),this.emissionOverTime=e.emissionOverTime??new Ct(10),this.emissionOverDistance=e.emissionOverDistance??new Ct(0),this.emissionBursts=e.emissionBursts??[],this.maxParticles=e.maxParticles,this.onlyUsedByOther=e.onlyUsedByOther??!1,this.emitterShape=e.shape??new Ci,this.behaviors=e.behaviors??[],this.worldSpace=e.worldSpace??!1,this.rendererEmitterSettings=e.rendererEmitterSettings??{},e.renderMode===t.RenderMode.StretchedBillBoard){const t=this.rendererEmitterSettings;void 0!==e.speedFactor&&(t.speedFactor=e.speedFactor),t.speedFactor=t.speedFactor??0,t.lengthFactor=t.lengthFactor??0}var i;this.rendererSettings={instancingGeometry:e.instancingGeometry??Ks,instancingIndices:e.instancingIndices??en,instancingUVs:e.instancingUVs??(e.instancingGeometry?(i=e.instancingGeometry,new Float32Array(i.length/3*2)):tn),instancingNormals:e.instancingNormals,renderMode:e.renderMode??t.RenderMode.BillBoard,renderOrder:e.renderOrder??0,uTileCount:e.uTileCount??1,vTileCount:e.vTileCount??1,blendTiles:e.blendTiles??!1,softParticles:e.softParticles??!1,softNearFade:e.softNearFade??0,softFarFade:e.softFarFade??0,materialBlendMode:e.blendMode??r.Constants.ALPHA_ADD,materialTransparent:e.transparent??!0,materialDepthTest:e.depthTest??!0,materialDepthWrite:e.depthWrite??!1,materialAlphaTest:e.alphaTest??0,texture:e.texture??null,reflectionTexture:null,reflectionLevel:1,reflectionFaces:null,reflectionAtlas:null,layerMask:e.layerMask??268435455,pivot:nn.nonZeroPivot(e.pivot),sortMode:nn.validSortMode(e.sortMode),minParticleSize:Math.max(0,e.minParticleSize??0),maxParticleSize:e.maxParticleSize??1/0,renderingGroupId:e.renderingGroupId??0,applyFog:e.applyFog??!0,lighting:nn.validLighting(e.lighting),rim:xs(e.rim),uvScroll:Ms(e.uvScroll),gradientMap:e.gradientMap??null,erosion:bs(e.erosion)},this.flip=nn.nonZeroFlip(e.flip),this.playbackSpeed=e.playbackSpeed??1,this.cullingMode=e.cullingMode??"always",this.scalingMode="hierarchy"===e.scalingMode?"hierarchy":"shape",this.alignToDirection=!0===e.alignToDirection,this.seed=e.seed,this.rendererSettings.renderMode!==t.RenderMode.Mesh||this.rendererSettings.instancingNormals||(this.rendererSettings.instancingNormals=nn.createFallbackNormals(this.rendererSettings.instancingGeometry)),this.materialRef=e.material??null,this.applyMaterialSettings(this.materialRef,{blendMode:e.blendMode,transparent:e.transparent,depthTest:e.depthTest,depthWrite:e.depthWrite,alphaTest:e.alphaTest,texture:e.texture,layerMask:e.layerMask}),this.neededToUpdateRender=!0,this.particles=[],this.startTileIndex=e.startTileIndex||new Ct(0),this.emitter=new As(this,e.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.emissionBursts.forEach(t=>t.count.startGen(this.memory)),this.emissionOverDistance.startGen(this.memory),this.startDelay.startGen(this.memory),this.startDelayTimeLeft=this.startDelay.genValue(this.memory,0),this.emitEnded=!1,this.markForDestroy=!1,this.prewarmed=!1}applyMaterialSettings(t,e={}){if(!this.rendererSettings)return;const i=void 0!==e.texture?e.texture:t?.albedoTexture??t?.diffuseTexture??t?.emissiveTexture??t?.opacityTexture??t?.baseTexture??this.rendererSettings.texture??null,s=t?.reflectionTexture??t?.environmentTexture??this.rendererSettings.reflectionTexture??null,n="number"==typeof s?.level?s.level:1,r=e.blendMode??("number"==typeof t?.alphaMode?t.alphaMode:this.rendererSettings.materialBlendMode),o=e.transparent??("function"==typeof t?.needAlphaBlending?t.needAlphaBlending():"number"==typeof t?.alpha?t.alpha<1:this.rendererSettings.materialTransparent),a=e.depthTest??("boolean"==typeof t?.disableDepthTest?!t.disableDepthTest:this.rendererSettings.materialDepthTest),l=e.depthWrite??("boolean"==typeof t?.disableDepthWrite?!t.disableDepthWrite:"boolean"==typeof t?.forceDepthWrite?t.forceDepthWrite:this.rendererSettings.materialDepthWrite),h=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:this.rendererSettings.materialAlphaTest})();this.rendererSettings.texture=i,this.rendererSettings.reflectionTexture=s,this.rendererSettings.reflectionLevel="number"==typeof t?.reflectionLevel?t.reflectionLevel:n;let c=t?.reflectionAtlas??e.reflectionAtlas??this.rendererSettings.reflectionAtlas??null;!c&&s?.isCube&&(c=Ns(s),!c&&this.sceneRef&&(Ds(s,this.sceneRef,e=>{this.rendererSettings.reflectionAtlas!==e&&(this.rendererSettings.reflectionAtlas=e,t&&null==t.reflectionAtlas&&(t.reflectionAtlas=e),this.neededToUpdateRender=!0)}),c=Ns(s))),this.rendererSettings.reflectionAtlas=c,this.rendererSettings.reflectionFaces=6===t?.reflectionFaces?.length?t.reflectionFaces:null,this.rendererSettings.materialBlendMode=r,this.rendererSettings.materialTransparent=o,this.rendererSettings.materialDepthTest=a,this.rendererSettings.materialDepthWrite=l,this.rendererSettings.materialAlphaTest=h,void 0!==e.layerMask&&(this.rendererSettings.layerMask=e.layerMask),this.neededToUpdateRender=!0}pause(){this.paused=!0}play(){this.paused=!1}stop(){this.restart(),this.pause()}setQualityFactor(t){this.qualityFactor=Math.max(.1,Math.min(1,t))}emissionFactor(){const t=this.emissionMultiplier;return t>=0?this.qualityFactor*t:this.qualityFactor}rebindParticles(){const t=this.particles;for(let e=0;e<t.length;e++)t[e].rebind()}growParticlePool(t){const e=this.particles.length;this.store.ensureCapacity(e+1)&&this.rebindParticles(),this.particles.push(t?new ii(this.store,e):new ti(this.store,e))}spawn(e,i,s){const n=Ws,r=js;s.decompose(n,Qs,r);const o=this.behaviors,a=o.length,l=this.rendererSettings.renderMode,h=l===t.RenderMode.Trail,c=!h,u=l===t.RenderMode.Mesh,d="rotation"===this.startRotation.type,f="vec3function"===this.startSize.type,m=i.time/this.duration,p=h?this.rendererEmitterSettings:void 0,y=Boolean(p?.followLocalOrigin);void 0!==this.maxParticles&&(e=Math.min(e,Math.max(0,this.maxParticles-this.particleNum)));for(let t=0;t<e;t++){i.burstParticleIndex=t,this.particleNum++,this.particles.length<this.particleNum&&this.growParticlePool(h);const e=this.particles[this.particleNum-1];if(e.reset(),e.speedModifier=1,this.finishedEventFired=!1,this.startColor.startGen(e.memory),this.startColor.genColor(e.memory,e.startColor,this.emissionState.time),e.color.copy(e.startColor),this.startSpeed.startGen(e.memory),e.startSpeed=this.startSpeed.genValue(e.memory,m),this.startLife.startGen(e.memory),e.life=this.startLife.genValue(e.memory,m),e.age=0,this.startSize.startGen(e.memory),f)this.startSize.genValue(e.memory,e.startSize,m);else{const t=this.startSize.genValue(e.memory,m);e.startSize.set(t,t,t)}if(this.startTileIndex.startGen(e.memory),e.uvTile=this.startTileIndex.genValue(e.memory),e.size.copy(e.startSize),c){const t=e;if(this.startRotation.startGen(e.memory),u)t.rotation instanceof H||(t.rotation=Gs),t.angularVelocity instanceof H&&t.angularVelocity.set(0,0,0,1),d?this.startRotation.genValue(e.memory,t.rotation,1,m):t.rotation.setFromAxisAngle(Js,this.startRotation.genValue(t.memory,m));else{t.rotation=d?0:this.startRotation.genValue(t.memory,m),t.angularVelocity=0;const e=this.flip;t.flip=void 0===e?0:(b()<e.x?1:0)|(b()<e.y?2:0)}}else if(p){const t=e;p.startLength.startGen(t.memory),t.length=p.startLength.genValue(t.memory,m),t.ensureHistoryCapacity(Math.max(1,Math.ceil(t.length))),t.resetHistory()}this.emitterShape.initialize(e,i),this.alignToDirection&&c&&this.alignParticleToDirection(e,u);const n=i.particle,l=i.inherit;if(void 0!==n&&void 0!==l&&0!==l&&this.inheritFromParent(e,n,l,c),h&&y){const t=e;t.localPosition||(t.localPosition=new K),t.localPosition.copy(t.position)}this.worldSpace?(e.position.applyMatrix4(s),e.startSize.multiply(r).abs(),e.size.copy(e.startSize),"hierarchy"===this.scalingMode?e.velocity.multiply(this.hierarchyScale).applyQuaternion(Qs):e.velocity.multiply(r).applyMatrix3(this.normalMatrix),e.rotation&&e.rotation instanceof H&&e.rotation.multiplyQuaternions(Qs,e.rotation)):this.onlyUsedByOther&&(e.parentMatrix=s);for(let t=0;t<a;t++)o[t].initialize(e,this);this.store.recordMemory(e.storeIndex,e.memory)}}alignParticleToDirection(t,e){const i=t.velocity,s=i.x*i.x+i.y*i.y+i.z*i.z;if(0!==s)if(e){const e=t.rotation;Ws.copy(i).divideScalar(Math.sqrt(s)),Qs.setFromUnitVectors(Js,Ws),e.multiplyQuaternions(Qs,e)}else 0===i.x&&0===i.y||(t.rotation=t.rotation+Math.atan2(-i.x,i.y))}inheritFromParent(t,e,i,s){if(i&ye.color&&(t.startColor.multiply(e.color),t.color.copy(t.startColor)),i&ye.size&&(t.startSize.multiply(e.size),t.size.copy(t.startSize)),i&ye.rotation&&s){const i=t,s=e.rotation;"number"==typeof i.rotation?"number"==typeof s&&(i.rotation+=s):s instanceof H&&i.rotation.multiplyQuaternions(s,i.rotation)}i&ye.lifetime&&e.life>0&&(t.life*=Math.max(0,1-e.age/e.life))}endEmit(){this.emitEnded=!0,this.autoDestroy&&(this.markForDestroy=!0),this.fire({type:"emitEnd",particleSystem:this})}dispose(){this.destroyed||(this.destroyed=!0,this._renderer&&this._renderer.deleteSystem(this),this.emitter.dispose(),this.fire({type:"destroy",particleSystem:this}))}restart(){this.memory.length=0,this.paused=!1,this.particleNum=0,this.boundsValid=!1,this.pendingCatchUp=0,void 0!==this.seedValue&&(this.rng=z(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.behaviors.forEach(t=>t.reset()),this.emitEnded=!1,this.markForDestroy=!1,this.finishedEventFired=!1,this.prewarmed=!1,this.emissionBursts.forEach(t=>t.count.startGen(this.memory)),this.emissionOverDistance.startGen(this.memory),this.startDelay.startGen(this.memory),this.startDelayTimeLeft=this.startDelay.genValue(this.memory,0),this.previousEmitterPos=void 0,this.emitterVelocity.set(0,0,0),this.simulationAccumulator=0,this.destroyed=!1}update(t,e=1/0,i){if(this.paused)return;if(t*=this.playbackSpeed,this.culled)return void("pauseAndCatchUp"===this.cullingMode&&(this.pendingCatchUp=Math.min(2,this.pendingCatchUp+t)));if(this.pendingCatchUp>0&&this.catchUp(i??performance.now()+nn.catchUpBudgetMs),this.firstTimeUpdate&&(this.firstTimeUpdate=!1,this.emitter.computeWorldMatrix(!0)),!this.looping&&this.finishedEventFired&&0===this.particleNum){t>.1&&(t=.1),this.simulationAccumulator+=t;const e=Math.min(8,Math.max(0,Math.round(this.simulationAccumulator/Ys-1e-9)));return void(this.simulationAccumulator-=e*Ys)}if(this.looping&&this.prewarm&&!this.prewarmed){this.prewarmed=!0;for(let t=0;t<60*this.duration;t++)this.update(1/60)}t>.1&&(t=.1),this.neededToUpdateRender&&(this._renderer&&this._renderer.updateSystem(this),this.neededToUpdateRender=!1);const s=this.emitter.matrixWorld.elements;if(this.tempEmitterPos.set(s[12],s[13],s[14]),void 0!==this.previousEmitterPos&&t>0&&this.emitterVelocity.copy(this.tempEmitterPos).sub(this.previousEmitterPos).divideScalar(t),(this.previousEmitterPos??(this.previousEmitterPos=new K)).copy(this.tempEmitterPos),this.startDelayTimeLeft>0&&(!this.prewarm||!this.looping)){if(this.startDelayTimeLeft-=t,this.startDelayTimeLeft>=0)return;t=Math.min(-this.startDelayTimeLeft,.1),this.startDelayTimeLeft=0}this.simulationAccumulator+=t;const n=Math.min(8,Math.max(0,Math.round(this.simulationAccumulator/Ys-1e-9)));for(let t=0;t<n&&(this.simulateStep(Ys),!(e!==1/0&&t+1<n&&performance.now()>=e));t++);this.simulationAccumulator-=n*Ys}catchUp(t){let e=Math.floor(this.pendingCatchUp/Ys);for(this.pendingCatchUp=0;e-- >0&&(this.simulateStep(Ys),!(e>0&&performance.now()>=t)););}storeBounds(e,i,s,n,r,o,a,l,h,c){if(0===e)return void(this.boundsValid=!1);this.stepsSinceBounds=i?0:this.stepsSinceBounds+1,this.boundsMaxSize=h,this.boundsMaxSpeedSq=c;const u=Math.sqrt(c),d=this.rendererSettings.renderMode;let f=u*Ys*(this.stepsSinceBounds+1);if(d===t.RenderMode.Mesh)f+=h*this.meshGeometryRadius();else if(d===t.RenderMode.StretchedBillBoard){const t=this.rendererEmitterSettings;f+=h*(1+(t.lengthFactor??0)+u*(t.speedFactor??0))}else{const t=this.rendererSettings.pivot;f+=h*(.75+(void 0===t?0:Math.abs(t.x)+Math.abs(t.y)+Math.abs(t.z)))}this.boundsMin.set(s,n,r),this.boundsMax.set(o,a,l),this.boundsPadding=f,this.boundsInWorld=this.worldSpace,this.boundsValid=!0}meshGeometryRadius(){const t=this.rendererSettings.instancingGeometry;if(t!==this.geometryRadiusFor){let e=0;for(let i=0;i+2<t.length;i+=3){const s=t[i]*t[i]+t[i+1]*t[i+1]+t[i+2]*t[i+2];s>e&&(e=s)}this.geometryRadius=Math.sqrt(e),this.geometryRadiusFor=t}return this.geometryRadius}getWorldBounds(e,i){if(!this.measureWorldBounds(e,i))return!1;if(this.rendererSettings.renderMode===t.RenderMode.Beam){const t=this.beamEndScratch;if(!this.getBeamEnd(t))return!0;const s=this.boundsInWorld?this.boundsPadding:this.boundsPadding*this.emitterMaxScale();e.set(Math.min(e.x,t.x-s),Math.min(e.y,t.y-s),Math.min(e.z,t.z-s)),i.set(Math.max(i.x,t.x+s),Math.max(i.y,t.y+s),Math.max(i.z,t.z+s))}return!0}getBeamEnd(t){const e=this.beamEnd;if(void 0===e)return!1;const i=e;if("function"==typeof i.getAbsolutePosition){const e=i.getAbsolutePosition();t.set(e.x,e.y,e.z)}else{const i=e;t.set(i.x,i.y,i.z)}return!0}emitterMaxScale(){const t=this.emitter.matrixWorld.elements;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]))}measureWorldBounds(t,e){if(!this.boundsValid)return!1;const i=this.boundsMin,s=this.boundsMax;if(this.boundsInWorld){const n=this.boundsPadding;return t.set(i.x-n,i.y-n,i.z-n),e.set(s.x+n,s.y+n,s.z+n),!0}const n=this.emitter.matrixWorld.elements,r=Math.sqrt(Math.max(n[0]*n[0]+n[1]*n[1]+n[2]*n[2],n[4]*n[4]+n[5]*n[5]+n[6]*n[6],n[8]*n[8]+n[9]*n[9]+n[10]*n[10])),o=this.boundsPadding*r;let a=1/0,l=1/0,h=1/0,c=-1/0,u=-1/0,d=-1/0;for(let t=0;t<8;t++){const e=1&t?s.x:i.x,r=2&t?s.y:i.y,o=4&t?s.z:i.z,f=1/(n[3]*e+n[7]*r+n[11]*o+n[15]),m=(n[0]*e+n[4]*r+n[8]*o+n[12])*f,p=(n[1]*e+n[5]*r+n[9]*o+n[13])*f,y=(n[2]*e+n[6]*r+n[10]*o+n[14])*f;m<a&&(a=m),m>c&&(c=m),p<l&&(l=p),p>u&&(u=p),y<h&&(h=y),y>d&&(d=y)}return t.set(a-o,l-o,h-o),e.set(c+o,u+o,d+o),!0}setWorldBounds(t,e,i,s,n,r,o){this.boundsMin.set(t,e,i),this.boundsMax.set(s,n,r),this.boundsPadding=o,this.boundsInWorld=!0,this.boundsValid=!0}get simulationStep(){return Ys}get simulationResidual(){return this.paused?0:this.simulationAccumulator>Ys?Ys:this.simulationAccumulator<-Ys?-Ys:this.simulationAccumulator}behaviorSteps(){const t=this.behaviors,e=this.fusionPlan;if(void 0!==e&&e.length===t.length){let i=!0;for(let s=0;s<t.length;s++)if(e[s]!==t[s]){i=!1;break}if(i)return this.fusionSteps}this.fusionPlan=t.slice(),this.fusionSteps=vi(t);let i=!1,s=!1;for(let e=0;e<t.length;e++){const n=t[e].type;Xs.has(n)?i=!0:Zs.has(n)?s=!0:Hs.has(n)||(i=!0,s=!0)}return this.planChangesSize=i,this.planChangesColor=s,this.fusionSteps}simulateStep(t){const e=this.rng;if(void 0===e)return void this.stepOnce(t);const i=M(e);try{this.stepOnce(t)}finally{M(i)}}stepOnce(e){this.motionScale=this.measureMotionScale(),this.onlyUsedByOther||this.emit(e,this.emissionState,this.emitter.matrixWorld);const i=this.particles,s=this.behaviors;s.length;const n=this.particleNum,r=this.rendererSettings.renderMode===t.RenderMode.Trail,o=this.rendererSettings.renderMode===t.RenderMode.StretchedBillBoard,a=this.store,l=3*n,h=this.behaviorSteps(),c=this.planChangesSize,u=this.planChangesColor;a.useSizeSnapshot(c),a.useColorSnapshot(u),a.previousPosition.set(a.position.subarray(0,l)),c&&a.previousSize.set(a.size.subarray(0,l)),o&&(a.keepPreviousVelocity()&&this.rebindParticles(),a.previousVelocity.set(a.velocity.subarray(0,l))),u&&a.previousColor.set(a.color.subarray(0,4*n)),this.emitterShape.update(this,e);for(let t=0;t<h.length;t++){const r=h[t],o=r.behaviors;for(let t=0;t<o.length;t++)o[t].frameUpdate(e);if(0===n)continue;if(void 0!==r.run){r.run(s,i,n,e,this.store);continue}const a=o[0];if(void 0===a.updateAll)for(let t=0;t<n;t++){const s=i[t];s.age<s.life&&a.update(s,e)}else a.updateAll(i,n,e)}const d=this.hasListeners("particleDied"),f=this.store,m=f.scalars,p=ze.SCALAR_STRIDE;let y=this.particleNum;if(!r){const t=f.position,s=f.velocity,n=f.previousSize,r=f.size,o=f.previousColor,a=f.color,l=c,h=u,g=this.stepsSinceBounds>=4||!this.boundsValid,v=this.boundsMin,x=this.boundsMax;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,P=g?0:this.boundsMaxSize,T=g?0:this.boundsMaxSpeedSq;for(let c=0;c<y;c++){const u=c*p;let v=m[u+ze.AGE];const x=3*c,O=g||0===v;if(0===v&&(l&&(n[x]=r[x],n[x+1]=r[x+1],n[x+2]=r[x+2]),h)){const t=4*c;o[t]=a[t],o[t+1]=a[t+1],o[t+2]=a[t+2],o[t+3]=a[t+3]}const V=e*m[u+ze.SPEED_MODIFIER],B=s[x],C=s[x+1],A=s[x+2],F=t[x]+B*V,$=t[x+1]+C*V,I=t[x+2]+A*V;if(t[x]=F,t[x+1]=$,t[x+2]=I,O&&(S=Math.min(S,F),M=Math.max(M,F),b=Math.min(b,$),z=Math.max(z,$),w=Math.min(w,I),_=Math.max(_,I),P=Math.max(P,Math.max(r[x],Math.max(r[x+1],r[x+2])))),T=Math.max(T,B*B+C*C+A*A),v+=e,m[u+ze.AGE]=v,v>=m[u+ze.LIFE]){const t=y-1,e=i[c],s=i[t];i[c]=s,i[t]=e,c!==t&&(f.swapRows(c,t),s.setStoreIndex(c),e.setStoreIndex(t)),y--,c--,d&&this.fire({type:"particleDied",particleSystem:this,particle:e})}}return this.particleNum=y,this.storeBounds(y,g,S,b,w,M,z,_,P,T),void this.notifyFinished()}if(n>0){const t=a.previousSize,e=a.size,i=a.previousColor,s=a.color;for(let r=0,o=0,a=0,l=0;r<n;r++,o+=3,a+=4,l+=p)0===m[l+ze.AGE]&&(c&&(t[o]=e[o],t[o+1]=e[o+1],t[o+2]=e[o+2]),u&&(i[a]=s[a],i[a+1]=s[a+1],i[a+2]=s[a+2],i[a+3]=s[a+3]))}if(this.rendererEmitterSettings.followLocalOrigin){const t=this.emitter.matrixWorld;for(let s=0;s<n;s++){const n=i[s];n.localPosition?(n.position.copy(n.localPosition),n.position.applyMatrix4(n.parentMatrix??t)):n.position.addScaledVector(n.velocity,e*n.speedModifier),n.age+=e}}else{const t=f.position,i=f.velocity;for(let s=0,r=0,o=0;s<n;s++,r+=3,o+=p){const s=e*m[o+ze.SPEED_MODIFIER];t[r]+=i[r]*s,t[r+1]+=i[r+1]*s,t[r+2]+=i[r+2]*s,m[o+ze.AGE]+=e}}{const t=this.rendererEmitterSettings,e=t.dieWithParticle,s=t.recordWorldSpace&&!this.worldSpace,r=this.emitter.matrixWorld;for(let t=0;t<n;t++){const n=i[t];if(e&&n.age>=n.life)n.resetHistory();else if(n.update(),s&&n.age<=n.life){const t=(n.historyHead+n.historyCapacity-1)%n.historyCapacity*3,e=n.historyPositions;Ws.set(e[t],e[t+1],e[t+2]),Ws.applyMatrix4(n.parentMatrix??r),e[t]=Ws.x,e[t+1]=Ws.y,e[t+2]=Ws.z}}}for(let t=0;t<y;t++){const e=i[t],s=t*p;if(m[s+ze.AGE]>=m[s+ze.LIFE]&&0===e.historyCount){const s=y-1,n=i[s];i[t]=n,i[s]=e,t!==s&&(f.swapRows(t,s),n.setStoreIndex(t),e.setStoreIndex(s)),y--,t--,d&&this.fire({type:"particleDied",particleSystem:this,particle:e})}}this.particleNum=y,this.notifyFinished()}notifyFinished(){this.isFinished()&&(this.finishedEventFired||(this.finishedEventFired=!0,this.fire({type:"finished",particleSystem:this})),this.autoDestroy&&(this.markForDestroy=!0,this.dispose()))}static burstWaveCount(t){return t.cycle>=1?Math.floor(t.cycle):1}static burstInterval(t){return t.interval>0?t.interval:0}emitBursts(t,e){const i=this.emissionBursts,s=i.length,n=t.time,r=t.burstWaves??(t.burstWaves=[]);for(;t.burstIndex<s&&i[t.burstIndex].time<=n;)r[t.burstIndex]=0,t.burstIndex++;const o=t.burstIndex;for(let s=0;s<o;s++){const o=i[s],a=nn.burstWaveCount(o);let l=r[s]??0;if(l>=a)continue;const h=nn.burstInterval(o);for(;l<a;){const i=o.time+l*h;if(l>0&&i>this.duration){l=a;break}if(i>n)break;t.burstWaveIndex=l,this.fireBurstWave(o,t,e),l++}r[s]=l}}fireBurstWave(t,e,i){if(b()>=t.probability)return;const s=t.count.genValue(this.memory,this.time),n=this.emissionFactor(),r=Math.abs(n-1)<.001?s:Math.floor(s*n+b());e.isBursting=!0,e.burstParticleCount=r,this.spawn(r,e,i),e.isBursting=!1}hasPendingBurstWaves(t){const e=t.burstWaves;if(void 0===e)return!1;const i=this.emissionBursts;for(let s=0;s<t.burstIndex&&s<i.length;s++){const t=i[s],n=e[s]??0;if(n<nn.burstWaveCount(t)&&(0===n||t.time+n*nn.burstInterval(t)<=this.duration))return!0}return!1}spawnAlongPath(t,e,i,s,n,r,o){const a=this.pathMatrix.copy(i),l=i.elements,h=a.elements,c=l[12],u=l[13],d=l[14];for(let i=1;i<=t;i++){const t=i*r-n,l=t<=0?0:t>=o?1:t/o;h[12]=s.x+(c-s.x)*l,h[13]=s.y+(u-s.y)*l,h[14]=s.z+(d-s.z)*l,this.spawn(1,e,a)}}emit(t,e,i){const s=this.emitEnded&&e===this.emissionState;if(e.time>this.duration)if(this.looping){e.time-=this.duration,e.burstIndex=0,void 0!==e.burstWaves&&(e.burstWaves.length=0);for(let t=0;t<this.behaviors.length;t++)this.behaviors[t].reset()}else this.emitEnded||this.onlyUsedByOther||this.endEmit();this.worldSpace&&this.normalMatrix.getNormalMatrix(i);const n=this.emissionBursts.length,r=this.emissionFactor();n>0&&!s&&this.emitBursts(e,i);let o=0,a=0,l=0,h=0;const c=e.previousWorldPos;if(!this.emitEnded){const s=e.time/this.duration;if(e.waitEmiting+=t*this.emissionOverTime.genValue(this.memory,s)*r,void 0!==c){this.temp.set(i.elements[12],i.elements[13],i.elements[14]),h=c.distanceTo(this.temp),l=e.travelDistance,e.travelDistance+=h;const t=this.emissionOverDistance.genValue(this.memory,s)*r;if(e.travelDistance*t>0){const i=Math.floor(e.travelDistance*t);e.travelDistance-=i/t,this.worldSpace&&h>0?(o=i,a=1/t):e.waitEmiting+=i}}}const u=Math.floor(e.waitEmiting);u>0&&(this.spawn(u,e,i),e.waitEmiting-=u),o>0&&this.spawnAlongPath(o,e,i,c,l,a,h),void 0===e.previousWorldPos&&(e.previousWorldPos=new K),e.previousWorldPos.set(i.elements[12],i.elements[13],i.elements[14]),e.time+=t}toJSON(t,e={}){const i=void 0===t||"string"==typeof t?{geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}}:t,s=this.ensureGeometryMeta(i),n=this.ensureMaterialMeta(i),r=this.toRendererSettingsJSON();return{version:"3.0",autoDestroy:this.autoDestroy,looping:this.looping,prewarm:this.prewarm,duration:this.duration,startDelay:this.startDelay.toJSON(),shape:this.emitterShape.toJSON(),startLife:this.startLife.toJSON(),startSpeed:this.startSpeed.toJSON(),startRotation:this.startRotation.toJSON(),startSize:this.startSize.toJSON(),startColor:this.startColor.toJSON(),emissionOverTime:this.emissionOverTime.toJSON(),emissionOverDistance:this.emissionOverDistance.toJSON(),emissionBursts:this.emissionBursts.map(t=>({time:t.time,count:t.count.toJSON(),probability:t.probability,interval:t.interval,cycle:t.cycle})),...void 0!==this.maxParticles?{maxParticles:this.maxParticles}:{},onlyUsedByOther:this.onlyUsedByOther,instancingGeometry:s,renderMode:this.renderMode,renderOrder:this.renderOrder,...0!==this.renderingGroupId?{renderingGroupId:this.renderingGroupId}:{},...this.applyFog?{}:{applyFog:!1},...1!==this.playbackSpeed?{playbackSpeed:this.playbackSpeed}:{},..."always"!==this.cullingMode?{cullingMode:this.cullingMode}:{},..."shape"!==this.scalingMode?{scalingMode:this.scalingMode}:{},...void 0!==this.seedValue?{seed:this.seedValue}:{},..."none"!==this.sortMode?{sortMode:this.sortMode}:{},...this.alignToDirection?{alignToDirection:!0}:{},...this.minParticleSize>0?{minParticleSize:this.minParticleSize}:{},...this.maxParticleSize!==1/0?{maxParticleSize:this.maxParticleSize}:{},rendererEmitterSettings:r,material:n,layers:this.rendererSettings.layerMask,startTileIndex:this.startTileIndex.toJSON(),uTileCount:this.rendererSettings.uTileCount,vTileCount:this.rendererSettings.vTileCount,blendTiles:this.rendererSettings.blendTiles,softParticles:this.rendererSettings.softParticles,softFarFade:this.rendererSettings.softFarFade,softNearFade:this.rendererSettings.softNearFade,blending:this.rendererSettings.materialBlendMode,transparent:this.rendererSettings.materialTransparent,depthTest:this.rendererSettings.materialDepthTest,depthWrite:this.rendererSettings.materialDepthWrite,alphaTest:this.rendererSettings.materialAlphaTest,behaviors:this.behaviors.map(t=>t.toJSON()),worldSpace:this.worldSpace,...this.pivot?{pivot:[this.pivot.x,this.pivot.y,this.pivot.z]}:{},...this.flip?{flip:[this.flip.x,this.flip.y]}:{}}}static fromJSON(e,i,s={},n){const o=$i(e.shape,i);let a;if(e.renderMode===t.RenderMode.Trail){const t=e.rendererEmitterSettings;a={startLength:void 0!==t?.startLength?Et(t.startLength):new Ct(30),followLocalOrigin:t?.followLocalOrigin??!1,...sn(t)}}else e.renderMode===t.RenderMode.StretchedBillBoard?(a={...e.rendererEmitterSettings??{}},void 0!==e.speedFactor&&(a.speedFactor=e.speedFactor)):a={};const l=e.material?i.materials?.[e.material]:void 0,h=l?.texture??e.texture,c="string"==typeof h?i.textures?.[h]??null:h??null,u=t=>"string"==typeof t?i.textures?.[t]??null:t??null,d=l?.erosion,f="string"==typeof e.instancingGeometry?i.geometries?.[e.instancingGeometry]:e.instancingGeometry,m=nn.resolveGeometryData(f),p=new nn({scene:n,autoDestroy:e.autoDestroy,looping:e.looping,prewarm:e.prewarm,duration:e.duration,startDelay:e.startDelay?Et(e.startDelay):void 0,shape:o,startLife:Et(e.startLife),startSpeed:Et(e.startSpeed),startRotation:ie(e.startRotation),startSize:ie(e.startSize),startColor:Xt(e.startColor),emissionOverTime:Et(e.emissionOverTime),emissionOverDistance:Et(e.emissionOverDistance),emissionBursts:e.emissionBursts?.map(t=>({time:t.time,count:"number"==typeof t.count?new Ct(t.count):Et(t.count),probability:t.probability??1,interval:t.interval??.1,cycle:t.cycle??t.cycleCount??1})),maxParticles:"number"==typeof e.maxParticles?e.maxParticles:void 0,onlyUsedByOther:e.onlyUsedByOther,instancingGeometry:m.positions,instancingIndices:m.indices,instancingUVs:m.uvs,instancingNormals:m.normals,renderMode:e.renderMode,rendererEmitterSettings:a,renderOrder:e.renderOrder,renderingGroupId:"number"==typeof e.renderingGroupId?e.renderingGroupId:void 0,applyFog:!1!==e.applyFog,playbackSpeed:"number"==typeof e.playbackSpeed?e.playbackSpeed:void 0,cullingMode:nn.validCullingMode(e.cullingMode),scalingMode:"hierarchy"===e.scalingMode?"hierarchy":"shape",seed:"number"==typeof e.seed?e.seed:void 0,sortMode:nn.validSortMode(e.sortMode),alignToDirection:!0===e.alignToDirection,minParticleSize:"number"==typeof e.minParticleSize?e.minParticleSize:void 0,maxParticleSize:"number"==typeof e.maxParticleSize?e.maxParticleSize:void 0,texture:c,material:l?.sourceMaterial??l,blendMode:l?.alphaMode??e.blending??r.Constants.ALPHA_ADD,transparent:l?.transparent??e.transparent??!0,depthTest:l?.depthTest??e.depthTest??!0,depthWrite:l?.depthWrite??e.depthWrite??!1,alphaTest:l?.alphaTest??e.alphaTest??0,startTileIndex:"number"==typeof e.startTileIndex?new Ct(e.startTileIndex):Et(e.startTileIndex),uTileCount:e.uTileCount,vTileCount:e.vTileCount,blendTiles:e.blendTiles,softParticles:e.softParticles,softFarFade:e.softFarFade,softNearFade:e.softNearFade,behaviors:[],worldSpace:e.worldSpace,layerMask:e.layers,pivot:e.pivot?new K(e.pivot[0]??0,e.pivot[1]??0,e.pivot[2]??0):void 0,flip:e.flip?new St(e.flip[0]??0,e.flip[1]??0):void 0,lighting:l?.lighting,rim:l?.rim,uvScroll:l?.uvScroll,gradientMap:u(l?.gradientMap),erosion:d&&"object"==typeof d?{...d,mask:u(d.mask)}:void 0});return p.behaviors=(e.behaviors??[]).map(t=>{const e=ri(t,p);return e&&"EmitSubParticleSystem"===e.type&&(s[t.subParticleSystem]=e),e}).filter(t=>null!==t),p}static nextSerializationId(t){return nn.serializationCounter+=1,`${t}_${nn.serializationCounter}`}static createFallbackNormals(t){const e=new Float32Array(t.length);for(let t=0;t<e.length;t+=3)e[t]=0,e[t+1]=0,e[t+2]=1;return e}toRendererSettingsJSON(){return this.renderMode===t.RenderMode.Trail?{startLength:this.rendererEmitterSettings.startLength.toJSON(),followLocalOrigin:this.rendererEmitterSettings.followLocalOrigin,...sn(this.rendererEmitterSettings)}:this.renderMode===t.RenderMode.StretchedBillBoard?{speedFactor:this.rendererEmitterSettings.speedFactor,lengthFactor:this.rendererEmitterSettings.lengthFactor}:{}}ensureGeometryMeta(t){const e=nn.nextSerializationId("quarks_geometry");return t.geometries[e]={uuid:e,type:"QuarksGeometry",positions:Array.from(this.rendererSettings.instancingGeometry),indices:Array.from(this.rendererSettings.instancingIndices),uvs:this.rendererSettings.instancingUVs?Array.from(this.rendererSettings.instancingUVs):void 0,normals:this.rendererSettings.instancingNormals?Array.from(this.rendererSettings.instancingNormals):void 0},e}ensureMaterialMeta(t){const e=this.rendererSettings.texture;let i;e&&(i=nn.nextSerializationId("quarks_texture"),t.textures[i]=e);const s=this.rendererSettings.reflectionAtlas;let n;s instanceof g.Texture&&(n=nn.nextSerializationId("quarks_texture"),t.textures[n]=s);const r=e=>{if(!(e instanceof g.Texture))return;const i=nn.nextSerializationId("quarks_texture");return t.textures[i]=e,i},o=this.erosion,a=nn.nextSerializationId("quarks_material");return t.materials[a]={uuid:a,type:"QuarksMaterial",transparent:this.rendererSettings.materialTransparent,alphaMode:this.rendererSettings.materialBlendMode,depthTest:this.rendererSettings.materialDepthTest,depthWrite:this.rendererSettings.materialDepthWrite,alphaTest:this.rendererSettings.materialAlphaTest,texture:i,reflectionAtlas:n,reflectionLevel:this.rendererSettings.reflectionLevel,..."fixed"!==this.lighting?{lighting:this.lighting}:{},...this.rim?{rim:{...this.rim,color:[...this.rim.color]}}:{},...this.uvScroll?{uvScroll:[...this.uvScroll]}:{},...this.gradientMap?{gradientMap:r(this.gradientMap)}:{},...o?{erosion:{mask:r(o.mask),softness:o.softness,edgeWidth:o.edgeWidth,edgeColor:[...o.edgeColor],maskScroll:[...o.maskScroll]}}:{},sourceMaterial:this.materialRef??void 0},a}static resolveGeometryData(t){if(t?.positions){const e=t.positions instanceof Float32Array?t.positions:new Float32Array(t.positions);return{positions:e,indices:ks(e,t.indices instanceof Uint16Array||t.indices instanceof Uint32Array?t.indices:t.indices?new Uint32Array(t.indices):void 0),uvs:t.uvs?t.uvs instanceof Float32Array?t.uvs:new Float32Array(t.uvs):void 0,normals:t.normals?t.normals instanceof Float32Array?t.normals:new Float32Array(t.normals):void 0}}const e=t?.data??t;if(e?.attributes?.position?.array){const t=new Float32Array(e.attributes.position.array);let i;if(e.index?.array){i=new("Uint16Array"===e.index.type?Uint16Array:Uint32Array)(e.index.array)}return{positions:t,indices:ks(t,i),uvs:e.attributes.uv?.array?new Float32Array(e.attributes.uv.array):void 0,normals:e.attributes.normal?.array?new Float32Array(e.attributes.normal.array):void 0}}return{positions:Ks,indices:en,uvs:tn}}addBehavior(t){this.behaviors.push(t),this._renderer?._invalidateUpdateOrder()}getRendererSettings(){return this.rendererSettings}addEventListener(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}removeAllEventListeners(t){this.listeners[t]&&(this.listeners[t]=[])}removeEventListener(t,e){if(this.listeners[t]){const i=this.listeners[t].indexOf(e);-1!==i&&this.listeners[t].splice(i,1)}}hasListeners(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 i=0;i<e.length;i++)e[i](t)}clone(){const e=this.behaviors.map(t=>t.clone());let i;i=this.renderMode===t.RenderMode.Trail?{startLength:this.rendererEmitterSettings.startLength.clone(),followLocalOrigin:this.rendererEmitterSettings.followLocalOrigin,...sn(this.rendererEmitterSettings)}:this.renderMode===t.RenderMode.StretchedBillBoard?{lengthFactor:this.rendererEmitterSettings.lengthFactor,speedFactor:this.rendererEmitterSettings.speedFactor}:{};const s=new nn({autoDestroy:this.autoDestroy,looping:this.looping,prewarm:this.prewarm,duration:this.duration,startDelay:this.startDelay.clone(),shape:this.emitterShape.clone(),startLife:this.startLife.clone(),startSpeed:this.startSpeed.clone(),startRotation:this.startRotation.clone(),startSize:this.startSize.clone(),startColor:this.startColor.clone(),emissionOverTime:this.emissionOverTime.clone(),emissionOverDistance:this.emissionOverDistance.clone(),emissionBursts:this.emissionBursts.map(t=>({...t})),maxParticles:this.maxParticles,onlyUsedByOther:this.onlyUsedByOther,instancingGeometry:this.rendererSettings.instancingGeometry,instancingIndices:this.rendererSettings.instancingIndices,instancingUVs:this.rendererSettings.instancingUVs,instancingNormals:this.rendererSettings.instancingNormals,renderMode:this.renderMode,renderOrder:this.renderOrder,renderingGroupId:this.renderingGroupId,applyFog:this.applyFog,playbackSpeed:this.playbackSpeed,cullingMode:this.cullingMode,scalingMode:this.scalingMode,seed:this.seedValue,sortMode:this.sortMode,alignToDirection:this.alignToDirection,minParticleSize:this.minParticleSize,maxParticleSize:this.maxParticleSize,rendererEmitterSettings:i,material:this.materialRef,texture:this.rendererSettings.texture,startTileIndex:this.startTileIndex,uTileCount:this.rendererSettings.uTileCount,vTileCount:this.rendererSettings.vTileCount,blendTiles:this.rendererSettings.blendTiles,softParticles:this.rendererSettings.softParticles,softFarFade:this.rendererSettings.softFarFade,softNearFade:this.rendererSettings.softNearFade,behaviors:e,worldSpace:this.worldSpace,blendMode:this.rendererSettings.materialBlendMode,transparent:this.rendererSettings.materialTransparent,depthTest:this.rendererSettings.materialDepthTest,depthWrite:this.rendererSettings.materialDepthWrite,alphaTest:this.rendererSettings.materialAlphaTest,layerMask:this.rendererSettings.layerMask,pivot:this.pivot,flip:this.flip,lighting:this.lighting,rim:this.rim,uvScroll:this.uvScroll,gradientMap:this.gradientMap,erosion:this.erosion,scene:this.emitter.getScene()});for(const t of e)t instanceof ve&&(t.particleSystem=s);return s}}nn.serializationCounter=0,nn.catchUpBudgetMs=2;class rn extends n.TransformNode{constructor(t="QuarksPrefab",e){super(t,e),this.type="QuarksPrefab",this.animationData=[],this.isPlaying=!1,this.currentTime=-1e-5,this.timeScale=1,this.duration=0,this._lastUpdateTimeMs=Date.now(),this._tempAnimationJSON=[]}registerBatchedRenderer(t){this._batchedRenderer=t}addParticleSystemAnimation(t,e=0,i=0,s=!1){const n={startTime:e,duration:i>0?i:t.system.duration,type:"ps",loop:s,target:t};return this.animationData.push(n),this.pause(),this.updateDuration(),n}addThreeAnimation(t,e,i=0,s=e?.duration??0,n=!1,r){const o={startTime:i,duration:s>0?s: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){this.animationData.splice(t,1),this.updateDuration()}play(){this.isPlaying||(this.isPlaying=!0,this._lastUpdateTimeMs=Date.now())}pause(){this.isPlaying&&(this.isPlaying=!1,this.animationData.forEach(t=>{"ps"===t.type&&t.target instanceof As?t.target.system.pause():t.clip?.pause?.()}))}stop(){this.pause(),this.currentTime=-1e-5,this.animationData.forEach(t=>{"ps"===t.type&&t.target instanceof As?t.target.system.stop():t.clip?.stop?.()})}update(t){if(!this.isPlaying)return;const e=Date.now(),i=t??Math.max((e-this._lastUpdateTimeMs)/1e3,0);this._lastUpdateTimeMs=e;const s=this.currentTime;this.currentTime+=i*this.timeScale,this.currentTime>this.duration?this.stop():this.animationData.forEach(t=>{const e=t.startTime,i=t.startTime+t.duration,n=this.currentTime>=e&&this.currentTime<=i,r=s>=e&&s<=i;if(!n||r){if(!n&&r){if(t.loop&&"ps"===t.type&&t.target instanceof As)return void t.target.system.restart();"ps"===t.type&&t.target instanceof As?t.target.system.endEmit():t.loop?t.clip?.play?.():t.clip?.stop?.()}}else"ps"===t.type&&t.target instanceof As?(t.target.system.restart(),this._batchedRenderer&&this._batchedRenderer.addSystem(t.target.system)):t.clip?.play?.()})}setTime(t){const e=this.currentTime;this.currentTime=t,this.animationData.forEach(i=>{const s=i.startTime,n=i.startTime+i.duration,r=this.currentTime>=s&&this.currentTime<n,o=e>=s&&e<n;!r||o?r||!o?r&&"three"===i.type&&i.clip?.setTime?.(Math.max(t-s,0)):"ps"===i.type&&i.target instanceof As?i.target.system.endEmit():i.clip?.stop?.():"ps"===i.type&&i.target instanceof As?i.target.system.restart():i.clip?.play?.()})}getDuration(){return this.duration}resolveReferences(t){const e={},i=t=>{t._quarksUUID&&(e[t._quarksUUID]=t),e[t.uniqueId.toString()]=t;const s=t.getChildren();for(const t of s)t instanceof n.TransformNode&&i(t)};i(t),this._tempAnimationJSON.forEach(t=>{const i=e[t.targetUUID];if("ps"===t.type&&i instanceof As)this.addParticleSystemAnimation(i,t.startTime,t.duration,t.loop);else if("three"===t.type&&i){const e=this.resolveTimelineClip(i,t.clipUUID);this.addThreeAnimation(i,e,t.startTime,t.duration,t.loop,t.clipUUID)}}),this.updateDuration(),this._tempAnimationJSON=[]}toJSON(){return{type:this.type,name:this.name,animationData:this.animationData.map(t=>({startTime:t.startTime,duration:t.duration,type:t.type,targetUUID:t.target._quarksUUID??t.target.uniqueId.toString(),clipUUID:"three"===t.type?t.clipUUID??t.clip?.uuid:void 0,loop:t.loop}))}}static fromJSON(t,e){const i=new rn(t.name||"QuarksPrefab",e);return Array.isArray(t.animationData)&&(i._tempAnimationJSON=t.animationData.filter(t=>"ps"===t?.type||"three"===t?.type)),i}resolveTimelineClip(t,e){const i=[t.animations,t.animationGroups,t.metadata?.animations,t.metadata?.animationGroups];for(const t of i){if(!Array.isArray(t))continue;if(!e)return t[0];const i=t.find(t=>t?.uuid===e);if(i)return i}}updateDuration(){let t=0;this.animationData.forEach(e=>{const i=e.startTime+e.duration;i>t&&(t=i)}),this.duration=t}}const on=new WeakMap,an=new WeakMap,ln=new WeakMap;function hn(t,e){let i=t.get(e);return void 0===i&&(i=new Map,t.set(e,i)),i}class cn{constructor(t,e={}){this.scene=t,this.options=e}async load(t){const{json:e,baseUrl:i}=await this.fetchEffectDocument(t);return this.loadFromJSON(e,i)}async loadFromJSON(t,e){const i=e??this.options.baseUrl??"";return await this.resolveResources(t,i),this.parse(t,i)}async loadAll(t,e={}){const i=await cn.mapPool(t,e.concurrency,async(i,s)=>{try{return await this.fetchEffectDocument(i)}catch(n){if(!e.continueOnError)throw n;return console.warn(`[QuarksLoader] Failed to fetch effect "${i}" (${s+1}/${t.length}):`,n),null}});return this.loadDocuments(i,e)}async loadFromJSONAll(t,e={}){const i=t.map(t=>{if(null!==t&&"object"==typeof t&&"json"in t){const e=t;return{json:e.json,baseUrl:e.baseUrl??this.options.baseUrl??""}}return{json:t,baseUrl:this.options.baseUrl??""}});return this.loadDocuments(i,e)}async resolveResources(t,e=""){await cn.resolveLinkedResources(t,{baseUrl:e,resolver:this.options.resolver,scene:this.scene})}static async resolveLinkedResources(t,e={}){const i=e.baseUrl??"",s=e.resolver,n=e.scene;await cn.inlineGeometryEntries(t,async t=>{const e=await cn.resolveWith(s,t,"geometry",i);return cn.fetchJsonWith(s,e,n)});const r=Array.isArray(t?.images)?t.images:[];await Promise.all(r.map(async t=>{"string"==typeof t?.url&&t.url&&(t.url=await cn.resolveWith(s,t.url,"image",i))}))}static async resolveExternalGeometries(t,e){await cn.inlineGeometryEntries(t,e)}parse(t,e=""){const i={textures:{},geometries:{},materials:{}};t.geometries&&this.parseGeometries(t.geometries,i),t.images&&this.parseImages(t.images,e,i),t.textures&&this.parseTextures(t.textures,i),t.materials&&this.parseMaterials(t.materials,i);const s=this.parseObject(t.object,i);return this.linkReferences(s),s}parseGeometries(t,e){for(const i of t)if("PlaneGeometry"===i.type){const t=(i.width||1)/2,s=(i.height||1)/2;e.geometries[i.uuid]={positions:new Float32Array([-t,-s,0,t,-s,0,t,s,0,-t,s,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"===i.type)e.geometries[i.uuid]=this.parseSphereGeometry(i);else if("BufferGeometry"===i.type&&i.data){const t=this.parseBufferGeometry(i.data);e.geometries[i.uuid]=t}else"QuarksGeometry"===i.type&&("string"!=typeof i.url||i.positions||console.warn(`[QuarksLoader] Geometry "${i.url}" is an external file; use load(), loadFromJSON(), or resolveResources() before parse().`),e.geometries[i.uuid]=this.share({positions:new Float32Array(i.positions??[]),indices:i.indices?new Uint32Array(i.indices):new Uint32Array(0),uvs:i.uvs?new Float32Array(i.uvs):void 0,normals:i.normals?new Float32Array(i.normals):void 0}))}share(t){if(!1===this.options.shareResources)return t;const e=hn(an,this.scene),i=function(t){let e=2166136261,i=2654435769;const s=[t.positions,t.indices,t.uvs,t.normals];let n="";for(const t of s){if(void 0===t){n+="-,";continue}const s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n+=s.length+",";for(let t=0;t<s.length;t++)e=Math.imul(e^s[t],16777619),i=Math.imul(i^s[t],1540483477)^i>>>15}return`${n}${(e>>>0).toString(16)}${(i>>>0).toString(16)}`}(t),s=e.get(i);return void 0!==s?s:(e.set(i,t),t)}static clearSharedResources(t){on.delete(t),an.delete(t),ln.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,i=Math.max(3,Math.floor(t.widthSegments??16)),s=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,l=[],h=[],c=[],u=[],d=[];let f=0;for(let t=0;t<=s;t++){const u=[],m=t/s,p=o+m*a;for(let t=0;t<=i;t++){const s=t/i,o=n+s*r,a=-e*Math.cos(o)*Math.sin(p),d=e*Math.cos(p),y=e*Math.sin(o)*Math.sin(p);l.push(a,d,y);const g=Math.hypot(a,d,y)||1;h.push(a/g,d/g,y/g),c.push(s,1-m),u.push(f++)}d.push(u)}const m=o<=0,p=o+a>=Math.PI;for(let t=0;t<s;t++)for(let e=0;e<i;e++){const i=d[t][e+1],n=d[t][e],r=d[t+1][e],o=d[t+1][e+1];0===t&&m||u.push(i,n,o),t===s-1&&p||u.push(n,r,o)}const y=l.length/3>65535?new Uint32Array(u):new Uint16Array(u);return{positions:new Float32Array(l),indices:y,uvs:new Float32Array(c),normals:new Float32Array(h)}}parseBufferGeometry(t){let e,i,s=new Float32Array(0),n=new Uint32Array(0);if(t.interleavedBuffers&&t.arrayBuffers){const n={};for(const[e,i]of Object.entries(t.interleavedBuffers)){const s=t.arrayBuffers[i.buffer];if(s){const t=new Float32Array(Array.isArray(s)?this.int32ArrayToFloat32(s):s);n[e]={data:t,stride:i.stride}}}if(t.attributes){if(t.attributes.position?.isInterleavedBufferAttribute){const e=t.attributes.position,i=n[e.data];i&&(s=this.extractInterleavedAttribute(i.data,i.stride,e.offset,e.itemSize))}if(t.attributes.uv?.isInterleavedBufferAttribute){const i=t.attributes.uv,s=n[i.data];s&&(e=this.extractInterleavedAttribute(s.data,s.stride,i.offset,i.itemSize))}if(t.attributes.normal?.isInterleavedBufferAttribute){const e=t.attributes.normal,s=n[e.data];s&&(i=this.extractInterleavedAttribute(s.data,s.stride,e.offset,e.itemSize))}}}else t.attributes&&(t.attributes.position?.array&&(s=new Float32Array(t.attributes.position.array)),t.attributes.uv?.array&&(e=new Float32Array(t.attributes.uv.array)),t.attributes.normal?.array&&(i=new Float32Array(t.attributes.normal.array)));return t.index&&(n="Uint16Array"===t.index.type?new Uint16Array(t.index.array):new Uint32Array(t.index.array)),n=ks(s,n),{positions:s,indices:n,uvs:e,normals:i}}extractInterleavedAttribute(t,e,i,s){const n=Math.floor(t.length/e),r=new Float32Array(n*s);for(let o=0;o<n;o++)for(let n=0;n<s;n++)r[o*s+n]=t[o*e+i+n];return r}int32ArrayToFloat32(t){const e=new ArrayBuffer(4*t.length),i=new Int32Array(e);for(let e=0;e<t.length;e++)i[e]=t[e];return new Float32Array(e)}async resolveResourceUrl(t,e,i){return cn.resolveWith(this.options.resolver,t,e,i)}async fetchEffectDocument(t){const e=this.options.baseUrl||t.substring(0,t.lastIndexOf("/")+1),i=await this.resolveResourceUrl(t,"effect",e);return{json:await cn.fetchJsonWith(this.options.resolver,i,void 0),baseUrl:e}}async loadDocuments(t,e){const i=t.length;if(0===i)return[];const s=new Array(i),n=new Array(i).fill(!1);let r=0;const o=(t,o)=>{n[t]||(n[t]=!0,s[t]=o,r++,e.onProgress?.(r,i))};await 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,o(n,null)}}));for(let s=0;s<i;s++){if(n[s])continue;const r=t[s];if(r)try{o(s,this.parse(r.json,r.baseUrl))}catch(t){if(!e.continueOnError)throw t;console.warn(`[QuarksLoader] Failed to parse effect ${s+1}/${i}:`,t),o(s,null)}else o(s,null)}return s}static async mapPool(t,e,i){if(0===t.length)return[];const s=void 0!==e&&e>0?e:t.length,n=new Array(t.length);let r=0;const o=Math.min(s,t.length);return await Promise.all(Array.from({length:o},()=>(async()=>{for(;r<t.length;){const e=r++;n[e]=await i(t[e],e)}})())),n}static async resolveWith(t,e,i,s){return t?.resolve?t.resolve(e,i,s):cn.joinUrl(s,e)}static fetchJsonWith(t,e,i){const s=async()=>{if(t?.fetchJson)return t.fetchJson(e);const i=await fetch(e);if(!i.ok)throw new Error(`HTTP ${i.status}`);return i.json()};if(!i)return s();const n=hn(ln,i),r=`json|${e}`;let o=n.get(r);return void 0===o&&(o=s().catch(t=>{throw n.get(r)===o&&n.delete(r),t}),n.set(r,o)),o}static async inlineGeometryEntries(t,e){const i=Array.isArray(t?.geometries)?t.geometries:[];await Promise.all(i.filter(t=>"string"==typeof t?.url&&!t.positions).map(async t=>{try{const i=await e(t.url);for(const e of["positions","indices","uvs","normals"]){const s=i?.[e];void 0!==s&&(t[e]=Array.isArray(s)?s.slice():s)}delete t.url}catch(e){console.warn(`[QuarksLoader] Could not load geometry "${t.url}":`,e)}}))}parseImages(t,e,i){this._images={};for(const i of t)i.url&&cn.warnIfNotAnImageUrl(i.url),this._images[i.uuid]=i.url?cn.joinUrl(e,i.url):null}static warnIfNotAnImageUrl(t){/^(data|blob):/i.test(t)||/\.(png|jpe?g|webp|gif|bmp|ktx2?|dds|env|basis)(\?|#|$)/i.test(t)||console.warn(`[QuarksLoader] 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){const i=this._images||{};for(const s of t){const t=i[s.image];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?hn(on,this.scene):void 0,l=a?.get(o);if(void 0!==l){e.textures[s.uuid]=l;continue}const h=new g.Texture(t,this.scene,{noMipmap:n,invertY:i,samplingMode:"number"==typeof s.samplingMode?s.samplingMode:void 0});Array.isArray(s.wrap)&&(h.wrapU=this.mapWrapMode(s.wrap[0]),h.wrapV=this.mapWrapMode(s.wrap[1]??s.wrap[0])),Array.isArray(s.repeat)&&(h.uScale=s.repeat[0]??1,h.vScale=s.repeat[1]??1),Array.isArray(s.offset)&&(h.uOffset=s.offset[0]??0,h.vOffset=s.offset[1]??0),"number"==typeof s.rotation&&(h.wAng=s.rotation),void 0!==a&&(a.set(o,h),h.onDisposeObservable.addOnce(()=>{a.get(o)===h&&a.delete(o)})),e.textures[s.uuid]=h}else e.textures[s.uuid]=null}}mapWrapMode(t){switch(t){case 1001:return g.Texture.CLAMP_ADDRESSMODE;case 1002:return g.Texture.MIRROR_ADDRESSMODE;default:return g.Texture.WRAP_ADDRESSMODE}}parseMaterials(t,e){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},s=i.map??i.texture;s&&(t.texture=e.textures[s]||null);const n=i.reflectionAtlas;if(n&&(t.reflectionAtlas=e.textures[n]||null),"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),Array.isArray(i.uvScroll)&&(t.uvScroll=i.uvScroll),i.gradientMap&&(t.gradientMap=e.textures[i.gradientMap]||null),i.erosion&&"object"==typeof i.erosion&&(t.erosion={...i.erosion,mask:i.erosion.mask&&e.textures[i.erosion.mask]||null}),"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]||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 i=Array.isArray(e)?e[0]:e;return t.materials[i]}createPlaceholderNode(t,e){const i=new n.TransformNode(e||t||"node",this.scene);return i.quarksOriginalType=t,i}createMeshNode(t,e){const i=new h.Mesh(t.name||t.type||"mesh",this.scene),s=this.getGeometry(e,t.geometry);if(s&&s.positions.length>0&&s.indices.length>0){const t=new c.VertexData;t.positions=s.positions,t.indices=s.indices,s.uvs&&s.uvs.length>0&&(t.uvs=s.uvs),s.normals&&s.normals.length>0&&(t.normals=s.normals),t.applyToMesh(i,!0)}const n=this.getMaterial(e,t.material);if(n){const t=new x.StandardMaterial(`quarks_loader_material_${n.uuid}`,this.scene);t.alphaMode=n.alphaMode??r.Constants.ALPHA_COMBINE,t.backFaceCulling=2!==n.side,t.alphaCutOff=n.alphaTest??0,t.disableDepthWrite=!n.depthWrite,n.texture&&(t.diffuseTexture=n.texture,t.opacityTexture=n.texture),i.material=t}return i}parseObject(t,e){let i;switch(t.type){case"QuarksPrefab":i=rn.fromJSON(t,this.scene);break;case"ParticleEmitter":if(t.ps){i=this.parseParticleSystem(t.ps,e).emitter;break}i=this.createPlaceholderNode(t.type,t.name);break;case"Mesh":case"SkinnedMesh":case"InstancedMesh":case"BatchedMesh":i=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":i=this.createPlaceholderNode(t.type,t.name);break;default:i=new n.TransformNode(t.name||t.type||"node",this.scene)}if(t.uuid&&(i._quarksUUID=t.uuid),t.name&&(i.name=t.name),t.matrix){const e=l.Matrix.FromArray(t.matrix),s=new l.Vector3(1,1,1),n=l.Quaternion.Identity(),r=new l.Vector3(0,0,0);e.decompose(s,n,r),i.position.copyFrom(r),i.scaling.copyFrom(s),i.rotationQuaternion=n}else t.position&&i.position.set(t.position[0],t.position[1],t.position[2]),t.scale&&i.scaling.set(t.scale[0],t.scale[1],t.scale[2]),t.quaternion?i.rotationQuaternion=new l.Quaternion(t.quaternion[0],t.quaternion[1],t.quaternion[2],t.quaternion[3]):t.rotation&&i.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]);if(void 0!==t.visible&&i.setEnabled(t.visible),t.children)for(const s of t.children){this.parseObject(s,e).parent=i}return i}parseParticleSystem(t,e){const i=nn.fromJSON(t,e,{},this.scene);return i._meshSurfaceReferenceUUID="mesh_surface"===t?.shape?.type?t?.shape?.mesh:void 0,i}linkReferences(t){const e={},i=t=>{t._quarksUUID&&(e[t._quarksUUID]=t);for(const e of t.getChildren())e instanceof n.TransformNode&&i(e)};i(t);const s=i=>{if(i instanceof rn&&i.resolveReferences(t),i instanceof As){const t=i.system,s=t._meshSurfaceReferenceUUID;if(s&&"mesh_surface"===t.emitterShape.type){const i=e[s];i instanceof h.Mesh&&(t.emitterShape.mesh=i)}for(let s=0;s<t.behaviors.length;s++)if(t.behaviors[s]instanceof ve){const n=t.behaviors[s],r=n.subParticleSystem;if("string"!=typeof r)continue;const o=e[r];o instanceof As?(n.subParticleSystem=o,o.system.onlyUsedByOther=!0):(n.subParticleSystem=void 0,""!==r&&console.warn(`[QuarksLoader] Emitter "${i.name}" has a sub emitter targeting "${r}", `+(o?"which is not a particle emitter":"which is not in the effect")+"; that sub emitter is skipped."))}}for(const t of i.getChildren())t instanceof n.TransformNode&&s(t)};s(t)}}Ui(),Ei(Li),t.ApplyCollision=Bt,t.ApplyForce=se,t.ApplySequences=oe,t.AxisAngleGenerator=Nt,t.BatchedParticleRenderer=Cs,t.BatchedRenderer=Bs,t.BehaviorFromJSON=ri,t.BehaviorTypes=ni,t.Bezier=Ft,t.BoxEmitter=bi,t.ChangeEmitDirection=ae,t.CircleEmitter=zi,t.ColorBySpeed=le,t.ColorGeneratorFromJSON=Xt,t.ColorOverLife=he,t.ColorRange=qt,t.ConeEmitter=_i,t.ConstantColor=Yt,t.ConstantValue=Ct,t.DEG2RAD=T,t.DonutEmitter=Pi,t.EdgeEmitter=Ti,t.EffectPool=class{constructor(t,e){this.template=t,this.options=e,this.idle=[],this.playing=new Set,this.systemsOf=new Map,this.disposed=!1,this.onSystemFinished=t=>{const e=t.particleSystem;for(const t of this.playing){const i=this.systemsOf.get(t);if(void 0!==i&&i.includes(e))return void(Fs.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 i=this.idle.pop()??this.makeCopy();return null===i?null:(i.parent=e,void 0!==t&&i.position.copyFrom(t),i.setEnabled(!0),this.playing.add(i),Fs.restart(i),Fs.play(i),i)}stop(t){this.playing.has(t)&&Fs.endEmit(t)}release(t){this.playing.delete(t)&&(Fs.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=Fs.instantiate(this.template),e=[];return Fs.runOnAllParticleEmitters(t,t=>{const i=t.system;i.autoDestroy=!1,i.addEventListener("finished",this.onSystemFinished),e.push(i)}),this.systemsOf.set(t,e),Fs.addToBatchRenderer(t,this.options.renderer),t.setEnabled(!1),t.parent=null,t}disposeCopy(t){const e=this.systemsOf.get(t)??[];for(const t of e)t.removeEventListener("finished",this.onSystemFinished),this.options.renderer.deleteSystem(t),t.dispose();this.systemsOf.delete(t),t.dispose()}},t.EmitSubParticleSystem=ve,t.EmitterFromJSON=$i,t.EmitterShapes=Fi,t.Euler=mt,t.EulerGenerator=Zt,t.ForceOverLife=xe,t.FrameOverLife=Se,t.GeneratorFromJSON=ie,t.Gradient=Qt,t.GravityForce=be,t.GridEmitter=Oi,t.HemisphereEmitter=Vi,t.InheritVelocity=we,t.IntervalValue=At,t.LimitSpeedOverLife=Me,t.MathUtils=Z,t.Matrix3=pt,t.Matrix4=nt,t.MeshSurfaceEmitter=Ni,t.MeshSurfaceEmitterPlugin=Li,t.NodeParticle=class{constructor(){this.position=new K,this.velocity=new K,this.age=0,this.life=1,this.size=new K,this.rotation=0,this.color=new zt(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}},t.Noise=Re,t.OrbitOverLife=De,t.ParticleEmitter=As,t.ParticleMeshPhysicsMaterial=qs,t.ParticleMeshStandardMaterial=Us,t.ParticleStore=ze,t.ParticleSystem=nn,t.PiecewiseBezier=It,t.PiecewiseFunction=$t,t.Plugins=Ii,t.PointEmitter=Bi,t.QuarksLoader=cn,t.QuarksPrefab=rn,t.QuarksUtil=Fs,t.Quaternion=H,t.QuaternionView=vt,t.RAD2DEG=O,t.RandomColor=Gt,t.RandomColorBetweenGradient=jt,t.RandomQuatGenerator=Ht,t.RecordState=class{constructor(t,e,i){this.position=t,this.size=e,this.color=i}},t.RectangleEmitter=Ai,t.Rotation3DOverLife=Ue,t.RotationBySpeed=qe,t.RotationGeneratorFromJSON=Kt,t.RotationOverLife=ke,t.SequencerFromJSON=re,t.ShapeTransform=Mi,t.SizeBySpeed=Je,t.SizeOverLife=Qe,t.SpeedOverLife=Ge,t.SphereEmitter=Ci,t.SpriteBatch=Ps,t.SpriteParticle=ti,t.SubEmitterInheritMask=ye,t.TextureSequencer=ne,t.TrailBatch=Vs,t.TrailParticle=ii,t.TurbulenceField=We,t.VFXBatch=_s,t.ValueGeneratorFromJSON=Et,t.Vector2=St,t.Vector3=K,t.Vector3Function=te,t.Vector3GeneratorFromJSON=ee,t.Vector3View=wt,t.Vector4=zt,t.Vector4View=Pt,t.VelocityOverLife=Ze,t.WebGLCoordinateSystem=it,t.WebGPUCoordinateSystem=st,t.WidthOverLength=si,t.cacheEnvAtlas=function(t,e){$s.set(t,e)},t.ceilPowerOfTwo=G,t.clamp=B,t.createEnvAtlasFromFaceUrls=Ls,t.createSeededRandom=z,t.cubeFaceUrls=Es,t.damp=I,t.defaultMeshLighting=vs,t.degToRad=k,t.denormalize=Y,t.ensureEnvAtlasFromCube=Ds,t.erosionEqual=ws,t.euclideanModulo=C,t.floorPowerOfTwo=W,t.generateUUID=V,t.getCachedEnvAtlas=Ns,t.getPhysicsResolver=Vt,t.getRandomSource=w,t.getRegisteredShaderChunks=function(){return Ri},t.getShaderChunk=function(t){return Ri[t]},t.getValueFromEmitterMode=wi,t.inverseLerp=F,t.isPowerOfTwo=Q,t.lerp=$,t.loadPlugin=Ei,t.localParticlePhysicsVertShader=Xi,t.localParticleVertShader="\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 vec4 rotation;\nattribute float uvTile;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\n\n// Varyings\nvarying vec2 vUV;\nvarying vec4 vColor;\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\nvoid main() {\n vec3 rotatedPosition = applyQuaternion(position * size, rotation);\n vec3 worldPos = rotatedPosition + offset;\n\n gl_Position = worldViewProjection * vec4(worldPos, 1.0);\n\n #ifdef UV_TILE\n vec2 tc = vec2(tileCountX, tileCountY);\n float baseTile = floor(uvTile);\n float tileU = mod(baseTile, tc.x) / tc.x;\n float tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV = uv / tc + vec2(tileU, tileV);\n #else\n vUV = uv;\n #endif\n\n vColor = color;\n}\n",t.mapLinear=A,t.meshRimEqual=Ss,t.normalize=X,t.normalizeErosion=bs,t.normalizeMeshRim=xs,t.normalizeUVScroll=Ms,t.particleFragShader=es,t.particlePhysicsFragShader=is,t.particleVertShader=ss,t.pingpong=E,t.planBehaviorFusion=vi,t.radToDeg=J,t.randFloat=D,t.randFloatSpread=U,t.randInt=R,t.random=b,t.registerShaderChunks=Ui,t.seededRandom=q,t.setPhysicsResolver=function(t){Ot=t},t.setQuaternionFromProperEuler=j,t.setRandomSource=M,t.smootherstep=L,t.smoothstep=N,t.stretchedBillboardVertShader=ns,t.subEmitterInheritMask=ge,t.trailFragShader=rs,t.trailVertShader=os,t.unloadPlugin=function(t){const e=Ii.find(e=>e.id===t);if(e){for(const t of e.emitterShapes)Fi[t.type]&&delete Fi[t.type];for(const t of e.behaviors)ni[t.type]&&delete ni[t.type]}},t.uvScrollEqual=zs,t.withRandomSource=function(t,e){const i=M(t);try{return e()}finally{M(i)}}});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@babylonjs/core/Buffers/buffer"),require("@babylonjs/core/Maths/math.frustum"),require("@babylonjs/core/Maths/math.plane"),require("@babylonjs/core/Meshes/transformNode"),require("@babylonjs/core/Engines/constants"),require("@babylonjs/core/Materials/shaderMaterial"),require("@babylonjs/core/Materials/Textures/rawTexture"),require("@babylonjs/core/Maths/math.vector"),require("@babylonjs/core/Meshes/mesh"),require("@babylonjs/core/Meshes/mesh.vertexData"),require("@babylonjs/core/Engines/shaderStore"),require("@babylonjs/core/Materials/effect"),require("@babylonjs/core/Materials/shaderLanguage"),require("@babylonjs/core/Culling/boundingInfo"),require("@babylonjs/core/Maths/math.color"),require("@babylonjs/core/scene"),require("@babylonjs/core/Materials/Textures/texture"),require("@babylonjs/core/Materials/PBR/pbrMaterial"),require("@babylonjs/core/Materials/standardMaterial")):"function"==typeof define&&define.amd?define(["exports","@babylonjs/core/Buffers/buffer","@babylonjs/core/Maths/math.frustum","@babylonjs/core/Maths/math.plane","@babylonjs/core/Meshes/transformNode","@babylonjs/core/Engines/constants","@babylonjs/core/Materials/shaderMaterial","@babylonjs/core/Materials/Textures/rawTexture","@babylonjs/core/Maths/math.vector","@babylonjs/core/Meshes/mesh","@babylonjs/core/Meshes/mesh.vertexData","@babylonjs/core/Engines/shaderStore","@babylonjs/core/Materials/effect","@babylonjs/core/Materials/shaderLanguage","@babylonjs/core/Culling/boundingInfo","@babylonjs/core/Maths/math.color","@babylonjs/core/scene","@babylonjs/core/Materials/Textures/texture","@babylonjs/core/Materials/PBR/pbrMaterial","@babylonjs/core/Materials/standardMaterial"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).BabylonQuarks={},t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON,t.BABYLON)}(this,function(t,e,i,s,n,r,o,a,h,l,c,u,d,f,m,p,y,g,v,x){"use strict";let S=null;function b(){return null===S?Math.random():S()}function w(){return S??Math.random}function M(t){const e=w();return S=t,e}function z(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 _=["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 V=1234567;const T=Math.PI/180,P=180/Math.PI;function O(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0;return(_[255&t]+_[t>>8&255]+_[t>>16&255]+_[t>>24&255]+"-"+_[255&e]+_[e>>8&255]+"-"+_[e>>16&15|64]+_[e>>24&255]+"-"+_[63&i|128]+_[i>>8&255]+"-"+_[i>>16&255]+_[i>>24&255]+_[255&s]+_[s>>8&255]+_[s>>16&255]+_[s>>24&255]).toLowerCase()}function A(t,e,i){return Math.max(e,Math.min(i,t))}function B(t,e){return(t%e+e)%e}function C(t,e,i,s,n){return s+(t-e)*(n-s)/(i-e)}function F(t,e,i){return t!==e?(i-t)/(e-t):0}function $(t,e,i){return(1-i)*t+i*e}function I(t,e,i,s){return $(t,e,1-Math.exp(-i*s))}function U(t,e=1){return e-Math.abs(B(t,2*e)-e)}function E(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)}function N(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*t*(t*(6*t-15)+10)}function R(t,e){return t+Math.floor(b()*(e-t+1))}function D(t,e){return t+b()*(e-t)}function L(t){return t*(.5-b())}function q(t){void 0!==t&&(V=t);let e=V+=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 k(t){return t*T}function J(t){return t*P}function Q(t){return!(t&t-1)&&0!==t}function G(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function W(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function j(t,e,i,s,n){const r=Math.cos,o=Math.sin,a=r(i/2),h=o(i/2),l=r((e+s)/2),c=o((e+s)/2),u=r((e-s)/2),d=o((e-s)/2),f=r((s-e)/2),m=o((s-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*m,h*f,a*l);break;case"YXY":t.set(h*f,a*c,h*m,a*l);break;case"ZYZ":t.set(h*m,h*f,a*c,a*l);break;default:console.warn("../math.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function Y(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 X(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 Z={DEG2RAD:T,RAD2DEG:P,generateUUID:O,clamp:A,euclideanModulo:B,mapLinear:C,inverseLerp:F,lerp:$,damp:I,pingpong:U,smoothstep:E,smootherstep:N,randInt:R,randFloat:D,randFloatSpread:L,seededRandom:q,degToRad:k,radToDeg:J,isPowerOfTwo:Q,ceilPowerOfTwo:G,floorPowerOfTwo:W,setQuaternionFromProperEuler:j,normalize:X,denormalize:Y};class H{constructor(t=0,e=0,i=0,s=1){this._x=t,this._y=e,this._z=i,this._w=s}static slerpFlat(t,e,i,s,n,r,o){let a=i[s+0],h=i[s+1],l=i[s+2],c=i[s+3];const u=n[r+0],d=n[r+1],f=n[r+2],m=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]=m);if(c!==m||a!==u||h!==d||l!==f){let t=1-o;const e=a*u+h*d+l*f+c*m,i=e>=0?1:-1,s=1-e*e;if(s>Number.EPSILON){const n=Math.sqrt(s),r=Math.atan2(n,e*i);t=Math.sin(t*r)/n,o=Math.sin(o*r)/n}const n=o*i;if(a=a*t+u*n,h=h*t+d*n,l=l*t+f*n,c=c*t+m*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,i,s,n,r){const o=i[s],a=i[s+1],h=i[s+2],l=i[s+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,i,s){return this._x=t,this._y=e,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new H(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 i=t._x,s=t._y,n=t._z,r=t._order,o=Math.cos,a=Math.sin,h=o(i/2),l=o(s/2),c=o(n/2),u=a(i/2),d=a(s/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 i=e/2,s=Math.sin(i);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],s=e[4],n=e[8],r=e[1],o=e[5],a=e[9],h=e[2],l=e[6],c=e[10],u=i+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-s)*t}else if(i>o&&i>c){const t=2*Math.sqrt(1+i-o-c);this._w=(l-a)/t,this._x=.25*t,this._y=(s+r)/t,this._z=(n+h)/t}else if(o>c){const t=2*Math.sqrt(1+o-i-c);this._w=(n-h)/t,this._x=(s+r)/t,this._y=.25*t,this._z=(a+l)/t}else{const t=2*Math.sqrt(1+c-i-o);this._w=(r-s)/t,this._x=(n+h)/t,this._y=(a+l)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<Number.EPSILON?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(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=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(A(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(0===i)return this;const s=Math.min(1,e/i);return this.slerp(t,s),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 i=t._x,s=t._y,n=t._z,r=t._w,o=e._x,a=e._y,h=e._z,l=e._w;return this._x=i*l+r*o+s*h-n*a,this._y=s*l+r*a+n*o-i*h,this._z=n*l+r*h+i*a-s*o,this._w=r*l-i*o-s*a-n*h,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const i=this._x,s=this._y,n=this._z,r=this._w;let o=r*t._w+i*t._x+s*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=i,this._y=s,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*i+e*this._x,this._y=t*s+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=i*c+this._x*u,this._y=s*c+this._y*u,this._z=n*c+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*b(),e=2*Math.PI*b(),i=b(),s=Math.sqrt(1-i),n=Math.sqrt(i);return this.set(s*Math.sin(t),s*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}}H.prototype.isQuaternion=!0;class K{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}set(t,e,i){return void 0===i&&(i=this.z),this.x=t,this.y=e,this.z=i,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 K(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(et.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(et.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6]*s,this.y=n[1]*e+n[4]*i+n[7]*s,this.z=n[2]*e+n[5]*i+n[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=t.elements,r=1/(n[3]*e+n[7]*i+n[11]*s+n[15]);return this.x=(n[0]*e+n[4]*i+n[8]*s+n[12])*r,this.y=(n[1]*e+n[5]*i+n[9]*s+n[13])*r,this.z=(n[2]*e+n[6]*i+n[10]*s+n[14])*r,this}applyQuaternion(t){const e=this.x,i=this.y,s=this.z,n=t.x,r=t.y,o=t.z,a=t.w,h=2*(r*s-o*i),l=2*(o*e-n*s),c=2*(n*i-r*e);return this.x=e+a*h+r*c-o*l,this.y=i+a*l+o*h-n*c,this.z=s+a*c+n*l-r*h,this}transformDirection(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[4]*i+n[8]*s,this.y=n[1]*e+n[5]*i+n[9]*s,this.z=n[2]*e+n[6]*i+n[10]*s,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 i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,s=t.y,n=t.z,r=e.x,o=e.y,a=e.z;return this.x=s*a-n*o,this.y=n*r-i*a,this.z=i*o-s*r,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return tt.copy(this).projectOnVector(t),this.sub(tt)}reflect(t){return this.sub(tt.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 i=this.dot(t)/e;return Math.acos(A(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,s=this.z-t.z;return e*e+i*i+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSphericalCoords(t,e,i){const s=Math.sin(e)*t;return this.x=s*Math.sin(i),this.y=Math.cos(e)*t,this.z=s*Math.cos(i),this}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,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(),i=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=s,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=b(),this.y=b(),this.z=b(),this}randomDirection(){const t=b()*Math.PI*2,e=2*b()-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*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}}K.prototype.isVector3=!0;const tt=new K,et=new H,it=2e3,st=2001;class nt{constructor(t,e,i,s,n,r,o,a,h,l,c,u,d,f,m,p){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,i,s,n,r,o,a,h,l,c,u,d,f,m,p)}extractPosition(t){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(t)}multiplyToArray(t,e,i){return console.error("THREE.Matrix4: .multiplyToArray() has been removed."),this}setRotationFromQuaternion(t){return this.makeRotationFromQuaternion(t)}set(t,e,i,s,n,r,o,a,h,l,c,u,d,f,m,p){const y=this.elements;return y[0]=t,y[4]=e,y[8]=i,y[12]=s,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]=m,y[15]=p,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 nt).fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[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,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,i=t.elements,s=1/rt.setFromMatrixColumn(t,0).length(),n=1/rt.setFromMatrixColumn(t,1).length(),r=1/rt.setFromMatrixColumn(t,2).length();return e[0]=i[0]*s,e[1]=i[1]*s,e[2]=i[2]*s,e[3]=0,e[4]=i[4]*n,e[5]=i[5]*n,e[6]=i[6]*n,e[7]=0,e[8]=i[8]*r,e[9]=i[9]*r,e[10]=i[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,n=t.z,r=Math.cos(i),o=Math.sin(i),a=Math.cos(s),h=Math.sin(s),l=Math.cos(n),c=Math.sin(n);if("XYZ"===t.order){const t=r*l,i=r*c,s=o*l,n=o*c;e[0]=a*l,e[4]=-a*c,e[8]=h,e[1]=i+s*h,e[5]=t-n*h,e[9]=-o*a,e[2]=n-t*h,e[6]=s+i*h,e[10]=r*a}else if("YXZ"===t.order){const t=a*l,i=a*c,s=h*l,n=h*c;e[0]=t+n*o,e[4]=s*o-i,e[8]=r*h,e[1]=r*c,e[5]=r*l,e[9]=-o,e[2]=i*o-s,e[6]=n+t*o,e[10]=r*a}else if("ZXY"===t.order){const t=a*l,i=a*c,s=h*l,n=h*c;e[0]=t-n*o,e[4]=-r*c,e[8]=s+i*o,e[1]=i+s*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,i=r*c,s=o*l,n=o*c;e[0]=a*l,e[4]=s*h-i,e[8]=t*h+n,e[1]=a*c,e[5]=n*h+t,e[9]=i*h-s,e[2]=-h,e[6]=o*a,e[10]=r*a}else if("YZX"===t.order){const t=r*a,i=r*h,s=o*a,n=o*h;e[0]=a*l,e[4]=n-t*c,e[8]=s*c+i,e[1]=c,e[5]=r*l,e[9]=-o*l,e[2]=-h*l,e[6]=i*c+s,e[10]=t-n*c}else if("XZY"===t.order){const t=r*a,i=r*h,s=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]=i*c-s,e[2]=s*c-i,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(at,t,ht)}lookAt(t,e,i){const s=this.elements;return ut.subVectors(t,e),0===ut.lengthSq()&&(ut.z=1),ut.normalize(),lt.crossVectors(i,ut),0===lt.lengthSq()&&(1===Math.abs(i.z)?ut.x+=1e-4:ut.z+=1e-4,ut.normalize(),lt.crossVectors(i,ut)),lt.normalize(),ct.crossVectors(ut,lt),s[0]=lt.x,s[4]=ct.x,s[8]=ut.x,s[1]=lt.y,s[5]=ct.y,s[9]=ut.y,s[2]=lt.z,s[6]=ct.z,s[10]=ut.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],o=i[4],a=i[8],h=i[12],l=i[1],c=i[5],u=i[9],d=i[13],f=i[2],m=i[6],p=i[10],y=i[14],g=i[3],v=i[7],x=i[11],S=i[15],b=s[0],w=s[4],M=s[8],z=s[12],_=s[1],V=s[5],T=s[9],P=s[13],O=s[2],A=s[6],B=s[10],C=s[14],F=s[3],$=s[7],I=s[11],U=s[15];return n[0]=r*b+o*_+a*O+h*F,n[4]=r*w+o*V+a*A+h*$,n[8]=r*M+o*T+a*B+h*I,n[12]=r*z+o*P+a*C+h*U,n[1]=l*b+c*_+u*O+d*F,n[5]=l*w+c*V+u*A+d*$,n[9]=l*M+c*T+u*B+d*I,n[13]=l*z+c*P+u*C+d*U,n[2]=f*b+m*_+p*O+y*F,n[6]=f*w+m*V+p*A+y*$,n[10]=f*M+m*T+p*B+y*I,n[14]=f*z+m*P+p*C+y*U,n[3]=g*b+v*_+x*O+S*F,n[7]=g*w+v*V+x*A+S*$,n[11]=g*M+v*T+x*B+S*I,n[15]=g*z+v*P+x*C+S*U,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],i=t[4],s=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-s*h*c-n*o*u+i*h*u+s*o*d-i*a*d)+t[7]*(+e*a*d-e*h*u+n*r*u-s*r*d+s*h*l-n*a*l)+t[11]*(+e*h*c-e*o*d-n*r*c+i*r*d+n*o*l-i*h*l)+t[15]*(-s*o*l-e*a*c+e*o*u+s*r*c-i*r*u+i*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,i){const s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],s=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],m=t[13],p=t[14],y=t[15],g=c*p*h-m*u*h+m*a*d-o*p*d-c*a*y+o*u*y,v=f*u*h-l*p*h-f*a*d+r*p*d+l*a*y-r*u*y,x=l*m*h-f*c*h+f*o*d-r*m*d-l*o*y+r*c*y,S=f*c*a-l*m*a-f*o*u+r*m*u+l*o*p-r*c*p,b=e*g+i*v+s*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]=(m*u*n-c*p*n-m*s*d+i*p*d+c*s*y-i*u*y)*w,t[2]=(o*p*n-m*a*n+m*s*h-i*p*h-o*s*y+i*a*y)*w,t[3]=(c*a*n-o*u*n-c*s*h+i*u*h+o*s*d-i*a*d)*w,t[4]=v*w,t[5]=(l*p*n-f*u*n+f*s*d-e*p*d-l*s*y+e*u*y)*w,t[6]=(f*a*n-r*p*n-f*s*h+e*p*h+r*s*y-e*a*y)*w,t[7]=(r*u*n-l*a*n+l*s*h-e*u*h-r*s*d+e*a*d)*w,t[8]=x*w,t[9]=(f*c*n-l*m*n-f*i*d+e*m*d+l*i*y-e*c*y)*w,t[10]=(r*m*n-f*o*n+f*i*h-e*m*h-r*i*y+e*o*y)*w,t[11]=(l*o*n-r*c*n-l*i*h+e*c*h+r*i*d-e*o*d)*w,t[12]=S*w,t[13]=(l*m*s-f*c*s+f*i*u-e*m*u-l*i*p+e*c*p)*w,t[14]=(f*o*s-r*m*s-f*i*a+e*m*a+r*i*p-e*o*p)*w,t[15]=(r*c*s-l*o*s+l*i*a-e*c*a-r*i*u+e*o*u)*w,this}scale(t){const e=this.elements,i=t.x,s=t.y,n=t.z;return e[0]*=i,e[4]*=s,e[8]*=n,e[1]*=i,e[5]*=s,e[9]*=n,e[2]*=i,e[6]*=s,e[10]*=n,e[3]*=i,e[7]*=s,e[11]*=n,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,s))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),s=Math.sin(e),n=1-i,r=t.x,o=t.y,a=t.z,h=n*r,l=n*o;return this.set(h*r+i,h*o-s*a,h*a+s*o,0,h*o+s*a,l*o+i,l*a-s*r,0,h*a-s*o,l*a+s*r,n*a*a+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,s,n,r){return this.set(1,i,n,0,t,1,r,0,e,s,1,0,0,0,0,1),this}compose(t,e,i){const s=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,m=r*l,p=r*c,y=o*c,g=a*h,v=a*l,x=a*c,S=i.x,b=i.y,w=i.z;return s[0]=(1-(m+y))*S,s[1]=(d+x)*S,s[2]=(f-v)*S,s[3]=0,s[4]=(d-x)*b,s[5]=(1-(u+y))*b,s[6]=(p+g)*b,s[7]=0,s[8]=(f+v)*w,s[9]=(p-g)*w,s[10]=(1-(u+m))*w,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,i){const s=this.elements;let n=rt.set(s[0],s[1],s[2]).length();const r=rt.set(s[4],s[5],s[6]).length(),o=rt.set(s[8],s[9],s[10]).length();this.determinant()<0&&(n=-n),t.x=s[12],t.y=s[13],t.z=s[14],ot.copy(this);const a=1/n,h=1/r,l=1/o;return ot.elements[0]*=a,ot.elements[1]*=a,ot.elements[2]*=a,ot.elements[4]*=h,ot.elements[5]*=h,ot.elements[6]*=h,ot.elements[8]*=l,ot.elements[9]*=l,ot.elements[10]*=l,e.setFromRotationMatrix(ot),i.x=n,i.y=r,i.z=o,this}makePerspective(t,e,i,s,n,r,o=2e3){const a=this.elements,h=2*n/(e-t),l=2*n/(i-s),c=(e+t)/(e-t),u=(i+s)/(i-s);let d,f;if(o===it)d=-(r+n)/(r-n),f=-2*r*n/(r-n);else{if(o!==st)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,i,s,n,r,o=2e3){const a=this.elements,h=1/(e-t),l=1/(i-s),c=1/(r-n),u=(e+t)*h,d=(i+s)*l;let f,m;if(o===it)f=(r+n)*c,m=-2*c;else{if(o!==st)throw new Error("../math.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);f=n*c,m=-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]=m,a[14]=-f,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<16;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}nt.prototype.isMatrix4=!0;const rt=new K,ot=new nt,at=new K(0,0,0),ht=new K(1,1,1),lt=new K,ct=new K,ut=new K,dt=new nt,ft=new H;class mt{constructor(t=0,e=0,i=0,s=mt.DEFAULT_ORDER){this._x=t,this._y=e,this._z=i,this._order=s}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,i,s=this._order){return this._x=t,this._y=e,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new mt(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,i=!0){const s=t.elements,n=s[0],r=s[4],o=s[8],a=s[1],h=s[5],l=s[9],c=s[2],u=s[6],d=s[10];switch(e){case"XYZ":this._y=Math.asin(A(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(-A(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(A(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(-A(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(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(-A(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===i&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return dt.makeRotationFromQuaternion(t),this.setFromRotationMatrix(dt,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return ft.setFromEuler(this),this.setFromQuaternion(ft,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}}mt.DEFAULT_ORDER="XYZ",mt.prototype.isEuler=!0;class pt{constructor(t,e,i,s,n,r,o,a,h){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,i,s,n,r,o,a,h)}set(t,e,i,s,n,r,o,a,h){const l=this.elements;return l[0]=t,l[1]=s,l[2]=o,l[3]=e,l[4]=n,l[5]=a,l[6]=i,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,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.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 i=t.elements,s=e.elements,n=this.elements,r=i[0],o=i[3],a=i[6],h=i[1],l=i[4],c=i[7],u=i[2],d=i[5],f=i[8],m=s[0],p=s[3],y=s[6],g=s[1],v=s[4],x=s[7],S=s[2],b=s[5],w=s[8];return n[0]=r*m+o*g+a*S,n[3]=r*p+o*v+a*b,n[6]=r*y+o*x+a*w,n[1]=h*m+l*g+c*S,n[4]=h*p+l*v+c*b,n[7]=h*y+l*x+c*w,n[2]=u*m+d*g+f*S,n[5]=u*p+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],i=t[1],s=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-i*n*l+i*o*a+s*n*h-s*r*a}invert(){const t=this.elements,e=t[0],i=t[1],s=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+i*u+s*d;if(0===f)return this.set(0,0,0,0,0,0,0,0,0);const m=1/f;return t[0]=c*m,t[1]=(s*h-l*i)*m,t[2]=(o*i-s*r)*m,t[3]=u*m,t[4]=(l*e-s*a)*m,t[5]=(s*n-o*e)*m,t[6]=d*m,t[7]=(i*a-h*e)*m,t[8]=(r*e-i*n)*m,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,i,s,n,r,o){const a=Math.cos(n),h=Math.sin(n);return this.set(i*a,i*h,-i*(a*r+h*o)+r+t,-s*h,s*a,-s*(-h*r+a*o)+o+e,0,0,1),this}scale(t,e){return this.premultiply(yt.makeScale(t,e)),this}rotate(t){return this.premultiply(yt.makeRotation(-t)),this}translate(t,e){return this.premultiply(yt.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,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,i=t.elements;for(let t=0;t<9;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return(new pt).fromArray(this.elements)}}pt.prototype.isMatrix3=!0;const yt=new pt,gt=new Float32Array(4);class vt extends H{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const xt=vt.prototype;xt.data=gt,xt.offset=0,Object.defineProperties(vt.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 St{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 St(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,i=this.y,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6],this.y=s[1]*e+s[4]*i+s[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 i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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 i=this.dot(t)/e;return Math.acos(A(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}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,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,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 i=Math.cos(e),s=Math.sin(e),n=this.x-t.x,r=this.y-t.y;return this.x=n*i-r*s+t.x,this.y=n*s+r*i+t.y,this}random(){return this.x=b(),this.y=b(),this}*[Symbol.iterator](){yield this.x,yield this.y}}St.isVector2=!0;const bt=new Float32Array(3);class wt extends K{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const Mt=wt.prototype;Mt.data=bt,Mt.offset=0,Object.defineProperties(wt.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 zt{constructor(t=0,e=0,i=0,s=1){this.x=t,this.y=e,this.z=i,this.w=s}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,i,s){return this.x=t,this.y=e,this.z=i,this.w=s,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 zt(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,i=this.y,s=this.z,n=this.w,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*s+r[12]*n,this.y=r[1]*e+r[5]*i+r[9]*s+r[13]*n,this.z=r[2]*e+r[6]*i+r[10]*s+r[14]*n,this.w=r[3]*e+r[7]*i+r[11]*s+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,i,s,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],m=a[2],p=a[6],y=a[10];if(Math.abs(l-u)<r&&Math.abs(c-m)<r&&Math.abs(f-p)<r){if(Math.abs(l+u)<o&&Math.abs(c+m)<o&&Math.abs(f+p)<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+m)/4,S=(f+p)/4;return t>a&&t>g?t<r?(i=0,s=.707106781,n=.707106781):(i=Math.sqrt(t),s=v/i,n=x/i):a>g?a<r?(i=.707106781,s=0,n=.707106781):(s=Math.sqrt(a),i=v/s,n=S/s):g<r?(i=.707106781,s=.707106781,n=0):(n=Math.sqrt(g),i=x/n,s=S/n),this.set(i,s,n,e),this}let g=Math.sqrt((p-f)*(p-f)+(c-m)*(c-m)+(u-l)*(u-l));return Math.abs(g)<.001&&(g=1),this.x=(p-f)/g,this.y=(c-m)/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 i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,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=b(),this.y=b(),this.z=b(),this.w=b(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}zt.prototype.isVector4=!0;const _t=new Float32Array(4);class Vt extends zt{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const Tt=Vt.prototype;let Pt;function Ot(){return Pt}Tt.data=_t,Tt.offset=0,Object.defineProperties(Vt.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 At{constructor(t,e){this.resolver=t,this.bounce=e,this.type="ApplyCollision",this.tempV=new K}initialize(t){}update(t,e){this.resolver&&this.resolver.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 At(Ot(),t.bounce)}clone(){return new At(this.resolver,this.bounce)}reset(){}}class Bt{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 Bt(t.value)}clone(){return new Bt(this.value)}}class Ct{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(b())}genValue(t){return-1===this.indexCount&&this.startGen(t),Z.lerp(this.a,this.b,t[this.indexCount])}toJSON(){return{type:"IntervalValue",a:this.a,b:this.b}}static fromJSON(t){return new Ct(t.a,t.b)}clone(){return new Ct(this.a,this.b)}}class Ft{constructor(t,e,i,s){this.p=[t,e,i,s]}genValue(t){const e=this.p,i=t*t,s=1-t,n=s*s;return e[0]*n*s+e[1]*n*t*3+e[2]*s*i*3+e[3]*i*t}derivativeCoefficients(t){const e=[];for(let i=t,s=i.length-1;s>0;s--){const t=[];for(let e=0;e<s;e++){const n=s*(i[e+1]-i[e]);t.push(n)}e.push(t),i=t}return e}getSlope(t){const e=this.derivativeCoefficients(this.p)[0],i=1-t,s=i*t*2,n=t*t;return i*i*e[0]+s*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,i=this.p,s=[],n=0,r=0,o=0;const a=[];for(a[n++]=i[0],a[n++]=i[1],a[n++]=i[2],a[n++]=i[3];i.length>1;){for(s=[],r=0,o=i.length-1;r<o;r++)e=t*i[r]+(1-t)*i[r+1],a[n++]=e,s.push(e);i=s}return a}split(t){const e=this.hull(t);return{left:new Ft(e[0],e[4],e[7],e[9]),right:new Ft(e[9],e[8],e[6],e[3]),span:e}}clone(){return new Ft(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 Ft(t.p0,t.p1,t.p2,t.p3)}}class $t{constructor(){this.functions=new Array}findFunction(t){const e=this.functions,i=e.length-1;if(i<=0)return 0===i&&t>=e[0][1]&&t<=1?0:-1;let s=0,n=i;for(;s+1<n;){const i=s+n>>1;if(t<e[i][1])n=i-1;else{if(!(t>this.getEndX(i)))return i;s=i+1}}for(let i=s;i<=n;i++)if(t>=e[i][1]&&t<=this.getEndX(i))return i;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 i=this.findFunction(t);this.functions.splice(i+1,0,[e,t])}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 It extends $t{constructor(t=[[new Ft(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 i=5*e;let s=this.tableSignature,n=null===s||s.length!==i;n&&(s=new Float64Array(i));for(let i=0,r=0;i<e;i++,r+=5){const e=t[i][0].p,o=t[i][1];n||(n=s[r]!==e[0]||s[r+1]!==e[1]||s[r+2]!==e[2]||s[r+3]!==e[3]||s[r+4]!==o),n&&(s[r]=e[0],s[r+1]=e[1],s[r+2]=e[2],s[r+3]=e[3],s[r+4]=o)}if(!n&&null!==this.table)return;this.tableSignature=s;const r=It.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 i=this.table;if(null!==i){const t=i.length-1;if(e<=0)return i[0];if(e>=1)return i[t];const s=e*t,n=0|s,r=s-n,o=i[n];return o+(i[n+1]-o)*r}return this.genValueExact(e)}genValueExact(t){const e=this.functions,i=e.length;if(0===i)return 0;const s=this.findFunction(t);if(-1===s)return t<e[0][1]?e[0][0].genValue(0):e[i-1][0].genValue(1);const n=e[s][1],r=(s+1<i?e[s+1][1]:1)-n;return e[s][0].genValue(r>0?(t-n)/r:0)}toSVG(t,e){if(e<1)return"";let i=["M",0,this.functions[0][0].p[0]].join(" ");for(let s=1/e;s<=1;s+=1/e)i=[i,"L",s*t,this.genValue(void 0,s)].join(" ");return i}toJSON(){return{type:"PiecewiseBezier",functions:this.functions.map(([t,e])=>({function:t.toJSON(),start:e}))}}static fromJSON(t){return new It(t.functions.map(t=>[Ft.fromJSON(t.function),t.start]))}clone(){return new It(this.functions.map(([t,e])=>[t.clone(),e]))}startGen(t){}}function Ut(t){switch(t.type){case"ConstantValue":return Bt.fromJSON(t);case"IntervalValue":return Ct.fromJSON(t);case"PiecewiseBezier":return It.fromJSON(t);default:return new Bt(0)}}It.TABLE_SIZE=257;class Et{constructor(t,e){this.axis=t,this.angle=e,this.type="rotation"}startGen(t){this.angle.startGen(t)}genValue(t,e,i,s){return e.setFromAxisAngle(this.axis,this.angle.genValue(t,s)*i)}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 Et(new K(t.axis.x,t.axis.y,t.axis.z),Ut(t.angle))}clone(){return new Et(this.axis.clone(),this.angle.clone())}}const Nt=t=>({r:t.x,g:t.y,b:t.z,a:t.w}),Rt=t=>new zt(t.r,t.g,t.b,t.a),Dt=(t,e)=>{switch(e){case"Vector3":return new K(t.x,t.y,t.z);case"Vector4":return new zt(t.x,t.y,t.z,t.w);case"Color":return new K(t.r,t.g,t.b);default:return t}},Lt=(t,e)=>{switch(e){case"Vector3":return{x:t.x,y:t.y,z:t.z};case"Vector4":return{x:t.x,y:t.y,z:t.z,w:t.w};case"Color":return{r:t.x,g:t.y,b:t.z};default:return t}};class qt{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(b())}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:Nt(this.a),b:Nt(this.b)}}static fromJSON(t){return new qt(Rt(t.a),Rt(t.b))}clone(){return new qt(this.a.clone(),this.b.clone())}}class kt{constructor(t,e){this.subType=e,this.type="function",this.keys=t}findKey(t){const e=this.keys,i=e.length-1;if(i<=0)return 0===i&&t>=e[0][1]&&t<=1?0:-1;if(1===i)return t<e[0][1]||t>1?-1:t<=e[1][1]?0:1;let s=0,n=i;for(;s+1<n;){const i=s+n>>1;if(t<e[i][1])n=i-1;else{if(!(t>this.getEndX(i)))return i;s=i+1}}for(let i=s;i<=n;i++)if(t>=e[i][1]&&t<=this.getEndX(i))return i;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 i=this.keys,s=this.findKey(e),n=i.length-1;if("Number"===this.subType){if(-1===s)return i[0][0];if(s>=n)return i[n][0];const t=i[s][1],r=i[s][0],o=i[s+1][1]-t;return(i[s+1][0]-r)*(o>0?(e-t)/o:0)+r}{if(-1===s)return t.copy(i[0][0]);if(s>=n)return t.copy(i[n][0]);const r=i[s][1],o=i[s+1][1]-r;return t.copy(i[s][0]).lerp(i[s+1][0],o>0?(e-r)/o:0)}}toJSON(){return this.keys[0][0].constructor.name,{type:"CLinearFunction",subType:this.subType,keys:this.keys.map(([t,e])=>({value:Lt(t,this.subType),pos:e}))}}static fromJSON(t){return new kt(t.keys.map(e=>[Dt(e.value,t.subType),e.pos]),t.subType)}clone(){return"Number"===this.subType?new kt(this.keys.map(([t,e])=>[t,e]),this.subType):new kt(this.keys.map(([t,e])=>[t.clone(),e]),this.subType)}}const Jt=new zt;class Qt{constructor(t=[[new K(0,0,0),0],[new K(1,1,1),0]],e=[[1,0],[1,1]]){this.table=null,this.tableSignature=null,this.type="function",this.color=new kt(t,"Color"),this.alpha=new kt(e,"Number")}refreshTable(){const t=this.color.keys,e=this.alpha.keys,i=4*t.length+2*e.length;let s=this.tableSignature,n=null===s||s.length!==i;n&&(s=new Float64Array(i));let r=0;for(let e=0;e<t.length;e++,r+=4){const i=t[e][0],o=t[e][1];n||(n=s[r]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z||s[r+3]!==o),n&&(s[r]=i.x,s[r+1]=i.y,s[r+2]=i.z,s[r+3]=o)}for(let t=0;t<e.length;t++,r+=2){const i=e[t][0],o=e[t][1];n||(n=s[r]!==i||s[r+1]!==o),n&&(s[r]=i,s[r+1]=o)}if(!n&&null!==this.table)return;this.tableSignature=s;const o=Qt.TABLE_SIZE,a=null!==this.table&&this.table.length===4*o?this.table:new Float32Array(4*o),h=1/(o-1),l=Jt;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,i){const s=this.table;if(null!==s){const t=Qt.TABLE_SIZE-1;if(i<=0)return e.x=s[0],e.y=s[1],e.z=s[2],e.w=s[3],e;if(i>=1){const i=4*t;return e.x=s[i],e.y=s[i+1],e.z=s[i+2],e.w=s[i+3],e}const n=i*t,r=0|n,o=n-r,a=4*r,h=a+4;return e.x=s[a]+(s[h]-s[a])*o,e.y=s[a+1]+(s[h+1]-s[a+1])*o,e.z=s[a+2]+(s[h+2]-s[a+2])*o,e.w=s[a+3]+(s[h+3]-s[a+3])*o,e}return this.genColorExact(e,i)}genColorExact(t,e){const i=this.color.keys,s=i.length-1,n=this.color.findKey(e);let r,o,a;if(-1===n||n>=s){const t=i[-1===n?0:s][0];r=t.x,o=t.y,a=t.z}else{const t=i[n][0],s=i[n+1][0],h=i[n][1],l=i[n+1][1]-h,c=l>0?(e-h)/l:0;r=t.x+(s.x-t.x)*c,o=t.y+(s.y-t.y)*c,a=t.z+(s.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],i=h[c][0],s=h[c+1][1]-t;u=i+(h[c+1][0]-i)*(s>0?(e-t)/s: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(t=>[qt.fromJSON(t.function).a,t.start]);return t.functions.length>0&&e.push([qt.fromJSON(t.functions[t.functions.length-1].function).b,1]),new Qt(e.map(t=>[new K(t[0].x,t[0].y,t[0].z),t[1]]),e.map(t=>[t[0].w,t[1]]))}{const e=new Qt;return e.alpha=kt.fromJSON(t.alpha),e.color=kt.fromJSON(t.color),e}}clone(){const t=new Qt;return t.alpha=this.alpha.clone(),t.color=this.color.clone(),t}startGen(t){}}Qt.TABLE_SIZE=257;class Gt{constructor(t,e){this.a=t,this.b=e,this.type="value"}startGen(t){}genColor(t,e){const i=b();return e.copy(this.a).lerp(this.b,i)}toJSON(){return{type:"RandomColor",a:Nt(this.a),b:Nt(this.b)}}static fromJSON(t){return new Gt(Rt(t.a),Rt(t.b))}clone(){return new Gt(this.a.clone(),this.b.clone())}}const Wt=new zt;class jt{constructor(t,e){this.indexCount=0,this.type="function",this.gradient1=t,this.gradient2=e}startGen(t){this.indexCount=t.length,t.push(b())}genColor(t,e,i){return this.gradient1.genColor(t,e,i),this.gradient2.genColor(t,Wt,i),t&&void 0!==t[this.indexCount]?e.lerp(Wt,t[this.indexCount]):e.lerp(Wt,b()),e}toJSON(){return{type:"RandomColorBetweenGradient",gradient1:this.gradient1.toJSON(),gradient2:this.gradient2.toJSON()}}static fromJSON(t){return new jt(Qt.fromJSON(t.gradient1),Qt.fromJSON(t.gradient2))}clone(){return new jt(this.gradient1.clone(),this.gradient2.clone())}}class Yt{constructor(t){this.color=t,this.type="value"}startGen(t){}genColor(t,e){return e.copy(this.color)}toJSON(){return{type:"ConstantColor",color:Nt(this.color)}}static fromJSON(t){return new Yt(Rt(t.color))}clone(){return new Yt(this.color.clone())}}function Xt(t){switch(t.type){case"ConstantColor":return Yt.fromJSON(t);case"ColorRange":return qt.fromJSON(t);case"RandomColor":return Gt.fromJSON(t);case"Gradient":return Qt.fromJSON(t);case"RandomColorBetweenGradient":return jt.fromJSON(t);default:return new Yt(new zt(1,1,1,1))}}class Zt{constructor(t,e,i,s){this.angleX=t,this.angleY=e,this.angleZ=i,this.type="rotation",this.eular=new mt(0,0,0,s)}startGen(t){this.angleX.startGen(t),this.angleY.startGen(t),this.angleZ.startGen(t)}genValue(t,e,i,s){return this.eular.set(this.angleX.genValue(t,s)*i,this.angleY.genValue(t,s)*i,this.angleZ.genValue(t,s)*i),e.setFromEuler(this.eular)}toJSON(){return{type:"Euler",angleX:this.angleX.toJSON(),angleY:this.angleY.toJSON(),angleZ:this.angleZ.toJSON(),eulerOrder:this.eular.order}}static fromJSON(t){return new Zt(Ut(t.angleX),Ut(t.angleY),Ut(t.angleZ),t.eulerOrder)}clone(){return new Zt(this.angleX,this.angleY,this.angleZ,this.eular.order)}}class Ht{constructor(){this.indexCount=0,this.type="rotation"}startGen(t){let e,i,s,n,r,o;this.indexCount=t.length;do{e=2*b()-1,i=2*b()-1,s=e*e+i*i}while(s>1);do{n=2*b()-1,r=2*b()-1,o=n*n+r*r}while(o>1);const a=Math.sqrt((1-s)/o);t.push(e,i,a*n,a*r)}genValue(t,e,i,s){-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 Ht}clone(){return new Ht}}function Kt(t){switch(t.type){case"AxisAngle":return Et.fromJSON(t);case"Euler":return Zt.fromJSON(t);case"RandomQuat":return Ht.fromJSON(t);default:return new Ht}}class te{constructor(t,e,i){this.x=t,this.y=e,this.z=i,this.type="vec3function"}startGen(t){this.x.startGen(t),this.y.startGen(t),this.z.startGen(t)}genValue(t,e,i){return e.set(this.x.genValue(t,i),this.y.genValue(t,i),this.z.genValue(t,i))}toJSON(){return{type:"Vector3Function",x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new te(Ut(t.x),Ut(t.y),Ut(t.z))}clone(){return new te(this.x,this.y,this.z)}}function ee(t){return"Vector3Function"===t.type?te.fromJSON(t):new te(new Bt(0),new Bt(0),new Bt(0))}function ie(t){switch(t.type){case"ConstantValue":case"IntervalValue":case"PiecewiseBezier":return Ut(t);case"AxisAngle":case"RandomQuat":case"Euler":return Kt(t);case"Vector3Function":return ee(t);default:return new Bt(0)}}class se{constructor(t,e){this.direction=t,this.magnitude=e,this.type="ApplyForce",this.memory={data:[],dataCount:0},this.magnitudeValue=this.magnitude.genValue(this.memory)}initialize(t){}update(t,e){const i=this.magnitudeValue*e,s=this.direction,n=t.velocity;n.x+=s.x*i,n.y+=s.y*i,n.z+=s.z*i}updateAll(t,e,i){const s=this.magnitudeValue*i,n=this.direction.x*s,r=this.direction.y*s,o=this.direction.z*s;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const s=e.velocity;s.x+=n,s.y+=r,s.z+=o}}frameUpdate(t){this.magnitudeValue=this.magnitude.genValue(this.memory)}toJSON(){return{type:this.type,direction:[this.direction.x,this.direction.y,this.direction.z],magnitude:this.magnitude.toJSON()}}static fromJSON(t){return new se(new K(t.direction[0],t.direction[1],t.direction[2]),Ut(t.magnitude??t.force))}clone(){return new se(this.direction.clone(),this.magnitude.clone())}reset(){}}class ne{constructor(t=0,e=0,i=new K){this.scaleX=t,this.scaleY=e,this.position=i,this.locations=[]}transform(t,e){t.x=this.locations[e%this.locations.length].x*this.scaleX+this.position.x,t.y=this.locations[e%this.locations.length].y*this.scaleY+this.position.y,t.z=this.position.z}static fromJSON(t){const e=new ne(t.scaleX,t.scaleY,new K(t.position[0],t.position[1],t.position[2]));return e.locations=t.locations.map(t=>new St(t.x,t.y)),e}clone(){const t=new ne(this.scaleX,this.scaleY,this.position.clone());return t.locations=this.locations.map(t=>t.clone()),t}toJSON(){return{scaleX:this.scaleX,scaleY:this.scaleY,position:this.position,locations:this.locations.map(t=>({x:t.x,y:t.y}))}}fromImage(t,e){const i=document.createElement("canvas");i.width=t.width,i.height=t.height;const s=i.getContext("2d");if(!s)return;s.drawImage(t,0,0);const n=s.getImageData(0,0,i.width,i.height,{colorSpace:"srgb"});i.remove(),this.locations.length=0;for(let t=0;t<n.height;t++)for(let i=0;i<n.width;i++)n.data[4*(t*n.width+i)+3]>e&&this.locations.push(new St(i,n.height-t))}}function re(t){return"TextureSequencer"===t.type?ne.fromJSON(t):new ne}class oe{constructor(t){this.type="ApplySequences",this.sequencers=[],this.time=0,this.index=0,this.pCount=0,this.tempV=new K,this.delay=t}initialize(t){t.id=this.pCount,t.dst=new K,t.begin=new K,t.inMotion=!1,this.pCount++}reset(){this.time=0,this.index=0,this.pCount=0}update(t,e){const i=this.sequencers[this.index];if(void 0===i)return;const s=t.id*this.delay;this.time>=i[0].a+s&&this.time<=i[0].b+s?(t.inMotion||(t.inMotion=!0,t.begin.copy(t.position),i[1].transform(t.dst,t.id)),t.position.lerpVectors(t.begin,t.dst,oe.BEZIER.genValue((this.time-i[0].a-s)/(i[0].b-i[0].a)))):this.time>i[0].b+s&&(t.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 oe(t.delay);return t.sequencers.forEach(t=>{e.sequencers.push([Ut(t.range),re(t.sequencer)])}),e}clone(){const t=new oe(this.delay);return t.sequencers=this.sequencers.map(t=>[t[0].clone(),t[1].clone()]),t}}oe.BEZIER=new Ft(0,0,1,1);class ae{constructor(t){this.angle=t,this.type="ChangeEmitDirection",this._temp=new K,this._q=new H,this.memory={data:[],dataCount:0}}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.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,b()*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 ae(Ut(t.angle))}clone(){return new ae(this.angle)}reset(){}}class he{constructor(t,e){this.color=t,this.speedRange=e,this.type="ColorBySpeed"}initialize(t){this.color.startGen(t.memory)}update(t,e){const i=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a);this.color.genColor(t.memory,t.color,i),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 he(Xt(t.color),Ct.fromJSON(t.speedRange))}clone(){return new he(this.color.clone(),this.speedRange.clone())}reset(){}}class le{constructor(t){this.color=t,this.type="ColorOverLife"}initialize(t){this.color.startGen(t.memory)}update(t,e){const i=t.color,s=t.startColor;this.color.genColor(t.memory,i,t.age/t.life),i.x*=s.x,i.y*=s.y,i.z*=s.z,i.w*=s.w}updateAll(t,e,i){const s=this.color;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const n=e.color,r=e.startColor;s.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 le(Xt(t.color))}clone(){return new le(this.color.clone())}reset(){}}function ce(t,e){return Math.floor(b()*(e-t))+t}const ue=new K(0,1,0),de=new K(0,0,0),fe=new K(1,1,1),me=new K(0,0,1);var pe;t.SubParticleEmitMode=void 0,(pe=t.SubParticleEmitMode||(t.SubParticleEmitMode={}))[pe.Death=0]="Death",pe[pe.Birth=1]="Birth",pe[pe.Frame=2]="Frame";const ye={color:1,size:2,rotation:4,lifetime:8};function ge(t){let e=0;for(const i of t)e|=ye[i]??0;return e}class ve{constructor(e,i,s,n=t.SubParticleEmitMode.Frame,r=1,o=[]){this.particleSystem=e,this.useVelocityAsBasis=i,this.subParticleSystem=s,this.mode=n,this.emitProbability=r,this.inherit=o,this.type="EmitSubParticleSystem",this.q_=new H,this.v_=new K,this.v2_=new K,this.subEmissions=new Array,this.spareEmissions=new Array;const a=this.target;a&&(a.onlyUsedByOther=!0)}initialize(t){}update(e,i){(this.mode===t.SubParticleEmitMode.Frame||this.mode===t.SubParticleEmitMode.Birth&&0===e.age||this.mode===t.SubParticleEmitMode.Death&&e.age+i>=e.life)&&this.emit(e,i)}get target(){const t=this.subParticleSystem;if(null!==t&&"object"==typeof t)return t.system}emit(t,e){if(!this.target)return;if(b()>this.emitProbability)return;const i=this.spareEmissions.pop(),s=void 0!==i?i:{burstParticleCount:0,burstParticleIndex:0,isBursting:!1,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,matrix:new nt,travelDistance:0,particle:void 0,previousWorldPos:void 0};s.burstParticleCount=0,s.burstParticleIndex=0,s.isBursting=!1,s.burstIndex=0,s.burstWaveIndex=0,s.time=0,s.waitEmiting=0,s.travelDistance=0,s.particle=t,s.inherit=ge(this.inherit),s.previousWorldPos=void 0,this.setMatrixFromParticle(s.matrix,t),this.subEmissions.push(s)}frameUpdate(t){const e=this.target;if(e)for(let i=0;i<this.subEmissions.length;i++)if(this.subEmissions[i].time>=e.duration){const t=this.subEmissions[i];t.particle=void 0,this.spareEmissions.push(t),this.subEmissions[i]=this.subEmissions[this.subEmissions.length-1],this.subEmissions.length=this.subEmissions.length-1,i--}else{const s=this.subEmissions[i];s.particle&&s.particle.age<s.particle.life?this.setMatrixFromParticle(s.matrix,s.particle):s.particle=void 0,e.emit(t,s,s.matrix)}else this.subEmissions.length=0}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 ve(e,t.useVelocityAsBasis,t.subParticleSystem,t.mode,t.emitProbability,ve.validInherit(t.inherit))}clone(){return new ve(this.particleSystem,this.useVelocityAsBasis,this.subParticleSystem,this.mode,this.emitProbability,this.inherit.slice())}reset(){}static validInherit(t){return Array.isArray(t)?t.filter(t=>t in ye):[]}setMatrixFromParticle(t,e){let i;if(void 0===e.rotation||this.useVelocityAsBasis)if(0!==e.velocity.x||0!==e.velocity.y||1!==e.velocity.z&&0!==e.velocity.z){this.v_.copy(me).cross(e.velocity),this.v2_.copy(e.velocity).cross(this.v_);const i=this.v_.length(),s=this.v2_.length();t.set(this.v_.x/i,this.v2_.x/s,e.velocity.x,e.position.x,this.v_.y/i,this.v2_.y/s,e.velocity.y,e.position.y,this.v_.z/i,this.v2_.z/s,e.velocity.z,e.position.z,0,0,0,1)}else t.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1);else e.rotation instanceof H?i=e.rotation:(this.q_.setFromAxisAngle(me,e.rotation),i=this.q_),t.compose(e.position,i,fe);this.particleSystem.worldSpace||t.multiplyMatrices(this.particleSystem.emitter.matrixWorld,t)}}class xe{initialize(t,e){this.ps=e,this.x.startGen(t.memory),this.y.startGen(t.memory),this.z.startGen(t.memory)}constructor(t,e,i){this.x=t,this.y=e,this.z=i,this.type="ForceOverLife",this._temp=new K,this._tempScale=new K,this._tempQ=new H}update(t,e){this._temp.set(this.x.genValue(t.memory,t.age/t.life),this.y.genValue(t.memory,t.age/t.life),this.z.genValue(t.memory,t.age/t.life)),void 0===this.ps||this.ps.worldSpace?t.velocity.addScaledVector(this._temp,e*(this.ps?.motionScale??1)):(this._temp.multiply(this._tempScale).applyQuaternion(this._tempQ),t.velocity.addScaledVector(this._temp,e))}updateAll(t,e,i){const s=this.ps;if(void 0===s)return;const n=this._temp,r=this.x,o=this.y,a=this.z,h=s.worldSpace,l=h?i*(s.motionScale??1):i;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const s=e.memory,c=e.age/e.life;n.set(r.genValue(s,c),o.genValue(s,c),a.genValue(s,c)),h||n.multiply(this._tempScale).applyQuaternion(this._tempQ),e.velocity.addScaledVector(n,l)}}toJSON(){return{type:this.type,x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new xe(Ut(t.x),Ut(t.y),Ut(t.z))}frameUpdate(t){if(this.ps&&!this.ps.worldSpace){const t=this._temp,e=this._tempQ,i=this._tempScale;this.ps.emitter.matrixWorld.decompose(t,e,i),e.invert(),i.set(1/i.x,1/i.y,1/i.z)}}clone(){return new xe(this.x.clone(),this.y.clone(),this.z.clone())}reset(){}}class Se{constructor(t,e={}){this.type="FrameOverLife",this.salt=new Ct(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,i){for(let i=0;i<e;i++){const e=t[i];e.age>=e.life||(e.uvTile=this.frameAt(e,e.age,e.age/e.life))}}frameAt(t,e,i){if(this.fps>0){const s=this.sampleFrame(t,i),n=this.frameCount;let r=Math.floor(e*this.fps)+this.offset(t);return this.random&&n>0?s+Math.floor(Se.hash(r,this.saltOf(t))*n):(n>0&&(r=this.loop?Se.wrap(r,n):Math.min(r,n-1)),s+r)}let s;if(1!==this.cycles&&this.cycles>0){const e=i*this.cycles;s=this.sampleFrame(t,i>=1?1:e-Math.floor(e))}else s=this.sampleFrame(t,i);return void 0!==this.startFrame&&(s+=this.offset(t),this.frameCount>0&&(s=Se.wrap(s,this.frameCount))),s}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 i=43758.5453*Math.sin(12.9898*t+7833.233*e);return Math.min(i-Math.floor(i),.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 Se(Ut(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?Ut(t.startFrame):void 0})}clone(){return new Se(this.frame.clone(),{fps:this.fps,cycles:this.cycles,frameCount:this.frameCount,loop:this.loop,random:this.random,startFrame:this.startFrame?.clone()})}reset(){}}class be{constructor(t,e){this.center=t,this.magnitude=e,this.type="GravityForce",this.temp=new K}initialize(t){}update(t,e){const i=t.position.distanceToSquared(this.center);0!==i&&(this.temp.copy(this.center).sub(t.position).normalize(),t.velocity.addScaledVector(this.temp,this.magnitude/i*e))}updateAll(t,e,i){const s=this.center.x,n=this.center.y,r=this.center.z,o=this.magnitude*i;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const a=e.position,h=s-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 be(new K(t.center[0],t.center[1],t.center[2]),t.magnitude)}clone(){return new be(this.center.clone(),this.magnitude)}reset(){}}class we{constructor(t=new Bt(1),e="initial"){this.multiplier=t,this.mode=e,this.type="InheritVelocity",this._temp=new K,this._tempPos=new K,this._tempQInv=new H,this._tempScaleInv=new K(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 we(t.multiplier?Ut(t.multiplier):new Bt(1),"current"===t.mode?"current":"initial")}clone(){return new we(this.multiplier.clone(),this.mode)}reset(){}}class Me{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"}update(t,e){let i=t.velocity.length(),s=this.speed.genValue(t.memory,t.age/t.life)*this.motionScale();if(i>s){const n=(i-s)/i;t.velocity.multiplyScalar(1-n*this.dampen*e*20)}}updateAll(t,e,i){const s=this.speed,n=this.dampen*i*20,r=this.motionScale();for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const o=e.velocity,a=o.length(),h=s.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 Me(Ut(t.speed),t.dampen)}frameUpdate(t){this.speed.refreshTable?.()}clone(){return new Me(this.speed.clone(),this.dampen)}reset(){}}class ze{constructor(t=64){this.previousVelocity=ze.EMPTY,this.rotationQuaternion=ze.EMPTY,this.angularVelocityQuaternion=ze.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*ze.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=ze.grow(this.position,3*e),this.previousPosition=ze.grow(this.previousPosition,3*e);const i=this.previousSize===this.size,s=this.previousColor===this.color;if(i||(this.previousSize=ze.grow(this.previousSize,3*e)),this.previousVelocity.length>0&&(this.previousVelocity=ze.grow(this.previousVelocity,3*e)),this.rotationQuaternion.length>0){const t=this.rotationQuaternion.length;this.rotationQuaternion=ze.grow(this.rotationQuaternion,4*e),this.angularVelocityQuaternion=ze.grow(this.angularVelocityQuaternion,4*e);for(let i=t+3;i<4*e;i+=4)this.rotationQuaternion[i]=1,this.angularVelocityQuaternion[i]=1}if(s||(this.previousColor=ze.grow(this.previousColor,4*e)),this.velocity=ze.grow(this.velocity,3*e),this.size=ze.grow(this.size,3*e),this.startSize=ze.grow(this.startSize,3*e),this.color=ze.grow(this.color,4*e),i&&(this.previousSize=this.size),s&&(this.previousColor=this.color),this.startColor=ze.grow(this.startColor,4*e),this.scalars=ze.growDouble(this.scalars,e*ze.SCALAR_STRIDE),this.memoryStride>0){const t=new Float64Array(e*this.memoryStride);t.fill(NaN),t.set(this.memory),this.memory=t}this.rotation=ze.grow(this.rotation,e),this.angularVelocity=ze.grow(this.angularVelocity,e),this.uvTile=ze.grow(this.uvTile,e),this.startSpeed=ze.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 i=e.length;let s=this.memoryStride;if(i>s||this.memory.length<this.capacity*s){s=Math.max(s,i);const t=new Float64Array(this.capacity*s);t.fill(NaN);const e=this.memoryStride,n=this.memory,r=e>0?n.length/e:0;for(let i=0,o=0,a=0;i<r;i++,o+=e,a+=s)for(let i=0;i<e;i++)t[a+i]=n[o+i];this.memory=t,this.memoryStride=s}const n=t*s;for(let t=0;t<s;t++){const s=t<i?e[t]:void 0;this.memory[n+t]="number"==typeof s?s: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 i=3*t,s=3*e;ze.swap3(this.position,i,s),ze.swap3(this.previousPosition,i,s),this.previousSize!==this.size&&ze.swap3(this.previousSize,i,s),this.previousVelocity.length>0&&ze.swap3(this.previousVelocity,i,s),ze.swap3(this.velocity,i,s),ze.swap3(this.size,i,s),ze.swap3(this.startSize,i,s);const n=4*t,r=4*e;ze.swap4(this.color,n,r),this.previousColor!==this.color&&ze.swap4(this.previousColor,n,r),ze.swap4(this.startColor,n,r),this.rotationQuaternion.length>0&&(ze.swap4(this.rotationQuaternion,n,r),ze.swap4(this.angularVelocityQuaternion,n,r)),ze.swap3(this.scalars,t*ze.SCALAR_STRIDE,e*ze.SCALAR_STRIDE);const o=this.memoryStride;if(o>0){const i=this.memory;for(let s=0,n=t*o,r=e*o;s<o;s++,n++,r++){const t=i[n];i[n]=i[r],i[r]=t}}ze.swap1(this.rotation,t,e),ze.swap1(this.angularVelocity,t,e),ze.swap1(this.uvTile,t,e),ze.swap1(this.startSpeed,t,e),ze.swap1(this.flip,t,e)}static swap1(t,e,i){const s=t[e];t[e]=t[i],t[i]=s}static growDouble(t,e){const i=new Float64Array(e);return i.set(t),i}static swap3(t,e,i){let s=t[e];t[e]=t[i],t[i]=s,s=t[e+1],t[e+1]=t[i+1],t[i+1]=s,s=t[e+2],t[e+2]=t[i+2],t[i+2]=s}static swap4(t,e,i){ze.swap3(t,e,i);const s=t[e+3];t[e+3]=t[i+3],t[i+3]=s}static grow(t,e){const i=new Float32Array(e);return i.set(t),i}}ze.EMPTY=new Float32Array(0),ze.SCALAR_STRIDE=3,ze.AGE=0,ze.LIFE=1,ze.SPEED_MODIFIER=2;const _e=.5*(Math.sqrt(3)-1),Ve=(3-Math.sqrt(3))/6,Te=1/3,Pe=1/6,Oe=(Math.sqrt(5)-1)/4,Ae=(5-Math.sqrt(5))/20,Be=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]),Ce=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 Fe{constructor(t=e){const e="function"==typeof t?t:function(t){let e=0,i=0,s=0,n=1;const r=function(){let t=4022871197;return function(e){e=e.toString();for(let i=0;i<e.length;i++){t+=e.charCodeAt(i);let s=.02519603282416938*t;t=s>>>0,s-=t,s*=t,t=s>>>0,s-=t,t+=4294967296*s}return 2.3283064365386963e-10*(t>>>0)}}();e=r(" "),i=r(" "),s=r(" "),e-=r(t),e<0&&(e+=1);i-=r(t),i<0&&(i+=1);s-=r(t),s<0&&(s+=1);return function(){const t=2091639*e+2.3283064365386963e-10*n;return e=i,i=s,s=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 i=0;i<255;i++){const s=i+~~(t()*(256-i)),n=e[i];e[i]=e[s],e[s]=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 i=this.permMod12,s=this.perm;let n=0,r=0,o=0;const a=(t+e)*_e,h=Math.floor(t+a),l=Math.floor(e+a),c=(h+l)*Ve,u=t-(h-c),d=e-(l-c);let f,m;u>d?(f=1,m=0):(f=0,m=1);const p=u-f+Ve,y=d-m+Ve,g=u-1+2*Ve,v=d-1+2*Ve,x=255&h,S=255&l;let b=.5-u*u-d*d;if(b>=0){const t=3*i[x+s[S]];b*=b,n=b*b*(Be[t]*u+Be[t+1]*d)}let w=.5-p*p-y*y;if(w>=0){const t=3*i[x+f+s[S+m]];w*=w,r=w*w*(Be[t]*p+Be[t+1]*y)}let M=.5-g*g-v*v;if(M>=0){const t=3*i[x+1+s[S+1]];M*=M,o=M*M*(Be[t]*g+Be[t+1]*v)}return 70*(n+r+o)}noise3D(t,e,i){const s=this.permMod12,n=this.perm;let r,o,a,h;const l=(t+e+i)*Te,c=Math.floor(t+l),u=Math.floor(e+l),d=Math.floor(i+l),f=(c+u+d)*Pe,m=t-(c-f),p=e-(u-f),y=i-(d-f);let g,v,x,S,b,w;m>=p?p>=y?(g=1,v=0,x=0,S=1,b=1,w=0):m>=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):p<y?(g=0,v=0,x=1,S=0,b=1,w=1):m<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=m-g+Pe,z=p-v+Pe,_=y-x+Pe,V=m-S+2*Pe,T=p-b+2*Pe,P=y-w+2*Pe,O=m-1+.5,A=p-1+.5,B=y-1+.5,C=255&c,F=255&u,$=255&d;let I=.6-m*m-p*p-y*y;if(I<0)r=0;else{const t=3*s[C+n[F+n[$]]];I*=I,r=I*I*(Be[t]*m+Be[t+1]*p+Be[t+2]*y)}let U=.6-M*M-z*z-_*_;if(U<0)o=0;else{const t=3*s[C+g+n[F+v+n[$+x]]];U*=U,o=U*U*(Be[t]*M+Be[t+1]*z+Be[t+2]*_)}let E=.6-V*V-T*T-P*P;if(E<0)a=0;else{const t=3*s[C+S+n[F+b+n[$+w]]];E*=E,a=E*E*(Be[t]*V+Be[t+1]*T+Be[t+2]*P)}let N=.6-O*O-A*A-B*B;if(N<0)h=0;else{const t=3*s[C+1+n[F+1+n[$+1]]];N*=N,h=N*N*(Be[t]*O+Be[t+1]*A+Be[t+2]*B)}return 32*(r+o+a+h)}noise4D(t,e,i,s){const n=this.perm;let r,o,a,h,l;const c=(t+e+i+s)*Oe,u=Math.floor(t+c),d=Math.floor(e+c),f=Math.floor(i+c),m=Math.floor(s+c),p=(u+d+f+m)*Ae,y=t-(u-p),g=e-(d-p),v=i-(f-p),x=s-(m-p);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,T=M>=3?1:0,P=S>=2?1:0,O=b>=2?1:0,A=w>=2?1:0,B=M>=2?1:0,C=S>=1?1:0,F=b>=1?1:0,$=w>=1?1:0,I=M>=1?1:0,U=y-z+Ae,E=g-_+Ae,N=v-V+Ae,R=x-T+Ae,D=y-P+2*Ae,L=g-O+2*Ae,q=v-A+2*Ae,k=x-B+2*Ae,J=y-C+3*Ae,Q=g-F+3*Ae,G=v-$+3*Ae,W=x-I+3*Ae,j=y-1+4*Ae,Y=g-1+4*Ae,X=v-1+4*Ae,Z=x-1+4*Ae,H=255&u,K=255&d,tt=255&f,et=255&m;let it=.6-y*y-g*g-v*v-x*x;if(it<0)r=0;else{const t=n[H+n[K+n[tt+n[et]]]]%32*4;it*=it,r=it*it*(Ce[t]*y+Ce[t+1]*g+Ce[t+2]*v+Ce[t+3]*x)}let st=.6-U*U-E*E-N*N-R*R;if(st<0)o=0;else{const t=n[H+z+n[K+_+n[tt+V+n[et+T]]]]%32*4;st*=st,o=st*st*(Ce[t]*U+Ce[t+1]*E+Ce[t+2]*N+Ce[t+3]*R)}let nt=.6-D*D-L*L-q*q-k*k;if(nt<0)a=0;else{const t=n[H+P+n[K+O+n[tt+A+n[et+B]]]]%32*4;nt*=nt,a=nt*nt*(Ce[t]*D+Ce[t+1]*L+Ce[t+2]*q+Ce[t+3]*k)}let rt=.6-J*J-Q*Q-G*G-W*W;if(rt<0)h=0;else{const t=n[H+C+n[K+F+n[tt+$+n[et+I]]]]%32*4;rt*=rt,h=rt*rt*(Ce[t]*J+Ce[t+1]*Q+Ce[t+2]*G+Ce[t+3]*W)}let ot=.6-j*j-Y*Y-X*X-Z*Z;if(ot<0)l=0;else{const t=n[H+1+n[K+1+n[tt+1+n[et+1]]]]%32*4;ot*=ot,l=ot*ot*(Ce[t]*j+Ce[t+1]*Y+Ce[t+2]*X+Ce[t+3]*Z)}return 27*(r+o+a+h+l)}}const $e=100,Ie=new Array($e),Ue=new K,Ee=new H;function Ne(t){let e=Ie[t];return void 0===e&&(e=new Fe(t),Ie[t]=e),e}class Re{constructor(t,e,i=new Bt(1),s=new Bt(0),n=new Bt(0),r){this.frequency=t,this.power=e,this.positionAmount=i,this.rotationAmount=s,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,i){const s=t.noise2D(0,e),n=this.remap;return void 0===n?s:n.genValue(i,.5*(s+1))}initialize(t){const e="number"==typeof t.rotation;let i=t._noiseState;if(void 0===i)return i={lastPos:new K,lastRot:0,lastRotQ:e?null:new H,generatorX:Ne(ce(0,$e)),generatorY:Ne(ce(0,$e)),generatorZ:Ne(ce(0,$e)),generatorW:Ne(ce(0,$e))},void(t._noiseState=i);i.lastPos.set(0,0,0),i.lastRot=0,e?i.lastRotQ=null:null===i.lastRotQ?i.lastRotQ=new H:i.lastRotQ.set(0,0,0,1),i.generatorX=Ne(ce(0,$e)),i.generatorY=Ne(ce(0,$e)),i.generatorZ=Ne(ce(0,$e)),i.generatorW=Ne(ce(0,$e))}static constantOf(t){return t instanceof Bt?t.value:NaN}update(t,e){const i=t._noiseState;if(void 0===i)return;const s=t.memory,n=t.age/t.life,r=this._frequency,o=r==r?r:this.frequency.genValue(s,n),a=this._power,h=a==a?a:this.power.genValue(s,n),l=this._positionAmount,c=l==l?l:this.positionAmount.genValue(s,n),u=this._rotationAmount,d=u==u?u:this.rotationAmount.genValue(s,n),f=t.age*o+this.scrollOffset;if(c>0){const e=h*c;t.position.sub(i.lastPos),Ue.set(this.sample(i.generatorX,f,s)*e,this.sample(i.generatorY,f,s)*e,this.sample(i.generatorZ,f,s)*e),t.position.add(Ue),i.lastPos.copy(Ue)}if(d>0){const e=h*d;if("number"==typeof t.rotation){const n=this.sample(i.generatorW,f,s)*Math.PI*e;t.rotation=t.rotation-i.lastRot+n,i.lastRot=n}else if(null!==i.lastRotQ){const n=t.rotation;i.lastRotQ.invert(),n.multiply(i.lastRotQ),Ee.set(this.sample(i.generatorX,f,s)*e,this.sample(i.generatorY,f,s)*e,this.sample(i.generatorZ,f,s)*e,this.sample(i.generatorW,f,s)*e).normalize(),n.multiply(Ee),i.lastRotQ.copy(Ee)}}}updateAll(t,e,i){const s=e>0?t[0].store:void 0;if(void 0===s){for(let s=0;s<e;s++){const e=t[s];e.age<e.life&&this.update(e,i)}return}const n=s.position,r=s.rotation,o=s.scalars,a=ze.SCALAR_STRIDE,h=this._frequency,l=this._power,c=this._positionAmount,u=this._rotationAmount;for(let i=0,s=0,d=0;i<e;i++,s+=3,d+=a){const e=o[d],a=o[d+1];if(e>=a)continue;const f=t[i],m=f._noiseState;if(void 0===m)continue;const p=f.memory,y=e/a,g=h==h?h:this.frequency.genValue(p,y),v=l==l?l:this.power.genValue(p,y),x=c==c?c:this.positionAmount.genValue(p,y),S=u==u?u:this.rotationAmount.genValue(p,y),b=e*g+this.scrollOffset;if(x>0){const t=v*x,e=m.lastPos,i=this.sample(m.generatorX,b,p)*t,r=this.sample(m.generatorY,b,p)*t,o=this.sample(m.generatorZ,b,p)*t;n[s]=Math.fround(n[s]-e.x)+i,n[s+1]=Math.fround(n[s+1]-e.y)+r,n[s+2]=Math.fround(n[s+2]-e.z)+o,e.set(i,r,o)}if(S>0){const t=v*S;if("number"==typeof f.rotation){const e=this.sample(m.generatorW,b,p)*Math.PI*t;r[i]=r[i]-m.lastRot+e,m.lastRot=e}else if(null!==m.lastRotQ){const e=f.rotation;m.lastRotQ.invert(),e.multiply(m.lastRotQ),Ee.set(this.sample(m.generatorX,b,p)*t,this.sample(m.generatorY,b,p)*t,this.sample(m.generatorZ,b,p)*t,this.sample(m.generatorW,b,p)*t).normalize(),e.multiply(Ee),m.lastRotQ.copy(Ee)}}}}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=Re.constantOf(this.frequency),this._power=Re.constantOf(this.power),this._positionAmount=Re.constantOf(this.positionAmount),this._rotationAmount=Re.constantOf(this.rotationAmount)}static fromJSON(t){return new Re(Ut(t.frequency),Ut(t.power),Ut(t.positionAmount),Ut(t.rotationAmount),t.scrollSpeed?Ut(t.scrollSpeed):new Bt(0),t.remap?Ut(t.remap):void 0)}clone(){return new Re(this.frequency.clone(),this.power.clone(),this.positionAmount.clone(),this.rotationAmount.clone(),this.scrollSpeed.clone(),this.remap?.clone())}reset(){this.scrollOffset=0}}class De{constructor(t,e=new K(0,1,0)){this.orbitSpeed=t,this.axis=e,this.type="OrbitOverLife",this.temp=new K,this.rotation=new H}initialize(t){this.orbitSpeed.startGen(t.memory)}update(t,e){this.temp.copy(t.position).projectOnVector(this.axis),this.rotation.setFromAxisAngle(this.axis,this.orbitSpeed.genValue(t.memory,t.age/t.life)*e),t.position.sub(this.temp),t.position.applyQuaternion(this.rotation),t.position.add(this.temp)}updateAll(t,e,i){const s=this.orbitSpeed,n=this.axis,r=this.temp,o=this.rotation;for(let a=0;a<e;a++){const e=t[a];if(e.age>=e.life)continue;const h=e.position;r.copy(h).projectOnVector(n),o.setFromAxisAngle(n,s.genValue(e.memory,e.age/e.life)*i),h.sub(r),h.applyQuaternion(o),h.add(r)}}frameUpdate(t){}toJSON(){return{type:this.type,orbitSpeed:this.orbitSpeed.toJSON(),axis:[this.axis.x,this.axis.y,this.axis.z]}}static fromJSON(t){return new De(Ut(t.orbitSpeed),t.axis?new K(t.axis[0],t.axis[1],t.axis[2]):void 0)}clone(){return new De(this.orbitSpeed.clone())}reset(){}}class Le{constructor(t){this.angularVelocity=t,this.type="Rotation3DOverLife",this.tempQuat=new H}initialize(t){t.rotation instanceof H&&(t.angularVelocity=new H,this.angularVelocity.startGen(t.memory))}update(t,e){if(t.rotation instanceof H){this.angularVelocity.genValue(t.memory,this.tempQuat,e,t.age/t.life),t.rotation.multiply(this.tempQuat);const i=t.angularVelocity;i instanceof H&&i.copy(this.tempQuat)}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new Le(Kt(t.angularVelocity))}frameUpdate(t){}clone(){return new Le(this.angularVelocity.clone())}reset(){}}class qe{constructor(t,e){this.angularVelocity=t,this.speedRange=e,this.type="RotationBySpeed",this.tempQuat=new H}initialize(t){"number"==typeof t.rotation&&this.angularVelocity.startGen(t.memory)}update(t,e){if("number"==typeof t.rotation){const i=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a),s=this.angularVelocity.genValue(t.memory,i);t.rotation+=e*s,t.angularVelocity=s}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new qe(Ut(t.angularVelocity),Ct.fromJSON(t.speedRange))}frameUpdate(t){}clone(){return new qe(this.angularVelocity.clone(),this.speedRange.clone())}reset(){}}class ke{constructor(t){this.angularVelocity=t,this.type="RotationOverLife",this.tempQuat=new H}initialize(t){"number"==typeof t.rotation?this.angularVelocity.startGen(t.memory):t.rotation instanceof H&&(this.angularVelocity.startGen(t.memory),t.angularVelocity instanceof H||(t.angularVelocity=new H))}update(t,e){if("number"==typeof t.rotation){const i=this.angularVelocity.genValue(t.memory,t.age/t.life);t.rotation+=e*i,t.angularVelocity=i}else if(t.rotation instanceof H){const i=this.angularVelocity.genValue(t.memory,t.age/t.life);this.turnAboutZ(t,t.rotation,i*e)}}updateAll(t,e,i){const s=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=s.genValue(e.memory,e.age/e.life);e.rotation=r+i*t,e.angularVelocity=t}else if(r instanceof H){const t=s.genValue(e.memory,e.age/e.life);this.turnAboutZ(e,r,t*i)}}}turnAboutZ(t,e,i){const s=this.tempQuat.setFromAxisAngle(me,i);e.multiply(s);const n=t.angularVelocity;n instanceof H&&n.copy(s)}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new ke(Ut(t.angularVelocity))}frameUpdate(t){this.angularVelocity.refreshTable?.()}clone(){return new ke(this.angularVelocity.clone())}reset(){}}class Je{initialize(t){this.size.startGen(t.memory)}constructor(t,e){this.size=t,this.speedRange=e,this.type="SizeBySpeed"}update(t){const e=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a);this.size instanceof te?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 Je(ie(t.size),Ct.fromJSON(t.speedRange))}frameUpdate(t){}clone(){return new Je(this.size.clone(),this.speedRange.clone())}reset(){}}class Qe{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 te}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 i=this._size.genValue(t.memory,e),s=t.size,n=t.startSize;s.x=n.x*i,s.y=n.y*i,s.z=n.z*i}}updateAll(t,e,i){if(this._sizeIsVector3){const i=this._size;for(let s=0;s<e;s++){const e=t[s];e.age>=e.life||i.genValue(e.memory,e.size,e.age/e.life).multiply(e.startSize)}return}const s=this._size;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const n=s.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 Qe(ie(t.size))}frameUpdate(t){this._size.refreshTable?.()}clone(){return new Qe(this.size.clone())}reset(){}}class Ge{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,i){const s=this.speed;for(let i=0;i<e;i++){const e=t[i];e.age>=e.life||(e.speedModifier=s.genValue(e.memory,e.age/e.life))}}toJSON(){return{type:this.type,speed:this.speed.toJSON()}}static fromJSON(t){return new Ge(Ut(t.speed))}frameUpdate(t){this.speed.refreshTable?.()}clone(){return new Ge(this.speed.clone())}reset(){}}class We{constructor(t,e,i,s){this.scale=t,this.octaves=e,this.velocityMultiplier=i,this.timeScale=s,this.type="TurbulenceField",this.generator=new Fe(b),this.timeOffset=new K,this.temp=new K,this.temp2=new K,this.timeOffset.x=b()/this.scale.x*this.timeScale.x,this.timeOffset.y=b()/this.scale.y*this.timeScale.y,this.timeOffset.z=b()/this.scale.z*this.timeScale.z}initialize(t){}update(t,e){const i=t.position.x/this.scale.x,s=t.position.y/this.scale.y,n=t.position.z/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(i*r,s*r,n*r,this.timeOffset.x*r)/r,this.generator.noise4D(i*r,s*r,n*r,this.timeOffset.y*r)/r,this.generator.noise4D(i*r,s*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,i){const s=e>0?t[0].store:void 0;if(void 0===s){for(let s=0;s<e;s++){const e=t[s];e.age<e.life&&this.update(e,i)}return}const n=s.position,r=s.velocity,o=s.scalars,a=ze.SCALAR_STRIDE,h=this.generator,l=this.octaves,c=1/this.scale.x,u=1/this.scale.y,d=1/this.scale.z,f=this.velocityMultiplier.x*i,m=this.velocityMultiplier.y*i,p=this.velocityMultiplier.z*i,y=this.timeOffset.x,g=this.timeOffset.y,v=this.timeOffset.z;for(let t=0,i=0,s=0;t<e;t++,i+=3,s+=a){if(o[s]>=o[s+1])continue;const t=n[i]*c,e=n[i+1]*u,a=n[i+2]*d;let x=0,S=0,b=0,w=1;for(let i=0;i<l;i++){const i=t*w,s=e*w,n=a*w;x+=h.noise4D(i,s,n,y*w)/w,S+=h.noise4D(i,s,n,g*w)/w,b+=h.noise4D(i,s,n,v*w)/w,w*=2}r[i]+=x*f,r[i+1]+=S*m,r[i+2]+=b*p}}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]}}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 We(new K(t.scale[0],t.scale[1],t.scale[2]),t.octaves,new K(t.velocityMultiplier[0],t.velocityMultiplier[1],t.velocityMultiplier[2]),new K(t.timeScale[0],t.timeScale[1],t.timeScale[2]))}clone(){return new We(this.scale.clone(),this.octaves,this.velocityMultiplier.clone(),this.timeScale.clone())}reset(){}}const je=new K(1,0,0),Ye=new K(0,1,0),Xe=new K(0,0,1);class Ze{constructor(t=new Bt(0),e=new Bt(0),i=new Bt(0),s=new Bt(0),n=new Bt(0),r=new Bt(0),o="local",a=new Bt(0),h=new K){this.linearX=t,this.linearY=e,this.linearZ=i,this.orbitalX=s,this.orbitalY=n,this.orbitalZ=r,this.space=o,this.radial=a,this.orbitalOffset=h,this.type="VelocityOverLife",this._temp=new K,this._tempEmitterPos=new K,this._tempQ=new H,this._tempQInv=new H,this._tempScale=new K(1,1,1),this._tempScaleInv=new K(1,1,1),this._tempRot=new H,this._axisX=new K(1,0,0),this._axisY=new K(0,1,0),this._axisZ=new K(0,0,1),this._center=new K}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(je),this._axisY.copy(Ye),this._axisZ.copy(Xe),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 i=t.age/t.life;this._temp.set(this.linearX.genValue(t.memory,i),this.linearY.genValue(t.memory,i),this.linearZ.genValue(t.memory,i));const s=void 0!==this.ps&&this.ps.worldSpace;s&&"local"===this.space?this._temp.multiply(this._tempScale).applyQuaternion(this._tempQ):s||"world"!==this.space||this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv),t.position.addScaledVector(this._temp,e);const n=this.radial.genValue(t.memory,i);if(0!==n){this._temp.copy(t.position).sub(this._center);const i=this._temp.length();i>0&&t.position.addScaledVector(this._temp,n*e/i)}const r=this.orbitalX.genValue(t.memory,i)*e,o=this.orbitalY.genValue(t.memory,i)*e,a=this.orbitalZ.genValue(t.memory,i)*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,i){0!==i&&(this._tempRot.setFromAxisAngle(e,i),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?Ut(t):new Bt(0);return new Ze(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 K(t.orbitalOffset[0]??0,t.orbitalOffset[1]??0,t.orbitalOffset[2]??0):new K)}clone(){return new Ze(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 He{constructor(t){this.data=t,this.next=null,this.prev=null}hasPrev(){return null!==this.prev}hasNext(){return null!==this.next}}class Ke{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 He(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 He(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 i=new He(e);i.next=t,i.prev=t.prev,null!==i.prev&&(i.prev.next=i),i.next.prev=i,t==this.head&&(this.head=i),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 ti{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 vt(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 vt(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 ze(1),e=0){this.rotationQuaternion=void 0,this.angularVelocityQuaternion=void 0,this.memory=[],this.store=t,this.storeIndex=e;const i=3*e,s=4*e;this.position=new wt(t.position,i),this.previousPosition=new wt(t.previousPosition,i),this.previousVelocity=new wt(t.previousVelocity,i),this.velocity=new wt(t.velocity,i),this.size=new wt(t.size,i),this.startSize=new wt(t.startSize,i),this.color=new Vt(t.color,s),this.startColor=new Vt(t.startColor,s),this.scalars=t.scalars,this.scalarOffset=e*ze.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,i=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,i),this.startColor.bind(t.startColor,i),this.rotationQuaternion?.bind(t.rotationQuaternion,i),this.angularVelocityQuaternion?.bind(t.angularVelocityQuaternion,i),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*ze.SCALAR_STRIDE}get died(){return this.age>=this.life}reset(){this.memory.length=0}}const ei=new Float32Array(0);class ii{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 Ke)}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 ze(1),e=0){this.length=100,this._previous=void 0,this.historyPositions=ei,this.historySizes=ei,this.historyBaseSizes=ei,this.headWidthScale=1,this.historyColors=ei,this.historySides=ei,this.historyCapacity=0,this.historyHead=0,this.historyCount=0,this.memory=[],this.store=t,this.storeIndex=e;const i=3*e,s=4*e;this.position=new wt(t.position,i),this.previousPosition=new wt(t.previousPosition,i),this.previousVelocity=new wt(t.previousVelocity,i),this.velocity=new wt(t.velocity,i),this.size=new wt(t.size,i),this.startSize=new wt(t.startSize,i),this.color=new Vt(t.color,s),this.startColor=new Vt(t.startColor,s),this.scalars=t.scalars,this.scalarOffset=e*ze.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,i=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,i),this.startColor.bind(t.startColor,i),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*ze.SCALAR_STRIDE}ensureHistoryCapacity(t){this.historyCapacity!==t&&(this.historyCapacity=t,this.historyPositions=new Float32Array(3*t),this.historySizes=new Float32Array(t),this.historyBaseSizes=new Float32Array(t),this.historyColors=new Float32Array(4*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(){0===this.historyCapacity&&this.ensureHistoryCapacity(Math.max(1,Math.ceil(this.length)));const t=this.historyCapacity,e=this.store,i=this.storeIndex,s=i*ze.SCALAR_STRIDE;if(e.scalars[s+ze.AGE]>e.scalars[s+ze.LIFE])return void(this.historyCount>0&&this.historyCount--);const n=this.historyHead,r=3*n,o=this.historyPositions,a=e.position,h=3*i;o[r]=a[h],o[r+1]=a[h+1],o[r+2]=a[h+2];const l=e.size[h];this.historyBaseSizes[n]=l,this.historySizes[n]=l*this.headWidthScale;const c=4*n,u=this.historyColors,d=e.color,f=4*i;u[c]=d[f],u[c+1]=d[f+1],u[c+2]=d[f+2],u[c+3]=d[f+3],this.historyHead=(n+1)%t,this.historyCount<t&&this.historyCount++}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.headWidthScale=1,this.resetHistory()}}class si{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 ii))return;const e=t.memory;t.headWidthScale=this.absolute?1:this.width.genValue(e,0);const i=t.historyCount;if(0===i)return;const s=t.historyCapacity,n=t.historySizes,r=t.historyBaseSizes,o=1/t.length,a=this.absolute;let h=t.getHistoryIndex(0);for(let t=0;t<i;t++){const l=this.width.genValue(e,(i-t)*o);n[h]=a?l:r[h]*l,h++,h===s&&(h=0)}}frameUpdate(t){}toJSON(){return{type:this.type,width:this.width.toJSON(),absolute:this.absolute}}static fromJSON(t){return new si(Ut(t.width),t.absolute??!0)}clone(){return new si(this.width.clone(),this.absolute)}reset(){}}const ni={ApplyForce:{type:"ApplyForce",constructor:se,params:[["direction",["vec3"]],["magnitude",["value"]]],loadJSON:se.fromJSON},Noise:{type:"Noise",constructor:Re,params:[["frequency",["value"]],["power",["value"]],["positionAmount",["value"]],["rotationAmount",["value"]]],loadJSON:Re.fromJSON},TurbulenceField:{type:"TurbulenceField",constructor:We,params:[["scale",["vec3"]],["octaves",["number"]],["velocityMultiplier",["vec3"]],["timeScale",["vec3"]]],loadJSON:We.fromJSON},GravityForce:{type:"GravityForce",constructor:be,params:[["center",["vec3"]],["magnitude",["number"]]],loadJSON:be.fromJSON},ColorOverLife:{type:"ColorOverLife",constructor:le,params:[["color",["colorFunc"]]],loadJSON:le.fromJSON},RotationOverLife:{type:"RotationOverLife",constructor:ke,params:[["angularVelocity",["value","valueFunc"]]],loadJSON:ke.fromJSON},Rotation3DOverLife:{type:"Rotation3DOverLife",constructor:Le,params:[["angularVelocity",["rotationFunc"]]],loadJSON:Le.fromJSON},SizeOverLife:{type:"SizeOverLife",constructor:Qe,params:[["size",["value","valueFunc","vec3Func"]]],loadJSON:Qe.fromJSON},ColorBySpeed:{type:"ColorBySpeed",constructor:he,params:[["color",["colorFunc"]],["speedRange",["range"]]],loadJSON:he.fromJSON},RotationBySpeed:{type:"RotationBySpeed",constructor:qe,params:[["angularVelocity",["value","valueFunc"]],["speedRange",["range"]]],loadJSON:qe.fromJSON},SizeBySpeed:{type:"SizeBySpeed",constructor:Je,params:[["size",["value","valueFunc","vec3Func"]],["speedRange",["range"]]],loadJSON:Je.fromJSON},SpeedOverLife:{type:"SpeedOverLife",constructor:Ge,params:[["speed",["value","valueFunc"]]],loadJSON:Ge.fromJSON},FrameOverLife:{type:"FrameOverLife",constructor:Se,params:[["frame",["value","valueFunc"]]],loadJSON:Se.fromJSON},ForceOverLife:{type:"ForceOverLife",constructor:xe,params:[["x",["value","valueFunc"]],["y",["value","valueFunc"]],["z",["value","valueFunc"]]],loadJSON:xe.fromJSON},VelocityOverLife:{type:"VelocityOverLife",constructor:Ze,params:[["linearX",["value","valueFunc"]],["linearY",["value","valueFunc"]],["linearZ",["value","valueFunc"]],["orbitalX",["value","valueFunc"]],["orbitalY",["value","valueFunc"]],["orbitalZ",["value","valueFunc"]],["space",["string"]]],loadJSON:Ze.fromJSON},InheritVelocity:{type:"InheritVelocity",constructor:we,params:[["multiplier",["value","valueFunc"]],["mode",["string"]]],loadJSON:we.fromJSON},OrbitOverLife:{type:"OrbitOverLife",constructor:De,params:[["orbitSpeed",["value","valueFunc"]],["axis",["vec3"]]],loadJSON:De.fromJSON},WidthOverLength:{type:"WidthOverLength",constructor:si,params:[["width",["value","valueFunc"]]],loadJSON:si.fromJSON},ChangeEmitDirection:{type:"ChangeEmitDirection",constructor:ae,params:[["angle",["value"]]],loadJSON:ae.fromJSON},ApplySequences:{type:"ApplySequences",constructor:oe,params:[["delay",["number"]]],loadJSON:oe.fromJSON},EmitSubParticleSystem:{type:"EmitSubParticleSystem",constructor:ve,params:[["particleSystem",["self"]],["useVelocityAsBasis",["boolean"]],["subParticleSystem",["particleSystem"]],["mode",["number"]],["emitProbability",["number"]]],loadJSON:ve.fromJSON},LimitSpeedOverLife:{type:"LimitSpeedOverLife",constructor:Me,params:[["speed",["value","valueFunc"]],["dampen",["number"]]],loadJSON:Me.fromJSON},ApplyCollision:{type:"ApplyCollision",constructor:At,params:[["bounce",["number"]]],loadJSON:At.fromJSON}};function ri(t,e){return ni[t.type]?ni[t.type].loadJSON(t,e):null}const oi={PiecewiseBezier:It,Vector3Function:te,Quaternion:H,ConstantValue:Bt,Gradient:Qt,Vector4View:Vt,AxisAngleGenerator:Et,IntervalValue:Ct,ColorRange:qt};function ai(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 hi(t,e,i){return`let ${e};\n if (${t}_tbl !== null) {\n const tt = ${i};\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, ${i});`}function li(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 ci(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 ui(t,e,i,s,n,r,o){return`{\n const cx = 2 * (${n} * ${i} - ${r} * ${e});\n const cy = 2 * (${r} * ${t} - ${s} * ${i});\n const cz = 2 * (${s} * ${e} - ${n} * ${t});\n const nx = ${t} + ${o} * cx + ${n} * cz - ${r} * cy;\n const ny = ${e} + ${o} * cy + ${r} * cx - ${s} * cz;\n ${i} = ${i} + ${o} * cz + ${s} * cy - ${n} * cx;\n ${t} = nx;\n ${e} = ny;\n }`}function di(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 fi(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 mi(t,e,i,s){return`{\n const half = ${t} / 2;\n const sn = Math.sin(half);\n const qx = ${e} * sn, qy = ${i} * sn, qz = ${s} * sn, qw = Math.cos(half);\n ${ui("px","py","pz","qx","qy","qz","qw")}\n px = Math.fround(px); py = Math.fround(py); pz = Math.fround(pz);\n }`}function pi(t,e){switch(t.type){case"ColorOverLife":return{setup:li(`g${e}`,`behaviors[${e}].color`),body:`{${ci(`g${e}`,"t")}}`};case"SizeOverLife":return{setup:`const g${e} = behaviors[${e}].size;\n const vec3_${e} = g${e} instanceof deps.Vector3Function;\n ${ai(`sg${e}`,`g${e}`)}`,body:`if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, t).multiply(p.startSize);\n } else {\n ${hi(`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 f${e} = b${e}.magnitudeValue * delta;\n const dx${e} = b${e}.direction.x * f${e};\n const dy${e} = b${e}.direction.y * f${e};\n const dz${e} = b${e}.direction.z * f${e};`,body:`vel[o3] += dx${e}; vel[o3 + 1] += dy${e}; vel[o3 + 2] += dz${e};`};case"RotationOverLife":return{setup:`${ai(`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 ${hi(`g${e}`,"rate","t")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n } else if (quat_${e}) {\n ${hi(`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:`${ai(`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}) {${hi(`g${e}`,"v","t")} uvTile[row] = v;}\n else uvTile[row] = b${e}.frameAt(p, age, t);`};case"SpeedOverLife":return{setup:ai(`g${e}`,`behaviors[${e}].speed`),body:`{${hi(`g${e}`,"v","t")} scalars[s + 2] = v;}`};case"ForceOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${ai(`gx${e}`,`b${e}.x`)}\n ${ai(`gy${e}`,`b${e}.y`)}\n ${ai(`gz${e}`,`b${e}.z`)}\n const local${e} = b${e}.ps !== undefined && !b${e}.ps.worldSpace;\n const ms${e} = !local${e} && b${e}.ps !== undefined ? (b${e}.ps.motionScale ?? 1) : 1;\n ${fi(`sc${e}`,`b${e}._tempScale`)}\n ${di(`q${e}`,`b${e}._tempQ`)}`,body:`{\n ${hi(`gx${e}`,"fx","t")}\n ${hi(`gy${e}`,"fy","t")}\n ${hi(`gz${e}`,"fz","t")}\n if (local${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${ui("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n } else if (ms${e} !== 1) {\n fx *= ms${e}; fy *= ms${e}; fz *= ms${e};\n }\n vel[o3] += fx * delta; vel[o3 + 1] += fy * delta; vel[o3 + 2] += fz * delta;}`};case"LimitSpeedOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${ai(`g${e}`,`b${e}.speed`)}\n const dampen${e} = b${e}.dampen * delta * 20;\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 ${hi(`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 ${li(`g${e}`,`b${e}.color`)}\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};`,body:`{const ts = (startSpeed[row] - lo${e}) / span${e};\n ${ci(`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 ${ai(`sg${e}`,`g${e}`)}`,body:`{const ts = (startSpeed[row] - lo${e}) / span${e};\n if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, ts).multiply(p.startSize);\n } else {\n ${hi(`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 ${ai(`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 const ts = (startSpeed[row] - lo${e}) / span${e};\n ${hi(`g${e}`,"rate","ts")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n }`};case"OrbitOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${ai(`g${e}`,`b${e}.orbitSpeed`)}\n ${fi(`ax${e}`,`b${e}.axis`)}\n const alen${e} = ax${e}x * ax${e}x + ax${e}y * ax${e}y + ax${e}z * ax${e}z;\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:`{let px = pos[o3], py = pos[o3 + 1], pz = pos[o3 + 2];\n let tx = 0, ty = 0, tz = 0;\n if (alen${e} !== 0) {\n const f = (ax${e}x * px + ax${e}y * py + ax${e}z * pz) / alen${e};\n tx = ax${e}x * f; ty = ax${e}y * f; tz = ax${e}z * f;\n }\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 ${hi(`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 ${ui("px","py","pz","qx","qy","qz","qw")}\n pos[o3] = Math.fround(px) + tx;\n pos[o3 + 1] = Math.fround(py) + ty;\n pos[o3 + 2] = Math.fround(pz) + tz;}`};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 ${ai(`lx${e}`,`b${e}.linearX`)}\n ${ai(`ly${e}`,`b${e}.linearY`)}\n ${ai(`lz${e}`,`b${e}.linearZ`)}\n ${ai(`ox${e}`,`b${e}.orbitalX`)}\n ${ai(`oy${e}`,`b${e}.orbitalY`)}\n ${ai(`oz${e}`,`b${e}.orbitalZ`)}\n ${fi(`aX${e}`,`b${e}._axisX`)}\n ${fi(`aY${e}`,`b${e}._axisY`)}\n ${fi(`aZ${e}`,`b${e}._axisZ`)}\n ${fi(`pv${e}`,`b${e}._tempEmitterPos`)}\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 ${fi(`sc${e}`,`toWorld${e} ? b${e}._tempScale : b${e}._tempScaleInv`)}\n ${di(`q${e}`,`toWorld${e} ? b${e}._tempQ : b${e}._tempQInv`)}`,body:`{\n ${hi(`lx${e}`,"fx","t")}\n ${hi(`ly${e}`,"fy","t")}\n ${hi(`lz${e}`,"fz","t")}\n if (convert${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${ui("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 ${hi(`ox${e}`,"rx","t")}\n ${hi(`oy${e}`,"ry","t")}\n ${hi(`oz${e}`,"rz","t")}\n rx *= delta; ry *= delta; rz *= delta;\n if (rx !== 0 || ry !== 0 || rz !== 0) {\n if (world${e}) {\n px = Math.fround(px - pv${e}x); py = Math.fround(py - pv${e}y); pz = Math.fround(pz - pv${e}z);\n }\n if (rx !== 0) ${mi("rx",`aX${e}x`,`aX${e}y`,`aX${e}z`)}\n if (ry !== 0) ${mi("ry",`aY${e}x`,`aY${e}y`,`aY${e}z`)}\n if (rz !== 0) ${mi("rz",`aZ${e}x`,`aZ${e}y`,`aZ${e}z`)}\n if (world${e}) {\n px = Math.fround(px + pv${e}x); py = Math.fround(py + pv${e}y); pz = Math.fround(pz + pv${e}z);\n }\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 ${fi(`sc${e}`,`b${e}._tempScaleInv`)}\n ${di(`q${e}`,`b${e}._tempQInv`)}\n ivx${e} *= sc${e}x; ivy${e} *= sc${e}y; ivz${e} *= sc${e}z;\n ${ui(`ivx${e}`,`ivy${e}`,`ivz${e}`,`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n }\n }\n ${ai(`gm${e}`,`b${e}.multiplier`)}`,body:`if (active${e}) {\n ${hi(`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 yi=new Map;function gi(t,e,i){const s=yi.get(i);if(void 0!==s)return s??void 0;const n=function(t,e){const i=`\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) {${i}};`)(oi)}catch(t){return}}(t,e);return yi.set(i,n??null),n}function vi(t){const e=[];let i=[],s=[],n=[],r=0;const o=()=>{if(0===s.length)return;const t=`${r}:${i.map(t=>t.type).join(",")}`,o=gi(s,n,t);if(void 0!==o)e.push({behaviors:i,run:o});else for(const t of i)e.push({behaviors:[t]});i=[],s=[],n=[]};for(let a=0;a<t.length;a++){const h=t[a],l=pi(h,a);null!==l?(0===s.length&&(r=a),i.push(h),s.push(l),n.push(a)):(o(),e.push({behaviors:[h]}))}return o(),e}var xi,Si;t.BoxEmitFrom=void 0,(xi=t.BoxEmitFrom||(t.BoxEmitFrom={}))[xi.Volume=0]="Volume",xi[xi.Shell=1]="Shell",xi[xi.Edge=2]="Edge";class bi{constructor(e={}){this.type="box",this._point=[0,0,0],this.width=e.width??1,this.height=e.height??1,this.depth=e.depth??1,this.emitFrom=e.emitFrom??t.BoxEmitFrom.Volume,this.boxThickness=e.boxThickness?[...e.boxThickness]:[0,0,0]}update(t,e){}initialize(e,i){const s=this._point;for(let t=0;t<3;t++)s[t]=2*b()-1;const n=Math.floor(3*b())%3;this.emitFrom===t.BoxEmitFrom.Shell?s[n]=this.onSurface(n):this.emitFrom===t.BoxEmitFrom.Edge&&(s[(n+1)%3]=this.onSurface((n+1)%3),s[(n+2)%3]=this.onSurface((n+2)%3)),e.position.set(s[0]*this.width/2,s[1]*this.height/2,s[2]*this.depth/2),e.velocity.set(0,0,e.startSpeed)}onSurface(t){const e=b()<.5?-1:1,i=this.boxThickness[t];return i<=0||b()<.5?e:e*(1-2*i*b())}toJSON(){return{type:"box",width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:[...this.boxThickness]}}static fromJSON(t){return new bi({width:t.width,height:t.height,depth:t.depth,emitFrom:t.emitFrom,boxThickness:Array.isArray(t.boxThickness)?t.boxThickness:void 0})}clone(){return new bi({width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:this.boxThickness})}}function wi(e,i,s,n){let r;switch(t.EmitterMode.Random===e?i=b():t.EmitterMode.Burst===e&&n.isBursting&&(i=n.burstParticleIndex/n.burstParticleCount),r=s>0?Math.floor(i/s)*s:i,e){case t.EmitterMode.Loop:r%=1;break;case t.EmitterMode.PingPong:r=Math.abs(r%2-1)}return r}t.EmitterMode=void 0,(Si=t.EmitterMode||(t.EmitterMode={}))[Si.Random=0]="Random",Si[Si.Loop=1]="Loop",Si[Si.PingPong=2]="PingPong",Si[Si.Burst=3]="Burst";class Mi{constructor(t,e,i){this.position=t??new K,this.rotation=e??new H,this.scale=i??new K(1,1,1)}apply(t){t.position.multiply(this.scale).applyQuaternion(this.rotation).add(this.position);const e=t.velocity,i=e.length();if(0===i)return;e.multiply(this.scale).applyQuaternion(this.rotation);const s=e.length();s>0&&e.multiplyScalar(i/s)}isIdentity(){const{position:t,rotation:e,scale:i}=this;return 0===t.x&&0===t.y&&0===t.z&&0===e.x&&0===e.y&&0===e.z&&1===e.w&&1===i.x&&1===i.y&&1===i.z}toJSON(){const t={},{position:e,rotation:i,scale:s}=this;return 0===e.x&&0===e.y&&0===e.z||(t.position=[e.x,e.y,e.z]),0===i.x&&0===i.y&&0===i.z&&1===i.w||(t.rotation=[i.x,i.y,i.z,i.w]),1===s.x&&1===s.y&&1===s.z||(t.scale=[s.x,s.y,s.z]),t}static fromJSON(t){if(!t)return;const{position:e,rotation:i,scale:s}=t;return new Mi(e?new K(e[0],e[1],e[2]):void 0,i?new H(i[0],i[1],i[2],i[3]):void 0,s?new K(s[0],s[1],s[2]):void 0)}static toShapeJSON(t){return t&&!t.isIdentity()?{transform:t.toJSON()}:{}}clone(){return new Mi(this.position.clone(),this.rotation.clone(),this.scale.clone())}}class zi{constructor(e={}){this.type="circle",this.currentValue=0,this.radius=e.radius??10,this.arc=e.arc??2*Math.PI,this.thickness=e.thickness??1,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Bt(1),this.memory=[],this.transform=e.transform}update(t,e){this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e),s=Z.lerp(1-this.thickness,1,b()),n=i*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(this.radius*s),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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new zi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?Ut(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new zi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class _i{constructor(e={}){this.type="cone",this.currentValue=0,this.radius=e.radius??10,this.arc=e.arc??2*Math.PI,this.thickness=e.thickness??1,this.angle=e.angle??Math.PI/6,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Bt(1),this.memory=[],this.transform=e.transform}update(e,i){t.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,e.emissionState.time/e.duration)*i)}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e),s=Z.lerp(1-this.thickness,1,b()),n=i*this.arc,r=Math.sqrt(s),o=Math.sin(n),a=Math.cos(n);t.position.x=r*a,t.position.y=r*o,t.position.z=0;const h=this.angle*r;t.velocity.set(0,0,Math.cos(h)).addScaledVector(t.position,Math.sin(h)).multiplyScalar(t.startSpeed),t.position.multiplyScalar(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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new _i({radius:t.radius,arc:t.arc,thickness:t.thickness,angle:t.angle,mode:t.mode,speed:t.speed?Ut(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new _i({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 Vi{constructor(e={}){this.type="donut",this.currentValue=0,this.radius=e.radius??10,this.arc=e.arc??2*Math.PI,this.thickness=e.thickness??1,this.donutRadius=e.donutRadius??.2*this.radius,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Bt(1),this.memory=[],this.transform=e.transform,this._m1=new nt}update(e,i){t.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,e.emissionState.time/e.duration)*i)}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e),s=b(),n=Z.lerp(1-this.thickness,1,b()),r=i*this.arc,o=s*Math.PI*2,a=Math.sin(r),h=Math.cos(r);if(t.position.x=this.radius*h,t.position.y=this.radius*a,t.position.z=0,t.velocity.z=this.donutRadius*n*Math.sin(o),t.velocity.x=this.donutRadius*n*Math.cos(o)*h,t.velocity.y=this.donutRadius*n*Math.cos(o)*a,t.position.add(t.velocity),t.velocity.normalize().multiplyScalar(t.startSpeed),t.rotation instanceof H){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(de,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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Vi({radius:t.radius,arc:t.arc,thickness:t.thickness,donutRadius:t.donutRadius,mode:t.mode,speed:t.speed?Ut(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new Vi({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 Ti{constructor(e={}){this.type="edge",this.currentValue=0,this.radius=e.radius??1,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Bt(1),this.memory=[]}update(e,i){t.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,e.emissionState.time/e.duration)*i)}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e);t.position.set((2*i-1)*this.radius,0,0),t.velocity.set(0,t.startSpeed,0)}toJSON(){return{type:"edge",radius:this.radius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new Ti({radius:t.radius,mode:t.mode,speed:t.speed?Ut(t.speed):void 0,spread:t.spread})}clone(){return new Ti({radius:this.radius,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}class Pi{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=Math.floor(b()*this.row),i=Math.floor(b()*this.column);t.position.x=i*this.width/this.column-this.width/2,t.position.y=e*this.height/this.row-this.height/2,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,...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Pi({...t,transform:Mi.fromJSON(t.transform)})}clone(){return new Pi({width:this.width,height:this.height,column:this.column,row:this.row,transform:this.transform?.clone()})}update(t,e){}}class Oi{constructor(e={}){this.type="hemisphere",this.currentValue=0,this.radius=e.radius??10,this.arc=e.arc??2*Math.PI,this.thickness=e.thickness??1,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Bt(1),this.memory=[],this.transform=e.transform,this._m1=new nt}update(e,i){t.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,e.emissionState.time/e.duration)*i)}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e),s=b(),n=Z.lerp(1-this.thickness,1,b()),r=i*this.arc,o=Math.acos(s),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(this.radius*n),t.rotation instanceof H){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(de,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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Oi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?Ut(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new Oi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Ai{constructor(t){this.type="point",this._m1=new nt,this.transform=t}update(t,e){}initialize(t){const e=b(),i=b(),s=e*Math.PI*2,n=Math.acos(2*i-1),r=Math.cbrt(b()),o=Math.sin(s),a=Math.cos(s),h=Math.sin(n),l=Math.cos(n);if(t.velocity.x=r*h*a,t.velocity.y=r*h*o,t.velocity.z=r*l,t.velocity.multiplyScalar(t.startSpeed),t.position.setScalar(0),t.rotation instanceof H){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(de,t.velocity,ue),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"point",...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Ai(Mi.fromJSON(t?.transform))}clone(){return new Ai(this.transform?.clone())}}class Bi{constructor(e={}){this.type="sphere",this.currentValue=0,this.radius=e.radius??10,this.arc=e.arc??2*Math.PI,this.thickness=e.thickness??1,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Bt(1),this.memory=[],this.transform=e.transform,this._m1=new nt}update(e,i){t.EmitterMode.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,e.emissionState.time/e.duration)*i)}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e),s=b(),n=Z.lerp(1-this.thickness,1,b()),r=i*this.arc,o=Math.acos(2*s-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(this.radius*n),t.rotation instanceof H){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(de,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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Bi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?Ut(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new Bi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Ci{constructor(e={}){this.type="rectangle",this.currentValue=0,this.width=e.width??10,this.height=e.height??10,this.thickness=e.thickness??1,this.mode=e.mode??t.EmitterMode.Random,this.spread=e.spread??0,this.speed=e.speed??new Bt(1),this.memory=[],this.transform=e.transform,this._m1=new nt}update(t,e){this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e}initialize(t,e){const i=wi(this.mode,this.currentValue,this.spread,e);b();const s=i*(2*(this.width+this.height));let n,r;s<this.width?(n=s-this.width/2,r=-this.height/2):s<this.width+this.height?(n=this.width/2,r=s-this.width-this.height/2):s<2*this.width+this.height?(n=this.width/2-(s-this.width-this.height),r=this.height/2):(n=-this.width/2,r=this.height/2-(s-2*this.width-this.height));const o=b(),a=1-this.thickness*o;if(t.position.x=n*a,t.position.y=r*a,t.position.z=0,t.velocity.x=n,t.velocity.y=r,t.velocity.z=0,t.velocity.normalize().multiplyScalar(t.startSpeed),t.rotation instanceof H){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(de,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(),...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Ci({width:t.width,height:t.height,thickness:t.thickness,mode:t.mode,speed:t.speed?Ut(t.speed):void 0,transform:Mi.fromJSON(t.transform),spread:t.spread})}clone(){return new Ci({width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}const Fi={box:{type:"box",params:[["width",["number"]],["height",["number"]],["depth",["number"]],["emitFrom",["number"]],["boxThickness",["vec3"]]],constructor:bi,loadJSON:bi.fromJSON},circle:{type:"circle",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:zi,loadJSON:zi.fromJSON},cone:{type:"cone",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:_i,loadJSON:_i.fromJSON},donut:{type:"donut",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["donutRadius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Vi,loadJSON:Vi.fromJSON},edge:{type:"edge",params:[["radius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Ti,loadJSON:Ti.fromJSON},point:{type:"point",params:[],constructor:Ai,loadJSON:Ai.fromJSON},sphere:{type:"sphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Bi,loadJSON:Bi.fromJSON},hemisphere:{type:"hemisphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Oi,loadJSON:Oi.fromJSON},grid:{type:"grid",params:[["width",["number"]],["height",["number"]],["rows",["number"]],["column",["number"]]],constructor:Pi,loadJSON:Pi.fromJSON},rectangle:{type:"rectangle",params:[["width",["number"]],["height",["number"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Ci,loadJSON:Ci.fromJSON}};function $i(t,e){return Fi[t.type].loadJSON(t,e)}const Ii=[];function Ui(t){if(!Ii.find(e=>e.id===t.id)){t.initialize();for(const e of t.emitterShapes)Fi[e.type]||(Fi[e.type]=e);for(const e of t.behaviors)ni[e.type]||(ni[e.type]=e)}}class Ei{get mesh(){return this._mesh}set mesh(t){if(this._mesh=t,!t)return;const i=t.getVerticesData(e.VertexBuffer.PositionKind),s=t.getIndices();if(!i||!s)return;this._positions=new Float32Array(i),this._indices=new Int32Array(s),this._triangleIndexToArea.length=0;let n=0;const r=s.length/3;this._triangleIndexToArea.push(0);const o=new K,a=new K,h=new K;for(let t=0;t<r;t++){const e=s[3*t],r=s[3*t+1],l=s[3*t+2];o.set(i[3*e],i[3*e+1],i[3*e+2]),a.set(i[3*r],i[3*r+1],i[3*r+2]),h.set(i[3*l],i[3*l+1],i[3*l+2]),a.sub(o),h.sub(o);const c=new K;c.crossVectors(a,h),n+=.5*c.length(),this._triangleIndexToArea.push(n)}}constructor(t,e,i){this.type="mesh_surface",this._triangleIndexToArea=[],this._meshReferenceId=e,this.transform=i,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 i=0,s=e;const n=b()*this._triangleIndexToArea[e];for(;i+1<s;){const t=Math.floor((i+s)/2);n<this._triangleIndexToArea[t]?s=t:i=t}let r=b(),o=b();r+o>1&&(r=1-r,o=1-o);const a=this._indices[3*i],h=this._indices[3*i+1],l=this._indices[3*i+2],c=this._positions[3*a],u=this._positions[3*a+1],d=this._positions[3*a+2],f=this._positions[3*h]-c,m=this._positions[3*h+1]-u,p=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+m*r+g*o,d+p*r+v*o);const x=m*v-p*g,S=p*y-f*v,w=f*g-m*y,M=Math.sqrt(x*x+S*S+w*w)||1;t.velocity.set(x/M,S/M,w/M).multiplyScalar(t.startSpeed),this.transform?.apply(t)}toJSON(){return{type:"mesh_surface",mesh:this._mesh?this._mesh.uniqueId?.toString():this._meshReferenceId??"",...Mi.toShapeJSON(this.transform)}}static fromJSON(t){return new Ei(void 0,t?.mesh,Mi.fromJSON(t?.transform))}clone(){return new Ei(this._mesh,this._meshReferenceId,this.transform?.clone())}update(t,e){}}const Ni={id:"babylon.quarks",initialize:()=>{},emitterShapes:[{type:"mesh_surface",params:[["mesh",["mesh"]]],constructor:Ei,loadJSON:t=>Ei.fromJSON(t)}],behaviors:[]};const Ri={};let Di=!1;function Li(){Di||(Ri.tile_pars_vertex="\n#ifdef UV_TILE\n attribute float uvTile;\n uniform vec2 tileCount;\n\n mat3 makeTileTransform(float tileIndex) {\n float col = mod(tileIndex, tileCount.x);\n float row = (tileCount.y - floor(tileIndex / tileCount.x) - 1.0);\n return mat3(\n 1.0 / tileCount.x, 0.0, 0.0,\n 0.0, 1.0 / tileCount.y, 0.0,\n col / tileCount.x, row / tileCount.y, 1.0\n );\n }\n#else\n mat3 makeTileTransform(float tileIndex) {\n return mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);\n }\n#endif\n\n#if defined(USE_UV)\n varying vec2 vUv;\n #ifdef TILE_BLEND\n varying vec2 vUvNext;\n varying float vUvBlend;\n #endif\n#endif\n",Ri.tile_vertex="\n#ifdef UV_TILE\n mat3 tileTransform = makeTileTransform(floor(uvTile));\n #ifdef TILE_BLEND\n mat3 nextTileTransform = makeTileTransform(ceil(uvTile));\n vUvBlend = fract(uvTile);\n #endif\n#else\n mat3 tileTransform = makeTileTransform(0.0);\n#endif\n\n#if defined(USE_UV)\n vUv = (tileTransform * vec3(uv, 1.0)).xy;\n #if defined(TILE_BLEND) && defined(UV_TILE)\n vUvNext = (nextTileTransform * vec3(uv, 1.0)).xy;\n #endif\n#endif\n",Ri.tile_pars_fragment="\n#if defined(USE_UV)\n varying vec2 vUv;\n #ifdef TILE_BLEND\n varying vec2 vUvNext;\n varying float vUvBlend;\n #endif\n#endif\n",Ri.tile_fragment="\n#ifdef USE_MAP\n vec4 texelColor = texture2D(map, vUv);\n #ifdef TILE_BLEND\n texelColor = mix(texelColor, texture2D(map, vUvNext), vUvBlend);\n #endif\n diffuseColor *= texelColor;\n#endif\n",Ri.soft_pars_vertex="\n#ifdef SOFT_PARTICLES\n varying vec4 projPosition;\n varying float linearDepth;\n#endif\n",Ri.soft_vertex="\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n linearDepth = -mvPosition.z;\n#endif\n",Ri.soft_pars_fragment="\n#ifdef SOFT_PARTICLES\n uniform sampler2D depthTexture;\n uniform vec4 projParams;\n uniform vec2 softParams;\n\n varying vec4 projPosition;\n varying float linearDepth;\n\n #define SOFT_NEAR_FADE softParams.x\n #define SOFT_INV_FADE_DISTANCE softParams.y\n\n #define zNear projParams.x\n #define zFar projParams.y\n\n float linearize_depth(float d) {\n return (zFar * zNear) / (zFar - d * (zFar - zNear));\n }\n#endif\n",Ri.soft_fragment="\n#ifdef SOFT_PARTICLES\n\n vec2 p2 = projPosition.xy / projPosition.w;\n p2 = 0.5 * p2 + 0.5;\n\n float readDepth = texture2D(depthTexture, p2.xy).r;\n float viewDepth = linearize_depth(readDepth);\n float softParticlesFade = saturate(SOFT_INV_FADE_DISTANCE * ((viewDepth - SOFT_NEAR_FADE) - linearDepth));\n\n gl_FragColor *= softParticlesFade;\n#endif\n",Di=!0)}const qi="\n#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n";function ki(t){return`\n#ifdef FOG\n vFogDistance = ${t};\n#endif\n`}const Ji="\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 fogCoeff = (fogEnd - fogDistance) / (fogEnd - fogStart);\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 Qi(t){return`\n#ifdef FOG\n {\n float fogFactor = quarksFogFactor();\n#ifdef FOG_ADDITIVE\n ${t} *= fogFactor;\n#else\n ${t} = mix(vFogColor, ${t}, fogFactor);\n#endif\n }\n#endif\n`}const Gi="\n#ifdef FOG\nvarying vFogDistance: vec3f;\n#endif\n";function Wi(t){return`\n#ifdef FOG\n vertexOutputs.vFogDistance = ${t};\n#endif\n`}const ji="\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 fogCoeff = (fogEnd - fogDistance) / (fogEnd - fogStart);\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#ifdef FOG_ADDITIVE\n return rgb * fogFactor;\n#else\n return mix(uniforms.vFogColor, rgb, fogFactor);\n#endif\n}\n#endif\n";function Yi(t){return`\n#ifdef FOG\n ${t} = vec4f(quarksFog(${t}.rgb, fragmentInputs.vFogDistance), ${t}.a);\n#endif\n`}var Xi=`\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\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\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 TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\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${qi}\nvoid main() {\n vec3 scaledPosition = position * size;\n vec3 rotatedPosition = applyQuaternion(scaledPosition, rotation);\n vec3 rotatedNormal = normalize(applyQuaternion(normal, rotation));\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${ki("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 linearDepth = -viewPos.z;\n#endif\n\n#ifdef UV_TILE\n vec2 tc = vec2(tileCountX, tileCountY);\n float baseTile = floor(uvTile);\n float tileU = mod(baseTile, tc.x) / tc.x;\n float tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV = uv / tc + vec2(tileU, tileV);\n #ifdef TILE_BLEND\n float nextTile = ceil(uvTile);\n float nextU = mod(nextTile, tc.x) / tc.x;\n float nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV2 = uv / tc + vec2(nextU, nextV);\n vTileBlend = fract(uvTile);\n #endif\n#else\n vUV = uv;\n#endif\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`;const Zi="\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 Hi(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#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 #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 Ki="\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 ts(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#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 #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 es=`\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#ifdef SOFT_PARTICLES\nuniform sampler2D depthTexture;\nuniform vec2 softParams;\nuniform vec4 projParams;\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${Ji}\n${Zi}\nvoid main() {\n${Hi(!0)}\n#ifdef USE_COLOR_AS_ALPHA\n baseColor.a *= (baseColor.r + baseColor.g + baseColor.b) / 3.0;\n#endif\n\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${Qi("baseColor.rgb")}\n gl_FragColor = baseColor;\n\n#ifdef SOFT_PARTICLES\n vec2 p2 = projPosition.xy / projPosition.w;\n p2 = 0.5 * p2 + 0.5;\n float readDepth = texture2D(depthTexture, p2.xy).r;\n float zNear = projParams.x;\n float zFar = projParams.y;\n float viewDepth = (zFar * zNear) / (zFar - readDepth * (zFar - zNear));\n float fade = clamp(softParams.y * ((viewDepth - softParams.x) - linearDepth), 0.0, 1.0);\n gl_FragColor *= fade;\n#endif\n}\n`,is=`\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#ifdef SOFT_PARTICLES\nuniform sampler2D depthTexture;\nuniform vec2 softParams;\nuniform vec4 projParams;\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${Ji}\n${Zi}\nvoid main() {\n${Hi(!0)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n vec3 N = normalize(vNormal);\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${Qi("color")}\n gl_FragColor = vec4(color, baseColor.a);\n\n#ifdef SOFT_PARTICLES\n vec2 p2 = projPosition.xy / projPosition.w;\n p2 = 0.5 * p2 + 0.5;\n float readDepth = texture2D(depthTexture, p2.xy).r;\n float zNear = projParams.x;\n float zFar = projParams.y;\n float viewDepth = (zFar * zNear) / (zFar - readDepth * (zFar - zNear));\n float fade = clamp(softParams.y * ((viewDepth - softParams.x) - linearDepth), 0.0, 1.0);\n gl_FragColor *= fade;\n#endif\n}\n`,ss=`\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;\nuniform mat4 worldViewProjection;\n\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\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 TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\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${qi}\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${ki("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n linearDepth = -mvPosition.z;\n#endif\n\n #ifdef UV_TILE\n vec2 tc = vec2(tileCountX, tileCountY);\n float baseTile = floor(uvTile);\n float tileU = mod(baseTile, tc.x) / tc.x;\n float tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV = uv / tc + vec2(tileU, tileV);\n #ifdef TILE_BLEND\n float nextTile = ceil(uvTile);\n float nextU = mod(nextTile, tc.x) / tc.x;\n float nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV2 = uv / tc + vec2(nextU, nextV);\n vTileBlend = fract(uvTile);\n #endif\n #else\n vUV = uv;\n #endif\n\n#ifdef UV1\n vUV1 = uv;\n#endif\n vColor = color;\n}\n`,ns=`\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;\nuniform float speedFactor;\n\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\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 TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\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${qi}\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. speedFactor 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#ifdef BEAM\n // Seen straight along its length a beam 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#else\n vec3 side = normalize(cross(mvPosition.xyz, vdir));\n#endif\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${ki("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 linearDepth = -mvPosition.z;\n#endif\n\n #ifdef UV_TILE\n vec2 tc = vec2(tileCountX, tileCountY);\n float baseTile = floor(uvTile);\n float tileU = mod(baseTile, tc.x) / tc.x;\n float tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV = quadUV / tc + vec2(tileU, tileV);\n #ifdef TILE_BLEND\n float nextTile = ceil(uvTile);\n float nextU = mod(nextTile, tc.x) / tc.x;\n float nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV2 = quadUV / tc + vec2(nextU, nextV);\n vTileBlend = fract(uvTile);\n #endif\n #else\n vUV = quadUV;\n #endif\n\n#ifdef UV1\n vUV1 = quadUV;\n#endif\n vColor = color;\n}\n`,rs=`\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${Ji}\n${Zi}\nvoid main() {\n${Hi(!1)}\n if (baseColor.a < 0.01) discard;\n\n${Qi("baseColor.rgb")}\n gl_FragColor = baseColor;\n}\n`,os=`\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;\nuniform float lineWidth;\nuniform vec2 resolution;\nuniform float sizeAttenuation;\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\nvec2 fix(vec4 i, float aspect) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n}\n\n${qi}\nvoid main() {\n float aspect = resolution.x / resolution.y;\n vec4 finalPosition = projection * view * vec4(position, 1.0);\n vec4 prevPos = projection * view * vec4(previous, 1.0);\n vec4 nextPos = projection * view * vec4(next, 1.0);\n\n vec2 currentP = fix(finalPosition, aspect);\n vec2 prevP = fix(prevPos, aspect);\n vec2 nextP = fix(nextPos, aspect);\n\n float w = lineWidth * width;\n vec2 dir;\n if (distance(nextP, currentP) < 0.0001) {\n dir = normalize(currentP - prevP);\n } else if (distance(prevP, currentP) < 0.0001) {\n dir = normalize(nextP - currentP);\n } else {\n vec2 dir1 = normalize(currentP - prevP);\n vec2 dir2 = normalize(nextP - currentP);\n dir = normalize(dir1 + dir2);\n }\n vec4 normal = vec4(-dir.y, dir.x, 0.0, 1.0);\n normal.xy *= 0.5 * w;\n normal *= projection;\n if (sizeAttenuation == 0.0) {\n normal.xy *= finalPosition.w;\n normal.xy /= (vec4(resolution, 0.0, 1.0) * projection).xy;\n }\n finalPosition.xy += normal.xy * side;\n gl_Position = finalPosition;\n${ki("(view * vec4(position, 1.0)).xyz")}\n vUV = uv;\n#ifdef UV1\n vUV1 = uv2;\n#endif\n vColor = color;\n}\n`;const as=2048,hs=2047;class ls{constructor(t){this.counts=new Uint32Array(as),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 i=this.uintView[0];return e?~i>>>0:i}}var cs=`\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\n#ifdef UV_TILE\nuniform tileCountX: f32;\nuniform tileCountY: f32;\n#endif\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 TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\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${Gi}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let scaledPosition = vertexInputs.position * vertexInputs.size;\n let rotatedPosition = applyQuaternion(scaledPosition, vertexInputs.rotation);\n let rotatedNormal = normalize(applyQuaternion(vertexInputs.normal, vertexInputs.rotation));\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${Wi("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 vertexOutputs.linearDepth = -viewPos.z;\n#endif\n\n#ifdef UV_TILE\n let tc = vec2f(uniforms.tileCountX, uniforms.tileCountY);\n let baseTile = floor(vertexInputs.uvTile);\n let tileU = (baseTile % tc.x) / tc.x;\n let tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV = vertexInputs.uv / tc + vec2f(tileU, tileV);\n #ifdef TILE_BLEND\n let nextTile = ceil(vertexInputs.uvTile);\n let nextU = (nextTile % tc.x) / tc.x;\n let nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV2 = vertexInputs.uv / tc + vec2f(nextU, nextV);\n vertexOutputs.vTileBlend = fract(vertexInputs.uvTile);\n #endif\n#else\n vertexOutputs.vUV = vertexInputs.uv;\n#endif\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`,us=`\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#ifdef SOFT_PARTICLES\nvar depthTextureSampler: sampler;\nvar depthTexture: texture_2d<f32>;\nuniform softParams: vec2f;\nuniform projParams: vec4f;\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${ji}\n${Ki}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${ts(!0)}\n#ifdef USE_COLOR_AS_ALPHA\n baseColor.a *= (baseColor.r + baseColor.g + baseColor.b) / 3.0;\n#endif\n\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n#ifdef SOFT_PARTICLES\n var p2 = fragmentInputs.projPosition.xy / fragmentInputs.projPosition.w;\n p2 = 0.5 * p2 + 0.5;\n let readDepth = textureSample(depthTexture, depthTextureSampler, p2).r;\n let zNear = uniforms.projParams.x;\n let zFar = uniforms.projParams.y;\n let viewDepth = (zFar * zNear) / (zFar - readDepth * (zFar - zNear));\n let fade = clamp(uniforms.softParams.y * ((viewDepth - uniforms.softParams.x) - fragmentInputs.linearDepth), 0.0, 1.0);\n baseColor *= fade;\n#endif\n\n${Yi("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,ds=`\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#ifdef SOFT_PARTICLES\nvar depthTextureSampler: sampler;\nvar depthTexture: texture_2d<f32>;\nuniform softParams: vec2f;\nuniform projParams: vec4f;\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${ji}\n${Ki}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${ts(!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 let N = normalize(fragmentInputs.vNormal);\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 var finalColor = vec4f(color, baseColor.a);\n\n#ifdef SOFT_PARTICLES\n var p2 = fragmentInputs.projPosition.xy / fragmentInputs.projPosition.w;\n p2 = 0.5 * p2 + 0.5;\n let readDepth = textureSample(depthTexture, depthTextureSampler, p2).r;\n let zNear = uniforms.projParams.x;\n let zFar = uniforms.projParams.y;\n let viewDepth = (zFar * zNear) / (zFar - readDepth * (zFar - zNear));\n let fade = clamp(uniforms.softParams.y * ((viewDepth - uniforms.softParams.x) - fragmentInputs.linearDepth), 0.0, 1.0);\n finalColor *= fade;\n#endif\n\n${Yi("finalColor")}\n fragmentOutputs.color = finalColor;\n}\n`,fs=`\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\n#ifdef UV_TILE\nuniform tileCountX: f32;\nuniform tileCountY: f32;\n#endif\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 TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\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${Gi}\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${Wi("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n vertexOutputs.linearDepth = -mvPosition.z;\n#endif\n\n #ifdef UV_TILE\n let tc = vec2f(uniforms.tileCountX, uniforms.tileCountY);\n let baseTile = floor(vertexInputs.uvTile);\n let tileU = (baseTile % tc.x) / tc.x;\n let tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV = vertexInputs.uv / tc + vec2f(tileU, tileV);\n #ifdef TILE_BLEND\n let nextTile = ceil(vertexInputs.uvTile);\n let nextU = (nextTile % tc.x) / tc.x;\n let nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV2 = vertexInputs.uv / tc + vec2f(nextU, nextV);\n vertexOutputs.vTileBlend = fract(vertexInputs.uvTile);\n #endif\n #else\n vertexOutputs.vUV = vertexInputs.uv;\n #endif\n\n#ifdef UV1\n vertexOutputs.vUV1 = vertexInputs.uv;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;function ms(t){return t.isWebGPU?f.ShaderLanguage.WGSL:f.ShaderLanguage.GLSL}function ps(t,e,i,s){if(s===f.ShaderLanguage.WGSL)return u.ShaderStore.ShadersStoreWGSL[t+"VertexShader"]=e.wgsl,void(u.ShaderStore.ShadersStoreWGSL[t+"FragmentShader"]=i.wgsl);d.Effect.ShadersStore[t+"VertexShader"]=e.glsl,d.Effect.ShadersStore[t+"FragmentShader"]=i.glsl}var ys,gs=`\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;\nuniform speedFactor: f32;\n\n#ifdef UV_TILE\nuniform tileCountX: f32;\nuniform tileCountY: f32;\n#endif\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 TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\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${Gi}\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. speedFactor 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#ifdef BEAM\n // Seen straight along its length a beam 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#else\n let side = normalize(cross(mvPosition.xyz, vdir));\n#endif\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${Wi("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 vertexOutputs.linearDepth = -mvPosition.z;\n#endif\n\n #ifdef UV_TILE\n let tc = vec2f(uniforms.tileCountX, uniforms.tileCountY);\n let baseTile = floor(vertexInputs.uvTile);\n let tileU = (baseTile % tc.x) / tc.x;\n let tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV = quadUV / tc + vec2f(tileU, tileV);\n #ifdef TILE_BLEND\n let nextTile = ceil(vertexInputs.uvTile);\n let nextU = (nextTile % tc.x) / tc.x;\n let nextV = 1.0 - floor(nextTile / tc.x) / tc.y - 1.0 / tc.y;\n vertexOutputs.vUV2 = quadUV / tc + vec2f(nextU, nextV);\n vertexOutputs.vTileBlend = fract(vertexInputs.uvTile);\n #endif\n #else\n vertexOutputs.vUV = quadUV;\n #endif\n\n#ifdef UV1\n vertexOutputs.vUV1 = quadUV;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;function vs(){return{direction:new h.Vector3(.4,-1,.6),color:new p.Color3(1,1,1),ambient:new p.Color3(.35,.35,.35)}}function xs(t){if(!t||"object"!=typeof t)return;const e=Array.isArray(t.color)?t.color:[1,1,1],i=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e;return{color:[i(e[0],1),i(e[1],1),i(e[2],1)],power:Math.max(.01,i(t.power,2)),strength:Math.max(0,i(t.strength,1)),mode:"mix"===t.mode||"fade"===t.mode?t.mode:"add"}}function Ss(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])}function bs(t,e={}){const i=t&&"object"==typeof t?t:{},s=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e,n=(t,e)=>Array.isArray(t)?[s(t[0],e[0]),s(t[1],e[1])]:[e[0],e[1]];return{channel:1===(i.channel??e.channel)?1:0,tiling:n(i.tiling,e.tiling??[1,1]),offset:n(i.offset,e.offset??[0,0]),scroll:n(i.scroll,e.scroll??[0,0])}}function ws(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 Ms(t,e={}){const i=bs(void 0,e),s={};return t.channel!==i.channel&&(s.channel=t.channel),t.tiling[0]===i.tiling[0]&&t.tiling[1]===i.tiling[1]||(s.tiling=[...t.tiling]),t.offset[0]===i.offset[0]&&t.offset[1]===i.offset[1]||(s.offset=[...t.offset]),t.scroll[0]===i.scroll[0]&&t.scroll[1]===i.scroll[1]||(s.scroll=[...t.scroll]),Object.keys(s).length>0?s:void 0}t.RenderMode=void 0,(ys=t.RenderMode||(t.RenderMode={}))[ys.BillBoard=0]="BillBoard",ys[ys.StretchedBillBoard=1]="StretchedBillBoard",ys[ys.Mesh=2]="Mesh",ys[ys.Trail=3]="Trail",ys[ys.HorizontalBillBoard=4]="HorizontalBillBoard",ys[ys.VerticalBillBoard=5]="VerticalBillBoard",ys[ys.Beam=6]="Beam";const zs={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 _s(t){if(!t||"object"!=typeof t||!t.ramp)return;const e=t.channel;return{ramp:t.ramp,channel:void 0!==e&&e in zs?e:"r"}}function Vs(t,e){return t===e||!!t&&!!e&&t.ramp===e.ramp&&t.channel===e.channel}function Ts(t){if(!t||"object"!=typeof t)return;const e=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e,i=Array.isArray(t.edgeColor)?t.edgeColor:[1,1,1];return{mask:t.mask??null,maskUV:bs(t.maskUV),softness:Math.max(1e-4,e(t.softness,.05)),edgeWidth:Math.max(0,e(t.edgeWidth,0)),edgeColor:[e(i[0],1),e(i[1],1),e(i[2],1)]}}function Ps(t,e){return t===e||!(!t||!e)&&(t.mask===e.mask&&ws(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])}const Os={scroll:[0,.5]};function As(t){if(!t||"object"!=typeof t||!t.map)return;const e=t.strength;return{map:t.map,mapUV:bs(t.mapUV,Os),strength:Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:.05)}}function Bs(t,e){return t===e||!(!t||!e)&&(t.map===e.map&&t.strength===e.strength&&ws(t.mapUV,e.mapUV))}function Cs(t){if(!t||"object"!=typeof t)return;const e=bs(t);return void 0===Ms(e)?void 0:e}function Fs(t,e){return t===e||!!t&&!!e&&ws(t,e)}function $s(t){const{mapUV:e,uvDistortion:i,erosion:s}=t;return 1===e?.channel||1===i?.mapUV.channel||!!s?.mask&&1===s.maskUV.channel}class Is{constructor(t,e){this.visibleSystems=[],this.boundsMin_=new K,this.boundsMax_=new K,this.time=0,this.scene=e,this.maxParticles=1e3,this.systems=new Set,this.settings={instancingGeometry:t.instancingGeometry,instancingIndices:t.instancingIndices,instancingUVs:t.instancingUVs,instancingUVs2:t.instancingUVs2,instancingNormals:t.instancingNormals,renderMode:t.renderMode,renderOrder:t.renderOrder,uTileCount:t.uTileCount,vTileCount:t.vTileCount,blendTiles:t.blendTiles,softParticles:t.softParticles,softNearFade:t.softNearFade,softFarFade:t.softFarFade,materialBlendMode:t.materialBlendMode,materialTransparent:t.materialTransparent,materialDepthTest:t.materialDepthTest,materialDepthWrite:t.materialDepthWrite,materialAlphaTest:t.materialAlphaTest,texture:t.texture,reflectionTexture:t.reflectionTexture??null,reflectionLevel:t.reflectionLevel??1,reflectionFaces:t.reflectionFaces??null,reflectionAtlas:t.reflectionAtlas??null,pivot:t.pivot?.clone(),sortMode:t.sortMode??"none",minParticleSize:t.minParticleSize??0,maxParticleSize:t.maxParticleSize??1/0,layerMask:t.layerMask,renderingGroupId:t.renderingGroupId??0,applyFog:t.applyFog??!0,lighting:t.lighting,rim:xs(t.rim),mapUV:Cs(t.mapUV),uvDistortion:As(t.uvDistortion),gradientMap:_s(t.gradientMap),erosion:Ts(t.erosion)},this.mesh=new l.Mesh("vfxBatch",e),this.configureMesh()}configureMesh(){const t=this.mesh;t.alwaysSelectAsActiveMesh=!0,t.doNotSyncBoundingInfo=!0,t.setBoundingInfo(new m.BoundingInfo(h.Vector3.Zero(),h.Vector3.Zero())),t.layerMask=this.settings.layerMask,t.renderingGroupId=this.settings.renderingGroupId,t.alphaIndex=this.settings.renderOrder,t.applyFog=!1}refreshBoundingInfo(){const t=this.boundsMin_,e=this.boundsMax_;let i=1/0,s=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<i&&(i=t.x),t.y<s&&(s=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===i&&u.y===s&&u.z===n&&d.x===r&&d.y===o&&d.z===a||(u.set(i,s,n),d.set(r,o,a),c.reConstruct(u,d)),this.mesh.alwaysSelectAsActiveMesh=!1}fogDefines(){if(!this.settings.applyFog)return[];return this.settings.materialTransparent&&(this.settings.materialBlendMode===r.Constants.ALPHA_ADD||this.settings.materialBlendMode===r.Constants.ALPHA_ONEONE)?["FOG","FOG_ADDITIVE"]:["FOG"]}bindFog(t){if(!this.settings.applyFog)return;const e=this.scene;t.onBindObservable.add(()=>{const i=t.getEffect();if(!i)return;const s=e.fogEnabled?e.fogMode:y.Scene.FOGMODE_NONE;i.setFloat4("vFogInfos",s,e.fogStart,e.fogEnd,e.fogDensity),i.setColor3("vFogColor",e.fogColor)})}usesUV1(){return $s(this.settings)}surfaceDefines(){const t=[],{mapUV:e,uvDistortion:i,gradientMap:s,erosion:n}=this.settings;return this.usesUV1()&&t.push("UV1"),e&&(t.push("MAP_TRANSFORM"),1===e.channel&&t.push("MAP_UV1")),i&&(t.push("UV_DISTORTION"),1===i.mapUV.channel&&t.push("UV_DISTORTION_UV1")),s&&t.push("GRADIENT_MAP"),n&&(t.push("EROSION"),n.mask&&(t.push("EROSION_MASK"),1===n.maskUV.channel&&t.push("EROSION_MASK_UV1"))),t}surfaceUniforms(t,e){const{mapUV:i,uvDistortion:s,gradientMap:n,erosion:r}=this.settings;i&&t.push("mapTransform"),s&&(e.push("distortionMap"),t.push("distortionTransform","distortionStrength")),n&&(e.push("gradientMap"),t.push("gradientMapRange","gradientMapChannel")),r&&(t.push("erosionParams","erosionEdgeColor"),r.mask&&(e.push("erosionMask"),t.push("erosionMaskTransform")))}bindSurface(t){const{mapUV:e,uvDistortion:i,gradientMap:s,erosion:n}=this.settings;if(i?.map&&(t.setTexture("distortionMap",i.map),t.setFloat("distortionStrength",i.strength)),s?.ramp){t.setTexture("gradientMap",s.ramp);const[e,i,n,r]=zs[s.channel];t.setVector4("gradientMapChannel",new h.Vector4(e,i,n,r))}if(n&&(n.mask&&t.setTexture("erosionMask",n.mask),t.setVector2("erosionParams",new h.Vector2(n.softness,n.edgeWidth)),t.setVector3("erosionEdgeColor",new h.Vector3(n.edgeColor[0],n.edgeColor[1],n.edgeColor[2]))),!(e||i||n?.mask||s))return;const r=t=>t-2*Math.floor(t/2),o=new h.Vector4,a=new h.Vector4,l=new h.Vector4,c=new h.Vector2(0,1),u=(t,e,i)=>i.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 r=this.time,h=t.getEffect();if(e&&(u(e,r,o),t.setVector4("mapTransform",o),h?.setVector4("mapTransform",o)),i&&(u(i.mapUV,r,a),t.setVector4("distortionTransform",a),h?.setVector4("distortionTransform",a)),n?.mask&&(u(n.maskUV,r,l),t.setVector4("erosionMaskTransform",l),h?.setVector4("erosionMaskTransform",l)),s?.ramp){const e=s.ramp.getSize().width,i=e>0?.5/e:0;c.set(i,1-i),t.setVector2("gradientMapRange",c),h?.setVector2("gradientMapRange",c)}};d(),t.onBindObservable.add(d)}addSystem(t){this.systems.add(t)}removeSystem(t){this.systems.delete(t)}getVisibleSystems(){const t=this.visibleSystems;let e=0;for(const i of this.systems)i.emitter.visible&&!0!==i.culled&&(t[e++]=i);return t.length=e,t}applyDepthTexture(t){const e=this.mesh.material;e&&e instanceof o.ShaderMaterial&&e.setTexture("depthTexture",t)}applyMeshLighting(t){}dispose(){this.mesh.dispose()}}Is.FOG_UNIFORMS=["vFogInfos","vFogColor"];class Us extends Is{static whiteTexture(t){let e=Us.whiteTextureByScene.get(t);return e||(e=a.RawTexture.CreateRGBATexture(new Uint8Array([255,255,255,255]),1,1,t),e.name="quarksMeshWhite",Us.whiteTextureByScene.set(t,e)),e}constructor(t,e){super(t,e),this.shaderMaterial=null,this.fixedLightDirection=new h.Vector3,this.fixedLightColor=new h.Vector3,this.fixedAmbientColor=new h.Vector3,this.warnedUV2=!1,this.gatherScratch=[],this.vector_=new K,this.vector2_=new K,this.vector3_=new K,this.quaternion_=new H,this.quaternion2_=new H,this.quaternion3_=new H,this.quaternion4_=new H,this.quaternion5_=new H,this.rotationMat_=new pt,this.rotationMat2_=new pt,this.lastStretchedSpeedFactor=Number.NaN,this.clearedInstanceUploaded=!1,this.beamEnd_=new K,this.storeFixedLighting(vs()),this.maxParticles=1e3,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh.dispose(),this.mesh=new l.Mesh("spriteBatch",this.scene),this.configureMesh();const t=new c.VertexData;t.positions=this.settings.instancingGeometry,t.indices=this.settings.instancingIndices;const e=this.settings.instancingGeometry.length/3,i=this.settings.instancingUVs;i&&i.length>=2*e?t.uvs=i: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 e=this.settings.instancingUVs2;if(this.settings.renderMode!==t.RenderMode.Mesh||!e||!this.usesUV1())return!1;const i=this.settings.instancingGeometry.length/3*2;return e.length===i||(this.warnedUV2||(this.warnedUV2=!0,console.warn(`[babylon.quarks] instancingUVs2 has ${e.length} values for ${i/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 i=this.scene.getEngine();this.offsetBuffer=new Float32Array(3*this.maxParticles),this.offsetVB=new e.VertexBuffer(i,this.offsetBuffer,"offset",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.offsetVB),this.colorBuffer=new Float32Array(4*this.maxParticles),this.colorVB=new e.VertexBuffer(i,this.colorBuffer,"color",!0,!1,4,!0),this.mesh.setVerticesBuffer(this.colorVB),this.sizeBuffer=new Float32Array(3*this.maxParticles),this.sizeVB=new e.VertexBuffer(i,this.sizeBuffer,"size",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.sizeVB),this.uvTileBuffer=new Float32Array(this.maxParticles),this.uvTileVB=new e.VertexBuffer(i,this.uvTileBuffer,"uvTile",!0,!1,1,!0),this.mesh.setVerticesBuffer(this.uvTileVB),this.settings.renderMode===t.RenderMode.Mesh?(this.rotationBuffer=new Float32Array(4*this.maxParticles),this.rotationVB=new e.VertexBuffer(i,this.rotationBuffer,"rotation",!0,!1,4,!0)):(this.rotationBuffer=new Float32Array(this.maxParticles),this.rotationVB=new e.VertexBuffer(i,this.rotationBuffer,"rotation",!0,!1,1,!0)),this.mesh.setVerticesBuffer(this.rotationVB),Us.drawsAlongVelocity(this.settings.renderMode)&&(this.velocityBuffer=new Float32Array(4*this.maxParticles),this.velocityVB=new e.VertexBuffer(i,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.disposeExpandableBuffers(),this.buildExpandableBuffers(),this.sortScratch=void 0,this.gatherScratch.length=0}sizeLimits(){const{minParticleSize:t,maxParticleSize:e}=this.settings;return Us.takesPivotAndFlip(this.settings.renderMode)?t<=0&&e===1/0?null:new h.Vector2(Math.max(0,t),Math.min(e,1e9)):null}sortInstances(t,e,i){if(t<2)return;const s=this.sortScratch??(this.sortScratch=new ls(this.maxParticles));s.ensure(t);const n=s.keys,r=this.settings.sortMode;if("distance"===r){const e=this.scene.activeCameras?.[0]??this.scene.activeCamera;if(!e)return;const i=e.globalPosition,r=i.x,o=i.y,a=i.z,h=this.offsetBuffer;for(let e=0,i=0;e<t;e++,i+=3){const t=h[i]-r,l=h[i+1]-o,c=h[i+2]-a;n[e]=s.floatKey(t*t+l*l+c*c,!0)}}else{const e="youngestInFront"===r,i=this.visibleSystems;let o=0;for(let t=0;t<i.length;t++){const r=i[t],a=r.particleNum,h=r.store;if(0===a)continue;if(void 0===h){const t=r.particles;for(let i=0;i<a;i++)n[o++]=s.floatKey(t[i].age,e);continue}const l=h.scalars,c=ze.SCALAR_STRIDE;for(let t=0,i=ze.AGE;t<a;t++,i+=c)n[o++]=s.floatKey(l[i],e)}if(o!==t)return}const o=function(t,e){const i=t.keys,s=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){s.fill(0);for(let r=0;r<e;r++)s[i[n[r]]>>>t&hs]++;if(s[i[n[0]]>>>t&hs]===e)continue;let o=0;for(let t=0;t<as;t++){const e=s[t];s[t]=o,o+=e}for(let o=0;o<e;o++){const e=n[o];r[s[i[e]>>>t&hs]++]=e}const a=n;n=r,r=a}return n}(s,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),i&&this.velocityBuffer&&(this.velocityBuffer=this.gatherInto(5,this.velocityBuffer,o,t,4))}gatherInto(t,e,i,s,n){let r=this.gatherScratch[t];return void 0!==r&&r.length===e.length||(r=new Float32Array(e.length)),function(t,e,i,s,n){if(1===n)for(let n=0;n<s;n++)e[n]=t[i[n]];else if(3===n)for(let n=0,r=0;n<s;n++,r+=3){const s=3*i[n];e[r]=t[s],e[r+1]=t[s+1],e[r+2]=t[s+2]}else if(4===n)for(let n=0,r=0;n<s;n++,r+=4){const s=4*i[n];e[r]=t[s],e[r+1]=t[s+1],e[r+2]=t[s+2],e[r+3]=t[s+3]}else for(let r=0;r<s;r++){const s=i[r]*n,o=r*n;for(let i=0;i<n;i++)e[o+i]=t[s+i]}}(e,r,i,s,n),this.gatherScratch[t]=e,r}rebuildMaterial(){const e=`quarksParticle_${this.settings.renderMode}`;this.lastStretchedSpeedFactor=Number.NaN;const i=this.fogDefines();let s,n;this.settings.renderMode===t.RenderMode.Mesh?(s={glsl:Xi,wgsl:cs},n={glsl:is,wgsl:ds}):Us.drawsAlongVelocity(this.settings.renderMode)?(s={glsl:ns,wgsl:gs},n={glsl:es,wgsl:us}):(s={glsl:ss,wgsl:fs},n={glsl:es,wgsl:us});const a=this.settings.texture??(this.settings.renderMode===t.RenderMode.Mesh?Us.whiteTexture(this.scene):null);a&&i.push("USE_MAP");const l=this.settings.reflectionAtlas;if(this.settings.renderMode===t.RenderMode.Mesh&&!!l&&!l.isReady()&&l){const t=l.onLoadObservable;t?.addOnce(()=>{this.rebuildMaterial()})}const c=this.settings.renderMode===t.RenderMode.Mesh&&!!l&&l.isReady();c&&i.push("USE_ENVMAP_ATLAS"),(this.settings.uTileCount>1||this.settings.vTileCount>1)&&i.push("UV_TILE"),this.settings.blendTiles&&i.push("TILE_BLEND"),this.settings.softParticles&&i.push("SOFT_PARTICLES"),this.settings.materialAlphaTest>0&&i.push("USE_ALPHATEST"),this.settings.renderMode===t.RenderMode.VerticalBillBoard&&i.push("VERTICAL"),this.settings.renderMode===t.RenderMode.HorizontalBillBoard&&i.push("HORIZONTAL"),this.settings.renderMode===t.RenderMode.Beam&&i.push("BEAM");const u=Us.takesPivotAndFlip(this.settings.renderMode)?this.settings.pivot:void 0;u&&i.push("PIVOT");const d=this.sizeLimits();d&&i.push("SIZE_LIMITS");const f=this.settings.renderMode===t.RenderMode.Mesh,m=this.settings.lighting??"fixed",p=f&&"unlit"!==m;f&&!p&&i.push("MESH_UNLIT");const y=f?this.settings.rim:void 0;y&&(i.push("MESH_RIM"),"fade"===y.mode?i.push("MESH_RIM_FADE"):"mix"===y.mode&&i.push("MESH_RIM_MIX"));const g=c||!!y;i.push(...this.surfaceDefines());const v=ms(this.scene.getEngine());ps(e,s,n,v);const x=["position","uv","offset","color","size","rotation","uvTile"];this.settings.renderMode===t.RenderMode.Mesh&&x.push("normal"),this.usesUV1()&&this.meshUV2()&&(i.push("MESH_UV2"),x.push("uv2")),Us.drawsAlongVelocity(this.settings.renderMode)&&x.push("velocity");const S=["world","view","projection","worldView","worldViewProjection",...Is.FOG_UNIFORMS],b=[];(this.settings.uTileCount>1||this.settings.vTileCount>1)&&(S.push("tileCountX"),S.push("tileCountY")),a&&b.push("map"),c&&(b.push("envAtlas"),S.push("reflectionLevel")),g&&S.push("eyePosition"),y&&(S.push("rimColor"),S.push("rimParams")),this.surfaceUniforms(S,b),Us.drawsAlongVelocity(this.settings.renderMode)&&S.push("speedFactor"),this.settings.softParticles&&(S.push("softParams"),S.push("projParams"),b.push("depthTexture")),this.settings.materialAlphaTest>0&&S.push("alphaTest"),u&&S.push("pivot"),d&&S.push("sizeLimits"),p&&(S.push("lightDirection"),S.push("lightColor"),S.push("ambientColor"));const w=new o.ShaderMaterial(e,this.scene,{vertex:e,fragment:e},{attributes:x,uniforms:S,samplers:b,defines:i,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:v});if(a&&w.setTexture("map",a),c&&l&&(w.setTexture("envAtlas",l),w.setFloat("reflectionLevel",this.settings.reflectionLevel)),y&&(w.setVector3("rimColor",new h.Vector3(y.color[0],y.color[1],y.color[2])),w.setVector2("rimParams",new h.Vector2(y.power,y.strength))),g){const t=new h.Vector3;w.setVector3("eyePosition",t),w.onBindObservable.add(()=>{const e=this.scene.activeCamera;e&&(t.copyFrom(e.globalPosition),w.setVector3("eyePosition",t))})}if((this.settings.uTileCount>1||this.settings.vTileCount>1)&&(w.setFloat("tileCountX",this.settings.uTileCount),w.setFloat("tileCountY",this.settings.vTileCount)),Us.drawsAlongVelocity(this.settings.renderMode)&&w.setFloat("speedFactor",this.settings.softNearFade>0?this.settings.softNearFade:1),this.settings.softParticles){w.setVector2("softParams",new h.Vector2(this.settings.softNearFade,1/Math.max(this.settings.softFarFade-this.settings.softNearFade,1e-4)));const t=new h.Vector4(0,0,0,0);w.onBindObservable.add(()=>{const e=this.scene.activeCamera;e&&(t.x=e.minZ,t.y=e.maxZ,w.setVector4("projParams",t))})}if(this.settings.materialAlphaTest>0&&w.setFloat("alphaTest",this.settings.materialAlphaTest),u&&w.setVector3("pivot",new h.Vector3(u.x,u.y,u.z)),d&&w.setVector2("sizeLimits",d),p&&(this.writeFixedLighting(w),"scene"===m)){const t=new h.Vector3,e=new h.Vector3,i=new h.Vector3;w.onBindObservable.add(()=>{Us.readSceneLight(this.scene,t,e,i)?(w.setVector3("lightDirection",t),w.setVector3("lightColor",e),w.setVector3("ambientColor",i)):this.writeFixedLighting(w)})}this.bindFog(w),this.bindSurface(w),w.backFaceCulling=!1,this.settings.materialTransparent?w.alphaMode=this.settings.materialBlendMode:w.alphaMode=r.Constants.ALPHA_DISABLE,w.needDepthPrePass=this.settings.materialDepthWrite,w.forceDepthWrite=this.settings.materialDepthWrite,w.disableDepthWrite=!this.settings.materialDepthWrite,this.mesh.material=w,this.shaderMaterial=w}applyMeshLighting(e){this.storeFixedLighting(e);const i=this.shaderMaterial;null!==i&&this.settings.renderMode===t.RenderMode.Mesh&&"unlit"!==this.settings.lighting&&this.writeFixedLighting(i)}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,i,s){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;i.set(l.r*h,l.g*h,l.b*h),s.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&&(s.x+=t.r*h,s.y+=t.g*h,s.z+=t.b*h)}return!0}return!1}update(){let e=0,i=0;const s=this.settings.renderMode,n=s===t.RenderMode.Mesh,r=s===t.RenderMode.StretchedBillBoard,o=s===t.RenderMode.Beam,a=r||o,h=Us.takesPivotAndFlip(s),l=this.getVisibleSystems();for(let t=0;t<l.length;t++)i+=l[t].particleNum;i>this.maxParticles&&this.expandBuffers(i);for(let t=0;t<l.length;t++){const i=l[t],s=i.particleNum;if(0===s)continue;const a=i.particles,c=this.quaternion2_,u=this.vector2_,d=this.vector3_,f=i.worldSpace,m=i.emitter.matrixWorld;if(n&&!f)m.decompose(u,c,d);else{const t=m.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]))}r&&!f&&this.rotationMat_.setFromMatrix4(m);const p=Math.abs(d.x),y=Math.abs(d.y),g=Math.abs(d.z),v=r?i.rendererEmitterSettings:void 0,x=void 0===v||0===v.speedFactor?.001:v.speedFactor,S=v?.lengthFactor??0,b=i.store,w=void 0!==b,M=void 0!==b&&!0!==i.onlyUsedByOther,z=i.simulationResidual??0,_=0===z?0:z/(i.simulationStep??z);w&&(0!==_&&s>0&&b.previousColor!==b.color?Us.continueColor(this.colorBuffer,4*e,b,s,_):this.colorBuffer.set(b.color.subarray(0,4*s),4*e));let V=!1;if(void 0!==b&&f)0!==_&&s>0?Us.extrapolate(this.offsetBuffer,3*e,b,s,_):this.offsetBuffer.set(b.position.subarray(0,3*s),3*e),0!==_&&s>0&&b.previousSize!==b.size?Us.continueVector3(this.sizeBuffer,3*e,b.size,b.previousSize,s,_):this.sizeBuffer.set(b.size.subarray(0,3*s),3*e),V=!0;else if(M&&s>0){const t=3*e,i=t+3*s,n=this.offsetBuffer;0!==_?Us.extrapolate(n,t,b,s,_):n.set(b.position.subarray(0,3*s),t);const r=m.elements,o=r[0],a=r[1],h=r[2],l=r[3],c=r[4],u=r[5],d=r[6],f=r[7],v=r[8],x=r[9],S=r[10],w=r[11],M=r[12],z=r[13],T=r[14],P=r[15];for(let e=t;e<i;e+=3){const t=n[e],i=n[e+1],s=n[e+2],r=1/(l*t+f*i+w*s+P);n[e]=(o*t+c*i+v*s+M)*r,n[e+1]=(a*t+u*i+x*s+z)*r,n[e+2]=(h*t+d*i+S*s+T)*r}const O=this.sizeBuffer;0!==_&&b.previousSize!==b.size?Us.continueVector3(O,t,b.size,b.previousSize,s,_):O.set(b.size.subarray(0,3*s),t);for(let e=t;e<i;e+=3)O[e]*=p,O[e+1]*=y,O[e+2]*=g;V=!0}const T=e;if(M&&!n){const t=b;this.uvTileBuffer.set(t.uvTile.subarray(0,s),T);const i=this.rotationBuffer;if(i.set(t.rotation.subarray(0,s),T),0!==z){const e=t.angularVelocity;for(let t=0;t<s;t++)i[T+t]+=e[t]*z}r&&this.velocityBuffer&&Us.writeVelocities(this.velocityBuffer,4*T,t,s,_,f?null:this.rotationMat_,x,S),e+=s}else if(M&&b.rotationQuaternion.length>0){const t=b;this.uvTileBuffer.set(t.uvTile.subarray(0,s),T),Us.writeQuaternions(this.rotationBuffer,4*T,t,s,_,f?null:c),e+=s}else for(let t=0;t<s;t++,e++){const i=a[t];if(n){let t=i.rotation;const s=i.angularVelocity;let n;if(0!==_&&s instanceof H&&(t=this.quaternion4_.copy(t).multiply(Us.partialTurn(s,_,this.quaternion5_))),f)n=t;else{let e;e=i.parentMatrix?this.quaternion3_.setFromRotationMatrix(i.parentMatrix):c,n=this.quaternion_,n.copy(e).multiply(t)}const r=4*e;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 t=i.angularVelocity;this.rotationBuffer[e]=i.rotation+("number"==typeof t?t*z:0)}if(!V){const t=i.position,s=i.previousPosition;let n=t.x+(t.x-s.x)*_,r=t.y+(t.y-s.y)*_,o=t.z+(t.z-s.z)*_;if(!f){const t=(i.parentMatrix??m).elements,e=1/(t[3]*n+t[7]*r+t[11]*o+t[15]),s=(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=s,r=a}const a=3*e;this.offsetBuffer[a]=n,this.offsetBuffer[a+1]=r,this.offsetBuffer[a+2]=o;const h=i.size,l=3*e;f||i.parentMatrix?(this.sizeBuffer[l]=h.x,this.sizeBuffer[l+1]=h.y,this.sizeBuffer[l+2]=h.z):(this.sizeBuffer[l]=h.x*p,this.sizeBuffer[l+1]=h.y*y,this.sizeBuffer[l+2]=h.z*g)}if(!w){const t=i.color,s=4*e;this.colorBuffer[s]=t.x,this.colorBuffer[s+1]=t.y,this.colorBuffer[s+2]=t.z,this.colorBuffer[s+3]=t.w}if(this.uvTileBuffer[e]=i.uvTile,r&&this.velocityBuffer){const t=i.velocity,s=i.previousVelocity,n=t.x+(t.x-s.x)*_,r=t.y+(t.y-s.y)*_,o=t.z+(t.z-s.z)*_;let a=this.vector_;a.set(n,r,o),f||(i.parentMatrix?(this.rotationMat2_.setFromMatrix4(i.parentMatrix),a.applyMatrix3(this.rotationMat2_)):a.applyMatrix3(this.rotationMat_));const h=4*e;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 P=i.tint;void 0!==P&&e>T&&Us.applyTint(this.colorBuffer,4*T,e-T,P),h&&void 0!==i.flip&&(void 0!==b?Us.applyFlip(this.sizeBuffer,3*T,b.flip,s):Us.applyFlipFromParticles(this.sizeBuffer,3*T,a,s)),o&&this.velocityBuffer&&this.writeBeams(i,T,e-T)}r&&l.length>0&&this.syncStretchedSpeedFactor(l[0]),this.mesh.forcedInstanceCount=e,this.refreshBoundingInfo(),0!==e?(this.clearedInstanceUploaded=!1,"none"!==this.settings.sortMode&&this.sortInstances(e,n,a),this.offsetVB.update(this.offsetBuffer.subarray(0,3*e)),this.sizeVB.update(this.sizeBuffer.subarray(0,3*e)),this.colorVB.update(this.colorBuffer.subarray(0,4*e)),this.uvTileVB.update(this.uvTileBuffer.subarray(0,e)),this.rotationVB.update(this.rotationBuffer.subarray(0,n?4*e:e)),a&&this.velocityVB&&this.velocityBuffer&&this.velocityVB.update(this.velocityBuffer.subarray(0,4*e))):this.clearedInstanceUploaded||(this.uploadClearedInstance(n,a),this.clearedInstanceUploaded=!0)}syncStretchedSpeedFactor(t){const e=this.shaderMaterial;if(null===e)return;const i=t.rendererEmitterSettings.speedFactor??1,s=0===i?.001:i;s!==this.lastStretchedSpeedFactor&&(e.setFloat("speedFactor",s),this.lastStretchedSpeedFactor=s)}static drawsAlongVelocity(e){return e===t.RenderMode.StretchedBillBoard||e===t.RenderMode.Beam}writeBeams(t,e,i){const s=this.velocityBuffer,n=this.offsetBuffer,r=this.beamEnd_,o="function"==typeof t.getBeamEnd&&t.getBeamEnd(r);for(let t=e;t<e+i;t++){const e=3*t,i=4*t;s[i]=o?r.x-n[e]:0,s[i+1]=o?r.y-n[e+1]:0,s[i+2]=o?r.z-n[e+2]:0,s[i+3]=0}}static takesPivotAndFlip(e){return e===t.RenderMode.BillBoard||e===t.RenderMode.StretchedBillBoard||e===t.RenderMode.VerticalBillBoard||e===t.RenderMode.HorizontalBillBoard}static applyTint(t,e,i,s){for(let n=0,r=e;n<i;n++,r+=4)t[r]*=s.x,t[r+1]*=s.y,t[r+2]*=s.z,t[r+3]*=s.w}static applyFlip(t,e,i,s){for(let n=0,r=e;n<s;n++,r+=3){const e=i[n];0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static applyFlipFromParticles(t,e,i,s){for(let n=0,r=e;n<s;n++,r+=3){const e=i[n].flip;0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static writeQuaternions(t,e,i,s,n,r){const o=i.rotationQuaternion,a=i.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 i=0,r=0,f=e;i<s;i++,r+=4,f+=4){let e=o[r],i=o[r+1],s=o[r+2],m=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,p=l*c,y=e*p+m*u+i*f-s*d,g=i*p+m*d+s*u-e*f,v=s*p+m*f+e*d-i*u;m=m*p-e*u-i*d-s*f,e=y,i=g,s=v}if(h){const t=l*m+d*e+c*s-u*i,n=c*m+d*i+u*e-l*s,r=u*m+d*s+l*i-c*e;m=d*m-l*e-c*i-u*s,e=t,i=n,s=r}t[f]=e,t[f+1]=i,t[f+2]=s,t[f+3]=m}}static writeVelocities(t,e,i,s,n,r,o,a){const h=i.velocity,l=i.previousVelocity.length>=3*s?i.previousVelocity:h,c=null!==r?r.elements:null;for(let i=0,r=0,u=e;i<s;i++,r+=3,u+=4){let e=h[r],i=h[r+1],s=h[r+2];if(0!==n&&(e+=(e-l[r])*n,i+=(i-l[r+1])*n,s+=(s-l[r+2])*n),null!==c){const t=c[0]*e+c[3]*i+c[6]*s,n=c[1]*e+c[4]*i+c[7]*s;s=c[2]*e+c[5]*i+c[8]*s,e=t,i=n}t[u]=e*o,t[u+1]=i*o,t[u+2]=s*o,t[u+3]=a}}static partialTurn(t,e,i){const s=t.x*e,n=t.y*e,r=t.z*e,o=1+(t.w-1)*e,a=1/Math.sqrt(s*s+n*n+r*r+o*o);return i.x=s*a,i.y=n*a,i.z=r*a,i.w=o*a,i}static continueVector3(t,e,i,s,n,r){for(let o=0,a=0;o<n;o++,a+=3){const n=i[a]+(i[a]-s[a])*r,o=i[a+1]+(i[a+1]-s[a+1])*r,h=i[a+2]+(i[a+2]-s[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,i,s,n){const r=i.color,o=i.previousColor;for(let i=0,a=0;i<s;i++,a+=4){const i=r[a]+(r[a]-o[a])*n,s=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]=i>0?i:0,t[e+a+1]=s>0?s:0,t[e+a+2]=h>0?h:0,t[e+a+3]=l>0?l:0}}static extrapolate(t,e,i,s,n){const r=i.position,o=i.previousPosition;for(let i=0,a=0;i<s;i++,a+=3){const i=r[a],s=r[a+1],h=r[a+2];t[e+a]=i+(i-o[a])*n,t[e+a+1]=s+(s-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.mesh.material&&this.mesh.material.dispose(),super.dispose()}}Us.whiteTextureByScene=new WeakMap;var Es=`\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${ji}\n${Ki}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${ts(!1)}\n if (baseColor.a < 0.01) { discard; }\n\n${Yi("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,Ns=`\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;\nuniform lineWidth: f32;\nuniform resolution: vec2f;\nuniform sizeAttenuation: f32;\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\nfn fix(i: vec4f, aspect: f32) -> vec2f {\n var res = i.xy / i.w;\n res.x *= aspect;\n return res;\n}\n\n${Gi}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let aspect = uniforms.resolution.x / uniforms.resolution.y;\n var finalPosition = uniforms.projection * uniforms.view * vec4f(vertexInputs.position, 1.0);\n let prevPos = uniforms.projection * uniforms.view * vec4f(vertexInputs.previous, 1.0);\n let nextPos = uniforms.projection * uniforms.view * vec4f(vertexInputs.next, 1.0);\n\n let currentP = fix(finalPosition, aspect);\n let prevP = fix(prevPos, aspect);\n let nextP = fix(nextPos, aspect);\n\n let w = uniforms.lineWidth * vertexInputs.width;\n var dir: vec2f;\n if (distance(nextP, currentP) < 0.0001) {\n dir = normalize(currentP - prevP);\n } else if (distance(prevP, currentP) < 0.0001) {\n dir = normalize(nextP - currentP);\n } else {\n let dir1 = normalize(currentP - prevP);\n let dir2 = normalize(nextP - currentP);\n dir = normalize(dir1 + dir2);\n }\n var normal = vec4f(-dir.y, dir.x, 0.0, 1.0);\n normal.x *= 0.5 * w;\n normal.y *= 0.5 * w;\n normal = normal * uniforms.projection;\n if (uniforms.sizeAttenuation == 0.0) {\n let screen = (vec4f(uniforms.resolution, 0.0, 1.0) * uniforms.projection).xy;\n normal.x = normal.x * finalPosition.w / screen.x;\n normal.y = normal.y * finalPosition.w / screen.y;\n }\n finalPosition.x += normal.x * vertexInputs.side;\n finalPosition.y += normal.y * vertexInputs.side;\n\n vertexOutputs.position = finalPosition;\n${Wi("(uniforms.view * vec4f(vertexInputs.position, 1.0)).xyz")}\n vertexOutputs.vUV = vertexInputs.uv;\n#ifdef UV1\n vertexOutputs.vUV1 = vertexInputs.uv2;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;class Rs extends Is{constructor(t,e){super(t,e),this.uv1Buffer=null,this.drawsNothing=!1,this.vector_=new K,this.vector2_=new K,this.vector3_=new K,this.quaternion_=new H,this.maxParticles=1024,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh.dispose(),this.mesh=new l.Mesh("trailBatch",this.scene),this.configureMesh(),this.buildGeometryBuffers()}buildGeometryBuffers(){this.positionBuffer=new Float32Array(6*this.maxParticles),this.previousBuffer=new Float32Array(6*this.maxParticles),this.nextBuffer=new Float32Array(6*this.maxParticles),this.uvBuffer=new Float32Array(4*this.maxParticles),this.uv1Buffer=this.usesUV1()?new Float32Array(4*this.maxParticles):null,this.sideBuffer=new Float32Array(2*this.maxParticles),this.widthBuffer=new Float32Array(2*this.maxParticles),this.colorBuffer=new Float32Array(8*this.maxParticles),this.indexBuffer=new Uint32Array(6*this.maxParticles);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(e.VertexBuffer.PositionKind,this.positionBuffer,!0),this.mesh.setVerticesData(e.VertexBuffer.UVKind,this.uvBuffer,!0),this.uv1Buffer&&this.mesh.setVerticesData(e.VertexBuffer.UV2Kind,this.uv1Buffer,!0),this.mesh.setVerticesData(e.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 t=this.scene.getEngine();this.previousVB=new e.VertexBuffer(t,this.previousBuffer,"previous",!0,!1,3,!1),this.nextVB=new e.VertexBuffer(t,this.nextBuffer,"next",!0,!1,3,!1),this.sideVB=new e.VertexBuffer(t,this.sideBuffer,"side",!0,!1,1,!1),this.widthVB=new e.VertexBuffer(t,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.previousVB?.dispose(),this.nextVB?.dispose(),this.sideVB?.dispose(),this.widthVB?.dispose(),this.buildGeometryBuffers()}rebuildMaterial(){const t="quarksTrail",e=this.fogDefines();this.settings.texture&&e.push("USE_MAP"),e.push(...this.surfaceDefines());const i=ms(this.scene.getEngine());ps(t,{glsl:os,wgsl:Ns},{glsl:rs,wgsl:Es},i);const s=["position","previous","next","side","width","uv","color"];this.uv1Buffer&&s.push("uv2");const n=["world","view","projection","worldViewProjection","lineWidth","resolution","sizeAttenuation",...Is.FOG_UNIFORMS],a=[];this.settings.texture&&a.push("map"),this.surfaceUniforms(n,a);const l=new o.ShaderMaterial(t,this.scene,{vertex:t,fragment:t},{attributes:s,uniforms:n,samplers:a,defines:e,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:i});this.settings.texture&&l.setTexture("map",this.settings.texture);const c=this.scene.getEngine();l.setFloat("lineWidth",1);const u=new h.Vector2(c.getRenderWidth(),c.getRenderHeight());l.setVector2("resolution",u),l.setFloat("sizeAttenuation",1),l.onBindObservable.add(()=>{const t=this.scene.getEngine(),e=t.getRenderWidth(),i=t.getRenderHeight();u.x===e&&u.y===i||(u.x=e,u.y=i,l.setVector2("resolution",u))}),this.bindFog(l),this.bindSurface(l),l.backFaceCulling=!1,this.settings.materialTransparent?l.alphaMode=this.settings.materialBlendMode:l.alphaMode=r.Constants.ALPHA_DISABLE,l.needDepthPrePass=this.settings.materialDepthWrite,l.forceDepthWrite=this.settings.materialDepthWrite,l.disableDepthWrite=!this.settings.materialDepthWrite,this.mesh.material=l}writeSweptPair(t,e,i,s,n,r,o,a){const h=this.positionBuffer;h[t]=e+n*a,h[t+1]=i+r*a,h[t+2]=s+o*a,h[t+3]=e-n*a,h[t+4]=i-r*a,h[t+5]=s-o*a}static ensureWorldMatrix(t){const e=t.emitter;!e.computeWorldMatrix||e.isSynchronized&&e.isSynchronized()||e.computeWorldMatrix(!0)}update(){let t=0,e=0,i=0;const s=this.getVisibleSystems();for(let t=0;t<s.length;t++){const e=s[t],n=e.particles;for(let t=0;t<e.particleNum;t++){const e=n[t].historyCount;0!==e&&(i+=2*e+2)}}i>this.maxParticles&&this.expandBuffers(i);for(let i=0;i<s.length;i++){const n=s[i],r=t;Rs.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,m=1/d,p=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);for(let i=0;i<u;i++){const s=c[i],n=s.historyCount;if(0===n)continue;const r=s.historyCapacity,o=s.historyPositions,a=s.historySizes,h=s.historySides,u=void 0!==M&&h.length===3*r,d=b?s.store.color:s.historyColors,v=4*s.storeIndex,z=s.uvTile%f,V=Math.floor(s.uvTile/f+.001),T=(s.parentMatrix??l).elements,P=T[0],O=T[1],A=T[2],B=T[3],C=T[4],F=T[5],$=T[6],I=T[7],U=T[8],E=T[9],N=T[10],R=T[11],D=T[12],L=T[13],q=T[14],k=T[15],J=1/(0!==_?n:Math.max(1,n-1));let Q=s.getHistoryIndex(0),G=o[3*Q],W=o[3*Q+1],j=o[3*Q+2];if(!w){const t=1/(B*G+I*W+R*j+k),e=(P*G+C*W+U*j+D)*t,i=(O*G+F*W+E*j+L)*t;j=(A*G+$*W+N*j+q)*t,G=e,W=i}let Y=G,X=W,Z=j;for(let i=0;i<n;i++,t+=2){let l=G,c=W,M=j,_=Q;if(i+1<n){_=Q+1===r?0:Q+1;const t=3*_;if(l=o[t],c=o[t+1],M=o[t+2],!w){const t=1/(B*l+I*c+R*M+k),e=(P*l+C*c+U*M+D)*t,i=(O*l+F*c+E*M+L)*t;M=(A*l+$*c+N*M+q)*t,l=e,c=i}}const T=a[Q],H=b?v:4*Q,K=d[H],tt=d[H+1],et=d[H+2],it=d[H+3],st=3*t;if(u){const t=3*Q;let e=h[t],i=h[t+1],s=h[t+2];if(!w){const t=P*e+C*i+U*s,n=O*e+F*i+E*s;s=A*e+$*i+N*s,e=t,i=n}this.writeSweptPair(st,G,W,j,e,i,s,.5*T)}else this.positionBuffer[st]=G,this.positionBuffer[st+1]=W,this.positionBuffer[st+2]=j,this.positionBuffer[st+3]=G,this.positionBuffer[st+4]=W,this.positionBuffer[st+5]=j;this.previousBuffer[st]=Y,this.previousBuffer[st+1]=X,this.previousBuffer[st+2]=Z,this.previousBuffer[st+3]=Y,this.previousBuffer[st+4]=X,this.previousBuffer[st+5]=Z,this.nextBuffer[st]=l,this.nextBuffer[st+1]=c,this.nextBuffer[st+2]=M,this.nextBuffer[st+3]=l,this.nextBuffer[st+4]=c,this.nextBuffer[st+5]=M,u?(this.widthBuffer[t]=0,this.widthBuffer[t+1]=0):y||s.parentMatrix?(this.widthBuffer[t]=T,this.widthBuffer[t+1]=T):(this.widthBuffer[t]=T*g,this.widthBuffer[t+1]=T*g);const nt=2*t,rt=i*J,ot=((x?1-rt:rt)+z)*m;if(this.uvBuffer[nt]=ot,this.uvBuffer[nt+1]=(f-V-1)*p,this.uvBuffer[nt+2]=ot,this.uvBuffer[nt+3]=(f-V)*p,S){const t=x?1-rt:rt;S[nt]=t,S[nt+1]=0,S[nt+2]=t,S[nt+3]=1}const at=4*t;this.colorBuffer[at]=K,this.colorBuffer[at+1]=tt,this.colorBuffer[at+2]=et,this.colorBuffer[at+3]=it,this.colorBuffer[at+4]=K,this.colorBuffer[at+5]=tt,this.colorBuffer[at+6]=et,this.colorBuffer[at+7]=it,i+1<n&&(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++),Y=G,X=W,Z=j,G=l,W=c,j=M,Q=_}if(0!==_){const i=s.previousPosition,n=s.position;let r=n.x+(n.x-i.x)*_,o=n.y+(n.y-i.y)*_,a=n.z+(n.z-i.z)*_;const h=t-2,l=.5*(this.positionBuffer[3*h]+this.positionBuffer[3*h+3]),c=.5*(this.positionBuffer[3*h+1]+this.positionBuffer[3*h+4]),d=.5*(this.positionBuffer[3*h+2]+this.positionBuffer[3*h+5]);if(!y){const t=1/(B*r+I*o+R*a+k),e=(P*r+C*o+U*a+D)*t,i=(O*r+F*o+E*a+L)*t;a=(A*r+$*o+N*a+q)*t,r=e,o=i}const v=3*t,b=s.size.x;if(u){const t=M.x,e=M.y,i=M.z;this.writeSweptPair(v,r,o,a,P*t+C*e+U*i,O*t+F*e+E*i,A*t+$*e+N*i,.5*b)}else this.positionBuffer[v]=r,this.positionBuffer[v+1]=o,this.positionBuffer[v+2]=a,this.positionBuffer[v+3]=r,this.positionBuffer[v+4]=o,this.positionBuffer[v+5]=a;this.previousBuffer[v]=l,this.previousBuffer[v+1]=c,this.previousBuffer[v+2]=d,this.previousBuffer[v+3]=l,this.previousBuffer[v+4]=c,this.previousBuffer[v+5]=d,this.nextBuffer[v]=r,this.nextBuffer[v+1]=o,this.nextBuffer[v+2]=a,this.nextBuffer[v+3]=r,this.nextBuffer[v+4]=o,this.nextBuffer[v+5]=a;const w=3*h;this.nextBuffer[w]=r,this.nextBuffer[w+1]=o,this.nextBuffer[w+2]=a,this.nextBuffer[w+3]=r,this.nextBuffer[w+4]=o,this.nextBuffer[w+5]=a,u?(this.widthBuffer[t]=0,this.widthBuffer[t+1]=0):y||s.parentMatrix?(this.widthBuffer[t]=b,this.widthBuffer[t+1]=b):(this.widthBuffer[t]=b*g,this.widthBuffer[t+1]=b*g);const T=2*t,J=((x?0:1)+z)*m;if(this.uvBuffer[T]=J,this.uvBuffer[T+1]=(f-V-1)*p,this.uvBuffer[T+2]=J,this.uvBuffer[T+3]=(f-V)*p,S){const t=x?0:1;S[T]=t,S[T+1]=0,S[T+2]=t,S[T+3]=1}const Q=s.color,G=4*t;this.colorBuffer[G]=Q.x,this.colorBuffer[G+1]=Q.y,this.colorBuffer[G+2]=Q.z,this.colorBuffer[G+3]=Q.w,this.colorBuffer[G+4]=Q.x,this.colorBuffer[G+5]=Q.y,this.colorBuffer[G+6]=Q.z,this.colorBuffer[G+7]=Q.w,this.indexBuffer[3*e]=h,this.indexBuffer[3*e+1]=h+1,this.indexBuffer[3*e+2]=t,e++,this.indexBuffer[3*e]=t,this.indexBuffer[3*e+1]=h+1,this.indexBuffer[3*e+2]=t+1,e++,t+=2}}const V=n.tint;if(void 0!==V){const e=this.colorBuffer;for(let i=4*r,s=4*t;i<s;i+=4)e[i]*=V.x,e[i+1]*=V.y,e[i+2]*=V.z,e[i+3]*=V.w}this.measureSystemBounds(n,r,t)}this.refreshBoundingInfo(),this.uploadGeometry(t,e)}measureSystemBounds(t,e,i){if(i<=e||"function"!=typeof t.setWorldBounds)return;const s=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*i;t<c;t+=3){const e=s[t],i=s[t+1],c=s[t+2];e<n&&(n=e),e>a&&(a=e),i<r&&(r=i),i>h&&(h=i),c<o&&(o=c),c>l&&(l=c)}const c=this.widthBuffer;let u=0;for(let t=e;t<i;t+=2){const e=c[t];e>u&&(u=e)}t.setWorldBounds(n,r,o,a,h,l,u)}uploadGeometry(t,i){const s=this.mesh.geometry,n=s?.getIndexBuffer();if(t>0&&i>0){this.mesh.updateVerticesData(e.VertexBuffer.PositionKind,this.positionBuffer.subarray(0,3*t)),this.mesh.updateVerticesData(e.VertexBuffer.UVKind,this.uvBuffer.subarray(0,2*t)),this.uv1Buffer&&this.mesh.updateVerticesData(e.VertexBuffer.UV2Kind,this.uv1Buffer.subarray(0,2*t)),n&&this.scene.getEngine().updateDynamicIndexBuffer(n,this.indexBuffer.subarray(0,3*i),0),this.previousVB.update(this.previousBuffer.subarray(0,3*t)),this.nextVB.update(this.nextBuffer.subarray(0,3*t)),this.widthVB.update(this.widthBuffer.subarray(0,t));const s=this.mesh.getVertexBuffer(e.VertexBuffer.ColorKind);s&&s.update(this.colorBuffer.subarray(0,4*t)),this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.mesh.subMeshes[0].indexCount=3*i,this.mesh.subMeshes[0].verticesCount=t),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._boundingInfo=t}dispose(){this.mesh.material&&this.mesh.material.dispose(),super.dispose()}}class Ds extends n.TransformNode{constructor(t,e){super(t,e),this.batches=[],this.elapsed=0,this.systemToBatchIndex=new Map,this.depthTexture=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=vs(),this.cullingEnabled=!0,this.catchUpBudgetMs=2,this.simulationBudgetMs=1/0,this.frustumPlanes=[],this.boundsMin=new K,this.boundsMax=new K}collectFrustumPlanes(){const t=this.getScene(),e=this.frustumPlanes,n=t.activeCameras,r=t.activeCamera,o=n&&n.length>0?n:r?[r]:[],a=6*o.length;for(;e.length<a;)e.push(new s.Plane(0,0,0,0));e.length=a;for(let t=0;t<o.length;t++){const s=o[t];s.getViewMatrix(),s.getProjectionMatrix();const n=s.getTransformationMatrix(),r=0===t?e:e.slice(6*t,6*t+6);if(i.Frustum.GetPlanesToRef(n,r),0!==t)for(let i=0;i<6;i++)e[6*t+i]=r[i]}return e}isSystemInView(t,e){const i=this.boundsMin,s=this.boundsMax;if(!t.getWorldBounds(i,s))return!0;for(let t=0;t<e.length;t+=6){let n=!0;for(let r=t;r<t+6;r++){const t=e[r],o=t.normal,a=o.x>=0?s.x:i.x,h=o.y>=0?s.y:i.y,l=o.z>=0?s.z:i.z;if(o.x*a+o.y*h+o.z*l+t.d<0){n=!1;break}}if(n)return!0}return!1}static clamp(t,e,i){return Math.max(e,Math.min(i,t))}static equals(e,i){return e.materialBlendMode===i.materialBlendMode&&e.materialTransparent===i.materialTransparent&&e.materialDepthTest===i.materialDepthTest&&e.materialDepthWrite===i.materialDepthWrite&&e.materialAlphaTest===i.materialAlphaTest&&e.texture===i.texture&&e.reflectionTexture===i.reflectionTexture&&e.reflectionLevel===i.reflectionLevel&&function(t,e){if(t===e)return!0;if(!t||!e||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0}(e.reflectionFaces,i.reflectionFaces)&&e.reflectionAtlas===i.reflectionAtlas&&e.renderMode===i.renderMode&&e.blendTiles===i.blendTiles&&e.softParticles===i.softParticles&&e.softFarFade===i.softFarFade&&e.softNearFade===i.softNearFade&&e.uTileCount===i.uTileCount&&e.vTileCount===i.vTileCount&&e.instancingGeometry===i.instancingGeometry&&(e.renderMode===t.RenderMode.Trail||e.instancingUVs===i.instancingUVs)&&(e.renderMode!==t.RenderMode.Mesh||e.instancingNormals===i.instancingNormals)&&(e.renderMode!==t.RenderMode.Mesh||!$s(e)||e.instancingUVs2===i.instancingUVs2)&&e.renderOrder===i.renderOrder&&e.layerMask===i.layerMask&&e.renderingGroupId===i.renderingGroupId&&e.applyFog===i.applyFog&&function(t,e){return(t?.x??0)===(e?.x??0)&&(t?.y??0)===(e?.y??0)&&(t?.z??0)===(e?.z??0)}(e.pivot,i.pivot)&&e.sortMode===(i.sortMode??"none")&&e.minParticleSize===(i.minParticleSize??0)&&e.maxParticleSize===(i.maxParticleSize??1/0)&&(e.lighting??"fixed")===(i.lighting??"fixed")&&Ss(e.rim,i.rim)&&Fs(e.mapUV,i.mapUV)&&Bs(e.uvDistortion,i.uvDistortion)&&Vs(e.gradientMap,i.gradientMap)&&Ps(e.erosion,i.erosion)}addSystem(t){const e=t;e._renderer=this,this.systemToBatchIndex.has(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(e){const i=e,s=e.getRendererSettings();for(let t=0;t<this.batches.length;t++)if(Ds.equals(this.batches[t].settings,s))return this.batches[t].addSystem(i),void this.systemToBatchIndex.set(i,t);let n;const r=this.getScene();switch(s.renderMode){case t.RenderMode.Trail:n=new Rs(s,r);break;case t.RenderMode.Mesh:case t.RenderMode.BillBoard:case t.RenderMode.VerticalBillBoard:case t.RenderMode.HorizontalBillBoard:case t.RenderMode.StretchedBillBoard:case t.RenderMode.Beam:n=new Us(s,r);break;default:throw new Error(`Unsupported render mode: ${s.renderMode}`)}n.mesh.parent=this,this.depthTexture&&n.applyDepthTexture(this.depthTexture),n.applyMeshLighting(this.meshLighting),n.addSystem(i),this.batches.push(n),this.batchEmptyFrames.push(0),this.systemToBatchIndex.set(i,this.batches.length-1)}deleteSystem(t){const e=this.removeFromBatch(t),i=this.systems.indexOf(t);-1!==i&&(this.systems.splice(i,1),this.orderedSystemsStale=!0);const s=this.orderedSystems.indexOf(t);return-1!==s&&this.orderedSystems.splice(s,1),e}removeFromBatch(t){const e=this.systemToBatchIndex.get(t);return void 0!==e&&(this.batches[e].removeSystem(t),this.systemToBatchIndex.delete(t),!0)}updateSystem(t){this.removeFromBatch(t),this.addSystem(t)}setDepthTexture(t){this.depthTexture=t;for(const e of this.batches)e.applyDepthTexture(t)}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.batches)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,i=Ds.clamp(t.minQuality??e.minQuality,.05,1),s=Ds.clamp(t.maxQuality??e.maxQuality,i,1);e.targetFrameMs=Math.max(t.targetFrameMs??e.targetFrameMs,.1),e.minQuality=i,e.maxQuality=s,e.decreaseStep=Math.max(t.decreaseStep??e.decreaseStep,.001),e.increaseStep=Math.max(t.increaseStep??e.increaseStep,.001),e.currentQuality=Ds.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,i=new Set,s=new Set(this.systems),n=r=>{if(!i.has(r)&&!e.has(r)){e.add(r);for(const t of(t=>{const e=[];for(const i of t.behaviors??[]){if("EmitSubParticleSystem"!==i.type)continue;const t=i.subParticleSystem?.system;void 0!==t&&s.has(t)&&e.push(t)}return e})(r))n(t);e.delete(r),i.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,i=e.enabled?performance.now():0;e.enabled&&this.applyAdaptiveQuality();const s=this.orderSystems(),n=this.cullingEnabled?this.collectFrustumPlanes():null,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<s.length;e++){const i=s[e];i.emitter.visible&&(i.culled=null!==n&&n.length>0&&"always"!==i.cullingMode&&!0!==i.onlyUsedByOther&&!this.isSystemInView(i,n),i.update(t,o,a)),s[e]!==i&&e--}this.refreshBatches(),e.enabled&&(e.lastFrameCpuMs=performance.now()-i,e.lastFrameCpuMs>e.targetFrameMs?e.currentQuality=Ds.clamp(e.currentQuality-e.decreaseStep,e.minQuality,e.maxQuality):e.currentQuality=Ds.clamp(e.currentQuality+e.increaseStep,e.minQuality,e.maxQuality))}refreshBatches(){const t=this.batchEmptyFrames;for(let e=0;e<this.batches.length;e++){const i=this.batches[e];if(i.time=this.elapsed,i.systems.size>0){t[e]=0,i.update();continue}const s=(t[e]??0)+1;t[e]=s,1===s?i.update():s>Ds.EMPTY_BATCH_GRACE_FRAMES&&(this.removeBatch(e),e--)}}removeBatch(t){this.batches[t].dispose(),this.batches.splice(t,1),this.batchEmptyFrames.splice(t,1);for(const[e,i]of this.systemToBatchIndex)i>t&&this.systemToBatchIndex.set(e,i-1)}getBatchRenderStats(){return this.batches.map((t,e)=>{let i=0;const s=[];for(const e of t.systems){const t=e;i+=t.particleNum,s.push(t.emitter.name)}return{batchIndex:e,renderMode:t.settings.renderMode,instanceCount:t.mesh.forcedInstanceCount??0,particleCount:i,systemNames:s}})}dispose(){for(const t of this.batches)t.dispose();this.batches=[],this.batchEmptyFrames.length=0,this.systems.length=0,this.systemToBatchIndex.clear(),super.dispose()}}Ds.EMPTY_BATCH_GRACE_FRAMES=120;const Ls=Ds;class qs extends n.TransformNode{get matrixWorld(){const t=this.getWorldMatrix(),e=t.updateFlag;if(e===this._matrixWorldFlag)return this._matrixWorld;this._matrixWorldFlag=e;const i=this._matrixWorld.elements,s=t.m;return i[0]=s[0],i[1]=s[1],i[2]=s[2],i[3]=s[3],i[4]=s[4],i[5]=s[5],i[6]=s[6],i[7]=s[7],i[8]=s[8],i[9]=s[9],i[10]=s[10],i[11]=s[11],i[12]=s[12],i[13]=s[13],i[14]=s[14],i[15]=s[15],this._matrixWorld}get visible(){return this.isEnabled()}set visible(t){this.setEnabled(t)}get uuid(){return this.uniqueId.toString()}constructor(t,e){super("particleEmitter",e||void 0),this._matrixWorld=new nt,this._matrixWorldFlag=-1,this.system=t}dispose(){super.dispose()}extractFromCache(t){const e=[];for(const i in t){const s=t[i];s&&"object"==typeof s&&delete s.metadata,e.push(s)}return e}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:this._quarksUUID??this.uniqueId.toString(),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(),ps:this.system.toJSON(t,e)}}}class ks{static runOnAllParticleEmitters(t,e){ks.traverseNode(t,t=>{t instanceof qs&&e(t)})}static addToBatchRenderer(t,e){ks.runOnAllParticleEmitters(t,t=>{e.addSystem(t.system)})}static play(t){ks.runOnAllParticleEmitters(t,t=>{t.system.play()})}static stop(t){ks.runOnAllParticleEmitters(t,t=>{t.system.stop()})}static pause(t){ks.runOnAllParticleEmitters(t,t=>{t.system.pause()})}static restart(t){ks.runOnAllParticleEmitters(t,t=>{t.system.restart()})}static setAutoDestroy(t,e){ks.runOnAllParticleEmitters(t,t=>{t.system.autoDestroy=e})}static endEmit(t){ks.runOnAllParticleEmitters(t,t=>{t.system.endEmit()})}static isEffectFinished(t){let e=!1,i=!0;return ks.runOnAllParticleEmitters(t,t=>{e=!0,t.system.isFinished()||(i=!1)}),e&&i}static instantiate(t,e){const i=new Map,s=(t,e,r)=>{let o;if(t instanceof qs)o=t.clone(r),i.set(t,o);else{if(!(t instanceof n.TransformNode))return null;o=new n.TransformNode(r??t.name,t.getScene()),o.position.copyFrom(t.position),o.rotation.copyFrom(t.rotation),o.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(o.rotationQuaternion=t.rotationQuaternion.clone()),o.setEnabled(t.isEnabled(!1))}o.parent=e;for(const e of t.getChildren())s(e,o);return o},r=s(t,null,e);for(const t of i.values())for(const e of t.system.behaviors)if(e instanceof ve){const t=i.get(e.subParticleSystem);void 0!==t&&(e.subParticleSystem=t)}return r}static getDuration(t){const e=[];ks.runOnAllParticleEmitters(t,t=>{e.push(t.system)});const i=new Map;for(let t=0;t<e.length;t++){const s=e[t];for(const t of s.behaviors){if(!(t instanceof ve))continue;const n=t.subParticleSystem?.system;if(void 0!==n&&"object"==typeof n){e.includes(n)||e.push(n);const t=i.get(n)??[];t.push(s),i.set(n,t)}}}const s=new Map,n=t=>{const e=s.get(t);if(void 0!==e)return e;s.set(t,1/0);const r=t.playbackSpeed,o=ks.maxOf(t.startLife)/r;let a;if(r>0)if(t.onlyUsedByOther){a=0;for(const e of i.get(t)??[])a=Math.max(a,n(e));a+=t.duration/r+o}else a=t.looping?1/0:(ks.maxOf(t.startDelay,0)+t.duration)/r+o;else a=1/0;return s.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 Bt)return t.value;if(t instanceof Ct)return Math.max(t.a,t.b);let i=-1/0;for(let s=0;s<=32;s++){const n=[];t.startGen(n);const r="function"===t.type?t.genValue(n,e??s/32):t.genValue(n);i=Math.max(i,r)}return i}static traverseNode(t,e){e(t);const i=t.getChildren();for(const t of i)ks.traverseNode(t,e)}}const Js=new WeakMap,Qs=new WeakMap;function Gs(t){if(!t?.isCube)return null;const e=t.files??t._files;return 6===e?.length?e.slice():null}function Ws(t){return Js.get(t)??null}async function js(t,e){if("undefined"==typeof document||"undefined"==typeof Image)throw new Error("createEnvAtlasFromFaceUrls requires a DOM Image/canvas environment");const i=await Promise.all(t.map(t=>function(t){return new Promise((e,i)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>e(s),s.onerror=()=>i(new Error(`Failed to load env face ${t}`)),s.src=t})}(t))),s=i[0].width||i[0].naturalWidth;if(!s)throw new Error("Env atlas face image has zero size");const n=document.createElement("canvas");n.width=3*s,n.height=2*s;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(i[t],t%3*s,Math.floor(t/3)*s,s,s);const o=new g.Texture(n.toDataURL("image/jpeg",.92),e,{noMipmap:!0,invertY:!1,samplingMode:g.Texture.LINEAR_LINEAR});return o.name="quarksEnvAtlas",o}const Ys={createFromFaceUrls:js};function Xs(t,e,i){const s=Js.get(t);if(s)return i(s),s;const n=()=>{const s=Qs.get(t);if(s)return void s.then(t=>{t&&i(t)});const n=Gs(t);if(!n)return;const r=Ys.createFromFaceUrls(n,e).then(e=>(Js.set(t,e),Qs.delete(t),i(e),e)).catch(e=>(Qs.delete(t),console.warn("[babylon.quarks] Failed to build env atlas from cubemap faces",e),null));Qs.set(t,r)};if(t.isReady())n();else{const e=t.onLoadObservable;e?e.addOnce(()=>n()):n()}return Js.get(t)??null}class Zs extends x.StandardMaterial{constructor(t,e,i={}){super(t,e),this.isParticleMeshStandardMaterial=!0,Object.assign(this,i)}}class Hs extends v.PBRMaterial{constructor(t,e,i={}){super(t,e),this.isParticleMeshPhysicsMaterial=!0,Object.assign(this,i)}}function Ks(t,e){if(e&&e.length>0)return e;const i=t.length/3,s=new Uint32Array(i);for(let t=0;t<i;t++)s[t]=t;return s}const tn=new K(0,0,1),en=new H,sn=new H,nn=new K,rn=new K,on=1/60,an=new Set(["SizeOverLife","SizeBySpeed"]),hn=new Set(["ColorOverLife","ColorBySpeed"]),ln=new Set(["ApplyForce","Noise","TurbulenceField","GravityForce","RotationOverLife","Rotation3DOverLife","RotationBySpeed","SpeedOverLife","FrameOverLife","ForceOverLife","VelocityOverLife","InheritVelocity","OrbitOverLife","WidthOverLength","ChangeEmitDirection","EmitSubParticleSystem","LimitSpeedOverLife","ApplyCollision"]),cn=new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]),un=new Float32Array([0,0,1,0,1,1,0,1]),dn=new WeakMap,fn=new WeakMap;function mn(t){let e=dn.get(t);return void 0!==e&&e.length===t.length/3*2||(e=new Float32Array(t.length/3*2),dn.set(t,e)),e}const pn=new Uint32Array([0,1,2,0,2,3]);function yn(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 gn(t){const e=t?.sideAxis;return e?{sideAxis:[e.x,e.y,e.z]}:{}}function vn(t){if(Array.isArray(t))return{sideAxis:new K(Number(t[0])||0,Number(t[1])||0,Number(t[2])||0)};if(t&&"object"==typeof t){const e=t;return{sideAxis:new K(e.x??0,e.y??0,e.z??0)}}return{}}class xn{set time(t){this.emissionState.time=t}get time(){return this.emissionState.time}get isEmitEnded(){return this.emitEnded}hasPendingEmission(){if(this.looping)return!0;if(this.emitEnded)return!1;if(this.onlyUsedByOther)return!1;const t=this.emissionState;if(t.waitEmiting>0)return!0;if(t.burstIndex<this.emissionBursts.length)return!0;if(this.hasPendingBurstWaves(t))return!0;if(t.time>=this.duration)return!1;const e=t.time/this.duration;return this.emissionOverTime.genValue(this.memory,e)>0||this.emissionOverDistance.genValue(this.memory,e)>0}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=t,this.neededToUpdateRender=!0}get vTileCount(){return this.rendererSettings.vTileCount}set vTileCount(t){this.rendererSettings.vTileCount=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}set sortMode(t){this.rendererSettings.sortMode=xn.validSortMode(t),this.neededToUpdateRender=!0}get minParticleSize(){return this.rendererSettings.minParticleSize}set minParticleSize(t){this.rendererSettings.minParticleSize=Math.max(0,t),this.neededToUpdateRender=!0}get maxParticleSize(){return this.rendererSettings.maxParticleSize}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=xn.nonZeroPivot(t),this.neededToUpdateRender=!0}get lighting(){return this.rendererSettings.lighting??"fixed"}set lighting(t){this.rendererSettings.lighting=xn.validLighting(t),this.neededToUpdateRender=!0}get rim(){return this.rendererSettings.rim}set rim(t){this.rendererSettings.rim=xs(t),this.neededToUpdateRender=!0}get mapUV(){return this.rendererSettings.mapUV}set mapUV(t){this.rendererSettings.mapUV=Cs(t),this.neededToUpdateRender=!0}get gradientMap(){return this.rendererSettings.gradientMap}set gradientMap(t){this.rendererSettings.gradientMap=_s(t),this.neededToUpdateRender=!0}get erosion(){return this.rendererSettings.erosion}set erosion(t){this.rendererSettings.erosion=Ts(t),this.neededToUpdateRender=!0}get uvDistortion(){return this.rendererSettings.uvDistortion}set uvDistortion(t){this.rendererSettings.uvDistortion=As(t),this.neededToUpdateRender=!0}measureMotionScale(){if("hierarchy"!==this.scalingMode||!this.worldSpace)return this.hierarchyScale.set(1,1,1),1;const t=this.emitter.matrixWorld.elements,e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),i=Math.sqrt(t[4]*t[4]+t[5]*t[5]+t[6]*t[6]),s=Math.sqrt(t[8]*t[8]+t[9]*t[9]+t[10]*t[10]);return this.hierarchyScale.set(e,i,s),(e+i+s)/3}static validLighting(t){return"unlit"===t||"scene"===t?t:"fixed"}static validSortMode(t){return"distance"===t||"oldestInFront"===t||"youngestInFront"===t?t:"none"}static validCullingMode(t){return"pause"===t||"pauseAndCatchUp"===t?t:"always"}static nonZeroPivot(t){return!t||0===t.x&&0===t.y&&0===t.z?void 0:t.clone()}static nonZeroFlip(t){return t&&(t.x>0||t.y>0)?t.clone():void 0}get softNearFade(){return this.rendererSettings.softNearFade}set softNearFade(t){this.rendererSettings.softNearFade=t,this.neededToUpdateRender=!0}get softFarFade(){return this.rendererSettings.softFarFade}set softFarFade(t){this.rendererSettings.softFarFade=t,this.neededToUpdateRender=!0}get instancingGeometry(){return this.rendererSettings.instancingGeometry}set instancingGeometry(t){this.restart(),this.particles.length=0;const e=this.rendererSettings,i=t.length/3*2,s=e.instancingGeometry;e.instancingGeometry=t,e.instancingUVs?.length===i&&e.instancingUVs!==dn.get(s)||(e.instancingUVs=mn(t)),!e.instancingNormals||e.instancingNormals.length===t.length&&e.instancingNormals!==fn.get(s)||(e.instancingNormals=xn.createFallbackNormals(t)),e.instancingUVs2&&e.instancingUVs2.length!==i&&(e.instancingUVs2=void 0),this.neededToUpdateRender=!0}get instancingUVs(){return this.rendererSettings.instancingUVs??mn(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 renderMode(){return this.rendererSettings.renderMode}set renderMode(e){if(this.rendererSettings.renderMode!==e){let i=!1;switch(this.rendererSettings.renderMode===t.RenderMode.Trail&&(i=!0),this.rendererSettings.renderMode===t.RenderMode.Mesh&&(this.startRotation=new Bt(0)),e){case t.RenderMode.Trail:this.rendererEmitterSettings={startLength:new Bt(30),followLocalOrigin:!1},i=!0;break;case t.RenderMode.Mesh:this.rendererEmitterSettings={},this.startRotation=new Et(new K(0,1,0),new Bt(0));break;case t.RenderMode.StretchedBillBoard:this.rendererEmitterSettings={speedFactor:0,lengthFactor:2};break;case t.RenderMode.BillBoard:case t.RenderMode.VerticalBillBoard:case t.RenderMode.HorizontalBillBoard:case t.RenderMode.Beam:this.rendererEmitterSettings={}}this.rendererSettings.renderMode=e,i&&(this.restart(),this.particles.length=0),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 seed(){return this.seedValue}set seed(t){this.seedValue=t,this.rng=void 0===t?void 0:z(t)}constructor(e){if(this.store=new ze(64),this.emitterVelocity=new K,this.finishedEventFired=!1,this.startDelayTimeLeft=0,this.tempEmitterPos=new K,this.temp=new K,this.pathMatrix=new nt,this.normalMatrix=new pt,this.memory=[],this.listeners={},this.materialRef=null,this.qualityFactor=1,this.simulationAccumulator=0,this.destroyed=!1,this.fusionSteps=[],this.planChangesSize=!0,this.planChangesColor=!0,this.hierarchyScale=new K(1,1,1),this.playbackSpeed=1,this.emissionMultiplier=1,this.cullingMode="always",this.scalingMode="shape",this.motionScale=1,this.alignToDirection=!1,this.culled=!1,this.pendingCatchUp=0,this.boundsMin=new K,this.boundsMax=new K,this.boundsPadding=0,this.boundsValid=!1,this.stepsSinceBounds=0,this.boundsMaxSize=0,this.boundsMaxSpeedSq=0,this.boundsInWorld=!1,this.geometryRadius=1,this.firstTimeUpdate=!0,this.beamEndScratch=new K,this.sceneRef=e.scene,this.layerMaskProxy={mask:e.layerMask??268435455},Object.defineProperty(this.layerMaskProxy,"mask",{enumerable:!0,get:()=>this.rendererSettings.layerMask,set:t=>{this.rendererSettings.layerMask=t,this.neededToUpdateRender=!0}}),this.autoDestroy=e.autoDestroy??!1,this.duration=e.duration??1,this.startDelay=e.startDelay??new Bt(0),this.looping=e.looping??!0,this.prewarm=e.prewarm??!1,this.startLife=e.startLife??new Bt(5),this.startSpeed=e.startSpeed??new Bt(0),this.startRotation=e.startRotation??new Bt(0),this.startSize=e.startSize??new Bt(1),this.startColor=e.startColor??new Yt(new zt(1,1,1,1)),this.emissionOverTime=e.emissionOverTime??new Bt(10),this.emissionOverDistance=e.emissionOverDistance??new Bt(0),this.emissionBursts=e.emissionBursts??[],this.maxParticles=e.maxParticles,this.onlyUsedByOther=e.onlyUsedByOther??!1,this.emitterShape=e.shape??new Bi,this.behaviors=e.behaviors??[],this.worldSpace=e.worldSpace??!1,this.rendererEmitterSettings=e.rendererEmitterSettings??{},e.renderMode===t.RenderMode.StretchedBillBoard){const t=this.rendererEmitterSettings;void 0!==e.speedFactor&&(t.speedFactor=e.speedFactor),t.speedFactor=t.speedFactor??0,t.lengthFactor=t.lengthFactor??0}this.rendererSettings={instancingGeometry:e.instancingGeometry??cn,instancingIndices:e.instancingIndices??pn,instancingUVs:e.instancingUVs??(e.instancingGeometry?mn(e.instancingGeometry):un),instancingUVs2:e.instancingUVs2,instancingNormals:e.instancingNormals,renderMode:e.renderMode??t.RenderMode.BillBoard,renderOrder:e.renderOrder??0,uTileCount:e.uTileCount??1,vTileCount:e.vTileCount??1,blendTiles:e.blendTiles??!1,softParticles:e.softParticles??!1,softNearFade:e.softNearFade??0,softFarFade:e.softFarFade??0,materialBlendMode:e.blendMode??r.Constants.ALPHA_ADD,materialTransparent:e.transparent??!0,materialDepthTest:e.depthTest??!0,materialDepthWrite:e.depthWrite??!1,materialAlphaTest:e.alphaTest??0,texture:e.texture??null,reflectionTexture:null,reflectionLevel:1,reflectionFaces:null,reflectionAtlas:null,layerMask:e.layerMask??268435455,pivot:xn.nonZeroPivot(e.pivot),sortMode:xn.validSortMode(e.sortMode),minParticleSize:Math.max(0,e.minParticleSize??0),maxParticleSize:e.maxParticleSize??1/0,renderingGroupId:e.renderingGroupId??0,applyFog:e.applyFog??!0,lighting:xn.validLighting(e.lighting),rim:xs(e.rim),mapUV:Cs(e.mapUV),gradientMap:_s(e.gradientMap),erosion:Ts(e.erosion),uvDistortion:As(e.uvDistortion)},this.flip=xn.nonZeroFlip(e.flip),this.playbackSpeed=e.playbackSpeed??1,this.cullingMode=e.cullingMode??"always",this.scalingMode="hierarchy"===e.scalingMode?"hierarchy":"shape",this.alignToDirection=!0===e.alignToDirection,this.seed=e.seed,this.rendererSettings.renderMode!==t.RenderMode.Mesh||this.rendererSettings.instancingNormals||(this.rendererSettings.instancingNormals=xn.createFallbackNormals(this.rendererSettings.instancingGeometry)),this.materialRef=e.material??null,this.applyMaterialSettings(this.materialRef,{blendMode:e.blendMode,transparent:e.transparent,depthTest:e.depthTest,depthWrite:e.depthWrite,alphaTest:e.alphaTest,texture:e.texture,layerMask:e.layerMask}),this.neededToUpdateRender=!0,this.particles=[],this.startTileIndex=e.startTileIndex||new Bt(0),this.emitter=new qs(this,e.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.emissionBursts.forEach(t=>t.count.startGen(this.memory)),this.emissionOverDistance.startGen(this.memory),this.startDelay.startGen(this.memory),this.startDelayTimeLeft=this.startDelay.genValue(this.memory,0),this.emitEnded=!1,this.markForDestroy=!1,this.prewarmed=!1}applyMaterialSettings(t,e={}){if(!this.rendererSettings)return;const i=void 0!==e.texture?e.texture:t?.albedoTexture??t?.diffuseTexture??t?.emissiveTexture??t?.opacityTexture??t?.baseTexture??this.rendererSettings.texture??null,s=t?.reflectionTexture??t?.environmentTexture??this.rendererSettings.reflectionTexture??null,n="number"==typeof s?.level?s.level:1,r=e.blendMode??("number"==typeof t?.alphaMode?t.alphaMode:this.rendererSettings.materialBlendMode),o=e.transparent??("function"==typeof t?.needAlphaBlending?t.needAlphaBlending():"number"==typeof t?.alpha?t.alpha<1:this.rendererSettings.materialTransparent),a=e.depthTest??("boolean"==typeof t?.disableDepthTest?!t.disableDepthTest:this.rendererSettings.materialDepthTest),h=e.depthWrite??("boolean"==typeof t?.disableDepthWrite?!t.disableDepthWrite:"boolean"==typeof t?.forceDepthWrite?t.forceDepthWrite:this.rendererSettings.materialDepthWrite),l=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:this.rendererSettings.materialAlphaTest})();this.rendererSettings.texture=i,this.rendererSettings.reflectionTexture=s,this.rendererSettings.reflectionLevel="number"==typeof t?.reflectionLevel?t.reflectionLevel:n;let c=t?.reflectionAtlas??e.reflectionAtlas??this.rendererSettings.reflectionAtlas??null;!c&&s?.isCube&&(c=Ws(s),!c&&this.sceneRef&&(Xs(s,this.sceneRef,e=>{this.rendererSettings.reflectionAtlas!==e&&(this.rendererSettings.reflectionAtlas=e,t&&null==t.reflectionAtlas&&(t.reflectionAtlas=e),this.neededToUpdateRender=!0)}),c=Ws(s))),this.rendererSettings.reflectionAtlas=c,this.rendererSettings.reflectionFaces=6===t?.reflectionFaces?.length?t.reflectionFaces:null,this.rendererSettings.materialBlendMode=r,this.rendererSettings.materialTransparent=o,this.rendererSettings.materialDepthTest=a,this.rendererSettings.materialDepthWrite=h,this.rendererSettings.materialAlphaTest=l,void 0!==e.layerMask&&(this.rendererSettings.layerMask=e.layerMask),this.neededToUpdateRender=!0}pause(){this.paused=!0}play(){this.paused=!1}stop(){this.restart(),this.pause()}setQualityFactor(t){this.qualityFactor=Math.max(.1,Math.min(1,t))}emissionFactor(){const t=this.emissionMultiplier;return t>=0?this.qualityFactor*t:this.qualityFactor}rebindParticles(){const t=this.particles;for(let e=0;e<t.length;e++)t[e].rebind()}growParticlePool(t){const e=this.particles.length;this.store.ensureCapacity(e+1)&&this.rebindParticles(),this.particles.push(t?new ii(this.store,e):new ti(this.store,e))}spawn(e,i,s){const n=nn,r=rn;s.decompose(n,en,r);const o=this.behaviors,a=o.length,h=this.rendererSettings.renderMode,l=h===t.RenderMode.Trail,c=!l,u=h===t.RenderMode.Mesh,d="rotation"===this.startRotation.type,f="vec3function"===this.startSize.type,m=i.time/this.duration,p=l?this.rendererEmitterSettings:void 0,y=Boolean(p?.followLocalOrigin);void 0!==this.maxParticles&&(e=Math.min(e,Math.max(0,this.maxParticles-this.particleNum)));for(let t=0;t<e;t++){i.burstParticleIndex=t,this.particleNum++,this.particles.length<this.particleNum&&this.growParticlePool(l);const e=this.particles[this.particleNum-1];if(e.reset(),e.speedModifier=1,this.finishedEventFired=!1,this.startColor.startGen(e.memory),this.startColor.genColor(e.memory,e.startColor,this.emissionState.time),e.color.copy(e.startColor),this.startSpeed.startGen(e.memory),e.startSpeed=this.startSpeed.genValue(e.memory,m),this.startLife.startGen(e.memory),e.life=this.startLife.genValue(e.memory,m),e.age=0,this.startSize.startGen(e.memory),f)this.startSize.genValue(e.memory,e.startSize,m);else{const t=this.startSize.genValue(e.memory,m);e.startSize.set(t,t,t)}if(this.startTileIndex.startGen(e.memory),e.uvTile=this.startTileIndex.genValue(e.memory),e.size.copy(e.startSize),c){const t=e;if(this.startRotation.startGen(e.memory),u)t.rotation instanceof H||(t.rotation=sn),t.angularVelocity instanceof H&&t.angularVelocity.set(0,0,0,1),d?this.startRotation.genValue(e.memory,t.rotation,1,m):t.rotation.setFromAxisAngle(tn,this.startRotation.genValue(t.memory,m));else{t.rotation=d?0:this.startRotation.genValue(t.memory,m),t.angularVelocity=0;const e=this.flip;t.flip=void 0===e?0:(b()<e.x?1:0)|(b()<e.y?2:0)}}else if(p){const t=e;p.startLength.startGen(t.memory),t.length=p.startLength.genValue(t.memory,m),t.ensureHistoryCapacity(Math.max(1,Math.ceil(t.length))),t.resetHistory()}this.emitterShape.initialize(e,i),this.alignToDirection&&c&&this.alignParticleToDirection(e,u);const n=i.particle,h=i.inherit;if(void 0!==n&&void 0!==h&&0!==h&&this.inheritFromParent(e,n,h,c),l&&y){const t=e;t.localPosition||(t.localPosition=new K),t.localPosition.copy(t.position)}this.worldSpace?(e.position.applyMatrix4(s),e.startSize.multiply(r).abs(),e.size.copy(e.startSize),"hierarchy"===this.scalingMode?e.velocity.multiply(this.hierarchyScale).applyQuaternion(en):e.velocity.multiply(r).applyMatrix3(this.normalMatrix),e.rotation&&e.rotation instanceof H&&e.rotation.multiplyQuaternions(en,e.rotation)):this.onlyUsedByOther&&(e.parentMatrix=s);for(let t=0;t<a;t++)o[t].initialize(e,this);this.store.recordMemory(e.storeIndex,e.memory)}}alignParticleToDirection(t,e){const i=t.velocity,s=i.x*i.x+i.y*i.y+i.z*i.z;if(0!==s)if(e){const e=t.rotation;nn.copy(i).divideScalar(Math.sqrt(s)),en.setFromUnitVectors(tn,nn),e.multiplyQuaternions(en,e)}else 0===i.x&&0===i.y||(t.rotation=t.rotation+Math.atan2(-i.x,i.y))}inheritFromParent(t,e,i,s){if(i&ye.color&&(t.startColor.multiply(e.color),t.color.copy(t.startColor)),i&ye.size&&(t.startSize.multiply(e.size),t.size.copy(t.startSize)),i&ye.rotation&&s){const i=t,s=e.rotation;"number"==typeof i.rotation?"number"==typeof s&&(i.rotation+=s):s instanceof H&&i.rotation.multiplyQuaternions(s,i.rotation)}i&ye.lifetime&&e.life>0&&(t.life*=Math.max(0,1-e.age/e.life))}endEmit(){this.emitEnded=!0,this.autoDestroy&&(this.markForDestroy=!0),this.fire({type:"emitEnd",particleSystem:this})}dispose(){this.destroyed||(this.destroyed=!0,this._renderer&&this._renderer.deleteSystem(this),this.emitter.dispose(),this.fire({type:"destroy",particleSystem:this}))}restart(){this.memory.length=0,this.paused=!1,this.particleNum=0,this.boundsValid=!1,this.pendingCatchUp=0,void 0!==this.seedValue&&(this.rng=z(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.behaviors.forEach(t=>t.reset()),this.emitEnded=!1,this.markForDestroy=!1,this.finishedEventFired=!1,this.prewarmed=!1,this.emissionBursts.forEach(t=>t.count.startGen(this.memory)),this.emissionOverDistance.startGen(this.memory),this.startDelay.startGen(this.memory),this.startDelayTimeLeft=this.startDelay.genValue(this.memory,0),this.previousEmitterPos=void 0,this.emitterVelocity.set(0,0,0),this.simulationAccumulator=0,this.destroyed=!1}update(t,e=1/0,i){if(this.paused)return;if(t*=this.playbackSpeed,this.culled)return void("pauseAndCatchUp"===this.cullingMode&&(this.pendingCatchUp=Math.min(2,this.pendingCatchUp+t)));if(this.pendingCatchUp>0&&this.catchUp(i??performance.now()+xn.catchUpBudgetMs),this.firstTimeUpdate&&(this.firstTimeUpdate=!1,this.emitter.computeWorldMatrix(!0)),!this.looping&&this.finishedEventFired&&0===this.particleNum){t>.1&&(t=.1),this.simulationAccumulator+=t;const e=Math.min(8,Math.max(0,Math.round(this.simulationAccumulator/on-1e-9)));return void(this.simulationAccumulator-=e*on)}if(this.looping&&this.prewarm&&!this.prewarmed){this.prewarmed=!0;for(let t=0;t<60*this.duration;t++)this.update(1/60)}t>.1&&(t=.1),this.neededToUpdateRender&&(this._renderer&&this._renderer.updateSystem(this),this.neededToUpdateRender=!1);const s=this.emitter.matrixWorld.elements;if(this.tempEmitterPos.set(s[12],s[13],s[14]),void 0!==this.previousEmitterPos&&t>0&&this.emitterVelocity.copy(this.tempEmitterPos).sub(this.previousEmitterPos).divideScalar(t),(this.previousEmitterPos??(this.previousEmitterPos=new K)).copy(this.tempEmitterPos),this.startDelayTimeLeft>0&&(!this.prewarm||!this.looping)){if(this.startDelayTimeLeft-=t,this.startDelayTimeLeft>=0)return;t=Math.min(-this.startDelayTimeLeft,.1),this.startDelayTimeLeft=0}this.simulationAccumulator+=t;const n=Math.min(8,Math.max(0,Math.round(this.simulationAccumulator/on-1e-9)));for(let t=0;t<n&&(this.simulateStep(on),!(e!==1/0&&t+1<n&&performance.now()>=e));t++);this.simulationAccumulator-=n*on}catchUp(t){let e=Math.floor(this.pendingCatchUp/on);for(this.pendingCatchUp=0;e-- >0&&(this.simulateStep(on),!(e>0&&performance.now()>=t)););}storeBounds(e,i,s,n,r,o,a,h,l,c){if(0===e)return void(this.boundsValid=!1);this.stepsSinceBounds=i?0:this.stepsSinceBounds+1,this.boundsMaxSize=l,this.boundsMaxSpeedSq=c;const u=Math.sqrt(c),d=this.rendererSettings.renderMode;let f=u*on*(this.stepsSinceBounds+1);if(d===t.RenderMode.Mesh)f+=l*this.meshGeometryRadius();else if(d===t.RenderMode.StretchedBillBoard){const t=this.rendererEmitterSettings;f+=l*(1+(t.lengthFactor??0)+u*(t.speedFactor??0))}else{const t=this.rendererSettings.pivot;f+=l*(.75+(void 0===t?0:Math.abs(t.x)+Math.abs(t.y)+Math.abs(t.z)))}this.boundsMin.set(s,n,r),this.boundsMax.set(o,a,h),this.boundsPadding=f,this.boundsInWorld=this.worldSpace,this.boundsValid=!0}meshGeometryRadius(){const t=this.rendererSettings.instancingGeometry;if(t!==this.geometryRadiusFor){let e=0;for(let i=0;i+2<t.length;i+=3){const s=t[i]*t[i]+t[i+1]*t[i+1]+t[i+2]*t[i+2];s>e&&(e=s)}this.geometryRadius=Math.sqrt(e),this.geometryRadiusFor=t}return this.geometryRadius}getWorldBounds(e,i){if(!this.measureWorldBounds(e,i))return!1;if(this.rendererSettings.renderMode===t.RenderMode.Beam){const t=this.beamEndScratch;if(!this.getBeamEnd(t))return!0;const s=this.boundsInWorld?this.boundsPadding:this.boundsPadding*this.emitterMaxScale();e.set(Math.min(e.x,t.x-s),Math.min(e.y,t.y-s),Math.min(e.z,t.z-s)),i.set(Math.max(i.x,t.x+s),Math.max(i.y,t.y+s),Math.max(i.z,t.z+s))}return!0}getBeamEnd(t){const e=this.beamEnd;if(void 0===e)return!1;const i=e;if("function"==typeof i.getAbsolutePosition){const e=i.getAbsolutePosition();t.set(e.x,e.y,e.z)}else{const i=e;t.set(i.x,i.y,i.z)}return!0}emitterMaxScale(){const t=this.emitter.matrixWorld.elements;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]))}measureWorldBounds(t,e){if(!this.boundsValid)return!1;const i=this.boundsMin,s=this.boundsMax;if(this.boundsInWorld){const n=this.boundsPadding;return t.set(i.x-n,i.y-n,i.z-n),e.set(s.x+n,s.y+n,s.z+n),!0}const n=this.emitter.matrixWorld.elements,r=Math.sqrt(Math.max(n[0]*n[0]+n[1]*n[1]+n[2]*n[2],n[4]*n[4]+n[5]*n[5]+n[6]*n[6],n[8]*n[8]+n[9]*n[9]+n[10]*n[10])),o=this.boundsPadding*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?s.x:i.x,r=2&t?s.y:i.y,o=4&t?s.z:i.z,f=1/(n[3]*e+n[7]*r+n[11]*o+n[15]),m=(n[0]*e+n[4]*r+n[8]*o+n[12])*f,p=(n[1]*e+n[5]*r+n[9]*o+n[13])*f,y=(n[2]*e+n[6]*r+n[10]*o+n[14])*f;m<a&&(a=m),m>c&&(c=m),p<h&&(h=p),p>u&&(u=p),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}setWorldBounds(t,e,i,s,n,r,o){this.boundsMin.set(t,e,i),this.boundsMax.set(s,n,r),this.boundsPadding=o,this.boundsInWorld=!0,this.boundsValid=!0}get simulationStep(){return on}get simulationResidual(){return this.paused?0:this.simulationAccumulator>on?on:this.simulationAccumulator<-on?-on:this.simulationAccumulator}behaviorSteps(){const t=this.behaviors,e=this.fusionPlan;if(void 0!==e&&e.length===t.length){let i=!0;for(let s=0;s<t.length;s++)if(e[s]!==t[s]){i=!1;break}if(i)return this.fusionSteps}this.fusionPlan=t.slice(),this.fusionSteps=vi(t);let i=!1,s=!1;for(let e=0;e<t.length;e++){const n=t[e].type;an.has(n)?i=!0:hn.has(n)?s=!0:ln.has(n)||(i=!0,s=!0)}return this.planChangesSize=i,this.planChangesColor=s,this.fusionSteps}simulateStep(t){const e=this.rng;if(void 0===e)return void this.stepOnce(t);const i=M(e);try{this.stepOnce(t)}finally{M(i)}}stepOnce(e){this.motionScale=this.measureMotionScale(),this.onlyUsedByOther||this.emit(e,this.emissionState,this.emitter.matrixWorld);const i=this.particles,s=this.behaviors;s.length;const n=this.particleNum,r=this.rendererSettings.renderMode===t.RenderMode.Trail,o=this.rendererSettings.renderMode===t.RenderMode.StretchedBillBoard,a=this.store,h=3*n,l=this.behaviorSteps(),c=this.planChangesSize,u=this.planChangesColor;a.useSizeSnapshot(c),a.useColorSnapshot(u),a.previousPosition.set(a.position.subarray(0,h)),c&&a.previousSize.set(a.size.subarray(0,h)),o&&(a.keepPreviousVelocity()&&this.rebindParticles(),a.previousVelocity.set(a.velocity.subarray(0,h))),u&&a.previousColor.set(a.color.subarray(0,4*n)),this.emitterShape.update(this,e);for(let t=0;t<l.length;t++){const r=l[t],o=r.behaviors;for(let t=0;t<o.length;t++)o[t].frameUpdate(e);if(0===n)continue;if(void 0!==r.run){r.run(s,i,n,e,this.store);continue}const a=o[0];if(void 0===a.updateAll)for(let t=0;t<n;t++){const s=i[t];s.age<s.life&&a.update(s,e)}else a.updateAll(i,n,e)}const d=this.hasListeners("particleDied"),f=this.store,m=f.scalars,p=ze.SCALAR_STRIDE;let y=this.particleNum;if(!r){const t=f.position,s=f.velocity,n=f.previousSize,r=f.size,o=f.previousColor,a=f.color,h=c,l=u,g=this.stepsSinceBounds>=4||!this.boundsValid,v=this.boundsMin,x=this.boundsMax;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:this.boundsMaxSize,T=g?0:this.boundsMaxSpeedSq;for(let c=0;c<y;c++){const u=c*p;let v=m[u+ze.AGE];const x=3*c,P=g||0===v;if(0===v&&(h&&(n[x]=r[x],n[x+1]=r[x+1],n[x+2]=r[x+2]),l)){const t=4*c;o[t]=a[t],o[t+1]=a[t+1],o[t+2]=a[t+2],o[t+3]=a[t+3]}const O=e*m[u+ze.SPEED_MODIFIER],A=s[x],B=s[x+1],C=s[x+2],F=t[x]+A*O,$=t[x+1]+B*O,I=t[x+2]+C*O;if(t[x]=F,t[x+1]=$,t[x+2]=I,P&&(S=Math.min(S,F),M=Math.max(M,F),b=Math.min(b,$),z=Math.max(z,$),w=Math.min(w,I),_=Math.max(_,I),V=Math.max(V,Math.max(r[x],Math.max(r[x+1],r[x+2])))),T=Math.max(T,A*A+B*B+C*C),v+=e,m[u+ze.AGE]=v,v>=m[u+ze.LIFE]){const t=y-1,e=i[c],s=i[t];i[c]=s,i[t]=e,c!==t&&(f.swapRows(c,t),s.setStoreIndex(c),e.setStoreIndex(t)),y--,c--,d&&this.fire({type:"particleDied",particleSystem:this,particle:e})}}return this.particleNum=y,this.storeBounds(y,g,S,b,w,M,z,_,V,T),void this.notifyFinished()}if(n>0){const t=a.previousSize,e=a.size,i=a.previousColor,s=a.color;for(let r=0,o=0,a=0,h=0;r<n;r++,o+=3,a+=4,h+=p)0===m[h+ze.AGE]&&(c&&(t[o]=e[o],t[o+1]=e[o+1],t[o+2]=e[o+2]),u&&(i[a]=s[a],i[a+1]=s[a+1],i[a+2]=s[a+2],i[a+3]=s[a+3]))}if(this.rendererEmitterSettings.followLocalOrigin){const t=this.emitter.matrixWorld;for(let s=0;s<n;s++){const n=i[s];n.localPosition?(n.position.copy(n.localPosition),n.position.applyMatrix4(n.parentMatrix??t)):n.position.addScaledVector(n.velocity,e*n.speedModifier),n.age+=e}}else{const t=f.position,i=f.velocity;for(let s=0,r=0,o=0;s<n;s++,r+=3,o+=p){const s=e*m[o+ze.SPEED_MODIFIER];t[r]+=i[r]*s,t[r+1]+=i[r+1]*s,t[r+2]+=i[r+2]*s,m[o+ze.AGE]+=e}}{const t=this.rendererEmitterSettings,e=t.dieWithParticle,s=t.recordWorldSpace&&!this.worldSpace,r=this.emitter.matrixWorld,o=t.sideAxis,a=this.worldSpace||Boolean(t.recordWorldSpace);for(let t=0;t<n;t++){const n=i[t];if(e&&n.age>=n.life)n.resetHistory();else{if(n.update(),s&&n.age<=n.life){const t=(n.historyHead+n.historyCapacity-1)%n.historyCapacity*3,e=n.historyPositions;nn.set(e[t],e[t+1],e[t+2]),nn.applyMatrix4(n.parentMatrix??r),e[t]=nn.x,e[t+1]=nn.y,e[t+2]=nn.z}if(o&&n.age<=n.life){n.ensureSideHistory();const t=(n.historyHead+n.historyCapacity-1)%n.historyCapacity*3,e=n.historySides;let i=o.x,s=o.y,h=o.z;if(a){const t=(n.parentMatrix??r).elements,e=t[0]*i+t[4]*s+t[8]*h,o=t[1]*i+t[5]*s+t[9]*h;h=t[2]*i+t[6]*s+t[10]*h,i=e,s=o}e[t]=i,e[t+1]=s,e[t+2]=h}}}}for(let t=0;t<y;t++){const e=i[t],s=t*p;if(m[s+ze.AGE]>=m[s+ze.LIFE]&&0===e.historyCount){const s=y-1,n=i[s];i[t]=n,i[s]=e,t!==s&&(f.swapRows(t,s),n.setStoreIndex(t),e.setStoreIndex(s)),y--,t--,d&&this.fire({type:"particleDied",particleSystem:this,particle:e})}}this.particleNum=y,this.notifyFinished()}notifyFinished(){this.isFinished()&&(this.finishedEventFired||(this.finishedEventFired=!0,this.fire({type:"finished",particleSystem:this})),this.autoDestroy&&(this.markForDestroy=!0,this.dispose()))}static burstWaveCount(t){return t.cycle>=1?Math.floor(t.cycle):1}static burstInterval(t){return t.interval>0?t.interval:0}emitBursts(t,e){const i=this.emissionBursts,s=i.length,n=t.time,r=t.burstWaves??(t.burstWaves=[]);for(;t.burstIndex<s&&i[t.burstIndex].time<=n;)r[t.burstIndex]=0,t.burstIndex++;const o=t.burstIndex;for(let s=0;s<o;s++){const o=i[s],a=xn.burstWaveCount(o);let h=r[s]??0;if(h>=a)continue;const l=xn.burstInterval(o);for(;h<a;){const i=o.time+h*l;if(h>0&&i>this.duration){h=a;break}if(i>n)break;t.burstWaveIndex=h,this.fireBurstWave(o,t,e),h++}r[s]=h}}fireBurstWave(t,e,i){if(b()>=t.probability)return;const s=t.count.genValue(this.memory,this.time),n=this.emissionFactor(),r=Math.abs(n-1)<.001?s:Math.floor(s*n+b());e.isBursting=!0,e.burstParticleCount=r,this.spawn(r,e,i),e.isBursting=!1}hasPendingBurstWaves(t){const e=t.burstWaves;if(void 0===e)return!1;const i=this.emissionBursts;for(let s=0;s<t.burstIndex&&s<i.length;s++){const t=i[s],n=e[s]??0;if(n<xn.burstWaveCount(t)&&(0===n||t.time+n*xn.burstInterval(t)<=this.duration))return!0}return!1}spawnAlongPath(t,e,i,s,n,r,o){const a=this.pathMatrix.copy(i),h=i.elements,l=a.elements,c=h[12],u=h[13],d=h[14];for(let i=1;i<=t;i++){const t=i*r-n,h=t<=0?0:t>=o?1:t/o;l[12]=s.x+(c-s.x)*h,l[13]=s.y+(u-s.y)*h,l[14]=s.z+(d-s.z)*h,this.spawn(1,e,a)}}emit(t,e,i){const s=this.emitEnded&&e===this.emissionState;if(e.time>this.duration)if(this.looping){e.time-=this.duration,e.burstIndex=0,void 0!==e.burstWaves&&(e.burstWaves.length=0);for(let t=0;t<this.behaviors.length;t++)this.behaviors[t].reset()}else this.emitEnded||this.onlyUsedByOther||this.endEmit();this.worldSpace&&this.normalMatrix.getNormalMatrix(i);const n=this.emissionBursts.length,r=this.emissionFactor();n>0&&!s&&this.emitBursts(e,i);let o=0,a=0,h=0,l=0;const c=e.previousWorldPos;if(!this.emitEnded){const s=e.time/this.duration;if(e.waitEmiting+=t*this.emissionOverTime.genValue(this.memory,s)*r,void 0!==c){this.temp.set(i.elements[12],i.elements[13],i.elements[14]),l=c.distanceTo(this.temp),h=e.travelDistance,e.travelDistance+=l;const t=this.emissionOverDistance.genValue(this.memory,s)*r;if(e.travelDistance*t>0){const i=Math.floor(e.travelDistance*t);e.travelDistance-=i/t,this.worldSpace&&l>0?(o=i,a=1/t):e.waitEmiting+=i}}}const u=Math.floor(e.waitEmiting);u>0&&(this.spawn(u,e,i),e.waitEmiting-=u),o>0&&this.spawnAlongPath(o,e,i,c,h,a,l),void 0===e.previousWorldPos&&(e.previousWorldPos=new K),e.previousWorldPos.set(i.elements[12],i.elements[13],i.elements[14]),e.time+=t}toJSON(t,e={}){const i=void 0===t||"string"==typeof t?{geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}}:t,s=this.ensureGeometryMeta(i),n=this.ensureMaterialMeta(i),r=this.toRendererSettingsJSON();return{version:"3.0",autoDestroy:this.autoDestroy,looping:this.looping,prewarm:this.prewarm,duration:this.duration,startDelay:this.startDelay.toJSON(),shape:this.emitterShape.toJSON(),startLife:this.startLife.toJSON(),startSpeed:this.startSpeed.toJSON(),startRotation:this.startRotation.toJSON(),startSize:this.startSize.toJSON(),startColor:this.startColor.toJSON(),emissionOverTime:this.emissionOverTime.toJSON(),emissionOverDistance:this.emissionOverDistance.toJSON(),emissionBursts:this.emissionBursts.map(t=>({time:t.time,count:t.count.toJSON(),probability:t.probability,interval:t.interval,cycle:t.cycle})),...void 0!==this.maxParticles?{maxParticles:this.maxParticles}:{},onlyUsedByOther:this.onlyUsedByOther,instancingGeometry:s,renderMode:this.renderMode,renderOrder:this.renderOrder,...0!==this.renderingGroupId?{renderingGroupId:this.renderingGroupId}:{},...this.applyFog?{}:{applyFog:!1},...1!==this.playbackSpeed?{playbackSpeed:this.playbackSpeed}:{},..."always"!==this.cullingMode?{cullingMode:this.cullingMode}:{},..."shape"!==this.scalingMode?{scalingMode:this.scalingMode}:{},...void 0!==this.seedValue?{seed:this.seedValue}:{},..."none"!==this.sortMode?{sortMode:this.sortMode}:{},...this.alignToDirection?{alignToDirection:!0}:{},...this.minParticleSize>0?{minParticleSize:this.minParticleSize}:{},...this.maxParticleSize!==1/0?{maxParticleSize:this.maxParticleSize}:{},rendererEmitterSettings:r,material:n,layers:this.rendererSettings.layerMask,startTileIndex:this.startTileIndex.toJSON(),uTileCount:this.rendererSettings.uTileCount,vTileCount:this.rendererSettings.vTileCount,blendTiles:this.rendererSettings.blendTiles,softParticles:this.rendererSettings.softParticles,softFarFade:this.rendererSettings.softFarFade,softNearFade:this.rendererSettings.softNearFade,blending:this.rendererSettings.materialBlendMode,transparent:this.rendererSettings.materialTransparent,depthTest:this.rendererSettings.materialDepthTest,depthWrite:this.rendererSettings.materialDepthWrite,alphaTest:this.rendererSettings.materialAlphaTest,behaviors:this.behaviors.map(t=>t.toJSON()),worldSpace:this.worldSpace,...this.pivot?{pivot:[this.pivot.x,this.pivot.y,this.pivot.z]}:{},...this.flip?{flip:[this.flip.x,this.flip.y]}:{}}}static fromJSON(e,i,s={},n){const o=$i(e.shape,i);let a;if(e.renderMode===t.RenderMode.Trail){const t=e.rendererEmitterSettings;a={startLength:void 0!==t?.startLength?Ut(t.startLength):new Bt(30),followLocalOrigin:t?.followLocalOrigin??!1,...yn(t),...vn(t?.sideAxis)}}else e.renderMode===t.RenderMode.StretchedBillBoard?(a={...e.rendererEmitterSettings??{}},void 0!==e.speedFactor&&(a.speedFactor=e.speedFactor)):a={};const h=e.material?i.materials?.[e.material]:void 0,l=h?.texture??e.texture,c="string"==typeof l?i.textures?.[l]??null:l??null,u=t=>"string"==typeof t?i.textures?.[t]??null:t??null,d=h?.erosion,f=h?.gradientMap,m=h?.uvDistortion,p="string"==typeof e.instancingGeometry?i.geometries?.[e.instancingGeometry]:e.instancingGeometry,y=xn.resolveGeometryData(p),g=new xn({scene:n,autoDestroy:e.autoDestroy,looping:e.looping,prewarm:e.prewarm,duration:e.duration,startDelay:e.startDelay?Ut(e.startDelay):void 0,shape:o,startLife:Ut(e.startLife),startSpeed:Ut(e.startSpeed),startRotation:ie(e.startRotation),startSize:ie(e.startSize),startColor:Xt(e.startColor),emissionOverTime:Ut(e.emissionOverTime),emissionOverDistance:Ut(e.emissionOverDistance),emissionBursts:e.emissionBursts?.map(t=>({time:t.time,count:"number"==typeof t.count?new Bt(t.count):Ut(t.count),probability:t.probability??1,interval:t.interval??.1,cycle:t.cycle??t.cycleCount??1})),maxParticles:"number"==typeof e.maxParticles?e.maxParticles:void 0,onlyUsedByOther:e.onlyUsedByOther,instancingGeometry:y.positions,instancingIndices:y.indices,instancingUVs:y.uvs,instancingUVs2:y.uvs2,instancingNormals:y.normals,renderMode:e.renderMode,rendererEmitterSettings:a,renderOrder:e.renderOrder,renderingGroupId:"number"==typeof e.renderingGroupId?e.renderingGroupId:void 0,applyFog:!1!==e.applyFog,playbackSpeed:"number"==typeof e.playbackSpeed?e.playbackSpeed:void 0,cullingMode:xn.validCullingMode(e.cullingMode),scalingMode:"hierarchy"===e.scalingMode?"hierarchy":"shape",seed:"number"==typeof e.seed?e.seed:void 0,sortMode:xn.validSortMode(e.sortMode),alignToDirection:!0===e.alignToDirection,minParticleSize:"number"==typeof e.minParticleSize?e.minParticleSize:void 0,maxParticleSize:"number"==typeof e.maxParticleSize?e.maxParticleSize:void 0,texture:c,material:h?.sourceMaterial??h,blendMode:h?.alphaMode??e.blending??r.Constants.ALPHA_ADD,transparent:h?.transparent??e.transparent??!0,depthTest:h?.depthTest??e.depthTest??!0,depthWrite:h?.depthWrite??e.depthWrite??!1,alphaTest:h?.alphaTest??e.alphaTest??0,startTileIndex:"number"==typeof e.startTileIndex?new Bt(e.startTileIndex):Ut(e.startTileIndex),uTileCount:e.uTileCount,vTileCount:e.vTileCount,blendTiles:e.blendTiles,softParticles:e.softParticles,softFarFade:e.softFarFade,softNearFade:e.softNearFade,behaviors:[],worldSpace:e.worldSpace,layerMask:e.layers,pivot:e.pivot?new K(e.pivot[0]??0,e.pivot[1]??0,e.pivot[2]??0):void 0,flip:e.flip?new St(e.flip[0]??0,e.flip[1]??0):void 0,lighting:h?.lighting,rim:h?.rim,mapUV:h?.mapUV,gradientMap:f&&"object"==typeof f?{...f,ramp:u(f.ramp)}:void 0,erosion:d&&"object"==typeof d?{...d,mask:u(d.mask)}:void 0,uvDistortion:m&&"object"==typeof m?{...m,map:u(m.map)}:void 0});return g.behaviors=(e.behaviors??[]).map(t=>{const e=ri(t,g);return e&&"EmitSubParticleSystem"===e.type&&(s[t.subParticleSystem]=e),e}).filter(t=>null!==t),g}static nextSerializationId(t){return xn.serializationCounter+=1,`${t}_${xn.serializationCounter}`}static createFallbackNormals(t){let e=fn.get(t);if(!e){e=new Float32Array(t.length);for(let t=2;t<e.length;t+=3)e[t]=1;fn.set(t,e)}return e}toRendererSettingsJSON(){return this.renderMode===t.RenderMode.Trail?{startLength:this.rendererEmitterSettings.startLength.toJSON(),followLocalOrigin:this.rendererEmitterSettings.followLocalOrigin,...yn(this.rendererEmitterSettings),...gn(this.rendererEmitterSettings)}:this.renderMode===t.RenderMode.StretchedBillBoard?{speedFactor:this.rendererEmitterSettings.speedFactor,lengthFactor:this.rendererEmitterSettings.lengthFactor}:{}}ensureGeometryMeta(t){const e=xn.nextSerializationId("quarks_geometry");return t.geometries[e]={uuid:e,type:"QuarksGeometry",positions:Array.from(this.rendererSettings.instancingGeometry),indices:Array.from(this.rendererSettings.instancingIndices),uvs:this.rendererSettings.instancingUVs?Array.from(this.rendererSettings.instancingUVs):void 0,...this.rendererSettings.instancingUVs2?{uvs2:Array.from(this.rendererSettings.instancingUVs2)}:{},normals:this.rendererSettings.instancingNormals?Array.from(this.rendererSettings.instancingNormals):void 0},e}ensureMaterialMeta(t){const e=this.rendererSettings.texture;let i;e&&(i=xn.nextSerializationId("quarks_texture"),t.textures[i]=e);const s=this.rendererSettings.reflectionAtlas;let n;s instanceof g.Texture&&(n=xn.nextSerializationId("quarks_texture"),t.textures[n]=s);const r=e=>{if(!(e instanceof g.Texture))return;const i=xn.nextSerializationId("quarks_texture");return t.textures[i]=e,i},o=this.erosion,a=this.uvDistortion,h=this.gradientMap,l=(t,e)=>void 0!==e?{[t]:e}:{},c=xn.nextSerializationId("quarks_material");return t.materials[c]={uuid:c,type:"QuarksMaterial",transparent:this.rendererSettings.materialTransparent,alphaMode:this.rendererSettings.materialBlendMode,depthTest:this.rendererSettings.materialDepthTest,depthWrite:this.rendererSettings.materialDepthWrite,alphaTest:this.rendererSettings.materialAlphaTest,texture:i,reflectionAtlas:n,reflectionLevel:this.rendererSettings.reflectionLevel,..."fixed"!==this.lighting?{lighting:this.lighting}:{},...this.rim?{rim:{...this.rim,color:[...this.rim.color]}}:{},...l("mapUV",this.mapUV?Ms(this.mapUV):void 0),...h?{gradientMap:{ramp:r(h.ramp),..."r"!==h.channel?{channel:h.channel}:{}}}:{},...o?{erosion:{mask:r(o.mask),...l("maskUV",Ms(o.maskUV)),softness:o.softness,edgeWidth:o.edgeWidth,edgeColor:[...o.edgeColor]}}:{},...a?{uvDistortion:{map:r(a.map),...l("mapUV",Ms(a.mapUV,Os)),strength:a.strength}}:{},sourceMaterial:this.materialRef??void 0},c}static resolveGeometryData(t){if(t?.positions){const e=t.positions instanceof Float32Array?t.positions:new Float32Array(t.positions);return{positions:e,indices:Ks(e,t.indices instanceof Uint16Array||t.indices instanceof Uint32Array?t.indices:t.indices?new Uint32Array(t.indices):void 0),uvs:t.uvs?t.uvs instanceof Float32Array?t.uvs:new Float32Array(t.uvs):void 0,uvs2:t.uvs2?t.uvs2 instanceof Float32Array?t.uvs2:new Float32Array(t.uvs2):void 0,normals:t.normals?t.normals instanceof Float32Array?t.normals:new Float32Array(t.normals):void 0}}const e=t?.data??t;if(e?.attributes?.position?.array){const t=new Float32Array(e.attributes.position.array);let i;if(e.index?.array){i=new("Uint16Array"===e.index.type?Uint16Array:Uint32Array)(e.index.array)}return{positions:t,indices:Ks(t,i),uvs:e.attributes.uv?.array?new Float32Array(e.attributes.uv.array):void 0,uvs2:(e.attributes.uv1??e.attributes.uv2)?.array?new Float32Array((e.attributes.uv1??e.attributes.uv2).array):void 0,normals:e.attributes.normal?.array?new Float32Array(e.attributes.normal.array):void 0}}return{positions:cn,indices:pn,uvs:un}}addBehavior(t){this.behaviors.push(t),this._renderer?._invalidateUpdateOrder()}getRendererSettings(){return this.rendererSettings}addEventListener(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}removeAllEventListeners(t){this.listeners[t]&&(this.listeners[t]=[])}removeEventListener(t,e){if(this.listeners[t]){const i=this.listeners[t].indexOf(e);-1!==i&&this.listeners[t].splice(i,1)}}hasListeners(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 i=0;i<e.length;i++)e[i](t)}clone(){const e=this.behaviors.map(t=>t.clone());let i;i=this.renderMode===t.RenderMode.Trail?{startLength:this.rendererEmitterSettings.startLength.clone(),followLocalOrigin:this.rendererEmitterSettings.followLocalOrigin,...yn(this.rendererEmitterSettings),...this.rendererEmitterSettings.sideAxis?{sideAxis:this.rendererEmitterSettings.sideAxis.clone()}:{}}:this.renderMode===t.RenderMode.StretchedBillBoard?{lengthFactor:this.rendererEmitterSettings.lengthFactor,speedFactor:this.rendererEmitterSettings.speedFactor}:{};const s=new xn({autoDestroy:this.autoDestroy,looping:this.looping,prewarm:this.prewarm,duration:this.duration,startDelay:this.startDelay.clone(),shape:this.emitterShape.clone(),startLife:this.startLife.clone(),startSpeed:this.startSpeed.clone(),startRotation:this.startRotation.clone(),startSize:this.startSize.clone(),startColor:this.startColor.clone(),emissionOverTime:this.emissionOverTime.clone(),emissionOverDistance:this.emissionOverDistance.clone(),emissionBursts:this.emissionBursts.map(t=>({...t})),maxParticles:this.maxParticles,onlyUsedByOther:this.onlyUsedByOther,instancingGeometry:this.rendererSettings.instancingGeometry,instancingIndices:this.rendererSettings.instancingIndices,instancingUVs:this.rendererSettings.instancingUVs,instancingUVs2:this.rendererSettings.instancingUVs2,instancingNormals:this.rendererSettings.instancingNormals,renderMode:this.renderMode,renderOrder:this.renderOrder,renderingGroupId:this.renderingGroupId,applyFog:this.applyFog,playbackSpeed:this.playbackSpeed,cullingMode:this.cullingMode,scalingMode:this.scalingMode,seed:this.seedValue,sortMode:this.sortMode,alignToDirection:this.alignToDirection,minParticleSize:this.minParticleSize,maxParticleSize:this.maxParticleSize,rendererEmitterSettings:i,material:this.materialRef,texture:this.rendererSettings.texture,startTileIndex:this.startTileIndex,uTileCount:this.rendererSettings.uTileCount,vTileCount:this.rendererSettings.vTileCount,blendTiles:this.rendererSettings.blendTiles,softParticles:this.rendererSettings.softParticles,softFarFade:this.rendererSettings.softFarFade,softNearFade:this.rendererSettings.softNearFade,behaviors:e,worldSpace:this.worldSpace,blendMode:this.rendererSettings.materialBlendMode,transparent:this.rendererSettings.materialTransparent,depthTest:this.rendererSettings.materialDepthTest,depthWrite:this.rendererSettings.materialDepthWrite,alphaTest:this.rendererSettings.materialAlphaTest,layerMask:this.rendererSettings.layerMask,pivot:this.pivot,flip:this.flip,lighting:this.lighting,rim:this.rim,mapUV:this.mapUV,gradientMap:this.gradientMap,erosion:this.erosion,uvDistortion:this.uvDistortion,scene:this.emitter.getScene()});for(const t of e)t instanceof ve&&(t.particleSystem=s);return this.tint&&(s.tint=this.tint.clone()),s}}xn.serializationCounter=0,xn.catchUpBudgetMs=2;class Sn extends n.TransformNode{constructor(t="QuarksPrefab",e){super(t,e),this.type="QuarksPrefab",this.animationData=[],this.isPlaying=!1,this.currentTime=-1e-5,this.timeScale=1,this.duration=0,this._lastUpdateTimeMs=Date.now(),this._tempAnimationJSON=[]}registerBatchedRenderer(t){this._batchedRenderer=t}addParticleSystemAnimation(t,e=0,i=0,s=!1){const n={startTime:e,duration:i>0?i:t.system.duration,type:"ps",loop:s,target:t};return this.animationData.push(n),this.pause(),this.updateDuration(),n}addThreeAnimation(t,e,i=0,s=e?.duration??0,n=!1,r){const o={startTime:i,duration:s>0?s: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){this.animationData.splice(t,1),this.updateDuration()}play(){this.isPlaying||(this.isPlaying=!0,this._lastUpdateTimeMs=Date.now())}pause(){this.isPlaying&&(this.isPlaying=!1,this.animationData.forEach(t=>{"ps"===t.type&&t.target instanceof qs?t.target.system.pause():t.clip?.pause?.()}))}stop(){this.pause(),this.currentTime=-1e-5,this.animationData.forEach(t=>{"ps"===t.type&&t.target instanceof qs?t.target.system.stop():t.clip?.stop?.()})}update(t){if(!this.isPlaying)return;const e=Date.now(),i=t??Math.max((e-this._lastUpdateTimeMs)/1e3,0);this._lastUpdateTimeMs=e;const s=this.currentTime;this.currentTime+=i*this.timeScale,this.currentTime>this.duration?this.stop():this.animationData.forEach(t=>{const e=t.startTime,i=t.startTime+t.duration,n=this.currentTime>=e&&this.currentTime<=i,r=s>=e&&s<=i;if(!n||r){if(!n&&r){if(t.loop&&"ps"===t.type&&t.target instanceof qs)return void t.target.system.restart();"ps"===t.type&&t.target instanceof qs?t.target.system.endEmit():t.loop?t.clip?.play?.():t.clip?.stop?.()}}else"ps"===t.type&&t.target instanceof qs?(t.target.system.restart(),this._batchedRenderer&&this._batchedRenderer.addSystem(t.target.system)):t.clip?.play?.()})}setTime(t){const e=this.currentTime;this.currentTime=t,this.animationData.forEach(i=>{const s=i.startTime,n=i.startTime+i.duration,r=this.currentTime>=s&&this.currentTime<n,o=e>=s&&e<n;!r||o?r||!o?r&&"three"===i.type&&i.clip?.setTime?.(Math.max(t-s,0)):"ps"===i.type&&i.target instanceof qs?i.target.system.endEmit():i.clip?.stop?.():"ps"===i.type&&i.target instanceof qs?i.target.system.restart():i.clip?.play?.()})}getDuration(){return this.duration}resolveReferences(t){const e={},i=t=>{t._quarksUUID&&(e[t._quarksUUID]=t),e[t.uniqueId.toString()]=t;const s=t.getChildren();for(const t of s)t instanceof n.TransformNode&&i(t)};i(t),this._tempAnimationJSON.forEach(t=>{const i=e[t.targetUUID];if("ps"===t.type&&i instanceof qs)this.addParticleSystemAnimation(i,t.startTime,t.duration,t.loop);else if("three"===t.type&&i){const e=this.resolveTimelineClip(i,t.clipUUID);this.addThreeAnimation(i,e,t.startTime,t.duration,t.loop,t.clipUUID)}}),this.updateDuration(),this._tempAnimationJSON=[]}toJSON(){return{type:this.type,name:this.name,animationData:this.animationData.map(t=>({startTime:t.startTime,duration:t.duration,type:t.type,targetUUID:t.target._quarksUUID??t.target.uniqueId.toString(),clipUUID:"three"===t.type?t.clipUUID??t.clip?.uuid:void 0,loop:t.loop}))}}static fromJSON(t,e){const i=new Sn(t.name||"QuarksPrefab",e);return Array.isArray(t.animationData)&&(i._tempAnimationJSON=t.animationData.filter(t=>"ps"===t?.type||"three"===t?.type)),i}resolveTimelineClip(t,e){const i=[t.animations,t.animationGroups,t.metadata?.animations,t.metadata?.animationGroups];for(const t of i){if(!Array.isArray(t))continue;if(!e)return t[0];const i=t.find(t=>t?.uuid===e);if(i)return i}}updateDuration(){let t=0;this.animationData.forEach(e=>{const i=e.startTime+e.duration;i>t&&(t=i)}),this.duration=t}}const bn=new WeakMap,wn=new WeakMap,Mn=new WeakMap;function zn(t,e){let i=t.get(e);return void 0===i&&(i=new Map,t.set(e,i)),i}class _n{constructor(t,e={}){this.scene=t,this.options=e}async load(t){const{json:e,baseUrl:i}=await this.fetchEffectDocument(t);return this.loadFromJSON(e,i)}async loadFromJSON(t,e){const i=e??this.options.baseUrl??"";return await this.resolveResources(t,i),this.parse(t,i)}async loadAll(t,e={}){const i=await _n.mapPool(t,e.concurrency,async(i,s)=>{try{return await this.fetchEffectDocument(i)}catch(n){if(!e.continueOnError)throw n;return console.warn(`[QuarksLoader] Failed to fetch effect "${i}" (${s+1}/${t.length}):`,n),null}});return this.loadDocuments(i,e)}async loadFromJSONAll(t,e={}){const i=t.map(t=>{if(null!==t&&"object"==typeof t&&"json"in t){const e=t;return{json:e.json,baseUrl:e.baseUrl??this.options.baseUrl??""}}return{json:t,baseUrl:this.options.baseUrl??""}});return this.loadDocuments(i,e)}async resolveResources(t,e=""){await _n.resolveLinkedResources(t,{baseUrl:e,resolver:this.options.resolver,scene:this.scene})}static async resolveLinkedResources(t,e={}){const i=e.baseUrl??"",s=e.resolver,n=e.scene;await _n.inlineGeometryEntries(t,async t=>{const e=await _n.resolveWith(s,t,"geometry",i);return _n.fetchJsonWith(s,e,n)});const r=Array.isArray(t?.images)?t.images:[];await Promise.all(r.map(async t=>{"string"==typeof t?.url&&t.url&&(t.url=await _n.resolveWith(s,t.url,"image",i))}))}static async resolveExternalGeometries(t,e){await _n.inlineGeometryEntries(t,e)}parse(t,e=""){const i={textures:{},geometries:{},materials:{}};t.geometries&&this.parseGeometries(t.geometries,i),t.images&&this.parseImages(t.images,e,i),t.textures&&this.parseTextures(t.textures,i),t.materials&&this.parseMaterials(t.materials,i);const s=this.parseObject(t.object,i);return this.linkReferences(s),s}parseGeometries(t,e){for(const i of t)if("PlaneGeometry"===i.type){const t=(i.width||1)/2,s=(i.height||1)/2;e.geometries[i.uuid]={positions:new Float32Array([-t,-s,0,t,-s,0,t,s,0,-t,s,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"===i.type)e.geometries[i.uuid]=this.parseSphereGeometry(i);else if("BufferGeometry"===i.type&&i.data){const t=this.parseBufferGeometry(i.data);e.geometries[i.uuid]=t}else"QuarksGeometry"===i.type&&("string"!=typeof i.url||i.positions||console.warn(`[QuarksLoader] Geometry "${i.url}" is an external file; use load(), loadFromJSON(), or resolveResources() before parse().`),e.geometries[i.uuid]=this.share({positions:new Float32Array(i.positions??[]),indices:i.indices?new Uint32Array(i.indices):new Uint32Array(0),uvs:i.uvs?new Float32Array(i.uvs):void 0,uvs2:i.uvs2?new Float32Array(i.uvs2):void 0,normals:i.normals?new Float32Array(i.normals):void 0}))}share(t){if(!1===this.options.shareResources)return t;const e=zn(wn,this.scene),i=function(t){let e=2166136261,i=2654435769;const s=[t.positions,t.indices,t.uvs,t.uvs2,t.normals];let n="";for(const t of s){if(void 0===t){n+="-,";continue}const s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n+=s.length+",";for(let t=0;t<s.length;t++)e=Math.imul(e^s[t],16777619),i=Math.imul(i^s[t],1540483477)^i>>>15}return`${n}${(e>>>0).toString(16)}${(i>>>0).toString(16)}`}(t),s=e.get(i);return void 0!==s?s:(e.set(i,t),t)}static clearSharedResources(t){bn.delete(t),wn.delete(t),Mn.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,i=Math.max(3,Math.floor(t.widthSegments??16)),s=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<=s;t++){const u=[],m=t/s,p=o+m*a;for(let t=0;t<=i;t++){const s=t/i,o=n+s*r,a=-e*Math.cos(o)*Math.sin(p),d=e*Math.cos(p),y=e*Math.sin(o)*Math.sin(p);h.push(a,d,y);const g=Math.hypot(a,d,y)||1;l.push(a/g,d/g,y/g),c.push(s,1-m),u.push(f++)}d.push(u)}const m=o<=0,p=o+a>=Math.PI;for(let t=0;t<s;t++)for(let e=0;e<i;e++){const i=d[t][e+1],n=d[t][e],r=d[t+1][e],o=d[t+1][e+1];0===t&&m||u.push(i,n,o),t===s-1&&p||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,i,s,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,i]of Object.entries(t.interleavedBuffers)){const s=t.arrayBuffers[i.buffer];if(s){const t=new Float32Array(Array.isArray(s)?this.int32ArrayToFloat32(s):s);r[e]={data:t,stride:i.stride}}}if(t.attributes){if(t.attributes.position?.isInterleavedBufferAttribute){const e=t.attributes.position,i=r[e.data];i&&(n=this.extractInterleavedAttribute(i.data,i.stride,e.offset,e.itemSize))}if(t.attributes.uv?.isInterleavedBufferAttribute){const i=t.attributes.uv,s=r[i.data];s&&(e=this.extractInterleavedAttribute(s.data,s.stride,i.offset,i.itemSize))}if(o?.isInterleavedBufferAttribute){const t=r[o.data];t&&(i=this.extractInterleavedAttribute(t.data,t.stride,o.offset,o.itemSize))}if(t.attributes.normal?.isInterleavedBufferAttribute){const e=t.attributes.normal,i=r[e.data];i&&(s=this.extractInterleavedAttribute(i.data,i.stride,e.offset,e.itemSize))}}}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&&(i=new Float32Array(o.array)),t.attributes.normal?.array&&(s=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=Ks(n,r),{positions:n,indices:r,uvs:e,uvs2:i,normals:s}}extractInterleavedAttribute(t,e,i,s){const n=Math.floor(t.length/e),r=new Float32Array(n*s);for(let o=0;o<n;o++)for(let n=0;n<s;n++)r[o*s+n]=t[o*e+i+n];return r}int32ArrayToFloat32(t){const e=new ArrayBuffer(4*t.length),i=new Int32Array(e);for(let e=0;e<t.length;e++)i[e]=t[e];return new Float32Array(e)}async resolveResourceUrl(t,e,i){return _n.resolveWith(this.options.resolver,t,e,i)}async fetchEffectDocument(t){const e=this.options.baseUrl||t.substring(0,t.lastIndexOf("/")+1),i=await this.resolveResourceUrl(t,"effect",e);return{json:await _n.fetchJsonWith(this.options.resolver,i,void 0),baseUrl:e}}async loadDocuments(t,e){const i=t.length;if(0===i)return[];const s=new Array(i),n=new Array(i).fill(!1);let r=0;const o=(t,o)=>{n[t]||(n[t]=!0,s[t]=o,r++,e.onProgress?.(r,i))};await 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,o(n,null)}}));for(let s=0;s<i;s++){if(n[s])continue;const r=t[s];if(r)try{o(s,this.parse(r.json,r.baseUrl))}catch(t){if(!e.continueOnError)throw t;console.warn(`[QuarksLoader] Failed to parse effect ${s+1}/${i}:`,t),o(s,null)}else o(s,null)}return s}static async mapPool(t,e,i){if(0===t.length)return[];const s=void 0!==e&&e>0?e:t.length,n=new Array(t.length);let r=0;const o=Math.min(s,t.length);return await Promise.all(Array.from({length:o},()=>(async()=>{for(;r<t.length;){const e=r++;n[e]=await i(t[e],e)}})())),n}static async resolveWith(t,e,i,s){return t?.resolve?t.resolve(e,i,s):_n.joinUrl(s,e)}static fetchJsonWith(t,e,i){const s=async()=>{if(t?.fetchJson)return t.fetchJson(e);const i=await fetch(e);if(!i.ok)throw new Error(`HTTP ${i.status}`);return i.json()};if(!i)return s();const n=zn(Mn,i),r=`json|${e}`;let o=n.get(r);return void 0===o&&(o=s().catch(t=>{throw n.get(r)===o&&n.delete(r),t}),n.set(r,o)),o}static async inlineGeometryEntries(t,e){const i=Array.isArray(t?.geometries)?t.geometries:[];await Promise.all(i.filter(t=>"string"==typeof t?.url&&!t.positions).map(async t=>{try{const i=await e(t.url);for(const e of["positions","indices","uvs","uvs2","normals"]){const s=i?.[e];void 0!==s&&(t[e]=Array.isArray(s)?s.slice():s)}delete t.url}catch(e){console.warn(`[QuarksLoader] Could not load geometry "${t.url}":`,e)}}))}parseImages(t,e,i){this._images={};for(const i of t)i.url&&_n.warnIfNotAnImageUrl(i.url),this._images[i.uuid]=i.url?_n.joinUrl(e,i.url):null}static warnIfNotAnImageUrl(t){/^(data|blob):/i.test(t)||/\.(png|jpe?g|webp|gif|bmp|ktx2?|dds|env|basis)(\?|#|$)/i.test(t)||console.warn(`[QuarksLoader] 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){const i=this._images||{};for(const s of t){const t=i[s.image];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?zn(bn,this.scene):void 0,h=a?.get(o);if(void 0!==h){e.textures[s.uuid]=h;continue}const l=new g.Texture(t,this.scene,{noMipmap:n,invertY:i,samplingMode:"number"==typeof s.samplingMode?s.samplingMode:void 0});Array.isArray(s.wrap)&&(l.wrapU=this.mapWrapMode(s.wrap[0]),l.wrapV=this.mapWrapMode(s.wrap[1]??s.wrap[0])),Array.isArray(s.repeat)&&(l.uScale=s.repeat[0]??1,l.vScale=s.repeat[1]??1),Array.isArray(s.offset)&&(l.uOffset=s.offset[0]??0,l.vOffset=s.offset[1]??0),"number"==typeof s.rotation&&(l.wAng=s.rotation),void 0!==a&&(a.set(o,l),l.onDisposeObservable.addOnce(()=>{a.get(o)===l&&a.delete(o)})),e.textures[s.uuid]=l}else e.textures[s.uuid]=null}}mapWrapMode(t){switch(t){case 1001:return g.Texture.CLAMP_ADDRESSMODE;case 1002:return g.Texture.MIRROR_ADDRESSMODE;default:return g.Texture.WRAP_ADDRESSMODE}}parseMaterials(t,e){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},s=i.map??i.texture;s&&(t.texture=e.textures[s]||null);const n=i.reflectionAtlas;if(n&&(t.reflectionAtlas=e.textures[n]||null),"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:i.gradientMap.ramp&&e.textures[i.gradientMap.ramp]||null}),i.erosion&&"object"==typeof i.erosion&&(t.erosion={...i.erosion,mask:i.erosion.mask&&e.textures[i.erosion.mask]||null}),i.uvDistortion&&"object"==typeof i.uvDistortion&&(t.uvDistortion={...i.uvDistortion,map:i.uvDistortion.map&&e.textures[i.uvDistortion.map]||null}),"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]||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 i=Array.isArray(e)?e[0]:e;return t.materials[i]}createPlaceholderNode(t,e){const i=new n.TransformNode(e||t||"node",this.scene);return i.quarksOriginalType=t,i}createMeshNode(t,e){const i=new l.Mesh(t.name||t.type||"mesh",this.scene),s=this.getGeometry(e,t.geometry);if(s&&s.positions.length>0&&s.indices.length>0){const t=new c.VertexData;t.positions=s.positions,t.indices=s.indices,s.uvs&&s.uvs.length>0&&(t.uvs=s.uvs),s.uvs2&&s.uvs2.length>0&&(t.uvs2=s.uvs2),s.normals&&s.normals.length>0&&(t.normals=s.normals),t.applyToMesh(i,!0)}const n=this.getMaterial(e,t.material);if(n){const t=new x.StandardMaterial(`quarks_loader_material_${n.uuid}`,this.scene);t.alphaMode=n.alphaMode??r.Constants.ALPHA_COMBINE,t.backFaceCulling=2!==n.side,t.alphaCutOff=n.alphaTest??0,t.disableDepthWrite=!n.depthWrite,n.texture&&(t.diffuseTexture=n.texture,t.opacityTexture=n.texture),i.material=t}return i}parseObject(t,e){let i;switch(t.type){case"QuarksPrefab":i=Sn.fromJSON(t,this.scene);break;case"ParticleEmitter":if(t.ps){i=this.parseParticleSystem(t.ps,e).emitter;break}i=this.createPlaceholderNode(t.type,t.name);break;case"Mesh":case"SkinnedMesh":case"InstancedMesh":case"BatchedMesh":i=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":i=this.createPlaceholderNode(t.type,t.name);break;default:i=new n.TransformNode(t.name||t.type||"node",this.scene)}if(t.uuid&&(i._quarksUUID=t.uuid),t.name&&(i.name=t.name),t.matrix){const e=h.Matrix.FromArray(t.matrix),s=new h.Vector3(1,1,1),n=h.Quaternion.Identity(),r=new h.Vector3(0,0,0);e.decompose(s,n,r),i.position.copyFrom(r),i.scaling.copyFrom(s),i.rotationQuaternion=n}else t.position&&i.position.set(t.position[0],t.position[1],t.position[2]),t.scale&&i.scaling.set(t.scale[0],t.scale[1],t.scale[2]),t.quaternion?i.rotationQuaternion=new h.Quaternion(t.quaternion[0],t.quaternion[1],t.quaternion[2],t.quaternion[3]):t.rotation&&i.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]);if(void 0!==t.visible&&i.setEnabled(t.visible),t.children)for(const s of t.children){this.parseObject(s,e).parent=i}return i}parseParticleSystem(t,e){const i=xn.fromJSON(t,e,{},this.scene);return i._meshSurfaceReferenceUUID="mesh_surface"===t?.shape?.type?t?.shape?.mesh:void 0,i}linkReferences(t){const e={},i=t=>{t._quarksUUID&&(e[t._quarksUUID]=t);for(const e of t.getChildren())e instanceof n.TransformNode&&i(e)};i(t);const s=i=>{if(i instanceof Sn&&i.resolveReferences(t),i instanceof qs){const t=i.system,s=t._meshSurfaceReferenceUUID;if(s&&"mesh_surface"===t.emitterShape.type){const i=e[s];i instanceof l.Mesh&&(t.emitterShape.mesh=i)}for(let s=0;s<t.behaviors.length;s++)if(t.behaviors[s]instanceof ve){const n=t.behaviors[s],r=n.subParticleSystem;if("string"!=typeof r)continue;const o=e[r];o instanceof qs?(n.subParticleSystem=o,o.system.onlyUsedByOther=!0):(n.subParticleSystem=void 0,""!==r&&console.warn(`[QuarksLoader] Emitter "${i.name}" has a sub emitter targeting "${r}", `+(o?"which is not a particle emitter":"which is not in the effect")+"; that sub emitter is skipped."))}}for(const t of i.getChildren())t instanceof n.TransformNode&&s(t)};s(t)}}Li(),Ui(Ni),t.ApplyCollision=At,t.ApplyForce=se,t.ApplySequences=oe,t.AxisAngleGenerator=Et,t.BatchedParticleRenderer=Ls,t.BatchedRenderer=Ds,t.BehaviorFromJSON=ri,t.BehaviorTypes=ni,t.Bezier=Ft,t.BoxEmitter=bi,t.ChangeEmitDirection=ae,t.CircleEmitter=zi,t.ColorBySpeed=he,t.ColorGeneratorFromJSON=Xt,t.ColorOverLife=le,t.ColorRange=qt,t.ConeEmitter=_i,t.ConstantColor=Yt,t.ConstantValue=Bt,t.DEG2RAD=T,t.DonutEmitter=Vi,t.EdgeEmitter=Ti,t.EffectPool=class{constructor(t,e){this.template=t,this.options=e,this.idle=[],this.playing=new Set,this.systemsOf=new Map,this.disposed=!1,this.onSystemFinished=t=>{const e=t.particleSystem;for(const t of this.playing){const i=this.systemsOf.get(t);if(void 0!==i&&i.includes(e))return void(ks.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 i=this.idle.pop()??this.makeCopy();return null===i?null:(i.parent=e,void 0!==t&&i.position.copyFrom(t),i.setEnabled(!0),this.playing.add(i),ks.restart(i),ks.play(i),i)}stop(t){this.playing.has(t)&&ks.endEmit(t)}release(t){this.playing.delete(t)&&(ks.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=ks.instantiate(this.template),e=[];return ks.runOnAllParticleEmitters(t,t=>{const i=t.system;i.autoDestroy=!1,i.addEventListener("finished",this.onSystemFinished),e.push(i)}),this.systemsOf.set(t,e),ks.addToBatchRenderer(t,this.options.renderer),t.setEnabled(!1),t.parent=null,t}disposeCopy(t){const e=this.systemsOf.get(t)??[];for(const t of e)t.removeEventListener("finished",this.onSystemFinished),this.options.renderer.deleteSystem(t),t.dispose();this.systemsOf.delete(t),t.dispose()}},t.EmitSubParticleSystem=ve,t.EmitterFromJSON=$i,t.EmitterShapes=Fi,t.Euler=mt,t.EulerGenerator=Zt,t.ForceOverLife=xe,t.FrameOverLife=Se,t.GRADIENT_MAP_WEIGHTS=zs,t.GeneratorFromJSON=ie,t.Gradient=Qt,t.GravityForce=be,t.GridEmitter=Pi,t.HemisphereEmitter=Oi,t.InheritVelocity=we,t.IntervalValue=Ct,t.LimitSpeedOverLife=Me,t.MathUtils=Z,t.Matrix3=pt,t.Matrix4=nt,t.MeshSurfaceEmitter=Ei,t.MeshSurfaceEmitterPlugin=Ni,t.NodeParticle=class{constructor(){this.position=new K,this.velocity=new K,this.age=0,this.life=1,this.size=new K,this.rotation=0,this.color=new zt(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}},t.Noise=Re,t.OrbitOverLife=De,t.ParticleEmitter=qs,t.ParticleMeshPhysicsMaterial=Hs,t.ParticleMeshStandardMaterial=Zs,t.ParticleStore=ze,t.ParticleSystem=xn,t.PiecewiseBezier=It,t.PiecewiseFunction=$t,t.Plugins=Ii,t.PointEmitter=Ai,t.QuarksLoader=_n,t.QuarksPrefab=Sn,t.QuarksUtil=ks,t.Quaternion=H,t.QuaternionView=vt,t.RAD2DEG=P,t.RandomColor=Gt,t.RandomColorBetweenGradient=jt,t.RandomQuatGenerator=Ht,t.RecordState=class{constructor(t,e,i){this.position=t,this.size=e,this.color=i}},t.RectangleEmitter=Ci,t.Rotation3DOverLife=Le,t.RotationBySpeed=qe,t.RotationGeneratorFromJSON=Kt,t.RotationOverLife=ke,t.SequencerFromJSON=re,t.ShapeTransform=Mi,t.SizeBySpeed=Je,t.SizeOverLife=Qe,t.SpeedOverLife=Ge,t.SphereEmitter=Bi,t.SpriteBatch=Us,t.SpriteParticle=ti,t.SubEmitterInheritMask=ye,t.TextureSequencer=ne,t.TrailBatch=Rs,t.TrailParticle=ii,t.TurbulenceField=We,t.UV_DISTORTION_DEFAULT_UV=Os,t.VFXBatch=Is,t.ValueGeneratorFromJSON=Ut,t.Vector2=St,t.Vector3=K,t.Vector3Function=te,t.Vector3GeneratorFromJSON=ee,t.Vector3View=wt,t.Vector4=zt,t.Vector4View=Vt,t.VelocityOverLife=Ze,t.WebGLCoordinateSystem=it,t.WebGPUCoordinateSystem=st,t.WidthOverLength=si,t.cacheEnvAtlas=function(t,e){Js.set(t,e)},t.ceilPowerOfTwo=G,t.clamp=A,t.createEnvAtlasFromFaceUrls=js,t.createSeededRandom=z,t.cubeFaceUrls=Gs,t.damp=I,t.defaultMeshLighting=vs,t.degToRad=k,t.denormalize=Y,t.ensureEnvAtlasFromCube=Xs,t.erosionEqual=Ps,t.euclideanModulo=B,t.floorPowerOfTwo=W,t.generateUUID=O,t.getCachedEnvAtlas=Ws,t.getPhysicsResolver=Ot,t.getRandomSource=w,t.getRegisteredShaderChunks=function(){return Ri},t.getShaderChunk=function(t){return Ri[t]},t.getValueFromEmitterMode=wi,t.gradientMapEqual=Vs,t.inverseLerp=F,t.isPowerOfTwo=Q,t.lerp=$,t.loadPlugin=Ui,t.localParticlePhysicsVertShader=Xi,t.localParticleVertShader="\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 vec4 rotation;\nattribute float uvTile;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\n\n// Varyings\nvarying vec2 vUV;\nvarying vec4 vColor;\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\nvoid main() {\n vec3 rotatedPosition = applyQuaternion(position * size, rotation);\n vec3 worldPos = rotatedPosition + offset;\n\n gl_Position = worldViewProjection * vec4(worldPos, 1.0);\n\n #ifdef UV_TILE\n vec2 tc = vec2(tileCountX, tileCountY);\n float baseTile = floor(uvTile);\n float tileU = mod(baseTile, tc.x) / tc.x;\n float tileV = 1.0 - floor(baseTile / tc.x) / tc.y - 1.0 / tc.y;\n vUV = uv / tc + vec2(tileU, tileV);\n #else\n vUV = uv;\n #endif\n\n vColor = color;\n}\n",t.mapLinear=C,t.mapUVEqual=Fs,t.meshRimEqual=Ss,t.normalize=X,t.normalizeErosion=Ts,t.normalizeGradientMap=_s,t.normalizeMapUV=Cs,t.normalizeMeshRim=xs,t.normalizeTextureUV=bs,t.normalizeUVDistortion=As,t.particleFragShader=es,t.particlePhysicsFragShader=is,t.particleVertShader=ss,t.pingpong=U,t.planBehaviorFusion=vi,t.radToDeg=J,t.randFloat=D,t.randFloatSpread=L,t.randInt=R,t.random=b,t.readsUV1=$s,t.registerShaderChunks=Li,t.seededRandom=q,t.setPhysicsResolver=function(t){Pt=t},t.setQuaternionFromProperEuler=j,t.setRandomSource=M,t.smootherstep=N,t.smoothstep=E,t.stretchedBillboardVertShader=ns,t.subEmitterInheritMask=ge,t.textureUVEqual=ws,t.textureUVToJSON=Ms,t.trailFragShader=rs,t.trailVertShader=os,t.unloadPlugin=function(t){const e=Ii.find(e=>e.id===t);if(e){for(const t of e.emitterShapes)Fi[t.type]&&delete Fi[t.type];for(const t of e.behaviors)ni[t.type]&&delete ni[t.type]}},t.uvDistortionEqual=Bs,t.withRandomSource=function(t,e){const i=M(t);try{return e()}finally{M(i)}}});
2
2
  //# sourceMappingURL=babylon.quarks.umd.min.js.map