@joy-ride/joy-ride 0.2.4 → 0.4.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.
@@ -768,7 +768,7 @@ void main() {
768
768
  alpha = max(alpha,glow*0.5*heat*uFade);
769
769
  }
770
770
  color = vec4(hot,alpha);
771
- }`,cy=class{canvas=document.createElement(`canvas`);gl;program;buffer;viewportUniform;fadeUniform;wallCountUniform;wallsUniform;disturbanceUniform;disturbanceRadiusUniform;electricColorUniform;electricCoronaUniform;wallData=new Float32Array(128);data=new Float32Array(256*ay);lost=!1;overlayHost=null;constructor(){this.canvas.width=512,this.canvas.height=512;let e=this.canvas.getContext(`webgl2`,{alpha:!0,depth:!1,stencil:!1,antialias:!0,premultipliedAlpha:!0});if(!e)throw Error(`WebGL2 is required for spark particles`);this.gl=e,this.canvas.addEventListener(`webglcontextlost`,e=>{e.preventDefault(),this.lost=!0});let t=Dv(e,oy,sy,`Spark`),n=e.createBuffer();if(!n)throw Pv(e,t),Error(`Unable to allocate spark buffer`);this.program=t,this.buffer=n,this.viewportUniform=kv(t,`uViewport`),this.fadeUniform=kv(t,`uFade`),this.wallCountUniform=kv(t,`uWallCount`),this.wallsUniform=kv(t,`uWalls[0]`),this.disturbanceUniform=kv(t,`uDisturbance`),this.disturbanceRadiusUniform=kv(t,`uDisturbanceRadius`),this.electricColorUniform=kv(t,`uElectricColor`),this.electricCoronaUniform=kv(t,`uElectricCorona`),e.bindBuffer(e.ARRAY_BUFFER,n),Mv(e,t,{aStart:{buffer:n,numComponents:2,stride:44,offset:0,divisor:1},aEnd:{buffer:n,numComponents:2,stride:44,offset:8,divisor:1},aMotion:{buffer:n,numComponents:2,stride:44,offset:16,divisor:1},aStyle:{buffer:n,numComponents:4,stride:44,offset:24,divisor:1},aSeed:{buffer:n,numComponents:1,stride:44,offset:40,divisor:1}})}clear(){if(this.lost||!this.overlayHost||this.canvas.style.display===`none`)return;let e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),e.disable(e.SCISSOR_TEST),e.viewport(0,0,this.canvas.width,this.canvas.height),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),this.canvas.style.display!==`none`&&(this.canvas.style.display=`none`)}dispose(){this.canvas.remove(),this.overlayHost=null,Pv(this.gl,this.program),this.gl.deleteBuffer(this.buffer),this.gl.getExtension(`WEBGL_lose_context`)?.loseContext(),this.lost=!0}mountOverlay(e,t,n){this.overlayHost!==e&&(this.canvas.remove(),this.overlayHost=e,this.canvas.dataset.jrOverlay=``,this.canvas.style.position=`fixed`,this.canvas.style.pointerEvents=`none`,this.canvas.style.zIndex=e.style.zIndex||ey(`world`),document.body.append(this.canvas)),this.canvas.style.display!==`block`&&(this.canvas.style.display=`block`);let r=e.hasAttribute(`data-jr-overlay`)?{left:0,top:0}:e.getBoundingClientRect(),i=`${r.left}px`,a=`${r.top}px`,o=`${t.width}px`,s=`${t.height}px`;this.canvas.style.left!==i&&(this.canvas.style.left=i),this.canvas.style.top!==a&&(this.canvas.style.top=a),this.canvas.style.width!==o&&(this.canvas.style.width=o),this.canvas.style.height!==s&&(this.canvas.style.height=s);let c=Math.ceil(t.width*n),l=Math.ceil(t.height*n);(this.canvas.width!==c||this.canvas.height!==l)&&(this.canvas.width=c,this.canvas.height=l)}draw(e,t,n,r,i=1,a,o=[],s,c=iy){if(this.lost||!t.length||n<=0){this.clear();return}let l=t.filter(e=>{let t=e.kind===2?ly(e.start,e.motion,e.age,e.seed):e.end;return t.x>-64&&t.x<r.width+64&&t.y>-64&&t.y<r.height+64});if(!l.length){this.clear();return}let u=1/0,d=1/0,f=-1/0,p=-1/0;for(let e of l){let t=e.kind===2?ly(e.start,e.motion,e.age,e.seed):e.end,n=e.kind===2?ly(e.start,e.motion,Math.max(0,e.age-.045),e.seed):e.start;u=Math.min(u,n.x,t.x),f=Math.max(f,n.x,t.x),d=Math.min(d,n.y,t.y),p=Math.max(p,n.y,t.y)}let m=a?0:Math.floor((u-16)/32)*32,h=a?0:Math.floor((d-16)/32)*32,g=a?r.width:Math.max(32,Math.ceil((f+16-m)/32)*32),_=a?r.height:Math.max(32,Math.ceil((p+16-h)/32)*32),v=Math.min(2,Math.max(1,i)),y=Math.ceil(g*v),b=Math.ceil(_*v);a?this.mountOverlay(a,r,v):(y>this.canvas.width&&(this.canvas.width=Math.ceil(y/256)*256),b>this.canvas.height&&(this.canvas.height=Math.ceil(b/256)*256)),this.data.length<l.length*ay&&(this.data=new Float32Array(Math.max(l.length*ay,this.data.length*2)));let x=0;for(let e of l)this.data[x]=(e.start.x-m)*v,this.data[x+1]=(e.start.y-h)*v,this.data[x+2]=(e.end.x-m)*v,this.data[x+3]=(e.end.y-h)*v,this.data[x+4]=e.motion.x*v,this.data[x+5]=e.motion.y*v,this.data[x+6]=e.age,this.data[x+7]=e.life,this.data[x+8]=e.size*v,this.data[x+9]=e.kind,this.data[x+10]=e.seed,x+=ay;let S=this.gl;performance.now();let C=a?0:this.canvas.height-b;S.viewport(0,C,y,b),a||(S.enable(S.SCISSOR_TEST),S.scissor(0,C,y,b)),S.clearColor(0,0,0,0),S.clear(S.COLOR_BUFFER_BIT),S.useProgram(this.program),S.bindBuffer(S.ARRAY_BUFFER,this.buffer),S.bufferData(S.ARRAY_BUFFER,this.data.subarray(0,x),S.DYNAMIC_DRAW),S.uniform2f(this.viewportUniform,y,b),S.uniform1f(this.fadeUniform,n),S.uniform3f(this.electricColorUniform,...c.color),S.uniform3f(this.electricCoronaUniform,...c.corona),s?(S.uniform4f(this.disturbanceUniform,(s.point.x-m)*v,(s.point.y-h)*v,s.velocity.x*v,s.velocity.y*v),S.uniform1f(this.disturbanceRadiusUniform,s.radius*v)):(S.uniform4f(this.disturbanceUniform,-1e5,-1e5,0,0),S.uniform1f(this.disturbanceRadiusUniform,1));let w=Math.min(32,o.length);for(let e=0;e<w;e++){let t=o[e],n=e*4;this.wallData[n]=(t.x-m)*v,this.wallData[n+1]=(t.y-h)*v,this.wallData[n+2]=(t.x+t.width-m)*v,this.wallData[n+3]=(t.y+t.height-h)*v}S.uniform1i(this.wallCountUniform,w),w&&S.uniform4fv(this.wallsUniform,this.wallData.subarray(0,w*4)),S.enable(S.BLEND),S.blendFuncSeparate(S.SRC_ALPHA,S.ONE_MINUS_SRC_ALPHA,S.ONE,S.ONE_MINUS_SRC_ALPHA),S.drawArraysInstanced(S.TRIANGLES,0,6,l.length),S.disable(S.BLEND),a||S.disable(S.SCISSOR_TEST),!a&&(performance.now(),e.drawImage(this.canvas,0,0,y,b,m,h,g,_))}};function ly(e,t,n,r){let i=r*Math.PI*2,a=3+r*73.19%1*3.1,o=7.5+r*41.73%1*6.2;return{x:e.x+t.x*n+(Math.sin(a*n+i*2.3)-Math.sin(i*2.3))*(5+r*91.7%1*13)+(Math.sin(o*n-i*3.1)-Math.sin(-i*3.1))*3.5,y:e.y+t.y*n-n*n*(24+r*19.3%1*38)+(Math.cos(a*n+i*1.7)-Math.cos(i*1.7))*4+(Math.sin(o*n+i*4.7)-Math.sin(i*4.7))*2.5}}var uy=360,dy=(e,t,n)=>Math.max(t,Math.min(n,e));function fy(e){let t=Math.max(1,e.pixelsPerMeter),n=Math.max(0,-j(e.velocity,e.normal))/t,r=M(k(e.velocity,A(e.normal,j(e.velocity,e.normal))))/t,i=r/Math.max(.001,r+n),a=dy((n+(e.wall?.4:0))/1.8,0,1)*dy((r-.8)/7,0,1)*dy(i/.65,0,1),o=dy((n-1.4)/9,0,1)*(1-i*.35);return Math.max(a,o)}function py(e){let t=t=>{let n=D(-t.y,t.x);return j(n,e.velocity)<0&&(n=A(n,-1)),n},n=t(e.normal),r=O(n,t(e.carNormal??A(e.normal,-1))),i=M(r);if(i<.001)return n;let a=O(A(r,1/i),A(e.normal,.12));return A(a,1/M(a))}function my(e,t){let n=dy(e.x,t.x,t.x+t.width),r=dy(e.y,t.y,t.y+t.height);return e.x!==n||e.y!==r?D(n,r):[{distance:n-t.x,point:D(t.x,r)},{distance:t.x+t.width-n,point:D(t.x+t.width,r)},{distance:r-t.y,point:D(n,t.y)},{distance:t.y+t.height-r,point:D(n,t.y+t.height)}].reduce((e,t)=>t.distance<e.distance?t:e).point}function hy(e,t,n){if(Math.abs(n.x)>=Math.abs(n.y)){let r=D(n.x<0?-1:1,0);return{point:D(r.x<0?t.x:t.x+t.width,dy(e.y,t.y,t.y+t.height)),normal:r}}let r=D(0,n.y<0?-1:1);return{point:D(dy(e.x,t.x,t.x+t.width),r.y<0?t.y:t.y+t.height),normal:r}}function gy(e,t,n){let r=j(e.velocity,t);r<0&&(e.velocity=k(e.velocity,A(t,r*(1+n))))}function _y(e,t,n){let r=e.point,i=e=>e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height,a=k(r,n),o=0,s=1,c=D(),l=!0;for(let e of[`x`,`y`]){let r=a[e],i=t[e],u=i+(e===`x`?t.width:t.height);if(Math.abs(r)<1e-6){if(n[e]<i||n[e]>u){l=!1;break}continue}let d=(i-n[e])/r,f=(u-n[e])/r,p=Math.min(d,f),m=Math.max(d,f);if(p>o&&(o=p,c=e===`x`?D(r>0?-1:1,0):D(0,r>0?-1:1)),s=Math.min(s,m),o>s){l=!1;break}}if(l&&!i(n)&&o>=0&&o<=1&&o<=s&&M(c)){e.point=O(O(n,A(a,o)),A(c,.75)),gy(e,c,.38);return}if(!i(r))return;let u=hy(my(r,t),t,[{value:Math.abs(n.x-t.x),normal:D(-1,0)},{value:Math.abs(n.x-t.x-t.width),normal:D(1,0)},{value:Math.abs(n.y-t.y),normal:D(0,-1)},{value:Math.abs(n.y-t.y-t.height),normal:D(0,1)}].reduce((e,t)=>t.value<e.value?t:e).normal);e.point=O(u.point,A(u.normal,.75)),gy(e,u.normal,.38),e.previous={...e.point}}var vy=class{random;particles=[];walls=[];gpu=null;gpuUnavailable=!1;elapsed=0;lastEmission=-1/0;enabled=!0;electricalPalette=iy;airflow=null;constructor(e=Math.random){this.random=e}captureState(){return E({particles:this.particles,walls:this.walls,gpuUnavailable:this.gpuUnavailable,elapsed:this.elapsed,lastEmission:this.lastEmission,enabled:this.enabled,electricalPalette:this.electricalPalette,airflow:this.airflow})}restoreState(e){this.gpu?.clear();let t=E(e);this.particles=t.particles,this.walls=t.walls,this.gpuUnavailable=t.gpuUnavailable,this.elapsed=t.elapsed,this.lastEmission=t.lastEmission,this.enabled=t.enabled,this.electricalPalette=t.electricalPalette,this.airflow=t.airflow}get count(){return this.particles.length}setEnabled(e){this.enabled=e,e||this.reset()}prepare(){if(!this.enabled||this.gpu||this.gpuUnavailable)return!!this.gpu;try{this.gpu=new cy}catch{this.gpuUnavailable=!0}return!!this.gpu}reset(){this.particles=[],this.lastEmission=-1/0,this.walls=[],this.airflow=null,this.gpu?.clear()}setElectricalPalette(e){let t=(e,t)=>Number.isFinite(e)?dy(e,0,1):t,n=e.color??this.electricalPalette.color,r=e.corona??this.electricalPalette.corona;this.electricalPalette={color:[0,1,2].map(e=>t(n[e],this.electricalPalette.color[e])),corona:[0,1,2].map(e=>t(r[e],this.electricalPalette.corona[e]))}}electric(e,t,n=1){if(!this.enabled||!Number.isFinite(n)||n<=0||!Number.isFinite(e.x)||!Number.isFinite(e.y)||!Number.isFinite(t.x)||!Number.isFinite(t.y))return 0;let r=dy(n,.1,3),i=M(t)>.001,a=i?Math.atan2(t.y,t.x):0,o=Math.round(3+r*5);for(let t=0;t<o;t++){let t=i?a+(this.random()-.5)*1.6:this.random()*Math.PI*2,n=D(Math.cos(t),Math.sin(t)),o=O(e,A(n,this.random()*1.6));this.particles.push({point:o,previous:{...o},velocity:A(n,(220+this.random()*460)*Math.sqrt(r)),plane:null,age:0,life:.06+this.random()*.16,size:.65+this.random()*.7,kind:4,seed:this.random()})}return this.trim(),o}disturb(e,t,n=90){this.airflow={point:{...e},velocity:{...t},radius:n}}dispose(){this.gpu?.dispose(),this.gpu=null}emit(e){if(!this.enabled||this.elapsed-this.lastEmission<.045)return 0;let t=fy(e);if(t<=0)return 0;this.lastEmission=this.elapsed;let n=py(e),r=k(e.velocity,A(e.normal,j(e.velocity,e.normal))),i=Math.max(0,-j(e.velocity,e.normal)),a=i/Math.max(.001,i+M(r)),o=O(A(n,1-a),A(e.normal,a)),s=M(o),c=s>.001?A(o,1/s):e.normal,l=Math.round(24+80*Math.sqrt(t)),u=M(e.velocity)/Math.max(1,e.pixelsPerMeter),d=e.wall?hy(e.point,e.wall,e.normal):null,f=d?.point??e.point,p=d?.normal??e.normal;for(let n=0;n<l;n++){let n=(this.random()-.5)*(.4+t*.45+a*1.5),i=Math.cos(n),o=Math.sin(n),s=O(A(D(c.x*i-c.y*o,c.x*o+c.y*i),(140+Math.min(420,u*30))*(.45+this.random()*1.15)),A(r,.08)),l=O(f,A(p,e.wall?1.35+this.random()*.25:.35+this.random()*.3));this.particles.push({point:l,previous:{...l},velocity:s,plane:{origin:f,normal:p},age:0,life:.18+this.random()*.34,size:.85+this.random()*1.6,kind:0,seed:this.random()})}let m=O(f,A(p,e.wall?1.5:.8));return this.particles.push({point:m,previous:{...m},velocity:D(),plane:null,age:0,life:.18,size:5.5+t*4,kind:3,seed:this.random()}),this.trim(),l+1}emitBulletImpact(e,t){if(!this.enabled)return;let n=M(t);if(n<.001)return;let r=A(t,-1/n),i=O(e,A(r,1.4));for(let t=0;t<40;t++){let n=(this.random()-.5)*2.7,a=D(r.x*Math.cos(n)-r.y*Math.sin(n),r.x*Math.sin(n)+r.y*Math.cos(n)),o=O(i,A(a,this.random()*1.5));this.particles.push({point:o,previous:{...o},velocity:A(a,t<12?320+this.random()*300:150+this.random()*330),plane:{origin:e,normal:r},age:0,life:.16+this.random()*.24,size:.7+this.random()*1.2,kind:0,seed:this.random()})}this.particles.push({point:i,previous:{...i},velocity:D(),plane:null,age:0,life:.15,size:8,kind:3,seed:this.random()}),this.trim()}emitExplosion(e,t,n,r=1){if(!this.enabled)return 0;let i=Math.max(1,n),a=dy(r,.5,2),o=Math.atan2(t.y,t.x),s=Math.round(32+20*Math.sqrt(a));for(let t=0;t<s;t++){let n=o+t*Math.PI*(3-Math.sqrt(5))+(this.random()-.5)*.3,r=D(Math.cos(n),Math.sin(n)),s=i*(5+this.random()*9)*Math.sqrt(a),c=O(e,A(r,i*.03));this.particles.push({point:c,previous:{...c},velocity:A(r,s),plane:null,age:0,life:.24+this.random()*.36,size:1+this.random()*1.1,kind:1,seed:this.random()})}return this.trim(),s}emitFire(e,t){if(!this.enabled||this.random()>=Math.min(1,t*15))return;let n=D(e.x+e.width/2,e.y+e.height/2),r=Math.cos(e.angle??0),i=Math.sin(e.angle??0);for(let t=0;t<12;t++){let t=e.fixedRadius??0,a=this.random()*Math.PI*2,o=Math.sqrt(this.random())*t,s=t>0?O(e.origin,D(Math.cos(a)*o,Math.sin(a)*o)):D(e.x+this.random()*e.width,e.y+this.random()*e.height),c=s.x-n.x,l=s.y-n.y,u=c*r+l*i,d=-c*i+l*r,f=Math.floor((u/e.width+.5)*e.pixelWidth),p=Math.floor((d/e.height+.5)*e.pixelHeight);if(f<0||p<0||f>=e.pixelWidth||p>=e.pixelHeight||(e.alpha[p*e.pixelWidth+f]??0)<32)continue;let m=D(n.x+u*r-d*i,n.y+u*i+d*r),h=(e.age-(t>0?0:Math.hypot(m.x-e.origin.x,m.y-e.origin.y)/e.farthest*e.spreadSeconds))/e.burnSeconds;if(!(h<=0||h>=.82)){this.addEmber(m);return}}}emitFireAt(e,t,n,r=10){if(!this.enabled||this.random()>=Math.min(1,n*r))return;let i=this.random()*Math.PI*2,a=Math.sqrt(this.random())*t;this.addEmber(O(e,D(Math.cos(i)*a,Math.sin(i)*a)))}addEmber(e){this.particles.push({point:e,previous:{...e},velocity:D((this.random()-.5)*76,-35-this.random()*100),plane:null,age:0,life:.5+this.random()*1.25,size:.55+this.random()**2*1.25,kind:2,seed:this.random()}),this.trim()}trim(){this.particles.length>uy&&this.particles.splice(0,this.particles.length-uy)}step(e,t={walls:[]}){if(this.elapsed+=e,this.airflow){let t=Math.exp(-e*5.5);this.airflow.velocity=A(this.airflow.velocity,t),M(this.airflow.velocity)<1&&(this.airflow=null)}if(this.walls=t.walls,!this.particles.length)return;let n=Math.min(e,.05);for(let e of this.particles)if(e.age+=n,e.kind!==2&&e.kind!==3){e.previous={...e.point};for(let r=0;r<2;r++){let r={...e.point},i=e.kind===4,a=i?8+e.seed*8:3.2+e.seed*6.3;if(e.velocity=A(e.velocity,Math.exp(-a*n/2)),i){let t=(e.seed-.5)*9*n*.5,r=Math.cos(t),i=Math.sin(t);e.velocity=D(e.velocity.x*r-e.velocity.y*i,e.velocity.x*i+e.velocity.y*r)}else e.velocity.y+=(38+e.seed*84)*n*.5;if(e.point=O(e.point,A(e.velocity,n/2)),e.plane){let t=j(k(e.point,e.plane.origin),e.plane.normal);t<0&&(e.point=O(e.point,A(e.plane.normal,-t+.4)),gy(e,e.plane.normal,.55))}for(let n of t.walls)_y(e,n,r);if(t.car&&Qt(t.car.mask,t.car.shape,e.point)){let n=en(t.car.mask,t.car.shape,e.point);for(let r=0;r<16&&Qt(t.car.mask,t.car.shape,e.point);r++)e.point=O(e.point,A(n,1.2));gy(e,n,.48)}}}this.particles=this.particles.filter(e=>e.age<e.life)}draw(e,t,n,r,i=1,a){if(!this.enabled||!this.particles.length||n<=0){this.gpu?.clear();return}if(this.prepare(),!this.gpu)return;let o=this.particles.map(e=>{let n=t(e.point),r=k(t(O(e.point,e.velocity)),n),i=e.kind<2||e.kind===4,a=i?t(e.previous):n;if(i){let i=k(n,a),o=M(i),s=e.kind===4?Math.min(20,M(r)*.04):Math.min(18,M(r)*(e.kind===1?.032:.038));if(o>.001&&o<s?(a.x=n.x-i.x/o*s,a.y=n.y-i.y/o*s):o<1&&(a.x-=r.x*.02,a.y-=r.y*.02),e.plane){let n=t(e.plane.origin),r=k(t(O(e.plane.origin,e.plane.normal)),n),i=j(k(a,n),r)/Math.max(1e-6,M(r));if(i<.7){let e=A(r,1/Math.max(1e-6,M(r)));a.x+=e.x*(.7-i),a.y+=e.y*(.7-i)}}}return{start:a,end:n,motion:r,age:e.age,life:e.life,size:e.size,kind:e.kind,seed:e.seed}}),s=[];if(a)for(let e of this.walls){let n=t({x:e.x,y:e.y}),i=t({x:e.x+e.width,y:e.y+e.height}),a=Math.min(n.x,i.x),o=Math.min(n.y,i.y),c=Math.abs(n.x-i.x),l=Math.abs(n.y-i.y);if(!(a>r.width||o>r.height||a+c<0||o+l<0)&&(s.push({x:a,y:o,width:c,height:l}),s.length===32))break}let c=this.airflow?{point:t(this.airflow.point),velocity:k(t(O(this.airflow.point,this.airflow.velocity)),t(this.airflow.point)),radius:M(k(t(O(this.airflow.point,D(this.airflow.radius,0))),t(this.airflow.point)))}:void 0;this.gpu.draw(e,o,n,r,i,a,s,c,this.electricalPalette)}},yy=[[0,0],[60,120],[120,180],[240,240],[300,300],[360,360]];function by(e,t=!1){for(let n=1;n<yy.length;n++){let r=yy[n-1],i=yy[n],a=t?r[1]:r[0],o=t?i[1]:i[0];if(e<=o)return(t?r[0]:r[1])+(e-a)/(o-a)*((t?i[0]:i[1])-(t?r[0]:r[1]))}return e}function xy(e){let[t,n,r]=e.map(e=>e/255),i=Math.max(t,n,r),a=Math.min(t,n,r),o=i-a,s=(i+a)*.5,c=o===0?0:o/(1-Math.abs(2*s-1)),l=o===0?0:i===t?(n-r)/o%6:i===n?(r-t)/o+2:(t-n)/o+4;return l=by((l*60+360)%360)*Math.PI/180,[.5+.5*Math.cos(l)*c,.5+.5*Math.sin(l)*c,c,s]}function Sy(e){let t=e[0]*2-1,n=e[1]*2-1,r=Math.max(0,Math.min(1,e[2])),i=Math.max(0,Math.min(1,Math.hypot(t,n)/Math.max(r,1e-6))),a=r*Math.min(1,Math.sqrt(i*2)),o=Math.max(0,Math.min(1,e[3]))*(r>1e-6?.65+.35*i:1),s=by((Math.atan2(n,t)*180/Math.PI+360)%360,!0),c=(1-Math.abs(2*o-1))*a,l=c*(1-Math.abs(s/60%2-1)),u=Math.floor(s/60)%6,d=0,f=0,p=0;switch(u){case 0:d=c,f=l;break;case 1:d=l,f=c;break;case 2:f=c,p=l;break;case 3:f=l,p=c;break;case 4:d=l,p=c;break;default:d=c,p=l}let m=o-c*.5;return[Math.max(0,Math.min(255,(d+m)*255)),Math.max(0,Math.min(255,(f+m)*255)),Math.max(0,Math.min(255,(p+m)*255))]}function Cy(e){let t=lt[e],n=e===`paint`?null:ft(e),r=Math.max(t?.gloss??0,(n?.surface?.clearcoat??0)*.5),i=Math.max(t?.relief??0,(n?.surface?.microRelief??0)*.7),a=Math.max(t?.film??0,n?.iridescence??0),o=Math.max(t?.grain??0,n?.sediment??0),s=n?.atmosphere?.emission??0;return{gloss:r,relief:i,film:a,grain:o,emission:s,emissionColor:n?.atmosphere?.emissionColor??[0,0,0],shaded:r+i+a+o+s>0}}function wy(e,t,n,r,i,a){if(!e.shaded)return t;let o=Math.max(0,-i*.55-a*.8)*e.gloss*82,s=Math.sin(n*.16+r*.08)*e.relief*8,c=Math.sin(n*.095+r*.13+i*3)*e.film*27,l=Math.sin(n*127.1+r*311.7)*43758.5453%1*e.grain*12,u=o+s+l,d=e.emission*.22,f=(t,n,r)=>Math.max(0,Math.min(255,t+u+r+e.emissionColor[n]*d));return[f(t[0],0,c),f(t[1],1,-c*.65),f(t[2],2,c*.8)]}var H=(e,t,n)=>Math.max(t,Math.min(n,e)),Ty=new Uint8Array(new Uint32Array([1]).buffer)[0]===1,Ey=(e,t,n)=>e+(t-e)*n,Dy=[[1,0],[-1,0],[0,1],[0,-1]],Oy=[[.7,.7],[-.7,.7],[.7,-.7],[-.7,-.7]],ky=class{kind;width;height;profile;canvas=document.createElement(`canvas`);splatterCanvas=null;splatterBounds=null;splatterDirty=!1;material;authored;deposited;pigment;colorPixels;basePixels;outline;spring;velocity;drops=[];burnDecay=new Float32Array;revision=0;pulled=!1;maxOutline=0;presented=-1;active=null;activeCells=new Set;outlineCells=new Set;wetBounds=null;renderedBounds=null;dirtyBounds=null;fullDirty=!0;color;appearance;cellSizePx=1;listeners=new Set;constructor(e,t,n,r,i){this.kind=e,this.width=t,this.height=n,this.profile=i,this.color=[...r],this.appearance=Cy(e);let a=T[e];this.material={thickness:a.thickness,deformation:i?.deformation??a.deformation,alpha:i?.opacity??a.alpha};let o=t*n;this.authored=new Uint8Array(o),this.deposited=new Uint8Array(o),this.pigment=new Float32Array(o*4),this.colorPixels=new Uint8Array(o*3),this.basePixels=Ty&&!this.appearance.shaded?new Uint32Array(o):null,this.outline=new Float32Array(o*2),this.spring=new Float32Array(o*2),this.velocity=new Float32Array(o*2),this.canvas.width=t,this.canvas.height=n}get shapeRevision(){return this.revision}get displaced(){return this.pulled||this.active!==null}get moving(){return this.active!==null}get hasSplatter(){return this.drops.length>0}get hasDeposits(){return this.deposited.some(e=>e>0)}get managedBytes(){return this.authored.byteLength+this.deposited.byteLength+this.pigment.byteLength+this.colorPixels.byteLength+(this.basePixels?.byteLength??0)+this.outline.byteLength+this.spring.byteLength+this.velocity.byteLength+this.canvas.width*this.canvas.height*4+(this.splatterCanvas?this.splatterCanvas.width*this.splatterCanvas.height*4:0)}setCellSize(e){this.cellSizePx=Math.max(.01,e)}configure(e,t){this.color=[...e],this.material.deformation=t?.deformation??T[this.kind].deformation;let n=t?.opacity??T[this.kind].alpha;n!==this.material.alpha&&(this.material.alpha=n,this.rebuildBasePixels()),this.changed()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}changed(e){e?this.fullDirty||(this.dirtyBounds=this.dirtyBounds?{left:Math.min(this.dirtyBounds.left,e.left),top:Math.min(this.dirtyBounds.top,e.top),right:Math.max(this.dirtyBounds.right,e.right),bottom:Math.max(this.dirtyBounds.bottom,e.bottom)}:{...e}):(this.fullDirty=!0,this.dirtyBounds=null),this.revision++;for(let e of this.listeners)e()}alphaAt(e){return Math.max(this.authored[e],this.deposited[e])}refreshBasePixel(e){if(!this.basePixels)return;let t=this.alphaAt(e),n=e*3;this.basePixels[e]=Math.round(t*this.material.alpha)<<24|this.colorPixels[n+2]<<16|this.colorPixels[n+1]<<8|this.colorPixels[n]}rebuildBasePixels(){if(this.basePixels)for(let e=0;e<this.width*this.height;e++)this.refreshBasePixel(e)}wetAt(e,t){let n=Math.floor(e),r=Math.floor(t);return n>=0&&r>=0&&n<this.width&&r<this.height&&this.alphaAt(r*this.width+n)>=24}includeWetBounds(e){this.wetBounds=this.wetBounds?{left:Math.min(this.wetBounds.left,e.left),top:Math.min(this.wetBounds.top,e.top),right:Math.max(this.wetBounds.right,e.right),bottom:Math.max(this.wetBounds.bottom,e.bottom)}:e}rebuildWetBounds(){let e=this.width,t=this.height,n=-1,r=-1;for(let i=0;i<this.height;i++)for(let a=0;a<this.width;a++)this.alphaAt(i*this.width+a)&&(e=Math.min(e,a),t=Math.min(t,i),n=Math.max(n,a),r=Math.max(r,i));this.wetBounds=n>=e?{left:e,top:t,right:n,bottom:r}:null}componentAt(e,t,n,r){let i=H(t.x-.5,0,this.width-1),a=H(t.y-.5,0,this.height-1),o=Math.floor(i),s=Math.floor(a),c=Math.min(this.width-1,o+1),l=Math.min(this.height-1,s+1),u=i-o,d=a-s,f=e[(s*this.width+o)*r+n],p=e[(s*this.width+c)*r+n],m=e[(l*this.width+o)*r+n],h=e[(l*this.width+c)*r+n];return Ey(Ey(f,p,u),Ey(m,h,u),d)}offsetAt(e,t=!0){return{x:this.componentAt(this.spring,e,0,2)+(t?this.componentAt(this.outline,e,0,2):0),y:this.componentAt(this.spring,e,1,2)+(t?this.componentAt(this.outline,e,1,2):0)}}sourcePoint(e){let t=this.offsetAt(e);return{x:e.x-t.x,y:e.y-t.y}}rawCoverage(e){return this.rawCoverageXY(e.x,e.y)}rawCoverageXY(e,t){if(e<0||t<0||e>=this.width||t>=this.height)return 0;let n=H(e-.5,0,this.width-1),r=H(t-.5,0,this.height-1),i=Math.floor(n),a=Math.floor(r),o=Math.min(this.width-1,i+1),s=Math.min(this.height-1,a+1),c=n-i,l=r-a;return Ey(Ey(this.alphaAt(a*this.width+i),this.alphaAt(a*this.width+o),c),Ey(this.alphaAt(s*this.width+i),this.alphaAt(s*this.width+o),c),l)/255}densityAt(e){return e.x<0||e.y<0||e.x>=this.width||e.y>=this.height?0:this.rawCoverage(this.sourcePoint(e))}colorAt(e){let t=this.sourcePoint(e),n=H(Math.floor(t.y),0,this.height-1)*this.width+H(Math.floor(t.x),0,this.width-1);return this.alphaAt(n)?[this.colorPixels[n*3],this.colorPixels[n*3+1],this.colorPixels[n*3+2]]:this.color}captureFuel(){let e=new Float32Array(this.width*this.height);for(let t=0;t<this.height;t++)for(let n=0;n<this.width;n++)e[t*this.width+n]=this.densityAt({x:n+.5,y:t+.5});return e}inspectState(){let e=this.captureFuel(),t=0,n=1/0,r=0;for(let i of e)t+=i,n=Math.min(n,i),r=Math.max(r,i);return{volume:t,minimum:n,maximum:r,finite:Number.isFinite(t)}}setPigment(e,t,n,r=xy(t)){let i=e*4;if(n>=1||!this.alphaAt(e))for(let e=0;e<4;e++)this.pigment[i+e]=r[e];else for(let e=0;e<4;e++)this.pigment[i+e]=Ey(this.pigment[i+e],r[e],n);let a=Sy([this.pigment[i],this.pigment[i+1],this.pigment[i+2],this.pigment[i+3]]);for(let t=0;t<3;t++)this.colorPixels[e*3+t]=Math.round(a[t]);this.refreshBasePixel(e)}seedMask(e,t,n,r=this.color){if(e.length!==this.width*this.height)throw RangeError(`Liquid seed must match the field resolution`);this.authored.set(e);let i=xy(r);for(let t=0;t<e.length;t++)e[t]&&!this.deposited[t]&&(this.pigment.set(i,t*4),this.colorPixels.set(r,t*3));this.rebuildBasePixels(),this.rebuildWetBounds(),this.changed()}removeSeed(){this.authored.fill(0),this.rebuildBasePixels(),this.rebuildWetBounds(),this.changed()}pour(e,t,n,r,i,a=this.color,o=n,s=r){if(!(e>0))return;n=this.sourcePoint(n),o=this.sourcePoint(o);let c=Math.max(0,Math.floor(Math.min(o.x-s,n.x-r)-2)),l=Math.min(this.width-1,Math.ceil(Math.max(o.x+s,n.x+r)+2)),u=Math.max(0,Math.floor(Math.min(o.y-s,n.y-r)-2)),d=Math.min(this.height-1,Math.ceil(Math.max(o.y+s,n.y+r)+2)),f=n.x-o.x,p=n.y-o.y,m=Math.max(1e-6,f*f+p*p),h=xy(a),g=!1;for(let t=u;t<=d;t++)for(let i=c;i<=l;i++){let c=i+.5,l=t+.5,u=H(((c-o.x)*f+(l-o.y)*p)/m,0,1),d=Ey(o.x,n.x,u),_=Ey(o.y,n.y,u),v=Ey(s,r,u),y=Math.hypot(c-d,l-_),b=Math.round(H(v+.5-y,0,1)*255);if(!b)continue;let x=t*this.width+i,S=this.alphaAt(x),C=this.colorPixels[x*3]===a[0]&&this.colorPixels[x*3+1]===a[1]&&this.colorPixels[x*3+2]===a[2];b<=this.deposited[x]&&S&&C||(!S||C?(this.pigment.set(h,x*4),this.colorPixels.set(a,x*3)):this.setPigment(x,a,H(e*b/(S*2),0,1),h),this.deposited[x]=Math.max(this.deposited[x],b),this.refreshBasePixel(x),g=!0)}g&&(this.includeWetBounds({left:c,top:u,right:l,bottom:d}),this.changed())}transferPigment(e,t,n,r,i){if(!(i>0))return;let a=xy(r),o=this.width,s=this.height,c=-1,l=-1;if(this.eachContactPixel(e,t,n,(e,t,n,u)=>{if(!this.alphaAt(e))return;this.setPigment(e,r,H(t*i,0,1),a);let d=Math.floor(n),f=Math.floor(u);o=Math.min(o,d),s=Math.min(s,f),c=Math.max(c,d),l=Math.max(l,f)},Math.max(2,n*1.1)),c>=o){let e=Math.ceil(this.maxOutline+8/this.cellSizePx)+2;this.changed({left:o-e,top:s-e,right:c+e,bottom:l+e})}}eachContactPixel(e,t,n,r,i=Math.max(2,n*1.8,(24*this.material.deformation+2)/this.cellSizePx)){let a=this.wetBounds,o=i+(this.pulled||this.active?8/this.cellSizePx:0),s=Math.max(0,Math.floor(Math.min(e.x,t.x)-i),a?Math.floor(a.left-o):0),c=Math.min(this.width-1,Math.ceil(Math.max(e.x,t.x)+i),a?Math.ceil(a.right+o):this.width-1),l=Math.max(0,Math.floor(Math.min(e.y,t.y)-i),a?Math.floor(a.top-o):0),u=Math.min(this.height-1,Math.ceil(Math.max(e.y,t.y)+i),a?Math.ceil(a.bottom+o):this.height-1),d=t.x-e.x,f=t.y-e.y,p=Math.max(1e-6,d*d+f*f),m=i*i;for(let t=l;t<=u;t++)for(let n=s;n<=c;n++){let a=n+.5,o=t+.5,s=H(((a-e.x)*d+(o-e.y)*f)/p,0,1),c=a-e.x-d*s,l=o-e.y-f*s,u=c*c+l*l;if(u>=m)continue;let h=1-Math.sqrt(u)/i;r(t*this.width+n,h*h,a,o)}return{left:s,top:l,right:c,bottom:u}}drag(e,t,n,r=5.5,i=0){if(this.material.deformation===0)return;let a=t.x-e.x,o=t.y-e.y;if(Math.hypot(a,o)<.5)return;let s=Math.max(2,r*1.8,(24*this.material.deformation+2)/this.cellSizePx),c=Math.max(2,r*1.8),l=Math.hypot(a,o),u=a/l,d=o/l,f=Math.max(2,r*1.25),p=!1,m=this.width,h=this.height,g=-1,_=-1,v=this.eachContactPixel(e,t,r,(e,t,n,r)=>{let i=Math.floor(n),c=Math.floor(r);if(!this.wetAt(n-u*f,r-d*f)||this.wetAt(n+u*f,r+d*f))return;let l=this.alphaAt(e)>=24,v=0;for(let[e,t]of Dy)this.wetAt(n+e*s*.35,r+t*s*.35)===l?this.wetAt(n+e*s*.7,r+t*s*.7)===l?this.wetAt(n+e*s,r+t*s)!==l&&(v=Math.max(v,.12)):v=Math.max(v,.3):v=Math.max(v,.65);if(!l&&v===0){for(let[e,t]of Oy)if(this.wetAt(n+e*s,r+t*s)){v=.12;break}}if(!l&&v===0)return;let y=this.material.deformation/(.65+this.material.thickness*.7),b=e*2;if(this.velocity[b]=H(this.velocity[b]+a*t*18*y,-90,90),this.velocity[b+1]=H(this.velocity[b+1]+o*t*18*y,-90,90),this.activeCells.add(e),v>0){let n=24*this.material.deformation/this.cellSizePx;this.outline[b]=H(this.outline[b]+a*t*y*v*.48,-n,n),this.outline[b+1]=H(this.outline[b+1]+o*t*y*v*.48,-n,n),this.maxOutline=Math.max(this.maxOutline,Math.abs(this.outline[b]),Math.abs(this.outline[b+1])),this.pulled=!0,this.outlineCells.add(e)}p=!0,m=Math.min(m,i),h=Math.min(h,c),g=Math.max(g,i),_=Math.max(_,c)},c);p&&(this.active=this.active?{left:Math.min(v.left,this.active.left),top:Math.min(v.top,this.active.top),right:Math.max(v.right,this.active.right),bottom:Math.max(v.bottom,this.active.bottom)}:v,this.changed({left:m,top:h,right:g,bottom:_}))}step(e,t=0,n=[],r,i=e){let a=H(e,0,1/30);if(this.activeCells.size){let e=Math.exp(-(7+this.material.thickness*5)*a),t=this.width,n=this.height,r=-1,i=-1;for(let o of this.activeCells){let s=o%this.width,c=Math.floor(o/this.width),l=0;for(let t=0;t<2;t++){let n=o*2+t,r=this.spring[n],i=(this.velocity[n]-r*95*a)*e;this.velocity[n]=i,this.spring[n]=H(r+i*a,-8/this.cellSizePx,8/this.cellSizePx),l=Math.max(l,Math.abs(this.spring[n]),Math.abs(i)*.08)}if(t=Math.min(t,s),n=Math.min(n,c),r=Math.max(r,s),i=Math.max(i,c),l<.012){let e=o*2;this.spring[e]=this.spring[e+1]=0,this.velocity[e]=this.velocity[e+1]=0,this.activeCells.delete(o)}}r>=t&&this.changed({left:t,top:n,right:r,bottom:i}),this.active=this.activeCells.size?{left:t,top:n,right:r,bottom:i}:null}if(t<=0&&!r)return;let o=this.wetBounds;if(!o)return;let s=r?.size??0;if(r){this.burnDecay.length!==r.rates.length&&(this.burnDecay=new Float32Array(r.rates.length));for(let e=0;e<r.rates.length;e++){let n=t+r.rates[e];this.burnDecay[e]=n>0?Math.exp(-n*i):1}}let c=t>0?Math.exp(-t*i):1,l=this.width===s*4&&this.height===s*4,u=this.width,d=this.height,f=-1,p=-1;for(let e=Math.max(0,o.top);e<=Math.min(this.height-1,o.bottom);e++){let t=r?(l?e>>2:Math.floor(e*s/this.height))*s:0;for(let n=Math.max(0,o.left);n<=Math.min(this.width-1,o.right);n++){let i=e*this.width+n;if(!this.authored[i]&&!this.deposited[i])continue;let a=i*2,o=c;if(r){let r=this.spring[a]+this.outline[a],i=this.spring[a+1]+this.outline[a+1],c=r===0&&i===0?t+(l?n>>2:Math.floor(n*s/this.width)):H(Math.floor((e+i)*s/this.height),0,s-1)*s+H(Math.floor((n+r)*s/this.width),0,s-1);o=this.burnDecay[c]}if(o>=1)continue;let m=Math.round(this.authored[i]*o),h=Math.round(this.deposited[i]*o);(m!==this.authored[i]||h!==this.deposited[i])&&(this.authored[i]=m,this.deposited[i]=h,this.refreshBasePixel(i),u=Math.min(u,n),d=Math.min(d,e),f=Math.max(f,n),p=Math.max(p,e))}}f>=u&&this.changed({left:u,top:d,right:f,bottom:p})}mayIntersect(e,t,n=1){let r=Math.max(1,Math.ceil(Math.hypot(t.x-e.x,t.y-e.y)/Math.max(1,n)));for(let n=0;n<=r;n++){let i=n/r,a={x:Ey(e.x,t.x,i),y:Ey(e.y,t.y,i)};if(this.densityAt(a)>.02)return!0}return!1}spray(e,t,n,r,i=1,a=this.color){let o=Math.min(12,Math.ceil(r*2));for(let r of Sa(e,t,Math.max(1,n*.35),o,i,this.material.thickness))this.drops.push({point:{x:r.x,y:r.y},radius:Math.max(.5,r.radius),color:a,opacity:this.material.alpha*r.opacity,age:0});this.drops.length>256&&this.drops.splice(0,this.drops.length-256),this.splatterDirty=!0}grow(e){if(e<=1)return this.width;let t=this.width,n=Math.ceil(this.width*e/2)*2,r=Math.ceil(this.height*e/2)*2,i=Math.floor((n-this.width)/2),a=Math.floor((r-this.height)/2),o=(e,t,r)=>{for(let o=0;o<this.height;o++)r.set(e.subarray(o*this.width*t,(o+1)*this.width*t),((o+a)*n+i)*t);return r};this.authored=o(this.authored,1,new Uint8Array(n*r)),this.deposited=o(this.deposited,1,new Uint8Array(n*r)),this.pigment=o(this.pigment,4,new Float32Array(n*r*4)),this.colorPixels=o(this.colorPixels,3,new Uint8Array(n*r*3)),this.basePixels&&=o(this.basePixels,1,new Uint32Array(n*r)),this.outline=o(this.outline,2,new Float32Array(n*r*2)),this.spring=o(this.spring,2,new Float32Array(n*r*2)),this.velocity=o(this.velocity,2,new Float32Array(n*r*2)),this.activeCells=new Set([...this.activeCells].map(e=>(Math.floor(e/t)+a)*n+e%t+i)),this.outlineCells=new Set([...this.outlineCells].map(e=>(Math.floor(e/t)+a)*n+e%t+i));for(let e of this.drops)e.point.x+=i,e.point.y+=a;return this.splatterDirty=!0,this.active&&(this.active.left+=i,this.active.right+=i,this.active.top+=a,this.active.bottom+=a),this.wetBounds&&(this.wetBounds.left+=i,this.wetBounds.right+=i,this.wetBounds.top+=a,this.wetBounds.bottom+=a),this.width=n,this.height=r,this.canvas.width=n,this.canvas.height=r,this.renderedBounds=null,this.changed(),n}setColor(e){this.color=[...e],this.changed()}reset(){this.authored.fill(0),this.deposited.fill(0),this.outline.fill(0),this.spring.fill(0),this.velocity.fill(0),this.drops=[],this.splatterCanvas=null,this.splatterBounds=null,this.splatterDirty=!1,this.active=null,this.activeCells.clear(),this.outlineCells.clear(),this.basePixels?.fill(0),this.wetBounds=null,this.pulled=!1,this.maxOutline=0,this.changed()}captureState(){return{width:this.width,height:this.height,cellSizePx:this.cellSizePx,active:this.active?{...this.active}:null,pulled:this.pulled,authored:this.authored.slice(),deposited:this.deposited.slice(),pigment:this.pigment.slice(),colorPixels:this.colorPixels.slice(),outline:this.outline.slice(),spring:this.spring.slice(),velocity:this.velocity.slice(),drops:this.drops.map(e=>({...e,point:{...e.point}})),color:[...this.color],dispose(){}}}restoreState(e){this.width=e.width,this.height=e.height,this.canvas.width=e.width,this.canvas.height=e.height,this.cellSizePx=e.cellSizePx,this.active=e.active?{...e.active}:null,this.pulled=e.pulled,this.authored=e.authored.slice(),this.deposited=e.deposited.slice(),this.pigment=e.pigment.slice(),this.colorPixels=e.colorPixels.slice(),this.basePixels=Ty&&!this.appearance.shaded?new Uint32Array(this.width*this.height):null,this.outline=e.outline.slice(),this.outlineCells=new Set;for(let e=0;e<this.width*this.height;e++)(this.outline[e*2]||this.outline[e*2+1])&&this.outlineCells.add(e);if(this.maxOutline=this.outline.reduce((e,t)=>Math.max(e,Math.abs(t)),0),this.spring=e.spring.slice(),this.velocity=e.velocity.slice(),this.activeCells=new Set,this.active)for(let e=this.active.top;e<=this.active.bottom;e++)for(let t=this.active.left;t<=this.active.right;t++){let n=e*this.width+t,r=n*2;(this.spring[r]!==0||this.spring[r+1]!==0||this.velocity[r]!==0||this.velocity[r+1]!==0)&&this.activeCells.add(n)}this.activeCells.size||(this.active=null),this.drops=e.drops.map(e=>({...e,point:{...e.point}})),this.splatterDirty=!0,this.color=[...e.color],this.rebuildBasePixels(),this.rebuildWetBounds(),this.renderedBounds=null,this.changed()}dispose(){this.listeners.clear(),this.canvas.remove(),this.splatterCanvas?.remove()}paintUnshaded(e,t){let n=this.basePixels,r=new Uint32Array(e.data.buffer),i=t.right-t.left+1;for(let e=t.top;e<=t.bottom;e++)r.set(n.subarray(e*this.width+t.left,e*this.width+t.right+1),(e-t.top)*i);let a=0,o=e=>{let n=e%this.width,o=Math.floor(e/this.width);if(n<t.left||n>t.right||o<t.top||o>t.bottom)return;let s=e*2,c=this.spring[s]+this.outline[s],l=this.spring[s+1]+this.outline[s+1];if(c===0&&l===0)return;a++;let u=n+.5-c,d=o+.5-l,f=this.rawCoverageXY(u,d),p=(o-t.top)*i+n-t.left;if(f<=0){r[p]=0;return}let m=(H(Math.floor(d),0,this.height-1)*this.width+H(Math.floor(u),0,this.width-1))*3;r[p]=Math.round(f*this.material.alpha*255)<<24|this.colorPixels[m+2]<<16|this.colorPixels[m+1]<<8|this.colorPixels[m]};for(let e of this.outlineCells)o(e);for(let e of this.activeCells)this.outlineCells.has(e)||o(e);return i*(t.bottom-t.top+1)-a}present(){if(this.presented!==this.revision){performance.now();let e=this.canvas.getContext(`2d`),t=this.pulled||this.active?Math.ceil(this.maxOutline+8/this.cellSizePx)+2:2,n=this.wetBounds,r=n?{left:Math.max(0,n.left-t),top:Math.max(0,n.top-t),right:Math.min(this.width-1,n.right+t),bottom:Math.min(this.height-1,n.bottom+t)}:null,i=this.renderedBounds,a=this.fullDirty?i&&r?{left:Math.min(i.left,r.left),top:Math.min(i.top,r.top),right:Math.max(i.right,r.right),bottom:Math.max(i.bottom,r.bottom)}:i??r:this.dirtyBounds;a&&e.clearRect(a.left,a.top,a.right-a.left+1,a.bottom-a.top+1);let o=r&&a?{left:Math.max(0,r.left,a.left),top:Math.max(0,r.top,a.top),right:Math.min(this.width-1,r.right,a.right),bottom:Math.min(this.height-1,r.bottom,a.bottom)}:null;if(o&&o.right>=o.left&&o.bottom>=o.top){let t=o.right-o.left+1,n=o.bottom-o.top+1,r=e.createImageData(t,n),i=Ty&&!this.appearance.shaded?new Uint32Array(r.data.buffer):null;performance.now();let a=this.basePixels?this.paintUnshaded(r,o):0;if(!this.basePixels)for(let e=o.top;e<=o.bottom;e++)for(let n=o.left;n<=o.right;n++){let s=(e*this.width+n)*2,c=this.spring[s]+this.outline[s],l=this.spring[s+1]+this.outline[s+1],u=c===0&&l===0;u&&a++;let d=((e-o.top)*t+n-o.left)*4;if(u&&i){let t=e*this.width+n,r=this.alphaAt(t);if(!r)continue;let a=t*3;i[d/4]=Math.round(r*this.material.alpha)<<24|this.colorPixels[a+2]<<16|this.colorPixels[a+1]<<8|this.colorPixels[a];continue}let f=n+.5-c,p=e+.5-l,m=u?this.alphaAt(e*this.width+n)/255:this.rawCoverageXY(f,p);if(m<=0)continue;let h=u?e*this.width+n:H(Math.floor(p),0,this.height-1)*this.width+H(Math.floor(f),0,this.width-1);if(this.appearance.shaded){let t=[this.colorPixels[h*3],this.colorPixels[h*3+1],this.colorPixels[h*3+2]],i=wy(this.appearance,t,n,e,this.rawCoverageXY(f+1,p)-this.rawCoverageXY(f-1,p),this.rawCoverageXY(f,p+1)-this.rawCoverageXY(f,p-1));for(let e=0;e<3;e++)r.data[d+e]=i[e]}else{if(i){i[d/4]=Math.round(m*this.material.alpha*255)<<24|this.colorPixels[h*3+2]<<16|this.colorPixels[h*3+1]<<8|this.colorPixels[h*3];continue}r.data[d]=this.colorPixels[h*3],r.data[d+1]=this.colorPixels[h*3+1],r.data[d+2]=this.colorPixels[h*3+2]}r.data[d+3]=Math.round(m*this.material.alpha*255)}t*n,performance.now(),e.putImageData(r,o.left,o.top)}this.renderedBounds=r,this.fullDirty=!1,this.dirtyBounds=null,this.presented=this.revision}}draw(e){if(this.present(),this.renderedBounds){let{left:t,top:n,right:r,bottom:i}=this.renderedBounds,a=r-t+1,o=i-n+1;e.drawImage(this.canvas,t,n,a,o,t,n,a,o)}this.drawSplatter(e)}drawSplatter(e){if(this.drops.length){if(this.splatterDirty||!this.splatterCanvas||!this.splatterBounds){let e={left:Math.floor(Math.min(...this.drops.map(e=>e.point.x-e.radius))),top:Math.floor(Math.min(...this.drops.map(e=>e.point.y-e.radius))),right:Math.ceil(Math.max(...this.drops.map(e=>e.point.x+e.radius))),bottom:Math.ceil(Math.max(...this.drops.map(e=>e.point.y+e.radius)))},t=this.splatterCanvas??document.createElement(`canvas`),n=Math.max(1,e.right-e.left),r=Math.max(1,e.bottom-e.top);t.width!==n&&(t.width=n),t.height!==r&&(t.height=r);let i=t.getContext(`2d`);i.clearRect(0,0,n,r);for(let t of this.drops)i.globalAlpha=t.opacity,i.fillStyle=`rgb(${t.color.join(` `)})`,i.beginPath(),i.arc(t.point.x-e.left,t.point.y-e.top,t.radius,0,Math.PI*2),i.fill();this.splatterCanvas=t,this.splatterBounds=e,this.splatterDirty=!1}e.drawImage(this.splatterCanvas,this.splatterBounds.left,this.splatterBounds.top)}}};function Ay(e,t,n){let r=Math.ceil(t/4),i=new Float32Array(r*r),a=n.width/r;for(let n=0;n<t;n++)for(let a=0;a<t;a++){let o=Math.floor(n/4)*r+Math.floor(a/4);i[o]=Math.max(i[o],e[n*t+a])}return{size:r,fuel:i,spacing:a,point:e=>({x:n.x+(e%r+.5)*a,y:n.y+(Math.floor(e/r)+.5)*a})}}function jy(e){let t=e.flatMap(e=>Array.from(e.fuel,(t,n)=>({field:e,i:n,fuel:t,point:e.point(n)})).filter(e=>e.fuel>=.035)),n=Math.max(1,...e.map(e=>e.spacing))*2,r=e=>`${Math.floor(e.x/n)},${Math.floor(e.y/n)}`,i=new Map;t.forEach((e,t)=>{let n=r(e.point),a=i.get(n)??[];a.push(t),i.set(n,a)});let a=function*(e,t){let r=Math.ceil(t/n),a=Math.floor(e.x/n),o=Math.floor(e.y/n);for(let e=-r;e<=r;e++)for(let t=-r;t<=r;t++)for(let n of i.get(`${a+e},${o+t}`)??[])yield n};return{nodes:t,neighbors:function*(e){let r=t[e];for(let e of a(r.point,n)){let n=t[e],i=Math.hypot(r.point.x-n.point.x,r.point.y-n.point.y);i<=(r.field.spacing+n.field.spacing)*.74&&(yield{next:e,distance:i})}},nearby:a,cellSize:n}}function My(e,t,n=0){let r=jy(e),i=new Int32Array(r.nodes.length).fill(-2),a=[];for(let e of t)for(let t of r.nearby(e,n+r.cellSize)){let o=r.nodes[t];i[t]===-2&&Math.hypot(o.point.x-e.x,o.point.y-e.y)<=n+o.field.spacing*.75&&(i[t]=-1,a.push(t))}for(let e=0;e<a.length;e++)for(let{next:t}of r.neighbors(a[e]))i[t]===-2&&(i[t]=a[e],a.push(t));let o=(e,t)=>{let n=-1,a=1/0;for(let o of r.nearby(e,t+r.cellSize)){if(i[o]===-2)continue;let s=r.nodes[o],c=Math.hypot(s.point.x-e.x,s.point.y-e.y);c<=t+s.field.spacing*.75&&c<a&&(n=o,a=c)}return n};return{points:a.map(e=>r.nodes[e].point),contains:(e,t=0)=>o(e,t)>=0,intersects:(e,t=0)=>{let n={x:e.x+e.width/2,y:e.y+e.height/2};for(let a of r.nearby(n,Math.hypot(e.width,e.height)/2+t+r.cellSize)){if(i[a]===-2)continue;let n=r.nodes[a],o=n.point,s=t+n.field.spacing*.5;if(o.x>=e.x-s&&o.x<=e.x+e.width+s&&o.y>=e.y-s&&o.y<=e.y+e.height+s)return!0}return!1},pathTo:(e,t=0)=>{let n=o(e,t),a=[];for(;n>=0;)a.push(r.nodes[n].point),n=i[n];return a.reverse()}}}var Ny=class{density;resolution;rect;lifetime;spreadMps;pixelsPerMeter;size;fuel;starts;ends;rates;alpha;baseAlpha;light;pixelsByCell;revision=0;complete=!1;lit=!1;constructor(e,t,n,r,i,a){this.density=e,this.resolution=t,this.rect=n,this.lifetime=r,this.spreadMps=i,this.pixelsPerMeter=a;let o=Ay(e,t,n);this.size=o.size,this.fuel=o.fuel,this.starts=new Float64Array(this.fuel.length).fill(1/0),this.ends=new Float64Array(this.fuel.length).fill(1/0),this.rates=new Float32Array(this.fuel.length),this.alpha=new Uint8Array(e.length),this.baseAlpha=new Uint8Array(e.length),this.light=new Float32Array(this.fuel.length);let s=Array.from({length:this.fuel.length},()=>[]);for(let n=0;n<t;n++)for(let r=0;r<t;r++){let i=n*t+r;e[i]<=.035||(this.baseAlpha[i]=Math.round(255*Math.min(1,(e[i]-.035)/.12)),s[Math.floor(n/4)*this.size+Math.floor(r/4)].push(i))}this.pixelsByCell=s.map(e=>e.length?Uint32Array.from(e):void 0)}point(e){return{x:this.rect.x+(e%this.size+.5)*this.spacing,y:this.rect.y+(Math.floor(e/this.size)+.5)*this.spacing}}get spacing(){return this.rect.width/this.size}get managedBytes(){return[this.density,this.fuel,this.starts,this.ends,this.rates,this.alpha,this.baseAlpha,this.light].reduce((e,t)=>e+t.byteLength,0)+this.pixelsByCell.reduce((e,t)=>e+(t?.byteLength??0),0)}indexAt(e){let t=Math.floor((e.x-this.rect.x)/this.spacing),n=Math.floor((e.y-this.rect.y)/this.spacing);return t<0||n<0||t>=this.size||n>=this.size?-1:n*this.size+t}inherit(e,t){for(let n=0;n<this.fuel.length;n++){let r=e.indexAt(this.point(n));if(r>=0&&Number.isFinite(e.starts[r])&&e.ends[r]>t){this.starts[n]=Math.max(t,e.starts[r]);let i=Math.min(1,(e.ends[r]-t)/Math.max(.01,e.ends[r]-e.starts[r])),a=this.fuel[n]>e.fuel[r]*i**2+.05;this.ends[n]=a?Math.max(e.ends[r],t+this.lifetime):e.ends[r]}}}update(e,t){let n=!1,r=this.light,i=!1;for(let a=0;a<this.fuel.length;a++){this.rates[a]=0;let o=this.starts[a],s=this.ends[a],c=r[a],l=0;if(Number.isFinite(o)&&e>=o){let r=Math.max(.01,s-o),i=Math.max(0,Math.min(1,(e-t-o)/r)),c=Math.max(0,Math.min(1,(e-o)/r)),u=Math.max(1e-6,(1-i)**2),d=Math.max(1e-6,(1-c)**2);this.rates[a]=Math.log(u/d)/Math.max(t,1e-4),e<s&&(n=!0,l=Math.min(1,(e-o)/.15)*Math.min(1,(s-e)/Math.min(2,r*.3)))}if(r[a]=l,c<=0&&l<=0)continue;let u=this.pixelsByCell[a];if(u)for(let e of u){let t=Math.round(this.baseAlpha[e]*l);this.alpha[e]=t,i||=t>0}}return this.lit=i,this.revision++,this.complete=this.starts.some(Number.isFinite)&&this.ends.every((t,n)=>this.fuel[n]<.035||t<=e),n}};function Py(e,t,n,r,i=[]){let{nodes:a,neighbors:o,nearby:s,cellSize:c}=jy(e);if(!a.length)return;let l=new Set;for(let e of[t,...i])for(let t of s(e,n+c)){let r=a[t];Math.hypot(r.point.x-e.x,r.point.y-e.y)<=n+r.field.spacing*.75&&l.add(t)}let u=new Float64Array(a.length).fill(1/0),d=[],f=(e,t)=>{if(t>=u[e])return;u[e]=t;let n=d.length;for(d.push({index:e,time:t});n>0;){let e=n-1>>1;if(d[e].time<=t)break;d[n]=d[e],n=e}d[n]={index:e,time:t}};for(a.forEach((e,t)=>{e.field.ends[e.i]<=r||(l.has(t)?f(t,r):Number.isFinite(e.field.starts[e.i])&&e.field.ends[e.i]>r&&f(t,Math.max(r,e.field.starts[e.i])))});d.length;){let e=d[0],t=d.pop();if(d.length){let e=0;for(;e*2+1<d.length;){let n=e*2+1;if(n+1<d.length&&d[n+1].time<d[n].time&&n++,d[n].time>=t.time)break;d[e]=d[n],e=n}d[e]=t}if(e.time===u[e.index])for(let{next:t,distance:n}of o(e.index)){let i=a[t];i.field.ends[i.i]<=r||f(t,e.time+n/Math.max(1,i.field.pixelsPerMeter)/i.field.spreadMps)}}a.forEach((e,t)=>{u[t]>=e.field.starts[e.i]||(e.field.starts[e.i]=u[t],e.field.ends[e.i]=u[t]+e.field.lifetime)})}function Fy(e){let t=e.extentM*e.pixelsPerMeter;return{x:e.center.x-t/2,y:e.center.y-t/2,width:t,height:t}}function Iy(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}function Ly(e,t,n){return t.x>=e.x-n&&t.x<=e.x+e.width+n&&t.y>=e.y-n&&t.y<=e.y+e.height+n}function Ry(e,t,n=0){if(!e.length||!t.length)return[];let r=e.map(Fy),i=new Uint8Array(e.length),a=[];for(let o=0;o<e.length;o++)t.some(e=>Ly(r[o],e,n))&&(i[o]=1,a.push(o));for(let t=0;t<a.length;t++){let n=r[a[t]];for(let t=0;t<e.length;t++)!i[t]&&Iy(n,r[t])&&(i[t]=1,a.push(t))}return a.map(t=>e[t])}function zy(e,t,n=0){return My(Ry(e.filter(e=>T[e.kind].conductive),t,n).map(e=>Ay(e.fluid.captureFuel(),e.resolution,Fy(e))),t,n)}function By(e,t,n){let r=[];for(let i of e){let e=i.fire;if(!e||!T[i.kind].burnable)continue;let a=e.size,o=Math.max(1,Math.ceil(n/e.spacing)),s=(n,r)=>{if(n<0||r<0||n>=a||r>=a)return!1;let i=r*a+n;return e.fuel[i]>=.035&&e.starts[i]<=t&&e.ends[i]>t};for(let t=0;t<a;t++)for(let n=0;n<a;n++)s(n,t)&&(s(n-1,t)&&s(n+1,t)&&s(n,t-1)&&s(n,t+1)&&(n%o!==0||t%o!==0)||r.push(e.point(t*a+n)))}return r}function Vy(e,t,n,r){let i=0,a=0,o=0,s=new Set,c=null,l=[0,0,0],u=[],d=[];for(let f of e){let e=n(f,t);if(e>.12&&(c=f.id),e>.1&&s.add(f.kind),ut(f.kind)===`water`&&!ft(f.kind)||e<.04)continue;let p=f.fluid.colorAt?.(r(f,t))??f.color;d.push({id:`liquid:${f.id}`,color:`rgb(${p.map(e=>Math.round(e)).join(` `)})`,opacity:Math.min(1,e),distanceM:f.elementProfile?.distanceM??(ft(f.kind)?mt(f.kind).carryM:T[f.kind].treadDistanceM),material:mt(f.kind)}),u.push(f.id);for(let t=0;t<3;t++)l[t]+=p[t]*e;i+=e,a=1-(1-a)*(1-e),o=Math.max(o,f.elementProfile?.distanceM??T[f.kind].treadDistanceM)}let f=i?{id:`liquid:${u.join(`,`)}`,color:`rgb(${l.map(e=>Math.round(e/i)).join(` `)})`,opacity:a,distanceM:o}:null;return{materials:[...s],paint:f,paints:d,splashFieldId:c}}function Hy(e,t,n,r,i){let a=new Uint8Array(e*e),o=0,s=i?Math.max(0,Math.floor(((i.left-t.x)/n+.5)*e)-1):0,c=i?Math.min(e,Math.ceil(((i.right-t.x)/n+.5)*e)+1):e,l=i?Math.max(0,Math.floor(((i.top-t.y)/n+.5)*e)-1):0,u=i?Math.min(e,Math.ceil(((i.bottom-t.y)/n+.5)*e)+1):e;for(let i=l;i<u;i++)for(let l=s;l<c;l++){let s=0;for(let a=0;a<2;a++)for(let o=0;o<2;o++)r({x:t.x+((l+.25+o*.5)/e-.5)*n,y:t.y+((i+.25+a*.5)/e-.5)*n})&&s++;let c=Math.round(s/4*255);a[i*e+l]=c,o+=c/255}return{mask:a,coverage:o/(e*e)}}var Uy=4,Wy={low:128,medium:160,high:192},Gy={low:192,medium:256,high:384},Ky=.115,qy=1/10,Jy=(e,t)=>{let n=typeof window>`u`?1:Math.min(3,Math.max(1,window.devicePixelRatio||1));return Math.max(Gy[t],Math.min(768,Math.ceil(e*n/16)*16))},Yy=(e,t)=>e.every((e,n)=>e===t[n]);function Xy(e,t,n,r,i){let a=N(D(-1),t),o=N(D(0,1),t+n),s=r.x*o.x+r.y*o.y;if(e){let e=M(r),t=Math.min(.55,e/22),n=Math.min(.28,Math.abs(s)/28),c=O(O(A(a,1-t-n),A(i,t)),A(o,-Math.sign(s)*n));return A(c,1/Math.max(.001,M(c)))}if(Math.abs(s)<=.8)return i;let c=Math.min(1,Math.abs(s)/Math.max(.8,M(r))),l=O(A(i,1-c),A(o,-Math.sign(s)*c));return A(l,1/Math.max(.001,M(l)))}var Zy=class{quality;fields=[];clock=0;fireTime=0;nextId=1;lastPours=new Map;lastFirePlan=-1/0;seam=null;wheelContacts=[];splashFields=new Map;captureState(){let e=[];try{for(let{fluid:t,...n}of this.fields)e.push({meta:E(n),fluid:t.captureState()})}catch(t){for(let t of e)t.fluid.dispose();throw t}return{fields:e,clock:this.clock,fireTime:this.fireTime,nextId:this.nextId,lastPours:E(this.lastPours),lastFirePlan:this.lastFirePlan,seam:this.seam?{previousId:this.seam.previous.id,currentId:this.seam.current.id,point:E(this.seam.point)}:null,wheelContacts:E(this.wheelContacts),splashFields:E(this.splashFields),quality:this.quality,dispose:()=>e.forEach(e=>e.fluid.dispose())}}restoreState(e){this.reset(),this.quality=e.quality;try{for(let{meta:t,fluid:n}of e.fields){let e=E(t),r=new ky(e.kind,e.resolution,e.resolution,e.color,e.elementProfile);r.setCellSize(e.extentM*e.pixelsPerMeter/e.resolution);try{r.restoreState(n)}catch(e){throw r.dispose(),e}this.fields.push({...e,fluid:r})}}catch(e){throw this.reset(),e}this.clock=e.clock,this.fireTime=e.fireTime,this.nextId=e.nextId,this.lastPours=E(e.lastPours),this.lastFirePlan=e.lastFirePlan,this.wheelContacts=E(e.wheelContacts),this.splashFields=E(e.splashFields??new Map);let t=this.fields.find(t=>t.id===e.seam?.previousId),n=this.fields.find(t=>t.id===e.seam?.currentId);this.seam=e.seam&&t&&n?{previous:t,current:n,point:E(e.seam.point)}:null}constructor(e=`high`){this.quality=e}get managedBytes(){return this.fields.reduce((e,t)=>e+96+(t.fire?.managedBytes??0)+t.fluid.managedBytes,0)}fireContactBounds(){return this.fields.filter(e=>T[e.kind].burnable).map(e=>{let t=e.extentM*e.pixelsPerMeter;return{x:e.center.x-t/2,y:e.center.y-t/2,width:t,height:t}})}hasConductiveCandidate(e,t){return this.fields.some(n=>{if(!T[n.kind].conductive)return!1;let r=n.extentM*n.pixelsPerMeter/2+t;return e.some(e=>Math.abs(e.x-n.center.x)<=r&&Math.abs(e.y-n.center.y)<=r)})}reset(){for(let e of this.fields)e.fluid.dispose();this.fields=[],this.clock=0,this.fireTime=0,this.lastPours.clear(),this.lastFirePlan=-1/0,this.seam=null,this.wheelContacts=[],this.splashFields.clear()}setQuality(e){this.quality=e}removeSeed(e){for(let t=this.fields.length-1;t>=0;t--){let n=this.fields[t];if(n.seedKey===e){n.fluid.removeSeed(),n.fluid.hasDeposits?n.seedKey=void 0:(n.fluid.dispose(),this.fields.splice(t,1));for(let[e,t]of this.splashFields)t===n.id&&this.splashFields.delete(e)}}}fieldForSeed(e){return this.fields.find(t=>t.seedKey===e)??null}seedShape(e,t,n,r,i,a,o,s){let c=this.fieldForSeed(e);c&&c.kind!==t&&(this.removeSeed(e),c=null);let l=Math.max(Uy,i/a+1.4);if(c??=this.create(t,n,r,a,s,Jy(l*a,this.quality)),!c)return!1;try{let t=c.pixelsPerMeter;c.seedKey=e,c.elementProfile=s,c.color=n;let a=Math.max(Uy,i/t+1.4,2*(M(k(r,c.center))/t+i/t/2+.7));c.poured===0?c.extentM=a:a>c.extentM&&this.expand(c,a/c.extentM),c.fluid.setCellSize(c.extentM*t/c.resolution),c.fluid.configure(n,s);let l=c.fluid.displaced,u=c.extentM*t/c.resolution,{mask:d,coverage:f}=Hy(c.resolution,c.center,c.extentM*t,e=>{if(!l)return o(e);let t=c.fluid.offsetAt(this.localPoint(c,e));return o(D(e.x+t.x*u,e.y+t.y*u))},l?void 0:{left:r.x-i/2,top:r.y-i/2,right:r.x+i/2,bottom:r.y+i/2});if(f<=0)return this.removeSeed(e),!1;let p=Math.max(1,f*c.extentM*c.extentM*3);return c.poured=Math.max(c.poured,p),c.fluid.seedMask(d,.85,p,n),!0}catch(t){throw this.removeSeed(e),t}}pour(e,t,n,r,i,a=T[e].color,o=`default`){if(r<=0)return;let s=this.lastPours.get(o),c=s?M(k(t,s.point))/Math.max(1,n):0,l=s?.kind===e&&Yy(a,s.color)&&s.age<.12&&c<2.5?s:void 0,u=l?c:0,d=Math.max(l?.age??1/120,1/120),f=Math.exp(-u/.45),p=(l?.localAmount??0)*f+r,m=Math.min(1.8,.11+Math.sqrt(p)*.32),h=-Math.expm1(-d/.12),g=l?l.radiusM+(m-l.radiusM)*h:m;this.deposit(e,a,t,n,r,i,g,l?.point,l?.radiusM),this.lastPours.set(o,{kind:e,color:a,point:{...t},age:0,localAmount:p,radiusM:g})}emit(e,t,n,r,i,a,o=T[e].color){r<=0||i<=0||this.deposit(e,o,t,n,r,a,i)}deposit(e,t,n,r,i,a,o,s,c=o){let l=this.fields.at(-1),u=e===`paint`||ft(e)?.mixing,d=i=>{if(!(i.kind===e||ft(e)?.mixing&&ft(i.kind)?.mixing)&&!(u&&i.kind===`paint`)||!u&&!Yy(t,i.color))return!1;let a=o*r;return[n,s??n,D((n.x+(s?.x??n.x))/2,(n.y+(s?.y??n.y))/2)].some(e=>M(k(e,i.center))/r+o>6.8?!1:[D(),D(a),D(-a),D(0,a),D(0,-a)].some(t=>{let n=O(e,t);return this.covers(i,n)&&i.fluid.densityAt(this.localPoint(i,n))>.02}))},f=(l&&d(l)?l:[...this.fields].reverse().find(d))??this.create(e,t,n,r);if(!f)return;f!==l&&!l?.seedKey&&l?.kind===e&&Yy(t,l.color)&&(this.seam={previous:l,current:f,point:{...n}});let p=this.seam?.current===f&&M(k(n,this.seam.point))<r*.85;this.depositIn(f,n,p?i*.5:i,a,o,t,s,c),p&&this.seam&&this.depositIn(this.seam.previous,n,i*.5,a,o,t,s,c)}depositIn(e,t,n,r,i,a=e.color,o,s=i){e.poured+=n;let c=2*(Math.max(M(k(t,e.center)),o?M(k(o,e.center)):0)/e.pixelsPerMeter+i+.25);c>e.extentM&&this.expand(e,Math.min(14/e.extentM,Math.max(1.25,c/e.extentM)));let l=this.localPoint(e,t),u=A(r,e.resolution/e.extentM);e.fluid.pour(n,this.clock+e.id,l,i*e.resolution/e.extentM,u,a,this.localPoint(e,o??t),s*e.resolution/e.extentM)}eject(e,t,n,r,i){this.pour(e,t,n,1.1,r,i)}splatter(e,t,n,r,i,a=!1,o=1,s){if(i<=0)return!1;let c=this.wheelContacts[e]?.splashFieldId??(s?this.splashFields.get(e):null),l=c==null?a||this.wheelContacts.length===0?[...this.fields].reverse().find(e=>this.covers(e,t)&&this.coverage(e,t)>.12):null:this.fields.find(e=>e.id===c);if(!l||!this.covers(l,t))return!1;let u=this.localPoint(l,t),d=l.resolution/l.extentM/l.pixelsPerMeter,f=s?.color.match(/[\d.]+/g)?.slice(0,3).map(Number);return l.fluid.spray(u,n,r*d,i*1.5*(s?.opacity??1),o,f?.length===3?f:void 0),!0}create(e,t,n,r,i,a){let o=a??Wy[this.quality],s;try{s=new ky(e,o,o,t,i)}catch{return null}let c={id:this.nextId++,kind:e,color:t,center:n,pixelsPerMeter:r,resolution:o,extentM:Uy,fluid:s,poured:0,elementProfile:i};return s.setCellSize(c.extentM*r/o),this.fields.push(c),c}step(e,t=[]){for(let[t,n]of this.lastPours)n.age+=e,n.age>1&&this.lastPours.delete(t);if(this.clock+=e,this.clock<1/30)return;let n=Math.min(.05,this.clock);this.clock=Math.max(0,this.clock-1/30),this.fireTime+=n;let r=this.fields.filter(e=>T[e.kind].burnable);this.fireTime-this.lastFirePlan>=.2&&r.some(e=>e.fire?.starts.some(Number.isFinite))&&r.some(e=>!e.fire||e.poured!==e.firePoured)&&(Py(r.map(e=>!e.fire||e.poured!==e.firePoured?this.prepareFire(e):e.fire),D(1/0,1/0),0,this.fireTime),this.lastFirePlan=this.fireTime);for(let e of this.fields){let r=[];for(let i of t){let t=M(i.velocity);if(M(k(i.point,e.center))>e.extentM*e.pixelsPerMeter*.62)continue;let a=e.resolution/e.extentM/e.pixelsPerMeter,o=this.localPoint(e,i.point);if(t<3&&(i.slip??0)<.05)continue;let s=D(i.point.x-i.velocity.x*n,i.point.y-i.velocity.y*n),c=this.localPoint(e,s);r.push({from:c,to:o,radius:Math.max(.65,i.radiusPx*a),paint:i.paint,slip:i.slip??0})}performance.now();let i=r.filter(t=>this.nearLiquid(e,t.from,t.to,t.radius));performance.now();for(let t of i)if(performance.now(),e.fluid.drag(t.from,t.to,n,t.radius,0),ut(e.kind)===`paint`&&t.paint){let r=t.paint.color.match(/[\d.]+/g)?.slice(0,3).map(Number);if(r?.length===3){let i=M(k(t.to,t.from)),a=(1-Math.exp(-i/Math.max(1,t.radius*3)-t.slip*n*2))*t.paint.opacity;performance.now(),e.fluid.transferPigment?.(t.from,t.to,t.radius,r,a*.32)}}let a=T[e.kind].burnable&&e.fire?.starts.some(Number.isFinite)?e.fire:void 0,o=a?this.fireTime-(e.fireUpdatedAt??this.fireTime-n):0,s=!!a&&o+1e-9>=qy,c=e.firePendingElapsed??0;performance.now(),e.fluid.step(n,0,[],c>0&&a?.rates.some(e=>e>0)?a:void 0,c||n),e.firePendingElapsed=0,s&&(performance.now(),a.update(this.fireTime,o),e.fireUpdatedAt=this.fireTime,e.firePendingElapsed=o)}for(let e=this.fields.length-1;e>=0;e--){let t=this.fields[e];if(!T[t.kind].burnable||!t.fire?.complete||(t.firePendingElapsed??0)>0)continue;let n=t.fluid.captureFuel();n.some(e=>e>=.035)?(this.prepareFire(t,n,.75),Py([t.fire],t.center,t.extentM*t.pixelsPerMeter,this.fireTime)):t.seedKey?(t.fluid.reset(),t.fire=void 0):(t.fluid.dispose(),this.fields.splice(e,1))}performance.now(),this.wheelContacts=t.map((e,t)=>{let n=this.sampleContact(e.point);return n.splashFieldId===null?e.paint||this.splashFields.delete(t):this.splashFields.set(t,n.splashFieldId),n});for(let e of this.splashFields.keys())e>=t.length&&this.splashFields.delete(e)}sampleContact(e){return Vy(this.fields,e,(e,t)=>this.coverage(e,t),(e,t)=>this.localPoint(e,t))}nearLiquid(e,t,n,r){return e.fluid.mayIntersect(t,n,r)}expand(e,t){if(t<=1)return;let n=e.resolution;e.resolution=e.fluid.grow(t),e.extentM*=e.resolution/n,e.fire&&(this.prepareFire(e),e.firePoured=-1)}localPoint(e,t){return D(e.resolution/2+(t.x-e.center.x)/e.pixelsPerMeter*e.resolution/e.extentM,e.resolution/2+(t.y-e.center.y)/e.pixelsPerMeter*e.resolution/e.extentM)}covers(e,t){let n=e.extentM*e.pixelsPerMeter*.5;return Math.abs(t.x-e.center.x)<=n&&Math.abs(t.y-e.center.y)<=n}coverage(e,t){if(!this.covers(e,t))return 0;let n=e.fluid.densityAt(this.localPoint(e,t));return Math.max(0,Math.min(1,(n-Ky+.012)/.024))*(e.elementProfile?.opacity??T[e.kind].alpha)}contacts(e,t){return this.fields.filter(n=>n.kind===e&&t.some(e=>this.coverage(n,e)>.1)).map(e=>e.id)}conductAt(e,t=0){return zy(this.fields,e,t)}densityAt(e,t){return Math.max(0,...this.fields.filter(n=>n.kind===e&&this.covers(n,t)).map(e=>e.fluid.densityAt(this.localPoint(e,t))))}prepareFire(e,t=e.fluid.captureFuel(),n){let r=T[e.kind],i=e.extentM*e.pixelsPerMeter,a=new Ny(t,e.resolution,{x:e.center.x-i/2,y:e.center.y-i/2,width:i,height:i},n??r.burnLifetime??r.burnSeconds??12,r.fireSpreadMps??T.oil.fireSpreadMps,e.pixelsPerMeter);return e.fire&&a.inherit(e.fire,this.fireTime),e.fire=a,e.firePoured=e.poured,e.fireSampleAt=this.fireTime,e.fireUpdatedAt=this.fireTime-e.id%3*qy/3,e.firePendingElapsed=0,a}igniteConducted(e,t){if(!e.length)return;let n=Ry(this.fields.filter(e=>T[e.kind].burnable),e,t).map(e=>!e.fire||e.firePoured!==e.poured?this.prepareFire(e):e.fire);if(n.length){Py(n,e[0],t,this.fireTime,e.slice(1));for(let e of n)e.update(this.fireTime,0);this.lastFirePlan=this.fireTime}}igniteAt(e,t=0){if(this.fireTime-this.lastFirePlan<.15)return;let n=[e];if(t>0)for(let r=0;r<8;r++)n.push(D(e.x+Math.cos(r*Math.PI/4)*t,e.y+Math.sin(r*Math.PI/4)*t));let r=this.fields.filter(e=>T[e.kind].burnable&&n.some(t=>this.coverage(e,t)>.08));if(!r.length||(this.lastFirePlan=this.fireTime,r.every(e=>e.fire&&e.firePoured===e.poured&&n.every(t=>{let n=e.fire.indexAt(t);return n<0||e.fire.fuel[n]<.035||Number.isFinite(e.fire.starts[n])}))))return;let i=this.fields.filter(e=>T[e.kind].burnable).map(e=>!e.fire||e.poured!==e.firePoured&&this.fireTime-(e.fireSampleAt??0)>=.2?this.prepareFire(e):e.fire);Py(i,e,t,this.fireTime);for(let e of i)e.update(this.fireTime,0)}igniteAlong(e,t,n=0){for(let r=0;r<=4;r++)this.igniteAt(D(e.x+(t.x-e.x)*r/4,e.y+(t.y-e.y)*r/4),n)}burningSources(e){return By(this.fields,this.fireTime,e)}burningMasks(){return this.fields.flatMap(e=>{let t=e.fire;return!T[e.kind].burnable||!t?.lit?[]:[{key:e,alpha:t.alpha,pixelWidth:t.resolution,pixelHeight:t.resolution,...t.rect,origin:e.center,age:.4,farthest:Math.max(1,t.rect.width),spreadSeconds:0,burnSeconds:1,intensity:.55,smokeRate:10,revision:t.revision}]})}kindAt(e){let t=!1,n=!1,r=!1;for(let i=this.fields.length-1;i>=0;i--){let a=this.fields[i];if(!(this.coverage(a,e)<=.1)){if(ut(a.kind)===`water`)return`water`;ut(a.kind)===`oil`&&(t=!0),ut(a.kind)===`paint`&&(n=!0),ut(a.kind)===`mud`&&(r=!0)}}return r?`mud`:t?`oil`:n?`paint`:null}pruneOutside(e){this.fields=this.fields.filter(t=>{let n=t.extentM*t.pixelsPerMeter*1.5,r=t.center.x+n>=e.x&&t.center.x-n<=e.x+e.width&&t.center.y+n>=e.y&&t.center.y-n<=e.y+e.height;return r||t.fluid.dispose(),r}),!this.seam||this.fields.includes(this.seam.previous)&&this.fields.includes(this.seam.current)||(this.seam=null)}draw(e,t,n,r,i){performance.now(),e.save(),e.globalAlpha=r;for(let r of this.fields){let a=t(r.center),o=r.extentM*r.pixelsPerMeter*n,s=r.fluid.hasSplatter?o*1.5:o/2;i&&(a.x+s<0||a.y+s<0||a.x-s>i.width||a.y-s>i.height)||(e.save(),e.translate(a.x-o/2,a.y-o/2),e.scale(o/r.resolution,o/r.resolution),r.fluid.draw(e),e.restore())}e.restore()}},Qy=class{liquids;camera;pixelSpace;elementFields=new Map;nextElementId=1;initialPuddles=[];constructor(e,t,n){this.liquids=e,this.camera=t,this.pixelSpace=n}captureState(){return E({elementFields:this.elementFields,nextElementId:this.nextElementId,initialPuddles:this.initialPuddles})}restoreState(e){let t=E(e);this.elementFields=t.elementFields,this.nextElementId=t.nextElementId,this.initialPuddles=t.initialPuddles}clearEffects(){this.elementFields.clear(),this.nextElementId=1}pourWorldLiquid(e,t,n,r,i){this.liquids.pour(e,this.camera.particlePoint(t),this.camera.particleScale(),n,D(),r,i)}addLiquid(e,t){let n=ot(e),r=t.amount??24;if(!Number.isFinite(t.at.x)||!Number.isFinite(t.at.y)||!Number.isFinite(r)||r<=0)throw RangeError(`Liquid position and positive amount must be finite.`);let i=t.color?at(t.color):void 0;if(t.initial){let e={kind:n,point:this.camera.documentPoint(t.at),amount:r,color:i};this.initialPuddles.push(e),this.depositInitialPuddle(e)}else this.pourWorldLiquid(n,t.at,r,i)}syncElementLiquids(e){performance.now();let t=new Set(e.map(e=>e.key));for(let[e,n]of this.elementFields)t.has(e)||(this.liquids.removeSeed(n.id),this.elementFields.delete(e));let n=new Map;for(let t of e){let e=this.localFromDocument({x:t.bounds.x,y:t.bounds.y}),r=this.localFromDocument({x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height}),i=D((e.x+r.x)/2,(e.y+r.y)/2),a=this.elementFields.get(t.key),o=a?.signature!==t.signature,s=a&&(a.center.x!==i.x||a.center.y!==i.y);if(!a||o||s){performance.now();let n=a?.id??`element-liquid-${this.nextElementId++}`,o=Math.max(Math.abs(r.x-e.x),Math.abs(r.y-e.y));if(!this.liquids.seedShape(n,t.kind,t.color,i,o,this.camera.particleScale(),e=>t.contains(this.pixelSpace?e:this.camera.documentPoint(e)),t.profile))continue;a={id:n,signature:t.signature,center:i},this.elementFields.set(t.key,a)}let c=this.liquids.fieldForSeed(a.id);c&&n.set(t.key,c)}return n}setInitialPuddles(e){this.liquids.reset(),this.elementFields.clear(),this.nextElementId=1,this.initialPuddles=e.map(({kind:e,color:t,point:n,amount:r})=>({kind:e,color:t?[...t]:void 0,point:{...n},amount:r})),this.restoreInitialPuddles()}restoreInitialPuddles(){for(let e of this.initialPuddles)this.depositInitialPuddle(e)}depositInitialPuddle({kind:e,color:t,point:n,amount:r}){let i=this.localFromDocument(n),a=this.camera.particleScale(),o=Math.max(1,Math.ceil(r/2));for(let n=0;n<o;n++)this.liquids.pour(e,i,a,r/o,D(),t),this.liquids.step(1/30)}localFromDocument(e){return this.pixelSpace?{...e}:this.camera.worldFromDocument(e)}},$y=class{bounds=[];tiles=new Map;dpr=1;scale=1;setBounds(e){this.bounds=e;for(let[t,n]of this.tiles)t>=e.length&&(n.canvas.remove(),this.tiles.delete(t))}resize(e,t,n,r){this.dpr=n,this.scale=r}tile(e){let t=this.tiles.get(e);if(t)return t;let n=document.createElement(`canvas`);n.dataset.jrLiquidTextVehicle=``;let r=n.getContext(`2d`);if(!r)throw Error(`Joy Ride requires a 2D canvas context.`);return n.setAttribute(`aria-hidden`,`true`),Object.assign(n.style,{position:`fixed`,pointerEvents:`none`,zIndex:ey(`foreground`),transformOrigin:`0 0`,display:`none`}),document.body.append(n),t={canvas:n,context:r,visible:!1},this.tiles.set(e,t),t}draw(e,t,n,r){for(let i=0;i<this.bounds.length;i++){let a=this.bounds[i],o=e({x:a.x,y:a.y}),s=e({x:a.x+a.width,y:a.y+a.height}),c=o.x,l=o.y,u=s.x-c,d=s.y-l;if(!t.some(({point:e,radius:t})=>e.x>=c-t&&e.x<=c+u+t&&e.y>=l-t&&e.y<=l+d+t)||u<=0||d<=0){let e=this.tiles.get(i);e?.visible&&(e.canvas.style.display=`none`,e.visible=!1);continue}let f=this.tile(i),{canvas:p,context:m}=f,h=Math.max(1,Math.ceil(u*this.dpr)),g=Math.max(1,Math.ceil(d*this.dpr));(p.width!==h||p.height!==g)&&(p.width=h,p.height=g,p.style.width=`${u}px`,p.style.height=`${d}px`);let _=`${c*this.scale}px`,v=`${l*this.scale}px`;p.style.left!==_&&(p.style.left=_),p.style.top!==v&&(p.style.top=v),p.style.scale!==String(this.scale)&&(p.style.scale=String(this.scale)),f.visible||=(p.style.display=`block`,!0),m.setTransform(this.dpr,0,0,this.dpr,0,0),m.clearRect(0,0,u,d),m.save(),m.translate(-c+n.x,-l+n.y),r(m),m.restore()}}dispose(){for(let e of this.tiles.values())e.canvas.remove();this.tiles.clear()}};function eb(e,t,n,r,i,a,o,s=[]){let{sim:c,tirePaint:l}=e;if(c.mode!==`car`)return;let u=[];c.car.statusEffects.setContacts(`mud`,St.mud,u),e.isGhost?c.car.tires.forEach((e,t)=>l.pauseTrack(t)):(l.step(a?c.car.tires.map(e=>M(c.body.velocityAt(c.body.world(e.local)))*r):[]),o?(c.car.tires.forEach((e,r)=>{let o=t[r],d=o?.materials??[],f=e=>d.some(t=>ut(t)===e&&!_t(t)),p=()=>{for(let e of d){let t=_t(e);t&&c.car.statusEffects.apply(`liquid:${e}`,t,r)}};if(d.some(e=>ut(e)===`water`)&&(c.car.washWheel(r),l.wash(r,o?.paints??[]),!o?.paints?.length)){p();return}f(`oil`)&&c.car.coatWithOil(r),d.some(e=>ut(e)===`mud`)&&(f(`mud`)&&c.car.coatWithMud(r),u.push(r)),p();for(let e of o?.paints??(o?.paint?[o.paint]:[]))l.touch(r,e);if(l.touch(r,s[r]??null),!a){l.pauseTrack(r);return}let m=l.coating(r),h=d.length>0&&!!o?.paint&&m?.color!==o.paint.color;(o?.paints?.length??+!!o?.paint)>0||s[r]?l.trackWet(r,n[r],-c.body.angle-e.angle,c.car.preset.geometry.tireWidthM,i,e.slip,h&&!s[r]):l.track(r,n[r],-c.body.angle-e.angle,c.car.preset.geometry.tireWidthM,i,h,e.slip)}),c.car.statusEffects.setContacts(`mud`,St.mud,u)):c.car.tires.forEach((e,t)=>l.pauseTrack(t)))}function tb(e,t,n,r,i,a,o){let s=e=>{let t=e.sim;return t.mode!==`car`||e.isGhost?[]:t.car.tires.map((n,r)=>{let i=t.body.world(n.local);return{point:o.particlePoint(i),velocity:o.particleVelocity(t.body.velocityAt(i)),radiusPx:t.car.preset.geometry.tireWidthM*o.particleScale*.7,slip:n.slip,paint:e.tirePaint.coating(r)}})},c=s(t),l=n.map(e=>({vehicle:e,tires:s(e)}));performance.now(),e.step(r,[...c,...l.flatMap(e=>e.tires)]),performance.now();for(let t of e.burningMasks())o.emitFire(t,r);performance.now();let u=e=>typeof a==`function`?a(e.sim.car.tires.map(t=>o.documentPoint(e.sim.body.world(t.local)))):e===t?a:[];eb(t,e.wheelContacts.slice(0,c.length),c.map(e=>e.point),r,o.particleScale,i,!o.fading,u(t));let d=c.length;for(let{vehicle:t,tires:n}of l)eb(t,e.wheelContacts.slice(d,d+n.length),n.map(e=>e.point),r,o.particleScale,!0,!o.fading,u(t)),d+=n.length;return{tires:c,companionTires:l}}var nb=class{camera;fields=new Zy;authoring;textVehicles=null;constructor(e,t){this.camera=e,this.fields.setQuality(t),this.authoring=new Qy(this.fields,e,e.pixelSpace)}get managedBytes(){return this.fields.managedBytes}setQuality(e){this.fields.setQuality(e)}captureState(){let e=this.fields.captureState();try{return{fields:e,authoring:this.authoring.captureState(),dispose:()=>e.dispose()}}catch(t){throw e.dispose(),t}}restoreState(e){this.fields.restoreState(e.fields),this.authoring.restoreState(e.authoring)}clearEffects(){this.fields.reset(),this.authoring.clearEffects()}restoreInitialPuddles(){this.authoring.restoreInitialPuddles()}dispose(){this.textVehicles?.dispose(),this.textVehicles=null,this.fields.reset()}resize(){this.textVehicles?.resize(this.camera.width,this.camera.height,this.camera.dpr,this.camera.regionScale)}pruneOutside(e){this.fields.pruneOutside(e)}draw(e,t){this.fields.draw(e,e=>this.camera.pixelSpace?k(e,this.camera.sceneScroll()):this.camera.screen(e),this.camera.pixelSpace?1:this.camera.zoom,t,{width:this.camera.width,height:this.camera.height})}drawTextVehicles(e,t,n){this.textVehicles?.draw(e=>this.camera.viewportFromDocument(e),e,t,n)}pourWorldLiquid(e,t,n,r,i){this.authoring.pourWorldLiquid(e,t,n,r,i)}emitPaint(e,t,n,r,i){this.fields.emit(`paint`,this.camera.particlePoint(e),this.camera.particleScale(),n,t,this.camera.pixelSpace?D(i.x,-i.y):i,r)}local(e){return this.camera.particlePoint(this.camera.worldFromDocument(e))}get ratio(){return this.camera.particleScale()/this.camera.documentScale()}hasConductiveCandidate(e,t){return this.fields.hasConductiveCandidate(e.map(e=>this.local(e)),t*this.ratio)}conductLightning(e,t=0){let n=e=>this.local(e),r=e=>this.camera.pixelSpace?e:this.camera.documentPoint(e),i=this.ratio,a=this.fields.conductAt(e.map(n),t*i);return{points:a.points.map(r),contains:(e,t=0)=>a.contains(n(e),t*i),intersects:(e,t=0)=>{let r=n(e),o=n({x:e.x+e.width,y:e.y+e.height});return a.intersects({x:Math.min(r.x,o.x),y:Math.min(r.y,o.y),width:Math.abs(r.x-o.x),height:Math.abs(r.y-o.y)},t*i)},pathTo:(e,t=0)=>a.pathTo(n(e),t*i).map(r)}}igniteAt(e,t){this.fields.igniteAt(this.local(e),t*this.ratio)}igniteConducted(e,t){this.fields.igniteConducted(e.map(e=>this.local(e)),t*this.ratio)}igniteFromFire(e){if(!e.length)return;let t=new Map,n=this.fields.fireContactBounds().map(e=>{if(this.camera.pixelSpace)return e;let t=this.camera.documentPoint({x:e.x,y:e.y}),n=this.camera.documentPoint({x:e.x+e.width,y:e.y+e.height});return{x:Math.min(t.x,n.x),y:Math.min(t.y,n.y),width:Math.abs(t.x-n.x),height:Math.abs(t.y-n.y)}});for(let r of e){let e=Math.max(0,Math.round(r.radiusPx/4)*4),i=t.get(e)??[],a=r.bounds?n.flatMap(e=>No(r,e)):No(r);for(let e of a)i.push(this.local(e));t.set(e,i)}for(let[e,n]of t)this.fields.igniteConducted(n,e*this.ratio)}burningSources(){let e=24*this.ratio;return this.fields.burningSources(e).map(e=>({point:this.camera.pixelSpace?e:this.camera.documentPoint(e),radiusPx:24,spreadSeconds:Ze.spreadSeconds}))}hasContact(e,t){return this.fields.contacts(ot(e),t.map(e=>this.camera.particlePoint(e))).length>0}add(e,t){this.authoring.addLiquid(e,t)}syncElements(e){if(this.camera.overlay){let t=e.filter(e=>typeof HTMLElement<`u`&&e.key instanceof HTMLElement&&(e.key.childElementCount>0||!!e.key.textContent?.trim())).map(e=>e.bounds);t.length&&(this.textVehicles??=new $y),this.textVehicles?.setBounds(t),this.resize()}return this.authoring.syncElementLiquids(e)}setInitialPuddles(e){this.authoring.setInitialPuddles(e)}pourVehicle(e,t,n,r,i=`player`){if(e.mode!==`car`)return;let a=e.body.world(D(-e.car.preset.geometry.lengthM/2-.58,0)),o=N(D(-4,0),e.body.angle);this.fields.pour(t,this.camera.particlePoint(a),this.camera.particleScale(),n,this.camera.pixelSpace?D(o.x,-o.y):o,r,i)}stepVehicles(e,t,n,r,i,a,o){return tb(this.fields,e,t,n,r,i,{particlePoint:e=>this.camera.particlePoint(e),particleVelocity:e=>this.camera.pixelSpace?D(e.x*this.camera.zoom,-e.y*this.camera.zoom):{...e},documentPoint:e=>this.camera.documentPoint(e),particleScale:this.camera.particleScale(),fading:a,emitFire:o})}splatter(e,t,n,r,i,a,o,s){this.fields.splatter(n,r,i,a,o,!1,s,e.tirePaint.coating(t))||e.tirePaint.splatter(t,r,i,a,o,s,this.camera.particleScale())}igniteAlong(e,t,n){this.fields.igniteAlong(e,t,n)}igniteAtLocal(e){this.fields.igniteAt(e)}pourOilPreview(e,t){this.fields.pour(`oil`,e,this.camera.particleScale(),t*6,D())}},rb=256,ib=48,ab=class{overPuddle;constructor(e=null){this.overPuddle=e}tiles=new Map;records=new Map;archived=0;references=0;processed=0;ratio=0;scale=0;captureState(){return{marks:E([...new Set([...this.records.values()].flat())]),processed:this.processed,scale:this.scale}}restoreState(e){this.clear(),this.scale=e.scale,this.seed(E(e.marks),e.scale),this.processed=e.processed}managedBytes(e){return this.tiles.size*(rb*this.ratio)**2*4+Math.max(0,this.archived-e)*136+this.references*8}clear(){this.tiles.clear(),this.records.clear(),this.archived=0,this.references=0,this.processed=0}seed(e,t){for(let n of e)(this.overPuddle===null||!!n.overPuddle===this.overPuddle)&&this.indexMark(n,t)}draw(e,t,n,r,i,a,o,s,c,l){n<this.processed&&this.clear(),(this.ratio!==c||this.scale!==s)&&(this.tiles.clear(),this.ratio=c,this.scale=s);let u=Math.min(t.length,n-this.processed);for(let e=t.length-u;e<t.length;e++){let n=t[e];(this.overPuddle===null||!!n.overPuddle===this.overPuddle)&&this.indexMark(n,s)}if(this.processed=n,!this.archived)return;let d=Math.floor(r/rb),f=Math.floor((r+a)/rb),p=Math.floor(i/rb),m=Math.floor((i+o)/rb),h=new Set;e.save(),e.globalAlpha=l;for(let t=p;t<=m;t++)for(let n=d;n<=f;n++){let a=`${n},${t}`;h.add(a);let o=this.records.get(a);if(!o?.length)continue;let c=this.tiles.get(a);if(!c){c=this.createTile(n,t);for(let e of o)this.stroke(c,e,s);this.tiles.set(a,c)}e.drawImage(c.canvas,n*rb-r,t*rb-i,rb,rb)}if(e.restore(),this.tiles.size>ib)for(let e of this.tiles.keys()){if(this.tiles.size<=ib)break;h.has(e)||this.tiles.delete(e)}}pruneOutside(e){for(let t of this.records.keys()){let[n,r]=t.split(`,`).map(Number);((n+1)*rb<e.x||n*rb>e.x+e.width||(r+1)*rb<e.y||r*rb>e.y+e.height)&&(this.records.delete(t),this.tiles.delete(t))}this.archived=new Set([...this.records.values()].flat()).size,this.references=[...this.records.values()].reduce((e,t)=>e+t.length,0)}indexMark(e,t){this.archived++;let n=e.widthM*Math.max(32,t)*.38+2,r=Math.floor((Math.min(e.from.x,e.point.x)-n)/rb),i=Math.floor((Math.max(e.from.x,e.point.x)+n)/rb),a=Math.floor((Math.min(e.from.y,e.point.y)-n)/rb),o=Math.floor((Math.max(e.from.y,e.point.y)+n)/rb);for(let n=a;n<=o;n++)for(let a=r;a<=i;a++){let r=`${a},${n}`,i=this.records.get(r);i||(i=[],this.records.set(r,i)),i.push(e),this.references++;let o=this.tiles.get(r);o&&this.stroke(o,e,t)}}createTile(e,t){let n=document.createElement(`canvas`);n.width=Math.ceil(rb*this.ratio),n.height=Math.ceil(rb*this.ratio);let r=n.getContext(`2d`);if(!r)throw Error(`Joy Ride tire marks require a 2D canvas context`);return r.setTransform(this.ratio,0,0,this.ratio,-e*rb*this.ratio,-t*rb*this.ratio),{canvas:n,context:r}}stroke(e,t,n){let r=e.context;wa(r,t,t.from,t.point,t.widthM*n*.76,n)}},ob=class{ground=new ab;dry=new Map;wet=new Map;seed(e,t){this.ground.seed(e,t)}forgetVehicle(e){this.dry.delete(e),this.wet.delete(e)}captureState(){return{ground:this.ground.captureState(),dry:[...this.dry].map(([e,t])=>[e,t.captureState()]),wet:[...this.wet].map(([e,t])=>[e,t.captureState()])}}restoreState(e){this.ground.restoreState(e.ground),this.dry=new Map(e.dry.map(([e,t])=>{let n=new ab(!1);return n.restoreState(t),[e,n]})),this.wet=new Map(e.wet.map(([e,t])=>{let n=new ab(!0);return n.restoreState(t),[e,n]}))}get managedBytes(){return this.ground.managedBytes(0)+[...this.dry.values(),...this.wet.values()].reduce((e,t)=>e+t.managedBytes(0),0)}clear(){this.ground.clear(),this.dry.clear(),this.wet.clear()}pruneOutside(e){for(let t of[...this.dry.values(),...this.wet.values()])t.pruneOutside(e)}draw(e,t,n,r){let{pixelSpace:i,scroll:a,width:o,height:s,particleScale:c,rasterRatio:l,zoom:u,effectsAlpha:d,screen:f}=r;if(e.save(),e.lineCap=`round`,i){n||this.ground.draw(e,[],0,a.x,a.y,o,s,c,l,d);let r=n?this.wet:this.dry;for(let i of t){let t=r.get(i.id);t||(t=new ab(n),r.set(i.id,t)),t.draw(e,i.tirePaint.marks,i.tirePaint.totalMarks,a.x,a.y,o,s,c,l,d)}}else for(let r of t)for(let t of r.tirePaint.marks){if(!!t.overPuddle!==n)continue;let r=f(t.point),i=f(t.from);(r.x<-20||r.x>o+20||r.y<-20||r.y>s+20)&&(i.x<-20||i.x>o+20||i.y<-20||i.y>s+20)||wa(e,t,i,r,t.widthM*c*u*.76,c*u,d)}e.restore()}};function sb(e,t,n,r){let i=k(n,t),a=M(i);if(a<1e-5)return;let o=A(i,1/a),s=e.widthPx,c=Math.max(.055*(s/e.widthM),s*.4),l=e.nextStamp,u=0;for(;l<=a&&u++<80;){let n=D(-o.y,o.x),i=O(O(t,A(o,l)),A(n,(Math.random()-.5)*s*.04));e.stamps.push({point:i,direction:o,length:c*(.78+Math.random()*.14),opacity:P(.57+r*.26+(Math.random()-.5)*.12,.3,1),shoulder:(Math.random()-.5)*.06}),l+=c}e.nextStamp=Math.max(0,l-a)}function cb(e,t,n){if(e.contactStamps>=48)return;let r=e.widthPx,i=D(-n.y,n.x);for(let a=0;a<2;a++)e.stamps.push({point:O(t,O(A(n,(Math.random()-.5)*r*1.4),A(i,(Math.random()-.5)*r*.2))),direction:n,length:r*(.3+Math.random()*.18),opacity:.35+Math.random()*.25,shoulder:(Math.random()-.5)*.06});e.contactStamps+=2}function lb(e,t,n,r,i,a){if(t.length<2)return;let o=t.map((e,r)=>{let i=t[Math.max(0,r-1)],a=t[Math.min(t.length-1,r+1)],o=k(a,i),s=Math.max(1e-5,M(o));return D(e.x-o.y/s*n,e.y+o.x/s*n)});e.beginPath(),e.moveTo(o[0].x,o[0].y);for(let t=1;t<o.length-1;t++){let n=A(O(o[t],o[t+1]),.5);e.quadraticCurveTo(o[t].x,o[t].y,n.x,n.y)}e.lineTo(o[o.length-1].x,o[o.length-1].y),e.strokeStyle=a,e.globalAlpha=i,e.lineWidth=r,e.stroke()}function ub(e,t,n,r,i,a){t.road&&(r=kl.dark);let o=n?t.points.map(a.screen):t.points,s=Math.max(2,(a.pixelSpace?t.widthPx:t.widthM*a.zoom)*.72);lb(e,o,0,s*.92,.075*t.opacity*r.alphaScale*i,r.ink),lb(e,o,-s*.29,s*.22,.17*t.opacity*r.alphaScale*i,r.ink),lb(e,o,s*.29,s*.22,.17*t.opacity*r.alphaScale*i,r.ink),e.fillStyle=r.ink;for(let o of t.stamps){let c=n?a.screen(o.point):o.point;if(n&&(c.x<-12||c.x>a.width+12||c.y<-12||c.y>a.height+12))continue;let l=a.pixelSpace?o.direction:D(o.direction.x,-o.direction.y),u=o.length*(a.pixelSpace?1:a.zoom);e.save(),e.translate(c.x,c.y),e.rotate(Math.atan2(l.y,l.x)),e.globalAlpha=.28*t.opacity*o.opacity*r.alphaScale*i;let d=s*.2,f=Math.max(1,u*.82),p=s*(.29+o.shoulder);e.beginPath(),e.roundRect(-f/2,-p-d/2,f,d,Math.min(.7,d*.2)),e.roundRect(-f/2,p-d/2,f,d,Math.min(.7,d*.2)),e.fill(),e.restore()}}var db=256,fb=48,pb=class{records=new Map;tiles=new Map;paths=0;pathBytes=0;references=0;ratio=0;theme=``;captureState(){return E([...new Set([...this.records.values()].flat())])}restoreState(e,t){this.clear();for(let n of E(e))this.add(n,t)}get managedBytes(){return this.tiles.size*(db*this.ratio)**2*4+this.pathBytes+this.references*8}clear(){this.records.clear(),this.tiles.clear(),this.paths=0,this.pathBytes=0,this.references=0}add(e,t){this.paths++,this.pathBytes+=96+e.points.length*24+e.stamps.length*64;let n=Math.max(2,e.widthPx)*2,r=Math.floor((e.bounds.left-n)/db),i=Math.floor((e.bounds.right+n)/db),a=Math.floor((e.bounds.bottom-n)/db),o=Math.floor((e.bounds.top+n)/db);for(let n=a;n<=o;n++)for(let a=r;a<=i;a++){let r=`${a},${n}`,i=this.records.get(r);i||(i=[],this.records.set(r,i)),i.push(e),this.references++;let o=this.tiles.get(r);o&&t(o.context,e)}}draw(e,t,n,r,i,a,o,s,c){if(!this.paths)return;(this.ratio!==a||this.theme!==o)&&(this.tiles.clear(),this.ratio=a,this.theme=o);let l=Math.floor(t/db),u=Math.floor((t+r)/db),d=Math.floor(n/db),f=Math.floor((n+i)/db),p=new Set;e.save(),e.globalAlpha=s;for(let r=d;r<=f;r++)for(let i=l;i<=u;i++){let a=`${i},${r}`,o=this.records.get(a);if(!o?.length)continue;p.add(a);let s=this.tiles.get(a);if(!s){s=this.createTile(i,r);for(let e of o)c(s.context,e);this.tiles.set(a,s)}e.drawImage(s.canvas,i*db-t,r*db-n,db,db)}if(e.restore(),this.tiles.size>fb)for(let e of this.tiles.keys()){if(this.tiles.size<=fb)break;p.has(e)||this.tiles.delete(e)}}pruneOutside(e){for(let t of this.records.keys()){let[n,r]=t.split(`,`).map(Number);((n+1)*db<e.x||n*db>e.x+e.width||(r+1)*db<e.y||r*db>e.y+e.height)&&(this.records.delete(t),this.tiles.delete(t))}let t=new Set([...this.records.values()].flat());this.paths=t.size,this.references=[...this.records.values()].reduce((e,t)=>e+t.length,0),this.pathBytes=[...t].reduce((e,t)=>e+96+t.points.length*24+t.stamps.length*64,0)}createTile(e,t){let n=document.createElement(`canvas`);n.width=Math.ceil(db*this.ratio),n.height=Math.ceil(db*this.ratio);let r=n.getContext(`2d`);if(!r)throw Error(`Joy Ride skid tiles require a 2D canvas context`);return r.setTransform(this.ratio,0,0,this.ratio,-e*db*this.ratio,-t*db*this.ratio),r.lineCap=`round`,r.lineJoin=`round`,{canvas:n,context:r}}},mb=class{clock=0;time=0;presetId=null;previous=new Map;paths=[];tiles=new pb;revealAlpha=1;pendingReveal=new Set;captureState(){let e=E({previous:this.previous,paths:this.paths});return{clock:this.clock,time:this.time,presetId:this.presetId,previous:e.previous,paths:e.paths,revealAlpha:this.revealAlpha,pendingRevealIndices:this.paths.flatMap((e,t)=>this.pendingReveal.has(e)?[t]:[]),tiles:this.tiles.captureState()}}restoreState(e,t,n){this.clock=e.clock,this.time=e.time,this.presetId=e.presetId;let r=E({previous:e.previous,paths:e.paths});this.previous=r.previous,this.paths=r.paths,this.revealAlpha=e.revealAlpha,this.pendingReveal=new Set(e.pendingRevealIndices.map(e=>this.paths[e]));let i=kl[n?`dark`:`light`];this.tiles.restoreState(e.tiles,(e,n)=>ub(e,n,!1,i,1,t))}get managedBytes(){return this.paths.reduce((e,t)=>e+96+t.points.length*24+t.stamps.length*64,0)+this.tiles.managedBytes}clear(){this.clock=0,this.time=0,this.presetId=null,this.previous.clear(),this.paths=[],this.revealAlpha=1,this.pendingReveal.clear(),this.tiles.clear()}beginReveal(e,t){this.setRevealAlpha(1,e,t),this.stop(e,t),this.revealAlpha=0}setRevealAlpha(e,t,n){let r=P(e,0,1);if((r!==this.revealAlpha||this.pendingReveal.size!==0)&&(this.revealAlpha=r,!(this.revealAlpha<1))){for(let e of this.pendingReveal)this.rasterize(e,t,n);this.pendingReveal.clear()}}fade(){this.previous.clear()}stop(e,t,n=!1){for(let{path:n}of this.previous.values())this.finish(n,e,t);this.previous.clear(),n&&(this.clock=0)}pruneOutside(e){this.tiles.pruneOutside(e)}step(e,t,n,r,i){this.time+=e,this.clock+=e,!(this.clock<1/30)&&(this.clock%=1/30,this.presetId!==t.car.preset.id&&(this.stop(i.view,i.dark),this.presetId=t.car.preset.id),t.car.tires.forEach((e,a)=>{let o=this.previous.get(a);if(r(a)){o&&this.finish(o.path,i.view,i.dark),this.previous.delete(a);return}let s=i.project(t.body.world(e.local)),c=n&&!e.front;if(!e.skidding&&!c){o&&this.finish(o.path,i.view,i.dark),this.previous.delete(a);return}let l=i.project(t.body.world(O(e.local,D(-t.car.preset.geometry.tireLengthM*.8)))),u=!i.dark&&i.roadAt(e,s),d=o&&o.path.road===u&&this.time-o.time<.18&&o.path.stamps.length<(i.pixelSpace?64:320)?o.path:{road:u,points:e.spinning?[l,s]:i.pixelSpace&&o&&o.path.stamps.length>=64?[o.path.points[o.path.points.length-1],s]:[s],stamps:[],contactStamps:0,nextStamp:0,widthM:t.car.preset.geometry.tireWidthM,widthPx:t.car.preset.geometry.tireWidthM*i.scale,opacity:e.spinning?1:c?.72:P(.25+e.slip*.55+e.heat*.2,.3,1),bounds:{left:Math.min(l.x,s.x),right:Math.max(l.x,s.x),bottom:Math.min(l.y,s.y),top:Math.max(l.y,s.y)}};if(d!==o?.path)o&&this.finish(o.path,i.view,i.dark),this.paths.push(d),e.spinning?sb(d,l,s,1):d.points.length>1&&sb(d,d.points[0],s,c?.72:e.slip);else{let n=d.points[d.points.length-1];M(k(s,n))>(i.pixelSpace?.05:.001)?(sb(d,n,s,e.spinning?1:c?.72:e.slip),d.points.push(s),d.bounds.left=Math.min(d.bounds.left,s.x),d.bounds.right=Math.max(d.bounds.right,s.x),d.bounds.bottom=Math.min(d.bounds.bottom,s.y),d.bounds.top=Math.max(d.bounds.top,s.y)):e.spinning&&cb(d,s,D(Math.cos(t.body.angle),i.pixelSpace?-Math.sin(t.body.angle):Math.sin(t.body.angle)))}this.previous.set(a,{path:d,time:this.time})}))}finish(e,t,n){this.revealAlpha<1?this.pendingReveal.add(e):this.rasterize(e,t,n)}rasterize(e,t,n){if(!t.pixelSpace)return;let r=kl[n?`dark`:`light`];this.tiles.add(e,(e,n)=>ub(e,n,!1,r,1,t));let i=this.paths.indexOf(e);i>=0&&this.paths.splice(i,1)}draw(e,t){let{pixelSpace:n,scroll:r,width:i,height:a,ratio:o,dark:s,alpha:c,visible:l,view:u}=t,d=kl[s?`dark`:`light`];performance.now(),n&&this.tiles.draw(e,r.x,r.y,i,a,o,s?`dark`:`light`,c,(e,t)=>ub(e,t,!1,d,1,u)),performance.now();for(let t of this.paths){let r=(n?t.widthPx:t.widthM*u.zoom)*2;t.bounds.right<l.left-r||t.bounds.left>l.right+r||t.bounds.top<l.bottom-r||t.bounds.bottom>l.top+r||ub(e,t,!0,d,c*this.revealAlpha,u)}}},hb={crashLow:{amplitudePx:.65,durationMs:85,frequencyHz:17},crashMedium:{amplitudePx:1.35,durationMs:125,frequencyHz:19},crashFast:{amplitudePx:2.35,durationMs:165,frequencyHz:21},rocketExplosion:{amplitudePx:2.8,durationMs:190,frequencyHz:16},lightning:{amplitudePx:3.1,durationMs:210,frequencyHz:26},combustibleExplosion:{amplitudePx:3.3,durationMs:215,frequencyHz:17}};function gb(e){return!Number.isFinite(e)||e<.8?null:e<3.5?`crashLow`:e<8?`crashMedium`:`crashFast`}var _b=class{enabled=!0;profiles={...hb};impulses=[];lastTriggered=new Map;sequence=0;captureState(){return{at:performance.now(),data:E({enabled:this.enabled,profiles:this.profiles,impulses:this.impulses,lastTriggered:this.lastTriggered,sequence:this.sequence})}}restoreState(e){let t=E(e.data);this.enabled=t.enabled,this.profiles=t.profiles,this.impulses=t.impulses,this.lastTriggered=t.lastTriggered,this.sequence=t.sequence;let n=performance.now()-e.at;for(let e of this.impulses)e.startedAt+=n;for(let[e,t]of this.lastTriggered)this.lastTriggered.set(e,t+n)}get active(){return this.impulses.length>0}setEnabled(e){this.enabled=e,e||this.reset()}setProfiles(e){let t={...hb};if(e)for(let n of Object.keys(t)){let r=e[n];if(!r)continue;let i=t[n],a=(e,t,n,r)=>e!==void 0&&Number.isFinite(e)?Math.max(n,Math.min(r,e)):t;t[n]={amplitudePx:a(r.amplitudePx,i.amplitudePx,0,6),durationMs:a(r.durationMs,i.durationMs,25,300),frequencyHz:a(r.frequencyHz,i.frequencyHz,5,35)}}this.profiles=t}reset(){this.impulses.length=0,this.lastTriggered.clear()}trigger(e,t=1,n=performance.now()){if(!this.enabled||!Number.isFinite(t)||t<=0)return;let r=this.profiles[e];!r||r.amplitudePx<=0||n-(this.lastTriggered.get(e)??-1/0)<55||(this.lastTriggered.set(e,n),this.impulses.push({event:e,startedAt:n,profile:r,amplitudePx:Math.min(5,r.amplitudePx*Math.min(2,t)),phase:++this.sequence*2.399963}),this.impulses.length>4&&this.impulses.shift())}sample(e){if(!this.enabled||!this.impulses.length)return{x:0,y:0};let t=0,n=0;for(let r=this.impulses.length-1;r>=0;r--){let i=this.impulses[r],a=Math.max(0,e-i.startedAt);if(a>=i.profile.durationMs){this.impulses.splice(r,1);continue}let o=(1-a/i.profile.durationMs)**2,s=a*i.profile.frequencyHz*Math.PI*2/1e3,c=i.amplitudePx*o;t+=Math.sin(s+i.phase)*c,n+=Math.sin(s*1.17+i.phase*.7+.8)*c*.72}return{x:Math.max(-4,Math.min(4,t)),y:Math.max(-4,Math.min(4,n))}}};function vb(e,t,n,r){let i=e=>e-r.x,a=e=>e-r.y,o=(e,t,n,i)=>n>=r.x&&e<=r.x+r.width&&i>=r.y&&t<=r.y+r.height;e.save(),e.lineCap=`round`,e.lineJoin=`round`,e.font=`bold 11px ui-monospace, SFMono-Regular, monospace`,n.forEach((t,n)=>{let r=t.box;o(r.x,r.y,r.x+r.width,r.y+r.height)&&(e.setLineDash([5,5]),e.strokeStyle=`rgba(210, 95, 255, 0.9)`,e.lineWidth=1.5,e.strokeRect(i(r.x),a(r.y),r.width,r.height),e.setLineDash([]),e.fillStyle=`#d25fff`,e.fillText(`TARGET ${n+1}`,i(r.x)+5,a(r.y)-9))});for(let n of t.segments){if(n.kind===`donut`){if(!o(n.center.x-n.radius,n.center.y-n.radius,n.center.x+n.radius,n.center.y+n.radius))continue;e.setLineDash([5,7]),e.strokeStyle=`#c33bdf`,e.lineWidth=2,e.beginPath(),e.arc(i(n.center.x),a(n.center.y),n.radius,0,Math.PI*2),e.stroke(),e.setLineDash([]),e.fillStyle=`#c33bdf`,e.beginPath(),e.arc(i(n.center.x),a(n.center.y),4,0,Math.PI*2),e.fill(),e.fillText(`${n.laps} PHYSICS DONUT${n.laps===1?``:`S`}`,i(n.center.x)+10,a(n.center.y)-10);continue}if(n.kind===`pause`){if(!o(n.point.x-16,n.point.y-16,n.point.x+16,n.point.y+16))continue;e.fillStyle=`#f7ba4c`,e.beginPath(),e.arc(i(n.point.x),a(n.point.y),6,0,Math.PI*2),e.fill(),e.fillText(`${Math.round(n.seconds*1e3)}ms`,i(n.point.x)+11,a(n.point.y)-10);continue}let t=[n.from,n.control1,n.control2,n.to];o(Math.min(...t.map(e=>e.x)),Math.min(...t.map(e=>e.y)),Math.max(...t.map(e=>e.x)),Math.max(...t.map(e=>e.y)))&&(e.beginPath(),e.moveTo(i(n.from.x),a(n.from.y)),e.bezierCurveTo(i(n.control1.x),a(n.control1.y),i(n.control2.x),a(n.control2.y),i(n.to.x),a(n.to.y)),e.setLineDash([9,7]),e.strokeStyle=`#09b7cf`,e.lineWidth=2.5,e.stroke())}e.setLineDash([]),o(t.entry.x-12,t.entry.y-12,t.entry.x+12,t.entry.y+12)&&(e.fillStyle=`#09b7cf`,e.beginPath(),e.arc(i(t.entry.x),a(t.entry.y),6,0,Math.PI*2),e.fill(),e.fillText(`ENTRY`,i(t.entry.x)+11,a(t.entry.y)-10)),e.restore()}function yb(e,t){return e===null?1:Math.max(0,1-(t-e)/240)}function bb(e,t,n,r,i,a,o=!1){let s=!t.front&&(t.spinning||o);if(!t.skidding&&!o)return null;let c=s?.38+.62*t.heat:P(t.slip*(.22+t.heat*.78),0,1);if(c<.05)return null;let l=M(e.body.velocity),u=l>.1?A(e.body.velocity,-1/l):N(D(-1),e.body.angle),d=D(u.x,-u.y),f=D(Math.cos(e.body.angle),-Math.sin(e.body.angle)),p=D(-f.y,f.x),m=Math.sign(t.local.y)||1;return{point:a(e.body.world(O(t.local,D(0,m*e.car.preset.geometry.tireWidthM*.53)))),amount:n*(t.front?3:s?12:6.5)*c,flow:O(A(r,s?.08:.22),O(A(d,(s?110+Math.min(18,Math.abs(t.wheelSurfaceSpeedMps)*3):125)*c),A(p,m*(s?64:45)*c))),radiusPx:(s?.8:.55+t.heat*.16)*i,swirlPx:m*(s?85:105)*c,strength:c,burnout:s}}function xb(e,t,n,r,i,a,o,s=!1){let c=e.sim;c.car.tires.forEach((l,u)=>{let d=bb(c,l,r,a,o.zoom,o.particlePoint,s&&!l.front);if(!d)return;let f=c.body.world(l.local),p=Xy(d.burnout,c.body.angle,l.angle,c.body.velocityAt(f),i);o.spray(e,u,n+u,t[u].point,o.particleVelocity(p),t[u].radiusPx,r*(d.burnout?85:48)*d.strength,P(.75+l.slipSpeedMps/12+M(c.body.velocityAt(f))/28,.8,1.9)),o.smoke?.({point:d.point,amount:d.amount,flow:d.flow,radiusPx:d.radiusPx,swirlPx:d.swirlPx})})}var Sb=class{canvas=document.createElement(`canvas`);mask=document.createElement(`canvas`);gl=this.canvas.getContext(`webgl2`,{alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0});program=null;texture=null;startedAt=-1/0;duration=680;constructor(){let e=this.gl;e&&(this.program=Dv(e,`#version 300 es
771
+ }`,cy=class{canvas=document.createElement(`canvas`);gl;program;buffer;viewportUniform;fadeUniform;wallCountUniform;wallsUniform;disturbanceUniform;disturbanceRadiusUniform;electricColorUniform;electricCoronaUniform;wallData=new Float32Array(128);data=new Float32Array(256*ay);lost=!1;overlayHost=null;constructor(){this.canvas.width=512,this.canvas.height=512;let e=this.canvas.getContext(`webgl2`,{alpha:!0,depth:!1,stencil:!1,antialias:!0,premultipliedAlpha:!0});if(!e)throw Error(`WebGL2 is required for spark particles`);this.gl=e,this.canvas.addEventListener(`webglcontextlost`,e=>{e.preventDefault(),this.lost=!0});let t=Dv(e,oy,sy,`Spark`),n=e.createBuffer();if(!n)throw Pv(e,t),Error(`Unable to allocate spark buffer`);this.program=t,this.buffer=n,this.viewportUniform=kv(t,`uViewport`),this.fadeUniform=kv(t,`uFade`),this.wallCountUniform=kv(t,`uWallCount`),this.wallsUniform=kv(t,`uWalls[0]`),this.disturbanceUniform=kv(t,`uDisturbance`),this.disturbanceRadiusUniform=kv(t,`uDisturbanceRadius`),this.electricColorUniform=kv(t,`uElectricColor`),this.electricCoronaUniform=kv(t,`uElectricCorona`),e.bindBuffer(e.ARRAY_BUFFER,n),Mv(e,t,{aStart:{buffer:n,numComponents:2,stride:44,offset:0,divisor:1},aEnd:{buffer:n,numComponents:2,stride:44,offset:8,divisor:1},aMotion:{buffer:n,numComponents:2,stride:44,offset:16,divisor:1},aStyle:{buffer:n,numComponents:4,stride:44,offset:24,divisor:1},aSeed:{buffer:n,numComponents:1,stride:44,offset:40,divisor:1}})}clear(){if(this.lost||!this.overlayHost||this.canvas.style.display===`none`)return;let e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),e.disable(e.SCISSOR_TEST),e.viewport(0,0,this.canvas.width,this.canvas.height),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),this.canvas.style.display!==`none`&&(this.canvas.style.display=`none`)}dispose(){this.canvas.remove(),this.overlayHost=null,Pv(this.gl,this.program),this.gl.deleteBuffer(this.buffer),this.gl.getExtension(`WEBGL_lose_context`)?.loseContext(),this.lost=!0}mountOverlay(e,t,n){this.overlayHost!==e&&(this.canvas.remove(),this.overlayHost=e,this.canvas.dataset.jrOverlay=``,this.canvas.style.position=`fixed`,this.canvas.style.pointerEvents=`none`,this.canvas.style.zIndex=e.style.zIndex||ey(`world`),document.body.append(this.canvas)),this.canvas.style.display!==`block`&&(this.canvas.style.display=`block`);let r=e.hasAttribute(`data-jr-overlay`)?{left:0,top:0}:e.getBoundingClientRect(),i=`${r.left}px`,a=`${r.top}px`,o=`${t.width}px`,s=`${t.height}px`;this.canvas.style.left!==i&&(this.canvas.style.left=i),this.canvas.style.top!==a&&(this.canvas.style.top=a),this.canvas.style.width!==o&&(this.canvas.style.width=o),this.canvas.style.height!==s&&(this.canvas.style.height=s);let c=Math.ceil(t.width*n),l=Math.ceil(t.height*n);(this.canvas.width!==c||this.canvas.height!==l)&&(this.canvas.width=c,this.canvas.height=l)}draw(e,t,n,r,i=1,a,o=[],s,c=iy){if(this.lost||!t.length||n<=0){this.clear();return}let l=t.filter(e=>{let t=e.kind===2?ly(e.start,e.motion,e.age,e.seed):e.end;return t.x>-64&&t.x<r.width+64&&t.y>-64&&t.y<r.height+64});if(!l.length){this.clear();return}let u=1/0,d=1/0,f=-1/0,p=-1/0;for(let e of l){let t=e.kind===2?ly(e.start,e.motion,e.age,e.seed):e.end,n=e.kind===2?ly(e.start,e.motion,Math.max(0,e.age-.045),e.seed):e.start;u=Math.min(u,n.x,t.x),f=Math.max(f,n.x,t.x),d=Math.min(d,n.y,t.y),p=Math.max(p,n.y,t.y)}let m=a?0:Math.floor((u-16)/32)*32,h=a?0:Math.floor((d-16)/32)*32,g=a?r.width:Math.max(32,Math.ceil((f+16-m)/32)*32),_=a?r.height:Math.max(32,Math.ceil((p+16-h)/32)*32),v=Math.min(2,Math.max(1,i)),y=Math.ceil(g*v),b=Math.ceil(_*v);a?this.mountOverlay(a,r,v):(y>this.canvas.width&&(this.canvas.width=Math.ceil(y/256)*256),b>this.canvas.height&&(this.canvas.height=Math.ceil(b/256)*256)),this.data.length<l.length*ay&&(this.data=new Float32Array(Math.max(l.length*ay,this.data.length*2)));let x=0;for(let e of l)this.data[x]=(e.start.x-m)*v,this.data[x+1]=(e.start.y-h)*v,this.data[x+2]=(e.end.x-m)*v,this.data[x+3]=(e.end.y-h)*v,this.data[x+4]=e.motion.x*v,this.data[x+5]=e.motion.y*v,this.data[x+6]=e.age,this.data[x+7]=e.life,this.data[x+8]=e.size*v,this.data[x+9]=e.kind,this.data[x+10]=e.seed,x+=ay;let S=this.gl;performance.now();let C=a?0:this.canvas.height-b;S.viewport(0,C,y,b),a||(S.enable(S.SCISSOR_TEST),S.scissor(0,C,y,b)),S.clearColor(0,0,0,0),S.clear(S.COLOR_BUFFER_BIT),S.useProgram(this.program),S.bindBuffer(S.ARRAY_BUFFER,this.buffer),S.bufferData(S.ARRAY_BUFFER,this.data.subarray(0,x),S.DYNAMIC_DRAW),S.uniform2f(this.viewportUniform,y,b),S.uniform1f(this.fadeUniform,n),S.uniform3f(this.electricColorUniform,...c.color),S.uniform3f(this.electricCoronaUniform,...c.corona),s?(S.uniform4f(this.disturbanceUniform,(s.point.x-m)*v,(s.point.y-h)*v,s.velocity.x*v,s.velocity.y*v),S.uniform1f(this.disturbanceRadiusUniform,s.radius*v)):(S.uniform4f(this.disturbanceUniform,-1e5,-1e5,0,0),S.uniform1f(this.disturbanceRadiusUniform,1));let w=Math.min(32,o.length);for(let e=0;e<w;e++){let t=o[e],n=e*4;this.wallData[n]=(t.x-m)*v,this.wallData[n+1]=(t.y-h)*v,this.wallData[n+2]=(t.x+t.width-m)*v,this.wallData[n+3]=(t.y+t.height-h)*v}S.uniform1i(this.wallCountUniform,w),w&&S.uniform4fv(this.wallsUniform,this.wallData.subarray(0,w*4)),S.enable(S.BLEND),S.blendFuncSeparate(S.SRC_ALPHA,S.ONE_MINUS_SRC_ALPHA,S.ONE,S.ONE_MINUS_SRC_ALPHA),S.drawArraysInstanced(S.TRIANGLES,0,6,l.length),S.disable(S.BLEND),a||S.disable(S.SCISSOR_TEST),!a&&(performance.now(),e.drawImage(this.canvas,0,0,y,b,m,h,g,_))}};function ly(e,t,n,r){let i=r*Math.PI*2,a=3+r*73.19%1*3.1,o=7.5+r*41.73%1*6.2;return{x:e.x+t.x*n+(Math.sin(a*n+i*2.3)-Math.sin(i*2.3))*(5+r*91.7%1*13)+(Math.sin(o*n-i*3.1)-Math.sin(-i*3.1))*3.5,y:e.y+t.y*n-n*n*(24+r*19.3%1*38)+(Math.cos(a*n+i*1.7)-Math.cos(i*1.7))*4+(Math.sin(o*n+i*4.7)-Math.sin(i*4.7))*2.5}}var uy=360,dy=(e,t,n)=>Math.max(t,Math.min(n,e));function fy(e){let t=Math.max(1,e.pixelsPerMeter),n=Math.max(0,-j(e.velocity,e.normal))/t,r=M(k(e.velocity,A(e.normal,j(e.velocity,e.normal))))/t,i=r/Math.max(.001,r+n),a=dy((n+(e.wall?.4:0))/1.8,0,1)*dy((r-.8)/7,0,1)*dy(i/.65,0,1),o=dy((n-1.4)/9,0,1)*(1-i*.35);return Math.max(a,o)}function py(e){let t=t=>{let n=D(-t.y,t.x);return j(n,e.velocity)<0&&(n=A(n,-1)),n},n=t(e.normal),r=O(n,t(e.carNormal??A(e.normal,-1))),i=M(r);if(i<.001)return n;let a=O(A(r,1/i),A(e.normal,.12));return A(a,1/M(a))}function my(e,t){let n=dy(e.x,t.x,t.x+t.width),r=dy(e.y,t.y,t.y+t.height);return e.x!==n||e.y!==r?D(n,r):[{distance:n-t.x,point:D(t.x,r)},{distance:t.x+t.width-n,point:D(t.x+t.width,r)},{distance:r-t.y,point:D(n,t.y)},{distance:t.y+t.height-r,point:D(n,t.y+t.height)}].reduce((e,t)=>t.distance<e.distance?t:e).point}function hy(e,t,n){if(Math.abs(n.x)>=Math.abs(n.y)){let r=D(n.x<0?-1:1,0);return{point:D(r.x<0?t.x:t.x+t.width,dy(e.y,t.y,t.y+t.height)),normal:r}}let r=D(0,n.y<0?-1:1);return{point:D(dy(e.x,t.x,t.x+t.width),r.y<0?t.y:t.y+t.height),normal:r}}function gy(e,t,n){let r=j(e.velocity,t);r<0&&(e.velocity=k(e.velocity,A(t,r*(1+n))))}function _y(e,t,n){let r=e.point,i=e=>e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height,a=k(r,n),o=0,s=1,c=D(),l=!0;for(let e of[`x`,`y`]){let r=a[e],i=t[e],u=i+(e===`x`?t.width:t.height);if(Math.abs(r)<1e-6){if(n[e]<i||n[e]>u){l=!1;break}continue}let d=(i-n[e])/r,f=(u-n[e])/r,p=Math.min(d,f),m=Math.max(d,f);if(p>o&&(o=p,c=e===`x`?D(r>0?-1:1,0):D(0,r>0?-1:1)),s=Math.min(s,m),o>s){l=!1;break}}if(l&&!i(n)&&o>=0&&o<=1&&o<=s&&M(c)){e.point=O(O(n,A(a,o)),A(c,.75)),gy(e,c,.38);return}if(!i(r))return;let u=hy(my(r,t),t,[{value:Math.abs(n.x-t.x),normal:D(-1,0)},{value:Math.abs(n.x-t.x-t.width),normal:D(1,0)},{value:Math.abs(n.y-t.y),normal:D(0,-1)},{value:Math.abs(n.y-t.y-t.height),normal:D(0,1)}].reduce((e,t)=>t.value<e.value?t:e).normal);e.point=O(u.point,A(u.normal,.75)),gy(e,u.normal,.38),e.previous={...e.point}}var vy=class{random;particles=[];walls=[];gpu=null;gpuUnavailable=!1;elapsed=0;lastEmission=-1/0;enabled=!0;electricalPalette=iy;airflow=null;constructor(e=Math.random){this.random=e}captureState(){return E({particles:this.particles,walls:this.walls,gpuUnavailable:this.gpuUnavailable,elapsed:this.elapsed,lastEmission:this.lastEmission,enabled:this.enabled,electricalPalette:this.electricalPalette,airflow:this.airflow})}restoreState(e){this.gpu?.clear();let t=E(e);this.particles=t.particles,this.walls=t.walls,this.gpuUnavailable=t.gpuUnavailable,this.elapsed=t.elapsed,this.lastEmission=t.lastEmission,this.enabled=t.enabled,this.electricalPalette=t.electricalPalette,this.airflow=t.airflow}get count(){return this.particles.length}setEnabled(e){this.enabled=e,e||this.reset()}prepare(){if(!this.enabled||this.gpu||this.gpuUnavailable)return!!this.gpu;try{this.gpu=new cy}catch{this.gpuUnavailable=!0}return!!this.gpu}reset(){this.particles=[],this.lastEmission=-1/0,this.walls=[],this.airflow=null,this.gpu?.clear()}setElectricalPalette(e){let t=(e,t)=>Number.isFinite(e)?dy(e,0,1):t,n=e.color??this.electricalPalette.color,r=e.corona??this.electricalPalette.corona;this.electricalPalette={color:[0,1,2].map(e=>t(n[e],this.electricalPalette.color[e])),corona:[0,1,2].map(e=>t(r[e],this.electricalPalette.corona[e]))}}electric(e,t,n=1){if(!this.enabled||!Number.isFinite(n)||n<=0||!Number.isFinite(e.x)||!Number.isFinite(e.y)||!Number.isFinite(t.x)||!Number.isFinite(t.y))return 0;let r=dy(n,.1,3),i=M(t)>.001,a=i?Math.atan2(t.y,t.x):0,o=Math.round(3+r*5);for(let t=0;t<o;t++){let t=i?a+(this.random()-.5)*1.6:this.random()*Math.PI*2,n=D(Math.cos(t),Math.sin(t)),o=O(e,A(n,this.random()*1.6));this.particles.push({point:o,previous:{...o},velocity:A(n,(220+this.random()*460)*Math.sqrt(r)),plane:null,age:0,life:.06+this.random()*.16,size:.65+this.random()*.7,kind:4,seed:this.random()})}return this.trim(),o}disturb(e,t,n=90){this.airflow={point:{...e},velocity:{...t},radius:n}}dispose(){this.gpu?.dispose(),this.gpu=null}emit(e){if(!this.enabled||this.elapsed-this.lastEmission<.045)return 0;let t=fy(e);if(t<=0)return 0;this.lastEmission=this.elapsed;let n=py(e),r=k(e.velocity,A(e.normal,j(e.velocity,e.normal))),i=Math.max(0,-j(e.velocity,e.normal)),a=i/Math.max(.001,i+M(r)),o=O(A(n,1-a),A(e.normal,a)),s=M(o),c=s>.001?A(o,1/s):e.normal,l=Math.round(24+80*Math.sqrt(t)),u=M(e.velocity)/Math.max(1,e.pixelsPerMeter),d=e.wall?hy(e.point,e.wall,e.normal):null,f=d?.point??e.point,p=d?.normal??e.normal;for(let n=0;n<l;n++){let n=(this.random()-.5)*(.4+t*.45+a*1.5),i=Math.cos(n),o=Math.sin(n),s=O(A(D(c.x*i-c.y*o,c.x*o+c.y*i),(140+Math.min(420,u*30))*(.45+this.random()*1.15)),A(r,.08)),l=O(f,A(p,e.wall?1.35+this.random()*.25:.35+this.random()*.3));this.particles.push({point:l,previous:{...l},velocity:s,plane:{origin:f,normal:p},age:0,life:.18+this.random()*.34,size:.85+this.random()*1.6,kind:0,seed:this.random()})}let m=O(f,A(p,e.wall?1.5:.8));return this.particles.push({point:m,previous:{...m},velocity:D(),plane:null,age:0,life:.18,size:5.5+t*4,kind:3,seed:this.random()}),this.trim(),l+1}emitBulletImpact(e,t){if(!this.enabled)return;let n=M(t);if(n<.001)return;let r=A(t,-1/n),i=O(e,A(r,1.4));for(let t=0;t<40;t++){let n=(this.random()-.5)*2.7,a=D(r.x*Math.cos(n)-r.y*Math.sin(n),r.x*Math.sin(n)+r.y*Math.cos(n)),o=O(i,A(a,this.random()*1.5));this.particles.push({point:o,previous:{...o},velocity:A(a,t<12?320+this.random()*300:150+this.random()*330),plane:{origin:e,normal:r},age:0,life:.16+this.random()*.24,size:.7+this.random()*1.2,kind:0,seed:this.random()})}this.particles.push({point:i,previous:{...i},velocity:D(),plane:null,age:0,life:.15,size:8,kind:3,seed:this.random()}),this.trim()}emitExplosion(e,t,n,r=1){if(!this.enabled)return 0;let i=Math.max(1,n),a=dy(r,.5,2),o=Math.atan2(t.y,t.x),s=Math.round(32+20*Math.sqrt(a));for(let t=0;t<s;t++){let n=o+t*Math.PI*(3-Math.sqrt(5))+(this.random()-.5)*.3,r=D(Math.cos(n),Math.sin(n)),s=i*(5+this.random()*9)*Math.sqrt(a),c=O(e,A(r,i*.03));this.particles.push({point:c,previous:{...c},velocity:A(r,s),plane:null,age:0,life:.24+this.random()*.36,size:1+this.random()*1.1,kind:1,seed:this.random()})}return this.trim(),s}emitFire(e,t){if(!this.enabled||this.random()>=Math.min(1,t*15))return;let n=D(e.x+e.width/2,e.y+e.height/2),r=Math.cos(e.angle??0),i=Math.sin(e.angle??0);for(let t=0;t<12;t++){let t=e.fixedRadius??0,a=this.random()*Math.PI*2,o=Math.sqrt(this.random())*t,s=t>0?O(e.origin,D(Math.cos(a)*o,Math.sin(a)*o)):D(e.x+this.random()*e.width,e.y+this.random()*e.height),c=s.x-n.x,l=s.y-n.y,u=c*r+l*i,d=-c*i+l*r,f=Math.floor((u/e.width+.5)*e.pixelWidth),p=Math.floor((d/e.height+.5)*e.pixelHeight);if(f<0||p<0||f>=e.pixelWidth||p>=e.pixelHeight||(e.alpha[p*e.pixelWidth+f]??0)<32)continue;let m=D(n.x+u*r-d*i,n.y+u*i+d*r),h=(e.age-(t>0?0:Math.hypot(m.x-e.origin.x,m.y-e.origin.y)/e.farthest*e.spreadSeconds))/e.burnSeconds;if(!(h<=0||h>=.82)){this.addEmber(m);return}}}emitFireAt(e,t,n,r=10){if(!this.enabled||this.random()>=Math.min(1,n*r))return;let i=this.random()*Math.PI*2,a=Math.sqrt(this.random())*t;this.addEmber(O(e,D(Math.cos(i)*a,Math.sin(i)*a)))}addEmber(e){this.particles.push({point:e,previous:{...e},velocity:D((this.random()-.5)*76,-35-this.random()*100),plane:null,age:0,life:.5+this.random()*1.25,size:.55+this.random()**2*1.25,kind:2,seed:this.random()}),this.trim()}trim(){this.particles.length>uy&&this.particles.splice(0,this.particles.length-uy)}step(e,t={walls:[]}){if(this.elapsed+=e,this.airflow){let t=Math.exp(-e*5.5);this.airflow.velocity=A(this.airflow.velocity,t),M(this.airflow.velocity)<1&&(this.airflow=null)}if(this.walls=t.walls,!this.particles.length)return;let n=Math.min(e,.05);for(let e of this.particles)if(e.age+=n,e.kind!==2&&e.kind!==3){e.previous={...e.point};for(let r=0;r<2;r++){let r={...e.point},i=e.kind===4,a=i?8+e.seed*8:3.2+e.seed*6.3;if(e.velocity=A(e.velocity,Math.exp(-a*n/2)),i){let t=(e.seed-.5)*9*n*.5,r=Math.cos(t),i=Math.sin(t);e.velocity=D(e.velocity.x*r-e.velocity.y*i,e.velocity.x*i+e.velocity.y*r)}else e.velocity.y+=(38+e.seed*84)*n*.5;if(e.point=O(e.point,A(e.velocity,n/2)),e.plane){let t=j(k(e.point,e.plane.origin),e.plane.normal);t<0&&(e.point=O(e.point,A(e.plane.normal,-t+.4)),gy(e,e.plane.normal,.55))}for(let n of t.walls)_y(e,n,r);if(t.car&&Qt(t.car.mask,t.car.shape,e.point)){let n=en(t.car.mask,t.car.shape,e.point);for(let r=0;r<16&&Qt(t.car.mask,t.car.shape,e.point);r++)e.point=O(e.point,A(n,1.2));gy(e,n,.48)}}}this.particles=this.particles.filter(e=>e.age<e.life)}draw(e,t,n,r,i=1,a){if(!this.enabled||!this.particles.length||n<=0){this.gpu?.clear();return}if(this.prepare(),!this.gpu)return;let o=this.particles.map(e=>{let n=t(e.point),r=k(t(O(e.point,e.velocity)),n),i=e.kind<2||e.kind===4,a=i?t(e.previous):n;if(i){let i=k(n,a),o=M(i),s=e.kind===4?Math.min(20,M(r)*.04):Math.min(18,M(r)*(e.kind===1?.032:.038));if(o>.001&&o<s?(a.x=n.x-i.x/o*s,a.y=n.y-i.y/o*s):o<1&&(a.x-=r.x*.02,a.y-=r.y*.02),e.plane){let n=t(e.plane.origin),r=k(t(O(e.plane.origin,e.plane.normal)),n),i=j(k(a,n),r)/Math.max(1e-6,M(r));if(i<.7){let e=A(r,1/Math.max(1e-6,M(r)));a.x+=e.x*(.7-i),a.y+=e.y*(.7-i)}}}return{start:a,end:n,motion:r,age:e.age,life:e.life,size:e.size,kind:e.kind,seed:e.seed}}),s=[];if(a)for(let e of this.walls){let n=t({x:e.x,y:e.y}),i=t({x:e.x+e.width,y:e.y+e.height}),a=Math.min(n.x,i.x),o=Math.min(n.y,i.y),c=Math.abs(n.x-i.x),l=Math.abs(n.y-i.y);if(!(a>r.width||o>r.height||a+c<0||o+l<0)&&(s.push({x:a,y:o,width:c,height:l}),s.length===32))break}let c=this.airflow?{point:t(this.airflow.point),velocity:k(t(O(this.airflow.point,this.airflow.velocity)),t(this.airflow.point)),radius:M(k(t(O(this.airflow.point,D(this.airflow.radius,0))),t(this.airflow.point)))}:void 0;this.gpu.draw(e,o,n,r,i,a,s,c,this.electricalPalette)}},yy=[[0,0],[60,120],[120,180],[240,240],[300,300],[360,360]];function by(e,t=!1){for(let n=1;n<yy.length;n++){let r=yy[n-1],i=yy[n],a=t?r[1]:r[0],o=t?i[1]:i[0];if(e<=o)return(t?r[0]:r[1])+(e-a)/(o-a)*((t?i[0]:i[1])-(t?r[0]:r[1]))}return e}function xy(e){let[t,n,r]=e.map(e=>e/255),i=Math.max(t,n,r),a=Math.min(t,n,r),o=i-a,s=(i+a)*.5,c=o===0?0:o/(1-Math.abs(2*s-1)),l=o===0?0:i===t?(n-r)/o%6:i===n?(r-t)/o+2:(t-n)/o+4;return l=by((l*60+360)%360)*Math.PI/180,[.5+.5*Math.cos(l)*c,.5+.5*Math.sin(l)*c,c,s]}function Sy(e){let t=e[0]*2-1,n=e[1]*2-1,r=Math.max(0,Math.min(1,e[2])),i=Math.max(0,Math.min(1,Math.hypot(t,n)/Math.max(r,1e-6))),a=r*Math.min(1,Math.sqrt(i*2)),o=Math.max(0,Math.min(1,e[3]))*(r>1e-6?.65+.35*i:1),s=by((Math.atan2(n,t)*180/Math.PI+360)%360,!0),c=(1-Math.abs(2*o-1))*a,l=c*(1-Math.abs(s/60%2-1)),u=Math.floor(s/60)%6,d=0,f=0,p=0;switch(u){case 0:d=c,f=l;break;case 1:d=l,f=c;break;case 2:f=c,p=l;break;case 3:f=l,p=c;break;case 4:d=l,p=c;break;default:d=c,p=l}let m=o-c*.5;return[Math.max(0,Math.min(255,(d+m)*255)),Math.max(0,Math.min(255,(f+m)*255)),Math.max(0,Math.min(255,(p+m)*255))]}function Cy(e){let t=lt[e],n=e===`paint`?null:ft(e),r=Math.max(t?.gloss??0,(n?.surface?.clearcoat??0)*.5),i=Math.max(t?.relief??0,(n?.surface?.microRelief??0)*.7),a=Math.max(t?.film??0,n?.iridescence??0),o=Math.max(t?.grain??0,n?.sediment??0),s=n?.atmosphere?.emission??0;return{gloss:r,relief:i,film:a,grain:o,emission:s,emissionColor:n?.atmosphere?.emissionColor??[0,0,0],shaded:r+i+a+o+s>0}}function wy(e,t,n,r,i,a){if(!e.shaded)return t;let o=Math.max(0,-i*.55-a*.8)*e.gloss*82,s=Math.sin(n*.16+r*.08)*e.relief*8,c=Math.sin(n*.095+r*.13+i*3)*e.film*27,l=Math.sin(n*127.1+r*311.7)*43758.5453%1*e.grain*12,u=o+s+l,d=e.emission*.22,f=(t,n,r)=>Math.max(0,Math.min(255,t+u+r+e.emissionColor[n]*d));return[f(t[0],0,c),f(t[1],1,-c*.65),f(t[2],2,c*.8)]}var H=(e,t,n)=>Math.max(t,Math.min(n,e)),Ty=new Uint8Array(new Uint32Array([1]).buffer)[0]===1,Ey=(e,t,n)=>e+(t-e)*n,Dy=[[1,0],[-1,0],[0,1],[0,-1]],Oy=[[.7,.7],[-.7,.7],[.7,-.7],[-.7,-.7]],ky=class{kind;width;height;profile;canvas=document.createElement(`canvas`);splatterCanvas=null;splatterBounds=null;splatterDirty=!1;material;authored;deposited;pigment;colorPixels;basePixels;outline;spring;velocity;drops=[];burnDecay=new Float32Array;revision=0;pulled=!1;maxOutline=0;presented=-1;active=null;activeCells=new Set;outlineCells=new Set;wetBounds=null;renderedBounds=null;dirtyBounds=null;fullDirty=!0;color;appearance;cellSizePx=1;listeners=new Set;constructor(e,t,n,r,i){this.kind=e,this.width=t,this.height=n,this.profile=i,this.color=[...r],this.appearance=Cy(e);let a=T[e];this.material={thickness:a.thickness,deformation:i?.deformation??a.deformation,alpha:i?.opacity??a.alpha};let o=t*n;this.authored=new Uint8Array(o),this.deposited=new Uint8Array(o),this.pigment=new Float32Array(o*4),this.colorPixels=new Uint8Array(o*3),this.basePixels=Ty&&!this.appearance.shaded?new Uint32Array(o):null,this.outline=new Float32Array(o*2),this.spring=new Float32Array(o*2),this.velocity=new Float32Array(o*2),this.canvas.width=t,this.canvas.height=n}get shapeRevision(){return this.revision}get displaced(){return this.pulled||this.active!==null}get moving(){return this.active!==null}get hasSplatter(){return this.drops.length>0}get hasDeposits(){return this.deposited.some(e=>e>0)}get managedBytes(){return this.authored.byteLength+this.deposited.byteLength+this.pigment.byteLength+this.colorPixels.byteLength+(this.basePixels?.byteLength??0)+this.outline.byteLength+this.spring.byteLength+this.velocity.byteLength+this.canvas.width*this.canvas.height*4+(this.splatterCanvas?this.splatterCanvas.width*this.splatterCanvas.height*4:0)}setCellSize(e){this.cellSizePx=Math.max(.01,e)}configure(e,t){this.color=[...e],this.material.deformation=t?.deformation??T[this.kind].deformation;let n=t?.opacity??T[this.kind].alpha;n!==this.material.alpha&&(this.material.alpha=n,this.rebuildBasePixels()),this.changed()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}changed(e){e?this.fullDirty||(this.dirtyBounds=this.dirtyBounds?{left:Math.min(this.dirtyBounds.left,e.left),top:Math.min(this.dirtyBounds.top,e.top),right:Math.max(this.dirtyBounds.right,e.right),bottom:Math.max(this.dirtyBounds.bottom,e.bottom)}:{...e}):(this.fullDirty=!0,this.dirtyBounds=null),this.revision++;for(let e of this.listeners)e()}alphaAt(e){return Math.max(this.authored[e],this.deposited[e])}refreshBasePixel(e){if(!this.basePixels)return;let t=this.alphaAt(e),n=e*3;this.basePixels[e]=Math.round(t*this.material.alpha)<<24|this.colorPixels[n+2]<<16|this.colorPixels[n+1]<<8|this.colorPixels[n]}rebuildBasePixels(){if(this.basePixels)for(let e=0;e<this.width*this.height;e++)this.refreshBasePixel(e)}wetAt(e,t){let n=Math.floor(e),r=Math.floor(t);return n>=0&&r>=0&&n<this.width&&r<this.height&&this.alphaAt(r*this.width+n)>=24}includeWetBounds(e){this.wetBounds=this.wetBounds?{left:Math.min(this.wetBounds.left,e.left),top:Math.min(this.wetBounds.top,e.top),right:Math.max(this.wetBounds.right,e.right),bottom:Math.max(this.wetBounds.bottom,e.bottom)}:e}rebuildWetBounds(){let e=this.width,t=this.height,n=-1,r=-1;for(let i=0;i<this.height;i++)for(let a=0;a<this.width;a++)this.alphaAt(i*this.width+a)&&(e=Math.min(e,a),t=Math.min(t,i),n=Math.max(n,a),r=Math.max(r,i));this.wetBounds=n>=e?{left:e,top:t,right:n,bottom:r}:null}componentAt(e,t,n,r){let i=H(t.x-.5,0,this.width-1),a=H(t.y-.5,0,this.height-1),o=Math.floor(i),s=Math.floor(a),c=Math.min(this.width-1,o+1),l=Math.min(this.height-1,s+1),u=i-o,d=a-s,f=e[(s*this.width+o)*r+n],p=e[(s*this.width+c)*r+n],m=e[(l*this.width+o)*r+n],h=e[(l*this.width+c)*r+n];return Ey(Ey(f,p,u),Ey(m,h,u),d)}offsetAt(e,t=!0){return{x:this.componentAt(this.spring,e,0,2)+(t?this.componentAt(this.outline,e,0,2):0),y:this.componentAt(this.spring,e,1,2)+(t?this.componentAt(this.outline,e,1,2):0)}}sourcePoint(e){let t=this.offsetAt(e);return{x:e.x-t.x,y:e.y-t.y}}rawCoverage(e){return this.rawCoverageXY(e.x,e.y)}rawCoverageXY(e,t){if(e<0||t<0||e>=this.width||t>=this.height)return 0;let n=H(e-.5,0,this.width-1),r=H(t-.5,0,this.height-1),i=Math.floor(n),a=Math.floor(r),o=Math.min(this.width-1,i+1),s=Math.min(this.height-1,a+1),c=n-i,l=r-a;return Ey(Ey(this.alphaAt(a*this.width+i),this.alphaAt(a*this.width+o),c),Ey(this.alphaAt(s*this.width+i),this.alphaAt(s*this.width+o),c),l)/255}densityAt(e){return e.x<0||e.y<0||e.x>=this.width||e.y>=this.height?0:this.rawCoverage(this.sourcePoint(e))}colorAt(e){let t=this.sourcePoint(e),n=H(Math.floor(t.y),0,this.height-1)*this.width+H(Math.floor(t.x),0,this.width-1);return this.alphaAt(n)?[this.colorPixels[n*3],this.colorPixels[n*3+1],this.colorPixels[n*3+2]]:this.color}captureFuel(){let e=new Float32Array(this.width*this.height);for(let t=0;t<this.height;t++)for(let n=0;n<this.width;n++)e[t*this.width+n]=this.densityAt({x:n+.5,y:t+.5});return e}inspectState(){let e=this.captureFuel(),t=0,n=1/0,r=0;for(let i of e)t+=i,n=Math.min(n,i),r=Math.max(r,i);return{volume:t,minimum:n,maximum:r,finite:Number.isFinite(t)}}setPigment(e,t,n,r=xy(t)){let i=e*4;if(n>=1||!this.alphaAt(e))for(let e=0;e<4;e++)this.pigment[i+e]=r[e];else for(let e=0;e<4;e++)this.pigment[i+e]=Ey(this.pigment[i+e],r[e],n);let a=Sy([this.pigment[i],this.pigment[i+1],this.pigment[i+2],this.pigment[i+3]]);for(let t=0;t<3;t++)this.colorPixels[e*3+t]=Math.round(a[t]);this.refreshBasePixel(e)}seedMask(e,t,n,r=this.color){if(e.length!==this.width*this.height)throw RangeError(`Liquid seed must match the field resolution`);this.authored.set(e);let i=xy(r),a=this.width,o=this.height,s=-1,c=-1;for(let t=0;t<e.length;t++){if(e[t]&&!this.deposited[t]&&(this.pigment.set(i,t*4),this.colorPixels.set(r,t*3)),this.refreshBasePixel(t),!e[t]&&!this.deposited[t])continue;let n=t%this.width,l=(t-n)/this.width;n<a&&(a=n),n>s&&(s=n),l<o&&(o=l),l>c&&(c=l)}this.wetBounds=s>=a?{left:a,top:o,right:s,bottom:c}:null,this.changed()}removeSeed(){this.authored.fill(0),this.rebuildBasePixels(),this.rebuildWetBounds(),this.changed()}pour(e,t,n,r,i,a=this.color,o=n,s=r){if(!(e>0))return;n=this.sourcePoint(n),o=this.sourcePoint(o);let c=Math.max(0,Math.floor(Math.min(o.x-s,n.x-r)-2)),l=Math.min(this.width-1,Math.ceil(Math.max(o.x+s,n.x+r)+2)),u=Math.max(0,Math.floor(Math.min(o.y-s,n.y-r)-2)),d=Math.min(this.height-1,Math.ceil(Math.max(o.y+s,n.y+r)+2)),f=n.x-o.x,p=n.y-o.y,m=Math.max(1e-6,f*f+p*p),h=xy(a),g=!1;for(let t=u;t<=d;t++)for(let i=c;i<=l;i++){let c=i+.5,l=t+.5,u=H(((c-o.x)*f+(l-o.y)*p)/m,0,1),d=Ey(o.x,n.x,u),_=Ey(o.y,n.y,u),v=Ey(s,r,u),y=Math.hypot(c-d,l-_),b=Math.round(H(v+.5-y,0,1)*255);if(!b)continue;let x=t*this.width+i,S=this.alphaAt(x),C=this.colorPixels[x*3]===a[0]&&this.colorPixels[x*3+1]===a[1]&&this.colorPixels[x*3+2]===a[2];b<=this.deposited[x]&&S&&C||(!S||C?(this.pigment.set(h,x*4),this.colorPixels.set(a,x*3)):this.setPigment(x,a,H(e*b/(S*2),0,1),h),this.deposited[x]=Math.max(this.deposited[x],b),this.refreshBasePixel(x),g=!0)}g&&(this.includeWetBounds({left:c,top:u,right:l,bottom:d}),this.changed())}transferPigment(e,t,n,r,i){if(!(i>0))return;let a=xy(r),o=this.width,s=this.height,c=-1,l=-1;if(this.eachContactPixel(e,t,n,(e,t,n,u)=>{if(!this.alphaAt(e))return;this.setPigment(e,r,H(t*i,0,1),a);let d=Math.floor(n),f=Math.floor(u);o=Math.min(o,d),s=Math.min(s,f),c=Math.max(c,d),l=Math.max(l,f)},Math.max(2,n*1.1)),c>=o){let e=Math.ceil(this.maxOutline+8/this.cellSizePx)+2;this.changed({left:o-e,top:s-e,right:c+e,bottom:l+e})}}eachContactPixel(e,t,n,r,i=Math.max(2,n*1.8,(24*this.material.deformation+2)/this.cellSizePx)){let a=this.wetBounds,o=i+(this.pulled||this.active?8/this.cellSizePx:0),s=Math.max(0,Math.floor(Math.min(e.x,t.x)-i),a?Math.floor(a.left-o):0),c=Math.min(this.width-1,Math.ceil(Math.max(e.x,t.x)+i),a?Math.ceil(a.right+o):this.width-1),l=Math.max(0,Math.floor(Math.min(e.y,t.y)-i),a?Math.floor(a.top-o):0),u=Math.min(this.height-1,Math.ceil(Math.max(e.y,t.y)+i),a?Math.ceil(a.bottom+o):this.height-1),d=t.x-e.x,f=t.y-e.y,p=Math.max(1e-6,d*d+f*f),m=i*i;for(let t=l;t<=u;t++)for(let n=s;n<=c;n++){let a=n+.5,o=t+.5,s=H(((a-e.x)*d+(o-e.y)*f)/p,0,1),c=a-e.x-d*s,l=o-e.y-f*s,u=c*c+l*l;if(u>=m)continue;let h=1-Math.sqrt(u)/i;r(t*this.width+n,h*h,a,o)}return{left:s,top:l,right:c,bottom:u}}drag(e,t,n,r=5.5,i=0){if(this.material.deformation===0)return;let a=t.x-e.x,o=t.y-e.y;if(Math.hypot(a,o)<.5)return;let s=Math.max(2,r*1.8,(24*this.material.deformation+2)/this.cellSizePx),c=Math.max(2,r*1.8),l=Math.hypot(a,o),u=a/l,d=o/l,f=Math.max(2,r*1.25),p=!1,m=this.width,h=this.height,g=-1,_=-1,v=this.eachContactPixel(e,t,r,(e,t,n,r)=>{let i=Math.floor(n),c=Math.floor(r);if(!this.wetAt(n-u*f,r-d*f)||this.wetAt(n+u*f,r+d*f))return;let l=this.alphaAt(e)>=24,v=0;for(let[e,t]of Dy)this.wetAt(n+e*s*.35,r+t*s*.35)===l?this.wetAt(n+e*s*.7,r+t*s*.7)===l?this.wetAt(n+e*s,r+t*s)!==l&&(v=Math.max(v,.12)):v=Math.max(v,.3):v=Math.max(v,.65);if(!l&&v===0){for(let[e,t]of Oy)if(this.wetAt(n+e*s,r+t*s)){v=.12;break}}if(!l&&v===0)return;let y=this.material.deformation/(.65+this.material.thickness*.7),b=e*2;if(this.velocity[b]=H(this.velocity[b]+a*t*18*y,-90,90),this.velocity[b+1]=H(this.velocity[b+1]+o*t*18*y,-90,90),this.activeCells.add(e),v>0){let n=24*this.material.deformation/this.cellSizePx;this.outline[b]=H(this.outline[b]+a*t*y*v*.48,-n,n),this.outline[b+1]=H(this.outline[b+1]+o*t*y*v*.48,-n,n),this.maxOutline=Math.max(this.maxOutline,Math.abs(this.outline[b]),Math.abs(this.outline[b+1])),this.pulled=!0,this.outlineCells.add(e)}p=!0,m=Math.min(m,i),h=Math.min(h,c),g=Math.max(g,i),_=Math.max(_,c)},c);p&&(this.active=this.active?{left:Math.min(v.left,this.active.left),top:Math.min(v.top,this.active.top),right:Math.max(v.right,this.active.right),bottom:Math.max(v.bottom,this.active.bottom)}:v,this.changed({left:m,top:h,right:g,bottom:_}))}step(e,t=0,n=[],r,i=e){let a=H(e,0,1/30);if(this.activeCells.size){let e=Math.exp(-(7+this.material.thickness*5)*a),t=this.width,n=this.height,r=-1,i=-1;for(let o of this.activeCells){let s=o%this.width,c=Math.floor(o/this.width),l=0;for(let t=0;t<2;t++){let n=o*2+t,r=this.spring[n],i=(this.velocity[n]-r*95*a)*e;this.velocity[n]=i,this.spring[n]=H(r+i*a,-8/this.cellSizePx,8/this.cellSizePx),l=Math.max(l,Math.abs(this.spring[n]),Math.abs(i)*.08)}if(t=Math.min(t,s),n=Math.min(n,c),r=Math.max(r,s),i=Math.max(i,c),l<.012){let e=o*2;this.spring[e]=this.spring[e+1]=0,this.velocity[e]=this.velocity[e+1]=0,this.activeCells.delete(o)}}r>=t&&this.changed({left:t,top:n,right:r,bottom:i}),this.active=this.activeCells.size?{left:t,top:n,right:r,bottom:i}:null}if(t<=0&&!r)return;let o=this.wetBounds;if(!o)return;let s=r?.size??0;if(r){this.burnDecay.length!==r.rates.length&&(this.burnDecay=new Float32Array(r.rates.length));for(let e=0;e<r.rates.length;e++){let n=t+r.rates[e];this.burnDecay[e]=n>0?Math.exp(-n*i):1}}let c=t>0?Math.exp(-t*i):1,l=this.width===s*4&&this.height===s*4,u=this.width,d=this.height,f=-1,p=-1;for(let e=Math.max(0,o.top);e<=Math.min(this.height-1,o.bottom);e++){let t=r?(l?e>>2:Math.floor(e*s/this.height))*s:0;for(let n=Math.max(0,o.left);n<=Math.min(this.width-1,o.right);n++){let i=e*this.width+n;if(!this.authored[i]&&!this.deposited[i])continue;let a=i*2,o=c;if(r){let r=this.spring[a]+this.outline[a],i=this.spring[a+1]+this.outline[a+1],c=r===0&&i===0?t+(l?n>>2:Math.floor(n*s/this.width)):H(Math.floor((e+i)*s/this.height),0,s-1)*s+H(Math.floor((n+r)*s/this.width),0,s-1);o=this.burnDecay[c]}if(o>=1)continue;let m=Math.round(this.authored[i]*o),h=Math.round(this.deposited[i]*o);(m!==this.authored[i]||h!==this.deposited[i])&&(this.authored[i]=m,this.deposited[i]=h,this.refreshBasePixel(i),u=Math.min(u,n),d=Math.min(d,e),f=Math.max(f,n),p=Math.max(p,e))}}f>=u&&this.changed({left:u,top:d,right:f,bottom:p})}mayIntersect(e,t,n=1){let r=Math.max(1,Math.ceil(Math.hypot(t.x-e.x,t.y-e.y)/Math.max(1,n)));for(let n=0;n<=r;n++){let i=n/r,a={x:Ey(e.x,t.x,i),y:Ey(e.y,t.y,i)};if(this.densityAt(a)>.02)return!0}return!1}spray(e,t,n,r,i=1,a=this.color){let o=Math.min(12,Math.ceil(r*2));for(let r of Sa(e,t,Math.max(1,n*.35),o,i,this.material.thickness))this.drops.push({point:{x:r.x,y:r.y},radius:Math.max(.5,r.radius),color:a,opacity:this.material.alpha*r.opacity,age:0});this.drops.length>256&&this.drops.splice(0,this.drops.length-256),this.splatterDirty=!0}grow(e){if(e<=1)return this.width;let t=this.width,n=Math.ceil(this.width*e/2)*2,r=Math.ceil(this.height*e/2)*2,i=Math.floor((n-this.width)/2),a=Math.floor((r-this.height)/2),o=(e,t,r)=>{for(let o=0;o<this.height;o++)r.set(e.subarray(o*this.width*t,(o+1)*this.width*t),((o+a)*n+i)*t);return r};this.authored=o(this.authored,1,new Uint8Array(n*r)),this.deposited=o(this.deposited,1,new Uint8Array(n*r)),this.pigment=o(this.pigment,4,new Float32Array(n*r*4)),this.colorPixels=o(this.colorPixels,3,new Uint8Array(n*r*3)),this.basePixels&&=o(this.basePixels,1,new Uint32Array(n*r)),this.outline=o(this.outline,2,new Float32Array(n*r*2)),this.spring=o(this.spring,2,new Float32Array(n*r*2)),this.velocity=o(this.velocity,2,new Float32Array(n*r*2)),this.activeCells=new Set([...this.activeCells].map(e=>(Math.floor(e/t)+a)*n+e%t+i)),this.outlineCells=new Set([...this.outlineCells].map(e=>(Math.floor(e/t)+a)*n+e%t+i));for(let e of this.drops)e.point.x+=i,e.point.y+=a;return this.splatterDirty=!0,this.active&&(this.active.left+=i,this.active.right+=i,this.active.top+=a,this.active.bottom+=a),this.wetBounds&&(this.wetBounds.left+=i,this.wetBounds.right+=i,this.wetBounds.top+=a,this.wetBounds.bottom+=a),this.width=n,this.height=r,this.canvas.width=n,this.canvas.height=r,this.renderedBounds=null,this.changed(),n}setColor(e){this.color=[...e],this.changed()}reset(){this.authored.fill(0),this.deposited.fill(0),this.outline.fill(0),this.spring.fill(0),this.velocity.fill(0),this.drops=[],this.splatterCanvas=null,this.splatterBounds=null,this.splatterDirty=!1,this.active=null,this.activeCells.clear(),this.outlineCells.clear(),this.basePixels?.fill(0),this.wetBounds=null,this.pulled=!1,this.maxOutline=0,this.changed()}captureState(){return{width:this.width,height:this.height,cellSizePx:this.cellSizePx,active:this.active?{...this.active}:null,pulled:this.pulled,authored:this.authored.slice(),deposited:this.deposited.slice(),pigment:this.pigment.slice(),colorPixels:this.colorPixels.slice(),outline:this.outline.slice(),spring:this.spring.slice(),velocity:this.velocity.slice(),drops:this.drops.map(e=>({...e,point:{...e.point}})),color:[...this.color],dispose(){}}}restoreState(e){this.width=e.width,this.height=e.height,this.canvas.width=e.width,this.canvas.height=e.height,this.cellSizePx=e.cellSizePx,this.active=e.active?{...e.active}:null,this.pulled=e.pulled,this.authored=e.authored.slice(),this.deposited=e.deposited.slice(),this.pigment=e.pigment.slice(),this.colorPixels=e.colorPixels.slice(),this.basePixels=Ty&&!this.appearance.shaded?new Uint32Array(this.width*this.height):null,this.outline=e.outline.slice(),this.outlineCells=new Set;for(let e=0;e<this.width*this.height;e++)(this.outline[e*2]||this.outline[e*2+1])&&this.outlineCells.add(e);if(this.maxOutline=this.outline.reduce((e,t)=>Math.max(e,Math.abs(t)),0),this.spring=e.spring.slice(),this.velocity=e.velocity.slice(),this.activeCells=new Set,this.active)for(let e=this.active.top;e<=this.active.bottom;e++)for(let t=this.active.left;t<=this.active.right;t++){let n=e*this.width+t,r=n*2;(this.spring[r]!==0||this.spring[r+1]!==0||this.velocity[r]!==0||this.velocity[r+1]!==0)&&this.activeCells.add(n)}this.activeCells.size||(this.active=null),this.drops=e.drops.map(e=>({...e,point:{...e.point}})),this.splatterDirty=!0,this.color=[...e.color],this.rebuildBasePixels(),this.rebuildWetBounds(),this.renderedBounds=null,this.changed()}dispose(){this.listeners.clear(),this.canvas.remove(),this.splatterCanvas?.remove()}paintUnshaded(e,t){let n=this.basePixels,r=new Uint32Array(e.data.buffer),i=t.right-t.left+1;for(let e=t.top;e<=t.bottom;e++)r.set(n.subarray(e*this.width+t.left,e*this.width+t.right+1),(e-t.top)*i);let a=0,o=e=>{let n=e%this.width,o=Math.floor(e/this.width);if(n<t.left||n>t.right||o<t.top||o>t.bottom)return;let s=e*2,c=this.spring[s]+this.outline[s],l=this.spring[s+1]+this.outline[s+1];if(c===0&&l===0)return;a++;let u=n+.5-c,d=o+.5-l,f=this.rawCoverageXY(u,d),p=(o-t.top)*i+n-t.left;if(f<=0){r[p]=0;return}let m=(H(Math.floor(d),0,this.height-1)*this.width+H(Math.floor(u),0,this.width-1))*3;r[p]=Math.round(f*this.material.alpha*255)<<24|this.colorPixels[m+2]<<16|this.colorPixels[m+1]<<8|this.colorPixels[m]};for(let e of this.outlineCells)o(e);for(let e of this.activeCells)this.outlineCells.has(e)||o(e);return i*(t.bottom-t.top+1)-a}present(){if(this.presented!==this.revision){performance.now();let e=this.canvas.getContext(`2d`),t=this.pulled||this.active?Math.ceil(this.maxOutline+8/this.cellSizePx)+2:2,n=this.wetBounds,r=n?{left:Math.max(0,n.left-t),top:Math.max(0,n.top-t),right:Math.min(this.width-1,n.right+t),bottom:Math.min(this.height-1,n.bottom+t)}:null,i=this.renderedBounds,a=this.fullDirty?i&&r?{left:Math.min(i.left,r.left),top:Math.min(i.top,r.top),right:Math.max(i.right,r.right),bottom:Math.max(i.bottom,r.bottom)}:i??r:this.dirtyBounds;a&&e.clearRect(a.left,a.top,a.right-a.left+1,a.bottom-a.top+1);let o=r&&a?{left:Math.max(0,r.left,a.left),top:Math.max(0,r.top,a.top),right:Math.min(this.width-1,r.right,a.right),bottom:Math.min(this.height-1,r.bottom,a.bottom)}:null;if(o&&o.right>=o.left&&o.bottom>=o.top){let t=o.right-o.left+1,n=o.bottom-o.top+1,r=e.createImageData(t,n),i=Ty&&!this.appearance.shaded?new Uint32Array(r.data.buffer):null;performance.now();let a=this.basePixels?this.paintUnshaded(r,o):0;if(!this.basePixels)for(let e=o.top;e<=o.bottom;e++)for(let n=o.left;n<=o.right;n++){let s=(e*this.width+n)*2,c=this.spring[s]+this.outline[s],l=this.spring[s+1]+this.outline[s+1],u=c===0&&l===0;u&&a++;let d=((e-o.top)*t+n-o.left)*4;if(u&&i){let t=e*this.width+n,r=this.alphaAt(t);if(!r)continue;let a=t*3;i[d/4]=Math.round(r*this.material.alpha)<<24|this.colorPixels[a+2]<<16|this.colorPixels[a+1]<<8|this.colorPixels[a];continue}let f=n+.5-c,p=e+.5-l,m=u?this.alphaAt(e*this.width+n)/255:this.rawCoverageXY(f,p);if(m<=0)continue;let h=u?e*this.width+n:H(Math.floor(p),0,this.height-1)*this.width+H(Math.floor(f),0,this.width-1);if(this.appearance.shaded){let t=[this.colorPixels[h*3],this.colorPixels[h*3+1],this.colorPixels[h*3+2]],i=wy(this.appearance,t,n,e,this.rawCoverageXY(f+1,p)-this.rawCoverageXY(f-1,p),this.rawCoverageXY(f,p+1)-this.rawCoverageXY(f,p-1));for(let e=0;e<3;e++)r.data[d+e]=i[e]}else{if(i){i[d/4]=Math.round(m*this.material.alpha*255)<<24|this.colorPixels[h*3+2]<<16|this.colorPixels[h*3+1]<<8|this.colorPixels[h*3];continue}r.data[d]=this.colorPixels[h*3],r.data[d+1]=this.colorPixels[h*3+1],r.data[d+2]=this.colorPixels[h*3+2]}r.data[d+3]=Math.round(m*this.material.alpha*255)}t*n,performance.now(),e.putImageData(r,o.left,o.top)}this.renderedBounds=r,this.fullDirty=!1,this.dirtyBounds=null,this.presented=this.revision}}draw(e){if(this.present(),this.renderedBounds){let{left:t,top:n,right:r,bottom:i}=this.renderedBounds,a=r-t+1,o=i-n+1;e.drawImage(this.canvas,t,n,a,o,t,n,a,o)}this.drawSplatter(e)}drawSplatter(e){if(this.drops.length){if(this.splatterDirty||!this.splatterCanvas||!this.splatterBounds){let e={left:Math.floor(Math.min(...this.drops.map(e=>e.point.x-e.radius))),top:Math.floor(Math.min(...this.drops.map(e=>e.point.y-e.radius))),right:Math.ceil(Math.max(...this.drops.map(e=>e.point.x+e.radius))),bottom:Math.ceil(Math.max(...this.drops.map(e=>e.point.y+e.radius)))},t=this.splatterCanvas??document.createElement(`canvas`),n=Math.max(1,e.right-e.left),r=Math.max(1,e.bottom-e.top);t.width!==n&&(t.width=n),t.height!==r&&(t.height=r);let i=t.getContext(`2d`);i.clearRect(0,0,n,r);for(let t of this.drops)i.globalAlpha=t.opacity,i.fillStyle=`rgb(${t.color.join(` `)})`,i.beginPath(),i.arc(t.point.x-e.left,t.point.y-e.top,t.radius,0,Math.PI*2),i.fill();this.splatterCanvas=t,this.splatterBounds=e,this.splatterDirty=!1}e.drawImage(this.splatterCanvas,this.splatterBounds.left,this.splatterBounds.top)}}};function Ay(e,t,n){let r=Math.ceil(t/4),i=new Float32Array(r*r),a=n.width/r;for(let n=0;n<t;n++)for(let a=0;a<t;a++){let o=Math.floor(n/4)*r+Math.floor(a/4);i[o]=Math.max(i[o],e[n*t+a])}return{size:r,fuel:i,spacing:a,point:e=>({x:n.x+(e%r+.5)*a,y:n.y+(Math.floor(e/r)+.5)*a})}}function jy(e){let t=e.flatMap(e=>Array.from(e.fuel,(t,n)=>({field:e,i:n,fuel:t,point:e.point(n)})).filter(e=>e.fuel>=.035)),n=Math.max(1,...e.map(e=>e.spacing))*2,r=e=>`${Math.floor(e.x/n)},${Math.floor(e.y/n)}`,i=new Map;t.forEach((e,t)=>{let n=r(e.point),a=i.get(n)??[];a.push(t),i.set(n,a)});let a=function*(e,t){let r=Math.ceil(t/n),a=Math.floor(e.x/n),o=Math.floor(e.y/n);for(let e=-r;e<=r;e++)for(let t=-r;t<=r;t++)for(let n of i.get(`${a+e},${o+t}`)??[])yield n};return{nodes:t,neighbors:function*(e){let r=t[e];for(let e of a(r.point,n)){let n=t[e],i=Math.hypot(r.point.x-n.point.x,r.point.y-n.point.y);i<=(r.field.spacing+n.field.spacing)*.74&&(yield{next:e,distance:i})}},nearby:a,cellSize:n}}function My(e,t,n=0){let r=jy(e),i=new Int32Array(r.nodes.length).fill(-2),a=[];for(let e of t)for(let t of r.nearby(e,n+r.cellSize)){let o=r.nodes[t];i[t]===-2&&Math.hypot(o.point.x-e.x,o.point.y-e.y)<=n+o.field.spacing*.75&&(i[t]=-1,a.push(t))}for(let e=0;e<a.length;e++)for(let{next:t}of r.neighbors(a[e]))i[t]===-2&&(i[t]=a[e],a.push(t));let o=(e,t)=>{let n=-1,a=1/0;for(let o of r.nearby(e,t+r.cellSize)){if(i[o]===-2)continue;let s=r.nodes[o],c=Math.hypot(s.point.x-e.x,s.point.y-e.y);c<=t+s.field.spacing*.75&&c<a&&(n=o,a=c)}return n};return{points:a.map(e=>r.nodes[e].point),contains:(e,t=0)=>o(e,t)>=0,intersects:(e,t=0)=>{let n={x:e.x+e.width/2,y:e.y+e.height/2};for(let a of r.nearby(n,Math.hypot(e.width,e.height)/2+t+r.cellSize)){if(i[a]===-2)continue;let n=r.nodes[a],o=n.point,s=t+n.field.spacing*.5;if(o.x>=e.x-s&&o.x<=e.x+e.width+s&&o.y>=e.y-s&&o.y<=e.y+e.height+s)return!0}return!1},pathTo:(e,t=0)=>{let n=o(e,t),a=[];for(;n>=0;)a.push(r.nodes[n].point),n=i[n];return a.reverse()}}}var Ny=class{density;resolution;rect;lifetime;spreadMps;pixelsPerMeter;size;fuel;starts;ends;rates;alpha;baseAlpha;light;pixelsByCell;revision=0;complete=!1;lit=!1;constructor(e,t,n,r,i,a){this.density=e,this.resolution=t,this.rect=n,this.lifetime=r,this.spreadMps=i,this.pixelsPerMeter=a;let o=Ay(e,t,n);this.size=o.size,this.fuel=o.fuel,this.starts=new Float64Array(this.fuel.length).fill(1/0),this.ends=new Float64Array(this.fuel.length).fill(1/0),this.rates=new Float32Array(this.fuel.length),this.alpha=new Uint8Array(e.length),this.baseAlpha=new Uint8Array(e.length),this.light=new Float32Array(this.fuel.length);let s=Array.from({length:this.fuel.length},()=>[]);for(let n=0;n<t;n++)for(let r=0;r<t;r++){let i=n*t+r;e[i]<=.035||(this.baseAlpha[i]=Math.round(255*Math.min(1,(e[i]-.035)/.12)),s[Math.floor(n/4)*this.size+Math.floor(r/4)].push(i))}this.pixelsByCell=s.map(e=>e.length?Uint32Array.from(e):void 0)}point(e){return{x:this.rect.x+(e%this.size+.5)*this.spacing,y:this.rect.y+(Math.floor(e/this.size)+.5)*this.spacing}}get spacing(){return this.rect.width/this.size}get managedBytes(){return[this.density,this.fuel,this.starts,this.ends,this.rates,this.alpha,this.baseAlpha,this.light].reduce((e,t)=>e+t.byteLength,0)+this.pixelsByCell.reduce((e,t)=>e+(t?.byteLength??0),0)}indexAt(e){let t=Math.floor((e.x-this.rect.x)/this.spacing),n=Math.floor((e.y-this.rect.y)/this.spacing);return t<0||n<0||t>=this.size||n>=this.size?-1:n*this.size+t}inherit(e,t){for(let n=0;n<this.fuel.length;n++){let r=e.indexAt(this.point(n));if(r>=0&&Number.isFinite(e.starts[r])&&e.ends[r]>t){this.starts[n]=Math.max(t,e.starts[r]);let i=Math.min(1,(e.ends[r]-t)/Math.max(.01,e.ends[r]-e.starts[r])),a=this.fuel[n]>e.fuel[r]*i**2+.05;this.ends[n]=a?Math.max(e.ends[r],t+this.lifetime):e.ends[r]}}}update(e,t){let n=!1,r=this.light,i=!1;for(let a=0;a<this.fuel.length;a++){this.rates[a]=0;let o=this.starts[a],s=this.ends[a],c=r[a],l=0;if(Number.isFinite(o)&&e>=o){let r=Math.max(.01,s-o),i=Math.max(0,Math.min(1,(e-t-o)/r)),c=Math.max(0,Math.min(1,(e-o)/r)),u=Math.max(1e-6,(1-i)**2),d=Math.max(1e-6,(1-c)**2);this.rates[a]=Math.log(u/d)/Math.max(t,1e-4),e<s&&(n=!0,l=Math.min(1,(e-o)/.15)*Math.min(1,(s-e)/Math.min(2,r*.3)))}if(r[a]=l,c<=0&&l<=0)continue;let u=this.pixelsByCell[a];if(u)for(let e of u){let t=Math.round(this.baseAlpha[e]*l);this.alpha[e]=t,i||=t>0}}return this.lit=i,this.revision++,this.complete=this.starts.some(Number.isFinite)&&this.ends.every((t,n)=>this.fuel[n]<.035||t<=e),n}};function Py(e,t,n,r,i=[]){let{nodes:a,neighbors:o,nearby:s,cellSize:c}=jy(e);if(!a.length)return;let l=new Set;for(let e of[t,...i])for(let t of s(e,n+c)){let r=a[t];Math.hypot(r.point.x-e.x,r.point.y-e.y)<=n+r.field.spacing*.75&&l.add(t)}let u=new Float64Array(a.length).fill(1/0),d=[],f=(e,t)=>{if(t>=u[e])return;u[e]=t;let n=d.length;for(d.push({index:e,time:t});n>0;){let e=n-1>>1;if(d[e].time<=t)break;d[n]=d[e],n=e}d[n]={index:e,time:t}};for(a.forEach((e,t)=>{e.field.ends[e.i]<=r||(l.has(t)?f(t,r):Number.isFinite(e.field.starts[e.i])&&e.field.ends[e.i]>r&&f(t,Math.max(r,e.field.starts[e.i])))});d.length;){let e=d[0],t=d.pop();if(d.length){let e=0;for(;e*2+1<d.length;){let n=e*2+1;if(n+1<d.length&&d[n+1].time<d[n].time&&n++,d[n].time>=t.time)break;d[e]=d[n],e=n}d[e]=t}if(e.time===u[e.index])for(let{next:t,distance:n}of o(e.index)){let i=a[t];i.field.ends[i.i]<=r||f(t,e.time+n/Math.max(1,i.field.pixelsPerMeter)/i.field.spreadMps)}}a.forEach((e,t)=>{u[t]>=e.field.starts[e.i]||(e.field.starts[e.i]=u[t],e.field.ends[e.i]=u[t]+e.field.lifetime)})}function Fy(e){let t=e.extentM*e.pixelsPerMeter;return{x:e.center.x-t/2,y:e.center.y-t/2,width:t,height:t}}function Iy(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}function Ly(e,t,n){return t.x>=e.x-n&&t.x<=e.x+e.width+n&&t.y>=e.y-n&&t.y<=e.y+e.height+n}function Ry(e,t,n=0){if(!e.length||!t.length)return[];let r=e.map(Fy),i=new Uint8Array(e.length),a=[];for(let o=0;o<e.length;o++)t.some(e=>Ly(r[o],e,n))&&(i[o]=1,a.push(o));for(let t=0;t<a.length;t++){let n=r[a[t]];for(let t=0;t<e.length;t++)!i[t]&&Iy(n,r[t])&&(i[t]=1,a.push(t))}return a.map(t=>e[t])}function zy(e,t,n=0){return My(Ry(e.filter(e=>T[e.kind].conductive),t,n).map(e=>Ay(e.fluid.captureFuel(),e.resolution,Fy(e))),t,n)}function By(e,t,n){let r=[];for(let i of e){let e=i.fire;if(!e||!T[i.kind].burnable)continue;let a=e.size,o=Math.max(1,Math.ceil(n/e.spacing)),s=(n,r)=>{if(n<0||r<0||n>=a||r>=a)return!1;let i=r*a+n;return e.fuel[i]>=.035&&e.starts[i]<=t&&e.ends[i]>t};for(let t=0;t<a;t++)for(let n=0;n<a;n++)s(n,t)&&(s(n-1,t)&&s(n+1,t)&&s(n,t-1)&&s(n,t+1)&&(n%o!==0||t%o!==0)||r.push(e.point(t*a+n)))}return r}function Vy(e,t,n,r){let i=0,a=0,o=0,s=new Set,c=null,l=[0,0,0],u=[],d=[];for(let f of e){let e=n(f,t);if(e>.12&&(c=f.id),e>.1&&s.add(f.kind),ut(f.kind)===`water`&&!ft(f.kind)||e<.04)continue;let p=f.fluid.colorAt?.(r(f,t))??f.color;d.push({id:`liquid:${f.id}`,color:`rgb(${p.map(e=>Math.round(e)).join(` `)})`,opacity:Math.min(1,e),distanceM:f.elementProfile?.distanceM??(ft(f.kind)?mt(f.kind).carryM:T[f.kind].treadDistanceM),material:mt(f.kind)}),u.push(f.id);for(let t=0;t<3;t++)l[t]+=p[t]*e;i+=e,a=1-(1-a)*(1-e),o=Math.max(o,f.elementProfile?.distanceM??T[f.kind].treadDistanceM)}let f=i?{id:`liquid:${u.join(`,`)}`,color:`rgb(${l.map(e=>Math.round(e/i)).join(` `)})`,opacity:a,distanceM:o}:null;return{materials:[...s],paint:f,paints:d,splashFieldId:c}}function Hy(e,t,n,r,i){let a=new Uint8Array(e*e),o=0,s=i?Math.max(0,Math.floor(((i.left-t.x)/n+.5)*e)-1):0,c=i?Math.min(e,Math.ceil(((i.right-t.x)/n+.5)*e)+1):e,l=i?Math.max(0,Math.floor(((i.top-t.y)/n+.5)*e)-1):0,u=i?Math.min(e,Math.ceil(((i.bottom-t.y)/n+.5)*e)+1):e;for(let i=l;i<u;i++)for(let l=s;l<c;l++){let s=0;for(let a=0;a<2;a++)for(let o=0;o<2;o++)r({x:t.x+((l+.25+o*.5)/e-.5)*n,y:t.y+((i+.25+a*.5)/e-.5)*n})&&s++;let c=Math.round(s/4*255);a[i*e+l]=c,o+=c/255}return{mask:a,coverage:o/(e*e)}}var Uy=4,Wy={low:128,medium:160,high:192},Gy={low:192,medium:256,high:384},Ky=.115,qy=1/10,Jy=(e,t)=>{let n=typeof window>`u`?1:Math.min(3,Math.max(1,window.devicePixelRatio||1));return Math.max(Gy[t],Math.min(768,Math.ceil(e*n/16)*16))},Yy=(e,t)=>e.every((e,n)=>e===t[n]);function Xy(e,t,n,r,i){let a=N(D(-1),t),o=N(D(0,1),t+n),s=r.x*o.x+r.y*o.y;if(e){let e=M(r),t=Math.min(.55,e/22),n=Math.min(.28,Math.abs(s)/28),c=O(O(A(a,1-t-n),A(i,t)),A(o,-Math.sign(s)*n));return A(c,1/Math.max(.001,M(c)))}if(Math.abs(s)<=.8)return i;let c=Math.min(1,Math.abs(s)/Math.max(.8,M(r))),l=O(A(i,1-c),A(o,-Math.sign(s)*c));return A(l,1/Math.max(.001,M(l)))}var Zy=class{quality;fields=[];clock=0;fireTime=0;nextId=1;lastPours=new Map;lastFirePlan=-1/0;seam=null;wheelContacts=[];splashFields=new Map;captureState(){let e=[];try{for(let{fluid:t,...n}of this.fields)e.push({meta:E(n),fluid:t.captureState()})}catch(t){for(let t of e)t.fluid.dispose();throw t}return{fields:e,clock:this.clock,fireTime:this.fireTime,nextId:this.nextId,lastPours:E(this.lastPours),lastFirePlan:this.lastFirePlan,seam:this.seam?{previousId:this.seam.previous.id,currentId:this.seam.current.id,point:E(this.seam.point)}:null,wheelContacts:E(this.wheelContacts),splashFields:E(this.splashFields),quality:this.quality,dispose:()=>e.forEach(e=>e.fluid.dispose())}}restoreState(e){this.reset(),this.quality=e.quality;try{for(let{meta:t,fluid:n}of e.fields){let e=E(t),r=new ky(e.kind,e.resolution,e.resolution,e.color,e.elementProfile);r.setCellSize(e.extentM*e.pixelsPerMeter/e.resolution);try{r.restoreState(n)}catch(e){throw r.dispose(),e}this.fields.push({...e,fluid:r})}}catch(e){throw this.reset(),e}this.clock=e.clock,this.fireTime=e.fireTime,this.nextId=e.nextId,this.lastPours=E(e.lastPours),this.lastFirePlan=e.lastFirePlan,this.wheelContacts=E(e.wheelContacts),this.splashFields=E(e.splashFields??new Map);let t=this.fields.find(t=>t.id===e.seam?.previousId),n=this.fields.find(t=>t.id===e.seam?.currentId);this.seam=e.seam&&t&&n?{previous:t,current:n,point:E(e.seam.point)}:null}constructor(e=`high`){this.quality=e}get managedBytes(){return this.fields.reduce((e,t)=>e+96+(t.fire?.managedBytes??0)+t.fluid.managedBytes,0)}fireContactBounds(){return this.fields.filter(e=>T[e.kind].burnable).map(e=>{let t=e.extentM*e.pixelsPerMeter;return{x:e.center.x-t/2,y:e.center.y-t/2,width:t,height:t}})}hasConductiveCandidate(e,t){return this.fields.some(n=>{if(!T[n.kind].conductive)return!1;let r=n.extentM*n.pixelsPerMeter/2+t;return e.some(e=>Math.abs(e.x-n.center.x)<=r&&Math.abs(e.y-n.center.y)<=r)})}reset(){for(let e of this.fields)e.fluid.dispose();this.fields=[],this.clock=0,this.fireTime=0,this.lastPours.clear(),this.lastFirePlan=-1/0,this.seam=null,this.wheelContacts=[],this.splashFields.clear()}setQuality(e){this.quality=e}removeSeed(e){for(let t=this.fields.length-1;t>=0;t--){let n=this.fields[t];if(n.seedKey===e){n.fluid.removeSeed(),n.fluid.hasDeposits?n.seedKey=void 0:(n.fluid.dispose(),this.fields.splice(t,1));for(let[e,t]of this.splashFields)t===n.id&&this.splashFields.delete(e)}}}fieldForSeed(e){return this.fields.find(t=>t.seedKey===e)??null}seedShape(e,t,n,r,i,a,o,s,c){let l=this.fieldForSeed(e);l&&l.kind!==t&&(this.removeSeed(e),l=null);let u=Math.max(Uy,i/a+1.4);if(l??=this.create(t,n,r,a,s,Jy(u*a,this.quality)),!l)return!1;try{let t=l.pixelsPerMeter;l.seedKey=e,l.elementProfile=s,l.color=n;let a=Math.max(Uy,i/t+1.4,2*(M(k(r,l.center))/t+i/t/2+.7));l.poured===0?l.extentM=a:a>l.extentM&&this.expand(l,a/l.extentM),l.fluid.setCellSize(l.extentM*t/l.resolution),l.fluid.configure(n,s);let u=l.fluid.displaced,d=l.extentM*t/l.resolution;performance.now();let{mask:f,coverage:p}=(u?null:c?.(l.resolution,l.center,l.extentM*t))??Hy(l.resolution,l.center,l.extentM*t,e=>{if(!u)return o(e);let t=l.fluid.offsetAt(this.localPoint(l,e));return o(D(e.x+t.x*d,e.y+t.y*d))},u?void 0:{left:r.x-i/2,top:r.y-i/2,right:r.x+i/2,bottom:r.y+i/2});if(p<=0)return this.removeSeed(e),!1;let m=Math.max(1,p*l.extentM*l.extentM*3);return l.poured=Math.max(l.poured,m),performance.now(),l.fluid.seedMask(f,.85,m,n),!0}catch(t){throw this.removeSeed(e),t}}pour(e,t,n,r,i,a=T[e].color,o=`default`){if(r<=0)return;let s=this.lastPours.get(o),c=s?M(k(t,s.point))/Math.max(1,n):0,l=s?.kind===e&&Yy(a,s.color)&&s.age<.12&&c<2.5?s:void 0,u=l?c:0,d=Math.max(l?.age??1/120,1/120),f=Math.exp(-u/.45),p=(l?.localAmount??0)*f+r,m=Math.min(1.8,.11+Math.sqrt(p)*.32),h=-Math.expm1(-d/.12),g=l?l.radiusM+(m-l.radiusM)*h:m;this.deposit(e,a,t,n,r,i,g,l?.point,l?.radiusM),this.lastPours.set(o,{kind:e,color:a,point:{...t},age:0,localAmount:p,radiusM:g})}emit(e,t,n,r,i,a,o=T[e].color){r<=0||i<=0||this.deposit(e,o,t,n,r,a,i)}deposit(e,t,n,r,i,a,o,s,c=o){let l=this.fields.at(-1),u=e===`paint`||ft(e)?.mixing,d=i=>{if(!(i.kind===e||ft(e)?.mixing&&ft(i.kind)?.mixing)&&!(u&&i.kind===`paint`)||!u&&!Yy(t,i.color))return!1;let a=o*r;return[n,s??n,D((n.x+(s?.x??n.x))/2,(n.y+(s?.y??n.y))/2)].some(e=>M(k(e,i.center))/r+o>6.8?!1:[D(),D(a),D(-a),D(0,a),D(0,-a)].some(t=>{let n=O(e,t);return this.covers(i,n)&&i.fluid.densityAt(this.localPoint(i,n))>.02}))},f=(l&&d(l)?l:[...this.fields].reverse().find(d))??this.create(e,t,n,r);if(!f)return;f!==l&&!l?.seedKey&&l?.kind===e&&Yy(t,l.color)&&(this.seam={previous:l,current:f,point:{...n}});let p=this.seam?.current===f&&M(k(n,this.seam.point))<r*.85;this.depositIn(f,n,p?i*.5:i,a,o,t,s,c),p&&this.seam&&this.depositIn(this.seam.previous,n,i*.5,a,o,t,s,c)}depositIn(e,t,n,r,i,a=e.color,o,s=i){e.poured+=n;let c=2*(Math.max(M(k(t,e.center)),o?M(k(o,e.center)):0)/e.pixelsPerMeter+i+.25);c>e.extentM&&this.expand(e,Math.min(14/e.extentM,Math.max(1.25,c/e.extentM)));let l=this.localPoint(e,t),u=A(r,e.resolution/e.extentM);e.fluid.pour(n,this.clock+e.id,l,i*e.resolution/e.extentM,u,a,this.localPoint(e,o??t),s*e.resolution/e.extentM)}eject(e,t,n,r,i){this.pour(e,t,n,1.1,r,i)}splatter(e,t,n,r,i,a=!1,o=1,s){if(i<=0)return!1;let c=this.wheelContacts[e]?.splashFieldId??(s?this.splashFields.get(e):null),l=c==null?a||this.wheelContacts.length===0?[...this.fields].reverse().find(e=>this.covers(e,t)&&this.coverage(e,t)>.12):null:this.fields.find(e=>e.id===c);if(!l||!this.covers(l,t))return!1;let u=this.localPoint(l,t),d=l.resolution/l.extentM/l.pixelsPerMeter,f=s?.color.match(/[\d.]+/g)?.slice(0,3).map(Number);return l.fluid.spray(u,n,r*d,i*1.5*(s?.opacity??1),o,f?.length===3?f:void 0),!0}create(e,t,n,r,i,a){let o=a??Wy[this.quality],s;try{s=new ky(e,o,o,t,i)}catch{return null}let c={id:this.nextId++,kind:e,color:t,center:n,pixelsPerMeter:r,resolution:o,extentM:Uy,fluid:s,poured:0,elementProfile:i};return s.setCellSize(c.extentM*r/o),this.fields.push(c),c}step(e,t=[]){for(let[t,n]of this.lastPours)n.age+=e,n.age>1&&this.lastPours.delete(t);if(this.clock+=e,this.clock<1/30)return;let n=Math.min(.05,this.clock);this.clock=Math.max(0,this.clock-1/30),this.fireTime+=n;let r=this.fields.filter(e=>T[e.kind].burnable);this.fireTime-this.lastFirePlan>=.2&&r.some(e=>e.fire?.starts.some(Number.isFinite))&&r.some(e=>!e.fire||e.poured!==e.firePoured)&&(Py(r.map(e=>!e.fire||e.poured!==e.firePoured?this.prepareFire(e):e.fire),D(1/0,1/0),0,this.fireTime),this.lastFirePlan=this.fireTime);for(let e of this.fields){let r=[];for(let i of t){let t=M(i.velocity);if(M(k(i.point,e.center))>e.extentM*e.pixelsPerMeter*.62)continue;let a=e.resolution/e.extentM/e.pixelsPerMeter,o=this.localPoint(e,i.point);if(t<3&&(i.slip??0)<.05)continue;let s=D(i.point.x-i.velocity.x*n,i.point.y-i.velocity.y*n),c=this.localPoint(e,s);r.push({from:c,to:o,radius:Math.max(.65,i.radiusPx*a),paint:i.paint,slip:i.slip??0})}performance.now();let i=r.filter(t=>this.nearLiquid(e,t.from,t.to,t.radius));performance.now();for(let t of i)if(performance.now(),e.fluid.drag(t.from,t.to,n,t.radius,0),ut(e.kind)===`paint`&&t.paint){let r=t.paint.color.match(/[\d.]+/g)?.slice(0,3).map(Number);if(r?.length===3){let i=M(k(t.to,t.from)),a=(1-Math.exp(-i/Math.max(1,t.radius*3)-t.slip*n*2))*t.paint.opacity;performance.now(),e.fluid.transferPigment?.(t.from,t.to,t.radius,r,a*.32)}}let a=T[e.kind].burnable&&e.fire?.starts.some(Number.isFinite)?e.fire:void 0,o=a?this.fireTime-(e.fireUpdatedAt??this.fireTime-n):0,s=!!a&&o+1e-9>=qy,c=e.firePendingElapsed??0;performance.now(),e.fluid.step(n,0,[],c>0&&a?.rates.some(e=>e>0)?a:void 0,c||n),e.firePendingElapsed=0,s&&(performance.now(),a.update(this.fireTime,o),e.fireUpdatedAt=this.fireTime,e.firePendingElapsed=o)}for(let e=this.fields.length-1;e>=0;e--){let t=this.fields[e];if(!T[t.kind].burnable||!t.fire?.complete||(t.firePendingElapsed??0)>0)continue;let n=t.fluid.captureFuel();n.some(e=>e>=.035)?(this.prepareFire(t,n,.75),Py([t.fire],t.center,t.extentM*t.pixelsPerMeter,this.fireTime)):t.seedKey?(t.fluid.reset(),t.fire=void 0):(t.fluid.dispose(),this.fields.splice(e,1))}performance.now(),this.wheelContacts=t.map((e,t)=>{let n=this.sampleContact(e.point);return n.splashFieldId===null?e.paint||this.splashFields.delete(t):this.splashFields.set(t,n.splashFieldId),n});for(let e of this.splashFields.keys())e>=t.length&&this.splashFields.delete(e)}sampleContact(e){return Vy(this.fields,e,(e,t)=>this.coverage(e,t),(e,t)=>this.localPoint(e,t))}nearLiquid(e,t,n,r){return e.fluid.mayIntersect(t,n,r)}expand(e,t){if(t<=1)return;let n=e.resolution;e.resolution=e.fluid.grow(t),e.extentM*=e.resolution/n,e.fire&&(this.prepareFire(e),e.firePoured=-1)}localPoint(e,t){return D(e.resolution/2+(t.x-e.center.x)/e.pixelsPerMeter*e.resolution/e.extentM,e.resolution/2+(t.y-e.center.y)/e.pixelsPerMeter*e.resolution/e.extentM)}covers(e,t){let n=e.extentM*e.pixelsPerMeter*.5;return Math.abs(t.x-e.center.x)<=n&&Math.abs(t.y-e.center.y)<=n}coverage(e,t){if(!this.covers(e,t))return 0;let n=e.fluid.densityAt(this.localPoint(e,t));return Math.max(0,Math.min(1,(n-Ky+.012)/.024))*(e.elementProfile?.opacity??T[e.kind].alpha)}contacts(e,t){return this.fields.filter(n=>n.kind===e&&t.some(e=>this.coverage(n,e)>.1)).map(e=>e.id)}conductAt(e,t=0){return zy(this.fields,e,t)}densityAt(e,t){return Math.max(0,...this.fields.filter(n=>n.kind===e&&this.covers(n,t)).map(e=>e.fluid.densityAt(this.localPoint(e,t))))}prepareFire(e,t=e.fluid.captureFuel(),n){let r=T[e.kind],i=e.extentM*e.pixelsPerMeter,a=new Ny(t,e.resolution,{x:e.center.x-i/2,y:e.center.y-i/2,width:i,height:i},n??r.burnLifetime??r.burnSeconds??12,r.fireSpreadMps??T.oil.fireSpreadMps,e.pixelsPerMeter);return e.fire&&a.inherit(e.fire,this.fireTime),e.fire=a,e.firePoured=e.poured,e.fireSampleAt=this.fireTime,e.fireUpdatedAt=this.fireTime-e.id%3*qy/3,e.firePendingElapsed=0,a}igniteConducted(e,t){if(!e.length)return;let n=Ry(this.fields.filter(e=>T[e.kind].burnable),e,t).map(e=>!e.fire||e.firePoured!==e.poured?this.prepareFire(e):e.fire);if(n.length){Py(n,e[0],t,this.fireTime,e.slice(1));for(let e of n)e.update(this.fireTime,0);this.lastFirePlan=this.fireTime}}igniteAt(e,t=0){if(this.fireTime-this.lastFirePlan<.15)return;let n=[e];if(t>0)for(let r=0;r<8;r++)n.push(D(e.x+Math.cos(r*Math.PI/4)*t,e.y+Math.sin(r*Math.PI/4)*t));let r=this.fields.filter(e=>T[e.kind].burnable&&n.some(t=>this.coverage(e,t)>.08));if(!r.length||(this.lastFirePlan=this.fireTime,r.every(e=>e.fire&&e.firePoured===e.poured&&n.every(t=>{let n=e.fire.indexAt(t);return n<0||e.fire.fuel[n]<.035||Number.isFinite(e.fire.starts[n])}))))return;let i=this.fields.filter(e=>T[e.kind].burnable).map(e=>!e.fire||e.poured!==e.firePoured&&this.fireTime-(e.fireSampleAt??0)>=.2?this.prepareFire(e):e.fire);Py(i,e,t,this.fireTime);for(let e of i)e.update(this.fireTime,0)}igniteAlong(e,t,n=0){for(let r=0;r<=4;r++)this.igniteAt(D(e.x+(t.x-e.x)*r/4,e.y+(t.y-e.y)*r/4),n)}burningSources(e){return By(this.fields,this.fireTime,e)}burningMasks(){return this.fields.flatMap(e=>{let t=e.fire;return!T[e.kind].burnable||!t?.lit?[]:[{key:e,alpha:t.alpha,pixelWidth:t.resolution,pixelHeight:t.resolution,...t.rect,origin:e.center,age:.4,farthest:Math.max(1,t.rect.width),spreadSeconds:0,burnSeconds:1,intensity:.55,smokeRate:10,revision:t.revision}]})}kindAt(e){let t=!1,n=!1,r=!1;for(let i=this.fields.length-1;i>=0;i--){let a=this.fields[i];if(!(this.coverage(a,e)<=.1)){if(ut(a.kind)===`water`)return`water`;ut(a.kind)===`oil`&&(t=!0),ut(a.kind)===`paint`&&(n=!0),ut(a.kind)===`mud`&&(r=!0)}}return r?`mud`:t?`oil`:n?`paint`:null}pruneOutside(e){this.fields=this.fields.filter(t=>{let n=t.extentM*t.pixelsPerMeter*1.5,r=t.center.x+n>=e.x&&t.center.x-n<=e.x+e.width&&t.center.y+n>=e.y&&t.center.y-n<=e.y+e.height;return r||t.fluid.dispose(),r}),!this.seam||this.fields.includes(this.seam.previous)&&this.fields.includes(this.seam.current)||(this.seam=null)}draw(e,t,n,r,i){performance.now(),e.save(),e.globalAlpha=r;for(let r of this.fields){let a=t(r.center),o=r.extentM*r.pixelsPerMeter*n,s=r.fluid.hasSplatter?o*1.5:o/2;i&&(a.x+s<0||a.y+s<0||a.x-s>i.width||a.y-s>i.height)||(e.save(),e.translate(a.x-o/2,a.y-o/2),e.scale(o/r.resolution,o/r.resolution),r.fluid.draw(e),e.restore())}e.restore()}},Qy=class{liquids;camera;pixelSpace;elementFields=new Map;nextElementId=1;initialPuddles=[];constructor(e,t,n){this.liquids=e,this.camera=t,this.pixelSpace=n}captureState(){return E({elementFields:this.elementFields,nextElementId:this.nextElementId,initialPuddles:this.initialPuddles})}restoreState(e){let t=E(e);this.elementFields=t.elementFields,this.nextElementId=t.nextElementId,this.initialPuddles=t.initialPuddles}clearEffects(){this.elementFields.clear(),this.nextElementId=1}pourWorldLiquid(e,t,n,r,i){this.liquids.pour(e,this.camera.particlePoint(t),this.camera.particleScale(),n,D(),r,i)}addLiquid(e,t){let n=ot(e),r=t.amount??24;if(!Number.isFinite(t.at.x)||!Number.isFinite(t.at.y)||!Number.isFinite(r)||r<=0)throw RangeError(`Liquid position and positive amount must be finite.`);let i=t.color?at(t.color):void 0;if(t.initial){let e={kind:n,point:this.camera.documentPoint(t.at),amount:r,color:i};this.initialPuddles.push(e),this.depositInitialPuddle(e)}else this.pourWorldLiquid(n,t.at,r,i)}syncElementLiquids(e){performance.now();let t=new Set(e.map(e=>e.key));for(let[e,n]of this.elementFields)t.has(e)||(this.liquids.removeSeed(n.id),this.elementFields.delete(e));let n=new Map,r=!1;for(let t of e){let e=this.localFromDocument({x:t.bounds.x,y:t.bounds.y}),i=this.localFromDocument({x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height}),a=D((e.x+i.x)/2,(e.y+i.y)/2),o=this.elementFields.get(t.key),s=o?.signature!==t.signature,c=o&&(o.center.x!==a.x||o.center.y!==a.y);if(!o||s||c){if(t.rasterize){if(r){let e=o&&this.liquids.fieldForSeed(o.id);e&&n.set(t.key,e);continue}r=!0}performance.now();let s=o?.id??`element-liquid-${this.nextElementId++}`,c=Math.max(Math.abs(i.x-e.x),Math.abs(i.y-e.y));if(!this.liquids.seedShape(s,t.kind,t.color,a,c,this.camera.particleScale(),e=>t.contains(this.pixelSpace?e:this.camera.documentPoint(e)),t.profile,this.pixelSpace?t.rasterize:void 0))continue;o={id:s,signature:t.signature,center:a},this.elementFields.set(t.key,o)}let l=this.liquids.fieldForSeed(o.id);l&&n.set(t.key,l)}return n}setInitialPuddles(e){this.liquids.reset(),this.elementFields.clear(),this.nextElementId=1,this.initialPuddles=e.map(({kind:e,color:t,point:n,amount:r})=>({kind:e,color:t?[...t]:void 0,point:{...n},amount:r})),this.restoreInitialPuddles()}restoreInitialPuddles(){for(let e of this.initialPuddles)this.depositInitialPuddle(e)}depositInitialPuddle({kind:e,color:t,point:n,amount:r}){let i=this.localFromDocument(n),a=this.camera.particleScale(),o=Math.max(1,Math.ceil(r/2));for(let n=0;n<o;n++)this.liquids.pour(e,i,a,r/o,D(),t),this.liquids.step(1/30)}localFromDocument(e){return this.pixelSpace?{...e}:this.camera.worldFromDocument(e)}},$y=class{bounds=[];tiles=new Map;dpr=1;scale=1;setBounds(e){this.bounds=e;for(let[t,n]of this.tiles)t>=e.length&&(n.canvas.remove(),this.tiles.delete(t))}resize(e,t,n,r){this.dpr=n,this.scale=r}tile(e){let t=this.tiles.get(e);if(t)return t;let n=document.createElement(`canvas`);n.dataset.jrLiquidTextVehicle=``;let r=n.getContext(`2d`);if(!r)throw Error(`Joy Ride requires a 2D canvas context.`);return n.setAttribute(`aria-hidden`,`true`),Object.assign(n.style,{position:`fixed`,pointerEvents:`none`,zIndex:ey(`foreground`),transformOrigin:`0 0`,display:`none`}),document.body.append(n),t={canvas:n,context:r,visible:!1},this.tiles.set(e,t),t}draw(e,t,n,r){for(let i=0;i<this.bounds.length;i++){let a=this.bounds[i],o=e({x:a.x,y:a.y}),s=e({x:a.x+a.width,y:a.y+a.height}),c=o.x,l=o.y,u=s.x-c,d=s.y-l;if(!t.some(({point:e,radius:t})=>e.x>=c-t&&e.x<=c+u+t&&e.y>=l-t&&e.y<=l+d+t)||u<=0||d<=0){let e=this.tiles.get(i);e?.visible&&(e.canvas.style.display=`none`,e.visible=!1);continue}let f=this.tile(i),{canvas:p,context:m}=f,h=Math.max(1,Math.ceil(u*this.dpr)),g=Math.max(1,Math.ceil(d*this.dpr));(p.width!==h||p.height!==g)&&(p.width=h,p.height=g,p.style.width=`${u}px`,p.style.height=`${d}px`);let _=`${c*this.scale}px`,v=`${l*this.scale}px`;p.style.left!==_&&(p.style.left=_),p.style.top!==v&&(p.style.top=v),p.style.scale!==String(this.scale)&&(p.style.scale=String(this.scale)),f.visible||=(p.style.display=`block`,!0),m.setTransform(this.dpr,0,0,this.dpr,0,0),m.clearRect(0,0,u,d),m.save(),m.translate(-c+n.x,-l+n.y),r(m),m.restore()}}dispose(){for(let e of this.tiles.values())e.canvas.remove();this.tiles.clear()}};function eb(e,t,n,r,i,a,o,s=[]){let{sim:c,tirePaint:l}=e;if(c.mode!==`car`)return;let u=[];c.car.statusEffects.setContacts(`mud`,St.mud,u),e.isGhost?c.car.tires.forEach((e,t)=>l.pauseTrack(t)):(l.step(a?c.car.tires.map(e=>M(c.body.velocityAt(c.body.world(e.local)))*r):[]),o?(c.car.tires.forEach((e,r)=>{let o=t[r],d=o?.materials??[],f=e=>d.some(t=>ut(t)===e&&!_t(t)),p=()=>{for(let e of d){let t=_t(e);t&&c.car.statusEffects.apply(`liquid:${e}`,t,r)}};if(d.some(e=>ut(e)===`water`)&&(c.car.washWheel(r),l.wash(r,o?.paints??[]),!o?.paints?.length)){p();return}f(`oil`)&&c.car.coatWithOil(r),d.some(e=>ut(e)===`mud`)&&(f(`mud`)&&c.car.coatWithMud(r),u.push(r)),p();for(let e of o?.paints??(o?.paint?[o.paint]:[]))l.touch(r,e);if(l.touch(r,s[r]??null),!a){l.pauseTrack(r);return}let m=l.coating(r),h=d.length>0&&!!o?.paint&&m?.color!==o.paint.color;(o?.paints?.length??+!!o?.paint)>0||s[r]?l.trackWet(r,n[r],-c.body.angle-e.angle,c.car.preset.geometry.tireWidthM,i,e.slip,h&&!s[r]):l.track(r,n[r],-c.body.angle-e.angle,c.car.preset.geometry.tireWidthM,i,h,e.slip)}),c.car.statusEffects.setContacts(`mud`,St.mud,u)):c.car.tires.forEach((e,t)=>l.pauseTrack(t)))}function tb(e,t,n,r,i,a,o){let s=e=>{let t=e.sim;return t.mode!==`car`||e.isGhost?[]:t.car.tires.map((n,r)=>{let i=t.body.world(n.local);return{point:o.particlePoint(i),velocity:o.particleVelocity(t.body.velocityAt(i)),radiusPx:t.car.preset.geometry.tireWidthM*o.particleScale*.7,slip:n.slip,paint:e.tirePaint.coating(r)}})},c=s(t),l=n.map(e=>({vehicle:e,tires:s(e)}));performance.now(),e.step(r,[...c,...l.flatMap(e=>e.tires)]),performance.now();for(let t of e.burningMasks())o.emitFire(t,r);performance.now();let u=e=>typeof a==`function`?a(e.sim.car.tires.map(t=>o.documentPoint(e.sim.body.world(t.local)))):e===t?a:[];eb(t,e.wheelContacts.slice(0,c.length),c.map(e=>e.point),r,o.particleScale,i,!o.fading,u(t));let d=c.length;for(let{vehicle:t,tires:n}of l)eb(t,e.wheelContacts.slice(d,d+n.length),n.map(e=>e.point),r,o.particleScale,!0,!o.fading,u(t)),d+=n.length;return{tires:c,companionTires:l}}var nb=class{camera;fields=new Zy;authoring;textVehicles=null;constructor(e,t){this.camera=e,this.fields.setQuality(t),this.authoring=new Qy(this.fields,e,e.pixelSpace)}get managedBytes(){return this.fields.managedBytes}setQuality(e){this.fields.setQuality(e)}captureState(){let e=this.fields.captureState();try{return{fields:e,authoring:this.authoring.captureState(),dispose:()=>e.dispose()}}catch(t){throw e.dispose(),t}}restoreState(e){this.fields.restoreState(e.fields),this.authoring.restoreState(e.authoring)}clearEffects(){this.fields.reset(),this.authoring.clearEffects()}restoreInitialPuddles(){this.authoring.restoreInitialPuddles()}dispose(){this.textVehicles?.dispose(),this.textVehicles=null,this.fields.reset()}resize(){this.textVehicles?.resize(this.camera.width,this.camera.height,this.camera.dpr,this.camera.regionScale)}pruneOutside(e){this.fields.pruneOutside(e)}draw(e,t){this.fields.draw(e,e=>this.camera.pixelSpace?k(e,this.camera.sceneScroll()):this.camera.screen(e),this.camera.pixelSpace?1:this.camera.zoom,t,{width:this.camera.width,height:this.camera.height})}drawTextVehicles(e,t,n){this.textVehicles?.draw(e=>this.camera.viewportFromDocument(e),e,t,n)}pourWorldLiquid(e,t,n,r,i){this.authoring.pourWorldLiquid(e,t,n,r,i)}emitPaint(e,t,n,r,i){this.fields.emit(`paint`,this.camera.particlePoint(e),this.camera.particleScale(),n,t,this.camera.pixelSpace?D(i.x,-i.y):i,r)}local(e){return this.camera.particlePoint(this.camera.worldFromDocument(e))}get ratio(){return this.camera.particleScale()/this.camera.documentScale()}hasConductiveCandidate(e,t){return this.fields.hasConductiveCandidate(e.map(e=>this.local(e)),t*this.ratio)}conductLightning(e,t=0){let n=e=>this.local(e),r=e=>this.camera.pixelSpace?e:this.camera.documentPoint(e),i=this.ratio,a=this.fields.conductAt(e.map(n),t*i);return{points:a.points.map(r),contains:(e,t=0)=>a.contains(n(e),t*i),intersects:(e,t=0)=>{let r=n(e),o=n({x:e.x+e.width,y:e.y+e.height});return a.intersects({x:Math.min(r.x,o.x),y:Math.min(r.y,o.y),width:Math.abs(r.x-o.x),height:Math.abs(r.y-o.y)},t*i)},pathTo:(e,t=0)=>a.pathTo(n(e),t*i).map(r)}}igniteAt(e,t){this.fields.igniteAt(this.local(e),t*this.ratio)}igniteConducted(e,t){this.fields.igniteConducted(e.map(e=>this.local(e)),t*this.ratio)}igniteFromFire(e){if(!e.length)return;let t=new Map,n=this.fields.fireContactBounds().map(e=>{if(this.camera.pixelSpace)return e;let t=this.camera.documentPoint({x:e.x,y:e.y}),n=this.camera.documentPoint({x:e.x+e.width,y:e.y+e.height});return{x:Math.min(t.x,n.x),y:Math.min(t.y,n.y),width:Math.abs(t.x-n.x),height:Math.abs(t.y-n.y)}});for(let r of e){let e=Math.max(0,Math.round(r.radiusPx/4)*4),i=t.get(e)??[],a=r.bounds?n.flatMap(e=>No(r,e)):No(r);for(let e of a)i.push(this.local(e));t.set(e,i)}for(let[e,n]of t)this.fields.igniteConducted(n,e*this.ratio)}burningSources(){let e=24*this.ratio;return this.fields.burningSources(e).map(e=>({point:this.camera.pixelSpace?e:this.camera.documentPoint(e),radiusPx:24,spreadSeconds:Ze.spreadSeconds}))}hasContact(e,t){return this.fields.contacts(ot(e),t.map(e=>this.camera.particlePoint(e))).length>0}add(e,t){this.authoring.addLiquid(e,t)}syncElements(e){if(this.camera.overlay){let t=e.filter(e=>typeof SVGGeometryElement<`u`&&e.key instanceof SVGGeometryElement||typeof HTMLElement<`u`&&e.key instanceof HTMLElement&&(e.key.childElementCount>0||!!e.key.textContent?.trim())).map(e=>e.bounds);t.length&&(this.textVehicles??=new $y),this.textVehicles?.setBounds(t),this.resize()}return this.authoring.syncElementLiquids(e)}setInitialPuddles(e){this.authoring.setInitialPuddles(e)}pourVehicle(e,t,n,r,i=`player`){if(e.mode!==`car`)return;let a=e.body.world(D(-e.car.preset.geometry.lengthM/2-.58,0)),o=N(D(-4,0),e.body.angle);this.fields.pour(t,this.camera.particlePoint(a),this.camera.particleScale(),n,this.camera.pixelSpace?D(o.x,-o.y):o,r,i)}stepVehicles(e,t,n,r,i,a,o){return tb(this.fields,e,t,n,r,i,{particlePoint:e=>this.camera.particlePoint(e),particleVelocity:e=>this.camera.pixelSpace?D(e.x*this.camera.zoom,-e.y*this.camera.zoom):{...e},documentPoint:e=>this.camera.documentPoint(e),particleScale:this.camera.particleScale(),fading:a,emitFire:o})}splatter(e,t,n,r,i,a,o,s){this.fields.splatter(n,r,i,a,o,!1,s,e.tirePaint.coating(t))||e.tirePaint.splatter(t,r,i,a,o,s,this.camera.particleScale())}igniteAlong(e,t,n){this.fields.igniteAlong(e,t,n)}igniteAtLocal(e){this.fields.igniteAt(e)}pourOilPreview(e,t){this.fields.pour(`oil`,e,this.camera.particleScale(),t*6,D())}},rb=256,ib=48,ab=class{overPuddle;constructor(e=null){this.overPuddle=e}tiles=new Map;records=new Map;archived=0;references=0;processed=0;ratio=0;scale=0;captureState(){return{marks:E([...new Set([...this.records.values()].flat())]),processed:this.processed,scale:this.scale}}restoreState(e){this.clear(),this.scale=e.scale,this.seed(E(e.marks),e.scale),this.processed=e.processed}managedBytes(e){return this.tiles.size*(rb*this.ratio)**2*4+Math.max(0,this.archived-e)*136+this.references*8}clear(){this.tiles.clear(),this.records.clear(),this.archived=0,this.references=0,this.processed=0}seed(e,t){for(let n of e)(this.overPuddle===null||!!n.overPuddle===this.overPuddle)&&this.indexMark(n,t)}draw(e,t,n,r,i,a,o,s,c,l){n<this.processed&&this.clear(),(this.ratio!==c||this.scale!==s)&&(this.tiles.clear(),this.ratio=c,this.scale=s);let u=Math.min(t.length,n-this.processed);for(let e=t.length-u;e<t.length;e++){let n=t[e];(this.overPuddle===null||!!n.overPuddle===this.overPuddle)&&this.indexMark(n,s)}if(this.processed=n,!this.archived)return;let d=Math.floor(r/rb),f=Math.floor((r+a)/rb),p=Math.floor(i/rb),m=Math.floor((i+o)/rb),h=new Set;e.save(),e.globalAlpha=l;for(let t=p;t<=m;t++)for(let n=d;n<=f;n++){let a=`${n},${t}`;h.add(a);let o=this.records.get(a);if(!o?.length)continue;let c=this.tiles.get(a);if(!c){c=this.createTile(n,t);for(let e of o)this.stroke(c,e,s);this.tiles.set(a,c)}e.drawImage(c.canvas,n*rb-r,t*rb-i,rb,rb)}if(e.restore(),this.tiles.size>ib)for(let e of this.tiles.keys()){if(this.tiles.size<=ib)break;h.has(e)||this.tiles.delete(e)}}pruneOutside(e){for(let t of this.records.keys()){let[n,r]=t.split(`,`).map(Number);((n+1)*rb<e.x||n*rb>e.x+e.width||(r+1)*rb<e.y||r*rb>e.y+e.height)&&(this.records.delete(t),this.tiles.delete(t))}this.archived=new Set([...this.records.values()].flat()).size,this.references=[...this.records.values()].reduce((e,t)=>e+t.length,0)}indexMark(e,t){this.archived++;let n=e.widthM*Math.max(32,t)*.38+2,r=Math.floor((Math.min(e.from.x,e.point.x)-n)/rb),i=Math.floor((Math.max(e.from.x,e.point.x)+n)/rb),a=Math.floor((Math.min(e.from.y,e.point.y)-n)/rb),o=Math.floor((Math.max(e.from.y,e.point.y)+n)/rb);for(let n=a;n<=o;n++)for(let a=r;a<=i;a++){let r=`${a},${n}`,i=this.records.get(r);i||(i=[],this.records.set(r,i)),i.push(e),this.references++;let o=this.tiles.get(r);o&&this.stroke(o,e,t)}}createTile(e,t){let n=document.createElement(`canvas`);n.width=Math.ceil(rb*this.ratio),n.height=Math.ceil(rb*this.ratio);let r=n.getContext(`2d`);if(!r)throw Error(`Joy Ride tire marks require a 2D canvas context`);return r.setTransform(this.ratio,0,0,this.ratio,-e*rb*this.ratio,-t*rb*this.ratio),{canvas:n,context:r}}stroke(e,t,n){let r=e.context;wa(r,t,t.from,t.point,t.widthM*n*.76,n)}},ob=class{ground=new ab;dry=new Map;wet=new Map;seed(e,t){this.ground.seed(e,t)}forgetVehicle(e){this.dry.delete(e),this.wet.delete(e)}captureState(){return{ground:this.ground.captureState(),dry:[...this.dry].map(([e,t])=>[e,t.captureState()]),wet:[...this.wet].map(([e,t])=>[e,t.captureState()])}}restoreState(e){this.ground.restoreState(e.ground),this.dry=new Map(e.dry.map(([e,t])=>{let n=new ab(!1);return n.restoreState(t),[e,n]})),this.wet=new Map(e.wet.map(([e,t])=>{let n=new ab(!0);return n.restoreState(t),[e,n]}))}get managedBytes(){return this.ground.managedBytes(0)+[...this.dry.values(),...this.wet.values()].reduce((e,t)=>e+t.managedBytes(0),0)}clear(){this.ground.clear(),this.dry.clear(),this.wet.clear()}pruneOutside(e){for(let t of[...this.dry.values(),...this.wet.values()])t.pruneOutside(e)}draw(e,t,n,r){let{pixelSpace:i,scroll:a,width:o,height:s,particleScale:c,rasterRatio:l,zoom:u,effectsAlpha:d,screen:f}=r;if(e.save(),e.lineCap=`round`,i){n||this.ground.draw(e,[],0,a.x,a.y,o,s,c,l,d);let r=n?this.wet:this.dry;for(let i of t){let t=r.get(i.id);t||(t=new ab(n),r.set(i.id,t)),t.draw(e,i.tirePaint.marks,i.tirePaint.totalMarks,a.x,a.y,o,s,c,l,d)}}else for(let r of t)for(let t of r.tirePaint.marks){if(!!t.overPuddle!==n)continue;let r=f(t.point),i=f(t.from);(r.x<-20||r.x>o+20||r.y<-20||r.y>s+20)&&(i.x<-20||i.x>o+20||i.y<-20||i.y>s+20)||wa(e,t,i,r,t.widthM*c*u*.76,c*u,d)}e.restore()}};function sb(e,t,n,r){let i=k(n,t),a=M(i);if(a<1e-5)return;let o=A(i,1/a),s=e.widthPx,c=Math.max(.055*(s/e.widthM),s*.4),l=e.nextStamp,u=0;for(;l<=a&&u++<80;){let n=D(-o.y,o.x),i=O(O(t,A(o,l)),A(n,(Math.random()-.5)*s*.04));e.stamps.push({point:i,direction:o,length:c*(.78+Math.random()*.14),opacity:P(.57+r*.26+(Math.random()-.5)*.12,.3,1),shoulder:(Math.random()-.5)*.06}),l+=c}e.nextStamp=Math.max(0,l-a)}function cb(e,t,n){if(e.contactStamps>=48)return;let r=e.widthPx,i=D(-n.y,n.x);for(let a=0;a<2;a++)e.stamps.push({point:O(t,O(A(n,(Math.random()-.5)*r*1.4),A(i,(Math.random()-.5)*r*.2))),direction:n,length:r*(.3+Math.random()*.18),opacity:.35+Math.random()*.25,shoulder:(Math.random()-.5)*.06});e.contactStamps+=2}function lb(e,t,n,r,i,a){if(t.length<2)return;let o=t.map((e,r)=>{let i=t[Math.max(0,r-1)],a=t[Math.min(t.length-1,r+1)],o=k(a,i),s=Math.max(1e-5,M(o));return D(e.x-o.y/s*n,e.y+o.x/s*n)});e.beginPath(),e.moveTo(o[0].x,o[0].y);for(let t=1;t<o.length-1;t++){let n=A(O(o[t],o[t+1]),.5);e.quadraticCurveTo(o[t].x,o[t].y,n.x,n.y)}e.lineTo(o[o.length-1].x,o[o.length-1].y),e.strokeStyle=a,e.globalAlpha=i,e.lineWidth=r,e.stroke()}function ub(e,t,n,r,i,a){t.road&&(r=kl.dark);let o=n?t.points.map(a.screen):t.points,s=Math.max(2,(a.pixelSpace?t.widthPx:t.widthM*a.zoom)*.72);lb(e,o,0,s*.92,.075*t.opacity*r.alphaScale*i,r.ink),lb(e,o,-s*.29,s*.22,.17*t.opacity*r.alphaScale*i,r.ink),lb(e,o,s*.29,s*.22,.17*t.opacity*r.alphaScale*i,r.ink),e.fillStyle=r.ink;for(let o of t.stamps){let c=n?a.screen(o.point):o.point;if(n&&(c.x<-12||c.x>a.width+12||c.y<-12||c.y>a.height+12))continue;let l=a.pixelSpace?o.direction:D(o.direction.x,-o.direction.y),u=o.length*(a.pixelSpace?1:a.zoom);e.save(),e.translate(c.x,c.y),e.rotate(Math.atan2(l.y,l.x)),e.globalAlpha=.28*t.opacity*o.opacity*r.alphaScale*i;let d=s*.2,f=Math.max(1,u*.82),p=s*(.29+o.shoulder);e.beginPath(),e.roundRect(-f/2,-p-d/2,f,d,Math.min(.7,d*.2)),e.roundRect(-f/2,p-d/2,f,d,Math.min(.7,d*.2)),e.fill(),e.restore()}}var db=256,fb=48,pb=class{records=new Map;tiles=new Map;paths=0;pathBytes=0;references=0;ratio=0;theme=``;captureState(){return E([...new Set([...this.records.values()].flat())])}restoreState(e,t){this.clear();for(let n of E(e))this.add(n,t)}get managedBytes(){return this.tiles.size*(db*this.ratio)**2*4+this.pathBytes+this.references*8}clear(){this.records.clear(),this.tiles.clear(),this.paths=0,this.pathBytes=0,this.references=0}add(e,t){this.paths++,this.pathBytes+=96+e.points.length*24+e.stamps.length*64;let n=Math.max(2,e.widthPx)*2,r=Math.floor((e.bounds.left-n)/db),i=Math.floor((e.bounds.right+n)/db),a=Math.floor((e.bounds.bottom-n)/db),o=Math.floor((e.bounds.top+n)/db);for(let n=a;n<=o;n++)for(let a=r;a<=i;a++){let r=`${a},${n}`,i=this.records.get(r);i||(i=[],this.records.set(r,i)),i.push(e),this.references++;let o=this.tiles.get(r);o&&t(o.context,e)}}draw(e,t,n,r,i,a,o,s,c){if(!this.paths)return;(this.ratio!==a||this.theme!==o)&&(this.tiles.clear(),this.ratio=a,this.theme=o);let l=Math.floor(t/db),u=Math.floor((t+r)/db),d=Math.floor(n/db),f=Math.floor((n+i)/db),p=new Set;e.save(),e.globalAlpha=s;for(let r=d;r<=f;r++)for(let i=l;i<=u;i++){let a=`${i},${r}`,o=this.records.get(a);if(!o?.length)continue;p.add(a);let s=this.tiles.get(a);if(!s){s=this.createTile(i,r);for(let e of o)c(s.context,e);this.tiles.set(a,s)}e.drawImage(s.canvas,i*db-t,r*db-n,db,db)}if(e.restore(),this.tiles.size>fb)for(let e of this.tiles.keys()){if(this.tiles.size<=fb)break;p.has(e)||this.tiles.delete(e)}}pruneOutside(e){for(let t of this.records.keys()){let[n,r]=t.split(`,`).map(Number);((n+1)*db<e.x||n*db>e.x+e.width||(r+1)*db<e.y||r*db>e.y+e.height)&&(this.records.delete(t),this.tiles.delete(t))}let t=new Set([...this.records.values()].flat());this.paths=t.size,this.references=[...this.records.values()].reduce((e,t)=>e+t.length,0),this.pathBytes=[...t].reduce((e,t)=>e+96+t.points.length*24+t.stamps.length*64,0)}createTile(e,t){let n=document.createElement(`canvas`);n.width=Math.ceil(db*this.ratio),n.height=Math.ceil(db*this.ratio);let r=n.getContext(`2d`);if(!r)throw Error(`Joy Ride skid tiles require a 2D canvas context`);return r.setTransform(this.ratio,0,0,this.ratio,-e*db*this.ratio,-t*db*this.ratio),r.lineCap=`round`,r.lineJoin=`round`,{canvas:n,context:r}}},mb=class{clock=0;time=0;presetId=null;previous=new Map;paths=[];tiles=new pb;revealAlpha=1;pendingReveal=new Set;captureState(){let e=E({previous:this.previous,paths:this.paths});return{clock:this.clock,time:this.time,presetId:this.presetId,previous:e.previous,paths:e.paths,revealAlpha:this.revealAlpha,pendingRevealIndices:this.paths.flatMap((e,t)=>this.pendingReveal.has(e)?[t]:[]),tiles:this.tiles.captureState()}}restoreState(e,t,n){this.clock=e.clock,this.time=e.time,this.presetId=e.presetId;let r=E({previous:e.previous,paths:e.paths});this.previous=r.previous,this.paths=r.paths,this.revealAlpha=e.revealAlpha,this.pendingReveal=new Set(e.pendingRevealIndices.map(e=>this.paths[e]));let i=kl[n?`dark`:`light`];this.tiles.restoreState(e.tiles,(e,n)=>ub(e,n,!1,i,1,t))}get managedBytes(){return this.paths.reduce((e,t)=>e+96+t.points.length*24+t.stamps.length*64,0)+this.tiles.managedBytes}clear(){this.clock=0,this.time=0,this.presetId=null,this.previous.clear(),this.paths=[],this.revealAlpha=1,this.pendingReveal.clear(),this.tiles.clear()}beginReveal(e,t){this.setRevealAlpha(1,e,t),this.stop(e,t),this.revealAlpha=0}setRevealAlpha(e,t,n){let r=P(e,0,1);if((r!==this.revealAlpha||this.pendingReveal.size!==0)&&(this.revealAlpha=r,!(this.revealAlpha<1))){for(let e of this.pendingReveal)this.rasterize(e,t,n);this.pendingReveal.clear()}}fade(){this.previous.clear()}stop(e,t,n=!1){for(let{path:n}of this.previous.values())this.finish(n,e,t);this.previous.clear(),n&&(this.clock=0)}pruneOutside(e){this.tiles.pruneOutside(e)}step(e,t,n,r,i){this.time+=e,this.clock+=e,!(this.clock<1/30)&&(this.clock%=1/30,this.presetId!==t.car.preset.id&&(this.stop(i.view,i.dark),this.presetId=t.car.preset.id),t.car.tires.forEach((e,a)=>{let o=this.previous.get(a);if(r(a)){o&&this.finish(o.path,i.view,i.dark),this.previous.delete(a);return}let s=i.project(t.body.world(e.local)),c=n&&!e.front;if(!e.skidding&&!c){o&&this.finish(o.path,i.view,i.dark),this.previous.delete(a);return}let l=i.project(t.body.world(O(e.local,D(-t.car.preset.geometry.tireLengthM*.8)))),u=!i.dark&&i.roadAt(e,s),d=o&&o.path.road===u&&this.time-o.time<.18&&o.path.stamps.length<(i.pixelSpace?64:320)?o.path:{road:u,points:e.spinning?[l,s]:i.pixelSpace&&o&&o.path.stamps.length>=64?[o.path.points[o.path.points.length-1],s]:[s],stamps:[],contactStamps:0,nextStamp:0,widthM:t.car.preset.geometry.tireWidthM,widthPx:t.car.preset.geometry.tireWidthM*i.scale,opacity:e.spinning?1:c?.72:P(.25+e.slip*.55+e.heat*.2,.3,1),bounds:{left:Math.min(l.x,s.x),right:Math.max(l.x,s.x),bottom:Math.min(l.y,s.y),top:Math.max(l.y,s.y)}};if(d!==o?.path)o&&this.finish(o.path,i.view,i.dark),this.paths.push(d),e.spinning?sb(d,l,s,1):d.points.length>1&&sb(d,d.points[0],s,c?.72:e.slip);else{let n=d.points[d.points.length-1];M(k(s,n))>(i.pixelSpace?.05:.001)?(sb(d,n,s,e.spinning?1:c?.72:e.slip),d.points.push(s),d.bounds.left=Math.min(d.bounds.left,s.x),d.bounds.right=Math.max(d.bounds.right,s.x),d.bounds.bottom=Math.min(d.bounds.bottom,s.y),d.bounds.top=Math.max(d.bounds.top,s.y)):e.spinning&&cb(d,s,D(Math.cos(t.body.angle),i.pixelSpace?-Math.sin(t.body.angle):Math.sin(t.body.angle)))}this.previous.set(a,{path:d,time:this.time})}))}finish(e,t,n){this.revealAlpha<1?this.pendingReveal.add(e):this.rasterize(e,t,n)}rasterize(e,t,n){if(!t.pixelSpace)return;let r=kl[n?`dark`:`light`];this.tiles.add(e,(e,n)=>ub(e,n,!1,r,1,t));let i=this.paths.indexOf(e);i>=0&&this.paths.splice(i,1)}draw(e,t){let{pixelSpace:n,scroll:r,width:i,height:a,ratio:o,dark:s,alpha:c,visible:l,view:u}=t,d=kl[s?`dark`:`light`];performance.now(),n&&this.tiles.draw(e,r.x,r.y,i,a,o,s?`dark`:`light`,c,(e,t)=>ub(e,t,!1,d,1,u)),performance.now();for(let t of this.paths){let r=(n?t.widthPx:t.widthM*u.zoom)*2;t.bounds.right<l.left-r||t.bounds.left>l.right+r||t.bounds.top<l.bottom-r||t.bounds.bottom>l.top+r||ub(e,t,!0,d,c*this.revealAlpha,u)}}},hb={crashLow:{amplitudePx:.65,durationMs:85,frequencyHz:17},crashMedium:{amplitudePx:1.35,durationMs:125,frequencyHz:19},crashFast:{amplitudePx:2.35,durationMs:165,frequencyHz:21},rocketExplosion:{amplitudePx:2.8,durationMs:190,frequencyHz:16},lightning:{amplitudePx:3.1,durationMs:210,frequencyHz:26},combustibleExplosion:{amplitudePx:3.3,durationMs:215,frequencyHz:17}};function gb(e){return!Number.isFinite(e)||e<.8?null:e<3.5?`crashLow`:e<8?`crashMedium`:`crashFast`}var _b=class{enabled=!0;profiles={...hb};impulses=[];lastTriggered=new Map;sequence=0;captureState(){return{at:performance.now(),data:E({enabled:this.enabled,profiles:this.profiles,impulses:this.impulses,lastTriggered:this.lastTriggered,sequence:this.sequence})}}restoreState(e){let t=E(e.data);this.enabled=t.enabled,this.profiles=t.profiles,this.impulses=t.impulses,this.lastTriggered=t.lastTriggered,this.sequence=t.sequence;let n=performance.now()-e.at;for(let e of this.impulses)e.startedAt+=n;for(let[e,t]of this.lastTriggered)this.lastTriggered.set(e,t+n)}get active(){return this.impulses.length>0}setEnabled(e){this.enabled=e,e||this.reset()}setProfiles(e){let t={...hb};if(e)for(let n of Object.keys(t)){let r=e[n];if(!r)continue;let i=t[n],a=(e,t,n,r)=>e!==void 0&&Number.isFinite(e)?Math.max(n,Math.min(r,e)):t;t[n]={amplitudePx:a(r.amplitudePx,i.amplitudePx,0,6),durationMs:a(r.durationMs,i.durationMs,25,300),frequencyHz:a(r.frequencyHz,i.frequencyHz,5,35)}}this.profiles=t}reset(){this.impulses.length=0,this.lastTriggered.clear()}trigger(e,t=1,n=performance.now()){if(!this.enabled||!Number.isFinite(t)||t<=0)return;let r=this.profiles[e];!r||r.amplitudePx<=0||n-(this.lastTriggered.get(e)??-1/0)<55||(this.lastTriggered.set(e,n),this.impulses.push({event:e,startedAt:n,profile:r,amplitudePx:Math.min(5,r.amplitudePx*Math.min(2,t)),phase:++this.sequence*2.399963}),this.impulses.length>4&&this.impulses.shift())}sample(e){if(!this.enabled||!this.impulses.length)return{x:0,y:0};let t=0,n=0;for(let r=this.impulses.length-1;r>=0;r--){let i=this.impulses[r],a=Math.max(0,e-i.startedAt);if(a>=i.profile.durationMs){this.impulses.splice(r,1);continue}let o=(1-a/i.profile.durationMs)**2,s=a*i.profile.frequencyHz*Math.PI*2/1e3,c=i.amplitudePx*o;t+=Math.sin(s+i.phase)*c,n+=Math.sin(s*1.17+i.phase*.7+.8)*c*.72}return{x:Math.max(-4,Math.min(4,t)),y:Math.max(-4,Math.min(4,n))}}};function vb(e,t,n,r){let i=e=>e-r.x,a=e=>e-r.y,o=(e,t,n,i)=>n>=r.x&&e<=r.x+r.width&&i>=r.y&&t<=r.y+r.height;e.save(),e.lineCap=`round`,e.lineJoin=`round`,e.font=`bold 11px ui-monospace, SFMono-Regular, monospace`,n.forEach((t,n)=>{let r=t.box;o(r.x,r.y,r.x+r.width,r.y+r.height)&&(e.setLineDash([5,5]),e.strokeStyle=`rgba(210, 95, 255, 0.9)`,e.lineWidth=1.5,e.strokeRect(i(r.x),a(r.y),r.width,r.height),e.setLineDash([]),e.fillStyle=`#d25fff`,e.fillText(`TARGET ${n+1}`,i(r.x)+5,a(r.y)-9))});for(let n of t.segments){if(n.kind===`donut`){if(!o(n.center.x-n.radius,n.center.y-n.radius,n.center.x+n.radius,n.center.y+n.radius))continue;e.setLineDash([5,7]),e.strokeStyle=`#c33bdf`,e.lineWidth=2,e.beginPath(),e.arc(i(n.center.x),a(n.center.y),n.radius,0,Math.PI*2),e.stroke(),e.setLineDash([]),e.fillStyle=`#c33bdf`,e.beginPath(),e.arc(i(n.center.x),a(n.center.y),4,0,Math.PI*2),e.fill(),e.fillText(`${n.laps} PHYSICS DONUT${n.laps===1?``:`S`}`,i(n.center.x)+10,a(n.center.y)-10);continue}if(n.kind===`pause`){if(!o(n.point.x-16,n.point.y-16,n.point.x+16,n.point.y+16))continue;e.fillStyle=`#f7ba4c`,e.beginPath(),e.arc(i(n.point.x),a(n.point.y),6,0,Math.PI*2),e.fill(),e.fillText(`${Math.round(n.seconds*1e3)}ms`,i(n.point.x)+11,a(n.point.y)-10);continue}let t=[n.from,n.control1,n.control2,n.to];o(Math.min(...t.map(e=>e.x)),Math.min(...t.map(e=>e.y)),Math.max(...t.map(e=>e.x)),Math.max(...t.map(e=>e.y)))&&(e.beginPath(),e.moveTo(i(n.from.x),a(n.from.y)),e.bezierCurveTo(i(n.control1.x),a(n.control1.y),i(n.control2.x),a(n.control2.y),i(n.to.x),a(n.to.y)),e.setLineDash([9,7]),e.strokeStyle=`#09b7cf`,e.lineWidth=2.5,e.stroke())}e.setLineDash([]),o(t.entry.x-12,t.entry.y-12,t.entry.x+12,t.entry.y+12)&&(e.fillStyle=`#09b7cf`,e.beginPath(),e.arc(i(t.entry.x),a(t.entry.y),6,0,Math.PI*2),e.fill(),e.fillText(`ENTRY`,i(t.entry.x)+11,a(t.entry.y)-10)),e.restore()}function yb(e,t){return e===null?1:Math.max(0,1-(t-e)/240)}function bb(e,t,n,r,i,a,o=!1){let s=!t.front&&(t.spinning||o);if(!t.skidding&&!o)return null;let c=s?.38+.62*t.heat:P(t.slip*(.22+t.heat*.78),0,1);if(c<.05)return null;let l=M(e.body.velocity),u=l>.1?A(e.body.velocity,-1/l):N(D(-1),e.body.angle),d=D(u.x,-u.y),f=D(Math.cos(e.body.angle),-Math.sin(e.body.angle)),p=D(-f.y,f.x),m=Math.sign(t.local.y)||1;return{point:a(e.body.world(O(t.local,D(0,m*e.car.preset.geometry.tireWidthM*.53)))),amount:n*(t.front?3:s?12:6.5)*c,flow:O(A(r,s?.08:.22),O(A(d,(s?110+Math.min(18,Math.abs(t.wheelSurfaceSpeedMps)*3):125)*c),A(p,m*(s?64:45)*c))),radiusPx:(s?.8:.55+t.heat*.16)*i,swirlPx:m*(s?85:105)*c,strength:c,burnout:s}}function xb(e,t,n,r,i,a,o,s=!1){let c=e.sim;c.car.tires.forEach((l,u)=>{let d=bb(c,l,r,a,o.zoom,o.particlePoint,s&&!l.front);if(!d)return;let f=c.body.world(l.local),p=Xy(d.burnout,c.body.angle,l.angle,c.body.velocityAt(f),i);o.spray(e,u,n+u,t[u].point,o.particleVelocity(p),t[u].radiusPx,r*(d.burnout?85:48)*d.strength,P(.75+l.slipSpeedMps/12+M(c.body.velocityAt(f))/28,.8,1.9)),o.smoke?.({point:d.point,amount:d.amount,flow:d.flow,radiusPx:d.radiusPx,swirlPx:d.swirlPx})})}var Sb=class{canvas=document.createElement(`canvas`);mask=document.createElement(`canvas`);gl=this.canvas.getContext(`webgl2`,{alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0});program=null;texture=null;startedAt=-1/0;duration=680;constructor(){let e=this.gl;e&&(this.program=Dv(e,`#version 300 es
772
772
  precision highp float;
773
773
  out vec2 uv;
774
774
  void main() {
@@ -1006,7 +1006,7 @@ void main() {
1006
1006
  float alpha=max(light.r,max(light.g,light.b));
1007
1007
  if (alpha<0.001) discard;
1008
1008
  color=vec4(light,alpha);
1009
- }`,Rb=class{canvas;gl;program;buffer;vao;data=new Float32Array(81920);width=1;height=1;lost=!1;disposed=!1;onLost=e=>{e.preventDefault(),this.lost=!0};onRestored=()=>{this.disposed||(this.initialize(),this.lost=!1)};constructor(e=document.createElement(`canvas`)){this.canvas=e;let t=e.getContext(`webgl2`,{alpha:!0,premultipliedAlpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1});if(!t)throw Error(`WebGL2 is required for electricity`);this.gl=t,this.initialize(),e.addEventListener(`webglcontextlost`,this.onLost),e.addEventListener(`webglcontextrestored`,this.onRestored)}initialize(){let e=this.gl,t=Dv(e,Ib,Lb,`Electricity`),n=e.createBuffer(),r=e.createVertexArray();if(!n||!r)throw Pv(e,t),e.deleteBuffer(n),e.deleteVertexArray(r),Error(`Unable to allocate electricity renderer`);this.program=t,this.buffer=n,this.vao=r,e.bindVertexArray(r),e.bindBuffer(e.ARRAY_BUFFER,n),e.bufferData(e.ARRAY_BUFFER,this.data.byteLength,e.DYNAMIC_DRAW),Mv(e,t,{aStart:{buffer:n,numComponents:2,stride:40,offset:0,divisor:1},aEnd:{buffer:n,numComponents:2,stride:40,offset:8,divisor:1},aStyle:{buffer:n,numComponents:4,stride:40,offset:16,divisor:1},aDistance:{buffer:n,numComponents:2,stride:40,offset:32,divisor:1}}),e.bindVertexArray(null)}resize(e,t,n=1){if(this.disposed)return;this.width=Math.max(1,Number.isFinite(e)?e:1),this.height=Math.max(1,Number.isFinite(t)?t:1);let r=Math.min(2,Math.max(.25,Number.isFinite(n)?n:1),Math.sqrt(3e6/(this.width*this.height)),4096/this.width,4096/this.height),i=Math.ceil(this.width*r),a=Math.ceil(this.height*r);this.canvas.width!==i&&(this.canvas.width=i),this.canvas.height!==a&&(this.canvas.height=a)}render(e,t,n={}){if(this.lost||this.disposed)return 0;let r=this.gl;r.viewport(0,0,this.canvas.width,this.canvas.height),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT);let i=0;if(Array.isArray(e))for(let t of e)i+=t.writeInstances(this.data,i);else i=e.writeInstances(this.data);return i?(r.useProgram(this.program),r.bindVertexArray(this.vao),r.bindBuffer(r.ARRAY_BUFFER,this.buffer),r.bufferSubData(r.ARRAY_BUFFER,0,this.data,0,i*10),jv(this.program,{uViewport:[this.width,this.height],uTime:t,uNoiseOrigin:n.noiseOrigin??[0,0],uNoiseScale:n.noiseScale??1,uDark:n.dark===!1?0:1,uExposure:n.exposure??.95,uColor:n.color??[.14,.64,1],uCorona:n.corona??[.28,.13,1]}),r.enable(r.BLEND),r.blendFunc(r.ONE,n.dark===!1?r.ONE_MINUS_SRC_ALPHA:r.ONE),r.drawArraysInstanced(r.TRIANGLES,0,6,i),r.bindVertexArray(null),i):0}dispose(){this.disposed||(this.disposed=!0,this.canvas.removeEventListener(`webglcontextlost`,this.onLost),this.canvas.removeEventListener(`webglcontextrestored`,this.onRestored),this.gl.deleteBuffer(this.buffer),Pv(this.gl,this.program),this.gl.deleteVertexArray(this.vao))}},zb={color:[.58,.81,1],corona:[.25,.48,.9]},Bb=(e,t,n)=>Math.max(t,Math.min(n,e)),Vb=(e,t)=>({x:Math.cos(e)*t,y:Math.sin(e)*t});function Hb(){return{shape:{kind:`point`,center:{x:0,y:0},radius:154},sources:Array.from({length:12},(e,t)=>Vb(t/12*Math.PI*2,126)),targets:Array.from({length:17},(e,t)=>Vb(t/17*Math.PI*2+.8,102))}}function Ub(e){let t=e|0,n=()=>(t^=t<<13,t^=t>>>17,t^=t<<5,(t>>>0)/4294967296),r=[{x:0,y:0},{x:300,y:0}];for(let e=0;e<5;e++){let t=[r[0]],i=82*.54**e;for(let e=1;e<r.length;e++){let a=r[e-1],o=r[e];t.push({x:(a.x+o.x)/2,y:(a.y+o.y)/2+(n()-.5)*i*2},o)}r=t}return{shape:{kind:`path`,points:r,width:82},sources:[{x:0,y:0}],targets:[{x:300,y:0}]}}var Wb=class{vehicles=new Map;visible=[];strikes=[];volumes=[];scratch=new Float32Array(12e3);gpu=null;elapsed=0;emit;failed=!1;cameraOrigin={x:0,y:0};cameraScale=1;get active(){return this.visible.length>0||this.strikes.length>0||this.volumes.length>0}get stats(){let e=[...this.vehicles.values()].flatMap(e=>[e.field,e.charge,e.arc,e.halo]);return{vehicles:this.vehicles.size,fields:e.filter(Boolean).length,nodes:e.reduce((e,t)=>e+(t?.simulation.stats.nodes??0),0),visible:this.visible.length+this.strikes.length+this.volumes.length}}create(e,t){let n=new Fb(e===`arc`?Ub(t):e===`field`?{...Hb(),targets:[{x:0,y:0}]}:Hb(),{seed:t,spacing:e===`field`?13:11,maxNodes:e===`arc`?640:e===`field`?520:330,strikesPerSecond:0,branching:.65,corona:e===`field`?.5:0,nearbyTargets:!1}),r={simulation:n,gain:1,pull:e===`field`};return n.onEmission=e=>{this.emit?.(e.point,e.direction,e.strength*(r.pull?.5:.8))},r}radial(e,t,n,r){let i=t.pixelsPerMetre*n/160;e.simulation.setEmissionFrame({x:t.center.x,y:t.center.y,angle:0,scaleX:i,scaleY:i,width:Bb(i,.65,2)}),e.gain=r}tether(e,t,n){return{x:e.x,y:e.y,angle:Math.atan2(t.y-e.y,t.x-e.x),scaleX:Math.max(.001,Math.hypot(t.x-e.x,t.y-e.y)/300),scaleY:Bb(Math.hypot(t.x-e.x,t.y-e.y)/300,.6,3)*(.95-n*.25),width:.75+n*.45}}strike(e,t,n){let r=e.simulation;r.reset(),r.setEmissionFrame(),r.configure({strikesPerSecond:0,branching:1.8,intensity:1.8});let i=r.onEmission;r.onEmission=void 0,r.discharge(1);for(let e=0;e<24;e++)r.step(1/60);r.onEmission=i;let a=r.writeInstances(this.scratch),o=this.scratch.slice(0,a*10),s=[],c=(e,t,n=!1)=>{if(e.length<2)return;let r=[0];for(let t=1;t<e.length;t++)r.push(r[t-1]+Math.hypot(e[t].x-e[t-1].x,e[t].y-e[t-1].y));let i=r[r.length-1];for(let c=0;c<a&&s.length<22e3;c++){let a=c*10;for(let t of[0,2]){let c=Bb(o[a+t]/300,0,1)*i,l=1;for(;l<r.length-1&&r[l]<c;)l++;let u=e[l-1],d=e[l],f=Math.max(.001,r[l]-r[l-1]),p=Bb((c-r[l-1])/f,0,1),m=n?Math.min(.15,i/300*.1):Math.min(3,Math.max(.65,i/300*.85)),h=o[a+t+1]*m;s.push(u.x+(d.x-u.x)*p-(d.y-u.y)/f*h,u.y+(d.y-u.y)*p+(d.x-u.x)/f*h)}s.push(o[a+4]*t,o[a+5],o[a+6],o[a+7],Bb(o[a]/300,0,1),Bb(o[a+2]/300,0,1))}};c([t.center,n],1.25);for(let e of t.lightning.branches.filter(e=>Math.hypot(e.x-n.x,e.y-n.y)>8).slice(0,4))c([n,e],.8),this.emit?.(e,{x:e.x-n.x,y:e.y-n.y},1.2);for(let e of t.lightning.paths?.slice(0,4)??[])c(e,.85,!0),e.length&&this.emit?.(e[e.length-1],{x:0,y:-1},1.2);this.strikes.push({data:new Float32Array(s),age:0,source:{...t.center},target:{...n},shook:!1}),this.strikes.length>4&&this.strikes.shift(),this.emit?.(n,{x:n.x-t.center.x,y:n.y-t.center.y},2.8),this.emit?.(t.center,{x:t.center.x-n.x,y:t.center.y-n.y},1.8),r.reset()}step(e,t,n,r){let i=Bb(e,0,.05);this.elapsed+=i,this.emit=n,this.visible.length=0,this.volumes.length=0;for(let e=this.strikes.length-1;e>=0;e--){let t=this.strikes[e],a=t.age;t.age+=i,!t.shook&&t.age>=.075&&(t.shook=!0,r?.(t.target),n?.(t.source,{x:0,y:-1},2.4));for(let e=0;e<t.data.length;e+=80){let r=(1-t.data[e+8])*.075;a<=r&&t.age>r&&a<.08&&n?.({x:t.data[e],y:t.data[e+1]},{x:t.data[e+3]-t.data[e+1],y:t.data[e]-t.data[e+2]},.6)}t.age>1.5&&this.strikes.splice(e,1)}for(let e of this.vehicles.values()){e.volumeTarget=0;for(let t of[e.field,e.charge,e.arc,e.halo])t?.simulation.configure({strikesPerSecond:0})}for(let e of t.slice(0,6)){let t=e.lightning.phase===`charging`,n=e.lightning.phase===`discharged`;if(!e.attractor&&!t&&!n&&!e.electrified)continue;let r=this.vehicles.get(e.id);r||(this.vehicles.size>=8&&this.release(this.vehicles.keys().next().value),r={touched:this.elapsed,dischargeId:-1},this.vehicles.set(e.id,r)),r.touched=this.elapsed;let i=Bb(e.lightning.charge,0,1);if(e.attractor){let t=r.field??=this.create(`field`,131+e.id.length);t.simulation.configure({strikesPerSecond:5,intensity:.95,corona:.6,branching:.35}),this.radial(t,e,e.attractorRadiusM,.9),r.volume={center:e.center,radius:e.attractorRadiusM*e.pixelsPerMetre,pull:!0,gain:r.volume?.gain??0},r.volumeTarget=1.3}if(t){let t=r.charge??=this.create(`field`,431+e.id.length);t.simulation.configure({strikesPerSecond:5+i*6,intensity:1+i*.7}),this.radial(t,e,2.8-i*.8,.9),e.attractor||(r.volume={center:e.center,radius:e.pixelsPerMetre*(2.8-i*.8),gain:r.volume?.gain??0},r.volumeTarget=.25+i*.3)}let a=e.lightning.target;if((t||n)&&a){let o=r.arc??=this.create(`arc`,761+e.id.length);n&&e.lightning.dischargeId!==r.dischargeId&&this.strike(o,e,a),t&&(o.simulation.setEmissionFrame(this.tether(e.center,a,i)),o.simulation.configure({strikesPerSecond:2+i*7,branching:.9+i*.5,intensity:.6+i*.5}),o.gain=i**1.4*.9)}if(e.electrified){let t=r.halo??=this.create(`halo`,919+e.id.length);t.simulation.configure({strikesPerSecond:8,intensity:.95}),this.radial(t,e,e.lengthM*.7,.9)}r.dischargeId=e.lightning.dischargeId}for(let[e,t]of this.vehicles)if(t.volume&&(t.volume.gain+=((t.volumeTarget??0)-t.volume.gain)*(1-Math.exp(-i*10)),t.volume.gain>.003&&this.volumes.push(t.volume)),this.elapsed-t.touched>2)this.release(e);else for(let e of[t.field,t.charge,t.arc,t.halo])e&&(e.simulation.step(i),e.simulation.stats.strokes>0&&this.visible.push(e))}writeInstances(e,t=0){let n=t,r=()=>n*10+10<=e.length;for(let t of this.volumes){if(!r())break;let i=this.cameraOrigin.x+t.center.x*this.cameraScale,a=this.cameraOrigin.y+t.center.y*this.cameraScale,o=n++*10;e.set([i,a,i+.01,a,t.radius*this.cameraScale,t.gain,+!!t.pull,5,0,1],o)}for(let t of this.strikes)for(let i=0;i<t.data.length&&r();i+=10){let r=n++*10;e.set(t.data.subarray(i,i+10),r);let a=(1-(t.data[i+8]+t.data[i+9])*.5)*.075,o=t.age-a,s=o<0?.1:t.age<.15?2.5:Math.exp(-(t.age-.15)*3.7)*1.8;e[r+5]*=s,e[r+4]*=o>=0&&o<.08?1.4:1,this.projectInstance(e,r)}for(let t of this.visible){let r=e.subarray(n*10,Math.min(e.length,(n+1200)*10)),i=t.simulation.writeInstances(r),a=t.pull&&i?r[6]:-1;for(let e=0;e<i;e++){let n=e*10;r[n+5]*=t.gain,t.pull&&(r[n+7]===2?r[n+5]*=.2:r[n+6]===a?(r[n+7]=0,r[n+5]*=1.2):(r[n+7]=3,r[n+4]*=3.8)),this.projectInstance(r,n)}n+=i}return n-t}projectInstance(e,t){for(let n of[0,2])e[t+n]=this.cameraOrigin.x+e[t+n]*this.cameraScale,e[t+n+1]=this.cameraOrigin.y+e[t+n+1]*this.cameraScale;e[t+4]*=this.cameraScale,e[t+8]*=this.cameraScale,e[t+9]*=this.cameraScale}draw(e,t,n,r,i,a,o=1,s=e=>e,c=1){if(!this.active||this.failed||o<=0)return;if(!this.gpu)try{this.gpu=new Rb}catch{this.failed=!0;return}this.cameraScale=c;let l=s({x:0,y:0});this.cameraOrigin=l,this.gpu.resize(t,n,r),this.gpu.render(this,i,{dark:a,exposure:a?1.05:1.2,...zb,noiseOrigin:[-l.x/c,-l.y/c],noiseScale:1/c}),this.cameraOrigin={x:0,y:0},this.cameraScale=1,e.save(),e.globalAlpha*=o,this.gpu.canvas.width*this.gpu.canvas.height/1e6,e.drawImage(this.gpu.canvas,0,0,t,n),e.restore()}release(e){let t=this.vehicles.get(e);if(t){for(let e of[t.field,t.charge,t.arc,t.halo])e?.simulation.dispose();this.vehicles.delete(e)}}reset(){for(let e of this.vehicles.keys())this.release(e);this.visible.length=0,this.strikes.length=0,this.volumes.length=0,this.elapsed=0}dispose(){this.reset(),this.gpu?.dispose(),this.gpu=null}},Gb=class{camera;effects=new Wb;clock=0;constructor(e){this.camera=e}step(e,t,n,r,i){if(this.clock+=n,this.clock<1/60)return;let a=Math.min(.05,this.clock);this.clock=Math.max(0,this.clock-1/60);let o=[];for(let n of[e,...t]){let e=n.sim;if(e.mode!==`car`||e.car.explodedAt!==null||n.isGhost)continue;let t=n.weapons.lightning.visual,r=e.car.statusEffects.remaining(`electrified`)>0;if(!n.controls.attractor&&t.phase===`idle`&&!r)continue;let i=this.camera.screen(e.body.position),a=Math.max(7,Mn(e.car.preset,this.camera.width,this.camera.documentScale()))*this.camera.zoom;i.x<-a||i.x>this.camera.width+a||i.y<-a||i.y>this.camera.height+a||o.push({id:n.id,center:this.camera.documentPoint(e.body.position),angle:-e.body.angle,pixelsPerMetre:this.camera.documentScale(),lengthM:e.car.preset.geometry.lengthM,widthM:e.car.preset.geometry.widthM,attractor:!!n.controls.attractor&&!e.paused,attractorRadiusM:7,electrified:r,lightning:t})}this.effects.step(e.sim.paused?0:a,o,(e,t,n)=>r.electric(this.camera.particlePoint(this.camera.worldFromDocument(e)),this.camera.pixelSpace?t:D(t.x/this.camera.documentScale(),-t.y/this.camera.documentScale()),n),()=>i.trigger(`lightning`,1,performance.now()))}draw(e,t,n,r){this.effects.draw(e,this.camera.width,this.camera.height,this.camera.dpr,t/1e3,n,r,e=>this.camera.screen(this.camera.worldFromDocument(e)),this.camera.zoom/this.camera.documentScale())}reset(){this.clock=0,this.effects.reset()}dispose(){this.effects.dispose()}},Kb=class{overlay;canvasWorld;carVisualOffset(e){return this.vehicles.carVisualOffset(e)}get cameraLock(){return this.view.cameraLock}set cameraLock(e){this.view.cameraLock=e}get cameraSmoothing(){return this.view.cameraSmoothing}set cameraSmoothing(e){this.view.cameraSmoothing=e}get deadZone(){return this.view.deadZone}set deadZone(e){this.view.deadZone=e}get speedZoom(){return this.view.speedZoom}set speedZoom(e){this.view.speedZoom=e}get speedZoomMinimumScale(){return this.view.speedZoomMinimumScale}set speedZoomMinimumScale(e){this.view.speedZoomMinimumScale=e}screen(e){return this.view.screen(e)}world(e){return this.view.world(e)}vehicleViewportPosition(e){return this.view.vehicleViewportPosition(e)}sceneScroll(){return this.view.sceneScroll()}get documentProjection(){return this.view.documentProjection}virtualOffset(){return this.view.virtualOffset()}documentPoint(e){return this.view.documentPoint(e)}worldFromDocument(e){return this.view.worldFromDocument(e)}documentScale(){return this.view.documentScale()}viewportSize(){return this.view.viewportSize()}presentationScale(){return this.view.presentationScale()}setSlowMoZoom(e){this.view.slowMoZoom=e}setCanvasWorldScale(e,t=1.5){this.view.setCanvasWorldScale(e,t)}setCameraFrame(e){this.view.setCameraFrame(e)}setCameraLock(e){this.view.setCameraLock(e)}viewportFromDocument(e){return this.view.viewportFromDocument(e)}documentFromViewport(e){return this.view.documentFromViewport(e)}bounds(){return this.view.bounds()}vehicleMarkerAt(e){if(!this.showVehicleMarkers)return null;let t=this.view.documentFromViewport(e);return this.vehicles.markerAt(this.view.screen(this.view.worldFromDocument(t)))}revealVehicle(e){this.view.revealVehicle(e)}resumeFollow(){this.view.resumeFollow()}interruptFollow(){this.view.interruptFollow()}restorePage(e){this.view.restorePage(e)&&(this.lastFlowCenter=null,this.flowVelocity=D())}followDocument(e){return this.view.followDocument(e)}primaryVehicleVisible=!0;primaryVehicleOpacity=1;beginVehicleArrivalFade(){this.skidTracks.beginReveal(this.skidView(),this.darkSurface()),this.primaryVehicleOpacity=0}setVehicleArrivalOpacity(e){this.primaryVehicleOpacity=P(e,0,1),this.skidTracks.setRevealAlpha(this.primaryVehicleOpacity,this.skidView(),this.darkSurface())}view;surface;vehicles;debris=new xs;get ctx(){return this.surface.context}nextHistoryPrune=0;trailClock=0;quality=`high`;fluidGovernor=new _c;vehicleLights=new El;surfaceTones=new Qd;vehicleLighting={...Dl};setVehicleLighting(e){this.vehicleLighting=Ol({...this.vehicleLighting,...e})}getVehicleLighting(){return{...this.vehicleLighting}}toggleVehicleLight(e){return this.setVehicleLighting({[e]:!this.vehicleLighting[e]}),this.getVehicleLighting()}surfaceTone=`auto`;trail=[];skidTracks=new mb;volumetrics;pointPuffs=[];objectGlint=null;showVehicleMarkers=!0;tireSmokeEnabled=!0;vehicleShadowsEnabled=!0;effectsFadeStartedAt=null;wallRects=[];combustion;ghostVehicles=new af;sparks=new vy;electricity;liquidLayer;tireMarks=new ob;seedGroundMarks(e){this.overlay&&this.tireMarks.seed(e,this.particleScale())}focusVehicle=null;activeVehicles=[];bindVehicle(e){this.focusVehicle=e}forgetVehicle(e){this.tireMarks.forgetVehicle(e),this.activeVehicles=this.activeVehicles.filter(t=>t.id!==e),this.focusVehicle?.id===e&&(this.focusVehicle=null)}get rocketFlightPosition(){let e=this.focusVehicle?.sim.body.position??D(),t=null,n=1/0;for(let r of this.activeVehicles){let i=r.weapons.rocket.projectile?.position;if(!i)continue;let a=M(k(i,e));a<n&&(t=i,n=a)}return t}screenShake=new _b;exhaustBursts=[];queueExhaustPops(e){for(let t of e)t<.12||this.exhaustBursts.push({age:0,lifetime:.08+t*.11,intensity:.4+t*.6});this.exhaustBursts.length>6&&this.exhaustBursts.splice(0,this.exhaustBursts.length-6)}lastFlowCenter=null;flowVelocity=D();captureState(){let e=[],t=t=>(t&&e.push(()=>t.dispose()),t);try{let n=t(this.volumetrics.captureState()),r=t(this.combustion.captureState()),i=t(this.liquidLayer.captureState());return{at:performance.now(),data:E({primaryVehicleVisible:this.primaryVehicleVisible,primaryVehicleOpacity:this.primaryVehicleOpacity,nextHistoryPrune:this.nextHistoryPrune,trailClock:this.trailClock,quality:this.quality,fluidQualityLimit:this.fluidGovernor.limit,vehicleLighting:this.vehicleLighting,surfaceTone:this.surfaceTone,trail:this.trail,pointPuffs:this.pointPuffs,showVehicleMarkers:this.showVehicleMarkers,tireSmokeEnabled:this.tireSmokeEnabled,vehicleShadowsEnabled:this.vehicleShadowsEnabled,effectsFadeStartedAt:this.effectsFadeStartedAt,wallRects:this.wallRects,exhaustBursts:this.exhaustBursts,lastFlowCenter:this.lastFlowCenter,flowVelocity:this.flowVelocity,debugDrive:this.debugDrive,previewGroundFire:this.previewGroundFire,previewWallSmoke:this.previewWallSmoke,previewSparks:this.previewSparks,previewDamage:this.previewDamage,previewOil:this.previewOil,previewOilSplatter:this.previewOilSplatter,oilSplatterPreviewSeconds:this.oilSplatterPreviewSeconds,sparkPreviewClock:this.sparkPreviewClock,damagePreviewApplied:this.damagePreviewApplied,groundFirePreviewLit:this.groundFirePreviewLit,tourDebug:this.tourDebug,trailLifetime:this.trailLifetime,fallbackSurfaceTone:this.fallbackSurfaceTone}),camera:this.view.captureState(),diagnostics:this.diagnostics.captureState(),vehicles:this.vehicles.captureState(),volumetrics:n,combustion:r,liquids:i,debris:this.debris.captureState(),skidTracks:this.skidTracks.captureState(),tireMarks:this.tireMarks.captureState(),sparks:this.sparks.captureState(),screenShake:this.screenShake.captureState(),dispose:()=>e.forEach(e=>e())}}catch(t){throw e.forEach(e=>e()),t}}restoreState(e){let t=this.captureState();try{this.applyState(e)}catch(e){try{this.applyState(t)}catch(t){throw AggregateError([e,t],`Renderer checkpoint rollback failed`,{cause:t})}throw e}finally{t.dispose()}}applyState(e){this.clearEffects();let t=E(e.data);this.primaryVehicleVisible=t.primaryVehicleVisible,this.primaryVehicleOpacity=t.primaryVehicleOpacity,this.nextHistoryPrune=t.nextHistoryPrune,this.trailClock=t.trailClock,this.quality=t.quality,this.fluidGovernor.restoreLimit(t.fluidQualityLimit),this.vehicleLighting=t.vehicleLighting,this.surfaceTone=t.surfaceTone,this.trail=t.trail,this.pointPuffs=t.pointPuffs,this.showVehicleMarkers=t.showVehicleMarkers,this.tireSmokeEnabled=t.tireSmokeEnabled,this.vehicleShadowsEnabled=t.vehicleShadowsEnabled,this.effectsFadeStartedAt=t.effectsFadeStartedAt,this.wallRects=t.wallRects,this.exhaustBursts=t.exhaustBursts,this.lastFlowCenter=t.lastFlowCenter,this.flowVelocity=t.flowVelocity,this.debugDrive=t.debugDrive,this.previewGroundFire=t.previewGroundFire,this.previewWallSmoke=t.previewWallSmoke,this.previewSparks=t.previewSparks,this.previewDamage=t.previewDamage,this.previewOil=t.previewOil,this.previewOilSplatter=t.previewOilSplatter,this.oilSplatterPreviewSeconds=t.oilSplatterPreviewSeconds,this.sparkPreviewClock=t.sparkPreviewClock,this.damagePreviewApplied=t.damagePreviewApplied,this.groundFirePreviewLit=t.groundFirePreviewLit,this.tourDebug=t.tourDebug,this.trailLifetime=t.trailLifetime,this.fallbackSurfaceTone=t.fallbackSurfaceTone,this.view.restoreState(e.camera),this.diagnostics.restoreState(e.diagnostics),this.vehicles.restoreState(e.vehicles),this.volumetrics.setQuality(this.fluidGovernor.apply(this.quality)),this.volumetrics.restoreState(e.volumetrics),this.combustion.setQuality(this.fluidGovernor.apply(this.quality)),this.combustion.restoreState(e.combustion),this.liquidLayer.restoreState(e.liquids),e.debris&&this.debris.restoreState(e.debris),this.skidTracks.restoreState(e.skidTracks,this.skidView(),this.darkSurface()),this.tireMarks.restoreState(e.tireMarks),this.sparks.restoreState(e.sparks),this.screenShake.restoreState(e.screenShake),this.effectsFadeStartedAt!==null&&(this.effectsFadeStartedAt+=performance.now()-e.at),this.view.rebaseTime(performance.now()),this.ghostVehicles.clearMaterials(),this.view.restorePresentation()}get flamethrowerFiring(){return this.activeVehicles.some(e=>e.weapons.flamethrower.firing)}get managedMemoryGroups(){return[{label:`Tire marks`,bytes:this.skidTracks.managedBytes+this.activeVehicles.reduce((e,t)=>e+t.tirePaint.managedBytes,0)+this.tireMarks.managedBytes},{label:`Smoke`,bytes:this.volumetrics.smokeBytes},{label:`Ghost`,bytes:this.volumetrics.ghostBytes},{label:`Fire`,bytes:this.combustion.managedBytes},{label:`Liquids`,bytes:this.liquidLayer.managedBytes},{label:`Debris`,bytes:this.debris.managedBytes+Uc().bytes},{label:`Tools`,bytes:this.activeVehicles.reduce((e,t)=>e+t.weapons.managedBytes,0)},{label:`Sparks`,bytes:this.sparks.count*112},{label:`Points`,bytes:this.pointPuffs.length*32},{label:`Vehicle trail`,bytes:this.trail.length*48}]}get managedBytes(){return this.managedMemoryGroups.reduce((e,t)=>e+t.bytes,0)}debugDrive=!1;previewGroundFire=!1;previewWallSmoke=!1;previewSparks=!1;previewDamage=!1;previewOil=!1;previewOilSplatter=!1;oilSplatterPreviewSeconds=0;sparkPreviewClock=0;damagePreviewApplied=!1;groundFirePreviewLit=!1;diagnostics=new bl;tourDebug=null;trailLifetime=12;constructor(e,t=!1,n=`high`,r=!1){this.overlay=t,this.canvasWorld=r,this.sparks.setElectricalPalette(zb),this.view=new vl(t,r,()=>this.resize()),this.surface=new yl(e,this.view,t,r),this.combustion=new Xv(this.view,n),this.volumetrics=new Qv(this.view,n),this.electricity=new Gb(this.view),this.liquidLayer=new nb(this.view,n),this.vehicles=new el(this.view),this.quality=n,this.resize()}get pixelSpace(){return this.overlay||this.canvasWorld}prepareFire(){return this.sparks.prepare()?this.combustion.ensure():!1}setQuality(e){if(e===this.quality)return;this.quality=e;let t=this.fluidGovernor.apply(e);this.volumetrics.setQuality(t),this.liquidLayer.setQuality(e),this.combustion.setQuality(t)}applyFluidQuality(){let e=this.fluidGovernor.apply(this.quality);this.volumetrics.setQuality(e),this.combustion.setQuality(e)}setSmokeTint(e){this.volumetrics.setSmokeTint(e)}setTireSmokeEnabled(e){this.tireSmokeEnabled=e}setVehicleShadowsEnabled(e){this.vehicleShadowsEnabled=e}setGhostStyle(e){this.volumetrics.setGhostStyle(e)}setSparksEnabled(e){this.sparks.setEnabled(e)}setScreenShakeEnabled(e){this.screenShake.setEnabled(e)}setScreenShakeProfiles(e){this.screenShake.setProfiles(e)}emitCrashShake(e){if(this.effectsFadeStartedAt!==null)return;let t=gb(e);t&&this.screenShake.trigger(t)}emitRocketExplosionShake(e=1){this.effectsFadeStartedAt===null&&this.screenShake.trigger(`rocketExplosion`,Math.sqrt(Math.max(0,e)))}emitCombustibleExplosion(e,t){if(this.effectsFadeStartedAt!==null)return;this.screenShake.trigger(`combustibleExplosion`);let n=this.particlePoint(this.worldFromDocument(e));this.sparks.emitExplosion(n,D(),this.particleScale(),1.2),this.combustion.queueBlast(n,t*this.particleScale()/Math.max(1,this.documentScale())),this.emitCombustibleBlast(e,t,0)}emitCombustibleBlast(e,t,n){if(this.effectsFadeStartedAt!==null||!this.combustion.activateBuoyancy())return;let r=this.particlePoint(this.worldFromDocument(e)),i=t*this.particleScale()/Math.max(1,this.documentScale()),a=Math.min(1,n/.34);for(let e=0;e<24;e++){let t=e*Math.PI*(3-Math.sqrt(5)),n=D(Math.cos(t),Math.sin(t));this.combustion.queueStamp({point:O(r,A(n,i*a*1.05)),radius:Math.max(4,i*(.29-a*.12)),flow:O(A(n,i*(2.6-a)),D(0,-i*.4)),progress:.28+a*.53,blast:!0})}}emitRocketExplosion(e,t,n=1){if(this.effectsFadeStartedAt!==null)return;let r=this.particlePoint(this.worldFromDocument(e)),i=this.particleVelocity(D(t.x/this.view.zoom,-t.y/this.view.zoom)),a=this.particleScale(),o=Math.sqrt(P(n,.5,2));this.combustion.ensure()&&(this.combustion.queueBlast(r,a*2.2*o),this.combustion.queueStamp({point:r,radius:a*.95*o,flow:D(0,-a*.7),progress:.24,strength:2.6,blast:!0}));for(let t=0;t<64;t++){let n=t*Math.PI*(3-Math.sqrt(5))+Math.atan2(i.y,i.x),s=a*Math.sqrt((t+.5)/64)*1.75*(.83+.17*Math.sin(t*11.8+e.x*.03))*o,c=D(Math.cos(n),Math.sin(n));this.combustion.available&&this.combustion.queueStamp({point:O(r,A(c,s)),radius:a*(.38+t%4*.065)*o,flow:O(A(c,a*2.5),D(0,-a*.5)),progress:.3+t%5*.06,strength:1.7+t%3*.28,blast:!0})}this.sparks.emitExplosion(r,i,a,n),this.sparks.emitFireAt(r,a*.5,.25,14)}setDeformEnabled(e){this.focusVehicle?.damage.setEnabled(e),e||(this.damagePreviewApplied=!1)}resetVehicleDamage(){this.focusVehicle?.damage.reset()}emitSparks(e){this.effectsFadeStartedAt===null&&this.sparks.emit(e)}emitVehicleBurn(e,t,n,r){let i=e.sim,a=this.documentScale(),o=O(this.documentPoint(i.body.position),this.carVisualOffset(i)),s=n.lengthM*a,c=n.widthM*a,l=D(Math.cos(i.body.angle),-Math.sin(i.body.angle)),u=D(-l.y,l.x),d=O(o,O(A(l,t.burnOriginLocal.x*a),A(u,t.burnOriginLocal.y*a))),f=this.combustion.alphaFor(n.alpha.solid);if(t.stage===`exploded`)return t.explosionStarted&&this.emitCombustibleExplosion(o,Math.max(78,s*.7)),t.blastAge<Tt.fireballSeconds&&this.emitSceneFire({key:t.key,alpha:f,pixelWidth:n.alpha.columns,pixelHeight:n.alpha.rows,x:o.x-s/2,y:o.y-c/2,width:s,height:c,angle:-i.body.angle,origin:o,farthest:Math.hypot(s,c),...Pt(t.blastAge)},r),t.blastPulse&&this.emitCombustibleBlast(o,Math.max(78,s*.7),t.blastAge),t.explosionStarted?o:null;let p=Nt(t.health,t.maxHealth,s,c);return p&&this.emitSceneFire({key:t.key,alpha:f,pixelWidth:n.alpha.columns,pixelHeight:n.alpha.rows,x:o.x-s/2,y:o.y-c/2,width:s,height:c,angle:-i.body.angle,origin:d,farthest:Math.hypot(s,c),...p},r),null}sceneFireDue(e){return this.effectsFadeStartedAt===null&&this.combustion.sceneMasksDue(e)}emitSceneFire(e,t=1/60){this.effectsFadeStartedAt===null&&this.combustion.queueMask(e)}pourWorldLiquid(e,t,n,r,i){this.liquidLayer.pourWorldLiquid(e,t,n,r,i)}emitPaint(e,t,n,r,i){this.liquidLayer.emitPaint(e,t,n,r,i)}hasConductiveLiquidNear(e,t){return this.liquidLayer.hasConductiveCandidate(e,t)}conductLightning(e,t=0){return this.liquidLayer.conductLightning(e,t)}igniteLiquidAt(e,t){this.liquidLayer.igniteAt(e,t)}igniteConductedLiquids(e,t){this.liquidLayer.igniteConducted(e,t)}igniteLiquidsFromFire(e){this.liquidLayer.igniteFromFire(e)}burningLiquidSources(){return this.liquidLayer.burningSources()}hasLiquidContact(e,t){return this.liquidLayer.hasContact(e,t)}addLiquid(e,t){this.liquidLayer.add(e,t)}syncElementLiquids(e){return this.liquidLayer.syncElements(e)}ejectLiquid(e,t=`oil`,n){this.liquidLayer.pourVehicle(e,t,.65,n)}setInitialPuddles(e){this.liquidLayer.setInitialPuddles(e)}setSurfaceTone(e){this.surfaceTone=e}fallbackSurfaceTone={at:-1/0,dark:!1};darkSurface(){if(this.surfaceTone!==`auto`)return this.surfaceTone===`dark`;let e=document.documentElement.dataset.jrTheme;if(e===`light`||e===`dark`)return e===`dark`;let t=performance.now();if(t-this.fallbackSurfaceTone.at<80)return this.fallbackSurfaceTone.dark;let n=getComputedStyle(document.body).backgroundColor,r=Al(/rgba\([^)]*,\s*0(?:\.0+)?\s*\)/.test(n)||n===`transparent`?getComputedStyle(document.documentElement).backgroundColor:n);return this.fallbackSurfaceTone={at:t,dark:r},r}setDebugEnabled(e){this.debugDrive=e||!1}setTourDebugRoute(e,t=[]){this.tourDebug=e?{route:e,stops:t}:null}fadeEffects(){if(this.effectsFadeStartedAt!==null)return;this.effectsFadeStartedAt=performance.now(),this.volumetrics.clearSmokeSources();let e=this.activeVehicles.length?this.activeVehicles:this.focusVehicle?[this.focusVehicle]:[];for(let t of e)t.weapons.reset(),t.tirePaint.reset(),t.damage.reset();this.screenShake.reset(),this.electricity.reset(),this.skidTracks.fade(),this.combustion.clearTireHistory(),this.exhaustBursts=[]}clearEffects(){this.debris.reset(),this.electricity.reset(),this.objectGlint?.dispose(),this.objectGlint=null,this.trail=[],this.skidTracks.clear(),this.volumetrics.reset(),this.pointPuffs=[];for(let e of this.activeVehicles.length?this.activeVehicles:this.focusVehicle?[this.focusVehicle]:[])e.weapons.rocket.reset(),e.weapons.machineGuns.reset(),e.weapons.flamethrower.reset();this.screenShake.reset(),this.combustion.reset(),this.exhaustBursts=[],this.sparks.reset(),this.liquidLayer.clearEffects(),this.tireMarks.clear(),this.lastFlowCenter=null,this.flowVelocity=D(),this.trailClock=0,this.effectsFadeStartedAt=null}reset(){this.view.reset(),this.clearEffects(),this.liquidLayer.restoreInitialPuddles(),this.wallRects=[],this.groundFirePreviewLit=!1,this.sparkPreviewClock=0,this.damagePreviewApplied=!1,this.vehicles.reset(),this.tourDebug=null,this.surface.clear(),this.view.resetFollow()}dispose(){this.liquidLayer.dispose(),this.debris.clear(),this.electricity.dispose(),this.objectGlint?.dispose(),this.surface.dispose(),this.view.dispose(),this.skidTracks.clear(),this.tireMarks.clear(),this.volumetrics.dispose(),this.combustion.dispose(),this.sparks.dispose()}resize(){let e=this.surface.resize();this.liquidLayer.resize(),this.volumetrics.resize(e),this.combustion.resize(e)}rasterPixelRatio(){return this.canvasWorld?Math.min(2,Math.round(this.view.dpr/this.view.regionScale*100)/100):this.view.dpr}setShowVehicleMarkers(e){this.showVehicleMarkers=e}flashTargets(e){this.resize(),this.objectGlint??=new Sb;let t=this.sceneScroll();this.objectGlint.trigger(this.view.width,this.view.height,this.view.dpr,n=>e(n,t))}particlePoint(e){return this.view.particlePoint(e)}particleScreen(e){return this.pixelSpace?k(e,this.sceneScroll()):this.screen(e)}particleVelocity(e){return this.pixelSpace?D(e.x*this.view.zoom,-e.y*this.view.zoom):{...e}}particleScale(){return this.view.particleScale()}emitPoints(e,t){t<=0||this.pointPuffs.push({point:this.particlePoint(this.worldFromDocument(e)),amount:t,age:0})}fluidView(){let e=this.sceneScroll();return this.pixelSpace?{origin:D(this.view.smokeMargin-e.x,this.view.smokeMargin-e.y),scaleX:1,scaleY:1}:{origin:D(this.view.width/2-this.view.camera.x*this.view.zoom,this.view.height/2+this.view.camera.y*this.view.zoom),scaleX:this.view.zoom,scaleY:-this.view.zoom}}flameView(){let e=this.fluidView();return this.pixelSpace?{...e,origin:D(e.origin.x-this.view.smokeMargin,e.origin.y-this.view.smokeMargin)}:e}clipFluidWalls(e){if(!this.overlay)return;let t=this.sceneScroll();for(let n of this.wallRects){let r=n.x-t.x,i=n.y-t.y;n.width<=0||n.height<=0||r>=this.view.width||i>=this.view.height||r+n.width<=0||i+n.height<=0||(e.beginPath(),e.rect(0,0,this.view.width,this.view.height),e.rect(r,i,n.width,n.height),e.clip(`evenodd`))}}stepVehicleWeapons(e,t,n,r,i,a,o,s,c){let l=e.sim;performance.now(),e.weapons.rocket.step(t,l,e=>{this.effectsFadeStartedAt===null&&this.volumetrics.emitSmoke({point:this.particlePoint(e.point),amount:e.amount,flow:this.particleVelocity(e.flow),radiusPx:e.radiusM*this.view.zoom,swirlPx:10})},n?(t,r,i)=>{let a=n(e,this.documentPoint(t),this.documentPoint(r),i*this.documentScale());return a?this.worldFromDocument(a):null}:void 0,e=>{this.effectsFadeStartedAt===null&&this.combustion.emitJet(e.from,e.to,e.flow,e.widthM,e.intensity,`rocket`)},o,s,void 0),e.weapons.machineGuns.step(t,l,r?(t,n,i)=>{let a=r(e,this.documentPoint(t),this.documentPoint(n),i*this.documentScale());return a?this.worldFromDocument(a):null}:void 0,i,(e,t)=>{this.effectsFadeStartedAt===null&&this.sparks.emitBulletImpact(this.particlePoint(e),this.particleVelocity(t)),c?.(e)}),e.weapons.flamethrower.step(t,l,e=>{this.effectsFadeStartedAt===null&&this.volumetrics.emitSmoke({point:this.particlePoint(e.point),amount:e.amount,flow:this.particleVelocity(e.flow),radiusPx:e.radiusM*this.view.zoom,swirlPx:10})},a?(t,n,r,i)=>{let o=a(e,this.documentPoint(t),this.documentPoint(n),r*this.documentScale(),i);return o?this.worldFromDocument(o):null}:void 0,(e,n,r,i,a)=>{if(this.effectsFadeStartedAt!==null)return;let o=this.particleScale();this.liquidLayer.igniteAlong(this.particlePoint(e),this.particlePoint(n),r*o*.5),a>.3&&this.sparks.emitFireAt(this.particlePoint(n),r*o*.4,t,3),this.combustion.queueStamp({point:this.particlePoint(n),radius:r*o,progress:a,flow:this.particleVelocity(i)})})}sprayTirePaint(e,t,n,r,i,a,o,s){this.liquidLayer.splatter(e,t,n,r,i,a,o,s)}advanceEffects(e,t,{walls:n=[],carMask:r,tirePaintSources:i=[],driven:a=!0,rocketCollision:o,bulletCollision:s,onGunshot:c,flameContact:l,onRocketLaunch:u,onRocketImpact:d,onBulletImpact:f,maskFor:p,companions:m=[]}={}){for(let e of this.pointPuffs)e.age+=t;this.pointPuffs=this.pointPuffs.filter(e=>e.age<.9),this.activeVehicles=[e,...m];let h=this.sceneScroll();this.debris.count&&this.debris.step(t,this.activeVehicles.filter(e=>e.sim.mode===`car`&&!e.isGhost&&e.sim.car.explodedAt===null).map(e=>{let t=this.particlePoint(e.sim.body.position),n=this.particleVelocity(e.sim.body.velocity),r=this.particleScale();return{x:t.x,y:t.y,vx:n.x,vy:n.y,angle:-e.sim.body.angle,length:e.sim.car.preset.geometry.lengthM*r,width:e.sim.car.preset.geometry.widthM*r}}),{x:h.x,y:h.y,width:this.view.width,height:this.view.height},n),this.volumetrics.stepGhost(t,this.activeVehicles,n,p,this.flameView(),e=>this.carVisualOffset(e.sim));let g=e.sim;if(this.wallRects=n,this.vehicles.updateCarPose(g,t),this.effectsFadeStartedAt===null){for(let e of this.activeVehicles)for(let n of e.liquidEmissions(t))this.liquidLayer.pourVehicle(e.sim,ot(n.liquid),n.amount,void 0,e.id);this.previewOil&&!this.previewOilSplatter&&this.liquidLayer.pourVehicle(g,`oil`,t*6)}for(let n of[e,...m])this.stepVehicleWeapons(n,t,o,s,c,l,u,d,f);let{tires:_,companionTires:v}=this.liquidLayer.stepVehicles(e,m,t,a,i,this.effectsFadeStartedAt!==null,(e,t)=>this.emitSceneFire(e,t)),y=this.documentScale(),b=D(Math.cos(g.body.angle),-Math.sin(g.body.angle)),x=g.mode===`car`&&r&&!e.isGhost?{mask:r.alpha,shape:{center:O(this.documentPoint(g.body.position),this.carVisualOffset(g)),forward:b,side:D(-b.y,b.x),halfLength:r.lengthM*y/2,halfWidth:r.widthM*y/2}}:void 0;if(this.previewDamage&&!this.damagePreviewApplied&&x&&(this.damagePreviewApplied=e.damage.hit(O(x.shape.center,A(x.shape.forward,x.shape.halfLength)),A(x.shape.forward,-1),x.shape,20,y)),this.electricity.step(e,m,t,this.sparks,this.screenShake),performance.now(),g.mode===`car`&&M(g.body.velocity)>.15&&this.sparks.disturb(this.particlePoint(g.body.position),this.particleVelocity(g.body.velocity),this.particleScale()*2.8),this.sparks.step(t,{walls:n,car:x}),this.previewSparks&&g.mode===`car`&&(this.sparkPreviewClock+=t,this.sparkPreviewClock>.12)){this.sparkPreviewClock=0;let e=this.particlePoint(g.body.position),t=this.particleScale();this.emitSparks({point:O(e,D(t*1.9,0)),velocity:D(t*4,t*10),normal:D(-1,0),pixelsPerMeter:t})}let S=this.particleScale(),C=this.particlePoint(g.body.position),w=this.lastFlowCenter?A(k(C,this.lastFlowCenter),1/Math.max(t,1e-4)):this.particleVelocity(g.body.velocity),ee=M(w),te=ee>40*S?A(w,40*S/ee):w;this.flowVelocity=O(this.flowVelocity,A(k(te,this.flowVelocity),1-Math.exp(-12*t))),this.lastFlowCenter=C;let ne=this.pixelSpace?this.flowVelocity:D(this.flowVelocity.x*this.view.zoom,-this.flowVelocity.y*this.view.zoom),re=D(Math.cos(g.body.angle),-Math.sin(g.body.angle)),ie=g.mode===`car`?{center:O(this.screen(g.body.position),D(this.view.smokeMargin,this.view.smokeMargin)),velocity:ne,forward:re,halfLength:g.car.preset.geometry.lengthM*this.view.zoom*.46,halfWidth:g.car.preset.geometry.widthM*this.view.zoom*.39,spin:-g.body.spin}:null;if(this.effectsFadeStartedAt!==null){this.volumetrics.clearSmokeSources(),this.combustion.stepTire(t),this.combustion.step(t,this.view.timeSeconds,e.isGhost?null:ie,this.wallRects,!0,this.flameView(),this.sparks),this.volumetrics.stepSmoke(t,ie,this.wallRects,this.fluidView());return}if(this.previewWallSmoke&&this.overlay){let e=this.sceneScroll(),n=this.wallRects.filter(t=>t.x-e.x>48&&t.x-e.x<this.view.width-48&&t.y+t.height/2-e.y>30&&t.y+t.height/2-e.y<this.view.height-30),r=n.find(t=>t.x-e.x>this.view.width*.5)??n[0];r&&this.volumetrics.emitSmoke({point:D(r.x-25,r.y+r.height/2),amount:t*15,flow:D(210,0),radiusPx:17,swirlPx:25})}if(performance.now(),this.combustion.stepTire(t),this.combustion.step(t,this.view.timeSeconds,e.isGhost?null:ie,this.wallRects,!1,this.flameView(),this.sparks),!this.pixelSpace){for(let e of this.trail)e.age+=t;if(this.trail=this.trail.filter(e=>e.age<this.trailLifetime),this.trailClock+=t,this.trailLifetime>0&&this.trailClock>=1/30){this.trailClock%=1/30;let e=this.trail.at(-1);(!e||M(k(e.point,g.body.position))>.04)&&this.trail.push({point:{...g.body.position},age:0,color:g.mode===`ship`?`#9bbcff`:g.mode===`brick`?`#f6bd79`:`#8ce6c5`}),this.trail.length>800&&this.trail.shift()}}if(g.mode!==`car`){this.volumetrics.stepSmoke(t,null,this.wallRects,this.fluidView()),this.skidTracks.stop(this.skidView(),this.darkSurface(),!0),this.combustion.clearTireHistory();return}if(e.isGhost){this.volumetrics.stepSmoke(t,null,this.wallRects,this.fluidView()),this.skidTracks.stop(this.skidView(),this.darkSurface()),this.combustion.clearTireHistory();return}let ae=this.advanceVehicleTireEffects(e,t,_,v,ne),oe=this.combustion.emberSource();oe&&this.sparks.emitFireAt(oe.point,oe.radius,t,20*oe.heat),performance.now(),this.volumetrics.stepSmoke(t,ie,this.wallRects,this.fluidView());let se=this.darkSurface();this.skidTracks.step(t,g,ae,t=>!!e.tirePaint.coating(t),{pixelSpace:this.pixelSpace,scale:this.particleScale(),dark:se,project:e=>this.particlePoint(e),roadAt:(e,t)=>!!this.overlay&&this.surfaceTones.at(e,this.viewportFromDocument(t),se),view:this.skidView()})}advanceVehicleTireEffects(e,t,n,r,i){let a=e.sim,o=this.particleScale();if(this.previewGroundFire&&!this.groundFirePreviewLit){for(let e of a.car.tires.filter(e=>!e.front)){let t=a.body.world(e.local);this.combustion.igniteTire(this.particlePoint(a.body.world(O(e.local,D(-2.4)))),this.particlePoint(t),a.car.preset.geometry.tireWidthM*o,18,.2*o)}this.groundFirePreviewLit=!0}let s=M(a.body.velocity),c=s>.1?A(a.body.velocity,-1/s):N(D(-1),a.body.angle);this.previewOilSplatter&&(s>.5?this.oilSplatterPreviewSeconds=0:s<.2&&(this.oilSplatterPreviewSeconds+=t),this.oilSplatterPreviewSeconds<2.25&&this.liquidLayer.pourOilPreview(n[0].point,t));let l={zoom:this.view.zoom,particlePoint:e=>this.particlePoint(e),particleVelocity:e=>this.particleVelocity(e),spray:(...e)=>this.sprayTirePaint(...e),smoke:this.tireSmokeEnabled?e=>this.volumetrics.emitSmoke(e):void 0};xb(e,n,0,t,c,i,l,this.previewOilSplatter&&s<.2&&this.oilSplatterPreviewSeconds>1&&this.oilSplatterPreviewSeconds<2.25);let u=n.length;for(let{vehicle:e,tires:n}of r){if(!e.isGhost){let r=e.sim,i=M(r.body.velocity),a=i>.1?A(r.body.velocity,-1/i):N(D(-1),r.body.angle);xb(e,n,u,t,a,this.particleVelocity(r.body.velocity),l)}u+=n.length}(e.isGhost||a.car.preset.sound.electric)&&(this.exhaustBursts=[]);for(let e of this.exhaustBursts){e.age+=t;let n=e.intensity*Math.max(0,1-e.age/e.lifetime);if(n<=0)continue;let r=N(D(-1,0),a.body.angle),i=O(A(r,4+5*n),A(a.body.velocity,.12));for(let e of this.vehicles.exhaustOutlets(a)){let o=a.body.world(e);if(this.combustion.emitJet(o,o,i,.13,n*.8,`exhaust`),n>.55){let e=O(o,A(r,1.45));this.volumetrics.emitSmoke({point:this.particlePoint(e),amount:t*n*.2,flow:this.particleVelocity(A(i,.48)),radiusPx:.13*this.particleScale(),swirlPx:7})}}}this.exhaustBursts=this.exhaustBursts.filter(e=>e.age<e.lifetime);let d=a.car.boostActive&&!e.isGhost;return d?this.combustion.stepBoostFire(a,t,e=>this.liquidLayer.igniteAtLocal(e)):this.combustion.clearTireHistory(),d}skidView(){return{pixelSpace:this.pixelSpace,zoom:this.view.zoom,width:this.view.width,height:this.view.height,screen:e=>this.particleScreen(e)}}vehicleLightInput(e,t,n){let r=tt(e.sim.car.preset),i=e=>[-1,1].map(t=>D(e.xM*this.view.zoom,t*e.yM*this.view.zoom)),a=e.sim,o=this.vehicles.imageFor(a.car.preset)??void 0,s=o?Kt(a.car.preset,o.naturalWidth,o.naturalHeight):null,c=a.body.velocity.x*Math.cos(a.body.angle)+a.body.velocity.y*Math.sin(a.body.angle),l=a.lastInput,u=Math.max(l.brake??0,+!!l.action,+(l.throttle<0&&c>.5||l.throttle>0&&c<-.5));return{center:O(this.screen(a.body.position),this.carVisualOffset(a)),angle:-a.body.angle,width:(s?.lengthM??a.car.preset.geometry.lengthM)*this.view.zoom,height:(s?.widthM??a.car.preset.geometry.widthM)*this.view.zoom,mounts:{headlights:i(r.headlights),taillights:i(r.taillights)},image:o,source:s?.source,dark:e.appearance===`auto`?this.overlay?this.surfaceTones.at(e,this.viewportFromDocument(this.documentPoint(a.body.position)),t):t:e.appearance===`dark`,braking:u,options:this.vehicleLighting,opacity:n}}drawVehicleAndWeapons(e,t,n){performance.now();let r=e.sim,{rocket:i,machineGuns:a,flamethrower:o}=e.weapons,s=this.ctx;if(e.isGhost){this.ghostVehicles.draw(e,s,{imageFor:e=>this.vehicles.imageFor(e),screen:e=>this.screen(e),visualOffset:e=>this.carVisualOffset(e),zoom:this.view.zoom,width:this.view.width,height:this.view.height,pixelSpace:this.pixelSpace,walls:this.wallRects,scroll:this.sceneScroll(),dark:this.darkSurface(),styleName:this.volumetrics.style}),i.drawFlight(s,e=>this.screen(e),r.car.preset,this.view.zoom,t),a.drawProjectiles(s,e=>this.screen(e),this.view.zoom,t);return}let c=this.carVisualOffset(r);if(s.save(),s.translate(c.x,c.y),r.car.explodedAt===null){this.vehicles.car(this.ctx,r.body,r,e.damage,Math.max(o.openAmount,a.openAmount));let i=n??this.vehicleLightInput(e,this.darkSurface(),t);this.vehicleLights.glints(s,{...i,center:this.screen(r.body.position)})}let l;if(i.state!==`idle`||o.state!==`closed`||a.state!==`closed`){let t=this.vehicles.imageFor(r.car.preset);if(t){let n=Kt(r.car.preset,t.naturalWidth,t.naturalHeight),i=e.damage.spriteFor(t,n);l={image:i??t,source:i?{x:0,y:0,width:i.width,height:i.height}:n.source,lengthM:n.lengthM,widthM:n.widthM}}}r.car.explodedAt===null&&i.drawMount(s,this.screen(r.body.position),r.body.angle,r.car.preset,this.view.zoom,t,l),r.car.explodedAt===null&&o.state!==`closed`?o.drawMount(s,this.screen(r.body.position),r.body.angle,r.car.preset,this.view.zoom,t,l):r.car.explodedAt===null&&a.drawMount(s,this.screen(r.body.position),r.body.angle,r.car.preset,this.view.zoom,t,l),s.restore(),s.save(),this.clipFluidWalls(s),s.translate(c.x,c.y),r.car.explodedAt===null&&this.vehicles.exhaust(this.ctx,r),s.restore(),i.drawFlight(s,e=>this.screen(e),r.car.preset,this.view.zoom,t),a.drawProjectiles(s,e=>this.screen(e),this.view.zoom,t)}drawGroundLayers(e,t,n,r){let i=t.sim;if(!this.pixelSpace){let{left:e,right:t,bottom:n,top:r}=this.bounds();for(let i=Math.floor(e/5)*5;i<=t;i+=5)this.vehicles.line(this.ctx,D(i,n),D(i,r),`#293c46`);for(let i=Math.floor(n/5)*5;i<=r;i+=5)this.vehicles.line(this.ctx,D(e,i),D(t,i),`#293c46`)}for(let t of this.trail){let n=this.screen(t.point),i=1-t.age/this.trailLifetime;e.globalAlpha=.6*i*i*r,e.fillStyle=t.color,e.beginPath(),e.arc(n.x,n.y,.8+1.4*i,0,Math.PI*2),e.fill()}e.globalAlpha=1,e.save(),e.lineCap=`round`,e.lineJoin=`round`;let a=this.sceneScroll(),o=this.pixelSpace?{left:a.x,right:a.x+this.view.width,bottom:a.y,top:a.y+this.view.height}:{left:this.world(D(0,0)).x,right:this.world(D(this.view.width,0)).x,bottom:this.world(D(0,this.view.height)).y,top:this.world(D(0,0)).y},s=this.darkSurface();performance.now(),this.skidTracks.draw(e,{pixelSpace:this.pixelSpace,scroll:a,width:this.view.width,height:this.view.height,ratio:this.rasterPixelRatio(),dark:s,alpha:r,visible:o,view:this.skidView()}),performance.now();let c={pixelSpace:this.pixelSpace,scroll:a,width:this.view.width,height:this.view.height,particleScale:this.particleScale(),rasterRatio:this.rasterPixelRatio(),zoom:this.view.zoom,effectsAlpha:r,screen:e=>this.particleScreen(e)};return this.tireMarks.draw(e,[t,...n],!1,c),e.restore(),this.liquidLayer.draw(e,r),performance.now(),this.tireMarks.draw(e,[t,...n],!0,c),i.barrier&&!this.overlay&&(e.strokeStyle=`#d4ab71`,e.lineWidth=2,e.strokeRect(3,3,this.view.width-6,this.view.height-6)),{scroll:a,darkSurface:s}}render(e,t,n,r,i=[]){let a=e.sim;performance.now(),this.resize();let o=yb(this.effectsFadeStartedAt,t);if(this.effectsFadeStartedAt!==null&&o===0&&(this.clearEffects(),this.liquidLayer.restoreInitialPuddles(),o=0),this.view.cameraStep(a,t),this.canvasWorld&&t>=this.nextHistoryPrune){this.nextHistoryPrune=t+2e3;let e=this.documentPoint(a.body.position),n=2800,r={x:e.x-n,y:e.y-n,width:n*2,height:n*2};this.skidTracks.pruneOutside(r),this.tireMarks.pruneOutside(r),this.liquidLayer.pruneOutside(r)}let s=this.ctx;this.surface.clear();let c=this.screenShake.sample(t);s.save(),(c.x||c.y)&&s.translate(c.x,c.y),r?.drawGround?.(s,this.sceneScroll(),{width:this.view.width,height:this.view.height});let{scroll:l,darkSurface:u}=this.drawGroundLayers(s,e,i,o),d=new Map((this.primaryVehicleVisible?[e,...i]:i).filter(e=>e.sim.mode===`car`&&e.sim.car.explodedAt===null&&!e.isGhost).map(t=>[t,this.vehicleLightInput(t,u,o*(t===e?this.primaryVehicleOpacity:1))])),f=[...d.values()].flatMap(e=>this.vehicleLights.smokeLights(e)),p=f.map(e=>({...e,point:{x:e.point.x+l.x,y:e.point.y+l.y}}));this.pixelSpace&&(s.save(),s.translate(-l.x,-l.y),qc(s,this.debris.particles,{x:l.x,y:l.y,width:this.view.width,height:this.view.height},u,`ground`,p),s.restore());for(let t of this.primaryVehicleVisible?[e,...i]:i)t.sim.mode!==`car`||t.sim.car.explodedAt!==null||t.isGhost||t===e&&this.primaryVehicleOpacity<=0||(s.save(),t===e&&(s.globalAlpha*=this.primaryVehicleOpacity),this.vehicles.carGround(this.ctx,t.sim,t.damage,this.rasterPixelRatio(),this.vehicleShadowsEnabled),s.restore());for(let e of d.values())this.vehicleLights.ground(s,e);if(s.save(),performance.now(),this.clipFluidWalls(s),s.globalAlpha=o,s.save(),s.translate(-this.view.smokeMargin,-this.view.smokeMargin),this.volumetrics.drawSmoke(s,this.fluidView(),f.map(e=>({...e,point:O(e.point,D(this.view.smokeMargin,this.view.smokeMargin))})),u),s.restore(),s.restore(),s.globalAlpha=1,r?.draw(s,l,{width:this.view.width,height:this.view.height}),this.debugDrive&&a.mode===`car`&&a.car.explodedAt===null&&!e.isGhost){let e=this.screen(a.body.position);s.save(),s.beginPath(),s.arc(e.x,e.y,Mn(a.car.preset,this.view.width,this.documentScale())*this.view.zoom,0,Math.PI*2),s.strokeStyle=u?`#92cfff88`:`#12528e88`,s.lineWidth=1,s.setLineDash([5,6]),s.stroke(),s.fillStyle=u?`#b7ddff`:`#12528e`,s.font=`10px ui-monospace, monospace`,s.fillText(`Lightning influence`,e.x+8,e.y-Mn(a.car.preset,this.view.width,this.documentScale())*this.view.zoom+14),s.restore()}this.volumetrics.ghostAvailable&&(s.save(),s.globalAlpha=o,this.volumetrics.drawGhost(s,this.flameView(),u),s.restore()),this.overlay&&this.debugDrive&&this.tourDebug&&vb(s,this.tourDebug.route,this.tourDebug.stops,{x:l.x,y:l.y,width:this.view.width,height:this.view.height}),this.primaryVehicleVisible&&a.mode===`car`&&(s.save(),s.globalAlpha*=this.primaryVehicleOpacity,this.drawVehicleAndWeapons(e,o,d.get(e)),s.restore(),this.debugDrive&&(r?.drawDebug?.(s,a,this,e.damage),this.diagnostics.draw(s,a,t,e=>this.screen(e),{width:this.view.width,rocketState:e.weapons.rocket.state,gunState:e.weapons.machineGuns.state,bulletCount:e.weapons.machineGuns.projectileCount,fluidEngine:this.volumetrics.smokeResolution.engine,quality:this.quality,fluidCols:this.volumetrics.smokeResolution.cols,fluidRows:this.volumetrics.smokeResolution.rows,fireCols:this.combustion.resolution?.cols??0,fireRows:this.combustion.resolution?.rows??0,groundedFireCount:this.combustion.count}))),this.primaryVehicleVisible&&a.mode===`ship`&&this.vehicles.ship(this.ctx,a.body,a),this.primaryVehicleVisible&&a.mode===`brick`&&this.vehicles.brick(this.ctx,a.body);for(let e of i){let t=e.sim;if(t.mode!==`car`||(this.drawVehicleAndWeapons(e,o,d.get(e)),t.car.explodedAt!==null))continue;let n=this.screen(t.body.position);s.save(),s.font=`600 10px ui-monospace, monospace`,s.textAlign=`center`;let r=e.label||`AI`,i=Math.max(30,Math.ceil(s.measureText(r).width)+14);s.fillStyle=`rgba(24, 27, 30, 0.88)`,s.fillRect(n.x-i/2,n.y-37,i,16),s.fillStyle=`#f5f2ec`,s.fillText(r,n.x,n.y-25),s.restore()}if(this.pixelSpace&&(s.save(),s.translate(-l.x,-l.y),qc(s,this.debris.particles,{x:l.x,y:l.y,width:this.view.width,height:this.view.height},u,`air`,p),s.restore()),s.save(),this.clipFluidWalls(s),performance.now(),this.combustion.draw(s,this.flameView(),u,f),s.restore(),this.electricity.draw(s,t,u,o),performance.now(),this.sparks.draw(s,e=>this.particleScreen(e),o,{width:this.view.width,height:this.view.height},this.view.dpr,this.canvasWorld?void 0:this.surface.canvas),this.pointPuffs.length){s.save(),s.font=`700 13px ui-monospace, monospace`,s.textAlign=`center`,s.textBaseline=`middle`;for(let e of this.pointPuffs){let t=this.particleScreen(e.point),n=e.age/.9;s.globalAlpha=(1-n)*o,s.fillStyle=`#f8f4e9`,s.strokeStyle=`rgba(22, 24, 26, 0.85)`,s.lineWidth=3;let r=`+${e.amount}`,i=t.y-16-n*26;s.strokeText(r,t.x,i),s.fillText(r,t.x,i)}s.restore()}if(r?.drawForeground?.(s,l,{width:this.view.width,height:this.view.height}),performance.now(),r?.drawHealthBars?.(s,l,{width:this.view.width,height:this.view.height},e,this,i),n){let e=this.screen(n.from),t=this.screen(n.to);s.strokeStyle=`#ffdf93`,s.lineWidth=2,s.beginPath(),s.moveTo(e.x,e.y),s.lineTo(t.x,t.y),s.stroke()}s.restore(),this.objectGlint?.draw(s,this.view.width,this.view.height,this.darkSurface()),this.vehicles.drawVehicleMarkers(this.ctx,this.primaryVehicleVisible?[e,...i]:i,this.showVehicleMarkers,e),this.surface.presentLockedCamera(),this.liquidLayer.drawTextVehicles([e,...i].filter(t=>(t!==e||this.primaryVehicleVisible)&&t.sim.mode===`car`&&!t.isGhost&&t.sim.car.explodedAt===null).map(e=>({point:this.screen(e.sim.body.position),radius:Math.hypot(e.sim.car.preset.geometry.lengthM,e.sim.car.preset.geometry.widthM)*this.view.zoom/2+12})),c,t=>{for(let n of[e,...i]){if(n===e&&!this.primaryVehicleVisible||n.sim.mode!==`car`||n.isGhost||n.sim.car.explodedAt!==null)continue;let r=this.carVisualOffset(n.sim);t.save(),t.translate(r.x,r.y),this.vehicles.car(t,n.sim.body,n.sim,n.damage,Math.max(n.weapons.flamethrower.openAmount,n.weapons.machineGuns.openAmount)),t.restore()}}),this.governFluidQuality(t)}governFluidQuality(e){let t=performance.now()-e;if(!(t>=0&&t<1e3))return;let n=this.volumetrics.running||this.combustion.running;this.fluidGovernor.sample(e,t,n,this.quality)&&(`${this.fluidGovernor.limit}`,this.applyFluidQuality())}},qb=343,Jb={vtwin:{label:`V-twin 90° 1.2`,cylinders:2,firingOrder:[1,2],banks:[[1],[2]],pinOffsets:{2:-90},idleRpm:1150,redlineRpm:9500,peakTorque:125,peakTorqueRpm:8e3,gears:6,engineInertia:.055,gasTempFactor:1.34,pulse:{attack:40,decay:6.5,hardness:.72,jitter:2},exhaust:{bank:.95,bankB:1.1,collector:.55,reflection:.5,damping:.34,muffler:[.16,.11,.075]},intake:{helmholtz:165,q:6,level:.4},voice:.92},i3:{label:`Inline-3 1.0`,cylinders:3,firingOrder:[1,2,3],banks:[[1,2,3]],idleRpm:850,redlineRpm:6500,peakTorque:200,peakTorqueRpm:2200,gears:5,engineInertia:.16,gasTempFactor:1.3,pulse:{attack:34,decay:5.5,hardness:.62,jitter:1.6},exhaust:{bank:1.45,collector:1.1,reflection:.55,damping:.42,muffler:[.32,.21,.14]},intake:{helmholtz:105,q:5.5,level:.34},voice:1},rotary2:{label:`Rotary 1.3 twin-rotor`,cylinders:4,firingOrder:[1,2,3,4],banks:[[1,2,3,4]],idleRpm:900,redlineRpm:9e3,peakTorque:220,peakTorqueRpm:5500,gears:5,engineInertia:.14,gasTempFactor:1.4,pulse:{attack:18,decay:3,hardness:.7,jitter:1.2},exhaust:{bank:1.05,collector:.8,reflection:.52,damping:.3,muffler:[.2,.13,.09]},intake:{helmholtz:145,q:6.6,level:.46},voice:.94},i4:{label:`Inline-4 2.0`,cylinders:4,firingOrder:[1,3,4,2],banks:[[1,2,3,4]],idleRpm:800,redlineRpm:7200,peakTorque:240,peakTorqueRpm:3900,gears:6,engineInertia:.19,gasTempFactor:1.28,pulse:{attack:38,decay:6.2,hardness:.66,jitter:1.1},exhaust:{bank:1.3,collector:1.05,reflection:.52,damping:.44,muffler:[.3,.19,.12]},intake:{helmholtz:118,q:6,level:.32},voice:.96},boxer4:{label:`Flat-4 boxer (unequal headers)`,cylinders:4,firingOrder:[1,3,2,4],banks:[[1,3],[2,4]],pinOffsets:{3:6,4:-6},idleRpm:800,redlineRpm:6800,peakTorque:300,peakTorqueRpm:3200,gears:6,engineInertia:.2,gasTempFactor:1.27,pulse:{attack:32,decay:5.4,hardness:.6,jitter:2.2},exhaust:{bank:1.62,bankB:.98,collector:1.15,reflection:.58,damping:.4,muffler:[.34,.22,.15]},intake:{helmholtz:100,q:5.2,level:.36},voice:1},i5:{label:`Inline-5 2.5`,cylinders:5,firingOrder:[1,2,4,5,3],banks:[[1,2,3,4,5]],idleRpm:820,redlineRpm:7e3,peakTorque:360,peakTorqueRpm:3200,gears:6,engineInertia:.24,gasTempFactor:1.29,pulse:{attack:33,decay:5.6,hardness:.64,jitter:1.5},exhaust:{bank:1.38,collector:1.08,reflection:.56,damping:.41,muffler:[.31,.2,.13]},intake:{helmholtz:108,q:5.6,level:.34},voice:1},i6:{label:`Inline-6 3.0`,cylinders:6,firingOrder:[1,5,3,6,2,4],banks:[[1,2,3,4,5,6]],idleRpm:750,redlineRpm:7e3,peakTorque:420,peakTorqueRpm:3e3,gears:7,engineInertia:.27,gasTempFactor:1.28,pulse:{attack:30,decay:5,hardness:.58,jitter:.7},exhaust:{bank:1.55,collector:1.2,reflection:.54,damping:.38,muffler:[.33,.21,.14]},intake:{helmholtz:95,q:6.4,level:.33},voice:.98},i6diesel:{label:`Inline-6 diesel 6.7`,cylinders:6,firingOrder:[1,5,3,6,2,4],banks:[[1,2,3,4,5,6]],idleRpm:640,redlineRpm:4600,peakTorque:950,peakTorqueRpm:1900,gears:8,engineInertia:.62,gasTempFactor:1.16,pulse:{attack:68,decay:9.5,hardness:.88,jitter:1.4},exhaust:{bank:1.35,collector:1.65,reflection:.52,damping:.6,muffler:[.46,.3,.2]},intake:{helmholtz:88,q:4.6,level:.24},voice:1.02},v6:{label:`V6 60°`,cylinders:6,firingOrder:[1,4,2,5,3,6],banks:[[1,2,3],[4,5,6]],idleRpm:780,redlineRpm:6800,peakTorque:380,peakTorqueRpm:3600,gears:6,engineInertia:.26,gasTempFactor:1.28,pulse:{attack:31,decay:5.2,hardness:.61,jitter:1.3},exhaust:{bank:1.2,collector:1.05,reflection:.56,damping:.4,muffler:[.3,.2,.13]},intake:{helmholtz:102,q:5.8,level:.33},voice:.98},v6tt:{label:`V6 3.8 twin-turbo build`,cylinders:6,firingOrder:[1,4,2,5,3,6],banks:[[1,2,3],[4,5,6]],idleRpm:750,redlineRpm:7100,peakTorque:640,peakTorqueRpm:3600,gears:7,engineInertia:.29,gasTempFactor:1.22,pulse:{attack:29,decay:5,hardness:.6,jitter:1.2},exhaust:{bank:.95,collector:1.3,reflection:.5,damping:.52,muffler:[.34,.23,.15]},intake:{helmholtz:112,q:5.4,level:.3},voice:.98},flat6:{label:`Flat-6 3.8`,cylinders:6,firingOrder:[1,6,2,4,3,5],banks:[[1,2,3],[4,5,6]],idleRpm:800,redlineRpm:8500,peakTorque:420,peakTorqueRpm:5e3,gears:7,engineInertia:.22,gasTempFactor:1.31,pulse:{attack:44,decay:7,hardness:.74,jitter:.9},exhaust:{bank:.85,collector:.72,reflection:.48,damping:.3,muffler:[.22,.15,.1]},intake:{helmholtz:138,q:7.2,level:.42},voice:1},v8cross:{label:`V8 cross-plane 5.0`,cylinders:8,firingOrder:[1,8,7,3,6,5,4,2],banks:[[1,2,3,4],[5,6,7,8]],idleRpm:700,redlineRpm:7e3,peakTorque:540,peakTorqueRpm:4200,gears:6,engineInertia:.38,gasTempFactor:1.26,pulse:{attack:26,decay:4.4,hardness:.55,jitter:2.6},exhaust:{bank:1.75,collector:1.35,reflection:.63,damping:.34,muffler:[.4,.26,.17]},intake:{helmholtz:78,q:5,level:.3},voice:1.06},v8tt:{label:`V8 4.0 twin-turbo build`,cylinders:8,firingOrder:[1,8,7,3,6,5,4,2],banks:[[1,2,3,4],[5,6,7,8]],idleRpm:660,redlineRpm:6800,peakTorque:800,peakTorqueRpm:3e3,gears:8,engineInertia:.42,gasTempFactor:1.21,pulse:{attack:24,decay:4.2,hardness:.54,jitter:2.4},exhaust:{bank:1.1,collector:1.55,reflection:.58,damping:.55,muffler:[.42,.28,.18]},intake:{helmholtz:74,q:4.8,level:.28},voice:1.05},v8flat:{label:`V8 flat-plane 4.5`,cylinders:8,firingOrder:[1,5,3,7,4,8,2,6],banks:[[1,2,3,4],[5,6,7,8]],idleRpm:900,redlineRpm:9e3,peakTorque:460,peakTorqueRpm:6e3,gears:7,engineInertia:.25,gasTempFactor:1.33,pulse:{attack:52,decay:8.4,hardness:.82,jitter:.6},exhaust:{bank:.78,collector:.62,reflection:.44,damping:.26,muffler:[.18,.12,.08]},intake:{helmholtz:155,q:7.8,level:.44},voice:1},v10:{label:`V10 5.2`,cylinders:10,firingOrder:[1,6,5,10,2,7,3,8,4,9],banks:[[1,2,3,4,5],[6,7,8,9,10]],idleRpm:900,redlineRpm:8700,peakTorque:560,peakTorqueRpm:6500,gears:7,engineInertia:.3,gasTempFactor:1.32,pulse:{attack:48,decay:7.8,hardness:.8,jitter:.8},exhaust:{bank:.82,collector:.66,reflection:.46,damping:.27,muffler:[.19,.13,.09]},intake:{helmholtz:148,q:7.4,level:.45},voice:1.02},v12:{label:`V12 6.5`,cylinders:12,firingOrder:[1,7,5,11,3,9,6,12,2,8,4,10],banks:[[1,2,3,4,5,6],[7,8,9,10,11,12]],idleRpm:850,redlineRpm:8500,peakTorque:690,peakTorqueRpm:5800,gears:8,engineInertia:.36,gasTempFactor:1.31,pulse:{attack:46,decay:7.4,hardness:.78,jitter:.5},exhaust:{bank:.9,collector:.7,reflection:.47,damping:.28,muffler:[.2,.14,.09]},intake:{helmholtz:142,q:7,level:.44},voice:1.04}};function Yb(e){let t=720/e.cylinders,n=new Map;return e.firingOrder.forEach((r,i)=>{let a=e.pinOffsets&&e.pinOffsets[r]||0;n.set(r,(i*t+a+720)%720)}),n}function Xb(e,t){let n=Yb(e);return e.banks[t].map(e=>n.get(e)).sort((e,t)=>e-t)}function Zb(e,t=1){return qb*t/(4*Math.max(.05,e))}function Qb(e,t=1){return 2*Math.max(.05,e)/(qb*t)}var $b={hatch:{label:`Hot hatch`,mass:1320,wheelRadius:.31,finalDrive:4.05,gearRatios:[3.31,2.13,1.48,1.14,.95,.82],dragArea:.68,rollingResistance:.014,brakeForce:9500,gearbox:`manual`,shiftTimeMs:130,gearTeeth:[37,31,27,24,22,20]},sports:{label:`Sports car`,mass:1450,wheelRadius:.33,finalDrive:3.73,gearRatios:[3.55,2.05,1.39,1,.82,.67],dragArea:.62,rollingResistance:.013,brakeForce:12e3,gearbox:`manual`,shiftTimeMs:95,gearTeeth:[39,33,28,25,22,19]},supercar:{label:`Supercar (dual-clutch)`,mass:1560,wheelRadius:.34,finalDrive:3.9,gearRatios:[3.08,2.19,1.63,1.29,1.03,.84,.69],dragArea:.6,rollingResistance:.012,brakeForce:15e3,gearbox:`dct`,shiftTimeMs:45,gearTeeth:[41,35,30,26,23,20,18]},muscle:{label:`Muscle car`,mass:1720,wheelRadius:.35,finalDrive:3.55,gearRatios:[2.97,2.07,1.43,1,.71],dragArea:.78,rollingResistance:.016,brakeForce:11e3,gearbox:`manual`,shiftTimeMs:150,gearTeeth:[35,30,26,23,20]},truck:{label:`Pickup (automatic)`,mass:2400,wheelRadius:.38,finalDrive:3.73,gearRatios:[4.17,2.34,1.52,1.14,.87,.69],dragArea:1.05,rollingResistance:.018,brakeForce:13e3,gearbox:`auto`,shiftTimeMs:190,gearTeeth:[43,36,31,27,24,21]}},ex={stiffness:5200,dampingRatio:.22,damping:13,backlash:.035,clutchTorqueCapacity:900,clutchStiffness:3.2},tx=(e,t,n)=>e<t?t:e>n?n:e,nx=(e,t)=>typeof e==`number`&&isFinite(e)?e:t,rx=Object.freeze({mix:Object.freeze({exhaust:1,intake:.75,transmission:.45,turbo:.4,transients:.42,sub:.25}),tone:Object.freeze({rumble:1,brightness:1,punch:1}),eq:Object.freeze([0,0,0,0,0]),fx:Object.freeze({reverbMix:.14,reverbSize:.32,reverbDamping:4200,width:.35,popDepth:1.05,dynamics:1}),turbo:Object.freeze({enabled:0,inertia:.42,maxBoost:1.1,whineOrder:52,boostRpm:3500,valve:1,bov:.4,surge:1,flutterHz:13,screamer:0,antiLag:0}),position:0,volume:.7}),ix=Object.freeze([{path:`engine.idleRpm`,label:`Idle`,min:400,max:2500,step:10,unit:`rpm`,group:`engine`,rebuild:!1},{path:`engine.redlineRpm`,label:`Redline`,min:3e3,max:12e3,step:100,unit:`rpm`,group:`engine`,rebuild:!1},{path:`engine.peakTorque`,label:`Peak torque`,min:40,max:1400,step:5,unit:`N·m`,group:`engine`,rebuild:!1},{path:`engine.peakTorqueRpm`,label:`Torque peak at`,min:1200,max:9e3,step:100,unit:`rpm`,group:`engine`,rebuild:!1},{path:`engine.gears`,label:`Gears`,min:3,max:10,step:1,unit:``,group:`engine`,rebuild:!0},{path:`engine.engineInertia`,label:`Rotating inertia`,min:.02,max:1.2,step:.005,unit:`kg·m²`,group:`engine`,rebuild:!1},{path:`engine.gasTempFactor`,label:`Gas temperature`,min:.8,max:1.8,step:.01,unit:`×c`,group:`engine`,rebuild:!0},{path:`engine.voice`,label:`Voice level`,min:.2,max:2,step:.01,unit:`%`,group:`engine`,rebuild:!1},{path:`engine.pulse.attack`,label:`Blowdown attack`,min:5,max:90,step:1,unit:``,group:`pulse`,rebuild:!0},{path:`engine.pulse.decay`,label:`Blowdown decay`,min:1,max:14,step:.1,unit:``,group:`pulse`,rebuild:!0},{path:`engine.pulse.hardness`,label:`Load hardening`,min:0,max:1.5,step:.01,unit:``,group:`pulse`,rebuild:!0},{path:`engine.pulse.jitter`,label:`Cylinder jitter`,min:0,max:6,step:.1,unit:``,group:`pulse`,rebuild:!0},{path:`engine.exhaust.bank`,label:`Header length`,min:.2,max:2.5,step:.01,unit:`m`,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.collector`,label:`Collector length`,min:.2,max:3,step:.01,unit:`m`,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.reflection`,label:`End reflection`,min:.05,max:.9,step:.01,unit:``,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.damping`,label:`Pipe damping`,min:.1,max:1.5,step:.01,unit:``,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.muffler.0`,label:`Muffler stage 1`,min:0,max:.8,step:.01,unit:`m`,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.muffler.1`,label:`Muffler stage 2`,min:0,max:.8,step:.01,unit:`m`,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.muffler.2`,label:`Muffler stage 3`,min:0,max:.8,step:.01,unit:`m`,group:`exhaust`,rebuild:!0},{path:`engine.intake.helmholtz`,label:`Plenum resonance`,min:40,max:400,step:1,unit:`Hz`,group:`intake`,rebuild:!0},{path:`engine.intake.q`,label:`Plenum Q`,min:.5,max:14,step:.1,unit:``,group:`intake`,rebuild:!0},{path:`engine.intake.level`,label:`Induction level`,min:0,max:1.5,step:.01,unit:`%`,group:`intake`,rebuild:!0},{path:`turbo.enabled`,label:`Turbo`,min:0,max:1,step:1,unit:`bool`,group:`turbo`,rebuild:!1},{path:`turbo.inertia`,label:`Turbo inertia`,min:.05,max:2,step:.01,unit:`s`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.boostRpm`,label:`Boost onset`,min:1200,max:7e3,step:100,unit:`rpm`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.maxBoost`,label:`Max boost`,min:.2,max:3,step:.05,unit:`bar`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.whineOrder`,label:`Blade order`,min:10,max:120,step:1,unit:``,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.valve`,label:`Blow-off valve`,min:0,max:2,step:1,unit:`enum`,options:[`None`,`Atmos`,`Recirc`],group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.bov`,label:`Valve size`,min:0,max:1,step:.01,unit:`%`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.surge`,label:`Flutter trim`,min:0,max:2,step:.01,unit:`%`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.flutterHz`,label:`Flutter rate`,min:5,max:25,step:.5,unit:`Hz`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.screamer`,label:`Screamer pipe`,min:0,max:1,step:1,unit:`bool`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.antiLag`,label:`Anti-lag`,min:0,max:1,step:1,unit:`bool`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`mix.exhaust`,label:`Exhaust`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`mix.intake`,label:`Intake`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`mix.transmission`,label:`Gearbox`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`mix.turbo`,label:`Turbo`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`mix.transients`,label:`Pops`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`mix.sub`,label:`Sub`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`tone.rumble`,label:`Rumble`,min:0,max:2,step:.01,unit:`%`,group:`tone`,rebuild:!1},{path:`tone.brightness`,label:`Brightness`,min:0,max:2,step:.01,unit:`%`,group:`tone`,rebuild:!1},{path:`tone.punch`,label:`Bass punch`,min:0,max:2,step:.01,unit:`%`,group:`tone`,rebuild:!1},{path:`fx.popDepth`,label:`Pop depth`,min:0,max:2,step:.01,unit:`%`,group:`tone`,rebuild:!1},{path:`fx.dynamics`,label:`Compression`,min:0,max:1,step:.01,unit:`%`,group:`tone`,rebuild:!1},{path:`fx.reverbMix`,label:`Reverb mix`,min:0,max:1,step:.01,unit:`%`,group:`fx`,rebuild:!1},{path:`fx.reverbSize`,label:`Reverb size`,min:.05,max:1,step:.01,unit:`%`,group:`fx`,rebuild:!1},{path:`fx.reverbDamping`,label:`Reverb damping`,min:800,max:12e3,step:100,unit:`Hz`,group:`fx`,rebuild:!1},{path:`fx.width`,label:`Stereo width`,min:0,max:1,step:.01,unit:`%`,group:`fx`,rebuild:!1},{path:`position`,label:`Listener position`,min:0,max:1,step:.01,unit:`%`,group:`fx`,rebuild:!1},{path:`volume`,label:`Volume`,min:0,max:1,step:.01,unit:`%`,group:`fx`,rebuild:!1},{path:`eq.0`,label:`Sub 60`,min:-18,max:18,step:.5,unit:`dB`,group:`eq`,rebuild:!1},{path:`eq.1`,label:`Body 200`,min:-18,max:18,step:.5,unit:`dB`,group:`eq`,rebuild:!1},{path:`eq.2`,label:`Honk 800`,min:-18,max:18,step:.5,unit:`dB`,group:`eq`,rebuild:!1},{path:`eq.3`,label:`Rasp 2.5k`,min:-18,max:18,step:.5,unit:`dB`,group:`eq`,rebuild:!1},{path:`eq.4`,label:`Air 8k`,min:-18,max:18,step:.5,unit:`dB`,group:`eq`,rebuild:!1}]),ax=Object.freeze([{id:`engine`,label:`Engine`,note:`The machine itself. Torque and inertia drive the physics; gas temperature sets the speed of sound in the pipes.`},{id:`pulse`,label:`Combustion pulse`,note:`The shape of one cylinder blowing down. Attack is the crack, decay is the tail, hardening is how much both sharpen under load.`},{id:`exhaust`,label:`Exhaust`,note:`Waveguide geometry in metres. Header and collector lengths set the resonances; reflection and damping set how many survive.`},{id:`intake`,label:`Intake`,note:`Airbox Helmholtz resonance. It does not track rpm — what tracks rpm is how hard it is excited.`},{id:`turbo`,label:`Turbo`,note:`Bolts onto any engine. Inertia is lag. No blow-off valve = full "stu-stu-stu"; an atmospheric valve goes "pssh", a recirculating one is quiet — the bigger the valve, the less is left to flutter. A screamer pipe vents the wastegate to air; anti-lag keeps the turbo spooled off-throttle, with bangs.`},{id:`mix`,label:`Voice mix`,note:`Balance between the voices.`},{id:`tone`,label:`Tone`,note:`The fixed-frequency part of the response, plus how hard the compressor works.`},{id:`fx`,label:`Space`,note:`Reverb, width, where the listener is, and output level.`},{id:`eq`,label:`EQ`,note:`Five bands, ±18 dB.`}]);function ox(e,t){let n=e;for(let e of t.split(`.`)){if(n==null)return;n=n[e]}return n}function sx(e,t,n){let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++)(i[r[e]]==null||typeof i[r[e]]!=`object`)&&(i[r[e]]={}),i=i[r[e]];return i[r[r.length-1]]=n,e}function cx(e){return ix.find(t=>t.path===e)}function lx(e){if(Array.isArray(e))return e.map(lx);if(e&&typeof e==`object`){let t={};for(let n of Object.keys(e))t[n]=lx(e[n]);return t}return e}function ux(e){let t=Jb[e];return t?fx({version:3,id:e,label:t.label,engine:lx(t),...lx(rx)}):null}function dx(){let e={};for(let t of Object.keys(Jb))e[t]=ux(t);return e}function fx(e){let t=e&&typeof e==`object`?e:{},n=Jb[t.id]||Jb.v8cross,r={version:3,id:typeof t.id==`string`&&t.id?t.id:`custom`,label:typeof t.label==`string`&&t.label?t.label:n.label,engine:{},mix:{},tone:{},eq:[],fx:{},turbo:{},position:0,volume:.7},i=t.engine&&typeof t.engine==`object`?t.engine:n,a=tx(Math.round(nx(i.cylinders,n.cylinders)),1,16);r.engine.cylinders=a;let o=Array.isArray(i.firingOrder)?i.firingOrder.slice(0,a):null,s=o&&o.length===a&&o.every(e=>Number.isInteger(e)&&e>=1&&e<=a)&&new Set(o).size===a;r.engine.firingOrder=s?o:n.cylinders===a?lx(n.firingOrder):Array.from({length:a},(e,t)=>t+1);let c=Array.isArray(i.banks)?i.banks.filter(Array.isArray):null,l=c?c.flat():[],u=c&&c.length>0&&l.length===a&&l.every(e=>r.engine.firingOrder.includes(e));if(r.engine.banks=u?lx(c):n.cylinders===a?lx(n.banks):[r.engine.firingOrder.slice()],i.pinOffsets&&typeof i.pinOffsets==`object`){let e={};for(let[t,n]of Object.entries(i.pinOffsets)){let r=Number(t);Number.isInteger(r)&&r>=1&&r<=a&&(e[r]=tx(nx(n,0),-360,360))}Object.keys(e).length&&(r.engine.pinOffsets=e)}let d=nx(i.exhaust&&i.exhaust.bankB,NaN);r.engine.exhaust={},isFinite(d)&&r.engine.banks.length>1&&(r.engine.exhaust.bankB=tx(d,.2,2.5));let f=!(t.turbo&&typeof t.turbo==`object`)&&i.turbo&&typeof i.turbo==`object`?{...i.turbo,enabled:1}:null,p=f?{...t,turbo:f}:t,m={engine:n,...rx};for(let e of ix){let t=ox(p,e.path);isFinite(Number(t))||(t=ox(m,e.path)),isFinite(Number(t))||(t=e.min);let n=tx(Number(t),e.min,e.max);sx(r,e.path,e.unit===`bool`||e.unit===`enum`?Math.round(n):n)}let h=r.engine.exhaust.muffler;return r.engine.exhaust.muffler=[0,1,2].map(e=>tx(nx(h&&h[e],.2),0,.8)),r.eq=[0,1,2,3,4].map(e=>tx(nx(r.eq[e],0),-18,18)),r}function px(e){return JSON.stringify(fx(e),null,2).replace(/\[\s+((?:-?[\d.]+,?\s+)+)\]/g,(e,t)=>`[`+t.trim().replace(/,\s+/g,`, `)+`]`)}function mx(e){let t;try{t=JSON.parse(String(e))}catch(e){return{preset:null,error:`not valid JSON: `+e.message}}return!t||typeof t!=`object`?{preset:null,error:`not an object`}:{preset:fx(t),error:null}}var hx=8192,gx=1024;function _x(e,t){let n=e.length;for(let r=1,i=0;r<n;r++){let a=n>>1;for(;i&a;a>>=1)i^=a;if(i^=a,r<i){let n=e[r];e[r]=e[i],e[i]=n,n=t[r],t[r]=t[i],t[i]=n}}for(let r=2;r<=n;r<<=1){let i=-2*Math.PI/r,a=Math.cos(i),o=Math.sin(i);for(let i=0;i<n;i+=r){let n=1,s=0;for(let c=0;c<r/2;c++){let l=e[i+c],u=t[i+c],d=e[i+c+r/2]*n-t[i+c+r/2]*s,f=e[i+c+r/2]*s+t[i+c+r/2]*n;e[i+c]=l+d,t[i+c]=u+f,e[i+c+r/2]=l-d,t[i+c+r/2]=u-f;let p=n*a-s*o;s=n*o+s*a,n=p}}}}function vx(e){let t=e>>>0||1;return()=>(t^=t<<13,t>>>=0,t^=t>>17,t^=t<<5,t>>>=0,t/4294967296)}function yx(e,t,n){return e<0||e>1?0:(1-Math.exp(-t*e))*Math.exp(-n*e)}function bx(e,t,n,r=0){let i=e.pulse,a=Math.max(0,Math.min(1.5,typeof i.hardness==`number`&&isFinite(i.hardness)?i.hardness:.65))/.65,o=i.attack*(.55+.85*a*n),s=i.decay*(1.25-.35*a*n),c=new Float64Array(hx),l=vx(e.cylinders*2654435761+Math.round(i.attack*97)),u=(i.jitter||0)/100;for(let e of t){let t=1+(l()*2-1)*u*2.5,n=(l()*2-1)*u*6,i=1+(l()*2-1)*u*1.5,a=((e+r+n)%720+720)%720/720;for(let e=0;e<hx;e++){let n=e/hx-a;n<0&&(n+=1),c[e]+=t*yx(n,o,s*i)}}return c}function xx(e){let t=e.length,n=new Float64Array(t);for(let r=0;r<t;r++)n[r]=e[(r+1)%t]-e[r];let r=0;for(let e=0;e<t;e++)r+=n[e];r/=t;for(let e=0;e<t;e++)n[e]-=r;return n}var Sx=24;function Cx(e,t=gx,n=Sx){let r=e.length,i=new Float64Array(r),a=new Float64Array(r);i.set(e),_x(i,a);let o=Math.min(t,r/2),s=new Float32Array(o),c=new Float32Array(o),l=n>0?2*n:0;for(let e=1;e<o;e++){let t=l?1/(1+e/l):1;s[e]=2*i[e]/r*t,c[e]=-2*a[e]/r*t}return s[0]=0,c[0]=0,{real:s,imag:c}}function wx(e,t=.25){let n=0;for(let t=1;t<e.real.length;t++)n+=.5*(e.real[t]**2+e.imag[t]**2);let r=t/(Math.sqrt(n)||1);for(let t=0;t<e.real.length;t++)e.real[t]*=r,e.imag[t]*=r;return e}function Tx(e,t,n){let r={disableNormalization:!0},i=(n,i,a)=>{let o=wx(Cx(xx(bx(t,n,i,a))));return e.createPeriodicWave(o.real,o.imag,r)},a=t.banks.map((e,r)=>{let a=n(t,r);return{soft:i(a,0,0),hard:i(a,1,0)}}),o=t.banks.flat().map((e,n)=>n*720/t.cylinders);return{banks:a,intake:{soft:i(o,0,360),hard:i(o,1,360)}}}function Ex(e,t,n){let r=Math.max(.02,Number(e.engineInertia)||.25),i=Math.max(1,e.cylinders||4),a=Math.max(40,(Number(t)||0)*Math.PI/30),o=.3*((Number(e.peakTorque)||300)*(.12+.88*Math.max(0,Math.min(1,n))))*(4*Math.PI/i)/(r*a*a);return Math.max(0,Math.min(.12,o))}function Dx(e,t){let n=e.pulse,r=(n.jitter||0)/100,i=vx(e.cylinders*2654435761+Math.round(n.attack*97)+7),a=[],o=e.banks.length,s=[];for(let n=0;n<o;n++)for(let o of t(e,n)){let e=1+(i()*2-1)*r*2.5,t=(i()*2-1)*r*6,c=1+(i()*2-1)*r*1.5,l=((o+t)%720+720)%720/720;a.push({out:n,angle:l,ampTrim:e,decayTrim:c}),s.push({angle:o+t+360,ampTrim:e,decayTrim:c})}for(let e of s)a.push({out:o,angle:(e.angle%720+720)%720/720,ampTrim:e.ampTrim,decayTrim:e.decayTrim});let c=Math.max(0,Math.min(1.5,typeof n.hardness==`number`&&isFinite(n.hardness)?n.hardness:.65))/.65,l=hx,u=1-Math.exp(-2*Math.PI*48/l),d=[];for(let e=0;e<=o;e++){let t=[];for(let r=0;r<=4;r++){let i=r/4*c,o=n.attack*(.55+.85*i),s=n.decay*(1.25-.35*i),d=new Float64Array(l);for(let t of a)if(t.out===e)for(let e=0;e<l;e++){let n=e/l-t.angle;n<0&&(n+=1),d[e]+=t.ampTrim*yx(n,o,s*t.decayTrim)}let f=0,p=0;for(let e=0;e<2;e++)for(let t=0;t<l;t++){let n=(d[t]-d[(t+l-1)%l])*l;f+=u*(n-f),e&&(p+=f*f)}let m=Math.sqrt(p/l)||1;t.push(.25/m)}d.push(t)}return{events:a.sort((e,t)=>e.angle-t.angle),outputs:o+1,attack:n.attack,decay:n.decay,hardness:c,ccv:typeof n.ccv==`number`?n.ccv:.012+.012*(n.jitter||1),jitterDeg:typeof n.jitterDeg==`number`?n.jitterDeg:.4+.5*(n.jitter||1),gains:d,seed:e.cylinders*40503+Math.round(n.attack*131)>>>0}}var Ox=1.02,kx=10,Ax=2e4,jx=.92,Mx=.02,Nx=.09,U=(e,t,n)=>e<t?t:e>n?n:e;function W(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function G(e,t,n,r=Mx){let i=W(t,0),a=W(n,0);e.setTargetAtTime(i,a<0?0:a,r>0?r:Mx)}function Px(e,t,n,r){let i=2*Math.PI*U(t,1,.49*r)/r,a=Math.cos(i),o=Math.sin(i)/(2*Math.max(1e-4,n)),s=1+o,c=(1-a)/2/s,l=(1-a)/s,u=c,d=-2*a/s,f=(1-o)/s,p=2*Math.PI*U(e,.01,.49*r)/r,m=Math.cos(p),h=Math.sin(p),g=Math.cos(2*p),_=Math.sin(2*p),v=c+l*m+u*g,y=-(l*h+u*_),b=1+d*m+f*g,x=-(d*h+f*_),S=Math.atan2(y,v)-Math.atan2(x,b);return Number.isFinite(S)?S:0}function Fx(e,t,n,r){let i=2*Math.PI*e;if(!(i>0))return 0;let a=Px(e,t,n,r),o=(Math.PI+a)/i;return o>0&&Number.isFinite(o)?o:1/(2*e)}var Ix=new Map;function Lx(e,t,n=4096,r=Rx()){let i=e+`:`+t+`:`+n+`:`+r,a=Ix.get(i);if(a)return a;let o=1/Math.max(.2,e/3.2)*1.05,s=1/Math.max(.2,t/3.2)*.85,c=new Float32Array(n);for(let e=0;e<n;e++){let t=r*(e/(n-1)*2-1);c[e]=t>=0?o*Math.tanh(t/o):s*Math.tanh(t/s)}return Ix.set(i,c),c}var Rx=()=>6,zx=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1;let r=t&&t.exhaust||{};this.length=U(W(n.length,W(r.bank,1)),.05,12),this.gasTemp=U(W(n.gasTempFactor,W(t&&t.gasTempFactor,1)),.5,2.5),this.reflection=U(W(n.reflection,W(r.reflection,.5)),0,jx),this.damping=U(W(n.damping,W(r.damping,.4)),.05,2),this.thermalSpan=U(W(n.thermalSpan,.05),0,.25),this.thermalBias=.35,this.sampleRate=W(e&&e.sampleRate,48e3),this.minLoopDelay=128/this.sampleRate,this.nominalDelay=Qb(this.length,this.gasTemp),this.frequency=Zb(this.length,this.gasTemp),this.lpBase=U(this.frequency*(1.8/this.damping),150,12e3),this.loopQ=.5;let i=.49*this.sampleRate;if(this.fMax=Math.min(Ax,i),this.tunedDelay=this._tunedDelay(this.frequency,this.lpBase),this.phaseCompensation=this.tunedDelay/this.nominalDelay,this.maxHeatScale=1+this.thermalSpan*(1-this.thermalBias),this.shortestDelay=this._tunedDelay(this.frequency*this.maxHeatScale,this.lpBase*this.maxHeatScale*1.35),this.mode=this.shortestDelay>=this.minLoopDelay*Ox?`delay`:`bandpass`,this.inGain=e.createGain(),this.inGain.gain.value=1,this.out=e.createGain(),this.out.gain.value=1,this.dryGain=e.createGain(),this.dryGain.gain.value=U(W(n.dry,.3),0,4),this.inGain.connect(this.dryGain),this.dryGain.connect(this.out),this.wetGain=e.createGain(),this.wetGain.gain.value=U(W(n.wet,.9),0,4),this.wetGain.connect(this.out),this.mode===`delay`){let t=Math.max(.01,this.nominalDelay/(1-this.thermalSpan)*1.25);this.maxDelayTime=t,this.sum=e.createGain(),this.sum.gain.value=1,this.delay=e.createDelay(t),this.delay.delayTime.value=U(this.tunedDelay,this.minLoopDelay,t),this.loopLP=e.createBiquadFilter(),this.loopLP.type=`lowpass`,this.loopLP.frequency.value=this._f(this.lpBase),this.loopLP.Q.value=this.loopQ,this.fb=e.createGain(),this.fb.gain.value=-this._fbMag(0),this.inGain.connect(this.sum),this.sum.connect(this.delay),this.delay.connect(this.loopLP),this.loopLP.connect(this.fb),this.fb.connect(this.sum),this.loopLP.connect(this.wetGain)}else{let t=this._fbMag(0);this.fallbackQ=U(Math.PI/(2*Math.max(.02,1-t)),.7,24);let r=U(Math.round(W(n.maxModes,3)),1,6);this.modes=[];let i=0,a=[];for(let e=0;e<r;e++){let t=this.frequency*(2*e+1);if(t>this.fMax*.95)break;let n=1/Math.sqrt(1+t/this.lpBase*(t/this.lpBase)),r=(1/(2*e+1))**.7*n;a.push(r),i+=r}a.length||(a.push(1),i=1);let o=.6/Math.max(.08,1-t);for(let t=0;t<a.length;t++){let n=e.createBiquadFilter();n.type=`bandpass`,n.frequency.value=this._f(this.frequency*(2*t+1)),n.Q.value=this.fallbackQ;let r=e.createGain();r.gain.value=a[t]/i*o,this.inGain.connect(n),n.connect(r),r.connect(this.wetGain),this.modes.push({bp:n,g:r,order:2*t+1})}}this._nodeCount=this._countNodes()}get input(){return this.inGain}get output(){return this.out}_f(e){return U(W(e,kx),kx,this.fMax)}_tunedDelay(e,t){return Fx(U(W(e,kx),kx,this.fMax),U(W(t,150),20,.49*this.sampleRate),this.loopQ,this.sampleRate)}_fbMag(e){return U(this.reflection*(.92+.08*U(e,0,1)),0,jx)}_heatScale(e){let t=U(W(e&&e.load,0),0,1),n=U(W(e&&e.rpmNorm,0),0,1),r=U(.6*t+.4*n,0,1);return 1+this.thermalSpan*(r-this.thermalBias)}update(e){if(this.disposed)return;let t=W(e&&e.now,W(this.ctx.currentTime,0)),n=U(W(e&&e.load,0),0,1),r=this._heatScale(e);if(this.mode===`delay`){let e=U(this.nominalDelay/r,this.minLoopDelay,this.maxDelayTime);G(this.delay.delayTime,e,t,Nx),G(this.loopLP.frequency,this._f(this.lpBase*r*(1+.35*n)),t,Mx),G(this.fb.gain,-this._fbMag(n),t,Mx)}else for(let e=0;e<this.modes.length;e++){let n=this.modes[e];G(n.bp.frequency,this._f(this.frequency*n.order*r),t,Nx)}}_countNodes(){let e=4;return this.mode===`delay`?e+=4:e+=this.modes.length*2,e}dispose(){if(this.disposed)return;this.disposed=!0;let e=[this.inGain,this.out,this.dryGain,this.wetGain,this.sum,this.delay,this.loopLP,this.fb];if(this.modes)for(let t of this.modes)e.push(t.bp,t.g);for(let t of e)t&&t.disconnect&&t.disconnect()}},Bx=class e{constructor(t,n,r={}){this.ctx=t,this.profile=n,this.disposed=!1;let i=n&&n.exhaust||{},a=Array.isArray(r.chambers)?r.chambers:Array.isArray(i.muffler)?i.muffler:[.3,.2,.13];this.chambers=a.map(e=>U(W(e,.2),.02,3)),this.gasTemp=U(W(r.gasTempFactor,W(n&&n.gasTempFactor,1)),.5,2.5),this.sampleRate=W(t&&t.sampleRate,48e3),this.fMax=Math.min(Ax,.49*this.sampleRate),this.thermalSpan=U(W(r.thermalSpan,.025),0,.2),this.thermalBias=.35;let o=this.chambers.map(e=>Qb(e,this.gasTemp));this.spread=U(W(r.spread,.06),0,.25);let s=r.decorrelate!==!1,c=e.peakCoincidence(o);this.delays=s?e._decorrelate(o,this.spread):o.slice();let l=e.peakCoincidence(this.delays);this.coincidence={before:c,after:l},this.notches=this.delays.map(e=>1/(2*e));let u=U(W(i.reflection,.5),0,1);this.branchGain=U(W(r.branchGain,.55+.3*u),.05,.9);let d=U(W(r.packingOctaves,7),1,40);this.packingBase=U(Zb(Math.max(...this.chambers),this.gasTemp)*d,500,11e3),this.inGain=t.createGain(),this.inGain.gain.value=1,this.out=t.createGain(),this.out.gain.value=1,this.stages=[];let f=this.inGain;for(let e=0;e<this.delays.length;e++){let n=this.delays[e],r=t.createGain();r.gain.value=1;let i=t.createGain();i.gain.value=1;let a=Math.max(.005,n/(1-this.thermalSpan)*1.5),o=t.createDelay(a);o.delayTime.value=U(n,0,a);let s=t.createGain();s.gain.value=this.branchGain*.92**e,f.connect(i),i.connect(r),f.connect(o),o.connect(s),s.connect(r),this.stages.push({sum:r,thru:i,delay:o,branch:s,T:n,maxT:a,taper:.92**e}),f=r}this.packing=t.createBiquadFilter(),this.packing.type=`lowpass`,this.packing.frequency.value=U(this.packingBase,kx,this.fMax),this.packing.Q.value=.6;let p=1;for(let e of this.stages)p*=1+e.branch.gain.value;this.trim=t.createGain(),this.trim.gain.value=1/Math.max(1,p*.72),f.connect(this.packing),this.packing.connect(this.trim),this.trim.connect(this.out),this._nodeCount=4+this.stages.length*4}get input(){return this.inGain}get output(){return this.out}static peakCoincidence(e,t=6,n=45){let r=0;for(let i=0;i<e.length;i++)for(let a=i+1;a<e.length;a++)for(let o=1;o<=t;o++)for(let s=1;s<=t;s++){let t=o/e[i],c=s/e[a];if(t>8e3||c>8e3)continue;let l=(t-c)/n;r+=Math.exp(-l*l)/(o*s)}return r}static _decorrelate(t,n){let r=t.slice();for(let i=1;i<r.length;i++){let a=r[i],o=1/0;for(let s=0;s<41;s++){let c=1+n*(2*s/40-1),l=r.slice(0,i+1);l[i]=t[i]*c;let u=e.peakCoincidence(l);u<o-1e-12&&(o=u,a=t[i]*c)}r[i]=a}return r}update(e){if(this.disposed)return;let t=W(e&&e.now,W(this.ctx.currentTime,0)),n=U(W(e&&e.load,0),0,1),r=U(W(e&&e.rpmNorm,0),0,1),i=U(.6*n+.4*r,0,1),a=1+this.thermalSpan*(i-this.thermalBias);for(let r=0;r<this.stages.length;r++){let i=this.stages[r];G(i.delay.delayTime,U(i.T/a,0,i.maxT),t,Nx);let o=U(W(e&&e.valve,0),0,1);G(i.branch.gain,U(this.branchGain*i.taper*(1-.12*n)*(1-.65*o),0,.95),t,Mx)}let o=U(W(e&&e.valve,0),0,1);G(this.packing.frequency,U(this.packingBase*(1+.3*n)*(1+1.1*o)*a,kx,this.fMax),t,Mx)}dispose(){if(this.disposed)return;this.disposed=!0;let e=[this.inGain,this.out,this.packing,this.trim];for(let t of this.stages)e.push(t.sum,t.thru,t.delay,t.branch);for(let t of e)t&&t.disconnect&&t.disconnect()}},Vx=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1;let r=t&&t.intake||{};this.f0=U(W(n.helmholtz,W(r.helmholtz,110)),kx,2e3),this.q0=U(W(n.q,W(r.q,6)),.3,30),this.level=U(W(n.level,W(r.level,.33)),0,4),this.sampleRate=W(e&&e.sampleRate,48e3),this.fMax=Math.min(Ax,.49*this.sampleRate),this.out=e.createGain(),this.out.gain.value=this.level,this.inGain=e.createGain(),this.inGain.gain.value=1,this.helm=e.createBiquadFilter(),this.helm.type=`bandpass`,this.helm.frequency.value=this._f(this.f0),this.helm.Q.value=this.q0,this.helmGain=e.createGain(),this.helmGain.gain.value=0,this.inGain.connect(this.helm),this.helm.connect(this.helmGain),this.helmGain.connect(this.out),this.directLP=e.createBiquadFilter(),this.directLP.type=`lowpass`,this.directLP.frequency.value=this._f(this.f0*4),this.directLP.Q.value=.7,this.directGain=e.createGain(),this.directGain.gain.value=0,this.inGain.connect(this.directLP),this.directLP.connect(this.directGain),this.directGain.connect(this.out),this.noiseBuf=this._makeNoise(e,2),this.noiseSrc=c(e.createBufferSource()),this.noiseSrc.buffer=this.noiseBuf,this.noiseSrc.loop=!0,this.noiseHP=e.createBiquadFilter(),this.noiseHP.type=`highpass`,this.noiseHP.frequency.value=this._f(this.f0*.8),this.noiseHP.Q.value=.7,this.noiseBP=e.createBiquadFilter(),this.noiseBP.type=`bandpass`,this.noiseBP.frequency.value=this._f(this.f0*3),this.noiseBP.Q.value=.9,this.noiseGain=e.createGain(),this.noiseGain.gain.value=0,this.noiseSrc.connect(this.noiseHP),this.noiseHP.connect(this.noiseBP),this.noiseBP.connect(this.noiseGain),this.noiseGain.connect(this.out),this.noiseToHelm=e.createGain(),this.noiseToHelm.gain.value=0,this.noiseHP.connect(this.noiseToHelm),this.noiseToHelm.connect(this.helm),this.started=!1,this._nodeCount=10}get input(){return this.inGain}get output(){return this.out}_f(e){return U(W(e,kx),kx,this.fMax)}_makeNoise(e,t){let n=Math.max(1,Math.floor(W(e&&e.sampleRate,48e3)*t)),r=e.createBuffer(1,n,W(e&&e.sampleRate,48e3)),i=r.getChannelData(0),a=2654435769,o=0,s=0;for(let e=0;e<n;e++){a^=a<<13,a>>>=0,a^=a>>17,a^=a<<5,a>>>=0;let t=a/4294967296*2-1;o=.997*o+t*.0555179,s=.985*s+t*.3104856,i[e]=U((o+s+t*.1848)*.32,-1,1)}return r}start(e){if(!(this.started||this.disposed)){this.started=!0;try{this.noiseSrc.start(W(e,0))}catch{}}}update(e){if(this.disposed)return;this.started||this.start(W(e&&e.now,0));let t=W(e&&e.now,W(this.ctx.currentTime,0)),n=U(W(e&&e.load,0),0,1),r=U(W(e&&e.throttle,0),0,1),i=U(W(e&&e.rpmNorm,0),0,1),a=U(W(e&&e.overrun,0),0,1),o=Math.max(n,.001)**.7,s=U(r*(.25+.75*i),0,1),c=U(a*(.15+.85*i),0,1);G(this.helm.Q,U(this.q0*(.55+.45*r),.3,30),t,.05),G(this.helm.frequency,this._f(this.f0),t,.1),G(this.helmGain.gain,U((.12+.88*o)*(.35+.65*i),0,4),t,Mx),G(this.directGain.gain,U(.3*(.2+.8*o),0,4),t,Mx),G(this.noiseBP.frequency,this._f(this.f0*(3+9*s)*(1+.6*c)),t,Mx),G(this.noiseBP.Q,U(.9+.7*s,.3,6),t,.05),G(this.noiseGain.gain,U(.42*s**1.2+.16*c,0,4),t,Mx),G(this.noiseToHelm.gain,U(.2*s+.05*c,0,2),t,Mx),G(this.out.gain,U(this.level,0,4),t,.1)}dispose(){if(this.disposed)return;this.disposed=!0;try{this.started&&this.noiseSrc.stop()}catch{}let e=[this.inGain,this.out,this.helm,this.helmGain,this.directLP,this.directGain,this.noiseSrc,this.noiseHP,this.noiseBP,this.noiseGain,this.noiseToHelm];for(let t of e)t&&t.disconnect&&t.disconnect()}},Hx=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1,this.maxDrive=U(W(n.maxDrive,4.5),1,40),this.idleDrive=U(W(n.idleDrive,1),.1,10);let r=U(W(n.kp,3.2),.5,12),i=U(W(n.kn,2),.5,12);this.sampleRate=W(e&&e.sampleRate,48e3),this.fMax=Math.min(Ax,.49*this.sampleRate),this.drive=e.createGain(),this.drive.gain.value=this.idleDrive,this.shaper=e.createWaveShaper(),this.shaper.curve=Lx(r,i,4096),this.shaper.oversample=`4x`,this.span=e.createGain(),this.span.gain.value=1/Rx(),this.dcBlock=e.createBiquadFilter(),this.dcBlock.type=`highpass`,this.dcBlock.frequency.value=U(22,kx,this.fMax),this.dcBlock.Q.value=.7,this.makeup=e.createGain(),this.makeup.gain.value=this._makeupFor(this.idleDrive),this.out=e.createGain(),this.out.gain.value=1,this.drive.connect(this.span),this.span.connect(this.shaper),this.shaper.connect(this.dcBlock),this.dcBlock.connect(this.makeup),this.makeup.connect(this.out),this._nodeCount=6}get input(){return this.drive}get output(){return this.out}_makeupFor(e){return U(1/Math.max(.05,e)**.7,.05,4)}update(e){if(this.disposed)return;let t=W(e&&e.now,W(this.ctx.currentTime,0)),n=U(W(e&&e.load,0),0,1),r=U(W(e&&e.rpmNorm,0),0,1),i=U(W(e&&e.boost,0),0,1),a=U(W(e&&e.overrun,0),0,1),o=U(n**1.5*(.55+.45*r)+.55*i*n,0,1.4),s=.25*a*(.3+.7*r)+.22*U(W(e&&e.valve,0),0,1)*(.4+.6*n),c=U(this.idleDrive+(this.maxDrive-this.idleDrive)*U(o+s,0,1),.1,this.maxDrive);G(this.drive.gain,c,t,Mx),G(this.makeup.gain,this._makeupFor(c),t,Mx)}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[this.drive,this.span,this.shaper,this.dcBlock,this.makeup,this.out])e&&e.disconnect&&e.disconnect()}}},Ux=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1,this.sampleRate=W(e&&e.sampleRate,48e3),this.fMax=Math.min(Ax,.49*this.sampleRate),this.boomHz=U(W(n.boomHz,62),20,300),this.panelHz=U(W(n.panelHz,155),40,800),this.extLP=U(W(n.exteriorLP,17e3),1e3,this.fMax),this.intLP=U(W(n.interiorLP,1050),120,8e3),this.intBoomDb=U(W(n.boomDb,6.5),0,18),this.intPanelDb=U(W(n.panelDb,3.5),0,18),this.intShelfDb=U(W(n.shelfDb,-11),-40,0),this.shelfHz=U(W(n.shelfHz,3200),500,this.fMax),this.position=U(W(n.position,0),0,1),this.target=this.position,this.inGain=e.createGain(),this.inGain.gain.value=1,this.boom=e.createBiquadFilter(),this.boom.type=`peaking`,this.boom.frequency.value=U(this.boomHz,kx,this.fMax),this.boom.Q.value=U(W(n.boomQ,3.2),.3,20),this.boom.gain.value=0,this.panel=e.createBiquadFilter(),this.panel.type=`peaking`,this.panel.frequency.value=U(this.panelHz,kx,this.fMax),this.panel.Q.value=U(W(n.panelQ,2.4),.3,20),this.panel.gain.value=0,this.lp=e.createBiquadFilter(),this.lp.type=`lowpass`,this.lp.frequency.value=U(this.extLP,kx,this.fMax),this.lp.Q.value=.6,this.shelf=e.createBiquadFilter(),this.shelf.type=`highshelf`,this.shelf.frequency.value=U(this.shelfHz,kx,this.fMax),this.shelf.gain.value=0,this.trim=e.createGain(),this.trim.gain.value=1,this.out=e.createGain(),this.out.gain.value=1,this.inGain.connect(this.boom),this.boom.connect(this.panel),this.panel.connect(this.lp),this.lp.connect(this.shelf),this.shelf.connect(this.trim),this.trim.connect(this.out),this._nodeCount=7,this._write(W(e.currentTime,0),.001)}get input(){return this.inGain}get output(){return this.out}setPerspective(e){return e===`interior`?this.setPosition(1):e===`exterior`&&this.setPosition(0),this}setPosition(e){return this.target=U(W(e,0),0,1),this.disposed||this._write(W(this.ctx.currentTime,0),.05),this}get perspective(){return this.target>=.5?`interior`:`exterior`}_write(e,t){let n=this.target,r=this.extLP*(this.intLP/this.extLP)**+n;G(this.lp.frequency,U(r,kx,this.fMax),e,t),G(this.boom.gain,this.intBoomDb*n,e,t),G(this.panel.gain,this.intPanelDb*n,e,t),G(this.shelf.gain,this.intShelfDb*n,e,t),G(this.trim.gain,U(10**(-4.5*n/20),.05,1),e,t)}update(e){if(this.disposed)return;let t=W(e&&e.now,W(this.ctx.currentTime,0));this._write(t,.05),this.position=this.target}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[this.inGain,this.boom,this.panel,this.lp,this.shelf,this.trim,this.out])e&&e.disconnect&&e.disconnect()}}},Wx=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1;let r=t&&t.exhaust||{},i=t&&Array.isArray(t.banks)&&t.banks.length?t.banks:[[1]];t&&t.gasTempFactor,this.sampleRate=W(e&&e.sampleRate,48e3),this.bankLengths=i.map((e,t)=>t===1&&Number.isFinite(r.bankB)?r.bankB:W(r.bank,1.2)),this.collectorNode=e.createGain(),this.collectorNode.gain.value=1/Math.sqrt(i.length);let a=n.transit!==!1;this.banks=[],this.transits=[],this.inputs=[];for(let r=0;r<i.length;r++){let i=new zx(e,t,Object.assign({length:this.bankLengths[r]},n.bankOpts));if(this.banks.push(i),this.inputs.push(i.input),a){let t=i.nominalDelay/2,n=Math.max(.005,t*2),r=e.createDelay(n);r.delayTime.value=U(t,0,n),i.output.connect(r),r.connect(this.collectorNode),this.transits.push({d:r,t,maxT:n})}else i.output.connect(this.collectorNode),this.transits.push(null)}this.collector=new zx(e,t,Object.assign({length:W(r.collector,1),reflection:U(W(r.reflection,.5)*.7,0,jx),damping:U(W(r.damping,.4)*1.5,.05,2)},n.collectorOpts)),this.collectorNode.connect(this.collector.input),this.muffler=new Bx(e,t,n.mufflerOpts),this.collector.output.connect(this.muffler.input),this.useNonlinearity=n.nonlinearity!==!1,this.out=e.createGain(),this.out.gain.value=1,this.useNonlinearity?(this.nonlinearity=new Hx(e,t,n.nonlinearityOpts),this.muffler.output.connect(this.nonlinearity.input),this.nonlinearity.output.connect(this.out)):(this.nonlinearity=null,this.muffler.output.connect(this.out)),this._thermalSpan=this.banks.length?this.banks[0].thermalSpan:.05,this._thermalBias=this.banks.length?this.banks[0].thermalBias:.35,this.report={bankLengths:this.bankLengths.slice(),bankFrequencies:this.banks.map(e=>e.frequency),bankModes:this.banks.map(e=>e.mode),collectorFrequency:this.collector.frequency,collectorMode:this.collector.mode,mufflerNotches:this.muffler.notches.slice(),transitSkewMs:this.transits[0]&&this.transits[1]?Math.abs(this.transits[0].t-this.transits[1].t)*1e3:0},this._nodeCount=this._countNodes()}get input(){return this.inputs[0]}get output(){return this.out}update(e){if(this.disposed)return;let t=W(e&&e.now,W(this.ctx.currentTime,0)),n=U(W(e&&e.load,0),0,1),r=U(W(e&&e.rpmNorm,0),0,1),i=U(.6*n+.4*r,0,1),a=1+this._thermalSpan*(i-this._thermalBias);for(let n=0;n<this.banks.length;n++){this.banks[n].update(e);let r=this.transits[n];r&&G(r.d.delayTime,U(r.t/a,0,r.maxT),t,Nx)}this.collector.update(e),this.muffler.update(e),this.nonlinearity&&this.nonlinearity.update(e)}_countNodes(){let e=2;for(let t of this.banks)e+=t._nodeCount;for(let t of this.transits)t&&(e+=1);return e+=this.collector._nodeCount+this.muffler._nodeCount,this.nonlinearity&&(e+=this.nonlinearity._nodeCount),e}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.banks)e.dispose();for(let e of this.transits)e&&e.d.disconnect&&e.d.disconnect();this.collector.dispose(),this.muffler.dispose(),this.nonlinearity&&this.nonlinearity.dispose();for(let e of[this.collectorNode,this.out])e&&e.disconnect&&e.disconnect()}}},Gx=3800,Kx=-5.5,qx=1150,K=.02,Jx=10,Yx=2e4,Xx=.004;function q(e,t,n){return e<t?t:e>n?n:e}function J(e,t){return typeof e==`number`&&isFinite(e)?e:t}function Zx(e,t){return q(J(e,t),Jx,Yx)}function Y(e,t,n,r){e.setTargetAtTime(J(t,0),J(n,0),r>0?r:K)}function X(e,t,n,r,i){e.setTargetAtTime(Zx(t,i===void 0?Jx:i),J(n,0),r>0?r:K)}function Qx(e){let t=e>>>0||1;return function(){return t^=t<<13,t>>>=0,t^=t>>17,t^=t<<5,t>>>=0,t/4294967296}}var $x=new WeakMap;function eS(e,t){let n=$x.get(e);if(n||(n={},$x.set(e,n)),n[t])return n[t];let r=J(e.sampleRate,48e3),i=Math.max(1024,Math.floor(r*2)),a=e.createBuffer(1,i,r),o=a.getChannelData(0),s=Qx(t===`pink`?2654435769:2246822507);if(t===`pink`){let e=0,t=0,n=0,r=0,a=0,c=0,l=0;for(let u=0;u<i;u++){let i=s()*2-1;e=.99886*e+i*.0555179,t=.99332*t+i*.0750759,n=.969*n+i*.153852,r=.8665*r+i*.3104856,a=.55*a+i*.5329522,c=-.7616*c-i*.016898,o[u]=(e+t+n+r+a+c+l+i*.5362)*.11,l=i*.115926}}else for(let e=0;e<i;e++)o[e]=s()*2-1;let c=Math.min(2048,i>>2);for(let e=0;e<c;e++){let t=e/c;o[e]=o[e]*t+o[i-c+e]*(1-t)}return n[t]=a,a}function tS(e,t,n){let r=c(e.createBufferSource());r.buffer=eS(e,t),r.loop=!0;try{r.start(0,J(n,0)),r.__started=!0}catch{}return r}function nS(e,t,n,r){let i=e.createGain();return i.gain.value=n,t.connect(i),i.connect(r),i}function rS(e,t){let n=J(t,0);for(let t=0;t<e.length;t++){let r=e[t];if(r&&!r.__started)try{r.start(n),r.__started=!0}catch{}}}function iS(e,t){for(let n=0;n<e.length;n++){try{e[n].stop(J(t,0))}catch{}try{e[n].disconnect()}catch{}}}function aS(e){for(let t=0;t<e.length;t++)try{e[t].disconnect()}catch{}}var oS=class{constructor(e,t,n){this.ctx=e,this.profile=t;let r=n||{};this.level=J(r.level,1),this.gearCut=r.gearCut===`straight`?`straight`:`helical`,this.driveshaftScale=typeof r.driveshaftScale==`number`&&isFinite(r.driveshaftScale)?r.driveshaftScale:`auto`,this._scale=0,this._srcs=[],this._nodes=[];let i=e=>(this._nodes.push(e),e);this.out=i(e.createGain()),this.out.gain.value=this.level;let a=tS(e,`white`,.71),o=tS(e,`pink`,1.31);this._srcs.push(a,o),this.meshOsc1=c(e.createOscillator()),this.meshOsc1.type=`sine`,this.meshOsc1.frequency.value=500,this.meshOsc2=c(e.createOscillator()),this.meshOsc2.type=`sine`,this.meshOsc2.frequency.value=1e3,this.runoutOsc=c(e.createOscillator()),this.runoutOsc.type=`sine`,this.runoutOsc.frequency.value=20,this._srcs.push(this.meshOsc1,this.meshOsc2,this.runoutOsc),this.meshH2=i(e.createGain()),this.meshH2.gain.value=this.gearCut===`straight`?.55:.2,this.meshBP=i(e.createBiquadFilter()),this.meshBP.type=`bandpass`,this.meshBP.frequency.value=500,this.meshBP.Q.value=this.gearCut===`straight`?9:3.5,this.meshNoiseG=i(e.createGain()),this.meshNoiseG.gain.value=this.gearCut===`straight`?.22:.6,this.meshAM=i(e.createGain()),this.meshAM.gain.value=.85,i(nS(e,this.runoutOsc,.15,this.meshAM.gain)),this.meshGain=i(e.createGain()),this.meshGain.gain.value=0,this.meshOsc1.connect(this.meshAM),this.meshOsc2.connect(this.meshH2),this.meshH2.connect(this.meshAM),a.connect(this.meshBP),this.meshBP.connect(this.meshNoiseG),this.meshNoiseG.connect(this.meshAM),this.meshAM.connect(this.meshGain),this.meshGain.connect(this.out),this.ratBP1=i(e.createBiquadFilter()),this.ratBP1.type=`bandpass`,this.ratBP1.frequency.value=1800,this.ratBP1.Q.value=2,this.ratBP2=i(e.createBiquadFilter()),this.ratBP2.type=`bandpass`,this.ratBP2.frequency.value=3600,this.ratBP2.Q.value=2.5,this.ratH2=i(e.createGain()),this.ratH2.gain.value=.5,this.ratAM=i(e.createGain()),this.ratAM.gain.value=.4,this.torsOsc=c(e.createOscillator()),this.torsOsc.type=`sawtooth`,this.torsOsc.frequency.value=60,this._srcs.push(this.torsOsc),i(nS(e,this.torsOsc,.6,this.ratAM.gain)),this.ratGain=i(e.createGain()),this.ratGain.gain.value=0,o.connect(this.ratBP1),o.connect(this.ratBP2),this.ratBP1.connect(this.ratAM),this.ratBP2.connect(this.ratH2),this.ratH2.connect(this.ratAM),this.ratAM.connect(this.ratGain),this.ratGain.connect(this.out),this.setVehicle(r.vehicle,r.gearTeeth,r.finalDrive),this.setProfile(t)}get input(){return null}get output(){return this.out}setVehicle(e,t,n){let r=e||null,i=t||r&&r.gearTeeth||null;this.teeth=i&&i.length?i:[37,31,27,24,22,20],this.finalDrive=q(J(n,J(r&&r.finalDrive,3.9)),1,12),this._scale=0}setProfile(e){this.profile=e,this.cyl=q(J(e&&e.cylinders,4),1,16),this.idleRpm=J(e&&e.idleRpm,800)}_shaftRpm(e){let t=Math.abs(J(e.wheelRpm,0));if(this.driveshaftScale!==`auto`)return t*this.driveshaftScale;if(this._scale===0){let n=J(e.gearRatio,0),r=J(e.rpm,0);if(n>.05&&t>50&&r>200&&J(e.clutchEngaged,0)>.9){let e=r/t,i=Math.abs(e-n),a=Math.abs(e-n/this.finalDrive);this._scale=i<a?this.finalDrive:1}}return t*(this._scale||1)}meshFrequency(e,t){let n=Math.round(J(e,0))-1;return n<0||n>=this.teeth.length?0:Math.abs(J(t,0))/60*J(this.teeth[n],0)}update(e){let t=J(e.now,0),n=Math.round(J(e.gear,0)),r=q(J(e.load,0),0,1),i=Math.max(0,J(e.rpm,0)),a=J(e.f0,i/120),o=q(J(e.clutchEngaged,0),0,1),s=e.shiftPhase||``,c=this._shaftRpm(e),l=this.meshFrequency(n,c),u=0;if(l>0){let e=1/(1+(l/1800)**2.4);u=q((l-30)/40,0,1)*e}let d=J(e.torqueSign,1)>=0?.22+.85*r:.34,f=+(n>0&&Math.abs(J(e.gearRatio,0))>.001),p=s===`open`||s===`sync`||s===`cut`?.05:1,m=.45+.55*q(c/2500,0,1),h=.065*(this.gearCut===`straight`?1:.42)*f*o*p*d*u*m;X(this.meshOsc1.frequency,l,t,K,500),X(this.meshOsc2.frequency,l*2,t,K,1e3);let g=this.gearCut===`straight`?.55:.2;Y(this.meshH2.gain,g/(1+(l*2/2600)**2.4),t,K),X(this.meshBP.frequency,l,t,K,500),X(this.runoutOsc.frequency,c/60*2,t,K,Jx),Y(this.meshGain.gain,h,t,K);let _=q(Math.abs(J(e.dRpm,0))/4e3,0,1),v=q(Math.abs(J(e.clutchSlip,0))/800,0,1),y=o*q(1-(i-this.idleRpm)/Math.max(200,this.idleRpm*1.6),0,1)*(1-.7*r)*(f?.4:1),b=1-.65*r*f,x=q(.5*y+.75*_+.7*v,0,1)*b;X(this.torsOsc.frequency,this.cyl*a,t,K,Jx),Y(this.ratGain.gain,.09*x*q(i/Math.max(1,this.idleRpm*.6),0,1),t,K)}start(e){rS(this._srcs,e)}dispose(){let e=J(this.ctx.currentTime,0);iS(this._srcs,e),aS(this._nodes),this._srcs.length=0}},sS=e=>e<.1,cS=class e{static supports(e){return!!(e&&e.turbo)}constructor(t,n,r){this.ctx=t;let i=r||{};this.level=J(i.level,1),this.maxTurboRpm=J(i.maxTurboRpm,15e4),this.flutterMode=i.flutter!==!1,this.surgeLevel=q(J(i.surgeLevel,1),0,3),this.spool=0,this.boost=0,this.boostBar=0,this.turboRpm=0,this._vent=0,this._surge=0,this._climb=0,this._liftRate=13,this._liftPitch=1,this._liftTau=.26,this._lastBov=-1e9,this._prevThrottle=0,this._prevShifting=!1,this._rnd=Qx(1374496523),this._srcs=[],this._nodes=[];let a=e=>(this._nodes.push(e),e);if(this.out=a(t.createGain()),this.out.gain.value=this.level,this._graphBuilt=!1,this.setProfile(n),!e.supports(n))return;this.bus=a(t.createGain()),this.airLP=a(t.createBiquadFilter()),this.airLP.type=`lowpass`,this.airLP.frequency.value=Gx,this.airLP.Q.value=-3.01,this.airShelf=a(t.createBiquadFilter()),this.airShelf.type=`highshelf`,this.airShelf.frequency.value=2600,this.airShelf.gain.value=Kx,this.bus.connect(this.airLP),this.airLP.connect(this.airShelf),this.airShelf.connect(this.out);let o=tS(t,`white`,1.07);this._srcs.push(o),this.whineOsc=c(t.createOscillator()),this.whineOsc.setPeriodicWave(uS(t)),this.whineOsc.frequency.value=1200,this._srcs.push(this.whineOsc),this.whineBP=a(t.createBiquadFilter()),this.whineBP.type=`bandpass`,this.whineBP.frequency.value=1500,this.whineBP.Q.value=1.5,this.whineGain=a(t.createGain()),this.whineGain.gain.value=0,this.whineDrive=a(t.createGain()),this.whineDrive.gain.value=1,this.whineShaper=a(t.createWaveShaper()),this.whineShaper.curve=dS(1024,.55),this.whineShaper.oversample=`4x`,this.whineOsc.connect(this.whineDrive),this.whineDrive.connect(this.whineShaper),this.whineShaper.connect(this.whineBP),this.whineBP.connect(this.whineGain),this.whineGain.connect(this.bus);let s=tS(t,`pink`,.29);this._srcs.push(s),this.grainBP=a(t.createBiquadFilter()),this.grainBP.type=`bandpass`,this.grainBP.frequency.value=55,this.grainBP.Q.value=.6,this.grainDepth=a(t.createGain()),this.grainDepth.gain.value=0,s.connect(this.grainBP),this.grainBP.connect(this.grainDepth),this.grainDepth.connect(this.whineGain.gain),this.wander1=c(t.createOscillator()),this.wander1.type=`sine`,this.wander1.frequency.value=.31,this.wander2=c(t.createOscillator()),this.wander2.type=`sine`,this.wander2.frequency.value=2.17,this._srcs.push(this.wander1,this.wander2),this.wanderDepth1=a(nS(t,this.wander1,0,this.whineOsc.detune)),this.wanderDepth2=a(nS(t,this.wander2,0,this.whineOsc.detune)),this.shaftOsc=c(t.createOscillator()),this.shaftOsc.type=`sine`,this.shaftOsc.frequency.value=180,this._srcs.push(this.shaftOsc),this.shaftDepth=a(t.createGain()),this.shaftDepth.gain.value=0,this.shaftOsc.connect(this.shaftDepth),this.shaftDepth.connect(this.whineGain.gain),this.hissBP=a(t.createBiquadFilter()),this.hissBP.type=`bandpass`,this.hissBP.frequency.value=2e3,this.hissBP.Q.value=.8,this.hissGain=a(t.createGain()),this.hissGain.gain.value=0,o.connect(this.hissBP),this.hissBP.connect(this.hissGain),this.hissGain.connect(this.bus),this.hissGrain=a(t.createGain()),this.hissGrain.gain.value=0,this.grainBP.connect(this.hissGrain),this.hissGrain.connect(this.hissGain.gain),this.whineNoiseBP=a(t.createBiquadFilter()),this.whineNoiseBP.type=`bandpass`,this.whineNoiseBP.frequency.value=800,this.whineNoiseBP.Q.value=6,this.whineNoiseGain=a(t.createGain()),this.whineNoiseGain.gain.value=0,o.connect(this.whineNoiseBP),this.whineNoiseBP.connect(this.whineNoiseGain),this.whineNoiseGain.connect(this.bus);let l=tS(t,`pink`,1.31);this._srcs.push(l),this.airflowHP=a(t.createBiquadFilter()),this.airflowHP.type=`highpass`,this.airflowHP.frequency.value=280,this.airflowHP.Q.value=.5,this.airflowLP=a(t.createBiquadFilter()),this.airflowLP.type=`lowpass`,this.airflowLP.frequency.value=1400,this.airflowLP.Q.value=.5,this.airflowGain=a(t.createGain()),this.airflowGain.gain.value=0,l.connect(this.airflowHP),this.airflowHP.connect(this.airflowLP),this.airflowLP.connect(this.airflowGain),this.airflowGain.connect(this.bus),this.bovBP=a(t.createBiquadFilter()),this.bovBP.type=`bandpass`,this.bovBP.frequency.value=2400,this.bovBP.Q.value=7,this.bovGain=a(t.createGain()),this.bovGain.gain.value=0,o.connect(this.bovBP),this.bovBP.connect(this.bovGain),this.bovGain.connect(this.bus),this.wgBP=a(t.createBiquadFilter()),this.wgBP.type=`bandpass`,this.wgBP.frequency.value=1500,this.wgBP.Q.value=.6,this.wgLevel=a(t.createGain()),this.wgLevel.gain.value=0,this.wgOsc=c(t.createOscillator()),this.wgOsc.type=`sawtooth`,this.wgOsc.frequency.value=24,this._srcs.push(this.wgOsc),this.wgShaper=a(t.createWaveShaper()),this.wgShaper.curve=fS(1024),this.wgShaper.oversample=`2x`,this.wgAM=a(t.createGain()),this.wgAM.gain.value=.05,this.wgOsc.connect(this.wgShaper),this.wgShaper.connect(this.wgAM.gain),o.connect(this.wgBP),this.wgBP.connect(this.wgAM),this.wgAM.connect(this.wgLevel),this.wgLevel.connect(this.bus),this.wgJitter=a(t.createGain()),this.wgJitter.gain.value=6,this.grainBP.connect(this.wgJitter),this.wgJitter.connect(this.wgOsc.frequency),this.wgGrain=a(t.createGain()),this.wgGrain.gain.value=0,this.grainBP.connect(this.wgGrain),this.wgGrain.connect(this.wgLevel.gain),this.hiOsc=c(t.createOscillator()),this.hiOsc.type=`sine`,this.hiOsc.frequency.value=6e3,this._srcs.push(this.hiOsc),this.hiGain=a(t.createGain()),this.hiGain.gain.value=0,this.hiOsc.connect(this.hiGain),this.hiGain.connect(this.out),this.hiGrain=a(t.createGain()),this.hiGrain.gain.value=0,this.grainBP.connect(this.hiGrain),this.hiGrain.connect(this.hiGain.gain),this.hiWander=a(nS(t,this.wander2,0,this.hiOsc.detune)),this.buzzOsc=c(t.createOscillator()),this.buzzOsc.type=`sawtooth`,this.buzzOsc.frequency.value=60,this._srcs.push(this.buzzOsc),this.buzzBP=a(t.createBiquadFilter()),this.buzzBP.type=`bandpass`,this.buzzBP.frequency.value=1500,this.buzzBP.Q.value=1.2,this.buzzGain=a(t.createGain()),this.buzzGain.gain.value=0,this.buzzOsc.connect(this.buzzBP),this.buzzBP.connect(this.buzzGain),this.buzzGain.connect(this.bus),this.bovHissHP=a(t.createBiquadFilter()),this.bovHissHP.type=`highpass`,this.bovHissHP.frequency.value=1800,this.bovHissHP.Q.value=-3.01,this.bovHissGain=a(t.createGain()),this.bovHissGain.gain.value=0,o.connect(this.bovHissHP),this.bovHissHP.connect(this.bovHissGain),this.bovHissGain.connect(this.bus),this.surgeOsc=c(t.createOscillator()),this.surgeOsc.type=`sawtooth`,this.surgeOsc.frequency.value=16,this._srcs.push(this.surgeOsc),this.surgeShaper=a(t.createWaveShaper()),this.surgeShaper.curve=fS(1024),this.surgeShaper.oversample=`2x`,this.surgeOsc.connect(this.surgeShaper),this.surgeBus=a(t.createGain()),this.surgeBus.gain.value=.7,this.surgeLP=a(t.createBiquadFilter()),this.surgeLP.type=`lowpass`,this.surgeLP.frequency.value=6500,this.surgeLP.Q.value=-3.01,this.surgeBus.connect(this.surgeLP),this.surgeLP.connect(this.out),this.whooshBP=a(t.createBiquadFilter()),this.whooshBP.type=`bandpass`,this.whooshBP.frequency.value=5e3,this.whooshBP.Q.value=.7,this.whooshGain=a(t.createGain()),this.whooshGain.gain.value=0,o.connect(this.whooshBP),this.whooshBP.connect(this.whooshGain),this.whooshGain.connect(this.surgeLP),this.whooshGrain=a(t.createGain()),this.whooshGrain.gain.value=0,this.grainBP.connect(this.whooshGrain),this.whooshGrain.connect(this.whooshGain.gain),this.surgeSend=a(t.createGain()),this.surgeSend.gain.value=.55,this.surgeJitter=a(t.createGain()),this.surgeJitter.gain.value=0,this.grainBP.connect(this.surgeJitter),this.surgeJitter.connect(this.surgeOsc.frequency),this.surgeBody=a(t.createBiquadFilter()),this.surgeBody.type=`bandpass`,this.surgeBody.frequency.value=3e3,this.surgeBody.Q.value=1.1,this.surgeBodyAM=a(t.createGain()),this.surgeBodyAM.gain.value=0,this.surgeBodyLvl=a(t.createGain()),this.surgeBodyLvl.gain.value=0,o.connect(this.surgeBody),this.surgeBody.connect(this.surgeBodyAM),this.surgeBodyAM.connect(this.surgeBodyLvl),this.surgeBodyLvl.connect(this.surgeBus),this.surgeBodyLvl.connect(this.surgeSend),this.surgeBodyDepth=a(t.createGain()),this.surgeBodyDepth.gain.value=1,this.surgeShaper.connect(this.surgeBodyDepth),this.surgeBodyDepth.connect(this.surgeBodyAM.gain),this.surgeChirp=a(t.createGain()),this.surgeChirp.gain.value=0,this.surgeShaper.connect(this.surgeChirp),this.fwOsc=c(t.createOscillator()),this.fwOsc.type=`sine`,this.fwOsc.frequency.value=7e3,this._srcs.push(this.fwOsc),this.fwBP=a(t.createBiquadFilter()),this.fwBP.type=`bandpass`,this.fwBP.frequency.value=7e3,this.fwBP.Q.value=3,this.fwNoise=a(t.createGain()),this.fwNoise.gain.value=3.2,this.fwTone=a(t.createGain()),this.fwTone.gain.value=.2,o.connect(this.fwBP),this.fwBP.connect(this.fwNoise),this.hiSurgeAM=a(t.createGain()),this.hiSurgeAM.gain.value=0,this.hiSurgeLvl=a(t.createGain()),this.hiSurgeLvl.gain.value=0,this.fwOsc.connect(this.fwTone),this.fwTone.connect(this.hiSurgeAM),this.fwNoise.connect(this.hiSurgeAM),this.hiSurgeAM.connect(this.hiSurgeLvl),this.hiSurgeLvl.connect(this.out),this.surgeShaper.connect(this.hiSurgeAM.gain),this.hiChirp=a(t.createGain()),this.hiChirp.gain.value=0,this.surgeShaper.connect(this.hiChirp),this.hiChirp.connect(this.fwOsc.frequency),this.hiChirpN=a(t.createGain()),this.hiChirpN.gain.value=0,this.surgeShaper.connect(this.hiChirpN),this.hiChirpN.connect(this.fwBP.frequency),this.surgeChirp.connect(this.surgeBody.frequency),this.surgeEdge=a(t.createBiquadFilter()),this.surgeEdge.type=`bandpass`,this.surgeEdge.frequency.value=5200,this.surgeEdge.Q.value=.8,this.surgeEdgeAM=a(t.createGain()),this.surgeEdgeAM.gain.value=0,this.surgeEdgeLvl=a(t.createGain()),this.surgeEdgeLvl.gain.value=0,o.connect(this.surgeEdge),this.surgeEdge.connect(this.surgeEdgeAM),this.surgeEdgeAM.connect(this.surgeEdgeLvl),this.surgeEdgeLvl.connect(this.surgeBus),this.surgeEdgeDepth=a(t.createGain()),this.surgeEdgeDepth.gain.value=1,this.surgeShaper.connect(this.surgeEdgeDepth),this.surgeEdgeDepth.connect(this.surgeEdgeAM.gain),this._graphBuilt=!0,this.enabled=!0}get input(){return null}get output(){return this.out}get state(){return{spool:this.spool,boost:this.boost,boostBar:this.boostBar,turboRpm:this.turboRpm,surge:this._surge}}setProfile(e){this.profile=e;let t=e&&e.turbo||null;this.turbo=t,this.enabled=!!t&&this._graphBuilt===!0,this.inertia=q(J(t&&t.inertia,.4),.05,3),this.maxBoost=q(J(t&&t.maxBoost,1),0,5),this.bovLevel=q(J(t&&t.bov,.5),0,2),this.surgeTrim=q(J(t&&t.surge,1),0,3),this.valve=Math.round(q(J(t&&t.valve,1),0,2)),this.flutterHz=q(J(t&&t.flutterHz,13),3,30),this.screamer=J(t&&t.screamer,0)>=.5,this.antiLag=J(t&&t.antiLag,0)>=.5;let n=J(e&&e.redlineRpm,7e3);this.boostRpm=Math.min(q(J(t&&t.boostRpm,3500),800,9e3),.65*n);let r=.5*J(t&&t.whineOrder,70);this.whineRef=q(n/120*r,200,qx)}update(e){if(!this.enabled)return;let t=J(e.now,0),n=q(J(e.dt,1/60),0,.25),r=q(J(e.load,0),0,1),i=q(J(e.throttle,0),0,1),a=q(J(e.rpmNorm,0),0,1),o=!!e.shifting;this._als=this.antiLag&&i<.12&&a>.15;let s=J(e.rpm,0),c=Math.max(.6*J(this.profile&&this.profile.redlineRpm,7e3),this.boostRpm+1500),l=q((s-this.boostRpm)/(c-this.boostRpm),0,1),u=e.limiter?Math.max(r,.95*i):r,d=this._als?.7*(.3+.7*a):q(u*(.08+.92*l),0,1),f=i<.12,p=q((d-this.spool)*3,0,1);this._climb+=(p-this._climb)*Math.min(1,n/.08);let m=d>this.spool?this.inertia*1.1:this.inertia*(f?.45:1.3),h=n>0?1-Math.exp(-n/Math.max(.001,m)):0;this.spool+=(d-this.spool)*h;let g=.04+.07*a;this.spool<g&&(this.spool=g),this.spool=q(J(this.spool,g),0,1),this._vent>0&&(this._vent*=Math.exp(-n/.18),this._vent<.001&&(this._vent=0));let _=this.spool*this.spool;this.boost=q(_*(1-.92*this._vent),0,1),this.boostBar=this.boost*this.maxBoost,this.turboRpm=this.spool*this.maxTurboRpm;let v=Math.max(120,this.whineRef*Math.max(.05,this.spool)**1.55);X(this.whineOsc.frequency,v,t,K,1e3),X(this.whineBP.frequency,v*1.25,t,K,1600),X(this.whineNoiseBP.frequency,v,t,K,800);let y=this.spool**2,b=q(Math.max(r,i*.7),0,1),x=.085*y*(.62+.38*b);Y(this.whineGain.gain,x,t,K),Y(this.whineNoiseGain.gain,.3*y*(.5+.5*b),t,K),Y(this.airflowGain.gain,.2*(.15+.85*this.spool)*this.spool*(.25+.75*b),t,.05),X(this.airflowLP.frequency,900+1300*this.spool,t,K,1400);let S=26*(1-.75*this.spool);Y(this.wanderDepth1.gain,S,t,.08),Y(this.wanderDepth2.gain,S*.4,t,.08);let C=.55-.3*this.spool;Y(this.grainDepth.gain,x*C,t,.05),Y(this.whineDrive.gain,.8+.9*this.spool,t,K),X(this.grainBP.frequency,28+120*this.spool,t,K,55),X(this.shaftOsc.frequency,q(v/11,4,400),t,K,180),Y(this.shaftDepth.gain,x*(.52-.28*this.spool),t,K);let w=q((this.spool-.4)/.3,0,1)*q((a-.4)/.3,0,1),ee=w*i*(this.screamer?1.3:.7);X(this.wgOsc.frequency,18+12*w+8*a,t,.05,24),X(this.wgBP.frequency,(this.screamer?900:1400)+1300*this.spool,t,K,1500),Y(this.wgLevel.gain,ee,t,.05),Y(this.wgGrain.gain,ee*.5,t,.05);let te=.1*y*(.45+.55*b);Y(this.hissGain.gain,te,t,K),Y(this.hissGrain.gain,te*.65,t,.05),X(this.hissBP.frequency,q(v*2.2,900,4200),t,K,2e3);let ne=.18*(q((this.boost-.12)/.45,0,1)*i*(1-.75*a)+.6*this._climb*Math.sqrt(this.spool));Y(this.whooshGain.gain,ne,t,.04),Y(this.whooshGrain.gain,ne*.6,t,.05),X(this.whooshBP.frequency,q(4e3+3500*this.spool,3e3,8e3),t,K,5e3);let re=.08*q((this.spool-.62)/.25,0,1)*b;X(this.buzzOsc.frequency,q(v/11,20,400),t,K,60),X(this.buzzBP.frequency,q(v*1.5,400,6e3),t,K,1500),Y(this.buzzGain.gain,re,t,K),X(this.hiOsc.frequency,q(5e3+8e3*this.spool**1.4,3e3,15e3),t,K,6e3);let ie=.022*y*(.55+.45*b);Y(this.hiGain.gain,ie,t,K),Y(this.hiGrain.gain,ie*.4,t,.05),Y(this.hiWander.gain,12*(1-.6*this.spool),t,.08);let ae=q(J(e.evBov,0),0,1);ae>0&&this._fireBov(t,ae),this._stepSurge(t,n,i,a,o,e),this._prevLimiter=!!e.limiter,this._prevThrottle=i,this._prevShifting=o}_stepSurge(e,t,n,r,i,a){this._surge*=Math.exp(-t/this._liftTau),this._closedT=sS(n)?(this._closedT||0)+t:0,this._surge<.001&&(this._surge=0);let o=n<.1,s=o&&this._prevThrottle>=.25,c=this._prevThrottle-n>.2&&n<.5,l=i&&!this._prevShifting,u=this.flutterMode===!1||this.antiLag?0:1,d=q((this.spool-.12)/.28,0,1)*(this.valve===0?1:q(1-.9*this.bovLevel,.15,1))*u,f=a.gearbox===`dct`?.35:a.gearbox===`auto`?.15:1,p=s||c?d:l?d*f:0;if(p>0){if(this._surge<.1){let e=()=>this._rnd();this._liftRate=this.flutterHz*(.7+.45*r+.35*this.boost)*(.85+.3*e()),this._liftPitch=(.85+.25*r)*(.92+.16*e()),this._liftTau=.1+.1*e()+.04*this.boost}this._surge=Math.max(this._surge,p)}o&&d>.06&&this._closedT<.15&&(this._surge=Math.max(this._surge,d*.8));let m=n>.5||n>this._prevThrottle+.05;!o&&!i&&m&&(this._surge*=Math.exp(-t/.11));let h=q(this._surge,0,1),g=this._liftRate*(.7+.45*h);X(this.surgeOsc.frequency,g,e,.03,16),X(this.surgeBody.frequency,(2400+700*h+500*r)*this._liftPitch,e,.04,3e3),X(this.surgeEdge.frequency,(4600+600*h+600*r)*this._liftPitch,e,.04,5200),Y(this.surgeChirp.gain,600*h,e,.04),Y(this.surgeJitter.gain,18*h,e,.04);let _=q(J(a.overrun,0),0,1),v=(.6+.4*r)*(.8+.3*_),y=this.surgeLevel*this.surgeTrim;Y(this.surgeBodyLvl.gain,6.5*y*h*v,e,.03),Y(this.surgeEdgeLvl.gain,.25*y*h*h*v,e,.03);let b=q(5500+3500*this.spool,4500,9500);X(this.fwOsc.frequency,b,e,.03,7e3),X(this.fwBP.frequency,b,e,.03,7e3),Y(this.hiSurgeLvl.gain,1.6*y*h*v,e,.03),Y(this.hiChirp.gain,900*h,e,.04),Y(this.hiChirpN.gain,900*h,e,.04)}release(){let e=J(this.ctx.currentTime,0);this.enabled=!1,this.out.gain.setTargetAtTime(0,e,.07),this.surgeSend.gain.setTargetAtTime(0,e,.07);for(let t of this._srcs)try{t.stop(e+.5)}catch{}this._srcs.length=0}_fireBov(e,t){if(this.valve===0)return;let n=this.valve===2,r=q(this.boost,0,1),i=q(this.bovLevel*1.35*t*(.15+.85*r)*(n?.3:1),5e-4,2.5),a=q(.11+.26*r,.05,.5),o=J(e,0)+Xx,s=this.bovBP.frequency;s.cancelScheduledValues(o),s.setValueAtTime(Zx((n?1300:2600)+1800*r,2800),o),s.exponentialRampToValueAtTime(Zx((n?300:520)+180*r,620),o+a*.8);let c=this.bovBP.Q;c.cancelScheduledValues(o),c.setValueAtTime(n?1.5:4.5,o),c.linearRampToValueAtTime(n?3:11,o+a*.6);let l=this.bovHissGain.gain;l.cancelScheduledValues(o),n||(l.setValueAtTime(4e-4,o),l.linearRampToValueAtTime(i*.45,o+.008),l.exponentialRampToValueAtTime(4e-4,o+a*.9),l.setValueAtTime(0,o+a));let u=this.bovGain.gain;u.cancelScheduledValues(o),u.setValueAtTime(4e-4,o),u.linearRampToValueAtTime(i,o+.012),u.exponentialRampToValueAtTime(4e-4,o+a),u.setValueAtTime(0,o+a+.005),this._vent=q(this.bovLevel,.15,1),this.spool*=.97,this._lastBov=J(e,0)}start(e){rS(this._srcs,e)}dispose(){let e=J(this.ctx.currentTime,0);iS(this._srcs,e),aS(this._nodes),this._srcs.length=0,this.enabled=!1}},lS=new WeakMap;function uS(e){let t=lS.get(e);if(t)return t;let n=new Float32Array(11),r=new Float32Array(11);for(let e=1;e<=10;e++){let t=e%2?1.25:.8;r[e]=1/e**1.4*t}let i=e.createPeriodicWave(n,r,{disableNormalization:!1});return lS.set(e,i),i}function dS(e=1024,t=.55){let n=new Float32Array(e);for(let r=0;r<e;r++){let i=r/(e-1)*2-1,a=i>=0?2.4*(1+t):2.4*(1-t);n[r]=Math.tanh(a*i)/Math.tanh(a)}return n}function fS(e=1024){let t=new Float32Array(e),n=.24;for(let r=0;r<e;r++){let i=r/(e-1),a=i<n?.5-.5*Math.cos(Math.PI*i/n):1;t[r]=a*Math.exp(-4.5*Math.max(0,i-n))}return t}var pS=Object.freeze({bang:Object.freeze({bus:`combustion`,fA:112,qA:1.6,fB:680,qB:2,mixB:.58,atk:.005,dec:.19,lvl:1}),crackle:Object.freeze({bus:`combustion`,fA:700,qA:3,fB:1850,qB:3.6,mixB:.62,atk:.003,dec:.055,lvl:.5}),clunk:Object.freeze({bus:`mechanical`,fA:330,qA:7,fB:1250,qB:6,mixB:.45,atk:.0035,dec:.075,lvl:.62}),thump:Object.freeze({bus:`mechanical`,fA:95,qA:2.2,fB:320,qB:3,mixB:.35,atk:.004,dec:.13,lvl:.8}),click:Object.freeze({bus:`mechanical`,fA:1500,qA:5,fB:2800,qB:6,mixB:.4,atk:.0018,dec:.02,lvl:.16})}),mS=class{constructor(e,t,n){this.ctx=e;let r=n||{};this.level=J(r.level,1),this.lookahead=q(J(r.lookahead,Xx),0,.05),this.overrunCrackle=r.overrunCrackle!==!1,this.maxPerFrame=q(Math.round(J(r.maxPerFrame,18)),1,48),this.stolen=0,this.fired=0,this.pops=[],this._next=0,this._nextPop=0,this._prevPhase=``,this._syncClicks=0,this._rnd=Qx(625341585),this._srcs=[],this._nodes=[];let i=e=>(this._nodes.push(e),e);this.out=i(e.createGain()),this.combOut=i(e.createGain()),this.makeup=q(J(r.makeup,9),1,40),this.out.gain.value=this.level*this.makeup,this.combOut.gain.value=this.level*this.makeup;let a=q(Math.round(J(r.voices,16)),2,40),o=Math.max(1,Math.round(a*.62));this.voices=Array(a),this.pools={combustion:[],mechanical:[]},this._cursor={combustion:0,mechanical:0};for(let t=0;t<a;t++){let n=tS(e,`white`,t*.137%1.9);this._srcs.push(n);let r=i(e.createBiquadFilter());r.type=`bandpass`,r.frequency.value=1e3,r.Q.value=6;let a=i(e.createBiquadFilter());a.type=`bandpass`,a.frequency.value=3e3,a.Q.value=8;let s=i(e.createGain());s.gain.value=.5;let c=i(e.createGain());c.gain.value=0;let l=t<o?`combustion`:`mechanical`;n.connect(r),n.connect(a),r.connect(c),a.connect(s),s.connect(c),c.connect(l===`combustion`?this.combOut:this.out);let u={bpA:r,bpB:a,mixB:s,gain:c,busyUntil:-1,bus:l};this.voices[t]=u,this.pools[l].push(u)}this.setProfile(t)}get input(){return null}get output(){return this.out}get combustionOutput(){return this.combOut}setProfile(e){this.profile=e;let t=q(J(e&&e.cylinders,6),1,16);this.cyl=t,this.idleRpm=J(e&&e.idleRpm,800),this.sizeF=(6/t)**.35,this.sizeA=(t/6)**.3,this.burstCount=q(1+Math.round(t/5),1,3)}trigger(e,t,n,r,i){let a=pS[e]||pS.click,o=J(this.ctx.currentTime,0),s=Math.max(J(t,o),o+this.lookahead),c=q(J(n,0)*a.lvl,8e-4,4),l=q(J(r,1),.2,5),u=q(a.dec*q(J(i,1),.2,6),.004,1.5),d=s+a.atk+u+.002,f=a.bus===`combustion`?`combustion`:`mechanical`,p=this.pools[f],m=p.length,h=-1;for(let e=0;e<m;e++){let t=(this._cursor[f]+e)%m;if(p[t].busyUntil<=s){h=t;break}}if(h<0){let e=0;for(let t=1;t<m;t++)p[t].busyUntil<p[e].busyUntil&&(e=t);h=e,this.stolen++}this._cursor[f]=(h+1)%m;let g=p[h];g.bpA.frequency.cancelScheduledValues(s),g.bpA.frequency.setValueAtTime(Zx(a.fA*l,1e3),s),g.bpA.Q.setValueAtTime(J(a.qA,4),s),g.bpB.frequency.cancelScheduledValues(s),g.bpB.frequency.setValueAtTime(Zx(a.fB*l,3e3),s),g.bpB.Q.setValueAtTime(J(a.qB,6),s),g.mixB.gain.cancelScheduledValues(s),g.mixB.gain.setValueAtTime(J(a.mixB,.5),s);let _=g.gain.gain;return _.cancelScheduledValues(s),_.setValueAtTime(4e-4,s),_.linearRampToValueAtTime(c,s+a.atk),_.exponentialRampToValueAtTime(4e-4,s+a.atk+u),_.setValueAtTime(0,d),g.busyUntil=d,this.fired++,f===`combustion`&&this.pops.length<64&&this.pops.push({time:s,amp:q(J(n,0),0,1)}),h}update(e){let t=J(e.now,0),n=Math.max(0,J(e.rpm,0)),r=q(J(e.rpmNorm,0),0,1),i=this._rnd,a=this.maxPerFrame,o=q(J(e.evCut,0),0,1);if(o>0&&a>0){let e=Math.min(a,this.burstCount),n=t+this.lookahead+i()*.008;for(let t=0;t<e;t++){let e=.72**t*(.55+.65*i()),s=q(.55*o*this.sizeA*e*(.5+.7*r),.001,1),c=t===0||i()<.45?`bang`:`crackle`;this.trigger(c,n,s,this.sizeF*(.75+.6*i()),.7+.8*i()),n+=.012+i()*.048,a--}}let s=q(J(e.evPop,0),0,1);if(s>0&&a>0){let e=i(),n=.5*s+.5*r,o;o=e<.34-.16*n?`crack`:e<.8-.1*n?`double`:`stutter`;let c=q(Math.round((1+6/Math.max(3,this.cyl))*(.6+.7*i())),2,3),l=Math.min(a,o===`crack`?1:o===`double`?2:c),u=o===`crack`?2.6:o===`double`?2:1.6,d=.42+1.05*i()*i(),f=t+this.lookahead+i()*.006;for(let e=0;e<l;e++){let t=.86**e*(.6+.8*i()),n=q(u*d*s*this.sizeA*t*(.5+.65*r),.001,2),c=e===0||i()<.5?`bang`:`crackle`,l=this.sizeF*(.62+.7*i())*(1-.22*s);this.trigger(c,f,n,l,.7+.9*i());let p=o===`stutter`?.55:1;f+=(.055+i()*.16)*(.6+4/Math.max(3,this.cyl))*p,a--}}let c=q(J(e.evLash,0),0,1);if(c>0&&a>0){let e=t+this.lookahead;this.trigger(`clunk`,e,q(.5*c,.001,1),.9+.25*i(),.8+.5*c),a--,c>.35&&a>0&&(this.trigger(`clunk`,e+.018+i()*.012,q(.16*c,.001,1),1.3,.5),a--)}let l=q(J(e.evEngage,0),0,1);l>0&&a>0&&(this.trigger(`thump`,t+this.lookahead,q(.45*l,.001,1),1,.8+.6*l),a--);let u=e.shiftPhase||``;u===`sync`?(this._prevPhase!==`sync`&&(this._syncClicks=0,this._syncNext=t),this._syncClicks<1&&t>=J(this._syncNext,t)&&a>0&&(this.trigger(`click`,t+this.lookahead,.3+.22*i(),.85+.4*i(),1),this._syncClicks++,this._syncNext=t+.035+i()*.03,a--)):this._prevPhase===`sync`&&(this._syncClicks=0),this._prevPhase=u;let d=q(J(e.overrun,0),0,1),f=e.popIntensity==null?d*.55:q(J(e.popIntensity,0),0,1);if(!(this.overrunCrackle&&f>.3&&n>this.idleRpm*1.5&&!e.shifting)){this._nextPop=t;return}this._nextPop<t&&(this._nextPop=t+.01+i()*.04);let p=t+.12,m=.35+1.2*f*(.35+.65*r)*(this.cyl/6);for(;this._nextPop<p&&a>0;){let e=Math.max(this._nextPop,t+this.lookahead),n=q(.3*f*this.sizeA*(.25+1.5*i()*i())*(.45+.55*r),.001,1);this.trigger(i()<.4?`bang`:`crackle`,e,n,this.sizeF*(.7+.9*i()),.6+.9*i()),this._nextPop=e+(.25+2.2*i()*i())/Math.max(.4,m),a--}this._nextPop<t&&(this._nextPop=t)}start(e){rS(this._srcs,e)}dispose(){let e=J(this.ctx.currentTime,0);iS(this._srcs,e),aS(this._nodes),this._srcs.length=0,this.voices.length=0}},hS=(e,t,n)=>e<t?t:e>n?n:e,gS=(e,t=0)=>typeof e==`number`&&isFinite(e)?e:t,_S=.02;function vS(e,t,n,r=_S){if(!e)return;let i=gS(t,0);e.setTargetAtTime(i,Math.max(0,gS(n,0)),r>0?r:_S)}function yS(e,t,n){let r=Math.max(1,Math.floor(e.sampleRate*t)),i=e.createBuffer(1,r,e.sampleRate),a=i.getChannelData(0),o=0;for(let e=0;e<r;e++){let t=Math.random()*2-1;n?(o=(o+.02*t)/1.02,a[e]=o*3.5):a[e]=t}let s=Math.min(2048,r>>2);for(let e=0;e<s;e++){let t=e/s;a[e]=a[e]*t+a[r-s+e]*(1-t)}return i}var bS=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.cyl=t.cylinders,this.pulseOrder=Math.max(.5,this.cyl/2/Math.max(1,t.banks.length)),this.src=c(e.createBufferSource()),this.src.buffer=yS(e,2.7,!1),this.src.loop=!0,this.hp=e.createBiquadFilter(),this.hp.type=`highpass`,this.hp.frequency.value=55,this.body=e.createBiquadFilter(),this.body.type=`lowpass`,this.body.frequency.value=900,this.body.Q.value=.9,this.peak=e.createBiquadFilter(),this.peak.type=`peaking`,this.peak.frequency.value=140,this.peak.Q.value=1.4,this.peak.gain.value=7,this.level=e.createGain(),this.level.gain.value=0,this.pulse=c(e.createOscillator()),this.pulse.type=`sawtooth`,this.pulse.frequency.value=40,this.pulseDepth=e.createGain(),this.pulseDepth.gain.value=0,this.out=e.createGain(),this.out.gain.value=1,this.src.connect(this.hp),this.hp.connect(this.peak),this.peak.connect(this.body),this.body.connect(this.level),this.level.connect(this.out),this.pulse.connect(this.pulseDepth),this.pulseDepth.connect(this.level.gain),this.gain=hS(gS(n.gain,1),0,4),this.started=!1}get input(){return null}get output(){return this.out}start(e){if(!this.started){this.started=!0;try{this.src.start(e)}catch{}try{this.pulse.start(e)}catch{}}}stop(e){try{this.src.stop(e)}catch{}try{this.pulse.stop(e)}catch{}this.started=!1}update(e){let t=gS(e.now,0),n=hS(gS(e.rpmNorm,0),0,1),r=hS(gS(e.load,0),0,1),i=hS(gS(e.overrun,0),0,1),a=hS(hS(gS(e.f0,10),.05,4e3)*this.pulseOrder*2,10,6e3),o=.3+.7*r,s=this.gain*.28*o*(.25+.75*n)*(1+.35*i);vS(this.level.gain,s,t),vS(this.pulse.frequency,a,t),vS(this.pulseDepth.gain,Math.min(s*.85,s*(1.1-.7*n)),t),vS(this.peak.frequency,hS(a,30,2e3),t),vS(this.body.frequency,hS(450+2600*r+1800*n,120,9e3),t),vS(this.hp.frequency,hS(40+30*n,20,400),t)}dispose(){for(let e of[this.src,this.hp,this.peak,this.body,this.level,this.pulse,this.pulseDepth,this.out])e&&e.disconnect&&e.disconnect()}},xS=class{constructor(e,t,n={}){this.ctx=e,this.profile=t;let r=Math.max(.5,t.cylinders/4),i=(t.idleRpm+t.redlineRpm)/2/120;for(;r*i<38&&r<8;)r*=2;for(;r*i>85&&r>.5;)r/=2;this.order=r,this.subHz=r*i,this.osc=c(e.createOscillator()),this.osc.type=`sine`,this.osc.frequency.value=40,this.shaper=e.createWaveShaper(),this.shaper.curve=this._curve(),this.shaper.oversample=`2x`,this.tone=e.createBiquadFilter(),this.tone.type=`lowpass`,this.tone.frequency.value=220,this.tone.Q.value=.7,this.level=e.createGain(),this.level.gain.value=0,this.out=e.createGain(),this.out.gain.value=hS(gS(n.gain,1),0,4),this.osc.connect(this.shaper),this.shaper.connect(this.tone),this.tone.connect(this.level),this.level.connect(this.out),this.started=!1}_curve(e=2048){let t=new Float32Array(e);for(let n=0;n<e;n++){let r=n/(e-1)*2-1;t[n]=Math.tanh(1.8*r)*.92+.08*Math.tanh(2.6*r*r*Math.sign(r))}return t}get input(){return null}get output(){return this.out}start(e){if(!this.started){this.started=!0;try{this.osc.start(e)}catch{}}}stop(e){try{this.osc.stop(e)}catch{}this.started=!1}update(e){let t=gS(e.now,0),n=hS(gS(e.f0,10),.05,4e3),r=hS(gS(e.load,0),0,1),i=hS(gS(e.rpmNorm,0),0,1),a=hS(gS(e.overrun,0),0,1);vS(this.osc.frequency,hS(n*this.order,12,400),t);let o=.34*(.18+.82*r**.75)*(1-.45*i)*(1-.6*a);vS(this.level.gain,o,t),vS(this.tone.frequency,hS(150+260*r,80,800),t)}dispose(){for(let e of[this.osc,this.shaper,this.tone,this.level,this.out])e&&e.disconnect&&e.disconnect()}},SS=class{constructor(e,t,n={}){this.ctx=e,this.depthCents=hS(gS(n.detuneCents,7),0,60),this.depthGain=hS(gS(n.tremolo,.1),0,.6);let r=[.237,1.703,5.317];this.lfos=r.map(t=>{let n=c(e.createOscillator());n.type=`sine`,n.frequency.value=t;let i=e.createGain();return i.gain.value=1/r.length,n.connect(i),{osc:n,gain:i}}),this.rough=c(e.createBufferSource()),this.rough.buffer=yS(e,3.1,!0),this.rough.loop=!0,this.roughLP=e.createBiquadFilter(),this.roughLP.type=`lowpass`,this.roughLP.frequency.value=22,this.roughGain=e.createGain(),this.roughGain.gain.value=.9,this.rough.connect(this.roughLP),this.roughLP.connect(this.roughGain),this.bus=e.createGain(),this.bus.gain.value=1;for(let e of this.lfos)e.gain.connect(this.bus);this.roughGain.connect(this.bus),this.detune=e.createGain(),this.detune.gain.value=0,this.tremolo=e.createGain(),this.tremolo.gain.value=0,this.bus.connect(this.detune),this.bus.connect(this.tremolo),this.started=!1}get input(){return null}get output(){return this.bus}setEventSource(e){this._event=e}start(e){if(!this.started){this.started=!0;for(let t of this.lfos)try{t.osc.start(e)}catch{}try{this.rough.start(e)}catch{}}}stop(e){for(let t of this.lfos)try{t.osc.stop(e)}catch{}try{this.rough.stop(e)}catch{}this.started=!1}update(e){let t=gS(e.now,0),n=hS(gS(e.rpmNorm,0),0,1),r=hS(gS(e.load,0),0,1),i=(1-n)*(1-.55*r),a=hS(gS(e.rough,0),0,1),o=+!this._event;vS(this.detune.gain,o*this.depthCents*(.25+.75*i)*(1+2.5*a),t,.08),vS(this.tremolo.gain,(this._event?.2:1)*this.depthGain*(.2+.8*i)*(1+1.5*a),t,.08),vS(this.roughLP.frequency,hS(8+40*n,4,200),t,.1)}dispose(){for(let e of this.lfos)e.osc.disconnect(),e.gain.disconnect();for(let e of[this.rough,this.roughLP,this.roughGain,this.bus,this.detune,this.tremolo])e&&e.disconnect&&e.disconnect()}},CS=Object.freeze([{id:`strain`,label:`Strain`,default:0,note:`Engine working against something — a climb, a trailer, a heavy car. More rumble, harder combustion, more growl, at the same throttle.`},{id:`aggression`,label:`Exhaust valve`,default:0,note:`Active exhaust bypass. Opens the muffler: shallower chambers, brighter packing, more rasp and more level.`},{id:`roughness`,label:`Roughness`,default:0,note:`Engine health. Cycle-to-cycle variation and random misfires — a skipped combustion event in the pipe.`},{id:`distance`,label:`Distance`,default:0,note:`Listener distance. Air absorption takes the top off, level falls, and the room takes over.`},{id:`environment`,label:`Enclosure`,default:0,note:`Open road → tunnel. Hard parallel walls: dense fluttering reflections and a longer tail.`}]),wS=Object.freeze(Object.fromEntries(CS.map(e=>[e.id,e.default]))),TS=(e,t,n)=>e<t?t:e>n?n:e,ES=60/(2*Math.PI),DS={manual:{cutF:.3,openF:.3,syncF:.15,engageF:.35,cutMin:.03,openMin:.035,syncMin:.018,engageMin:.05,openClutch:0,engageStart:0,cutDepth:1,cutBang:.85,blip:.85,blipTolRpm:130,lashMax:.17,shuffle:.36,openStretch:2.6},dct:{cutF:.3,openF:.25,syncF:.15,engageF:.6,cutMin:.012,openMin:.01,syncMin:.008,engageMin:.028,openClutch:.1,engageStart:.4,cutDepth:1,cutBang:1,blip:1,blipTolRpm:60,lashMax:.09,shuffle:.26,openStretch:2},auto:{cutF:.2,openF:.25,syncF:.18,engageF:.9,cutMin:.02,openMin:.025,syncMin:.018,engageMin:.09,openClutch:0,engageStart:.12,cutDepth:.55,cutBang:.15,blip:.35,blipTolRpm:220,lashMax:.2,shuffle:.42,openStretch:1.6}},OS=class{constructor(e={}){this.type=e.type in DS?e.type:`manual`,this.k=DS[this.type],this.S=Math.max(.02,(e.shiftTimeMs||120)/1e3),this.gearCount=e.gearCount||6,this.idleRpm=e.idleRpm||800,this.redlineRpm=e.redlineRpm||7e3,this.revMatch=e.revMatch!==!1,this.autoShift=e.autoShift!==!1,this.upFracLow=.55,this.upFracHigh=.936,this.downFracLow=.28,this.downFracHigh=.44,this.kickdownThrottle=.85,this.minShiftInterval=.35,this.tCut=0,this.tOpen=0,this.tSync=0,this.tEngage=0,this.reset()}reset(){this.phase=``,this.t=0,this.from=0,this.to=0,this.isDown=!1,this.revTargetW=0,this.sinceShift=999,this.contactSeen=!1,this.blipHeld=!1}get shifting(){let e=this.phase;return e===`cut`||e===`open`||e===`sync`||e===`engage`}get busy(){return this.phase!==``}request(e,t,n=!1){if(t=Math.round(t),this.shifting||t<0||t>this.gearCount||t===e.gear||!n&&this.sinceShift<this.minShiftInterval||this.wouldOverRev(e,t))return!1;this.from=e.gear,this.to=t,this.isDown=t!==0&&(e.gear===0||t<e.gear),this.contactSeen=!1,this.blipHeld=!1;let r=this.k,i=this.S;this.tCut=Math.max(r.cutMin,r.cutF*i),this.tOpen=Math.max(r.openMin,r.openF*i),this.tSync=Math.max(r.syncMin,r.syncF*i),this.tEngage=Math.max(r.engageMin,r.engageF*i),this.revTargetW=this.isDown&&this.revMatch&&t>0?TS(e.gearedRpm(t),this.idleRpm,this.redlineRpm*.97)/ES:0,this.phase=`cut`,this.t=0;let a=TS(((typeof e.egt==`number`?e.egt:1)-.45)/.35,0,1),o=r.cutBang*(.25+.75*e.throttle)*r.cutDepth*a,s=TS((.12+.55*a)*r.cutBang,0,.9);return o>.04&&Math.random()<s&&e.fireEvent(`cut`,TS(o,0,1)),!0}wouldOverRev(e,t){return t<=0?!1:e.gearedRpm(t)>this.redlineRpm}upshiftRpm(e){let t=this.upFracLow+(this.upFracHigh-this.upFracLow)*TS(e,0,1);return Math.max(this.idleRpm*1.6,this.redlineRpm*t)}downshiftRpm(e){let t=this.downFracLow+(this.downFracHigh-this.downFracLow)*TS(e,0,1);return Math.max(this.idleRpm*1.15,this.redlineRpm*t)}auto(e){if(!this.autoShift||this.busy||e.gear===0||this.sinceShift<this.minShiftInterval)return;let t=e.throttle,n=e.rpm,r=this.upshiftRpm(t);if(n>=r&&e.gear<this.gearCount&&t>.05){this.request(e,e.gear+1);return}let i=typeof e.wotTorque==`function`?t=>e.wotTorque(t)*t:null;if(i&&t>=this.kickdownThrottle&&e.gear<this.gearCount&&n>this.redlineRpm*.6){let t=e.gearedRpm(e.gear+1);if(t>this.idleRpm*1.5&&i(t)>=i(n)){this.request(e,e.gear+1);return}}if(e.gear>1){let a=e.gear-1,o=e.gearedRpm(a);if(o>=r)return;if(n<=this.downshiftRpm(t)){this.request(e,a);return}t>=this.kickdownThrottle&&n<this.redlineRpm*.55&&o<this.redlineRpm*.92&&(!i||i(o)>i(n))&&this.request(e,a)}}step(e,t){if(t.gearboxNeutral=!1,t.syncing=!1,t.fuelCut=0,t.throttleOverride=null,t.clutchCmd=null,t.clutchRate=0,!this.busy&&(this.sinceShift+=e,this.auto(t),!this.busy)){t.shiftPhase=``,t.shifting=!1;return}this.t+=e;let n=this.k;switch(this.phase){case`cut`:t.fuelCut=n.cutDepth,t.clutchCmd=1,this.t>=this.tCut&&this._enter(`open`,t);break;case`open`:if(t.gearboxNeutral=!0,t.clutchCmd=n.openClutch,t.clutchRate=60,this.isDown&&this.revTargetW>0){let e=this.revTargetW-t.we,r=n.blipTolRpm/ES;e>r?this.blipHeld=!0:e<0&&(this.blipHeld=!1),t.throttleOverride=this.blipHeld?n.blip:0;let i=Math.abs(e)<=r;(this.t>=this.tOpen&&i||this.t>=this.tOpen*n.openStretch)&&this._enter(`sync`,t)}else t.fuelCut=n.cutDepth,n.cutDepth>=1&&(t.throttleOverride=0),this.t>=this.tOpen&&this._enter(`sync`,t);break;case`sync`:{t.gearboxNeutral=!0,t.clutchCmd=n.openClutch,t.fuelCut=n.cutDepth,n.cutDepth>=1&&(t.throttleOverride=0),this.to>0&&(t.syncing=!0,t.syncTargetW=t.inputShaftTargetW(this.to));let e=this.to===0||Math.abs(t.wg-t.syncTargetW)<3;(this.t>=this.tSync&&e||this.t>=this.tSync*3)&&this._enter(`engage`,t);break}case`engage`:{let e=TS(this.t/this.tEngage,0,1),r=e*e*(3-2*e);t.clutchCmd=n.engageStart+(1-n.engageStart)*r,t.clutchRate=4/this.tEngage,this.to===0&&(t.clutchCmd=0),t.lashContactedSince&&(this.contactSeen=!0),this.t>=this.tEngage&&this._enter(`lash`,t);break}case`lash`:t.clutchCmd=this.to===0?0:1,t.lashContactedSince&&(this.contactSeen=!0),(this.contactSeen||this.t>=n.lashMax||this.to===0)&&this._enter(`shuffle`,t);break;case`shuffle`:t.clutchCmd=this.to===0?0:null,this.t>=n.shuffle&&(this.phase=``,this.t=0,this.sinceShift=0,t.clutchCmd=null)}t.shiftPhase=this.phase,t.shifting=this.shifting}_enter(e,t){if(this.phase,this.phase=e,this.t=0,e===`sync`&&(t.selectGear(this.to),this.to>0&&(t.syncTargetW=t.inputShaftTargetW(this.to))),e===`engage`){t.gearboxNeutral=!1;let e=Math.abs(t.we-t.wg)*ES;t.fireEvent(`engage`,TS(.15+e/1800,0,1)),t.lashContactedSince=!1,this.contactSeen=!1}e===`lash`&&t.fireEvent(`shiftDone`,1)}},kS=60/(2*Math.PI),AS=2*Math.PI/60,jS=1.225,MS=9.81,Z=(e,t,n)=>e<t?t:e>n?n:e,NS=2e3,PS=240,FS=.03,IS=.02,LS=52,RS=.2,zS=15,BS=1.5,VS=.055,HS=.55,US=2.4,WS=.85,GS=.45,KS=class{constructor(e,t,n={}){this.engine=e,this.vehicle=t,this.dl=Object.assign({},ex,n.driveline),this.eff=n.driveEfficiency==null?.92:n.driveEfficiency,this.Je=Math.max(.02,e.engineInertia),this.Jin=n.inputInertia==null?FS:n.inputInertia,this.Jout=n.outputInertia==null?IS:n.outputInertia,this.r=t.wheelRadius,this.fd=t.finalDrive,this.ratios=t.gearRatios,this.gearCount=this.ratios.length,this.Jv=t.mass*this.r*this.r+LS*this.r*this.r,this.subStep=n.subStep||5e-4,this.launchFlareRpm=n.launchFlareRpm==null?2400:n.launchFlareRpm,this.launchRateOverride=n.launchRate==null?null:n.launchRate,this.launchRate=this.launchRateFor(1),this.shift=n.shiftController||new OS({type:t.gearbox,shiftTimeMs:t.shiftTimeMs,gearCount:this.gearCount,idleRpm:e.idleRpm,redlineRpm:e.redlineRpm,autoShift:n.autoShift!==!1,revMatch:n.revMatch!==!1}),this.isAuto=t.gearbox===`auto`,this.throttle=0,this.brake=0,this.we=e.idleRpm*AS,this.wg=this.we,this.wo=0,this.ww=0,this.twist=0,this.dtwist=0,this.lash=0,this.contact=0,this.clutch=0,this.boost=0,this.gear=1,this.Tp=0,this.Te=0,this.Tc=0,this.load=0,this.overrun=0,this.limiterCut=0,this.limiterActive=!1,this.lashTimer=0,this.lashContactedSince=!1,this.launchArmed=!0,this.launchI=0,this.launchT=0,this.launchRef=0,this.lockup=0,this.bovArm=0,this.boostDump=0,this.turboSpeed=0,this.egt=0,this.dfco=0,this.dfcoEdge=0,this.prevDfco=0,this.popCharge=0,this.prevOverride=0,this.thrPeak=0,this.cutRpmN=0,this.popRefractory=0,this.lashHeat=0,this.prevLimiter=!1,this.limiterBark=0,this.prevRpm=this.we*kS,this.gearboxNeutral=!1,this.syncing=!1,this.syncTargetW=0,this.clutchCmd=null,this.burnoutClutchOverride=null,this.clutchRate=0,this.fuelCut=0,this.throttleOverride=null,this.shiftPhase=``,this.shifting=!1,this.ev={cut:0,lash:0,engage:0,bov:0,shiftDone:0,pop:0},this.params={now:0,dt:0,rpm:0,f0:0,rpmNorm:0,dRpm:0,throttle:0,load:0,overrun:0,torqueSign:1,gear:1,gearRatio:0,speed:0,wheelRpm:0,clutchSlip:0,clutchEngaged:0,boost:0,shifting:!1,shiftPhase:``,evCut:0,evLash:0,evEngage:0,evBov:0,evShiftDone:0,evPop:0},this.clutch=0,this._writeParams(0,0)}setThrottle(e){this.throttle=Z(Number(e)||0,0,1)}setBrake(e){this.brake=Z(Number(e)||0,0,1)}setEngine(e){this.engine=e,this.Je=Math.max(.02,e.engineInertia),this.launchRate=this.launchRateFor(1),this.shift.idleRpm=e.idleRpm,this.shift.redlineRpm=e.redlineRpm;let t=Z(this.we*kS,e.idleRpm,e.redlineRpm);this.we=t*AS,this.prevRpm=t,this.boost=0,this.limiterCut=0,this.limiterActive=!1}setVehicle(e){let t=this.speed;this.vehicle=e,this.r=e.wheelRadius,this.fd=e.finalDrive,this.ratios=e.gearRatios,this.gearCount=this.ratios.length,this.Jv=e.mass*this.r*this.r+LS*this.r*this.r,this.isAuto=e.gearbox===`auto`,this.shift.type=e.gearbox,this.shift.gearCount=this.gearCount,this.shift.setTiming&&this.shift.setTiming(e.shiftTimeMs),this.shift.reset(),this.launchRate=this.launchRateFor(1),this.gear=Z(Math.round(this.gear),0,this.gearCount),this.ww=t/this.r,this.wo=this.ww*this.fd,this.twist=0,this.dtwist=0,this.contact=0}setAutoShift(e){this.shift.autoShift=!!e}shiftUp(){return this.gear>=this.gearCount?!1:this.shift.request(this,this.gear+1,!0)}shiftDown(){return this.gear<=1?!1:this.shift.request(this,this.gear-1,!0)}setGear(e){return this.shift.request(this,e,!0)}get rpm(){return this.we*kS}get speed(){return this.ww*this.r}get gearRatio(){return this.gear>0?this.ratios[this.gear-1]:0}get totalRatio(){return this.gear>0?this.ratios[this.gear-1]*this.fd:0}gearedRpm(e){return e<=0||e>this.gearCount?0:Math.abs(this.ww)*this.fd*this.ratios[e-1]*kS}launchRateFor(e){if(this.launchRateOverride!=null)return this.launchRateOverride;let t=Z(Math.round(e),1,this.gearCount)-1,n=Math.abs(this.ratios[t]*this.fd)||1;return Z(this.engine.peakTorque*n*this.eff/this.r/Math.max(1,this.vehicle.mass)/this.r*n*kS*.55,400,12e3)}inputShaftTargetW(e){return e<=0||e>this.gearCount?0:this.ww*this.fd*this.ratios[e-1]}selectGear(e){this.gear=Z(Math.round(e),0,this.gearCount)}fireEvent(e,t){t>this.ev[e]&&(e===`pop`&&this.we*kS<NS||(this.ev[e]=t>1?1:t))}_JoutSide(e,t=!0){if(e<=0)return this.Jout;let n=this.ratios[e-1];return(t?this.Je+this.Jin:this.Jin)*n*n+this.Jout}_JvehOut(){return this.Jv/(this.fd*this.fd)}modeW(e,t=!0){let n=this._JoutSide(e,t),r=this._JvehOut();return Math.sqrt(this.dl.stiffness*(1/n+1/r))}modeHz(e,t=!0){return this.modeW(e,t)/(2*Math.PI)}modeZeta(e,t=!0){if(this.dl.dampingRatio!=null)return this.dl.dampingRatio;let n=this._Jred(e,t);return this.dl.damping/(2*Math.sqrt(this.dl.stiffness*n))}_Jred(e,t=!0){let n=this._JoutSide(e,t),r=this._JvehOut();return 1/(1/n+1/r)}_dampCoeff(){if(this.dl.dampingRatio==null)return this.dl.damping;let e=this.clutch>.5&&!this.gearboxNeutral,t=this._Jred(this.gear>0?this.gear:1,e);return Z(2*this.dl.dampingRatio*Math.sqrt(this.dl.stiffness*Math.max(1e-4,t)),1,400)}stabilityReport(){let e=0,t=``;for(let n=1;n<=this.gearCount;n++)for(let r of[!0,!1]){let i=this.modeW(n,r);i>e&&(e=i,t=`gear ${n} clutch ${r?`locked`:`open`}`)}let n=Math.sqrt(this.dl.stiffness/this.Jout);n>e&&(e=n,t=`gearbox neutral (output shaft alone)`);let r=this.dl.damping/this.Jout;return{subStep:this.subStep,worstModeRadS:e,worstModeHz:e/(2*Math.PI),worstModeWhere:t,stableBelowSpring:2/e,stableBelowDamper:2/r,phasePerStepRad:e*this.subStep,marginSpring:2/e/this.subStep,marginDamper:2/r/this.subStep}}getState(){return{rpm:this.rpm,speed:this.speed,speedKmh:this.speed*3.6,gear:this.gear,throttle:this.throttle,brake:this.brake,twist:this.twist,contact:this.contact,clutch:this.clutch,Tp:this.Tp,boost:this.boost,phase:this.shiftPhase,shifting:this.shifting,limiter:this.limiterActive,gearCount:this.gearCount,redline:this.engine.redlineRpm,idle:this.engine.idleRpm}}torqueFactor(e){let t=(e-this.engine.peakTorqueRpm)/(this.engine.redlineRpm*.75);return Z(1-.85*t*t,.3,1)}wotTorque(e){return this.engine.peakTorque*this.torqueFactor(e)*this._boostMult()-this.frictionTorque(e,1)}frictionTorque(e,t){return(18+.012*e+22e-7*e*e)*(1-.62*t)}step(e,t=0){let n=Number(e)||0;if(n<=0)return this.params.now=t,this.params.dt=0,this.params.evCut=this.params.evLash=this.params.evEngage=0,this.params.evBov=this.params.evShiftDone=0,this.params;n=Math.min(n,.1);let r=Math.min(PS,Math.max(1,Math.ceil(n/this.subStep))),i=n/r;for(let e=0;e<r;e++)this._substep(i);return this._writeParams(n,t),this.params}_substep(e){let t=this.engine;this.vehicle;let n=this.dl;this.lashContactedSince=!1,this.shift.step(e,this);let r=this.gear>0&&!this.gearboxNeutral,i=this.gear>0?this.ratios[this.gear-1]:0;this.limiterCut>0?(this.limiterCut-=e,this.limiterCut<=0&&this.rpm>t.redlineRpm-200&&(this.limiterCut=.012)):this.rpm>=t.redlineRpm&&(this.limiterCut=.05),this.limiterActive=this.limiterCut>0;let a=this.throttleOverride==null?this.throttle:this.throttleOverride;a*=1-Z(this.fuelCut,0,1),this.limiterActive&&(a=0),this.thrEff=a,this._stepTurbo(e,a),this._stepExhaustThermal(e,a);let o=this.we*kS,s=a*t.peakTorque*this.torqueFactor(o)*this._boostMult()-this.frictionTorque(o,a);if(this.throttle<.06&&o<t.idleRpm*1.25&&!this.limiterActive){let e=this.frictionTorque(t.idleRpm,0)+(t.idleRpm-o)*.55;e>s&&(s=e)}this.Te=s;let c=n.backlash,l=this._dampCoeff(),u=0;this.twist>c?(u=n.stiffness*(this.twist-c)+l*this.dtwist,u<0&&(u=0)):this.twist<-c&&(u=n.stiffness*(this.twist+c)+l*this.dtwist,u>0&&(u=0)),this.Tp=u,this._stepClutch(e,r,i);let d=0,f=0;if(this.isAuto){let e=this._converter(this.we,this.wg);d=e.pump,f=e.turbine}let p=r?this.Jin+this.Jout/(i*i):this.Jin,m=-this._gearboxDrag(this.wg);if(r&&(m-=u/i),this.syncing){let e=this.syncTargetW-this.wg;m+=Z(e*this.Jin/.008,-400,400)}m+=f;let h=s-d,g=m,_=this.Je*p/(this.Je+p),v=n.clutchTorqueCapacity*this.clutch*this._stallGuard(),y=_*((this.we-this.wg)/e+h/this.Je-g/p);y>v?y=v:y<-v&&(y=-v),this.Tc=y,this.we+=e*(h-y)/this.Je,this.wg+=e*(g+y)/p;let b=t.idleRpm*.42*AS,x=t.redlineRpm*1.015*AS;this.we<b&&(this.we=b),this.we>x&&(this.we=x),r?this.wo=this.wg/i:this.wo+=e*(-u-this._gearboxDrag(this.wo)*.5)/this.Jout,this._stepVehicle(e,u),this.dtwist=this.wo-this.ww*this.fd,this.twist+=e*this.dtwist,Math.abs(this.twist)<3||(this.twist=Z(this.twist||0,-3,3)),this.lash=Z(this.twist,-c,c),this._detectLash(e,c)}_gearboxDrag(e){return .006*e+(e>.5?.4:e<-.5?-.4:0)}_stallGuard(){let e=this.engine.idleRpm*AS;return Z((this.we-e*.92)/(e*.55),0,1)}_stepClutch(e,t,n){let r=this.burnoutClutchOverride??this.clutchCmd,i=this.burnoutClutchOverride==null?this.clutchRate:18;r??(this.isAuto?(r=t&&this.gear>=2&&this.gearedRpm(this.gear)>this.engine.idleRpm*1.35&&this.throttle<.85?1:0,i=2.5):r=this._launchClutch(e,t)),i>0||(i=this.dl.clutchStiffness*12),this.clutch+=(Z(r,0,1)-this.clutch)*Math.min(1,e*i),this.clutch=Z(this.clutch,0,1)}_launchClutch(e,t){let n=this.engine.idleRpm,r=this.gearedRpm(this.gear);if(!t||this.gear===0)return this.launchI=0,this.launchT=0,this.launchRef=0,this.launchArmed=!0,0;let i=Z(n*1.05+this.throttle*this.launchFlareRpm,n,this.engine.redlineRpm*.9);if(this.launchArmed&&this.clutch>.985&&r>i*.75?this.launchArmed=!1:!this.launchArmed&&r<n*.95&&(this.launchArmed=!0),!this.launchArmed)return this.launchI=0,this.launchT=0,this.launchRef=0,1;if(this.throttle<.05&&r<n*.5)return this.launchT=0,this.launchRef=0,this.launchI=Math.max(0,this.launchI-e/.2),Z(this.launchI,0,.22);this.launchT=Math.min(4,(this.launchT||0)+e);let a=this.launchRateFor(this.gear),o=Math.max(300,i-n),s=r+o*(1-Z(r/Math.max(1,o*1.8),0,1));this.launchRef>0||(this.launchRef=Math.max(n*1.05,this.rpm));let c=s-this.launchRef,l=c>0?Math.min(a,c/GS):c/GS;this.launchRef+=l*e;let u=Math.max(s,n*1.05);this.launchRef=Math.min(this.launchRef,u,this.rpm+o*.5),this.launchRef=Math.max(this.launchRef,n*1.05),this.rpm>this.launchRef&&(this.launchRef=Math.min(this.rpm,u));let d=this.launchRef,f=this.dl.clutchTorqueCapacity*this._stallGuard(),p=this.Te-this.Je*l*AS,m=f>1?Z(p/f,0,1):0,h=(this.rpm-d)/d;this.launchI=Z(this.launchI*(1-Math.min(1,e/.6))+8*h*e,-.4,.5);let g=Z(m+this.launchI+1.5*h,0,1),_=Z((this.launchT-.9)/1.2,0,1);return Math.max(g,Math.min(_,m))}_converter(e,t){if(e>t+.5){let n=Z(t/Math.max(e,.001),0,1),r=Z(.008*e*e*(1-n*n),0,4*this.engine.peakTorque);return{pump:r,turbine:r*(1+1*(1-n)**1.2)}}if(t>e+.5){let n=Z(e/Math.max(t,.001),0,1),r=Z(.0048*t*t*(1-n*n),0,4*this.engine.peakTorque);return{pump:-r,turbine:-r}}return{pump:0,turbine:0}}_stepVehicle(e,t){let n=this.vehicle,r=this.ww*this.r,i=t>0?t*this.fd*this.eff:t*this.fd,a=.5*jS*n.dragArea*r*r,o=r>0?a*this.r:0,s=(n.rollingResistance*n.mass*MS+this.brake*n.brakeForce)*this.r,c=i-o;if(this.ww>1e-6){let t=this.ww+e*(c-s)/this.Jv;this.ww=t<0&&c<s?0:Math.max(0,t)}else this.ww=c>s?e*(c-s)/this.Jv:0}_detectLash(e,t){this.lashTimer+=e,this.lashHeat=Math.max(0,this.lashHeat-e/HS);let n=this.twist>t?1:this.twist<-t?-1:0;if(n===0){Math.abs(this.twist)<t*WS&&(this.contact=0);return}if(n===this.contact)return;let r=Math.abs(this.dtwist);if(this.contact=n,r<RS||this.lashTimer<VS)return;this.lashTimer=0,this.lashContactedSince=!0;let i=1/(1+US*this.lashHeat);this.lashHeat=Math.min(3,this.lashHeat+1);let a=Z((r/zS)**+BS*i,.001,1);a<.05||this.fireEvent(`lash`,a)}_stepExhaustThermal(e,t){let n=this.we*kS,r=Z((n-this.engine.idleRpm)/Math.max(1,this.engine.redlineRpm-this.engine.idleRpm),0,1),i=Z(.12+.88*t**.6*(.35+.65*r),0,1),a=i>this.egt?5:26;this.egt+=(i-this.egt)*Math.min(1,e/a);let o=this.throttle,s=o<.06&&n>this.engine.idleRpm*1.5&&!this.gearboxNeutral;if(this.dfco=+!!s,this.thrPeak=Math.max(o,this.thrPeak-e/.7),this.popRefractory=Math.max(0,this.popRefractory-e),this.limiterBark=Math.max(0,this.limiterBark-e),this.limiterActive&&!this.prevLimiter&&this.egt>.5&&this.limiterBark<=0&&(this.limiterBark=.34,this.fireEvent(`pop`,Z(.16+.14*Math.random(),0,1))),this.prevLimiter=this.limiterActive,this.dfco!==this.prevDfco){if(this.dfcoEdge=1,this.dfco){let e=Z(this.thrPeak,0,1),t=r**1.7;this.cutRpmN=r;let n=.55+Math.random()*.95;this.popCharge=Z(this.popCharge+(.5+2.1*t)*(.4+.6*e)*n,0,3.4);let i=Z((this.egt-.42)/.34,0,1)*(.18+.82*t)*(.45+.55*e);this.egt>.42&&this.popRefractory<=0&&Math.random()<i&&(this.popRefractory=.45,this.fireEvent(`pop`,Z((this.egt-.35)*1.25*(.1+1.3*t)*(.35+.65*e)*n,0,1)))}else this.popCharge=Z(this.popCharge+.35,0,3.4)}this.prevDfco=this.dfco,this.dfcoEdge=Math.max(0,this.dfcoEdge-e/.85);let c=this.throttleOverride;if(this.prevOverride>.3&&!(c>.3)){this.popCharge=Z(this.popCharge+1.1+.5*r,0,2.6);let e=Z((this.egt-.32)/.3,0,1)*(.35+.65*r);this.egt>.32&&this.popRefractory<=0&&Math.random()<e&&(this.popRefractory=.45,this.fireEvent(`pop`,Z((this.egt-.25)*1.45*(.5+.5*r),0,1)))}this.prevOverride=c??0,this.popCharge=Math.max(0,this.popCharge-e*(.22+.55*(1-this.dfco)))}_stepTurbo(e,t){let n=this.engine.turbo;if(!n){this.boost=0;return}let r=this.we*kS,i=Math.min(Z(Number(n.boostRpm)||3500,800,9e3),.65*this.engine.redlineRpm),a=Math.max(.6*this.engine.redlineRpm,i+1500),o=Z((r-i)/(a-i),0,1),s=n.antiLag>=.5&&t<.12&&r>.3*this.engine.redlineRpm,c=s?.7*o:Z(t,0,1)*o;s&&(this._alsT=(this._alsT||0)-e,this._alsT<=0&&(this._alsT=.06+.16*Math.random(),this.fireEvent(`pop`,.35+.45*Math.random())));let l=this.boostDump>0?.05:c>this.boost?.25+n.inertia*.9:.18+n.inertia*.4;this.boost+=(c-this.boost)*Math.min(1,e/l),this.boost=Z(this.boost,0,1),this.boostDump>0&&(this.boostDump-=e);let u=r>900?.12+.2*o:0,d=Z(Math.max(u,c),0,1),f=d>this.turboSpeed?.22+n.inertia*.85:.42+n.inertia*.55;this.turboSpeed+=(d-this.turboSpeed)*Math.min(1,e/f),this.turboSpeed=Z(this.turboSpeed,0,1),t>.45?this.bovArm=1:this.bovArm>0&&t<.12&&this.boost>.18&&!this.limiterActive&&n.valve>=.5&&!s&&(this.bovArm=0,this.boostDump=.12,this.fireEvent(`bov`,Z(this.boost*(.4+.6*n.bov),.1,1)))}_boostMult(){let e=this.engine.turbo;return e?1+.55*this.boost*e.maxBoost:1}_writeParams(e,t){let n=this.params,r=this.engine,i=this.we*kS;n.now=t,n.dt=e,n.rpm=i,n.f0=i/120,n.rpmNorm=Z((i-r.idleRpm)/(r.redlineRpm-r.idleRpm),0,1),n.dRpm=e>0?(i-this.prevRpm)/e:0,this.prevRpm=i,n.throttle=this.throttle,n.limiter=(this.limiterActive||i>r.redlineRpm-120)&&this.throttle>.5?1:0;let a=Z(this.thrEff||0,0,1),o=e>0?Z(e*12,0,1):1;this.load+=(a-this.load)*o,n.load=Z(this.load,0,1);let s=+(this.thrEff<.05&&i>r.idleRpm*1.7&&this.gear>0&&this.Tp<-2);this.overrun+=(s-this.overrun)*(e>0?Z(e*8,0,1):1),n.overrun=Z(this.overrun,0,1),n.torqueSign=this.Tp>1?1:this.Tp<-1?-1:this.Te>=0?1:-1,n.gear=this.gear,n.gearRatio=this.totalRatio,n.speed=this.ww*this.r,n.wheelRpm=this.ww*this.fd*kS,n.clutchSlip=(this.we-this.wg)*kS,n.clutchEngaged=this.clutch,n.boost=this.boost,n.shifting=this.shifting,n.gearbox=this.vehicle.gearbox,n.shiftPhase=this.shiftPhase;let c=this.ev;return n.evCut=c.cut,n.evLash=c.lash,n.evEngage=c.engage,n.evBov=c.bov,n.evShiftDone=c.shiftDone,n.evPop=c.pop,c.cut=c.lash=c.engage=c.bov=c.shiftDone=c.pop=0,n.turboSpeed=this.turboSpeed,n.egt=this.egt,n.dfco=this.dfco,n.cutRpmN=this.cutRpmN,n.popIntensity=Z(Math.max(0,this.egt-.45)/.55*Z(this.popCharge,0,1)*(.12+.88*this.dfcoEdge)*(.45+.55*this.cutRpmN),0,1)*+(i>=NS),n}},qS=1.225,JS=9.81,YS=60/(2*Math.PI),XS=.8,ZS=(e,t,n)=>e<t?t:e>n?n:e;function QS(e,t,n=1){let r=(t-e.peakTorqueRpm)/(e.redlineRpm*.75),i=ZS(1-.85*r*r,.3,1),a=e.turbo,o=a?1+.55*n*a.maxBoost:1,s=(18+.012*t+22e-7*t*t)*.38;return e.peakTorque*i*o-s}function $S(e){let t={rpm:e.redlineRpm,power:0,torque:0};for(let n=e.idleRpm;n<=e.redlineRpm;n+=25){let r=QS(e,n),i=r*n/YS;i>t.power&&(t.power=i,t.rpm=n),r>t.torque&&(t.torque=r)}return t}function eC(e){return[2.6+.4*(e-4),3.8+.8*(e-4)]}function tC(e,t,n={}){let r=Math.round(ZS(n.gears||e.gears||t.gearRatios&&t.gearRatios.length||6,3,10)),i=t.gravity||JS,a=n.efficiency||.92,o=t.wheelRadius,s=t.finalDrive,c=t.mass,l=e=>.5*qS*t.dragArea*e*e+t.rollingResistance*c*i,u=$S(e),d=Math.min(u.rpm*1.04,e.redlineRpm*.9),f=a*QS(e,d)*d/YS,p=0,m=200;for(let e=0;e<60;e++){let e=.5*(p+m);l(e)*e<f?p=e:m=e}let h=p,g=d/YS*o/Math.max(h,1),_=.6*c*i*o/(Math.max(1,u.torque)*a),[v,y]=eC(r),b=ZS(_/g,v,y),x=[];for(let e=1;e<=r;e++){let t=((r-e)/(r-1))**1.15;x.push(+(XS*g*b**+t/s).toFixed(3))}return{gearRatios:x,gearTeeth:x.map(e=>Math.round(ZS(16+6.5*e,17,46))),topSpeed:h}}function nC(e,t,n){let r=tC(e,t,n);return{...t,gearRatios:r.gearRatios,gearTeeth:r.gearTeeth}}var rC=(e,t,n)=>e<t?t:e>n?n:e,iC=(e,t=0)=>typeof e==`number`&&isFinite(e)?e:t,aC=class e{static BANDS=[{f:60,type:`lowshelf`,label:`sub`},{f:200,type:`peaking`,q:.9,label:`body`},{f:800,type:`peaking`,q:1,label:`honk`},{f:2500,type:`peaking`,q:.9,label:`rasp`},{f:8e3,type:`highshelf`,label:`air`}];constructor(t,n={}){this.ctx=t,this.inGain=t.createGain(),this.out=t.createGain(),this.bands=e.BANDS.map(e=>{let n=t.createBiquadFilter();return n.type=e.type,n.frequency.value=e.f,e.q&&(n.Q.value=e.q),n.gain.value=0,n});let r=this.inGain;for(let e of this.bands)r.connect(e),r=e;r.connect(this.out),n.gains&&this.setGains(n.gains)}get input(){return this.inGain}get output(){return this.out}setGains(e){let t=this.ctx.currentTime;for(let n=0;n<this.bands.length&&n<e.length;n++)this.bands[n].gain.setTargetAtTime(rC(iC(e[n],0),-18,18),t,.03)}setBand(e,t){e<0||e>=this.bands.length||this.bands[e].gain.setTargetAtTime(rC(iC(t,0),-18,18),this.ctx.currentTime,.03)}getGains(){return this.bands.map(e=>e.gain.value)}reset(){this.setGains(this.bands.map(()=>0))}update(){}dispose(){for(let e of[this.inGain,this.out,...this.bands])e.disconnect()}},oC=class{constructor(e,t={}){this.ctx=e,this.inGain=e.createGain(),this.out=e.createGain(),this.dry=e.createGain(),this.wet=e.createGain(),this.conv=e.createConvolver(),this.conv.normalize=!0,this.damp=e.createBiquadFilter(),this.damp.type=`lowpass`,this.damp.frequency.value=4200,this.damp.Q.value=.7,this.hp=e.createBiquadFilter(),this.hp.type=`highpass`,this.hp.frequency.value=110,this.inGain.connect(this.dry),this.dry.connect(this.out),this.inGain.connect(this.hp),this.hp.connect(this.conv),this.conv.connect(this.damp),this.damp.connect(this.wet),this.wet.connect(this.out),this._size=rC(iC(t.size,.35),.05,1),this._mix=rC(iC(t.mix,.16),0,1),this.setSize(this._size),this.setMix(this._mix)}get input(){return this.inGain}get output(){return this.out}_buildIR(e){let t=this.ctx,n=.15+2.05*rC(e,0,1),r=Math.max(64,Math.floor(t.sampleRate*n)),i=t.createBuffer(2,r,t.sampleRate),a=2.6+3.4*(1-e);for(let e=0;e<2;e++){let n=i.getChannelData(e);for(let e=0;e<r;e++){let t=e/r;n[e]=(Math.random()*2-1)*(1-t)**a}for(let e=0;e<7;e++){let i=Math.floor((.004+.055*Math.random())*t.sampleRate);i<r&&(n[i]+=(Math.random()*2-1)*.55*(1-e/7))}}return i}setSize(e){return this._size=rC(iC(e,.35),.05,1),this.conv.buffer=this._buildIR(this._size),this._size}setMix(e){return this._mix=rC(iC(e,0),0,1),this._writeMix(.03),this._mix}setExtra(e){let t=rC(iC(e,0),0,1);Math.abs(t-(this._extra||0))<.001||(this._extra=t,this._writeMix(.08))}_writeMix(e){let t=rC(this._mix+(this._extra||0)*(1-this._mix),0,1),n=this.ctx.currentTime;this.dry.gain.setTargetAtTime(Math.cos(t*Math.PI/2),n,e),this.wet.gain.setTargetAtTime(Math.sin(t*Math.PI/2)*1.4,n,e)}setDamping(e){this.damp.frequency.setTargetAtTime(rC(iC(e,4200),400,18e3),this.ctx.currentTime,.05)}getState(){return{size:this._size,mix:this._mix,damping:this.damp.frequency.value}}update(){}dispose(){for(let e of[this.inGain,this.out,this.dry,this.wet,this.conv,this.damp,this.hp])e.disconnect()}},sC=class{constructor(e,t={}){this.ctx=e,this.inGain=e.createGain(),this.merger=e.createChannelMerger(2),this.out=e.createGain(),this.delay=e.createDelay(.08),this.delay.delayTime.value=.016,this.tilt=e.createBiquadFilter(),this.tilt.type=`highshelf`,this.tilt.frequency.value=1800,this.tilt.gain.value=-3,this.plus=e.createGain(),this.minus=e.createGain(),this.plus.gain.value=0,this.minus.gain.value=0,this.inGain.connect(this.merger,0,0),this.inGain.connect(this.merger,0,1),this.inGain.connect(this.delay),this.delay.connect(this.tilt),this.tilt.connect(this.plus),this.tilt.connect(this.minus),this.plus.connect(this.merger,0,0),this.minus.connect(this.merger,0,1),this.merger.connect(this.out),this.setWidth(iC(t.width,.35))}get input(){return this.inGain}get output(){return this.out}setWidth(e){this._width=rC(iC(e,0),0,1);let t=this.ctx.currentTime,n=this._width*.85;return this.plus.gain.setTargetAtTime(n,t,.03),this.minus.gain.setTargetAtTime(-n,t,.03),this.delay.delayTime.setTargetAtTime(.008+.018*this._width,t,.05),this._width}getWidth(){return this._width}update(){}dispose(){for(let e of[this.inGain,this.merger,this.out,this.delay,this.tilt,this.plus,this.minus])e.disconnect()}},cC=class e{static BANDS=[{name:`low`,f:220,threshold:-16,ratio:2.6,attack:.018,release:.26,knee:10,makeup:1.1},{name:`mid`,f:2e3,threshold:-18,ratio:2,attack:.022,release:.2,knee:14,makeup:2.12},{name:`high`,f:0,threshold:-24,ratio:3,attack:.003,release:.12,knee:8,makeup:.9}];constructor(t,n={}){this.ctx=t,this._amount=rC(iC(n.amount,1),0,1),this.inGain=t.createGain(),this.out=t.createGain(),this.out.gain.value=rC(iC(n.makeup,1),0,4);let r=(e,n)=>{let r=t.createBiquadFilter();return r.type=e,r.frequency.value=rC(n,20,2e4),r.Q.value=-3.0103,r};this.bands=[];let[i,a]=e.BANDS;for(let n of e.BANDS){let e=t.createDynamicsCompressor();e.threshold.value=n.threshold,e.ratio.value=n.ratio,e.attack.value=n.attack,e.release.value=n.release,e.knee.value=n.knee;let o=t.createGain();o.gain.value=n.makeup;let s=[];n.name===`low`?s.push(r(`lowpass`,i.f),r(`lowpass`,i.f)):n.name===`mid`?s.push(r(`highpass`,i.f),r(`highpass`,i.f),r(`lowpass`,a.f),r(`lowpass`,a.f)):s.push(r(`highpass`,a.f),r(`highpass`,a.f));let c=this.inGain;for(let e of s)c.connect(e),c=e;c.connect(e),e.connect(o),o.connect(this.out),this.bands.push({spec:n,comp:e,makeup:o,chain:s})}this.setAmount(this._amount)}get input(){return this.inGain}get output(){return this.out}setAmount(e){this._amount=rC(iC(e,1),0,1);let t=iC(this.ctx.currentTime,0);for(let e of this.bands){let n=rC(e.spec.threshold*this._amount,-100,0);e.comp.threshold.setTargetAtTime(n,t,.05);let r=1+(e.spec.makeup-1)*this._amount,i=lC(n,e.spec.ratio,e.spec.knee);e.makeup.gain.setTargetAtTime(r*10**(-i/20),t,.05)}return this._amount}getAmount(){return this._amount}getReduction(){let e={};for(let t of this.bands)e[t.spec.name]=iC(t.comp.reduction,0);return e}update(){}dispose(){for(let e of this.bands){for(let t of e.chain)t.disconnect();e.comp.disconnect(),e.makeup.disconnect()}this.inGain.disconnect(),this.out.disconnect()}};function lC(e,t,n=0){let r=Math.min(0,iC(e,0))+Math.max(0,iC(n,0))/2,i=Math.max(1,iC(t,1));return Math.max(0,-.6*Math.min(0,r)*(1-1/i))}var uC=class{constructor(e){this.ctx=e,this.pre=e.createGain(),this.pre.gain.value=1/4,this.shaper=e.createWaveShaper();let t=8193,n=new Float32Array(t),r=.6,i=.39;for(let e=0;e<t;e++){let t=4*(e/8192*2-1),a=Math.abs(t),o=a<=r?a:r+i*Math.tanh((a-r)/i);n[e]=Math.sign(t)*o}this.shaper.curve=n,this.shaper.oversample=`2x`,this.pre.connect(this.shaper)}get input(){return this.pre}get output(){return this.shaper}dispose(){this.pre.disconnect(),this.shaper.disconnect()}},dC=class{constructor(e,t={}){this.ctx=e;let n=-3.0103,r=(t,n,r)=>{let i=e.createBiquadFilter();return i.type=t,i.frequency.value=n,i.Q.value=r,i};this.inGain=e.createGain(),this.lp1=r(`lowpass`,140,n),this.lp2=r(`lowpass`,140,n),this.drive=e.createGain(),this.drive.gain.value=2.2,this.span=e.createGain(),this.span.gain.value=1/4,this.shaper=e.createWaveShaper();let i=4097,a=new Float32Array(i);for(let e=0;e<i;e++){let t=4*(e/4096*2-1),n=Math.tanh(t);a[e]=n+.45*n*n}this.shaper.curve=a,this.shaper.oversample=`2x`,this.hp=r(`highpass`,90,.7),this.lp3=r(`lowpass`,420,.6),this.amount=e.createGain(),this.amount.gain.value=rC(iC(t.amount,.15),0,2),this.inGain.connect(this.lp1),this.lp1.connect(this.lp2),this.lp2.connect(this.drive),this.drive.connect(this.span),this.span.connect(this.shaper),this.shaper.connect(this.hp),this.hp.connect(this.lp3),this.lp3.connect(this.amount)}get input(){return this.inGain}get output(){return this.amount}setAmount(e){this.amount.gain.setTargetAtTime(rC(iC(e,0),0,2),this.ctx.currentTime,.05)}dispose(){for(let e of[this.inGain,this.lp1,this.lp2,this.drive,this.span,this.shaper,this.hp,this.lp3,this.amount])e.disconnect()}},fC=class{constructor(e){this.ctx=e,this.inGain=e.createGain(),this.out=e.createGain(),this.inGain.connect(this.out),this.loops=[.037,.061].map((t,n)=>{let r=e.createGain(),i=e.createDelay(.2);i.delayTime.value=t;let a=e.createBiquadFilter();a.type=`lowpass`,a.frequency.value=n?1900:2600,a.Q.value=.5;let o=e.createBiquadFilter();o.type=`highpass`,o.frequency.value=70,o.Q.value=.5;let s=e.createGain();s.gain.value=0;let c=e.createGain();return c.gain.value=0,this.inGain.connect(r),r.connect(i),i.connect(a),a.connect(o),o.connect(s),s.connect(r),o.connect(c),c.connect(this.out),{sum:r,d:i,lp:a,hp:o,fb:s,wet:c}}),this._env=-1}get input(){return this.inGain}get output(){return this.out}setEnvironment(e){if(e=rC(iC(e,0),0,1),Math.abs(e-this._env)<.001)return;this._env=e;let t=this.ctx.currentTime;this.loops.forEach((n,r)=>{n.fb.gain.setTargetAtTime(.52*e,t,.08),n.wet.gain.setTargetAtTime((r?.3:.38)*e,t,.08)})}dispose(){this.inGain.disconnect(),this.out.disconnect();for(let e of this.loops)for(let t of Object.values(e))t.disconnect()}},pC=`/**
1009
+ }`,Rb=class{canvas;gl;program;buffer;vao;data=new Float32Array(81920);width=1;height=1;lost=!1;disposed=!1;onLost=e=>{e.preventDefault(),this.lost=!0};onRestored=()=>{this.disposed||(this.initialize(),this.lost=!1)};constructor(e=document.createElement(`canvas`)){this.canvas=e;let t=e.getContext(`webgl2`,{alpha:!0,premultipliedAlpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1});if(!t)throw Error(`WebGL2 is required for electricity`);this.gl=t,this.initialize(),e.addEventListener(`webglcontextlost`,this.onLost),e.addEventListener(`webglcontextrestored`,this.onRestored)}initialize(){let e=this.gl,t=Dv(e,Ib,Lb,`Electricity`),n=e.createBuffer(),r=e.createVertexArray();if(!n||!r)throw Pv(e,t),e.deleteBuffer(n),e.deleteVertexArray(r),Error(`Unable to allocate electricity renderer`);this.program=t,this.buffer=n,this.vao=r,e.bindVertexArray(r),e.bindBuffer(e.ARRAY_BUFFER,n),e.bufferData(e.ARRAY_BUFFER,this.data.byteLength,e.DYNAMIC_DRAW),Mv(e,t,{aStart:{buffer:n,numComponents:2,stride:40,offset:0,divisor:1},aEnd:{buffer:n,numComponents:2,stride:40,offset:8,divisor:1},aStyle:{buffer:n,numComponents:4,stride:40,offset:16,divisor:1},aDistance:{buffer:n,numComponents:2,stride:40,offset:32,divisor:1}}),e.bindVertexArray(null)}resize(e,t,n=1){if(this.disposed)return;this.width=Math.max(1,Number.isFinite(e)?e:1),this.height=Math.max(1,Number.isFinite(t)?t:1);let r=Math.min(2,Math.max(.25,Number.isFinite(n)?n:1),Math.sqrt(3e6/(this.width*this.height)),4096/this.width,4096/this.height),i=Math.ceil(this.width*r),a=Math.ceil(this.height*r);this.canvas.width!==i&&(this.canvas.width=i),this.canvas.height!==a&&(this.canvas.height=a)}render(e,t,n={}){if(this.lost||this.disposed)return 0;let r=this.gl;r.viewport(0,0,this.canvas.width,this.canvas.height),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT);let i=0;if(Array.isArray(e))for(let t of e)i+=t.writeInstances(this.data,i);else i=e.writeInstances(this.data);return i?(r.useProgram(this.program),r.bindVertexArray(this.vao),r.bindBuffer(r.ARRAY_BUFFER,this.buffer),r.bufferSubData(r.ARRAY_BUFFER,0,this.data,0,i*10),jv(this.program,{uViewport:[this.width,this.height],uTime:t,uNoiseOrigin:n.noiseOrigin??[0,0],uNoiseScale:n.noiseScale??1,uDark:n.dark===!1?0:1,uExposure:n.exposure??.95,uColor:n.color??[.14,.64,1],uCorona:n.corona??[.28,.13,1]}),r.enable(r.BLEND),r.blendFunc(r.ONE,n.dark===!1?r.ONE_MINUS_SRC_ALPHA:r.ONE),r.drawArraysInstanced(r.TRIANGLES,0,6,i),r.bindVertexArray(null),i):0}dispose(){this.disposed||(this.disposed=!0,this.canvas.removeEventListener(`webglcontextlost`,this.onLost),this.canvas.removeEventListener(`webglcontextrestored`,this.onRestored),this.gl.deleteBuffer(this.buffer),Pv(this.gl,this.program),this.gl.deleteVertexArray(this.vao))}},zb={color:[.58,.81,1],corona:[.25,.48,.9]},Bb=(e,t,n)=>Math.max(t,Math.min(n,e)),Vb=(e,t)=>({x:Math.cos(e)*t,y:Math.sin(e)*t});function Hb(){return{shape:{kind:`point`,center:{x:0,y:0},radius:154},sources:Array.from({length:12},(e,t)=>Vb(t/12*Math.PI*2,126)),targets:Array.from({length:17},(e,t)=>Vb(t/17*Math.PI*2+.8,102))}}function Ub(e){let t=e|0,n=()=>(t^=t<<13,t^=t>>>17,t^=t<<5,(t>>>0)/4294967296),r=[{x:0,y:0},{x:300,y:0}];for(let e=0;e<5;e++){let t=[r[0]],i=82*.54**e;for(let e=1;e<r.length;e++){let a=r[e-1],o=r[e];t.push({x:(a.x+o.x)/2,y:(a.y+o.y)/2+(n()-.5)*i*2},o)}r=t}return{shape:{kind:`path`,points:r,width:82},sources:[{x:0,y:0}],targets:[{x:300,y:0}]}}var Wb=class{vehicles=new Map;visible=[];strikes=[];volumes=[];scratch=new Float32Array(12e3);gpu=null;elapsed=0;emit;failed=!1;cameraOrigin={x:0,y:0};cameraScale=1;get active(){return this.visible.length>0||this.strikes.length>0||this.volumes.length>0}get stats(){let e=[...this.vehicles.values()].flatMap(e=>[e.field,e.charge,e.arc,e.halo]);return{vehicles:this.vehicles.size,fields:e.filter(Boolean).length,nodes:e.reduce((e,t)=>e+(t?.simulation.stats.nodes??0),0),visible:this.visible.length+this.strikes.length+this.volumes.length}}create(e,t){let n=new Fb(e===`arc`?Ub(t):e===`field`?{...Hb(),targets:[{x:0,y:0}]}:Hb(),{seed:t,spacing:e===`field`?13:11,maxNodes:e===`arc`?640:e===`field`?520:330,strikesPerSecond:0,branching:.65,corona:e===`field`?.5:0,nearbyTargets:!1}),r={simulation:n,gain:1,pull:e===`field`};return n.onEmission=e=>{this.emit?.(e.point,e.direction,e.strength*(r.pull?.5:.8))},r}radial(e,t,n,r){let i=t.pixelsPerMetre*n/160;e.simulation.setEmissionFrame({x:t.center.x,y:t.center.y,angle:0,scaleX:i,scaleY:i,width:Bb(i,.65,2)}),e.gain=r}tether(e,t,n){return{x:e.x,y:e.y,angle:Math.atan2(t.y-e.y,t.x-e.x),scaleX:Math.max(.001,Math.hypot(t.x-e.x,t.y-e.y)/300),scaleY:Bb(Math.hypot(t.x-e.x,t.y-e.y)/300,.6,3)*(.95-n*.25),width:.75+n*.45}}strike(e,t,n){let r=e.simulation;r.reset(),r.setEmissionFrame(),r.configure({strikesPerSecond:0,branching:1.8,intensity:1.8});let i=r.onEmission;r.onEmission=void 0,r.discharge(1);for(let e=0;e<24;e++)r.step(1/60);r.onEmission=i;let a=r.writeInstances(this.scratch),o=this.scratch.slice(0,a*10),s=[],c=(e,t,n=!1)=>{if(e.length<2)return;let r=[0];for(let t=1;t<e.length;t++)r.push(r[t-1]+Math.hypot(e[t].x-e[t-1].x,e[t].y-e[t-1].y));let i=r[r.length-1];for(let c=0;c<a&&s.length<22e3;c++){let a=c*10;for(let t of[0,2]){let c=Bb(o[a+t]/300,0,1)*i,l=1;for(;l<r.length-1&&r[l]<c;)l++;let u=e[l-1],d=e[l],f=Math.max(.001,r[l]-r[l-1]),p=Bb((c-r[l-1])/f,0,1),m=n?Math.min(.15,i/300*.1):Math.min(3,Math.max(.65,i/300*.85)),h=o[a+t+1]*m;s.push(u.x+(d.x-u.x)*p-(d.y-u.y)/f*h,u.y+(d.y-u.y)*p+(d.x-u.x)/f*h)}s.push(o[a+4]*t,o[a+5],o[a+6],o[a+7],Bb(o[a]/300,0,1),Bb(o[a+2]/300,0,1))}};c([t.center,n],1.25);for(let e of t.lightning.branches.filter(e=>Math.hypot(e.x-n.x,e.y-n.y)>8).slice(0,4))c([n,e],.8),this.emit?.(e,{x:e.x-n.x,y:e.y-n.y},1.2);for(let e of t.lightning.paths?.slice(0,4)??[])c(e,.85,!0),e.length&&this.emit?.(e[e.length-1],{x:0,y:-1},1.2);this.strikes.push({data:new Float32Array(s),age:0,source:{...t.center},target:{...n},shook:!1}),this.strikes.length>4&&this.strikes.shift(),this.emit?.(n,{x:n.x-t.center.x,y:n.y-t.center.y},2.8),this.emit?.(t.center,{x:t.center.x-n.x,y:t.center.y-n.y},1.8),r.reset()}step(e,t,n,r){let i=Bb(e,0,.05);this.elapsed+=i,this.emit=n,this.visible.length=0,this.volumes.length=0;for(let e=this.strikes.length-1;e>=0;e--){let t=this.strikes[e],a=t.age;t.age+=i,!t.shook&&t.age>=.075&&(t.shook=!0,r?.(t.target),n?.(t.source,{x:0,y:-1},2.4));for(let e=0;e<t.data.length;e+=80){let r=(1-t.data[e+8])*.075;a<=r&&t.age>r&&a<.08&&n?.({x:t.data[e],y:t.data[e+1]},{x:t.data[e+3]-t.data[e+1],y:t.data[e]-t.data[e+2]},.6)}t.age>1.5&&this.strikes.splice(e,1)}for(let e of this.vehicles.values()){e.volumeTarget=0;for(let t of[e.field,e.charge,e.arc,e.halo])t?.simulation.configure({strikesPerSecond:0})}for(let e of t.slice(0,6)){let t=e.lightning.phase===`charging`,n=e.lightning.phase===`discharged`;if(!e.attractor&&!t&&!n&&!e.electrified)continue;let r=this.vehicles.get(e.id);r||(this.vehicles.size>=8&&this.release(this.vehicles.keys().next().value),r={touched:this.elapsed,dischargeId:-1},this.vehicles.set(e.id,r)),r.touched=this.elapsed;let i=Bb(e.lightning.charge,0,1);if(e.attractor){let t=r.field??=this.create(`field`,131+e.id.length);t.simulation.configure({strikesPerSecond:5,intensity:.95,corona:.6,branching:.35}),this.radial(t,e,e.attractorRadiusM,.9),r.volume={center:e.center,radius:e.attractorRadiusM*e.pixelsPerMetre,pull:!0,gain:r.volume?.gain??0},r.volumeTarget=1.3}if(t){let t=r.charge??=this.create(`field`,431+e.id.length);t.simulation.configure({strikesPerSecond:5+i*6,intensity:1+i*.7}),this.radial(t,e,2.8-i*.8,.9),e.attractor||(r.volume={center:e.center,radius:e.pixelsPerMetre*(2.8-i*.8),gain:r.volume?.gain??0},r.volumeTarget=.25+i*.3)}let a=e.lightning.target;if((t||n)&&a){let o=r.arc??=this.create(`arc`,761+e.id.length);n&&e.lightning.dischargeId!==r.dischargeId&&this.strike(o,e,a),t&&(o.simulation.setEmissionFrame(this.tether(e.center,a,i)),o.simulation.configure({strikesPerSecond:2+i*7,branching:.9+i*.5,intensity:.6+i*.5}),o.gain=i**1.4*.9)}if(e.electrified){let t=r.halo??=this.create(`halo`,919+e.id.length);t.simulation.configure({strikesPerSecond:8,intensity:.95}),this.radial(t,e,e.lengthM*.7,.9)}r.dischargeId=e.lightning.dischargeId}for(let[e,t]of this.vehicles)if(t.volume&&(t.volume.gain+=((t.volumeTarget??0)-t.volume.gain)*(1-Math.exp(-i*10)),t.volume.gain>.003&&this.volumes.push(t.volume)),this.elapsed-t.touched>2)this.release(e);else for(let e of[t.field,t.charge,t.arc,t.halo])e&&(e.simulation.step(i),e.simulation.stats.strokes>0&&this.visible.push(e))}writeInstances(e,t=0){let n=t,r=()=>n*10+10<=e.length;for(let t of this.volumes){if(!r())break;let i=this.cameraOrigin.x+t.center.x*this.cameraScale,a=this.cameraOrigin.y+t.center.y*this.cameraScale,o=n++*10;e.set([i,a,i+.01,a,t.radius*this.cameraScale,t.gain,+!!t.pull,5,0,1],o)}for(let t of this.strikes)for(let i=0;i<t.data.length&&r();i+=10){let r=n++*10;e.set(t.data.subarray(i,i+10),r);let a=(1-(t.data[i+8]+t.data[i+9])*.5)*.075,o=t.age-a,s=o<0?.1:t.age<.15?2.5:Math.exp(-(t.age-.15)*3.7)*1.8;e[r+5]*=s,e[r+4]*=o>=0&&o<.08?1.4:1,this.projectInstance(e,r)}for(let t of this.visible){let r=e.subarray(n*10,Math.min(e.length,(n+1200)*10)),i=t.simulation.writeInstances(r),a=t.pull&&i?r[6]:-1;for(let e=0;e<i;e++){let n=e*10;r[n+5]*=t.gain,t.pull&&(r[n+7]===2?r[n+5]*=.2:r[n+6]===a?(r[n+7]=0,r[n+5]*=1.2):(r[n+7]=3,r[n+4]*=3.8)),this.projectInstance(r,n)}n+=i}return n-t}projectInstance(e,t){for(let n of[0,2])e[t+n]=this.cameraOrigin.x+e[t+n]*this.cameraScale,e[t+n+1]=this.cameraOrigin.y+e[t+n+1]*this.cameraScale;e[t+4]*=this.cameraScale,e[t+8]*=this.cameraScale,e[t+9]*=this.cameraScale}draw(e,t,n,r,i,a,o=1,s=e=>e,c=1){if(!this.active||this.failed||o<=0)return;if(!this.gpu)try{this.gpu=new Rb}catch{this.failed=!0;return}this.cameraScale=c;let l=s({x:0,y:0});this.cameraOrigin=l,this.gpu.resize(t,n,r),this.gpu.render(this,i,{dark:a,exposure:a?1.05:1.2,...zb,noiseOrigin:[-l.x/c,-l.y/c],noiseScale:1/c}),this.cameraOrigin={x:0,y:0},this.cameraScale=1,e.save(),e.globalAlpha*=o,this.gpu.canvas.width*this.gpu.canvas.height/1e6,e.drawImage(this.gpu.canvas,0,0,t,n),e.restore()}release(e){let t=this.vehicles.get(e);if(t){for(let e of[t.field,t.charge,t.arc,t.halo])e?.simulation.dispose();this.vehicles.delete(e)}}reset(){for(let e of this.vehicles.keys())this.release(e);this.visible.length=0,this.strikes.length=0,this.volumes.length=0,this.elapsed=0}dispose(){this.reset(),this.gpu?.dispose(),this.gpu=null}},Gb=class{camera;effects=new Wb;clock=0;constructor(e){this.camera=e}step(e,t,n,r,i){if(this.clock+=n,this.clock<1/60)return;let a=Math.min(.05,this.clock);this.clock=Math.max(0,this.clock-1/60);let o=[];for(let n of[e,...t]){let e=n.sim;if(e.mode!==`car`||e.car.explodedAt!==null||n.isGhost)continue;let t=n.weapons.lightning.visual,r=e.car.statusEffects.remaining(`electrified`)>0;if(!n.controls.attractor&&t.phase===`idle`&&!r)continue;let i=this.camera.screen(e.body.position),a=Math.max(7,Mn(e.car.preset,this.camera.width,this.camera.documentScale()))*this.camera.zoom;i.x<-a||i.x>this.camera.width+a||i.y<-a||i.y>this.camera.height+a||o.push({id:n.id,center:this.camera.documentPoint(e.body.position),angle:-e.body.angle,pixelsPerMetre:this.camera.documentScale(),lengthM:e.car.preset.geometry.lengthM,widthM:e.car.preset.geometry.widthM,attractor:!!n.controls.attractor&&!e.paused,attractorRadiusM:7,electrified:r,lightning:t})}this.effects.step(e.sim.paused?0:a,o,(e,t,n)=>r.electric(this.camera.particlePoint(this.camera.worldFromDocument(e)),this.camera.pixelSpace?t:D(t.x/this.camera.documentScale(),-t.y/this.camera.documentScale()),n),()=>i.trigger(`lightning`,1,performance.now()))}draw(e,t,n,r){this.effects.draw(e,this.camera.width,this.camera.height,this.camera.dpr,t/1e3,n,r,e=>this.camera.screen(this.camera.worldFromDocument(e)),this.camera.zoom/this.camera.documentScale())}reset(){this.clock=0,this.effects.reset()}dispose(){this.effects.dispose()}},Kb=class{overlay;canvasWorld;carVisualOffset(e){return this.vehicles.carVisualOffset(e)}get cameraLock(){return this.view.cameraLock}set cameraLock(e){this.view.cameraLock=e}get cameraSmoothing(){return this.view.cameraSmoothing}set cameraSmoothing(e){this.view.cameraSmoothing=e}get deadZone(){return this.view.deadZone}set deadZone(e){this.view.deadZone=e}get speedZoom(){return this.view.speedZoom}set speedZoom(e){this.view.speedZoom=e}get speedZoomMinimumScale(){return this.view.speedZoomMinimumScale}set speedZoomMinimumScale(e){this.view.speedZoomMinimumScale=e}screen(e){return this.view.screen(e)}world(e){return this.view.world(e)}vehicleViewportPosition(e){return this.view.vehicleViewportPosition(e)}sceneScroll(){return this.view.sceneScroll()}get documentProjection(){return this.view.documentProjection}virtualOffset(){return this.view.virtualOffset()}documentPoint(e){return this.view.documentPoint(e)}worldFromDocument(e){return this.view.worldFromDocument(e)}documentScale(){return this.view.documentScale()}viewportSize(){return this.view.viewportSize()}presentationScale(){return this.view.presentationScale()}setSlowMoZoom(e){this.view.slowMoZoom=e}setCanvasWorldScale(e,t=1.5){this.view.setCanvasWorldScale(e,t)}setCameraFrame(e){this.view.setCameraFrame(e)}setCameraLock(e){this.view.setCameraLock(e)}viewportFromDocument(e){return this.view.viewportFromDocument(e)}documentFromViewport(e){return this.view.documentFromViewport(e)}bounds(){return this.view.bounds()}vehicleMarkerAt(e){if(!this.showVehicleMarkers)return null;let t=this.view.documentFromViewport(e);return this.vehicles.markerAt(this.view.screen(this.view.worldFromDocument(t)))}revealVehicle(e){this.view.revealVehicle(e)}resumeFollow(){this.view.resumeFollow()}interruptFollow(){this.view.interruptFollow()}restorePage(e){this.view.restorePage(e)&&(this.lastFlowCenter=null,this.flowVelocity=D())}followDocument(e){return this.view.followDocument(e)}primaryVehicleVisible=!0;primaryVehicleOpacity=1;beginVehicleArrivalFade(){this.skidTracks.beginReveal(this.skidView(),this.darkSurface()),this.primaryVehicleOpacity=0}setVehicleArrivalOpacity(e){this.primaryVehicleOpacity=P(e,0,1),this.skidTracks.setRevealAlpha(this.primaryVehicleOpacity,this.skidView(),this.darkSurface())}view;surface;vehicles;debris=new xs;get ctx(){return this.surface.context}nextHistoryPrune=0;trailClock=0;quality=`high`;fluidGovernor=new _c;vehicleLights=new El;surfaceTones=new Qd;vehicleLighting={...Dl};setVehicleLighting(e){this.vehicleLighting=Ol({...this.vehicleLighting,...e})}getVehicleLighting(){return{...this.vehicleLighting}}toggleVehicleLight(e){return this.setVehicleLighting({[e]:!this.vehicleLighting[e]}),this.getVehicleLighting()}surfaceTone=`auto`;trail=[];skidTracks=new mb;volumetrics;pointPuffs=[];objectGlint=null;showVehicleMarkers=!0;tireSmokeEnabled=!0;vehicleShadowsEnabled=!0;effectsFadeStartedAt=null;wallRects=[];combustion;ghostVehicles=new af;sparks=new vy;electricity;liquidLayer;tireMarks=new ob;seedGroundMarks(e){this.overlay&&this.tireMarks.seed(e,this.particleScale())}focusVehicle=null;activeVehicles=[];bindVehicle(e){this.focusVehicle=e}forgetVehicle(e){this.tireMarks.forgetVehicle(e),this.activeVehicles=this.activeVehicles.filter(t=>t.id!==e),this.focusVehicle?.id===e&&(this.focusVehicle=null)}get rocketFlightPosition(){let e=this.focusVehicle?.sim.body.position??D(),t=null,n=1/0;for(let r of this.activeVehicles){let i=r.weapons.rocket.projectile?.position;if(!i)continue;let a=M(k(i,e));a<n&&(t=i,n=a)}return t}screenShake=new _b;exhaustBursts=[];queueExhaustPops(e){for(let t of e)t<.12||this.exhaustBursts.push({age:0,lifetime:.08+t*.11,intensity:.4+t*.6});this.exhaustBursts.length>6&&this.exhaustBursts.splice(0,this.exhaustBursts.length-6)}lastFlowCenter=null;flowVelocity=D();captureState(){let e=[],t=t=>(t&&e.push(()=>t.dispose()),t);try{let n=t(this.volumetrics.captureState()),r=t(this.combustion.captureState()),i=t(this.liquidLayer.captureState());return{at:performance.now(),data:E({primaryVehicleVisible:this.primaryVehicleVisible,primaryVehicleOpacity:this.primaryVehicleOpacity,nextHistoryPrune:this.nextHistoryPrune,trailClock:this.trailClock,quality:this.quality,fluidQualityLimit:this.fluidGovernor.limit,vehicleLighting:this.vehicleLighting,surfaceTone:this.surfaceTone,trail:this.trail,pointPuffs:this.pointPuffs,showVehicleMarkers:this.showVehicleMarkers,tireSmokeEnabled:this.tireSmokeEnabled,vehicleShadowsEnabled:this.vehicleShadowsEnabled,effectsFadeStartedAt:this.effectsFadeStartedAt,wallRects:this.wallRects,exhaustBursts:this.exhaustBursts,lastFlowCenter:this.lastFlowCenter,flowVelocity:this.flowVelocity,debugDrive:this.debugDrive,previewGroundFire:this.previewGroundFire,previewWallSmoke:this.previewWallSmoke,previewSparks:this.previewSparks,previewDamage:this.previewDamage,previewOil:this.previewOil,previewOilSplatter:this.previewOilSplatter,oilSplatterPreviewSeconds:this.oilSplatterPreviewSeconds,sparkPreviewClock:this.sparkPreviewClock,damagePreviewApplied:this.damagePreviewApplied,groundFirePreviewLit:this.groundFirePreviewLit,tourDebug:this.tourDebug,trailLifetime:this.trailLifetime,fallbackSurfaceTone:this.fallbackSurfaceTone}),camera:this.view.captureState(),diagnostics:this.diagnostics.captureState(),vehicles:this.vehicles.captureState(),volumetrics:n,combustion:r,liquids:i,debris:this.debris.captureState(),skidTracks:this.skidTracks.captureState(),tireMarks:this.tireMarks.captureState(),sparks:this.sparks.captureState(),screenShake:this.screenShake.captureState(),dispose:()=>e.forEach(e=>e())}}catch(t){throw e.forEach(e=>e()),t}}restoreState(e){let t=this.captureState();try{this.applyState(e)}catch(e){try{this.applyState(t)}catch(t){throw AggregateError([e,t],`Renderer checkpoint rollback failed`,{cause:t})}throw e}finally{t.dispose()}}applyState(e){this.clearEffects();let t=E(e.data);this.primaryVehicleVisible=t.primaryVehicleVisible,this.primaryVehicleOpacity=t.primaryVehicleOpacity,this.nextHistoryPrune=t.nextHistoryPrune,this.trailClock=t.trailClock,this.quality=t.quality,this.fluidGovernor.restoreLimit(t.fluidQualityLimit),this.vehicleLighting=t.vehicleLighting,this.surfaceTone=t.surfaceTone,this.trail=t.trail,this.pointPuffs=t.pointPuffs,this.showVehicleMarkers=t.showVehicleMarkers,this.tireSmokeEnabled=t.tireSmokeEnabled,this.vehicleShadowsEnabled=t.vehicleShadowsEnabled,this.effectsFadeStartedAt=t.effectsFadeStartedAt,this.wallRects=t.wallRects,this.exhaustBursts=t.exhaustBursts,this.lastFlowCenter=t.lastFlowCenter,this.flowVelocity=t.flowVelocity,this.debugDrive=t.debugDrive,this.previewGroundFire=t.previewGroundFire,this.previewWallSmoke=t.previewWallSmoke,this.previewSparks=t.previewSparks,this.previewDamage=t.previewDamage,this.previewOil=t.previewOil,this.previewOilSplatter=t.previewOilSplatter,this.oilSplatterPreviewSeconds=t.oilSplatterPreviewSeconds,this.sparkPreviewClock=t.sparkPreviewClock,this.damagePreviewApplied=t.damagePreviewApplied,this.groundFirePreviewLit=t.groundFirePreviewLit,this.tourDebug=t.tourDebug,this.trailLifetime=t.trailLifetime,this.fallbackSurfaceTone=t.fallbackSurfaceTone,this.view.restoreState(e.camera),this.diagnostics.restoreState(e.diagnostics),this.vehicles.restoreState(e.vehicles),this.volumetrics.setQuality(this.fluidGovernor.apply(this.quality)),this.volumetrics.restoreState(e.volumetrics),this.combustion.setQuality(this.fluidGovernor.apply(this.quality)),this.combustion.restoreState(e.combustion),this.liquidLayer.restoreState(e.liquids),e.debris&&this.debris.restoreState(e.debris),this.skidTracks.restoreState(e.skidTracks,this.skidView(),this.darkSurface()),this.tireMarks.restoreState(e.tireMarks),this.sparks.restoreState(e.sparks),this.screenShake.restoreState(e.screenShake),this.effectsFadeStartedAt!==null&&(this.effectsFadeStartedAt+=performance.now()-e.at),this.view.rebaseTime(performance.now()),this.ghostVehicles.clearMaterials(),this.view.restorePresentation()}get flamethrowerFiring(){return this.activeVehicles.some(e=>e.weapons.flamethrower.firing)}get managedMemoryGroups(){return[{label:`Tire marks`,bytes:this.skidTracks.managedBytes+this.activeVehicles.reduce((e,t)=>e+t.tirePaint.managedBytes,0)+this.tireMarks.managedBytes},{label:`Smoke`,bytes:this.volumetrics.smokeBytes},{label:`Ghost`,bytes:this.volumetrics.ghostBytes},{label:`Fire`,bytes:this.combustion.managedBytes},{label:`Liquids`,bytes:this.liquidLayer.managedBytes},{label:`Debris`,bytes:this.debris.managedBytes+Uc().bytes},{label:`Tools`,bytes:this.activeVehicles.reduce((e,t)=>e+t.weapons.managedBytes,0)},{label:`Sparks`,bytes:this.sparks.count*112},{label:`Points`,bytes:this.pointPuffs.length*32},{label:`Vehicle trail`,bytes:this.trail.length*48}]}get managedBytes(){return this.managedMemoryGroups.reduce((e,t)=>e+t.bytes,0)}debugDrive=!1;previewGroundFire=!1;previewWallSmoke=!1;previewSparks=!1;previewDamage=!1;previewOil=!1;previewOilSplatter=!1;oilSplatterPreviewSeconds=0;sparkPreviewClock=0;damagePreviewApplied=!1;groundFirePreviewLit=!1;diagnostics=new bl;tourDebug=null;trailLifetime=12;constructor(e,t=!1,n=`high`,r=!1){this.overlay=t,this.canvasWorld=r,this.sparks.setElectricalPalette(zb),this.view=new vl(t,r,()=>this.resize()),this.surface=new yl(e,this.view,t,r),this.combustion=new Xv(this.view,n),this.volumetrics=new Qv(this.view,n),this.electricity=new Gb(this.view),this.liquidLayer=new nb(this.view,n),this.vehicles=new el(this.view),this.quality=n,this.resize()}get pixelSpace(){return this.overlay||this.canvasWorld}prepareFire(){return this.sparks.prepare()?this.combustion.ensure():!1}setQuality(e){if(e===this.quality)return;this.quality=e;let t=this.fluidGovernor.apply(e);this.volumetrics.setQuality(t),this.liquidLayer.setQuality(e),this.combustion.setQuality(t)}applyFluidQuality(){let e=this.fluidGovernor.apply(this.quality);this.volumetrics.setQuality(e),this.combustion.setQuality(e)}setSmokeTint(e){this.volumetrics.setSmokeTint(e)}setTireSmokeEnabled(e){this.tireSmokeEnabled=e}setVehicleShadowsEnabled(e){this.vehicleShadowsEnabled=e}setGhostStyle(e){this.volumetrics.setGhostStyle(e)}setSparksEnabled(e){this.sparks.setEnabled(e)}setScreenShakeEnabled(e){this.screenShake.setEnabled(e)}setScreenShakeProfiles(e){this.screenShake.setProfiles(e)}emitCrashShake(e){if(this.effectsFadeStartedAt!==null)return;let t=gb(e);t&&this.screenShake.trigger(t)}emitRocketExplosionShake(e=1){this.effectsFadeStartedAt===null&&this.screenShake.trigger(`rocketExplosion`,Math.sqrt(Math.max(0,e)))}emitCombustibleExplosion(e,t){if(this.effectsFadeStartedAt!==null)return;this.screenShake.trigger(`combustibleExplosion`);let n=this.particlePoint(this.worldFromDocument(e));this.sparks.emitExplosion(n,D(),this.particleScale(),1.2),this.combustion.queueBlast(n,t*this.particleScale()/Math.max(1,this.documentScale())),this.emitCombustibleBlast(e,t,0)}emitCombustibleBlast(e,t,n){if(this.effectsFadeStartedAt!==null||!this.combustion.activateBuoyancy())return;let r=this.particlePoint(this.worldFromDocument(e)),i=t*this.particleScale()/Math.max(1,this.documentScale()),a=Math.min(1,n/.34);for(let e=0;e<24;e++){let t=e*Math.PI*(3-Math.sqrt(5)),n=D(Math.cos(t),Math.sin(t));this.combustion.queueStamp({point:O(r,A(n,i*a*1.05)),radius:Math.max(4,i*(.29-a*.12)),flow:O(A(n,i*(2.6-a)),D(0,-i*.4)),progress:.28+a*.53,blast:!0})}}emitRocketExplosion(e,t,n=1){if(this.effectsFadeStartedAt!==null)return;let r=this.particlePoint(this.worldFromDocument(e)),i=this.particleVelocity(D(t.x/this.view.zoom,-t.y/this.view.zoom)),a=this.particleScale(),o=Math.sqrt(P(n,.5,2));this.combustion.ensure()&&(this.combustion.queueBlast(r,a*2.2*o),this.combustion.queueStamp({point:r,radius:a*.95*o,flow:D(0,-a*.7),progress:.24,strength:2.6,blast:!0}));for(let t=0;t<64;t++){let n=t*Math.PI*(3-Math.sqrt(5))+Math.atan2(i.y,i.x),s=a*Math.sqrt((t+.5)/64)*1.75*(.83+.17*Math.sin(t*11.8+e.x*.03))*o,c=D(Math.cos(n),Math.sin(n));this.combustion.available&&this.combustion.queueStamp({point:O(r,A(c,s)),radius:a*(.38+t%4*.065)*o,flow:O(A(c,a*2.5),D(0,-a*.5)),progress:.3+t%5*.06,strength:1.7+t%3*.28,blast:!0})}this.sparks.emitExplosion(r,i,a,n),this.sparks.emitFireAt(r,a*.5,.25,14)}setDeformEnabled(e){this.focusVehicle?.damage.setEnabled(e),e||(this.damagePreviewApplied=!1)}resetVehicleDamage(){this.focusVehicle?.damage.reset()}emitSparks(e){this.effectsFadeStartedAt===null&&this.sparks.emit(e)}emitVehicleBurn(e,t,n,r){let i=e.sim,a=this.documentScale(),o=O(this.documentPoint(i.body.position),this.carVisualOffset(i)),s=n.lengthM*a,c=n.widthM*a,l=D(Math.cos(i.body.angle),-Math.sin(i.body.angle)),u=D(-l.y,l.x),d=O(o,O(A(l,t.burnOriginLocal.x*a),A(u,t.burnOriginLocal.y*a))),f=this.combustion.alphaFor(n.alpha.solid);if(t.stage===`exploded`)return t.explosionStarted&&this.emitCombustibleExplosion(o,Math.max(78,s*.7)),t.blastAge<Tt.fireballSeconds&&this.emitSceneFire({key:t.key,alpha:f,pixelWidth:n.alpha.columns,pixelHeight:n.alpha.rows,x:o.x-s/2,y:o.y-c/2,width:s,height:c,angle:-i.body.angle,origin:o,farthest:Math.hypot(s,c),...Pt(t.blastAge)},r),t.blastPulse&&this.emitCombustibleBlast(o,Math.max(78,s*.7),t.blastAge),t.explosionStarted?o:null;let p=Nt(t.health,t.maxHealth,s,c);return p&&this.emitSceneFire({key:t.key,alpha:f,pixelWidth:n.alpha.columns,pixelHeight:n.alpha.rows,x:o.x-s/2,y:o.y-c/2,width:s,height:c,angle:-i.body.angle,origin:d,farthest:Math.hypot(s,c),...p},r),null}sceneFireDue(e){return this.effectsFadeStartedAt===null&&this.combustion.sceneMasksDue(e)}emitSceneFire(e,t=1/60){this.effectsFadeStartedAt===null&&this.combustion.queueMask(e)}pourWorldLiquid(e,t,n,r,i){this.liquidLayer.pourWorldLiquid(e,t,n,r,i)}emitPaint(e,t,n,r,i){this.liquidLayer.emitPaint(e,t,n,r,i)}hasConductiveLiquidNear(e,t){return this.liquidLayer.hasConductiveCandidate(e,t)}conductLightning(e,t=0){return this.liquidLayer.conductLightning(e,t)}igniteLiquidAt(e,t){this.liquidLayer.igniteAt(e,t)}igniteConductedLiquids(e,t){this.liquidLayer.igniteConducted(e,t)}igniteLiquidsFromFire(e){this.liquidLayer.igniteFromFire(e)}burningLiquidSources(){return this.liquidLayer.burningSources()}hasLiquidContact(e,t){return this.liquidLayer.hasContact(e,t)}addLiquid(e,t){this.liquidLayer.add(e,t)}syncElementLiquids(e){return this.liquidLayer.syncElements(e)}ejectLiquid(e,t=`oil`,n){this.liquidLayer.pourVehicle(e,t,.65,n)}setInitialPuddles(e){this.liquidLayer.setInitialPuddles(e)}setSurfaceTone(e){this.surfaceTone=e}fallbackSurfaceTone={at:-1/0,dark:!1};darkSurface(){if(this.surfaceTone!==`auto`)return this.surfaceTone===`dark`;let e=document.documentElement.dataset.jrTheme;if(e===`light`||e===`dark`)return e===`dark`;let t=performance.now();if(t-this.fallbackSurfaceTone.at<80)return this.fallbackSurfaceTone.dark;let n=getComputedStyle(document.body).backgroundColor,r=Al(/rgba\([^)]*,\s*0(?:\.0+)?\s*\)/.test(n)||n===`transparent`?getComputedStyle(document.documentElement).backgroundColor:n);return this.fallbackSurfaceTone={at:t,dark:r},r}setDebugEnabled(e){this.debugDrive=e||!1}setTourDebugRoute(e,t=[]){this.tourDebug=e?{route:e,stops:t}:null}fadeEffects(){if(this.effectsFadeStartedAt!==null)return;this.effectsFadeStartedAt=performance.now(),this.liquidLayer.clearEffects(),this.liquidLayer.restoreInitialPuddles(),this.volumetrics.clearSmokeSources();let e=this.activeVehicles.length?this.activeVehicles:this.focusVehicle?[this.focusVehicle]:[];for(let t of e)t.weapons.reset(),t.tirePaint.reset(),t.damage.reset();this.screenShake.reset(),this.electricity.reset(),this.skidTracks.fade(),this.combustion.clearTireHistory(),this.exhaustBursts=[]}clearEffects(e=!0){this.debris.reset(),this.electricity.reset(),this.objectGlint?.dispose(),this.objectGlint=null,this.trail=[],this.skidTracks.clear(),this.volumetrics.reset(),this.pointPuffs=[];for(let e of this.activeVehicles.length?this.activeVehicles:this.focusVehicle?[this.focusVehicle]:[])e.weapons.rocket.reset(),e.weapons.machineGuns.reset(),e.weapons.flamethrower.reset();this.screenShake.reset(),this.combustion.reset(),this.exhaustBursts=[],this.sparks.reset(),e&&this.liquidLayer.clearEffects(),this.tireMarks.clear(),this.lastFlowCenter=null,this.flowVelocity=D(),this.trailClock=0,this.effectsFadeStartedAt=null}reset(){this.view.reset(),this.clearEffects(),this.liquidLayer.restoreInitialPuddles(),this.wallRects=[],this.groundFirePreviewLit=!1,this.sparkPreviewClock=0,this.damagePreviewApplied=!1,this.vehicles.reset(),this.tourDebug=null,this.surface.clear(),this.view.resetFollow()}dispose(){this.liquidLayer.dispose(),this.debris.clear(),this.electricity.dispose(),this.objectGlint?.dispose(),this.surface.dispose(),this.view.dispose(),this.skidTracks.clear(),this.tireMarks.clear(),this.volumetrics.dispose(),this.combustion.dispose(),this.sparks.dispose()}resize(){let e=this.surface.resize();this.liquidLayer.resize(),this.volumetrics.resize(e),this.combustion.resize(e)}rasterPixelRatio(){return this.canvasWorld?Math.min(2,Math.round(this.view.dpr/this.view.regionScale*100)/100):this.view.dpr}setShowVehicleMarkers(e){this.showVehicleMarkers=e}flashTargets(e){this.resize(),this.objectGlint??=new Sb;let t=this.sceneScroll();this.objectGlint.trigger(this.view.width,this.view.height,this.view.dpr,n=>e(n,t))}particlePoint(e){return this.view.particlePoint(e)}particleScreen(e){return this.pixelSpace?k(e,this.sceneScroll()):this.screen(e)}particleVelocity(e){return this.pixelSpace?D(e.x*this.view.zoom,-e.y*this.view.zoom):{...e}}particleScale(){return this.view.particleScale()}emitPoints(e,t){t<=0||this.pointPuffs.push({point:this.particlePoint(this.worldFromDocument(e)),amount:t,age:0})}fluidView(){let e=this.sceneScroll();return this.pixelSpace?{origin:D(this.view.smokeMargin-e.x,this.view.smokeMargin-e.y),scaleX:1,scaleY:1}:{origin:D(this.view.width/2-this.view.camera.x*this.view.zoom,this.view.height/2+this.view.camera.y*this.view.zoom),scaleX:this.view.zoom,scaleY:-this.view.zoom}}flameView(){let e=this.fluidView();return this.pixelSpace?{...e,origin:D(e.origin.x-this.view.smokeMargin,e.origin.y-this.view.smokeMargin)}:e}clipFluidWalls(e){if(!this.overlay)return;let t=this.sceneScroll();for(let n of this.wallRects){let r=n.x-t.x,i=n.y-t.y;n.width<=0||n.height<=0||r>=this.view.width||i>=this.view.height||r+n.width<=0||i+n.height<=0||(e.beginPath(),e.rect(0,0,this.view.width,this.view.height),e.rect(r,i,n.width,n.height),e.clip(`evenodd`))}}stepVehicleWeapons(e,t,n,r,i,a,o,s,c){let l=e.sim;performance.now(),e.weapons.rocket.step(t,l,e=>{this.effectsFadeStartedAt===null&&this.volumetrics.emitSmoke({point:this.particlePoint(e.point),amount:e.amount,flow:this.particleVelocity(e.flow),radiusPx:e.radiusM*this.view.zoom,swirlPx:10})},n?(t,r,i)=>{let a=n(e,this.documentPoint(t),this.documentPoint(r),i*this.documentScale());return a?this.worldFromDocument(a):null}:void 0,e=>{this.effectsFadeStartedAt===null&&this.combustion.emitJet(e.from,e.to,e.flow,e.widthM,e.intensity,`rocket`)},o,s,void 0),e.weapons.machineGuns.step(t,l,r?(t,n,i)=>{let a=r(e,this.documentPoint(t),this.documentPoint(n),i*this.documentScale());return a?this.worldFromDocument(a):null}:void 0,i,(e,t)=>{this.effectsFadeStartedAt===null&&this.sparks.emitBulletImpact(this.particlePoint(e),this.particleVelocity(t)),c?.(e)}),e.weapons.flamethrower.step(t,l,e=>{this.effectsFadeStartedAt===null&&this.volumetrics.emitSmoke({point:this.particlePoint(e.point),amount:e.amount,flow:this.particleVelocity(e.flow),radiusPx:e.radiusM*this.view.zoom,swirlPx:10})},a?(t,n,r,i)=>{let o=a(e,this.documentPoint(t),this.documentPoint(n),r*this.documentScale(),i);return o?this.worldFromDocument(o):null}:void 0,(e,n,r,i,a)=>{if(this.effectsFadeStartedAt!==null)return;let o=this.particleScale();this.liquidLayer.igniteAlong(this.particlePoint(e),this.particlePoint(n),r*o*.5),a>.3&&this.sparks.emitFireAt(this.particlePoint(n),r*o*.4,t,3),this.combustion.queueStamp({point:this.particlePoint(n),radius:r*o,progress:a,flow:this.particleVelocity(i)})})}sprayTirePaint(e,t,n,r,i,a,o,s){this.liquidLayer.splatter(e,t,n,r,i,a,o,s)}advanceEffects(e,t,{walls:n=[],carMask:r,tirePaintSources:i=[],driven:a=!0,rocketCollision:o,bulletCollision:s,onGunshot:c,flameContact:l,onRocketLaunch:u,onRocketImpact:d,onBulletImpact:f,maskFor:p,companions:m=[]}={}){for(let e of this.pointPuffs)e.age+=t;this.pointPuffs=this.pointPuffs.filter(e=>e.age<.9),this.activeVehicles=[e,...m];let h=this.sceneScroll();this.debris.count&&this.debris.step(t,this.activeVehicles.filter(e=>e.sim.mode===`car`&&!e.isGhost&&e.sim.car.explodedAt===null).map(e=>{let t=this.particlePoint(e.sim.body.position),n=this.particleVelocity(e.sim.body.velocity),r=this.particleScale();return{x:t.x,y:t.y,vx:n.x,vy:n.y,angle:-e.sim.body.angle,length:e.sim.car.preset.geometry.lengthM*r,width:e.sim.car.preset.geometry.widthM*r}}),{x:h.x,y:h.y,width:this.view.width,height:this.view.height},n),this.volumetrics.stepGhost(t,this.activeVehicles,n,p,this.flameView(),e=>this.carVisualOffset(e.sim));let g=e.sim;if(this.wallRects=n,this.vehicles.updateCarPose(g,t),this.effectsFadeStartedAt===null){for(let e of this.activeVehicles)for(let n of e.liquidEmissions(t))this.liquidLayer.pourVehicle(e.sim,ot(n.liquid),n.amount,void 0,e.id);this.previewOil&&!this.previewOilSplatter&&this.liquidLayer.pourVehicle(g,`oil`,t*6)}for(let n of[e,...m])this.stepVehicleWeapons(n,t,o,s,c,l,u,d,f);let{tires:_,companionTires:v}=this.liquidLayer.stepVehicles(e,m,t,a,i,this.effectsFadeStartedAt!==null,(e,t)=>this.emitSceneFire(e,t)),y=this.documentScale(),b=D(Math.cos(g.body.angle),-Math.sin(g.body.angle)),x=g.mode===`car`&&r&&!e.isGhost?{mask:r.alpha,shape:{center:O(this.documentPoint(g.body.position),this.carVisualOffset(g)),forward:b,side:D(-b.y,b.x),halfLength:r.lengthM*y/2,halfWidth:r.widthM*y/2}}:void 0;if(this.previewDamage&&!this.damagePreviewApplied&&x&&(this.damagePreviewApplied=e.damage.hit(O(x.shape.center,A(x.shape.forward,x.shape.halfLength)),A(x.shape.forward,-1),x.shape,20,y)),this.electricity.step(e,m,t,this.sparks,this.screenShake),performance.now(),g.mode===`car`&&M(g.body.velocity)>.15&&this.sparks.disturb(this.particlePoint(g.body.position),this.particleVelocity(g.body.velocity),this.particleScale()*2.8),this.sparks.step(t,{walls:n,car:x}),this.previewSparks&&g.mode===`car`&&(this.sparkPreviewClock+=t,this.sparkPreviewClock>.12)){this.sparkPreviewClock=0;let e=this.particlePoint(g.body.position),t=this.particleScale();this.emitSparks({point:O(e,D(t*1.9,0)),velocity:D(t*4,t*10),normal:D(-1,0),pixelsPerMeter:t})}let S=this.particleScale(),C=this.particlePoint(g.body.position),w=this.lastFlowCenter?A(k(C,this.lastFlowCenter),1/Math.max(t,1e-4)):this.particleVelocity(g.body.velocity),ee=M(w),te=ee>40*S?A(w,40*S/ee):w;this.flowVelocity=O(this.flowVelocity,A(k(te,this.flowVelocity),1-Math.exp(-12*t))),this.lastFlowCenter=C;let ne=this.pixelSpace?this.flowVelocity:D(this.flowVelocity.x*this.view.zoom,-this.flowVelocity.y*this.view.zoom),re=D(Math.cos(g.body.angle),-Math.sin(g.body.angle)),ie=g.mode===`car`?{center:O(this.screen(g.body.position),D(this.view.smokeMargin,this.view.smokeMargin)),velocity:ne,forward:re,halfLength:g.car.preset.geometry.lengthM*this.view.zoom*.46,halfWidth:g.car.preset.geometry.widthM*this.view.zoom*.39,spin:-g.body.spin}:null;if(this.effectsFadeStartedAt!==null){this.volumetrics.clearSmokeSources(),this.combustion.stepTire(t),this.combustion.step(t,this.view.timeSeconds,e.isGhost?null:ie,this.wallRects,!0,this.flameView(),this.sparks),this.volumetrics.stepSmoke(t,ie,this.wallRects,this.fluidView());return}if(this.previewWallSmoke&&this.overlay){let e=this.sceneScroll(),n=this.wallRects.filter(t=>t.x-e.x>48&&t.x-e.x<this.view.width-48&&t.y+t.height/2-e.y>30&&t.y+t.height/2-e.y<this.view.height-30),r=n.find(t=>t.x-e.x>this.view.width*.5)??n[0];r&&this.volumetrics.emitSmoke({point:D(r.x-25,r.y+r.height/2),amount:t*15,flow:D(210,0),radiusPx:17,swirlPx:25})}if(performance.now(),this.combustion.stepTire(t),this.combustion.step(t,this.view.timeSeconds,e.isGhost?null:ie,this.wallRects,!1,this.flameView(),this.sparks),!this.pixelSpace){for(let e of this.trail)e.age+=t;if(this.trail=this.trail.filter(e=>e.age<this.trailLifetime),this.trailClock+=t,this.trailLifetime>0&&this.trailClock>=1/30){this.trailClock%=1/30;let e=this.trail.at(-1);(!e||M(k(e.point,g.body.position))>.04)&&this.trail.push({point:{...g.body.position},age:0,color:g.mode===`ship`?`#9bbcff`:g.mode===`brick`?`#f6bd79`:`#8ce6c5`}),this.trail.length>800&&this.trail.shift()}}if(g.mode!==`car`){this.volumetrics.stepSmoke(t,null,this.wallRects,this.fluidView()),this.skidTracks.stop(this.skidView(),this.darkSurface(),!0),this.combustion.clearTireHistory();return}if(e.isGhost){this.volumetrics.stepSmoke(t,null,this.wallRects,this.fluidView()),this.skidTracks.stop(this.skidView(),this.darkSurface()),this.combustion.clearTireHistory();return}let ae=this.advanceVehicleTireEffects(e,t,_,v,ne),oe=this.combustion.emberSource();oe&&this.sparks.emitFireAt(oe.point,oe.radius,t,20*oe.heat),performance.now(),this.volumetrics.stepSmoke(t,ie,this.wallRects,this.fluidView());let se=this.darkSurface();this.skidTracks.step(t,g,ae,t=>!!e.tirePaint.coating(t),{pixelSpace:this.pixelSpace,scale:this.particleScale(),dark:se,project:e=>this.particlePoint(e),roadAt:(e,t)=>!!this.overlay&&this.surfaceTones.at(e,this.viewportFromDocument(t),se),view:this.skidView()})}advanceVehicleTireEffects(e,t,n,r,i){let a=e.sim,o=this.particleScale();if(this.previewGroundFire&&!this.groundFirePreviewLit){for(let e of a.car.tires.filter(e=>!e.front)){let t=a.body.world(e.local);this.combustion.igniteTire(this.particlePoint(a.body.world(O(e.local,D(-2.4)))),this.particlePoint(t),a.car.preset.geometry.tireWidthM*o,18,.2*o)}this.groundFirePreviewLit=!0}let s=M(a.body.velocity),c=s>.1?A(a.body.velocity,-1/s):N(D(-1),a.body.angle);this.previewOilSplatter&&(s>.5?this.oilSplatterPreviewSeconds=0:s<.2&&(this.oilSplatterPreviewSeconds+=t),this.oilSplatterPreviewSeconds<2.25&&this.liquidLayer.pourOilPreview(n[0].point,t));let l={zoom:this.view.zoom,particlePoint:e=>this.particlePoint(e),particleVelocity:e=>this.particleVelocity(e),spray:(...e)=>this.sprayTirePaint(...e),smoke:this.tireSmokeEnabled?e=>this.volumetrics.emitSmoke(e):void 0};xb(e,n,0,t,c,i,l,this.previewOilSplatter&&s<.2&&this.oilSplatterPreviewSeconds>1&&this.oilSplatterPreviewSeconds<2.25);let u=n.length;for(let{vehicle:e,tires:n}of r){if(!e.isGhost){let r=e.sim,i=M(r.body.velocity),a=i>.1?A(r.body.velocity,-1/i):N(D(-1),r.body.angle);xb(e,n,u,t,a,this.particleVelocity(r.body.velocity),l)}u+=n.length}(e.isGhost||a.car.preset.sound.electric)&&(this.exhaustBursts=[]);for(let e of this.exhaustBursts){e.age+=t;let n=e.intensity*Math.max(0,1-e.age/e.lifetime);if(n<=0)continue;let r=N(D(-1,0),a.body.angle),i=O(A(r,4+5*n),A(a.body.velocity,.12));for(let e of this.vehicles.exhaustOutlets(a)){let o=a.body.world(e);if(this.combustion.emitJet(o,o,i,.13,n*.8,`exhaust`),n>.55){let e=O(o,A(r,1.45));this.volumetrics.emitSmoke({point:this.particlePoint(e),amount:t*n*.2,flow:this.particleVelocity(A(i,.48)),radiusPx:.13*this.particleScale(),swirlPx:7})}}}this.exhaustBursts=this.exhaustBursts.filter(e=>e.age<e.lifetime);let d=a.car.boostActive&&!e.isGhost;return d?this.combustion.stepBoostFire(a,t,e=>this.liquidLayer.igniteAtLocal(e)):this.combustion.clearTireHistory(),d}skidView(){return{pixelSpace:this.pixelSpace,zoom:this.view.zoom,width:this.view.width,height:this.view.height,screen:e=>this.particleScreen(e)}}vehicleLightInput(e,t,n){let r=tt(e.sim.car.preset),i=e=>[-1,1].map(t=>D(e.xM*this.view.zoom,t*e.yM*this.view.zoom)),a=e.sim,o=this.vehicles.imageFor(a.car.preset)??void 0,s=o?Kt(a.car.preset,o.naturalWidth,o.naturalHeight):null,c=a.body.velocity.x*Math.cos(a.body.angle)+a.body.velocity.y*Math.sin(a.body.angle),l=a.lastInput,u=Math.max(l.brake??0,+!!l.action,+(l.throttle<0&&c>.5||l.throttle>0&&c<-.5));return{center:O(this.screen(a.body.position),this.carVisualOffset(a)),angle:-a.body.angle,width:(s?.lengthM??a.car.preset.geometry.lengthM)*this.view.zoom,height:(s?.widthM??a.car.preset.geometry.widthM)*this.view.zoom,mounts:{headlights:i(r.headlights),taillights:i(r.taillights)},image:o,source:s?.source,dark:e.appearance===`auto`?this.overlay?this.surfaceTones.at(e,this.viewportFromDocument(this.documentPoint(a.body.position)),t):t:e.appearance===`dark`,braking:u,options:this.vehicleLighting,opacity:n}}drawVehicleAndWeapons(e,t,n){performance.now();let r=e.sim,{rocket:i,machineGuns:a,flamethrower:o}=e.weapons,s=this.ctx;if(e.isGhost){this.ghostVehicles.draw(e,s,{imageFor:e=>this.vehicles.imageFor(e),screen:e=>this.screen(e),visualOffset:e=>this.carVisualOffset(e),zoom:this.view.zoom,width:this.view.width,height:this.view.height,pixelSpace:this.pixelSpace,walls:this.wallRects,scroll:this.sceneScroll(),dark:this.darkSurface(),styleName:this.volumetrics.style}),i.drawFlight(s,e=>this.screen(e),r.car.preset,this.view.zoom,t),a.drawProjectiles(s,e=>this.screen(e),this.view.zoom,t);return}let c=this.carVisualOffset(r);if(s.save(),s.translate(c.x,c.y),r.car.explodedAt===null){this.vehicles.car(this.ctx,r.body,r,e.damage,Math.max(o.openAmount,a.openAmount));let i=n??this.vehicleLightInput(e,this.darkSurface(),t);this.vehicleLights.glints(s,{...i,center:this.screen(r.body.position)})}let l;if(i.state!==`idle`||o.state!==`closed`||a.state!==`closed`){let t=this.vehicles.imageFor(r.car.preset);if(t){let n=Kt(r.car.preset,t.naturalWidth,t.naturalHeight),i=e.damage.spriteFor(t,n);l={image:i??t,source:i?{x:0,y:0,width:i.width,height:i.height}:n.source,lengthM:n.lengthM,widthM:n.widthM}}}r.car.explodedAt===null&&i.drawMount(s,this.screen(r.body.position),r.body.angle,r.car.preset,this.view.zoom,t,l),r.car.explodedAt===null&&o.state!==`closed`?o.drawMount(s,this.screen(r.body.position),r.body.angle,r.car.preset,this.view.zoom,t,l):r.car.explodedAt===null&&a.drawMount(s,this.screen(r.body.position),r.body.angle,r.car.preset,this.view.zoom,t,l),s.restore(),s.save(),this.clipFluidWalls(s),s.translate(c.x,c.y),r.car.explodedAt===null&&this.vehicles.exhaust(this.ctx,r),s.restore(),i.drawFlight(s,e=>this.screen(e),r.car.preset,this.view.zoom,t),a.drawProjectiles(s,e=>this.screen(e),this.view.zoom,t)}drawGroundLayers(e,t,n,r){let i=t.sim;if(!this.pixelSpace){let{left:e,right:t,bottom:n,top:r}=this.bounds();for(let i=Math.floor(e/5)*5;i<=t;i+=5)this.vehicles.line(this.ctx,D(i,n),D(i,r),`#293c46`);for(let i=Math.floor(n/5)*5;i<=r;i+=5)this.vehicles.line(this.ctx,D(e,i),D(t,i),`#293c46`)}for(let t of this.trail){let n=this.screen(t.point),i=1-t.age/this.trailLifetime;e.globalAlpha=.6*i*i*r,e.fillStyle=t.color,e.beginPath(),e.arc(n.x,n.y,.8+1.4*i,0,Math.PI*2),e.fill()}e.globalAlpha=1,e.save(),e.lineCap=`round`,e.lineJoin=`round`;let a=this.sceneScroll(),o=this.pixelSpace?{left:a.x,right:a.x+this.view.width,bottom:a.y,top:a.y+this.view.height}:{left:this.world(D(0,0)).x,right:this.world(D(this.view.width,0)).x,bottom:this.world(D(0,this.view.height)).y,top:this.world(D(0,0)).y},s=this.darkSurface();performance.now(),this.skidTracks.draw(e,{pixelSpace:this.pixelSpace,scroll:a,width:this.view.width,height:this.view.height,ratio:this.rasterPixelRatio(),dark:s,alpha:r,visible:o,view:this.skidView()}),performance.now();let c={pixelSpace:this.pixelSpace,scroll:a,width:this.view.width,height:this.view.height,particleScale:this.particleScale(),rasterRatio:this.rasterPixelRatio(),zoom:this.view.zoom,effectsAlpha:r,screen:e=>this.particleScreen(e)};return this.tireMarks.draw(e,[t,...n],!1,c),e.restore(),this.liquidLayer.draw(e,1),performance.now(),this.tireMarks.draw(e,[t,...n],!0,c),i.barrier&&!this.overlay&&(e.strokeStyle=`#d4ab71`,e.lineWidth=2,e.strokeRect(3,3,this.view.width-6,this.view.height-6)),{scroll:a,darkSurface:s}}render(e,t,n,r,i=[]){let a=e.sim;performance.now(),this.resize();let o=yb(this.effectsFadeStartedAt,t);if(this.effectsFadeStartedAt!==null&&o===0&&(this.clearEffects(!1),o=0),this.view.cameraStep(a,t),this.canvasWorld&&t>=this.nextHistoryPrune){this.nextHistoryPrune=t+2e3;let e=this.documentPoint(a.body.position),n=2800,r={x:e.x-n,y:e.y-n,width:n*2,height:n*2};this.skidTracks.pruneOutside(r),this.tireMarks.pruneOutside(r),this.liquidLayer.pruneOutside(r)}let s=this.ctx;this.surface.clear();let c=this.screenShake.sample(t);s.save(),(c.x||c.y)&&s.translate(c.x,c.y),r?.drawGround?.(s,this.sceneScroll(),{width:this.view.width,height:this.view.height});let{scroll:l,darkSurface:u}=this.drawGroundLayers(s,e,i,o),d=new Map((this.primaryVehicleVisible?[e,...i]:i).filter(e=>e.sim.mode===`car`&&e.sim.car.explodedAt===null&&!e.isGhost).map(t=>[t,this.vehicleLightInput(t,u,o*(t===e?this.primaryVehicleOpacity:1))])),f=[...d.values()].flatMap(e=>this.vehicleLights.smokeLights(e)),p=f.map(e=>({...e,point:{x:e.point.x+l.x,y:e.point.y+l.y}}));this.pixelSpace&&(s.save(),s.translate(-l.x,-l.y),qc(s,this.debris.particles,{x:l.x,y:l.y,width:this.view.width,height:this.view.height},u,`ground`,p),s.restore());for(let t of this.primaryVehicleVisible?[e,...i]:i)t.sim.mode!==`car`||t.sim.car.explodedAt!==null||t.isGhost||t===e&&this.primaryVehicleOpacity<=0||(s.save(),t===e&&(s.globalAlpha*=this.primaryVehicleOpacity),this.vehicles.carGround(this.ctx,t.sim,t.damage,this.rasterPixelRatio(),this.vehicleShadowsEnabled),s.restore());for(let e of d.values())this.vehicleLights.ground(s,e);if(s.save(),performance.now(),this.clipFluidWalls(s),s.globalAlpha=o,s.save(),s.translate(-this.view.smokeMargin,-this.view.smokeMargin),this.volumetrics.drawSmoke(s,this.fluidView(),f.map(e=>({...e,point:O(e.point,D(this.view.smokeMargin,this.view.smokeMargin))})),u),s.restore(),s.restore(),s.globalAlpha=1,r?.draw(s,l,{width:this.view.width,height:this.view.height}),this.debugDrive&&a.mode===`car`&&a.car.explodedAt===null&&!e.isGhost){let e=this.screen(a.body.position);s.save(),s.beginPath(),s.arc(e.x,e.y,Mn(a.car.preset,this.view.width,this.documentScale())*this.view.zoom,0,Math.PI*2),s.strokeStyle=u?`#92cfff88`:`#12528e88`,s.lineWidth=1,s.setLineDash([5,6]),s.stroke(),s.fillStyle=u?`#b7ddff`:`#12528e`,s.font=`10px ui-monospace, monospace`,s.fillText(`Lightning influence`,e.x+8,e.y-Mn(a.car.preset,this.view.width,this.documentScale())*this.view.zoom+14),s.restore()}this.volumetrics.ghostAvailable&&(s.save(),s.globalAlpha=o,this.volumetrics.drawGhost(s,this.flameView(),u),s.restore()),this.overlay&&this.debugDrive&&this.tourDebug&&vb(s,this.tourDebug.route,this.tourDebug.stops,{x:l.x,y:l.y,width:this.view.width,height:this.view.height}),this.primaryVehicleVisible&&a.mode===`car`&&(s.save(),s.globalAlpha*=this.primaryVehicleOpacity,this.drawVehicleAndWeapons(e,o,d.get(e)),s.restore(),this.debugDrive&&(r?.drawDebug?.(s,a,this,e.damage),this.diagnostics.draw(s,a,t,e=>this.screen(e),{width:this.view.width,rocketState:e.weapons.rocket.state,gunState:e.weapons.machineGuns.state,bulletCount:e.weapons.machineGuns.projectileCount,fluidEngine:this.volumetrics.smokeResolution.engine,quality:this.quality,fluidCols:this.volumetrics.smokeResolution.cols,fluidRows:this.volumetrics.smokeResolution.rows,fireCols:this.combustion.resolution?.cols??0,fireRows:this.combustion.resolution?.rows??0,groundedFireCount:this.combustion.count}))),this.primaryVehicleVisible&&a.mode===`ship`&&this.vehicles.ship(this.ctx,a.body,a),this.primaryVehicleVisible&&a.mode===`brick`&&this.vehicles.brick(this.ctx,a.body);for(let e of i){let t=e.sim;if(t.mode!==`car`||(this.drawVehicleAndWeapons(e,o,d.get(e)),t.car.explodedAt!==null))continue;let n=this.screen(t.body.position);s.save(),s.font=`600 10px ui-monospace, monospace`,s.textAlign=`center`;let r=e.label||`AI`,i=Math.max(30,Math.ceil(s.measureText(r).width)+14);s.fillStyle=`rgba(24, 27, 30, 0.88)`,s.fillRect(n.x-i/2,n.y-37,i,16),s.fillStyle=`#f5f2ec`,s.fillText(r,n.x,n.y-25),s.restore()}if(this.pixelSpace&&(s.save(),s.translate(-l.x,-l.y),qc(s,this.debris.particles,{x:l.x,y:l.y,width:this.view.width,height:this.view.height},u,`air`,p),s.restore()),s.save(),this.clipFluidWalls(s),performance.now(),this.combustion.draw(s,this.flameView(),u,f),s.restore(),this.electricity.draw(s,t,u,o),performance.now(),this.sparks.draw(s,e=>this.particleScreen(e),o,{width:this.view.width,height:this.view.height},this.view.dpr,this.canvasWorld?void 0:this.surface.canvas),this.pointPuffs.length){s.save(),s.font=`700 13px ui-monospace, monospace`,s.textAlign=`center`,s.textBaseline=`middle`;for(let e of this.pointPuffs){let t=this.particleScreen(e.point),n=e.age/.9;s.globalAlpha=(1-n)*o,s.fillStyle=`#f8f4e9`,s.strokeStyle=`rgba(22, 24, 26, 0.85)`,s.lineWidth=3;let r=`+${e.amount}`,i=t.y-16-n*26;s.strokeText(r,t.x,i),s.fillText(r,t.x,i)}s.restore()}if(r?.drawForeground?.(s,l,{width:this.view.width,height:this.view.height}),performance.now(),r?.drawHealthBars?.(s,l,{width:this.view.width,height:this.view.height},e,this,i),n){let e=this.screen(n.from),t=this.screen(n.to);s.strokeStyle=`#ffdf93`,s.lineWidth=2,s.beginPath(),s.moveTo(e.x,e.y),s.lineTo(t.x,t.y),s.stroke()}s.restore(),this.objectGlint?.draw(s,this.view.width,this.view.height,this.darkSurface()),this.vehicles.drawVehicleMarkers(this.ctx,this.primaryVehicleVisible?[e,...i]:i,this.showVehicleMarkers,e),this.surface.presentLockedCamera(),this.liquidLayer.drawTextVehicles([e,...i].filter(t=>(t!==e||this.primaryVehicleVisible)&&t.sim.mode===`car`&&!t.isGhost&&t.sim.car.explodedAt===null).map(e=>({point:this.screen(e.sim.body.position),radius:Math.hypot(e.sim.car.preset.geometry.lengthM,e.sim.car.preset.geometry.widthM)*this.view.zoom/2+12})),c,t=>{for(let n of[e,...i]){if(n===e&&!this.primaryVehicleVisible||n.sim.mode!==`car`||n.isGhost||n.sim.car.explodedAt!==null)continue;let r=this.carVisualOffset(n.sim);t.save(),t.translate(r.x,r.y),this.vehicles.car(t,n.sim.body,n.sim,n.damage,Math.max(n.weapons.flamethrower.openAmount,n.weapons.machineGuns.openAmount)),t.restore()}}),this.governFluidQuality(t)}governFluidQuality(e){let t=performance.now()-e;if(!(t>=0&&t<1e3))return;let n=this.volumetrics.running||this.combustion.running;this.fluidGovernor.sample(e,t,n,this.quality)&&(`${this.fluidGovernor.limit}`,this.applyFluidQuality())}},qb=343,Jb={vtwin:{label:`V-twin 90° 1.2`,cylinders:2,firingOrder:[1,2],banks:[[1],[2]],pinOffsets:{2:-90},idleRpm:1150,redlineRpm:9500,peakTorque:125,peakTorqueRpm:8e3,gears:6,engineInertia:.055,gasTempFactor:1.34,pulse:{attack:40,decay:6.5,hardness:.72,jitter:2},exhaust:{bank:.95,bankB:1.1,collector:.55,reflection:.5,damping:.34,muffler:[.16,.11,.075]},intake:{helmholtz:165,q:6,level:.4},voice:.92},i3:{label:`Inline-3 1.0`,cylinders:3,firingOrder:[1,2,3],banks:[[1,2,3]],idleRpm:850,redlineRpm:6500,peakTorque:200,peakTorqueRpm:2200,gears:5,engineInertia:.16,gasTempFactor:1.3,pulse:{attack:34,decay:5.5,hardness:.62,jitter:1.6},exhaust:{bank:1.45,collector:1.1,reflection:.55,damping:.42,muffler:[.32,.21,.14]},intake:{helmholtz:105,q:5.5,level:.34},voice:1},rotary2:{label:`Rotary 1.3 twin-rotor`,cylinders:4,firingOrder:[1,2,3,4],banks:[[1,2,3,4]],idleRpm:900,redlineRpm:9e3,peakTorque:220,peakTorqueRpm:5500,gears:5,engineInertia:.14,gasTempFactor:1.4,pulse:{attack:18,decay:3,hardness:.7,jitter:1.2},exhaust:{bank:1.05,collector:.8,reflection:.52,damping:.3,muffler:[.2,.13,.09]},intake:{helmholtz:145,q:6.6,level:.46},voice:.94},i4:{label:`Inline-4 2.0`,cylinders:4,firingOrder:[1,3,4,2],banks:[[1,2,3,4]],idleRpm:800,redlineRpm:7200,peakTorque:240,peakTorqueRpm:3900,gears:6,engineInertia:.19,gasTempFactor:1.28,pulse:{attack:38,decay:6.2,hardness:.66,jitter:1.1},exhaust:{bank:1.3,collector:1.05,reflection:.52,damping:.44,muffler:[.3,.19,.12]},intake:{helmholtz:118,q:6,level:.32},voice:.96},boxer4:{label:`Flat-4 boxer (unequal headers)`,cylinders:4,firingOrder:[1,3,2,4],banks:[[1,3],[2,4]],pinOffsets:{3:6,4:-6},idleRpm:800,redlineRpm:6800,peakTorque:300,peakTorqueRpm:3200,gears:6,engineInertia:.2,gasTempFactor:1.27,pulse:{attack:32,decay:5.4,hardness:.6,jitter:2.2},exhaust:{bank:1.62,bankB:.98,collector:1.15,reflection:.58,damping:.4,muffler:[.34,.22,.15]},intake:{helmholtz:100,q:5.2,level:.36},voice:1},i5:{label:`Inline-5 2.5`,cylinders:5,firingOrder:[1,2,4,5,3],banks:[[1,2,3,4,5]],idleRpm:820,redlineRpm:7e3,peakTorque:360,peakTorqueRpm:3200,gears:6,engineInertia:.24,gasTempFactor:1.29,pulse:{attack:33,decay:5.6,hardness:.64,jitter:1.5},exhaust:{bank:1.38,collector:1.08,reflection:.56,damping:.41,muffler:[.31,.2,.13]},intake:{helmholtz:108,q:5.6,level:.34},voice:1},i6:{label:`Inline-6 3.0`,cylinders:6,firingOrder:[1,5,3,6,2,4],banks:[[1,2,3,4,5,6]],idleRpm:750,redlineRpm:7e3,peakTorque:420,peakTorqueRpm:3e3,gears:7,engineInertia:.27,gasTempFactor:1.28,pulse:{attack:30,decay:5,hardness:.58,jitter:.7},exhaust:{bank:1.55,collector:1.2,reflection:.54,damping:.38,muffler:[.33,.21,.14]},intake:{helmholtz:95,q:6.4,level:.33},voice:.98},i6diesel:{label:`Inline-6 diesel 6.7`,cylinders:6,firingOrder:[1,5,3,6,2,4],banks:[[1,2,3,4,5,6]],idleRpm:640,redlineRpm:4600,peakTorque:950,peakTorqueRpm:1900,gears:8,engineInertia:.62,gasTempFactor:1.16,pulse:{attack:68,decay:9.5,hardness:.88,jitter:1.4},exhaust:{bank:1.35,collector:1.65,reflection:.52,damping:.6,muffler:[.46,.3,.2]},intake:{helmholtz:88,q:4.6,level:.24},voice:1.02},v6:{label:`V6 60°`,cylinders:6,firingOrder:[1,4,2,5,3,6],banks:[[1,2,3],[4,5,6]],idleRpm:780,redlineRpm:6800,peakTorque:380,peakTorqueRpm:3600,gears:6,engineInertia:.26,gasTempFactor:1.28,pulse:{attack:31,decay:5.2,hardness:.61,jitter:1.3},exhaust:{bank:1.2,collector:1.05,reflection:.56,damping:.4,muffler:[.3,.2,.13]},intake:{helmholtz:102,q:5.8,level:.33},voice:.98},v6tt:{label:`V6 3.8 twin-turbo build`,cylinders:6,firingOrder:[1,4,2,5,3,6],banks:[[1,2,3],[4,5,6]],idleRpm:750,redlineRpm:7100,peakTorque:640,peakTorqueRpm:3600,gears:7,engineInertia:.29,gasTempFactor:1.22,pulse:{attack:29,decay:5,hardness:.6,jitter:1.2},exhaust:{bank:.95,collector:1.3,reflection:.5,damping:.52,muffler:[.34,.23,.15]},intake:{helmholtz:112,q:5.4,level:.3},voice:.98},flat6:{label:`Flat-6 3.8`,cylinders:6,firingOrder:[1,6,2,4,3,5],banks:[[1,2,3],[4,5,6]],idleRpm:800,redlineRpm:8500,peakTorque:420,peakTorqueRpm:5e3,gears:7,engineInertia:.22,gasTempFactor:1.31,pulse:{attack:44,decay:7,hardness:.74,jitter:.9},exhaust:{bank:.85,collector:.72,reflection:.48,damping:.3,muffler:[.22,.15,.1]},intake:{helmholtz:138,q:7.2,level:.42},voice:1},v8cross:{label:`V8 cross-plane 5.0`,cylinders:8,firingOrder:[1,8,7,3,6,5,4,2],banks:[[1,2,3,4],[5,6,7,8]],idleRpm:700,redlineRpm:7e3,peakTorque:540,peakTorqueRpm:4200,gears:6,engineInertia:.38,gasTempFactor:1.26,pulse:{attack:26,decay:4.4,hardness:.55,jitter:2.6},exhaust:{bank:1.75,collector:1.35,reflection:.63,damping:.34,muffler:[.4,.26,.17]},intake:{helmholtz:78,q:5,level:.3},voice:1.06},v8tt:{label:`V8 4.0 twin-turbo build`,cylinders:8,firingOrder:[1,8,7,3,6,5,4,2],banks:[[1,2,3,4],[5,6,7,8]],idleRpm:660,redlineRpm:6800,peakTorque:800,peakTorqueRpm:3e3,gears:8,engineInertia:.42,gasTempFactor:1.21,pulse:{attack:24,decay:4.2,hardness:.54,jitter:2.4},exhaust:{bank:1.1,collector:1.55,reflection:.58,damping:.55,muffler:[.42,.28,.18]},intake:{helmholtz:74,q:4.8,level:.28},voice:1.05},v8flat:{label:`V8 flat-plane 4.5`,cylinders:8,firingOrder:[1,5,3,7,4,8,2,6],banks:[[1,2,3,4],[5,6,7,8]],idleRpm:900,redlineRpm:9e3,peakTorque:460,peakTorqueRpm:6e3,gears:7,engineInertia:.25,gasTempFactor:1.33,pulse:{attack:52,decay:8.4,hardness:.82,jitter:.6},exhaust:{bank:.78,collector:.62,reflection:.44,damping:.26,muffler:[.18,.12,.08]},intake:{helmholtz:155,q:7.8,level:.44},voice:1},v10:{label:`V10 5.2`,cylinders:10,firingOrder:[1,6,5,10,2,7,3,8,4,9],banks:[[1,2,3,4,5],[6,7,8,9,10]],idleRpm:900,redlineRpm:8700,peakTorque:560,peakTorqueRpm:6500,gears:7,engineInertia:.3,gasTempFactor:1.32,pulse:{attack:48,decay:7.8,hardness:.8,jitter:.8},exhaust:{bank:.82,collector:.66,reflection:.46,damping:.27,muffler:[.19,.13,.09]},intake:{helmholtz:148,q:7.4,level:.45},voice:1.02},v12:{label:`V12 6.5`,cylinders:12,firingOrder:[1,7,5,11,3,9,6,12,2,8,4,10],banks:[[1,2,3,4,5,6],[7,8,9,10,11,12]],idleRpm:850,redlineRpm:8500,peakTorque:690,peakTorqueRpm:5800,gears:8,engineInertia:.36,gasTempFactor:1.31,pulse:{attack:46,decay:7.4,hardness:.78,jitter:.5},exhaust:{bank:.9,collector:.7,reflection:.47,damping:.28,muffler:[.2,.14,.09]},intake:{helmholtz:142,q:7,level:.44},voice:1.04}};function Yb(e){let t=720/e.cylinders,n=new Map;return e.firingOrder.forEach((r,i)=>{let a=e.pinOffsets&&e.pinOffsets[r]||0;n.set(r,(i*t+a+720)%720)}),n}function Xb(e,t){let n=Yb(e);return e.banks[t].map(e=>n.get(e)).sort((e,t)=>e-t)}function Zb(e,t=1){return qb*t/(4*Math.max(.05,e))}function Qb(e,t=1){return 2*Math.max(.05,e)/(qb*t)}var $b={hatch:{label:`Hot hatch`,mass:1320,wheelRadius:.31,finalDrive:4.05,gearRatios:[3.31,2.13,1.48,1.14,.95,.82],dragArea:.68,rollingResistance:.014,brakeForce:9500,gearbox:`manual`,shiftTimeMs:130,gearTeeth:[37,31,27,24,22,20]},sports:{label:`Sports car`,mass:1450,wheelRadius:.33,finalDrive:3.73,gearRatios:[3.55,2.05,1.39,1,.82,.67],dragArea:.62,rollingResistance:.013,brakeForce:12e3,gearbox:`manual`,shiftTimeMs:95,gearTeeth:[39,33,28,25,22,19]},supercar:{label:`Supercar (dual-clutch)`,mass:1560,wheelRadius:.34,finalDrive:3.9,gearRatios:[3.08,2.19,1.63,1.29,1.03,.84,.69],dragArea:.6,rollingResistance:.012,brakeForce:15e3,gearbox:`dct`,shiftTimeMs:45,gearTeeth:[41,35,30,26,23,20,18]},muscle:{label:`Muscle car`,mass:1720,wheelRadius:.35,finalDrive:3.55,gearRatios:[2.97,2.07,1.43,1,.71],dragArea:.78,rollingResistance:.016,brakeForce:11e3,gearbox:`manual`,shiftTimeMs:150,gearTeeth:[35,30,26,23,20]},truck:{label:`Pickup (automatic)`,mass:2400,wheelRadius:.38,finalDrive:3.73,gearRatios:[4.17,2.34,1.52,1.14,.87,.69],dragArea:1.05,rollingResistance:.018,brakeForce:13e3,gearbox:`auto`,shiftTimeMs:190,gearTeeth:[43,36,31,27,24,21]}},ex={stiffness:5200,dampingRatio:.22,damping:13,backlash:.035,clutchTorqueCapacity:900,clutchStiffness:3.2},tx=(e,t,n)=>e<t?t:e>n?n:e,nx=(e,t)=>typeof e==`number`&&isFinite(e)?e:t,rx=Object.freeze({mix:Object.freeze({exhaust:1,intake:.75,transmission:.45,turbo:.4,transients:.42,sub:.25}),tone:Object.freeze({rumble:1,brightness:1,punch:1}),eq:Object.freeze([0,0,0,0,0]),fx:Object.freeze({reverbMix:.14,reverbSize:.32,reverbDamping:4200,width:.35,popDepth:1.05,dynamics:1}),turbo:Object.freeze({enabled:0,inertia:.42,maxBoost:1.1,whineOrder:52,boostRpm:3500,valve:1,bov:.4,surge:1,flutterHz:13,screamer:0,antiLag:0}),position:0,volume:.7}),ix=Object.freeze([{path:`engine.idleRpm`,label:`Idle`,min:400,max:2500,step:10,unit:`rpm`,group:`engine`,rebuild:!1},{path:`engine.redlineRpm`,label:`Redline`,min:3e3,max:12e3,step:100,unit:`rpm`,group:`engine`,rebuild:!1},{path:`engine.peakTorque`,label:`Peak torque`,min:40,max:1400,step:5,unit:`N·m`,group:`engine`,rebuild:!1},{path:`engine.peakTorqueRpm`,label:`Torque peak at`,min:1200,max:9e3,step:100,unit:`rpm`,group:`engine`,rebuild:!1},{path:`engine.gears`,label:`Gears`,min:3,max:10,step:1,unit:``,group:`engine`,rebuild:!0},{path:`engine.engineInertia`,label:`Rotating inertia`,min:.02,max:1.2,step:.005,unit:`kg·m²`,group:`engine`,rebuild:!1},{path:`engine.gasTempFactor`,label:`Gas temperature`,min:.8,max:1.8,step:.01,unit:`×c`,group:`engine`,rebuild:!0},{path:`engine.voice`,label:`Voice level`,min:.2,max:2,step:.01,unit:`%`,group:`engine`,rebuild:!1},{path:`engine.pulse.attack`,label:`Blowdown attack`,min:5,max:90,step:1,unit:``,group:`pulse`,rebuild:!0},{path:`engine.pulse.decay`,label:`Blowdown decay`,min:1,max:14,step:.1,unit:``,group:`pulse`,rebuild:!0},{path:`engine.pulse.hardness`,label:`Load hardening`,min:0,max:1.5,step:.01,unit:``,group:`pulse`,rebuild:!0},{path:`engine.pulse.jitter`,label:`Cylinder jitter`,min:0,max:6,step:.1,unit:``,group:`pulse`,rebuild:!0},{path:`engine.exhaust.bank`,label:`Header length`,min:.2,max:2.5,step:.01,unit:`m`,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.collector`,label:`Collector length`,min:.2,max:3,step:.01,unit:`m`,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.reflection`,label:`End reflection`,min:.05,max:.9,step:.01,unit:``,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.damping`,label:`Pipe damping`,min:.1,max:1.5,step:.01,unit:``,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.muffler.0`,label:`Muffler stage 1`,min:0,max:.8,step:.01,unit:`m`,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.muffler.1`,label:`Muffler stage 2`,min:0,max:.8,step:.01,unit:`m`,group:`exhaust`,rebuild:!0},{path:`engine.exhaust.muffler.2`,label:`Muffler stage 3`,min:0,max:.8,step:.01,unit:`m`,group:`exhaust`,rebuild:!0},{path:`engine.intake.helmholtz`,label:`Plenum resonance`,min:40,max:400,step:1,unit:`Hz`,group:`intake`,rebuild:!0},{path:`engine.intake.q`,label:`Plenum Q`,min:.5,max:14,step:.1,unit:``,group:`intake`,rebuild:!0},{path:`engine.intake.level`,label:`Induction level`,min:0,max:1.5,step:.01,unit:`%`,group:`intake`,rebuild:!0},{path:`turbo.enabled`,label:`Turbo`,min:0,max:1,step:1,unit:`bool`,group:`turbo`,rebuild:!1},{path:`turbo.inertia`,label:`Turbo inertia`,min:.05,max:2,step:.01,unit:`s`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.boostRpm`,label:`Boost onset`,min:1200,max:7e3,step:100,unit:`rpm`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.maxBoost`,label:`Max boost`,min:.2,max:3,step:.05,unit:`bar`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.whineOrder`,label:`Blade order`,min:10,max:120,step:1,unit:``,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.valve`,label:`Blow-off valve`,min:0,max:2,step:1,unit:`enum`,options:[`None`,`Atmos`,`Recirc`],group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.bov`,label:`Valve size`,min:0,max:1,step:.01,unit:`%`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.surge`,label:`Flutter trim`,min:0,max:2,step:.01,unit:`%`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.flutterHz`,label:`Flutter rate`,min:5,max:25,step:.5,unit:`Hz`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.screamer`,label:`Screamer pipe`,min:0,max:1,step:1,unit:`bool`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`turbo.antiLag`,label:`Anti-lag`,min:0,max:1,step:1,unit:`bool`,group:`turbo`,rebuild:!1,needs:`turbo`},{path:`mix.exhaust`,label:`Exhaust`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`mix.intake`,label:`Intake`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`mix.transmission`,label:`Gearbox`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`mix.turbo`,label:`Turbo`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`mix.transients`,label:`Pops`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`mix.sub`,label:`Sub`,min:0,max:1.6,step:.01,unit:`%`,group:`mix`,rebuild:!1},{path:`tone.rumble`,label:`Rumble`,min:0,max:2,step:.01,unit:`%`,group:`tone`,rebuild:!1},{path:`tone.brightness`,label:`Brightness`,min:0,max:2,step:.01,unit:`%`,group:`tone`,rebuild:!1},{path:`tone.punch`,label:`Bass punch`,min:0,max:2,step:.01,unit:`%`,group:`tone`,rebuild:!1},{path:`fx.popDepth`,label:`Pop depth`,min:0,max:2,step:.01,unit:`%`,group:`tone`,rebuild:!1},{path:`fx.dynamics`,label:`Compression`,min:0,max:1,step:.01,unit:`%`,group:`tone`,rebuild:!1},{path:`fx.reverbMix`,label:`Reverb mix`,min:0,max:1,step:.01,unit:`%`,group:`fx`,rebuild:!1},{path:`fx.reverbSize`,label:`Reverb size`,min:.05,max:1,step:.01,unit:`%`,group:`fx`,rebuild:!1},{path:`fx.reverbDamping`,label:`Reverb damping`,min:800,max:12e3,step:100,unit:`Hz`,group:`fx`,rebuild:!1},{path:`fx.width`,label:`Stereo width`,min:0,max:1,step:.01,unit:`%`,group:`fx`,rebuild:!1},{path:`position`,label:`Listener position`,min:0,max:1,step:.01,unit:`%`,group:`fx`,rebuild:!1},{path:`volume`,label:`Volume`,min:0,max:1,step:.01,unit:`%`,group:`fx`,rebuild:!1},{path:`eq.0`,label:`Sub 60`,min:-18,max:18,step:.5,unit:`dB`,group:`eq`,rebuild:!1},{path:`eq.1`,label:`Body 200`,min:-18,max:18,step:.5,unit:`dB`,group:`eq`,rebuild:!1},{path:`eq.2`,label:`Honk 800`,min:-18,max:18,step:.5,unit:`dB`,group:`eq`,rebuild:!1},{path:`eq.3`,label:`Rasp 2.5k`,min:-18,max:18,step:.5,unit:`dB`,group:`eq`,rebuild:!1},{path:`eq.4`,label:`Air 8k`,min:-18,max:18,step:.5,unit:`dB`,group:`eq`,rebuild:!1}]),ax=Object.freeze([{id:`engine`,label:`Engine`,note:`The machine itself. Torque and inertia drive the physics; gas temperature sets the speed of sound in the pipes.`},{id:`pulse`,label:`Combustion pulse`,note:`The shape of one cylinder blowing down. Attack is the crack, decay is the tail, hardening is how much both sharpen under load.`},{id:`exhaust`,label:`Exhaust`,note:`Waveguide geometry in metres. Header and collector lengths set the resonances; reflection and damping set how many survive.`},{id:`intake`,label:`Intake`,note:`Airbox Helmholtz resonance. It does not track rpm — what tracks rpm is how hard it is excited.`},{id:`turbo`,label:`Turbo`,note:`Bolts onto any engine. Inertia is lag. No blow-off valve = full "stu-stu-stu"; an atmospheric valve goes "pssh", a recirculating one is quiet — the bigger the valve, the less is left to flutter. A screamer pipe vents the wastegate to air; anti-lag keeps the turbo spooled off-throttle, with bangs.`},{id:`mix`,label:`Voice mix`,note:`Balance between the voices.`},{id:`tone`,label:`Tone`,note:`The fixed-frequency part of the response, plus how hard the compressor works.`},{id:`fx`,label:`Space`,note:`Reverb, width, where the listener is, and output level.`},{id:`eq`,label:`EQ`,note:`Five bands, ±18 dB.`}]);function ox(e,t){let n=e;for(let e of t.split(`.`)){if(n==null)return;n=n[e]}return n}function sx(e,t,n){let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++)(i[r[e]]==null||typeof i[r[e]]!=`object`)&&(i[r[e]]={}),i=i[r[e]];return i[r[r.length-1]]=n,e}function cx(e){return ix.find(t=>t.path===e)}function lx(e){if(Array.isArray(e))return e.map(lx);if(e&&typeof e==`object`){let t={};for(let n of Object.keys(e))t[n]=lx(e[n]);return t}return e}function ux(e){let t=Jb[e];return t?fx({version:3,id:e,label:t.label,engine:lx(t),...lx(rx)}):null}function dx(){let e={};for(let t of Object.keys(Jb))e[t]=ux(t);return e}function fx(e){let t=e&&typeof e==`object`?e:{},n=Jb[t.id]||Jb.v8cross,r={version:3,id:typeof t.id==`string`&&t.id?t.id:`custom`,label:typeof t.label==`string`&&t.label?t.label:n.label,engine:{},mix:{},tone:{},eq:[],fx:{},turbo:{},position:0,volume:.7},i=t.engine&&typeof t.engine==`object`?t.engine:n,a=tx(Math.round(nx(i.cylinders,n.cylinders)),1,16);r.engine.cylinders=a;let o=Array.isArray(i.firingOrder)?i.firingOrder.slice(0,a):null,s=o&&o.length===a&&o.every(e=>Number.isInteger(e)&&e>=1&&e<=a)&&new Set(o).size===a;r.engine.firingOrder=s?o:n.cylinders===a?lx(n.firingOrder):Array.from({length:a},(e,t)=>t+1);let c=Array.isArray(i.banks)?i.banks.filter(Array.isArray):null,l=c?c.flat():[],u=c&&c.length>0&&l.length===a&&l.every(e=>r.engine.firingOrder.includes(e));if(r.engine.banks=u?lx(c):n.cylinders===a?lx(n.banks):[r.engine.firingOrder.slice()],i.pinOffsets&&typeof i.pinOffsets==`object`){let e={};for(let[t,n]of Object.entries(i.pinOffsets)){let r=Number(t);Number.isInteger(r)&&r>=1&&r<=a&&(e[r]=tx(nx(n,0),-360,360))}Object.keys(e).length&&(r.engine.pinOffsets=e)}let d=nx(i.exhaust&&i.exhaust.bankB,NaN);r.engine.exhaust={},isFinite(d)&&r.engine.banks.length>1&&(r.engine.exhaust.bankB=tx(d,.2,2.5));let f=!(t.turbo&&typeof t.turbo==`object`)&&i.turbo&&typeof i.turbo==`object`?{...i.turbo,enabled:1}:null,p=f?{...t,turbo:f}:t,m={engine:n,...rx};for(let e of ix){let t=ox(p,e.path);isFinite(Number(t))||(t=ox(m,e.path)),isFinite(Number(t))||(t=e.min);let n=tx(Number(t),e.min,e.max);sx(r,e.path,e.unit===`bool`||e.unit===`enum`?Math.round(n):n)}let h=r.engine.exhaust.muffler;return r.engine.exhaust.muffler=[0,1,2].map(e=>tx(nx(h&&h[e],.2),0,.8)),r.eq=[0,1,2,3,4].map(e=>tx(nx(r.eq[e],0),-18,18)),r}function px(e){return JSON.stringify(fx(e),null,2).replace(/\[\s+((?:-?[\d.]+,?\s+)+)\]/g,(e,t)=>`[`+t.trim().replace(/,\s+/g,`, `)+`]`)}function mx(e){let t;try{t=JSON.parse(String(e))}catch(e){return{preset:null,error:`not valid JSON: `+e.message}}return!t||typeof t!=`object`?{preset:null,error:`not an object`}:{preset:fx(t),error:null}}var hx=8192,gx=1024;function _x(e,t){let n=e.length;for(let r=1,i=0;r<n;r++){let a=n>>1;for(;i&a;a>>=1)i^=a;if(i^=a,r<i){let n=e[r];e[r]=e[i],e[i]=n,n=t[r],t[r]=t[i],t[i]=n}}for(let r=2;r<=n;r<<=1){let i=-2*Math.PI/r,a=Math.cos(i),o=Math.sin(i);for(let i=0;i<n;i+=r){let n=1,s=0;for(let c=0;c<r/2;c++){let l=e[i+c],u=t[i+c],d=e[i+c+r/2]*n-t[i+c+r/2]*s,f=e[i+c+r/2]*s+t[i+c+r/2]*n;e[i+c]=l+d,t[i+c]=u+f,e[i+c+r/2]=l-d,t[i+c+r/2]=u-f;let p=n*a-s*o;s=n*o+s*a,n=p}}}}function vx(e){let t=e>>>0||1;return()=>(t^=t<<13,t>>>=0,t^=t>>17,t^=t<<5,t>>>=0,t/4294967296)}function yx(e,t,n){return e<0||e>1?0:(1-Math.exp(-t*e))*Math.exp(-n*e)}function bx(e,t,n,r=0){let i=e.pulse,a=Math.max(0,Math.min(1.5,typeof i.hardness==`number`&&isFinite(i.hardness)?i.hardness:.65))/.65,o=i.attack*(.55+.85*a*n),s=i.decay*(1.25-.35*a*n),c=new Float64Array(hx),l=vx(e.cylinders*2654435761+Math.round(i.attack*97)),u=(i.jitter||0)/100;for(let e of t){let t=1+(l()*2-1)*u*2.5,n=(l()*2-1)*u*6,i=1+(l()*2-1)*u*1.5,a=((e+r+n)%720+720)%720/720;for(let e=0;e<hx;e++){let n=e/hx-a;n<0&&(n+=1),c[e]+=t*yx(n,o,s*i)}}return c}function xx(e){let t=e.length,n=new Float64Array(t);for(let r=0;r<t;r++)n[r]=e[(r+1)%t]-e[r];let r=0;for(let e=0;e<t;e++)r+=n[e];r/=t;for(let e=0;e<t;e++)n[e]-=r;return n}var Sx=24;function Cx(e,t=gx,n=Sx){let r=e.length,i=new Float64Array(r),a=new Float64Array(r);i.set(e),_x(i,a);let o=Math.min(t,r/2),s=new Float32Array(o),c=new Float32Array(o),l=n>0?2*n:0;for(let e=1;e<o;e++){let t=l?1/(1+e/l):1;s[e]=2*i[e]/r*t,c[e]=-2*a[e]/r*t}return s[0]=0,c[0]=0,{real:s,imag:c}}function wx(e,t=.25){let n=0;for(let t=1;t<e.real.length;t++)n+=.5*(e.real[t]**2+e.imag[t]**2);let r=t/(Math.sqrt(n)||1);for(let t=0;t<e.real.length;t++)e.real[t]*=r,e.imag[t]*=r;return e}function Tx(e,t,n){let r={disableNormalization:!0},i=(n,i,a)=>{let o=wx(Cx(xx(bx(t,n,i,a))));return e.createPeriodicWave(o.real,o.imag,r)},a=t.banks.map((e,r)=>{let a=n(t,r);return{soft:i(a,0,0),hard:i(a,1,0)}}),o=t.banks.flat().map((e,n)=>n*720/t.cylinders);return{banks:a,intake:{soft:i(o,0,360),hard:i(o,1,360)}}}function Ex(e,t,n){let r=Math.max(.02,Number(e.engineInertia)||.25),i=Math.max(1,e.cylinders||4),a=Math.max(40,(Number(t)||0)*Math.PI/30),o=.3*((Number(e.peakTorque)||300)*(.12+.88*Math.max(0,Math.min(1,n))))*(4*Math.PI/i)/(r*a*a);return Math.max(0,Math.min(.12,o))}function Dx(e,t){let n=e.pulse,r=(n.jitter||0)/100,i=vx(e.cylinders*2654435761+Math.round(n.attack*97)+7),a=[],o=e.banks.length,s=[];for(let n=0;n<o;n++)for(let o of t(e,n)){let e=1+(i()*2-1)*r*2.5,t=(i()*2-1)*r*6,c=1+(i()*2-1)*r*1.5,l=((o+t)%720+720)%720/720;a.push({out:n,angle:l,ampTrim:e,decayTrim:c}),s.push({angle:o+t+360,ampTrim:e,decayTrim:c})}for(let e of s)a.push({out:o,angle:(e.angle%720+720)%720/720,ampTrim:e.ampTrim,decayTrim:e.decayTrim});let c=Math.max(0,Math.min(1.5,typeof n.hardness==`number`&&isFinite(n.hardness)?n.hardness:.65))/.65,l=hx,u=1-Math.exp(-2*Math.PI*48/l),d=[];for(let e=0;e<=o;e++){let t=[];for(let r=0;r<=4;r++){let i=r/4*c,o=n.attack*(.55+.85*i),s=n.decay*(1.25-.35*i),d=new Float64Array(l);for(let t of a)if(t.out===e)for(let e=0;e<l;e++){let n=e/l-t.angle;n<0&&(n+=1),d[e]+=t.ampTrim*yx(n,o,s*t.decayTrim)}let f=0,p=0;for(let e=0;e<2;e++)for(let t=0;t<l;t++){let n=(d[t]-d[(t+l-1)%l])*l;f+=u*(n-f),e&&(p+=f*f)}let m=Math.sqrt(p/l)||1;t.push(.25/m)}d.push(t)}return{events:a.sort((e,t)=>e.angle-t.angle),outputs:o+1,attack:n.attack,decay:n.decay,hardness:c,ccv:typeof n.ccv==`number`?n.ccv:.012+.012*(n.jitter||1),jitterDeg:typeof n.jitterDeg==`number`?n.jitterDeg:.4+.5*(n.jitter||1),gains:d,seed:e.cylinders*40503+Math.round(n.attack*131)>>>0}}var Ox=1.02,kx=10,Ax=2e4,jx=.92,Mx=.02,Nx=.09,U=(e,t,n)=>e<t?t:e>n?n:e;function W(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function G(e,t,n,r=Mx){let i=W(t,0),a=W(n,0);e.setTargetAtTime(i,a<0?0:a,r>0?r:Mx)}function Px(e,t,n,r){let i=2*Math.PI*U(t,1,.49*r)/r,a=Math.cos(i),o=Math.sin(i)/(2*Math.max(1e-4,n)),s=1+o,c=(1-a)/2/s,l=(1-a)/s,u=c,d=-2*a/s,f=(1-o)/s,p=2*Math.PI*U(e,.01,.49*r)/r,m=Math.cos(p),h=Math.sin(p),g=Math.cos(2*p),_=Math.sin(2*p),v=c+l*m+u*g,y=-(l*h+u*_),b=1+d*m+f*g,x=-(d*h+f*_),S=Math.atan2(y,v)-Math.atan2(x,b);return Number.isFinite(S)?S:0}function Fx(e,t,n,r){let i=2*Math.PI*e;if(!(i>0))return 0;let a=Px(e,t,n,r),o=(Math.PI+a)/i;return o>0&&Number.isFinite(o)?o:1/(2*e)}var Ix=new Map;function Lx(e,t,n=4096,r=Rx()){let i=e+`:`+t+`:`+n+`:`+r,a=Ix.get(i);if(a)return a;let o=1/Math.max(.2,e/3.2)*1.05,s=1/Math.max(.2,t/3.2)*.85,c=new Float32Array(n);for(let e=0;e<n;e++){let t=r*(e/(n-1)*2-1);c[e]=t>=0?o*Math.tanh(t/o):s*Math.tanh(t/s)}return Ix.set(i,c),c}var Rx=()=>6,zx=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1;let r=t&&t.exhaust||{};this.length=U(W(n.length,W(r.bank,1)),.05,12),this.gasTemp=U(W(n.gasTempFactor,W(t&&t.gasTempFactor,1)),.5,2.5),this.reflection=U(W(n.reflection,W(r.reflection,.5)),0,jx),this.damping=U(W(n.damping,W(r.damping,.4)),.05,2),this.thermalSpan=U(W(n.thermalSpan,.05),0,.25),this.thermalBias=.35,this.sampleRate=W(e&&e.sampleRate,48e3),this.minLoopDelay=128/this.sampleRate,this.nominalDelay=Qb(this.length,this.gasTemp),this.frequency=Zb(this.length,this.gasTemp),this.lpBase=U(this.frequency*(1.8/this.damping),150,12e3),this.loopQ=.5;let i=.49*this.sampleRate;if(this.fMax=Math.min(Ax,i),this.tunedDelay=this._tunedDelay(this.frequency,this.lpBase),this.phaseCompensation=this.tunedDelay/this.nominalDelay,this.maxHeatScale=1+this.thermalSpan*(1-this.thermalBias),this.shortestDelay=this._tunedDelay(this.frequency*this.maxHeatScale,this.lpBase*this.maxHeatScale*1.35),this.mode=this.shortestDelay>=this.minLoopDelay*Ox?`delay`:`bandpass`,this.inGain=e.createGain(),this.inGain.gain.value=1,this.out=e.createGain(),this.out.gain.value=1,this.dryGain=e.createGain(),this.dryGain.gain.value=U(W(n.dry,.3),0,4),this.inGain.connect(this.dryGain),this.dryGain.connect(this.out),this.wetGain=e.createGain(),this.wetGain.gain.value=U(W(n.wet,.9),0,4),this.wetGain.connect(this.out),this.mode===`delay`){let t=Math.max(.01,this.nominalDelay/(1-this.thermalSpan)*1.25);this.maxDelayTime=t,this.sum=e.createGain(),this.sum.gain.value=1,this.delay=e.createDelay(t),this.delay.delayTime.value=U(this.tunedDelay,this.minLoopDelay,t),this.loopLP=e.createBiquadFilter(),this.loopLP.type=`lowpass`,this.loopLP.frequency.value=this._f(this.lpBase),this.loopLP.Q.value=this.loopQ,this.fb=e.createGain(),this.fb.gain.value=-this._fbMag(0),this.inGain.connect(this.sum),this.sum.connect(this.delay),this.delay.connect(this.loopLP),this.loopLP.connect(this.fb),this.fb.connect(this.sum),this.loopLP.connect(this.wetGain)}else{let t=this._fbMag(0);this.fallbackQ=U(Math.PI/(2*Math.max(.02,1-t)),.7,24);let r=U(Math.round(W(n.maxModes,3)),1,6);this.modes=[];let i=0,a=[];for(let e=0;e<r;e++){let t=this.frequency*(2*e+1);if(t>this.fMax*.95)break;let n=1/Math.sqrt(1+t/this.lpBase*(t/this.lpBase)),r=(1/(2*e+1))**.7*n;a.push(r),i+=r}a.length||(a.push(1),i=1);let o=.6/Math.max(.08,1-t);for(let t=0;t<a.length;t++){let n=e.createBiquadFilter();n.type=`bandpass`,n.frequency.value=this._f(this.frequency*(2*t+1)),n.Q.value=this.fallbackQ;let r=e.createGain();r.gain.value=a[t]/i*o,this.inGain.connect(n),n.connect(r),r.connect(this.wetGain),this.modes.push({bp:n,g:r,order:2*t+1})}}this._nodeCount=this._countNodes()}get input(){return this.inGain}get output(){return this.out}_f(e){return U(W(e,kx),kx,this.fMax)}_tunedDelay(e,t){return Fx(U(W(e,kx),kx,this.fMax),U(W(t,150),20,.49*this.sampleRate),this.loopQ,this.sampleRate)}_fbMag(e){return U(this.reflection*(.92+.08*U(e,0,1)),0,jx)}_heatScale(e){let t=U(W(e&&e.load,0),0,1),n=U(W(e&&e.rpmNorm,0),0,1),r=U(.6*t+.4*n,0,1);return 1+this.thermalSpan*(r-this.thermalBias)}update(e){if(this.disposed)return;let t=W(e&&e.now,W(this.ctx.currentTime,0)),n=U(W(e&&e.load,0),0,1),r=this._heatScale(e);if(this.mode===`delay`){let e=U(this.nominalDelay/r,this.minLoopDelay,this.maxDelayTime);G(this.delay.delayTime,e,t,Nx),G(this.loopLP.frequency,this._f(this.lpBase*r*(1+.35*n)),t,Mx),G(this.fb.gain,-this._fbMag(n),t,Mx)}else for(let e=0;e<this.modes.length;e++){let n=this.modes[e];G(n.bp.frequency,this._f(this.frequency*n.order*r),t,Nx)}}_countNodes(){let e=4;return this.mode===`delay`?e+=4:e+=this.modes.length*2,e}dispose(){if(this.disposed)return;this.disposed=!0;let e=[this.inGain,this.out,this.dryGain,this.wetGain,this.sum,this.delay,this.loopLP,this.fb];if(this.modes)for(let t of this.modes)e.push(t.bp,t.g);for(let t of e)t&&t.disconnect&&t.disconnect()}},Bx=class e{constructor(t,n,r={}){this.ctx=t,this.profile=n,this.disposed=!1;let i=n&&n.exhaust||{},a=Array.isArray(r.chambers)?r.chambers:Array.isArray(i.muffler)?i.muffler:[.3,.2,.13];this.chambers=a.map(e=>U(W(e,.2),.02,3)),this.gasTemp=U(W(r.gasTempFactor,W(n&&n.gasTempFactor,1)),.5,2.5),this.sampleRate=W(t&&t.sampleRate,48e3),this.fMax=Math.min(Ax,.49*this.sampleRate),this.thermalSpan=U(W(r.thermalSpan,.025),0,.2),this.thermalBias=.35;let o=this.chambers.map(e=>Qb(e,this.gasTemp));this.spread=U(W(r.spread,.06),0,.25);let s=r.decorrelate!==!1,c=e.peakCoincidence(o);this.delays=s?e._decorrelate(o,this.spread):o.slice();let l=e.peakCoincidence(this.delays);this.coincidence={before:c,after:l},this.notches=this.delays.map(e=>1/(2*e));let u=U(W(i.reflection,.5),0,1);this.branchGain=U(W(r.branchGain,.55+.3*u),.05,.9);let d=U(W(r.packingOctaves,7),1,40);this.packingBase=U(Zb(Math.max(...this.chambers),this.gasTemp)*d,500,11e3),this.inGain=t.createGain(),this.inGain.gain.value=1,this.out=t.createGain(),this.out.gain.value=1,this.stages=[];let f=this.inGain;for(let e=0;e<this.delays.length;e++){let n=this.delays[e],r=t.createGain();r.gain.value=1;let i=t.createGain();i.gain.value=1;let a=Math.max(.005,n/(1-this.thermalSpan)*1.5),o=t.createDelay(a);o.delayTime.value=U(n,0,a);let s=t.createGain();s.gain.value=this.branchGain*.92**e,f.connect(i),i.connect(r),f.connect(o),o.connect(s),s.connect(r),this.stages.push({sum:r,thru:i,delay:o,branch:s,T:n,maxT:a,taper:.92**e}),f=r}this.packing=t.createBiquadFilter(),this.packing.type=`lowpass`,this.packing.frequency.value=U(this.packingBase,kx,this.fMax),this.packing.Q.value=.6;let p=1;for(let e of this.stages)p*=1+e.branch.gain.value;this.trim=t.createGain(),this.trim.gain.value=1/Math.max(1,p*.72),f.connect(this.packing),this.packing.connect(this.trim),this.trim.connect(this.out),this._nodeCount=4+this.stages.length*4}get input(){return this.inGain}get output(){return this.out}static peakCoincidence(e,t=6,n=45){let r=0;for(let i=0;i<e.length;i++)for(let a=i+1;a<e.length;a++)for(let o=1;o<=t;o++)for(let s=1;s<=t;s++){let t=o/e[i],c=s/e[a];if(t>8e3||c>8e3)continue;let l=(t-c)/n;r+=Math.exp(-l*l)/(o*s)}return r}static _decorrelate(t,n){let r=t.slice();for(let i=1;i<r.length;i++){let a=r[i],o=1/0;for(let s=0;s<41;s++){let c=1+n*(2*s/40-1),l=r.slice(0,i+1);l[i]=t[i]*c;let u=e.peakCoincidence(l);u<o-1e-12&&(o=u,a=t[i]*c)}r[i]=a}return r}update(e){if(this.disposed)return;let t=W(e&&e.now,W(this.ctx.currentTime,0)),n=U(W(e&&e.load,0),0,1),r=U(W(e&&e.rpmNorm,0),0,1),i=U(.6*n+.4*r,0,1),a=1+this.thermalSpan*(i-this.thermalBias);for(let r=0;r<this.stages.length;r++){let i=this.stages[r];G(i.delay.delayTime,U(i.T/a,0,i.maxT),t,Nx);let o=U(W(e&&e.valve,0),0,1);G(i.branch.gain,U(this.branchGain*i.taper*(1-.12*n)*(1-.65*o),0,.95),t,Mx)}let o=U(W(e&&e.valve,0),0,1);G(this.packing.frequency,U(this.packingBase*(1+.3*n)*(1+1.1*o)*a,kx,this.fMax),t,Mx)}dispose(){if(this.disposed)return;this.disposed=!0;let e=[this.inGain,this.out,this.packing,this.trim];for(let t of this.stages)e.push(t.sum,t.thru,t.delay,t.branch);for(let t of e)t&&t.disconnect&&t.disconnect()}},Vx=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1;let r=t&&t.intake||{};this.f0=U(W(n.helmholtz,W(r.helmholtz,110)),kx,2e3),this.q0=U(W(n.q,W(r.q,6)),.3,30),this.level=U(W(n.level,W(r.level,.33)),0,4),this.sampleRate=W(e&&e.sampleRate,48e3),this.fMax=Math.min(Ax,.49*this.sampleRate),this.out=e.createGain(),this.out.gain.value=this.level,this.inGain=e.createGain(),this.inGain.gain.value=1,this.helm=e.createBiquadFilter(),this.helm.type=`bandpass`,this.helm.frequency.value=this._f(this.f0),this.helm.Q.value=this.q0,this.helmGain=e.createGain(),this.helmGain.gain.value=0,this.inGain.connect(this.helm),this.helm.connect(this.helmGain),this.helmGain.connect(this.out),this.directLP=e.createBiquadFilter(),this.directLP.type=`lowpass`,this.directLP.frequency.value=this._f(this.f0*4),this.directLP.Q.value=.7,this.directGain=e.createGain(),this.directGain.gain.value=0,this.inGain.connect(this.directLP),this.directLP.connect(this.directGain),this.directGain.connect(this.out),this.noiseBuf=this._makeNoise(e,2),this.noiseSrc=c(e.createBufferSource()),this.noiseSrc.buffer=this.noiseBuf,this.noiseSrc.loop=!0,this.noiseHP=e.createBiquadFilter(),this.noiseHP.type=`highpass`,this.noiseHP.frequency.value=this._f(this.f0*.8),this.noiseHP.Q.value=.7,this.noiseBP=e.createBiquadFilter(),this.noiseBP.type=`bandpass`,this.noiseBP.frequency.value=this._f(this.f0*3),this.noiseBP.Q.value=.9,this.noiseGain=e.createGain(),this.noiseGain.gain.value=0,this.noiseSrc.connect(this.noiseHP),this.noiseHP.connect(this.noiseBP),this.noiseBP.connect(this.noiseGain),this.noiseGain.connect(this.out),this.noiseToHelm=e.createGain(),this.noiseToHelm.gain.value=0,this.noiseHP.connect(this.noiseToHelm),this.noiseToHelm.connect(this.helm),this.started=!1,this._nodeCount=10}get input(){return this.inGain}get output(){return this.out}_f(e){return U(W(e,kx),kx,this.fMax)}_makeNoise(e,t){let n=Math.max(1,Math.floor(W(e&&e.sampleRate,48e3)*t)),r=e.createBuffer(1,n,W(e&&e.sampleRate,48e3)),i=r.getChannelData(0),a=2654435769,o=0,s=0;for(let e=0;e<n;e++){a^=a<<13,a>>>=0,a^=a>>17,a^=a<<5,a>>>=0;let t=a/4294967296*2-1;o=.997*o+t*.0555179,s=.985*s+t*.3104856,i[e]=U((o+s+t*.1848)*.32,-1,1)}return r}start(e){if(!(this.started||this.disposed)){this.started=!0;try{this.noiseSrc.start(W(e,0))}catch{}}}update(e){if(this.disposed)return;this.started||this.start(W(e&&e.now,0));let t=W(e&&e.now,W(this.ctx.currentTime,0)),n=U(W(e&&e.load,0),0,1),r=U(W(e&&e.throttle,0),0,1),i=U(W(e&&e.rpmNorm,0),0,1),a=U(W(e&&e.overrun,0),0,1),o=Math.max(n,.001)**.7,s=U(r*(.25+.75*i),0,1),c=U(a*(.15+.85*i),0,1);G(this.helm.Q,U(this.q0*(.55+.45*r),.3,30),t,.05),G(this.helm.frequency,this._f(this.f0),t,.1),G(this.helmGain.gain,U((.12+.88*o)*(.35+.65*i),0,4),t,Mx),G(this.directGain.gain,U(.3*(.2+.8*o),0,4),t,Mx),G(this.noiseBP.frequency,this._f(this.f0*(3+9*s)*(1+.6*c)),t,Mx),G(this.noiseBP.Q,U(.9+.7*s,.3,6),t,.05),G(this.noiseGain.gain,U(.42*s**1.2+.16*c,0,4),t,Mx),G(this.noiseToHelm.gain,U(.2*s+.05*c,0,2),t,Mx),G(this.out.gain,U(this.level,0,4),t,.1)}dispose(){if(this.disposed)return;this.disposed=!0;try{this.started&&this.noiseSrc.stop()}catch{}let e=[this.inGain,this.out,this.helm,this.helmGain,this.directLP,this.directGain,this.noiseSrc,this.noiseHP,this.noiseBP,this.noiseGain,this.noiseToHelm];for(let t of e)t&&t.disconnect&&t.disconnect()}},Hx=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1,this.maxDrive=U(W(n.maxDrive,4.5),1,40),this.idleDrive=U(W(n.idleDrive,1),.1,10);let r=U(W(n.kp,3.2),.5,12),i=U(W(n.kn,2),.5,12);this.sampleRate=W(e&&e.sampleRate,48e3),this.fMax=Math.min(Ax,.49*this.sampleRate),this.drive=e.createGain(),this.drive.gain.value=this.idleDrive,this.shaper=e.createWaveShaper(),this.shaper.curve=Lx(r,i,4096),this.shaper.oversample=`4x`,this.span=e.createGain(),this.span.gain.value=1/Rx(),this.dcBlock=e.createBiquadFilter(),this.dcBlock.type=`highpass`,this.dcBlock.frequency.value=U(22,kx,this.fMax),this.dcBlock.Q.value=.7,this.makeup=e.createGain(),this.makeup.gain.value=this._makeupFor(this.idleDrive),this.out=e.createGain(),this.out.gain.value=1,this.drive.connect(this.span),this.span.connect(this.shaper),this.shaper.connect(this.dcBlock),this.dcBlock.connect(this.makeup),this.makeup.connect(this.out),this._nodeCount=6}get input(){return this.drive}get output(){return this.out}_makeupFor(e){return U(1/Math.max(.05,e)**.7,.05,4)}update(e){if(this.disposed)return;let t=W(e&&e.now,W(this.ctx.currentTime,0)),n=U(W(e&&e.load,0),0,1),r=U(W(e&&e.rpmNorm,0),0,1),i=U(W(e&&e.boost,0),0,1),a=U(W(e&&e.overrun,0),0,1),o=U(n**1.5*(.55+.45*r)+.55*i*n,0,1.4),s=.25*a*(.3+.7*r)+.22*U(W(e&&e.valve,0),0,1)*(.4+.6*n),c=U(this.idleDrive+(this.maxDrive-this.idleDrive)*U(o+s,0,1),.1,this.maxDrive);G(this.drive.gain,c,t,Mx),G(this.makeup.gain,this._makeupFor(c),t,Mx)}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[this.drive,this.span,this.shaper,this.dcBlock,this.makeup,this.out])e&&e.disconnect&&e.disconnect()}}},Ux=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1,this.sampleRate=W(e&&e.sampleRate,48e3),this.fMax=Math.min(Ax,.49*this.sampleRate),this.boomHz=U(W(n.boomHz,62),20,300),this.panelHz=U(W(n.panelHz,155),40,800),this.extLP=U(W(n.exteriorLP,17e3),1e3,this.fMax),this.intLP=U(W(n.interiorLP,1050),120,8e3),this.intBoomDb=U(W(n.boomDb,6.5),0,18),this.intPanelDb=U(W(n.panelDb,3.5),0,18),this.intShelfDb=U(W(n.shelfDb,-11),-40,0),this.shelfHz=U(W(n.shelfHz,3200),500,this.fMax),this.position=U(W(n.position,0),0,1),this.target=this.position,this.inGain=e.createGain(),this.inGain.gain.value=1,this.boom=e.createBiquadFilter(),this.boom.type=`peaking`,this.boom.frequency.value=U(this.boomHz,kx,this.fMax),this.boom.Q.value=U(W(n.boomQ,3.2),.3,20),this.boom.gain.value=0,this.panel=e.createBiquadFilter(),this.panel.type=`peaking`,this.panel.frequency.value=U(this.panelHz,kx,this.fMax),this.panel.Q.value=U(W(n.panelQ,2.4),.3,20),this.panel.gain.value=0,this.lp=e.createBiquadFilter(),this.lp.type=`lowpass`,this.lp.frequency.value=U(this.extLP,kx,this.fMax),this.lp.Q.value=.6,this.shelf=e.createBiquadFilter(),this.shelf.type=`highshelf`,this.shelf.frequency.value=U(this.shelfHz,kx,this.fMax),this.shelf.gain.value=0,this.trim=e.createGain(),this.trim.gain.value=1,this.out=e.createGain(),this.out.gain.value=1,this.inGain.connect(this.boom),this.boom.connect(this.panel),this.panel.connect(this.lp),this.lp.connect(this.shelf),this.shelf.connect(this.trim),this.trim.connect(this.out),this._nodeCount=7,this._write(W(e.currentTime,0),.001)}get input(){return this.inGain}get output(){return this.out}setPerspective(e){return e===`interior`?this.setPosition(1):e===`exterior`&&this.setPosition(0),this}setPosition(e){return this.target=U(W(e,0),0,1),this.disposed||this._write(W(this.ctx.currentTime,0),.05),this}get perspective(){return this.target>=.5?`interior`:`exterior`}_write(e,t){let n=this.target,r=this.extLP*(this.intLP/this.extLP)**+n;G(this.lp.frequency,U(r,kx,this.fMax),e,t),G(this.boom.gain,this.intBoomDb*n,e,t),G(this.panel.gain,this.intPanelDb*n,e,t),G(this.shelf.gain,this.intShelfDb*n,e,t),G(this.trim.gain,U(10**(-4.5*n/20),.05,1),e,t)}update(e){if(this.disposed)return;let t=W(e&&e.now,W(this.ctx.currentTime,0));this._write(t,.05),this.position=this.target}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[this.inGain,this.boom,this.panel,this.lp,this.shelf,this.trim,this.out])e&&e.disconnect&&e.disconnect()}}},Wx=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1;let r=t&&t.exhaust||{},i=t&&Array.isArray(t.banks)&&t.banks.length?t.banks:[[1]];t&&t.gasTempFactor,this.sampleRate=W(e&&e.sampleRate,48e3),this.bankLengths=i.map((e,t)=>t===1&&Number.isFinite(r.bankB)?r.bankB:W(r.bank,1.2)),this.collectorNode=e.createGain(),this.collectorNode.gain.value=1/Math.sqrt(i.length);let a=n.transit!==!1;this.banks=[],this.transits=[],this.inputs=[];for(let r=0;r<i.length;r++){let i=new zx(e,t,Object.assign({length:this.bankLengths[r]},n.bankOpts));if(this.banks.push(i),this.inputs.push(i.input),a){let t=i.nominalDelay/2,n=Math.max(.005,t*2),r=e.createDelay(n);r.delayTime.value=U(t,0,n),i.output.connect(r),r.connect(this.collectorNode),this.transits.push({d:r,t,maxT:n})}else i.output.connect(this.collectorNode),this.transits.push(null)}this.collector=new zx(e,t,Object.assign({length:W(r.collector,1),reflection:U(W(r.reflection,.5)*.7,0,jx),damping:U(W(r.damping,.4)*1.5,.05,2)},n.collectorOpts)),this.collectorNode.connect(this.collector.input),this.muffler=new Bx(e,t,n.mufflerOpts),this.collector.output.connect(this.muffler.input),this.useNonlinearity=n.nonlinearity!==!1,this.out=e.createGain(),this.out.gain.value=1,this.useNonlinearity?(this.nonlinearity=new Hx(e,t,n.nonlinearityOpts),this.muffler.output.connect(this.nonlinearity.input),this.nonlinearity.output.connect(this.out)):(this.nonlinearity=null,this.muffler.output.connect(this.out)),this._thermalSpan=this.banks.length?this.banks[0].thermalSpan:.05,this._thermalBias=this.banks.length?this.banks[0].thermalBias:.35,this.report={bankLengths:this.bankLengths.slice(),bankFrequencies:this.banks.map(e=>e.frequency),bankModes:this.banks.map(e=>e.mode),collectorFrequency:this.collector.frequency,collectorMode:this.collector.mode,mufflerNotches:this.muffler.notches.slice(),transitSkewMs:this.transits[0]&&this.transits[1]?Math.abs(this.transits[0].t-this.transits[1].t)*1e3:0},this._nodeCount=this._countNodes()}get input(){return this.inputs[0]}get output(){return this.out}update(e){if(this.disposed)return;let t=W(e&&e.now,W(this.ctx.currentTime,0)),n=U(W(e&&e.load,0),0,1),r=U(W(e&&e.rpmNorm,0),0,1),i=U(.6*n+.4*r,0,1),a=1+this._thermalSpan*(i-this._thermalBias);for(let n=0;n<this.banks.length;n++){this.banks[n].update(e);let r=this.transits[n];r&&G(r.d.delayTime,U(r.t/a,0,r.maxT),t,Nx)}this.collector.update(e),this.muffler.update(e),this.nonlinearity&&this.nonlinearity.update(e)}_countNodes(){let e=2;for(let t of this.banks)e+=t._nodeCount;for(let t of this.transits)t&&(e+=1);return e+=this.collector._nodeCount+this.muffler._nodeCount,this.nonlinearity&&(e+=this.nonlinearity._nodeCount),e}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.banks)e.dispose();for(let e of this.transits)e&&e.d.disconnect&&e.d.disconnect();this.collector.dispose(),this.muffler.dispose(),this.nonlinearity&&this.nonlinearity.dispose();for(let e of[this.collectorNode,this.out])e&&e.disconnect&&e.disconnect()}}},Gx=3800,Kx=-5.5,qx=1150,K=.02,Jx=10,Yx=2e4,Xx=.004;function q(e,t,n){return e<t?t:e>n?n:e}function J(e,t){return typeof e==`number`&&isFinite(e)?e:t}function Zx(e,t){return q(J(e,t),Jx,Yx)}function Y(e,t,n,r){e.setTargetAtTime(J(t,0),J(n,0),r>0?r:K)}function X(e,t,n,r,i){e.setTargetAtTime(Zx(t,i===void 0?Jx:i),J(n,0),r>0?r:K)}function Qx(e){let t=e>>>0||1;return function(){return t^=t<<13,t>>>=0,t^=t>>17,t^=t<<5,t>>>=0,t/4294967296}}var $x=new WeakMap;function eS(e,t){let n=$x.get(e);if(n||(n={},$x.set(e,n)),n[t])return n[t];let r=J(e.sampleRate,48e3),i=Math.max(1024,Math.floor(r*2)),a=e.createBuffer(1,i,r),o=a.getChannelData(0),s=Qx(t===`pink`?2654435769:2246822507);if(t===`pink`){let e=0,t=0,n=0,r=0,a=0,c=0,l=0;for(let u=0;u<i;u++){let i=s()*2-1;e=.99886*e+i*.0555179,t=.99332*t+i*.0750759,n=.969*n+i*.153852,r=.8665*r+i*.3104856,a=.55*a+i*.5329522,c=-.7616*c-i*.016898,o[u]=(e+t+n+r+a+c+l+i*.5362)*.11,l=i*.115926}}else for(let e=0;e<i;e++)o[e]=s()*2-1;let c=Math.min(2048,i>>2);for(let e=0;e<c;e++){let t=e/c;o[e]=o[e]*t+o[i-c+e]*(1-t)}return n[t]=a,a}function tS(e,t,n){let r=c(e.createBufferSource());r.buffer=eS(e,t),r.loop=!0;try{r.start(0,J(n,0)),r.__started=!0}catch{}return r}function nS(e,t,n,r){let i=e.createGain();return i.gain.value=n,t.connect(i),i.connect(r),i}function rS(e,t){let n=J(t,0);for(let t=0;t<e.length;t++){let r=e[t];if(r&&!r.__started)try{r.start(n),r.__started=!0}catch{}}}function iS(e,t){for(let n=0;n<e.length;n++){try{e[n].stop(J(t,0))}catch{}try{e[n].disconnect()}catch{}}}function aS(e){for(let t=0;t<e.length;t++)try{e[t].disconnect()}catch{}}var oS=class{constructor(e,t,n){this.ctx=e,this.profile=t;let r=n||{};this.level=J(r.level,1),this.gearCut=r.gearCut===`straight`?`straight`:`helical`,this.driveshaftScale=typeof r.driveshaftScale==`number`&&isFinite(r.driveshaftScale)?r.driveshaftScale:`auto`,this._scale=0,this._srcs=[],this._nodes=[];let i=e=>(this._nodes.push(e),e);this.out=i(e.createGain()),this.out.gain.value=this.level;let a=tS(e,`white`,.71),o=tS(e,`pink`,1.31);this._srcs.push(a,o),this.meshOsc1=c(e.createOscillator()),this.meshOsc1.type=`sine`,this.meshOsc1.frequency.value=500,this.meshOsc2=c(e.createOscillator()),this.meshOsc2.type=`sine`,this.meshOsc2.frequency.value=1e3,this.runoutOsc=c(e.createOscillator()),this.runoutOsc.type=`sine`,this.runoutOsc.frequency.value=20,this._srcs.push(this.meshOsc1,this.meshOsc2,this.runoutOsc),this.meshH2=i(e.createGain()),this.meshH2.gain.value=this.gearCut===`straight`?.55:.2,this.meshBP=i(e.createBiquadFilter()),this.meshBP.type=`bandpass`,this.meshBP.frequency.value=500,this.meshBP.Q.value=this.gearCut===`straight`?9:3.5,this.meshNoiseG=i(e.createGain()),this.meshNoiseG.gain.value=this.gearCut===`straight`?.22:.6,this.meshAM=i(e.createGain()),this.meshAM.gain.value=.85,i(nS(e,this.runoutOsc,.15,this.meshAM.gain)),this.meshGain=i(e.createGain()),this.meshGain.gain.value=0,this.meshOsc1.connect(this.meshAM),this.meshOsc2.connect(this.meshH2),this.meshH2.connect(this.meshAM),a.connect(this.meshBP),this.meshBP.connect(this.meshNoiseG),this.meshNoiseG.connect(this.meshAM),this.meshAM.connect(this.meshGain),this.meshGain.connect(this.out),this.ratBP1=i(e.createBiquadFilter()),this.ratBP1.type=`bandpass`,this.ratBP1.frequency.value=1800,this.ratBP1.Q.value=2,this.ratBP2=i(e.createBiquadFilter()),this.ratBP2.type=`bandpass`,this.ratBP2.frequency.value=3600,this.ratBP2.Q.value=2.5,this.ratH2=i(e.createGain()),this.ratH2.gain.value=.5,this.ratAM=i(e.createGain()),this.ratAM.gain.value=.4,this.torsOsc=c(e.createOscillator()),this.torsOsc.type=`sawtooth`,this.torsOsc.frequency.value=60,this._srcs.push(this.torsOsc),i(nS(e,this.torsOsc,.6,this.ratAM.gain)),this.ratGain=i(e.createGain()),this.ratGain.gain.value=0,o.connect(this.ratBP1),o.connect(this.ratBP2),this.ratBP1.connect(this.ratAM),this.ratBP2.connect(this.ratH2),this.ratH2.connect(this.ratAM),this.ratAM.connect(this.ratGain),this.ratGain.connect(this.out),this.setVehicle(r.vehicle,r.gearTeeth,r.finalDrive),this.setProfile(t)}get input(){return null}get output(){return this.out}setVehicle(e,t,n){let r=e||null,i=t||r&&r.gearTeeth||null;this.teeth=i&&i.length?i:[37,31,27,24,22,20],this.finalDrive=q(J(n,J(r&&r.finalDrive,3.9)),1,12),this._scale=0}setProfile(e){this.profile=e,this.cyl=q(J(e&&e.cylinders,4),1,16),this.idleRpm=J(e&&e.idleRpm,800)}_shaftRpm(e){let t=Math.abs(J(e.wheelRpm,0));if(this.driveshaftScale!==`auto`)return t*this.driveshaftScale;if(this._scale===0){let n=J(e.gearRatio,0),r=J(e.rpm,0);if(n>.05&&t>50&&r>200&&J(e.clutchEngaged,0)>.9){let e=r/t,i=Math.abs(e-n),a=Math.abs(e-n/this.finalDrive);this._scale=i<a?this.finalDrive:1}}return t*(this._scale||1)}meshFrequency(e,t){let n=Math.round(J(e,0))-1;return n<0||n>=this.teeth.length?0:Math.abs(J(t,0))/60*J(this.teeth[n],0)}update(e){let t=J(e.now,0),n=Math.round(J(e.gear,0)),r=q(J(e.load,0),0,1),i=Math.max(0,J(e.rpm,0)),a=J(e.f0,i/120),o=q(J(e.clutchEngaged,0),0,1),s=e.shiftPhase||``,c=this._shaftRpm(e),l=this.meshFrequency(n,c),u=0;if(l>0){let e=1/(1+(l/1800)**2.4);u=q((l-30)/40,0,1)*e}let d=J(e.torqueSign,1)>=0?.22+.85*r:.34,f=+(n>0&&Math.abs(J(e.gearRatio,0))>.001),p=s===`open`||s===`sync`||s===`cut`?.05:1,m=.45+.55*q(c/2500,0,1),h=.065*(this.gearCut===`straight`?1:.42)*f*o*p*d*u*m;X(this.meshOsc1.frequency,l,t,K,500),X(this.meshOsc2.frequency,l*2,t,K,1e3);let g=this.gearCut===`straight`?.55:.2;Y(this.meshH2.gain,g/(1+(l*2/2600)**2.4),t,K),X(this.meshBP.frequency,l,t,K,500),X(this.runoutOsc.frequency,c/60*2,t,K,Jx),Y(this.meshGain.gain,h,t,K);let _=q(Math.abs(J(e.dRpm,0))/4e3,0,1),v=q(Math.abs(J(e.clutchSlip,0))/800,0,1),y=o*q(1-(i-this.idleRpm)/Math.max(200,this.idleRpm*1.6),0,1)*(1-.7*r)*(f?.4:1),b=1-.65*r*f,x=q(.5*y+.75*_+.7*v,0,1)*b;X(this.torsOsc.frequency,this.cyl*a,t,K,Jx),Y(this.ratGain.gain,.09*x*q(i/Math.max(1,this.idleRpm*.6),0,1),t,K)}start(e){rS(this._srcs,e)}dispose(){let e=J(this.ctx.currentTime,0);iS(this._srcs,e),aS(this._nodes),this._srcs.length=0}},sS=e=>e<.1,cS=class e{static supports(e){return!!(e&&e.turbo)}constructor(t,n,r){this.ctx=t;let i=r||{};this.level=J(i.level,1),this.maxTurboRpm=J(i.maxTurboRpm,15e4),this.flutterMode=i.flutter!==!1,this.surgeLevel=q(J(i.surgeLevel,1),0,3),this.spool=0,this.boost=0,this.boostBar=0,this.turboRpm=0,this._vent=0,this._surge=0,this._climb=0,this._liftRate=13,this._liftPitch=1,this._liftTau=.26,this._lastBov=-1e9,this._prevThrottle=0,this._prevShifting=!1,this._rnd=Qx(1374496523),this._srcs=[],this._nodes=[];let a=e=>(this._nodes.push(e),e);if(this.out=a(t.createGain()),this.out.gain.value=this.level,this._graphBuilt=!1,this.setProfile(n),!e.supports(n))return;this.bus=a(t.createGain()),this.airLP=a(t.createBiquadFilter()),this.airLP.type=`lowpass`,this.airLP.frequency.value=Gx,this.airLP.Q.value=-3.01,this.airShelf=a(t.createBiquadFilter()),this.airShelf.type=`highshelf`,this.airShelf.frequency.value=2600,this.airShelf.gain.value=Kx,this.bus.connect(this.airLP),this.airLP.connect(this.airShelf),this.airShelf.connect(this.out);let o=tS(t,`white`,1.07);this._srcs.push(o),this.whineOsc=c(t.createOscillator()),this.whineOsc.setPeriodicWave(uS(t)),this.whineOsc.frequency.value=1200,this._srcs.push(this.whineOsc),this.whineBP=a(t.createBiquadFilter()),this.whineBP.type=`bandpass`,this.whineBP.frequency.value=1500,this.whineBP.Q.value=1.5,this.whineGain=a(t.createGain()),this.whineGain.gain.value=0,this.whineDrive=a(t.createGain()),this.whineDrive.gain.value=1,this.whineShaper=a(t.createWaveShaper()),this.whineShaper.curve=dS(1024,.55),this.whineShaper.oversample=`4x`,this.whineOsc.connect(this.whineDrive),this.whineDrive.connect(this.whineShaper),this.whineShaper.connect(this.whineBP),this.whineBP.connect(this.whineGain),this.whineGain.connect(this.bus);let s=tS(t,`pink`,.29);this._srcs.push(s),this.grainBP=a(t.createBiquadFilter()),this.grainBP.type=`bandpass`,this.grainBP.frequency.value=55,this.grainBP.Q.value=.6,this.grainDepth=a(t.createGain()),this.grainDepth.gain.value=0,s.connect(this.grainBP),this.grainBP.connect(this.grainDepth),this.grainDepth.connect(this.whineGain.gain),this.wander1=c(t.createOscillator()),this.wander1.type=`sine`,this.wander1.frequency.value=.31,this.wander2=c(t.createOscillator()),this.wander2.type=`sine`,this.wander2.frequency.value=2.17,this._srcs.push(this.wander1,this.wander2),this.wanderDepth1=a(nS(t,this.wander1,0,this.whineOsc.detune)),this.wanderDepth2=a(nS(t,this.wander2,0,this.whineOsc.detune)),this.shaftOsc=c(t.createOscillator()),this.shaftOsc.type=`sine`,this.shaftOsc.frequency.value=180,this._srcs.push(this.shaftOsc),this.shaftDepth=a(t.createGain()),this.shaftDepth.gain.value=0,this.shaftOsc.connect(this.shaftDepth),this.shaftDepth.connect(this.whineGain.gain),this.hissBP=a(t.createBiquadFilter()),this.hissBP.type=`bandpass`,this.hissBP.frequency.value=2e3,this.hissBP.Q.value=.8,this.hissGain=a(t.createGain()),this.hissGain.gain.value=0,o.connect(this.hissBP),this.hissBP.connect(this.hissGain),this.hissGain.connect(this.bus),this.hissGrain=a(t.createGain()),this.hissGrain.gain.value=0,this.grainBP.connect(this.hissGrain),this.hissGrain.connect(this.hissGain.gain),this.whineNoiseBP=a(t.createBiquadFilter()),this.whineNoiseBP.type=`bandpass`,this.whineNoiseBP.frequency.value=800,this.whineNoiseBP.Q.value=6,this.whineNoiseGain=a(t.createGain()),this.whineNoiseGain.gain.value=0,o.connect(this.whineNoiseBP),this.whineNoiseBP.connect(this.whineNoiseGain),this.whineNoiseGain.connect(this.bus);let l=tS(t,`pink`,1.31);this._srcs.push(l),this.airflowHP=a(t.createBiquadFilter()),this.airflowHP.type=`highpass`,this.airflowHP.frequency.value=280,this.airflowHP.Q.value=.5,this.airflowLP=a(t.createBiquadFilter()),this.airflowLP.type=`lowpass`,this.airflowLP.frequency.value=1400,this.airflowLP.Q.value=.5,this.airflowGain=a(t.createGain()),this.airflowGain.gain.value=0,l.connect(this.airflowHP),this.airflowHP.connect(this.airflowLP),this.airflowLP.connect(this.airflowGain),this.airflowGain.connect(this.bus),this.bovBP=a(t.createBiquadFilter()),this.bovBP.type=`bandpass`,this.bovBP.frequency.value=2400,this.bovBP.Q.value=7,this.bovGain=a(t.createGain()),this.bovGain.gain.value=0,o.connect(this.bovBP),this.bovBP.connect(this.bovGain),this.bovGain.connect(this.bus),this.wgBP=a(t.createBiquadFilter()),this.wgBP.type=`bandpass`,this.wgBP.frequency.value=1500,this.wgBP.Q.value=.6,this.wgLevel=a(t.createGain()),this.wgLevel.gain.value=0,this.wgOsc=c(t.createOscillator()),this.wgOsc.type=`sawtooth`,this.wgOsc.frequency.value=24,this._srcs.push(this.wgOsc),this.wgShaper=a(t.createWaveShaper()),this.wgShaper.curve=fS(1024),this.wgShaper.oversample=`2x`,this.wgAM=a(t.createGain()),this.wgAM.gain.value=.05,this.wgOsc.connect(this.wgShaper),this.wgShaper.connect(this.wgAM.gain),o.connect(this.wgBP),this.wgBP.connect(this.wgAM),this.wgAM.connect(this.wgLevel),this.wgLevel.connect(this.bus),this.wgJitter=a(t.createGain()),this.wgJitter.gain.value=6,this.grainBP.connect(this.wgJitter),this.wgJitter.connect(this.wgOsc.frequency),this.wgGrain=a(t.createGain()),this.wgGrain.gain.value=0,this.grainBP.connect(this.wgGrain),this.wgGrain.connect(this.wgLevel.gain),this.hiOsc=c(t.createOscillator()),this.hiOsc.type=`sine`,this.hiOsc.frequency.value=6e3,this._srcs.push(this.hiOsc),this.hiGain=a(t.createGain()),this.hiGain.gain.value=0,this.hiOsc.connect(this.hiGain),this.hiGain.connect(this.out),this.hiGrain=a(t.createGain()),this.hiGrain.gain.value=0,this.grainBP.connect(this.hiGrain),this.hiGrain.connect(this.hiGain.gain),this.hiWander=a(nS(t,this.wander2,0,this.hiOsc.detune)),this.buzzOsc=c(t.createOscillator()),this.buzzOsc.type=`sawtooth`,this.buzzOsc.frequency.value=60,this._srcs.push(this.buzzOsc),this.buzzBP=a(t.createBiquadFilter()),this.buzzBP.type=`bandpass`,this.buzzBP.frequency.value=1500,this.buzzBP.Q.value=1.2,this.buzzGain=a(t.createGain()),this.buzzGain.gain.value=0,this.buzzOsc.connect(this.buzzBP),this.buzzBP.connect(this.buzzGain),this.buzzGain.connect(this.bus),this.bovHissHP=a(t.createBiquadFilter()),this.bovHissHP.type=`highpass`,this.bovHissHP.frequency.value=1800,this.bovHissHP.Q.value=-3.01,this.bovHissGain=a(t.createGain()),this.bovHissGain.gain.value=0,o.connect(this.bovHissHP),this.bovHissHP.connect(this.bovHissGain),this.bovHissGain.connect(this.bus),this.surgeOsc=c(t.createOscillator()),this.surgeOsc.type=`sawtooth`,this.surgeOsc.frequency.value=16,this._srcs.push(this.surgeOsc),this.surgeShaper=a(t.createWaveShaper()),this.surgeShaper.curve=fS(1024),this.surgeShaper.oversample=`2x`,this.surgeOsc.connect(this.surgeShaper),this.surgeBus=a(t.createGain()),this.surgeBus.gain.value=.7,this.surgeLP=a(t.createBiquadFilter()),this.surgeLP.type=`lowpass`,this.surgeLP.frequency.value=6500,this.surgeLP.Q.value=-3.01,this.surgeBus.connect(this.surgeLP),this.surgeLP.connect(this.out),this.whooshBP=a(t.createBiquadFilter()),this.whooshBP.type=`bandpass`,this.whooshBP.frequency.value=5e3,this.whooshBP.Q.value=.7,this.whooshGain=a(t.createGain()),this.whooshGain.gain.value=0,o.connect(this.whooshBP),this.whooshBP.connect(this.whooshGain),this.whooshGain.connect(this.surgeLP),this.whooshGrain=a(t.createGain()),this.whooshGrain.gain.value=0,this.grainBP.connect(this.whooshGrain),this.whooshGrain.connect(this.whooshGain.gain),this.surgeSend=a(t.createGain()),this.surgeSend.gain.value=.55,this.surgeJitter=a(t.createGain()),this.surgeJitter.gain.value=0,this.grainBP.connect(this.surgeJitter),this.surgeJitter.connect(this.surgeOsc.frequency),this.surgeBody=a(t.createBiquadFilter()),this.surgeBody.type=`bandpass`,this.surgeBody.frequency.value=3e3,this.surgeBody.Q.value=1.1,this.surgeBodyAM=a(t.createGain()),this.surgeBodyAM.gain.value=0,this.surgeBodyLvl=a(t.createGain()),this.surgeBodyLvl.gain.value=0,o.connect(this.surgeBody),this.surgeBody.connect(this.surgeBodyAM),this.surgeBodyAM.connect(this.surgeBodyLvl),this.surgeBodyLvl.connect(this.surgeBus),this.surgeBodyLvl.connect(this.surgeSend),this.surgeBodyDepth=a(t.createGain()),this.surgeBodyDepth.gain.value=1,this.surgeShaper.connect(this.surgeBodyDepth),this.surgeBodyDepth.connect(this.surgeBodyAM.gain),this.surgeChirp=a(t.createGain()),this.surgeChirp.gain.value=0,this.surgeShaper.connect(this.surgeChirp),this.fwOsc=c(t.createOscillator()),this.fwOsc.type=`sine`,this.fwOsc.frequency.value=7e3,this._srcs.push(this.fwOsc),this.fwBP=a(t.createBiquadFilter()),this.fwBP.type=`bandpass`,this.fwBP.frequency.value=7e3,this.fwBP.Q.value=3,this.fwNoise=a(t.createGain()),this.fwNoise.gain.value=3.2,this.fwTone=a(t.createGain()),this.fwTone.gain.value=.2,o.connect(this.fwBP),this.fwBP.connect(this.fwNoise),this.hiSurgeAM=a(t.createGain()),this.hiSurgeAM.gain.value=0,this.hiSurgeLvl=a(t.createGain()),this.hiSurgeLvl.gain.value=0,this.fwOsc.connect(this.fwTone),this.fwTone.connect(this.hiSurgeAM),this.fwNoise.connect(this.hiSurgeAM),this.hiSurgeAM.connect(this.hiSurgeLvl),this.hiSurgeLvl.connect(this.out),this.surgeShaper.connect(this.hiSurgeAM.gain),this.hiChirp=a(t.createGain()),this.hiChirp.gain.value=0,this.surgeShaper.connect(this.hiChirp),this.hiChirp.connect(this.fwOsc.frequency),this.hiChirpN=a(t.createGain()),this.hiChirpN.gain.value=0,this.surgeShaper.connect(this.hiChirpN),this.hiChirpN.connect(this.fwBP.frequency),this.surgeChirp.connect(this.surgeBody.frequency),this.surgeEdge=a(t.createBiquadFilter()),this.surgeEdge.type=`bandpass`,this.surgeEdge.frequency.value=5200,this.surgeEdge.Q.value=.8,this.surgeEdgeAM=a(t.createGain()),this.surgeEdgeAM.gain.value=0,this.surgeEdgeLvl=a(t.createGain()),this.surgeEdgeLvl.gain.value=0,o.connect(this.surgeEdge),this.surgeEdge.connect(this.surgeEdgeAM),this.surgeEdgeAM.connect(this.surgeEdgeLvl),this.surgeEdgeLvl.connect(this.surgeBus),this.surgeEdgeDepth=a(t.createGain()),this.surgeEdgeDepth.gain.value=1,this.surgeShaper.connect(this.surgeEdgeDepth),this.surgeEdgeDepth.connect(this.surgeEdgeAM.gain),this._graphBuilt=!0,this.enabled=!0}get input(){return null}get output(){return this.out}get state(){return{spool:this.spool,boost:this.boost,boostBar:this.boostBar,turboRpm:this.turboRpm,surge:this._surge}}setProfile(e){this.profile=e;let t=e&&e.turbo||null;this.turbo=t,this.enabled=!!t&&this._graphBuilt===!0,this.inertia=q(J(t&&t.inertia,.4),.05,3),this.maxBoost=q(J(t&&t.maxBoost,1),0,5),this.bovLevel=q(J(t&&t.bov,.5),0,2),this.surgeTrim=q(J(t&&t.surge,1),0,3),this.valve=Math.round(q(J(t&&t.valve,1),0,2)),this.flutterHz=q(J(t&&t.flutterHz,13),3,30),this.screamer=J(t&&t.screamer,0)>=.5,this.antiLag=J(t&&t.antiLag,0)>=.5;let n=J(e&&e.redlineRpm,7e3);this.boostRpm=Math.min(q(J(t&&t.boostRpm,3500),800,9e3),.65*n);let r=.5*J(t&&t.whineOrder,70);this.whineRef=q(n/120*r,200,qx)}update(e){if(!this.enabled)return;let t=J(e.now,0),n=q(J(e.dt,1/60),0,.25),r=q(J(e.load,0),0,1),i=q(J(e.throttle,0),0,1),a=q(J(e.rpmNorm,0),0,1),o=!!e.shifting;this._als=this.antiLag&&i<.12&&a>.15;let s=J(e.rpm,0),c=Math.max(.6*J(this.profile&&this.profile.redlineRpm,7e3),this.boostRpm+1500),l=q((s-this.boostRpm)/(c-this.boostRpm),0,1),u=e.limiter?Math.max(r,.95*i):r,d=this._als?.7*(.3+.7*a):q(u*(.08+.92*l),0,1),f=i<.12,p=q((d-this.spool)*3,0,1);this._climb+=(p-this._climb)*Math.min(1,n/.08);let m=d>this.spool?this.inertia*1.1:this.inertia*(f?.45:1.3),h=n>0?1-Math.exp(-n/Math.max(.001,m)):0;this.spool+=(d-this.spool)*h;let g=.04+.07*a;this.spool<g&&(this.spool=g),this.spool=q(J(this.spool,g),0,1),this._vent>0&&(this._vent*=Math.exp(-n/.18),this._vent<.001&&(this._vent=0));let _=this.spool*this.spool;this.boost=q(_*(1-.92*this._vent),0,1),this.boostBar=this.boost*this.maxBoost,this.turboRpm=this.spool*this.maxTurboRpm;let v=Math.max(120,this.whineRef*Math.max(.05,this.spool)**1.55);X(this.whineOsc.frequency,v,t,K,1e3),X(this.whineBP.frequency,v*1.25,t,K,1600),X(this.whineNoiseBP.frequency,v,t,K,800);let y=this.spool**2,b=q(Math.max(r,i*.7),0,1),x=.085*y*(.62+.38*b);Y(this.whineGain.gain,x,t,K),Y(this.whineNoiseGain.gain,.3*y*(.5+.5*b),t,K),Y(this.airflowGain.gain,.2*(.15+.85*this.spool)*this.spool*(.25+.75*b),t,.05),X(this.airflowLP.frequency,900+1300*this.spool,t,K,1400);let S=26*(1-.75*this.spool);Y(this.wanderDepth1.gain,S,t,.08),Y(this.wanderDepth2.gain,S*.4,t,.08);let C=.55-.3*this.spool;Y(this.grainDepth.gain,x*C,t,.05),Y(this.whineDrive.gain,.8+.9*this.spool,t,K),X(this.grainBP.frequency,28+120*this.spool,t,K,55),X(this.shaftOsc.frequency,q(v/11,4,400),t,K,180),Y(this.shaftDepth.gain,x*(.52-.28*this.spool),t,K);let w=q((this.spool-.4)/.3,0,1)*q((a-.4)/.3,0,1),ee=w*i*(this.screamer?1.3:.7);X(this.wgOsc.frequency,18+12*w+8*a,t,.05,24),X(this.wgBP.frequency,(this.screamer?900:1400)+1300*this.spool,t,K,1500),Y(this.wgLevel.gain,ee,t,.05),Y(this.wgGrain.gain,ee*.5,t,.05);let te=.1*y*(.45+.55*b);Y(this.hissGain.gain,te,t,K),Y(this.hissGrain.gain,te*.65,t,.05),X(this.hissBP.frequency,q(v*2.2,900,4200),t,K,2e3);let ne=.18*(q((this.boost-.12)/.45,0,1)*i*(1-.75*a)+.6*this._climb*Math.sqrt(this.spool));Y(this.whooshGain.gain,ne,t,.04),Y(this.whooshGrain.gain,ne*.6,t,.05),X(this.whooshBP.frequency,q(4e3+3500*this.spool,3e3,8e3),t,K,5e3);let re=.08*q((this.spool-.62)/.25,0,1)*b;X(this.buzzOsc.frequency,q(v/11,20,400),t,K,60),X(this.buzzBP.frequency,q(v*1.5,400,6e3),t,K,1500),Y(this.buzzGain.gain,re,t,K),X(this.hiOsc.frequency,q(5e3+8e3*this.spool**1.4,3e3,15e3),t,K,6e3);let ie=.022*y*(.55+.45*b);Y(this.hiGain.gain,ie,t,K),Y(this.hiGrain.gain,ie*.4,t,.05),Y(this.hiWander.gain,12*(1-.6*this.spool),t,.08);let ae=q(J(e.evBov,0),0,1);ae>0&&this._fireBov(t,ae),this._stepSurge(t,n,i,a,o,e),this._prevLimiter=!!e.limiter,this._prevThrottle=i,this._prevShifting=o}_stepSurge(e,t,n,r,i,a){this._surge*=Math.exp(-t/this._liftTau),this._closedT=sS(n)?(this._closedT||0)+t:0,this._surge<.001&&(this._surge=0);let o=n<.1,s=o&&this._prevThrottle>=.25,c=this._prevThrottle-n>.2&&n<.5,l=i&&!this._prevShifting,u=this.flutterMode===!1||this.antiLag?0:1,d=q((this.spool-.12)/.28,0,1)*(this.valve===0?1:q(1-.9*this.bovLevel,.15,1))*u,f=a.gearbox===`dct`?.35:a.gearbox===`auto`?.15:1,p=s||c?d:l?d*f:0;if(p>0){if(this._surge<.1){let e=()=>this._rnd();this._liftRate=this.flutterHz*(.7+.45*r+.35*this.boost)*(.85+.3*e()),this._liftPitch=(.85+.25*r)*(.92+.16*e()),this._liftTau=.1+.1*e()+.04*this.boost}this._surge=Math.max(this._surge,p)}o&&d>.06&&this._closedT<.15&&(this._surge=Math.max(this._surge,d*.8));let m=n>.5||n>this._prevThrottle+.05;!o&&!i&&m&&(this._surge*=Math.exp(-t/.11));let h=q(this._surge,0,1),g=this._liftRate*(.7+.45*h);X(this.surgeOsc.frequency,g,e,.03,16),X(this.surgeBody.frequency,(2400+700*h+500*r)*this._liftPitch,e,.04,3e3),X(this.surgeEdge.frequency,(4600+600*h+600*r)*this._liftPitch,e,.04,5200),Y(this.surgeChirp.gain,600*h,e,.04),Y(this.surgeJitter.gain,18*h,e,.04);let _=q(J(a.overrun,0),0,1),v=(.6+.4*r)*(.8+.3*_),y=this.surgeLevel*this.surgeTrim;Y(this.surgeBodyLvl.gain,6.5*y*h*v,e,.03),Y(this.surgeEdgeLvl.gain,.25*y*h*h*v,e,.03);let b=q(5500+3500*this.spool,4500,9500);X(this.fwOsc.frequency,b,e,.03,7e3),X(this.fwBP.frequency,b,e,.03,7e3),Y(this.hiSurgeLvl.gain,1.6*y*h*v,e,.03),Y(this.hiChirp.gain,900*h,e,.04),Y(this.hiChirpN.gain,900*h,e,.04)}release(){let e=J(this.ctx.currentTime,0);this.enabled=!1,this.out.gain.setTargetAtTime(0,e,.07),this.surgeSend.gain.setTargetAtTime(0,e,.07);for(let t of this._srcs)try{t.stop(e+.5)}catch{}this._srcs.length=0}_fireBov(e,t){if(this.valve===0)return;let n=this.valve===2,r=q(this.boost,0,1),i=q(this.bovLevel*1.35*t*(.15+.85*r)*(n?.3:1),5e-4,2.5),a=q(.11+.26*r,.05,.5),o=J(e,0)+Xx,s=this.bovBP.frequency;s.cancelScheduledValues(o),s.setValueAtTime(Zx((n?1300:2600)+1800*r,2800),o),s.exponentialRampToValueAtTime(Zx((n?300:520)+180*r,620),o+a*.8);let c=this.bovBP.Q;c.cancelScheduledValues(o),c.setValueAtTime(n?1.5:4.5,o),c.linearRampToValueAtTime(n?3:11,o+a*.6);let l=this.bovHissGain.gain;l.cancelScheduledValues(o),n||(l.setValueAtTime(4e-4,o),l.linearRampToValueAtTime(i*.45,o+.008),l.exponentialRampToValueAtTime(4e-4,o+a*.9),l.setValueAtTime(0,o+a));let u=this.bovGain.gain;u.cancelScheduledValues(o),u.setValueAtTime(4e-4,o),u.linearRampToValueAtTime(i,o+.012),u.exponentialRampToValueAtTime(4e-4,o+a),u.setValueAtTime(0,o+a+.005),this._vent=q(this.bovLevel,.15,1),this.spool*=.97,this._lastBov=J(e,0)}start(e){rS(this._srcs,e)}dispose(){let e=J(this.ctx.currentTime,0);iS(this._srcs,e),aS(this._nodes),this._srcs.length=0,this.enabled=!1}},lS=new WeakMap;function uS(e){let t=lS.get(e);if(t)return t;let n=new Float32Array(11),r=new Float32Array(11);for(let e=1;e<=10;e++){let t=e%2?1.25:.8;r[e]=1/e**1.4*t}let i=e.createPeriodicWave(n,r,{disableNormalization:!1});return lS.set(e,i),i}function dS(e=1024,t=.55){let n=new Float32Array(e);for(let r=0;r<e;r++){let i=r/(e-1)*2-1,a=i>=0?2.4*(1+t):2.4*(1-t);n[r]=Math.tanh(a*i)/Math.tanh(a)}return n}function fS(e=1024){let t=new Float32Array(e),n=.24;for(let r=0;r<e;r++){let i=r/(e-1),a=i<n?.5-.5*Math.cos(Math.PI*i/n):1;t[r]=a*Math.exp(-4.5*Math.max(0,i-n))}return t}var pS=Object.freeze({bang:Object.freeze({bus:`combustion`,fA:112,qA:1.6,fB:680,qB:2,mixB:.58,atk:.005,dec:.19,lvl:1}),crackle:Object.freeze({bus:`combustion`,fA:700,qA:3,fB:1850,qB:3.6,mixB:.62,atk:.003,dec:.055,lvl:.5}),clunk:Object.freeze({bus:`mechanical`,fA:330,qA:7,fB:1250,qB:6,mixB:.45,atk:.0035,dec:.075,lvl:.62}),thump:Object.freeze({bus:`mechanical`,fA:95,qA:2.2,fB:320,qB:3,mixB:.35,atk:.004,dec:.13,lvl:.8}),click:Object.freeze({bus:`mechanical`,fA:1500,qA:5,fB:2800,qB:6,mixB:.4,atk:.0018,dec:.02,lvl:.16})}),mS=class{constructor(e,t,n){this.ctx=e;let r=n||{};this.level=J(r.level,1),this.lookahead=q(J(r.lookahead,Xx),0,.05),this.overrunCrackle=r.overrunCrackle!==!1,this.maxPerFrame=q(Math.round(J(r.maxPerFrame,18)),1,48),this.stolen=0,this.fired=0,this.pops=[],this._next=0,this._nextPop=0,this._prevPhase=``,this._syncClicks=0,this._rnd=Qx(625341585),this._srcs=[],this._nodes=[];let i=e=>(this._nodes.push(e),e);this.out=i(e.createGain()),this.combOut=i(e.createGain()),this.makeup=q(J(r.makeup,9),1,40),this.out.gain.value=this.level*this.makeup,this.combOut.gain.value=this.level*this.makeup;let a=q(Math.round(J(r.voices,16)),2,40),o=Math.max(1,Math.round(a*.62));this.voices=Array(a),this.pools={combustion:[],mechanical:[]},this._cursor={combustion:0,mechanical:0};for(let t=0;t<a;t++){let n=tS(e,`white`,t*.137%1.9);this._srcs.push(n);let r=i(e.createBiquadFilter());r.type=`bandpass`,r.frequency.value=1e3,r.Q.value=6;let a=i(e.createBiquadFilter());a.type=`bandpass`,a.frequency.value=3e3,a.Q.value=8;let s=i(e.createGain());s.gain.value=.5;let c=i(e.createGain());c.gain.value=0;let l=t<o?`combustion`:`mechanical`;n.connect(r),n.connect(a),r.connect(c),a.connect(s),s.connect(c),c.connect(l===`combustion`?this.combOut:this.out);let u={bpA:r,bpB:a,mixB:s,gain:c,busyUntil:-1,bus:l};this.voices[t]=u,this.pools[l].push(u)}this.setProfile(t)}get input(){return null}get output(){return this.out}get combustionOutput(){return this.combOut}setProfile(e){this.profile=e;let t=q(J(e&&e.cylinders,6),1,16);this.cyl=t,this.idleRpm=J(e&&e.idleRpm,800),this.sizeF=(6/t)**.35,this.sizeA=(t/6)**.3,this.burstCount=q(1+Math.round(t/5),1,3)}trigger(e,t,n,r,i){let a=pS[e]||pS.click,o=J(this.ctx.currentTime,0),s=Math.max(J(t,o),o+this.lookahead),c=q(J(n,0)*a.lvl,8e-4,4),l=q(J(r,1),.2,5),u=q(a.dec*q(J(i,1),.2,6),.004,1.5),d=s+a.atk+u+.002,f=a.bus===`combustion`?`combustion`:`mechanical`,p=this.pools[f],m=p.length,h=-1;for(let e=0;e<m;e++){let t=(this._cursor[f]+e)%m;if(p[t].busyUntil<=s){h=t;break}}if(h<0){let e=0;for(let t=1;t<m;t++)p[t].busyUntil<p[e].busyUntil&&(e=t);h=e,this.stolen++}this._cursor[f]=(h+1)%m;let g=p[h];g.bpA.frequency.cancelScheduledValues(s),g.bpA.frequency.setValueAtTime(Zx(a.fA*l,1e3),s),g.bpA.Q.setValueAtTime(J(a.qA,4),s),g.bpB.frequency.cancelScheduledValues(s),g.bpB.frequency.setValueAtTime(Zx(a.fB*l,3e3),s),g.bpB.Q.setValueAtTime(J(a.qB,6),s),g.mixB.gain.cancelScheduledValues(s),g.mixB.gain.setValueAtTime(J(a.mixB,.5),s);let _=g.gain.gain;return _.cancelScheduledValues(s),_.setValueAtTime(4e-4,s),_.linearRampToValueAtTime(c,s+a.atk),_.exponentialRampToValueAtTime(4e-4,s+a.atk+u),_.setValueAtTime(0,d),g.busyUntil=d,this.fired++,f===`combustion`&&this.pops.length<64&&this.pops.push({time:s,amp:q(J(n,0),0,1)}),h}update(e){let t=J(e.now,0),n=Math.max(0,J(e.rpm,0)),r=q(J(e.rpmNorm,0),0,1),i=this._rnd,a=this.maxPerFrame,o=q(J(e.evCut,0),0,1);if(o>0&&a>0){let e=Math.min(a,this.burstCount),n=t+this.lookahead+i()*.008;for(let t=0;t<e;t++){let e=.72**t*(.55+.65*i()),s=q(.55*o*this.sizeA*e*(.5+.7*r),.001,1),c=t===0||i()<.45?`bang`:`crackle`;this.trigger(c,n,s,this.sizeF*(.75+.6*i()),.7+.8*i()),n+=.012+i()*.048,a--}}let s=q(J(e.evPop,0),0,1);if(s>0&&a>0){let e=i(),n=.5*s+.5*r,o;o=e<.34-.16*n?`crack`:e<.8-.1*n?`double`:`stutter`;let c=q(Math.round((1+6/Math.max(3,this.cyl))*(.6+.7*i())),2,3),l=Math.min(a,o===`crack`?1:o===`double`?2:c),u=o===`crack`?2.6:o===`double`?2:1.6,d=.42+1.05*i()*i(),f=t+this.lookahead+i()*.006;for(let e=0;e<l;e++){let t=.86**e*(.6+.8*i()),n=q(u*d*s*this.sizeA*t*(.5+.65*r),.001,2),c=e===0||i()<.5?`bang`:`crackle`,l=this.sizeF*(.62+.7*i())*(1-.22*s);this.trigger(c,f,n,l,.7+.9*i());let p=o===`stutter`?.55:1;f+=(.055+i()*.16)*(.6+4/Math.max(3,this.cyl))*p,a--}}let c=q(J(e.evLash,0),0,1);if(c>0&&a>0){let e=t+this.lookahead;this.trigger(`clunk`,e,q(.5*c,.001,1),.9+.25*i(),.8+.5*c),a--,c>.35&&a>0&&(this.trigger(`clunk`,e+.018+i()*.012,q(.16*c,.001,1),1.3,.5),a--)}let l=q(J(e.evEngage,0),0,1);l>0&&a>0&&(this.trigger(`thump`,t+this.lookahead,q(.45*l,.001,1),1,.8+.6*l),a--);let u=e.shiftPhase||``;u===`sync`?(this._prevPhase!==`sync`&&(this._syncClicks=0,this._syncNext=t),this._syncClicks<1&&t>=J(this._syncNext,t)&&a>0&&(this.trigger(`click`,t+this.lookahead,.3+.22*i(),.85+.4*i(),1),this._syncClicks++,this._syncNext=t+.035+i()*.03,a--)):this._prevPhase===`sync`&&(this._syncClicks=0),this._prevPhase=u;let d=q(J(e.overrun,0),0,1),f=e.popIntensity==null?d*.55:q(J(e.popIntensity,0),0,1);if(!(this.overrunCrackle&&f>.3&&n>this.idleRpm*1.5&&!e.shifting)){this._nextPop=t;return}this._nextPop<t&&(this._nextPop=t+.01+i()*.04);let p=t+.12,m=.35+1.2*f*(.35+.65*r)*(this.cyl/6);for(;this._nextPop<p&&a>0;){let e=Math.max(this._nextPop,t+this.lookahead),n=q(.3*f*this.sizeA*(.25+1.5*i()*i())*(.45+.55*r),.001,1);this.trigger(i()<.4?`bang`:`crackle`,e,n,this.sizeF*(.7+.9*i()),.6+.9*i()),this._nextPop=e+(.25+2.2*i()*i())/Math.max(.4,m),a--}this._nextPop<t&&(this._nextPop=t)}start(e){rS(this._srcs,e)}dispose(){let e=J(this.ctx.currentTime,0);iS(this._srcs,e),aS(this._nodes),this._srcs.length=0,this.voices.length=0}},hS=(e,t,n)=>e<t?t:e>n?n:e,gS=(e,t=0)=>typeof e==`number`&&isFinite(e)?e:t,_S=.02;function vS(e,t,n,r=_S){if(!e)return;let i=gS(t,0);e.setTargetAtTime(i,Math.max(0,gS(n,0)),r>0?r:_S)}function yS(e,t,n){let r=Math.max(1,Math.floor(e.sampleRate*t)),i=e.createBuffer(1,r,e.sampleRate),a=i.getChannelData(0),o=0;for(let e=0;e<r;e++){let t=Math.random()*2-1;n?(o=(o+.02*t)/1.02,a[e]=o*3.5):a[e]=t}let s=Math.min(2048,r>>2);for(let e=0;e<s;e++){let t=e/s;a[e]=a[e]*t+a[r-s+e]*(1-t)}return i}var bS=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.cyl=t.cylinders,this.pulseOrder=Math.max(.5,this.cyl/2/Math.max(1,t.banks.length)),this.src=c(e.createBufferSource()),this.src.buffer=yS(e,2.7,!1),this.src.loop=!0,this.hp=e.createBiquadFilter(),this.hp.type=`highpass`,this.hp.frequency.value=55,this.body=e.createBiquadFilter(),this.body.type=`lowpass`,this.body.frequency.value=900,this.body.Q.value=.9,this.peak=e.createBiquadFilter(),this.peak.type=`peaking`,this.peak.frequency.value=140,this.peak.Q.value=1.4,this.peak.gain.value=7,this.level=e.createGain(),this.level.gain.value=0,this.pulse=c(e.createOscillator()),this.pulse.type=`sawtooth`,this.pulse.frequency.value=40,this.pulseDepth=e.createGain(),this.pulseDepth.gain.value=0,this.out=e.createGain(),this.out.gain.value=1,this.src.connect(this.hp),this.hp.connect(this.peak),this.peak.connect(this.body),this.body.connect(this.level),this.level.connect(this.out),this.pulse.connect(this.pulseDepth),this.pulseDepth.connect(this.level.gain),this.gain=hS(gS(n.gain,1),0,4),this.started=!1}get input(){return null}get output(){return this.out}start(e){if(!this.started){this.started=!0;try{this.src.start(e)}catch{}try{this.pulse.start(e)}catch{}}}stop(e){try{this.src.stop(e)}catch{}try{this.pulse.stop(e)}catch{}this.started=!1}update(e){let t=gS(e.now,0),n=hS(gS(e.rpmNorm,0),0,1),r=hS(gS(e.load,0),0,1),i=hS(gS(e.overrun,0),0,1),a=hS(hS(gS(e.f0,10),.05,4e3)*this.pulseOrder*2,10,6e3),o=.3+.7*r,s=this.gain*.28*o*(.25+.75*n)*(1+.35*i);vS(this.level.gain,s,t),vS(this.pulse.frequency,a,t),vS(this.pulseDepth.gain,Math.min(s*.85,s*(1.1-.7*n)),t),vS(this.peak.frequency,hS(a,30,2e3),t),vS(this.body.frequency,hS(450+2600*r+1800*n,120,9e3),t),vS(this.hp.frequency,hS(40+30*n,20,400),t)}dispose(){for(let e of[this.src,this.hp,this.peak,this.body,this.level,this.pulse,this.pulseDepth,this.out])e&&e.disconnect&&e.disconnect()}},xS=class{constructor(e,t,n={}){this.ctx=e,this.profile=t;let r=Math.max(.5,t.cylinders/4),i=(t.idleRpm+t.redlineRpm)/2/120;for(;r*i<38&&r<8;)r*=2;for(;r*i>85&&r>.5;)r/=2;this.order=r,this.subHz=r*i,this.osc=c(e.createOscillator()),this.osc.type=`sine`,this.osc.frequency.value=40,this.shaper=e.createWaveShaper(),this.shaper.curve=this._curve(),this.shaper.oversample=`2x`,this.tone=e.createBiquadFilter(),this.tone.type=`lowpass`,this.tone.frequency.value=220,this.tone.Q.value=.7,this.level=e.createGain(),this.level.gain.value=0,this.out=e.createGain(),this.out.gain.value=hS(gS(n.gain,1),0,4),this.osc.connect(this.shaper),this.shaper.connect(this.tone),this.tone.connect(this.level),this.level.connect(this.out),this.started=!1}_curve(e=2048){let t=new Float32Array(e);for(let n=0;n<e;n++){let r=n/(e-1)*2-1;t[n]=Math.tanh(1.8*r)*.92+.08*Math.tanh(2.6*r*r*Math.sign(r))}return t}get input(){return null}get output(){return this.out}start(e){if(!this.started){this.started=!0;try{this.osc.start(e)}catch{}}}stop(e){try{this.osc.stop(e)}catch{}this.started=!1}update(e){let t=gS(e.now,0),n=hS(gS(e.f0,10),.05,4e3),r=hS(gS(e.load,0),0,1),i=hS(gS(e.rpmNorm,0),0,1),a=hS(gS(e.overrun,0),0,1);vS(this.osc.frequency,hS(n*this.order,12,400),t);let o=.34*(.18+.82*r**.75)*(1-.45*i)*(1-.6*a);vS(this.level.gain,o,t),vS(this.tone.frequency,hS(150+260*r,80,800),t)}dispose(){for(let e of[this.osc,this.shaper,this.tone,this.level,this.out])e&&e.disconnect&&e.disconnect()}},SS=class{constructor(e,t,n={}){this.ctx=e,this.depthCents=hS(gS(n.detuneCents,7),0,60),this.depthGain=hS(gS(n.tremolo,.1),0,.6);let r=[.237,1.703,5.317];this.lfos=r.map(t=>{let n=c(e.createOscillator());n.type=`sine`,n.frequency.value=t;let i=e.createGain();return i.gain.value=1/r.length,n.connect(i),{osc:n,gain:i}}),this.rough=c(e.createBufferSource()),this.rough.buffer=yS(e,3.1,!0),this.rough.loop=!0,this.roughLP=e.createBiquadFilter(),this.roughLP.type=`lowpass`,this.roughLP.frequency.value=22,this.roughGain=e.createGain(),this.roughGain.gain.value=.9,this.rough.connect(this.roughLP),this.roughLP.connect(this.roughGain),this.bus=e.createGain(),this.bus.gain.value=1;for(let e of this.lfos)e.gain.connect(this.bus);this.roughGain.connect(this.bus),this.detune=e.createGain(),this.detune.gain.value=0,this.tremolo=e.createGain(),this.tremolo.gain.value=0,this.bus.connect(this.detune),this.bus.connect(this.tremolo),this.started=!1}get input(){return null}get output(){return this.bus}setEventSource(e){this._event=e}start(e){if(!this.started){this.started=!0;for(let t of this.lfos)try{t.osc.start(e)}catch{}try{this.rough.start(e)}catch{}}}stop(e){for(let t of this.lfos)try{t.osc.stop(e)}catch{}try{this.rough.stop(e)}catch{}this.started=!1}update(e){let t=gS(e.now,0),n=hS(gS(e.rpmNorm,0),0,1),r=hS(gS(e.load,0),0,1),i=(1-n)*(1-.55*r),a=hS(gS(e.rough,0),0,1),o=+!this._event;vS(this.detune.gain,o*this.depthCents*(.25+.75*i)*(1+2.5*a),t,.08),vS(this.tremolo.gain,(this._event?.2:1)*this.depthGain*(.2+.8*i)*(1+1.5*a),t,.08),vS(this.roughLP.frequency,hS(8+40*n,4,200),t,.1)}dispose(){for(let e of this.lfos)e.osc.disconnect(),e.gain.disconnect();for(let e of[this.rough,this.roughLP,this.roughGain,this.bus,this.detune,this.tremolo])e&&e.disconnect&&e.disconnect()}},CS=Object.freeze([{id:`strain`,label:`Strain`,default:0,note:`Engine working against something — a climb, a trailer, a heavy car. More rumble, harder combustion, more growl, at the same throttle.`},{id:`aggression`,label:`Exhaust valve`,default:0,note:`Active exhaust bypass. Opens the muffler: shallower chambers, brighter packing, more rasp and more level.`},{id:`roughness`,label:`Roughness`,default:0,note:`Engine health. Cycle-to-cycle variation and random misfires — a skipped combustion event in the pipe.`},{id:`distance`,label:`Distance`,default:0,note:`Listener distance. Air absorption takes the top off, level falls, and the room takes over.`},{id:`environment`,label:`Enclosure`,default:0,note:`Open road → tunnel. Hard parallel walls: dense fluttering reflections and a longer tail.`}]),wS=Object.freeze(Object.fromEntries(CS.map(e=>[e.id,e.default]))),TS=(e,t,n)=>e<t?t:e>n?n:e,ES=60/(2*Math.PI),DS={manual:{cutF:.3,openF:.3,syncF:.15,engageF:.35,cutMin:.03,openMin:.035,syncMin:.018,engageMin:.05,openClutch:0,engageStart:0,cutDepth:1,cutBang:.85,blip:.85,blipTolRpm:130,lashMax:.17,shuffle:.36,openStretch:2.6},dct:{cutF:.3,openF:.25,syncF:.15,engageF:.6,cutMin:.012,openMin:.01,syncMin:.008,engageMin:.028,openClutch:.1,engageStart:.4,cutDepth:1,cutBang:1,blip:1,blipTolRpm:60,lashMax:.09,shuffle:.26,openStretch:2},auto:{cutF:.2,openF:.25,syncF:.18,engageF:.9,cutMin:.02,openMin:.025,syncMin:.018,engageMin:.09,openClutch:0,engageStart:.12,cutDepth:.55,cutBang:.15,blip:.35,blipTolRpm:220,lashMax:.2,shuffle:.42,openStretch:1.6}},OS=class{constructor(e={}){this.type=e.type in DS?e.type:`manual`,this.k=DS[this.type],this.S=Math.max(.02,(e.shiftTimeMs||120)/1e3),this.gearCount=e.gearCount||6,this.idleRpm=e.idleRpm||800,this.redlineRpm=e.redlineRpm||7e3,this.revMatch=e.revMatch!==!1,this.autoShift=e.autoShift!==!1,this.upFracLow=.55,this.upFracHigh=.936,this.downFracLow=.28,this.downFracHigh=.44,this.kickdownThrottle=.85,this.minShiftInterval=.35,this.tCut=0,this.tOpen=0,this.tSync=0,this.tEngage=0,this.reset()}reset(){this.phase=``,this.t=0,this.from=0,this.to=0,this.isDown=!1,this.revTargetW=0,this.sinceShift=999,this.contactSeen=!1,this.blipHeld=!1}get shifting(){let e=this.phase;return e===`cut`||e===`open`||e===`sync`||e===`engage`}get busy(){return this.phase!==``}request(e,t,n=!1){if(t=Math.round(t),this.shifting||t<0||t>this.gearCount||t===e.gear||!n&&this.sinceShift<this.minShiftInterval||this.wouldOverRev(e,t))return!1;this.from=e.gear,this.to=t,this.isDown=t!==0&&(e.gear===0||t<e.gear),this.contactSeen=!1,this.blipHeld=!1;let r=this.k,i=this.S;this.tCut=Math.max(r.cutMin,r.cutF*i),this.tOpen=Math.max(r.openMin,r.openF*i),this.tSync=Math.max(r.syncMin,r.syncF*i),this.tEngage=Math.max(r.engageMin,r.engageF*i),this.revTargetW=this.isDown&&this.revMatch&&t>0?TS(e.gearedRpm(t),this.idleRpm,this.redlineRpm*.97)/ES:0,this.phase=`cut`,this.t=0;let a=TS(((typeof e.egt==`number`?e.egt:1)-.45)/.35,0,1),o=r.cutBang*(.25+.75*e.throttle)*r.cutDepth*a,s=TS((.12+.55*a)*r.cutBang,0,.9);return o>.04&&Math.random()<s&&e.fireEvent(`cut`,TS(o,0,1)),!0}wouldOverRev(e,t){return t<=0?!1:e.gearedRpm(t)>this.redlineRpm}upshiftRpm(e){let t=this.upFracLow+(this.upFracHigh-this.upFracLow)*TS(e,0,1);return Math.max(this.idleRpm*1.6,this.redlineRpm*t)}downshiftRpm(e){let t=this.downFracLow+(this.downFracHigh-this.downFracLow)*TS(e,0,1);return Math.max(this.idleRpm*1.15,this.redlineRpm*t)}auto(e){if(!this.autoShift||this.busy||e.gear===0||this.sinceShift<this.minShiftInterval)return;let t=e.throttle,n=e.rpm,r=this.upshiftRpm(t);if(n>=r&&e.gear<this.gearCount&&t>.05){this.request(e,e.gear+1);return}let i=typeof e.wotTorque==`function`?t=>e.wotTorque(t)*t:null;if(i&&t>=this.kickdownThrottle&&e.gear<this.gearCount&&n>this.redlineRpm*.6){let t=e.gearedRpm(e.gear+1);if(t>this.idleRpm*1.5&&i(t)>=i(n)){this.request(e,e.gear+1);return}}if(e.gear>1){let a=e.gear-1,o=e.gearedRpm(a);if(o>=r)return;if(n<=this.downshiftRpm(t)){this.request(e,a);return}t>=this.kickdownThrottle&&n<this.redlineRpm*.55&&o<this.redlineRpm*.92&&(!i||i(o)>i(n))&&this.request(e,a)}}step(e,t){if(t.gearboxNeutral=!1,t.syncing=!1,t.fuelCut=0,t.throttleOverride=null,t.clutchCmd=null,t.clutchRate=0,!this.busy&&(this.sinceShift+=e,this.auto(t),!this.busy)){t.shiftPhase=``,t.shifting=!1;return}this.t+=e;let n=this.k;switch(this.phase){case`cut`:t.fuelCut=n.cutDepth,t.clutchCmd=1,this.t>=this.tCut&&this._enter(`open`,t);break;case`open`:if(t.gearboxNeutral=!0,t.clutchCmd=n.openClutch,t.clutchRate=60,this.isDown&&this.revTargetW>0){let e=this.revTargetW-t.we,r=n.blipTolRpm/ES;e>r?this.blipHeld=!0:e<0&&(this.blipHeld=!1),t.throttleOverride=this.blipHeld?n.blip:0;let i=Math.abs(e)<=r;(this.t>=this.tOpen&&i||this.t>=this.tOpen*n.openStretch)&&this._enter(`sync`,t)}else t.fuelCut=n.cutDepth,n.cutDepth>=1&&(t.throttleOverride=0),this.t>=this.tOpen&&this._enter(`sync`,t);break;case`sync`:{t.gearboxNeutral=!0,t.clutchCmd=n.openClutch,t.fuelCut=n.cutDepth,n.cutDepth>=1&&(t.throttleOverride=0),this.to>0&&(t.syncing=!0,t.syncTargetW=t.inputShaftTargetW(this.to));let e=this.to===0||Math.abs(t.wg-t.syncTargetW)<3;(this.t>=this.tSync&&e||this.t>=this.tSync*3)&&this._enter(`engage`,t);break}case`engage`:{let e=TS(this.t/this.tEngage,0,1),r=e*e*(3-2*e);t.clutchCmd=n.engageStart+(1-n.engageStart)*r,t.clutchRate=4/this.tEngage,this.to===0&&(t.clutchCmd=0),t.lashContactedSince&&(this.contactSeen=!0),this.t>=this.tEngage&&this._enter(`lash`,t);break}case`lash`:t.clutchCmd=this.to===0?0:1,t.lashContactedSince&&(this.contactSeen=!0),(this.contactSeen||this.t>=n.lashMax||this.to===0)&&this._enter(`shuffle`,t);break;case`shuffle`:t.clutchCmd=this.to===0?0:null,this.t>=n.shuffle&&(this.phase=``,this.t=0,this.sinceShift=0,t.clutchCmd=null)}t.shiftPhase=this.phase,t.shifting=this.shifting}_enter(e,t){if(this.phase,this.phase=e,this.t=0,e===`sync`&&(t.selectGear(this.to),this.to>0&&(t.syncTargetW=t.inputShaftTargetW(this.to))),e===`engage`){t.gearboxNeutral=!1;let e=Math.abs(t.we-t.wg)*ES;t.fireEvent(`engage`,TS(.15+e/1800,0,1)),t.lashContactedSince=!1,this.contactSeen=!1}e===`lash`&&t.fireEvent(`shiftDone`,1)}},kS=60/(2*Math.PI),AS=2*Math.PI/60,jS=1.225,MS=9.81,Z=(e,t,n)=>e<t?t:e>n?n:e,NS=2e3,PS=240,FS=.03,IS=.02,LS=52,RS=.2,zS=15,BS=1.5,VS=.055,HS=.55,US=2.4,WS=.85,GS=.45,KS=class{constructor(e,t,n={}){this.engine=e,this.vehicle=t,this.dl=Object.assign({},ex,n.driveline),this.eff=n.driveEfficiency==null?.92:n.driveEfficiency,this.Je=Math.max(.02,e.engineInertia),this.Jin=n.inputInertia==null?FS:n.inputInertia,this.Jout=n.outputInertia==null?IS:n.outputInertia,this.r=t.wheelRadius,this.fd=t.finalDrive,this.ratios=t.gearRatios,this.gearCount=this.ratios.length,this.Jv=t.mass*this.r*this.r+LS*this.r*this.r,this.subStep=n.subStep||5e-4,this.launchFlareRpm=n.launchFlareRpm==null?2400:n.launchFlareRpm,this.launchRateOverride=n.launchRate==null?null:n.launchRate,this.launchRate=this.launchRateFor(1),this.shift=n.shiftController||new OS({type:t.gearbox,shiftTimeMs:t.shiftTimeMs,gearCount:this.gearCount,idleRpm:e.idleRpm,redlineRpm:e.redlineRpm,autoShift:n.autoShift!==!1,revMatch:n.revMatch!==!1}),this.isAuto=t.gearbox===`auto`,this.throttle=0,this.brake=0,this.we=e.idleRpm*AS,this.wg=this.we,this.wo=0,this.ww=0,this.twist=0,this.dtwist=0,this.lash=0,this.contact=0,this.clutch=0,this.boost=0,this.gear=1,this.Tp=0,this.Te=0,this.Tc=0,this.load=0,this.overrun=0,this.limiterCut=0,this.limiterActive=!1,this.lashTimer=0,this.lashContactedSince=!1,this.launchArmed=!0,this.launchI=0,this.launchT=0,this.launchRef=0,this.lockup=0,this.bovArm=0,this.boostDump=0,this.turboSpeed=0,this.egt=0,this.dfco=0,this.dfcoEdge=0,this.prevDfco=0,this.popCharge=0,this.prevOverride=0,this.thrPeak=0,this.cutRpmN=0,this.popRefractory=0,this.lashHeat=0,this.prevLimiter=!1,this.limiterBark=0,this.prevRpm=this.we*kS,this.gearboxNeutral=!1,this.syncing=!1,this.syncTargetW=0,this.clutchCmd=null,this.burnoutClutchOverride=null,this.clutchRate=0,this.fuelCut=0,this.throttleOverride=null,this.shiftPhase=``,this.shifting=!1,this.ev={cut:0,lash:0,engage:0,bov:0,shiftDone:0,pop:0},this.params={now:0,dt:0,rpm:0,f0:0,rpmNorm:0,dRpm:0,throttle:0,load:0,overrun:0,torqueSign:1,gear:1,gearRatio:0,speed:0,wheelRpm:0,clutchSlip:0,clutchEngaged:0,boost:0,shifting:!1,shiftPhase:``,evCut:0,evLash:0,evEngage:0,evBov:0,evShiftDone:0,evPop:0},this.clutch=0,this._writeParams(0,0)}setThrottle(e){this.throttle=Z(Number(e)||0,0,1)}setBrake(e){this.brake=Z(Number(e)||0,0,1)}setEngine(e){this.engine=e,this.Je=Math.max(.02,e.engineInertia),this.launchRate=this.launchRateFor(1),this.shift.idleRpm=e.idleRpm,this.shift.redlineRpm=e.redlineRpm;let t=Z(this.we*kS,e.idleRpm,e.redlineRpm);this.we=t*AS,this.prevRpm=t,this.boost=0,this.limiterCut=0,this.limiterActive=!1}setVehicle(e){let t=this.speed;this.vehicle=e,this.r=e.wheelRadius,this.fd=e.finalDrive,this.ratios=e.gearRatios,this.gearCount=this.ratios.length,this.Jv=e.mass*this.r*this.r+LS*this.r*this.r,this.isAuto=e.gearbox===`auto`,this.shift.type=e.gearbox,this.shift.gearCount=this.gearCount,this.shift.setTiming&&this.shift.setTiming(e.shiftTimeMs),this.shift.reset(),this.launchRate=this.launchRateFor(1),this.gear=Z(Math.round(this.gear),0,this.gearCount),this.ww=t/this.r,this.wo=this.ww*this.fd,this.twist=0,this.dtwist=0,this.contact=0}setAutoShift(e){this.shift.autoShift=!!e}shiftUp(){return this.gear>=this.gearCount?!1:this.shift.request(this,this.gear+1,!0)}shiftDown(){return this.gear<=1?!1:this.shift.request(this,this.gear-1,!0)}setGear(e){return this.shift.request(this,e,!0)}get rpm(){return this.we*kS}get speed(){return this.ww*this.r}get gearRatio(){return this.gear>0?this.ratios[this.gear-1]:0}get totalRatio(){return this.gear>0?this.ratios[this.gear-1]*this.fd:0}gearedRpm(e){return e<=0||e>this.gearCount?0:Math.abs(this.ww)*this.fd*this.ratios[e-1]*kS}launchRateFor(e){if(this.launchRateOverride!=null)return this.launchRateOverride;let t=Z(Math.round(e),1,this.gearCount)-1,n=Math.abs(this.ratios[t]*this.fd)||1;return Z(this.engine.peakTorque*n*this.eff/this.r/Math.max(1,this.vehicle.mass)/this.r*n*kS*.55,400,12e3)}inputShaftTargetW(e){return e<=0||e>this.gearCount?0:this.ww*this.fd*this.ratios[e-1]}selectGear(e){this.gear=Z(Math.round(e),0,this.gearCount)}fireEvent(e,t){t>this.ev[e]&&(e===`pop`&&this.we*kS<NS||(this.ev[e]=t>1?1:t))}_JoutSide(e,t=!0){if(e<=0)return this.Jout;let n=this.ratios[e-1];return(t?this.Je+this.Jin:this.Jin)*n*n+this.Jout}_JvehOut(){return this.Jv/(this.fd*this.fd)}modeW(e,t=!0){let n=this._JoutSide(e,t),r=this._JvehOut();return Math.sqrt(this.dl.stiffness*(1/n+1/r))}modeHz(e,t=!0){return this.modeW(e,t)/(2*Math.PI)}modeZeta(e,t=!0){if(this.dl.dampingRatio!=null)return this.dl.dampingRatio;let n=this._Jred(e,t);return this.dl.damping/(2*Math.sqrt(this.dl.stiffness*n))}_Jred(e,t=!0){let n=this._JoutSide(e,t),r=this._JvehOut();return 1/(1/n+1/r)}_dampCoeff(){if(this.dl.dampingRatio==null)return this.dl.damping;let e=this.clutch>.5&&!this.gearboxNeutral,t=this._Jred(this.gear>0?this.gear:1,e);return Z(2*this.dl.dampingRatio*Math.sqrt(this.dl.stiffness*Math.max(1e-4,t)),1,400)}stabilityReport(){let e=0,t=``;for(let n=1;n<=this.gearCount;n++)for(let r of[!0,!1]){let i=this.modeW(n,r);i>e&&(e=i,t=`gear ${n} clutch ${r?`locked`:`open`}`)}let n=Math.sqrt(this.dl.stiffness/this.Jout);n>e&&(e=n,t=`gearbox neutral (output shaft alone)`);let r=this.dl.damping/this.Jout;return{subStep:this.subStep,worstModeRadS:e,worstModeHz:e/(2*Math.PI),worstModeWhere:t,stableBelowSpring:2/e,stableBelowDamper:2/r,phasePerStepRad:e*this.subStep,marginSpring:2/e/this.subStep,marginDamper:2/r/this.subStep}}getState(){return{rpm:this.rpm,speed:this.speed,speedKmh:this.speed*3.6,gear:this.gear,throttle:this.throttle,brake:this.brake,twist:this.twist,contact:this.contact,clutch:this.clutch,Tp:this.Tp,boost:this.boost,phase:this.shiftPhase,shifting:this.shifting,limiter:this.limiterActive,gearCount:this.gearCount,redline:this.engine.redlineRpm,idle:this.engine.idleRpm}}torqueFactor(e){let t=(e-this.engine.peakTorqueRpm)/(this.engine.redlineRpm*.75);return Z(1-.85*t*t,.3,1)}wotTorque(e){return this.engine.peakTorque*this.torqueFactor(e)*this._boostMult()-this.frictionTorque(e,1)}frictionTorque(e,t){return(18+.012*e+22e-7*e*e)*(1-.62*t)}step(e,t=0){let n=Number(e)||0;if(n<=0)return this.params.now=t,this.params.dt=0,this.params.evCut=this.params.evLash=this.params.evEngage=0,this.params.evBov=this.params.evShiftDone=0,this.params;n=Math.min(n,.1);let r=Math.min(PS,Math.max(1,Math.ceil(n/this.subStep))),i=n/r;for(let e=0;e<r;e++)this._substep(i);return this._writeParams(n,t),this.params}_substep(e){let t=this.engine;this.vehicle;let n=this.dl;this.lashContactedSince=!1,this.shift.step(e,this);let r=this.gear>0&&!this.gearboxNeutral,i=this.gear>0?this.ratios[this.gear-1]:0;this.limiterCut>0?(this.limiterCut-=e,this.limiterCut<=0&&this.rpm>t.redlineRpm-200&&(this.limiterCut=.012)):this.rpm>=t.redlineRpm&&(this.limiterCut=.05),this.limiterActive=this.limiterCut>0;let a=this.throttleOverride==null?this.throttle:this.throttleOverride;a*=1-Z(this.fuelCut,0,1),this.limiterActive&&(a=0),this.thrEff=a,this._stepTurbo(e,a),this._stepExhaustThermal(e,a);let o=this.we*kS,s=a*t.peakTorque*this.torqueFactor(o)*this._boostMult()-this.frictionTorque(o,a);if(this.throttle<.06&&o<t.idleRpm*1.25&&!this.limiterActive){let e=this.frictionTorque(t.idleRpm,0)+(t.idleRpm-o)*.55;e>s&&(s=e)}this.Te=s;let c=n.backlash,l=this._dampCoeff(),u=0;this.twist>c?(u=n.stiffness*(this.twist-c)+l*this.dtwist,u<0&&(u=0)):this.twist<-c&&(u=n.stiffness*(this.twist+c)+l*this.dtwist,u>0&&(u=0)),this.Tp=u,this._stepClutch(e,r,i);let d=0,f=0;if(this.isAuto){let e=this._converter(this.we,this.wg);d=e.pump,f=e.turbine}let p=r?this.Jin+this.Jout/(i*i):this.Jin,m=-this._gearboxDrag(this.wg);if(r&&(m-=u/i),this.syncing){let e=this.syncTargetW-this.wg;m+=Z(e*this.Jin/.008,-400,400)}m+=f;let h=s-d,g=m,_=this.Je*p/(this.Je+p),v=n.clutchTorqueCapacity*this.clutch*this._stallGuard(),y=_*((this.we-this.wg)/e+h/this.Je-g/p);y>v?y=v:y<-v&&(y=-v),this.Tc=y,this.we+=e*(h-y)/this.Je,this.wg+=e*(g+y)/p;let b=t.idleRpm*.42*AS,x=t.redlineRpm*1.015*AS;this.we<b&&(this.we=b),this.we>x&&(this.we=x),r?this.wo=this.wg/i:this.wo+=e*(-u-this._gearboxDrag(this.wo)*.5)/this.Jout,this._stepVehicle(e,u),this.dtwist=this.wo-this.ww*this.fd,this.twist+=e*this.dtwist,Math.abs(this.twist)<3||(this.twist=Z(this.twist||0,-3,3)),this.lash=Z(this.twist,-c,c),this._detectLash(e,c)}_gearboxDrag(e){return .006*e+(e>.5?.4:e<-.5?-.4:0)}_stallGuard(){let e=this.engine.idleRpm*AS;return Z((this.we-e*.92)/(e*.55),0,1)}_stepClutch(e,t,n){let r=this.burnoutClutchOverride??this.clutchCmd,i=this.burnoutClutchOverride==null?this.clutchRate:18;r??(this.isAuto?(r=t&&this.gear>=2&&this.gearedRpm(this.gear)>this.engine.idleRpm*1.35&&this.throttle<.85?1:0,i=2.5):r=this._launchClutch(e,t)),i>0||(i=this.dl.clutchStiffness*12),this.clutch+=(Z(r,0,1)-this.clutch)*Math.min(1,e*i),this.clutch=Z(this.clutch,0,1)}_launchClutch(e,t){let n=this.engine.idleRpm,r=this.gearedRpm(this.gear);if(!t||this.gear===0)return this.launchI=0,this.launchT=0,this.launchRef=0,this.launchArmed=!0,0;let i=Z(n*1.05+this.throttle*this.launchFlareRpm,n,this.engine.redlineRpm*.9);if(this.launchArmed&&this.clutch>.985&&r>i*.75?this.launchArmed=!1:!this.launchArmed&&r<n*.95&&(this.launchArmed=!0),!this.launchArmed)return this.launchI=0,this.launchT=0,this.launchRef=0,1;if(this.throttle<.05&&r<n*.5)return this.launchT=0,this.launchRef=0,this.launchI=Math.max(0,this.launchI-e/.2),Z(this.launchI,0,.22);this.launchT=Math.min(4,(this.launchT||0)+e);let a=this.launchRateFor(this.gear),o=Math.max(300,i-n),s=r+o*(1-Z(r/Math.max(1,o*1.8),0,1));this.launchRef>0||(this.launchRef=Math.max(n*1.05,this.rpm));let c=s-this.launchRef,l=c>0?Math.min(a,c/GS):c/GS;this.launchRef+=l*e;let u=Math.max(s,n*1.05);this.launchRef=Math.min(this.launchRef,u,this.rpm+o*.5),this.launchRef=Math.max(this.launchRef,n*1.05),this.rpm>this.launchRef&&(this.launchRef=Math.min(this.rpm,u));let d=this.launchRef,f=this.dl.clutchTorqueCapacity*this._stallGuard(),p=this.Te-this.Je*l*AS,m=f>1?Z(p/f,0,1):0,h=(this.rpm-d)/d;this.launchI=Z(this.launchI*(1-Math.min(1,e/.6))+8*h*e,-.4,.5);let g=Z(m+this.launchI+1.5*h,0,1),_=Z((this.launchT-.9)/1.2,0,1);return Math.max(g,Math.min(_,m))}_converter(e,t){if(e>t+.5){let n=Z(t/Math.max(e,.001),0,1),r=Z(.008*e*e*(1-n*n),0,4*this.engine.peakTorque);return{pump:r,turbine:r*(1+1*(1-n)**1.2)}}if(t>e+.5){let n=Z(e/Math.max(t,.001),0,1),r=Z(.0048*t*t*(1-n*n),0,4*this.engine.peakTorque);return{pump:-r,turbine:-r}}return{pump:0,turbine:0}}_stepVehicle(e,t){let n=this.vehicle,r=this.ww*this.r,i=t>0?t*this.fd*this.eff:t*this.fd,a=.5*jS*n.dragArea*r*r,o=r>0?a*this.r:0,s=(n.rollingResistance*n.mass*MS+this.brake*n.brakeForce)*this.r,c=i-o;if(this.ww>1e-6){let t=this.ww+e*(c-s)/this.Jv;this.ww=t<0&&c<s?0:Math.max(0,t)}else this.ww=c>s?e*(c-s)/this.Jv:0}_detectLash(e,t){this.lashTimer+=e,this.lashHeat=Math.max(0,this.lashHeat-e/HS);let n=this.twist>t?1:this.twist<-t?-1:0;if(n===0){Math.abs(this.twist)<t*WS&&(this.contact=0);return}if(n===this.contact)return;let r=Math.abs(this.dtwist);if(this.contact=n,r<RS||this.lashTimer<VS)return;this.lashTimer=0,this.lashContactedSince=!0;let i=1/(1+US*this.lashHeat);this.lashHeat=Math.min(3,this.lashHeat+1);let a=Z((r/zS)**+BS*i,.001,1);a<.05||this.fireEvent(`lash`,a)}_stepExhaustThermal(e,t){let n=this.we*kS,r=Z((n-this.engine.idleRpm)/Math.max(1,this.engine.redlineRpm-this.engine.idleRpm),0,1),i=Z(.12+.88*t**.6*(.35+.65*r),0,1),a=i>this.egt?5:26;this.egt+=(i-this.egt)*Math.min(1,e/a);let o=this.throttle,s=o<.06&&n>this.engine.idleRpm*1.5&&!this.gearboxNeutral;if(this.dfco=+!!s,this.thrPeak=Math.max(o,this.thrPeak-e/.7),this.popRefractory=Math.max(0,this.popRefractory-e),this.limiterBark=Math.max(0,this.limiterBark-e),this.limiterActive&&!this.prevLimiter&&this.egt>.5&&this.limiterBark<=0&&(this.limiterBark=.34,this.fireEvent(`pop`,Z(.16+.14*Math.random(),0,1))),this.prevLimiter=this.limiterActive,this.dfco!==this.prevDfco){if(this.dfcoEdge=1,this.dfco){let e=Z(this.thrPeak,0,1),t=r**1.7;this.cutRpmN=r;let n=.55+Math.random()*.95;this.popCharge=Z(this.popCharge+(.5+2.1*t)*(.4+.6*e)*n,0,3.4);let i=Z((this.egt-.42)/.34,0,1)*(.18+.82*t)*(.45+.55*e);this.egt>.42&&this.popRefractory<=0&&Math.random()<i&&(this.popRefractory=.45,this.fireEvent(`pop`,Z((this.egt-.35)*1.25*(.1+1.3*t)*(.35+.65*e)*n,0,1)))}else this.popCharge=Z(this.popCharge+.35,0,3.4)}this.prevDfco=this.dfco,this.dfcoEdge=Math.max(0,this.dfcoEdge-e/.85);let c=this.throttleOverride;if(this.prevOverride>.3&&!(c>.3)){this.popCharge=Z(this.popCharge+1.1+.5*r,0,2.6);let e=Z((this.egt-.32)/.3,0,1)*(.35+.65*r);this.egt>.32&&this.popRefractory<=0&&Math.random()<e&&(this.popRefractory=.45,this.fireEvent(`pop`,Z((this.egt-.25)*1.45*(.5+.5*r),0,1)))}this.prevOverride=c??0,this.popCharge=Math.max(0,this.popCharge-e*(.22+.55*(1-this.dfco)))}_stepTurbo(e,t){let n=this.engine.turbo;if(!n){this.boost=0;return}let r=this.we*kS,i=Math.min(Z(Number(n.boostRpm)||3500,800,9e3),.65*this.engine.redlineRpm),a=Math.max(.6*this.engine.redlineRpm,i+1500),o=Z((r-i)/(a-i),0,1),s=n.antiLag>=.5&&t<.12&&r>.3*this.engine.redlineRpm,c=s?.7*o:Z(t,0,1)*o;s&&(this._alsT=(this._alsT||0)-e,this._alsT<=0&&(this._alsT=.06+.16*Math.random(),this.fireEvent(`pop`,.35+.45*Math.random())));let l=this.boostDump>0?.05:c>this.boost?.25+n.inertia*.9:.18+n.inertia*.4;this.boost+=(c-this.boost)*Math.min(1,e/l),this.boost=Z(this.boost,0,1),this.boostDump>0&&(this.boostDump-=e);let u=r>900?.12+.2*o:0,d=Z(Math.max(u,c),0,1),f=d>this.turboSpeed?.22+n.inertia*.85:.42+n.inertia*.55;this.turboSpeed+=(d-this.turboSpeed)*Math.min(1,e/f),this.turboSpeed=Z(this.turboSpeed,0,1),t>.45?this.bovArm=1:this.bovArm>0&&t<.12&&this.boost>.18&&!this.limiterActive&&n.valve>=.5&&!s&&(this.bovArm=0,this.boostDump=.12,this.fireEvent(`bov`,Z(this.boost*(.4+.6*n.bov),.1,1)))}_boostMult(){let e=this.engine.turbo;return e?1+.55*this.boost*e.maxBoost:1}_writeParams(e,t){let n=this.params,r=this.engine,i=this.we*kS;n.now=t,n.dt=e,n.rpm=i,n.f0=i/120,n.rpmNorm=Z((i-r.idleRpm)/(r.redlineRpm-r.idleRpm),0,1),n.dRpm=e>0?(i-this.prevRpm)/e:0,this.prevRpm=i,n.throttle=this.throttle,n.limiter=(this.limiterActive||i>r.redlineRpm-120)&&this.throttle>.5?1:0;let a=Z(this.thrEff||0,0,1),o=e>0?Z(e*12,0,1):1;this.load+=(a-this.load)*o,n.load=Z(this.load,0,1);let s=+(this.thrEff<.05&&i>r.idleRpm*1.7&&this.gear>0&&this.Tp<-2);this.overrun+=(s-this.overrun)*(e>0?Z(e*8,0,1):1),n.overrun=Z(this.overrun,0,1),n.torqueSign=this.Tp>1?1:this.Tp<-1?-1:this.Te>=0?1:-1,n.gear=this.gear,n.gearRatio=this.totalRatio,n.speed=this.ww*this.r,n.wheelRpm=this.ww*this.fd*kS,n.clutchSlip=(this.we-this.wg)*kS,n.clutchEngaged=this.clutch,n.boost=this.boost,n.shifting=this.shifting,n.gearbox=this.vehicle.gearbox,n.shiftPhase=this.shiftPhase;let c=this.ev;return n.evCut=c.cut,n.evLash=c.lash,n.evEngage=c.engage,n.evBov=c.bov,n.evShiftDone=c.shiftDone,n.evPop=c.pop,c.cut=c.lash=c.engage=c.bov=c.shiftDone=c.pop=0,n.turboSpeed=this.turboSpeed,n.egt=this.egt,n.dfco=this.dfco,n.cutRpmN=this.cutRpmN,n.popIntensity=Z(Math.max(0,this.egt-.45)/.55*Z(this.popCharge,0,1)*(.12+.88*this.dfcoEdge)*(.45+.55*this.cutRpmN),0,1)*+(i>=NS),n}},qS=1.225,JS=9.81,YS=60/(2*Math.PI),XS=.8,ZS=(e,t,n)=>e<t?t:e>n?n:e;function QS(e,t,n=1){let r=(t-e.peakTorqueRpm)/(e.redlineRpm*.75),i=ZS(1-.85*r*r,.3,1),a=e.turbo,o=a?1+.55*n*a.maxBoost:1,s=(18+.012*t+22e-7*t*t)*.38;return e.peakTorque*i*o-s}function $S(e){let t={rpm:e.redlineRpm,power:0,torque:0};for(let n=e.idleRpm;n<=e.redlineRpm;n+=25){let r=QS(e,n),i=r*n/YS;i>t.power&&(t.power=i,t.rpm=n),r>t.torque&&(t.torque=r)}return t}function eC(e){return[2.6+.4*(e-4),3.8+.8*(e-4)]}function tC(e,t,n={}){let r=Math.round(ZS(n.gears||e.gears||t.gearRatios&&t.gearRatios.length||6,3,10)),i=t.gravity||JS,a=n.efficiency||.92,o=t.wheelRadius,s=t.finalDrive,c=t.mass,l=e=>.5*qS*t.dragArea*e*e+t.rollingResistance*c*i,u=$S(e),d=Math.min(u.rpm*1.04,e.redlineRpm*.9),f=a*QS(e,d)*d/YS,p=0,m=200;for(let e=0;e<60;e++){let e=.5*(p+m);l(e)*e<f?p=e:m=e}let h=p,g=d/YS*o/Math.max(h,1),_=.6*c*i*o/(Math.max(1,u.torque)*a),[v,y]=eC(r),b=ZS(_/g,v,y),x=[];for(let e=1;e<=r;e++){let t=((r-e)/(r-1))**1.15;x.push(+(XS*g*b**+t/s).toFixed(3))}return{gearRatios:x,gearTeeth:x.map(e=>Math.round(ZS(16+6.5*e,17,46))),topSpeed:h}}function nC(e,t,n){let r=tC(e,t,n);return{...t,gearRatios:r.gearRatios,gearTeeth:r.gearTeeth}}var rC=(e,t,n)=>e<t?t:e>n?n:e,iC=(e,t=0)=>typeof e==`number`&&isFinite(e)?e:t,aC=class e{static BANDS=[{f:60,type:`lowshelf`,label:`sub`},{f:200,type:`peaking`,q:.9,label:`body`},{f:800,type:`peaking`,q:1,label:`honk`},{f:2500,type:`peaking`,q:.9,label:`rasp`},{f:8e3,type:`highshelf`,label:`air`}];constructor(t,n={}){this.ctx=t,this.inGain=t.createGain(),this.out=t.createGain(),this.bands=e.BANDS.map(e=>{let n=t.createBiquadFilter();return n.type=e.type,n.frequency.value=e.f,e.q&&(n.Q.value=e.q),n.gain.value=0,n});let r=this.inGain;for(let e of this.bands)r.connect(e),r=e;r.connect(this.out),n.gains&&this.setGains(n.gains)}get input(){return this.inGain}get output(){return this.out}setGains(e){let t=this.ctx.currentTime;for(let n=0;n<this.bands.length&&n<e.length;n++)this.bands[n].gain.setTargetAtTime(rC(iC(e[n],0),-18,18),t,.03)}setBand(e,t){e<0||e>=this.bands.length||this.bands[e].gain.setTargetAtTime(rC(iC(t,0),-18,18),this.ctx.currentTime,.03)}getGains(){return this.bands.map(e=>e.gain.value)}reset(){this.setGains(this.bands.map(()=>0))}update(){}dispose(){for(let e of[this.inGain,this.out,...this.bands])e.disconnect()}},oC=class{constructor(e,t={}){this.ctx=e,this.inGain=e.createGain(),this.out=e.createGain(),this.dry=e.createGain(),this.wet=e.createGain(),this.conv=e.createConvolver(),this.conv.normalize=!0,this.damp=e.createBiquadFilter(),this.damp.type=`lowpass`,this.damp.frequency.value=4200,this.damp.Q.value=.7,this.hp=e.createBiquadFilter(),this.hp.type=`highpass`,this.hp.frequency.value=110,this.inGain.connect(this.dry),this.dry.connect(this.out),this.inGain.connect(this.hp),this.hp.connect(this.conv),this.conv.connect(this.damp),this.damp.connect(this.wet),this.wet.connect(this.out),this._size=rC(iC(t.size,.35),.05,1),this._mix=rC(iC(t.mix,.16),0,1),this.setSize(this._size),this.setMix(this._mix)}get input(){return this.inGain}get output(){return this.out}_buildIR(e){let t=this.ctx,n=.15+2.05*rC(e,0,1),r=Math.max(64,Math.floor(t.sampleRate*n)),i=t.createBuffer(2,r,t.sampleRate),a=2.6+3.4*(1-e);for(let e=0;e<2;e++){let n=i.getChannelData(e);for(let e=0;e<r;e++){let t=e/r;n[e]=(Math.random()*2-1)*(1-t)**a}for(let e=0;e<7;e++){let i=Math.floor((.004+.055*Math.random())*t.sampleRate);i<r&&(n[i]+=(Math.random()*2-1)*.55*(1-e/7))}}return i}setSize(e){return this._size=rC(iC(e,.35),.05,1),this.conv.buffer=this._buildIR(this._size),this._size}setMix(e){return this._mix=rC(iC(e,0),0,1),this._writeMix(.03),this._mix}setExtra(e){let t=rC(iC(e,0),0,1);Math.abs(t-(this._extra||0))<.001||(this._extra=t,this._writeMix(.08))}_writeMix(e){let t=rC(this._mix+(this._extra||0)*(1-this._mix),0,1),n=this.ctx.currentTime;this.dry.gain.setTargetAtTime(Math.cos(t*Math.PI/2),n,e),this.wet.gain.setTargetAtTime(Math.sin(t*Math.PI/2)*1.4,n,e)}setDamping(e){this.damp.frequency.setTargetAtTime(rC(iC(e,4200),400,18e3),this.ctx.currentTime,.05)}getState(){return{size:this._size,mix:this._mix,damping:this.damp.frequency.value}}update(){}dispose(){for(let e of[this.inGain,this.out,this.dry,this.wet,this.conv,this.damp,this.hp])e.disconnect()}},sC=class{constructor(e,t={}){this.ctx=e,this.inGain=e.createGain(),this.merger=e.createChannelMerger(2),this.out=e.createGain(),this.delay=e.createDelay(.08),this.delay.delayTime.value=.016,this.tilt=e.createBiquadFilter(),this.tilt.type=`highshelf`,this.tilt.frequency.value=1800,this.tilt.gain.value=-3,this.plus=e.createGain(),this.minus=e.createGain(),this.plus.gain.value=0,this.minus.gain.value=0,this.inGain.connect(this.merger,0,0),this.inGain.connect(this.merger,0,1),this.inGain.connect(this.delay),this.delay.connect(this.tilt),this.tilt.connect(this.plus),this.tilt.connect(this.minus),this.plus.connect(this.merger,0,0),this.minus.connect(this.merger,0,1),this.merger.connect(this.out),this.setWidth(iC(t.width,.35))}get input(){return this.inGain}get output(){return this.out}setWidth(e){this._width=rC(iC(e,0),0,1);let t=this.ctx.currentTime,n=this._width*.85;return this.plus.gain.setTargetAtTime(n,t,.03),this.minus.gain.setTargetAtTime(-n,t,.03),this.delay.delayTime.setTargetAtTime(.008+.018*this._width,t,.05),this._width}getWidth(){return this._width}update(){}dispose(){for(let e of[this.inGain,this.merger,this.out,this.delay,this.tilt,this.plus,this.minus])e.disconnect()}},cC=class e{static BANDS=[{name:`low`,f:220,threshold:-16,ratio:2.6,attack:.018,release:.26,knee:10,makeup:1.1},{name:`mid`,f:2e3,threshold:-18,ratio:2,attack:.022,release:.2,knee:14,makeup:2.12},{name:`high`,f:0,threshold:-24,ratio:3,attack:.003,release:.12,knee:8,makeup:.9}];constructor(t,n={}){this.ctx=t,this._amount=rC(iC(n.amount,1),0,1),this.inGain=t.createGain(),this.out=t.createGain(),this.out.gain.value=rC(iC(n.makeup,1),0,4);let r=(e,n)=>{let r=t.createBiquadFilter();return r.type=e,r.frequency.value=rC(n,20,2e4),r.Q.value=-3.0103,r};this.bands=[];let[i,a]=e.BANDS;for(let n of e.BANDS){let e=t.createDynamicsCompressor();e.threshold.value=n.threshold,e.ratio.value=n.ratio,e.attack.value=n.attack,e.release.value=n.release,e.knee.value=n.knee;let o=t.createGain();o.gain.value=n.makeup;let s=[];n.name===`low`?s.push(r(`lowpass`,i.f),r(`lowpass`,i.f)):n.name===`mid`?s.push(r(`highpass`,i.f),r(`highpass`,i.f),r(`lowpass`,a.f),r(`lowpass`,a.f)):s.push(r(`highpass`,a.f),r(`highpass`,a.f));let c=this.inGain;for(let e of s)c.connect(e),c=e;c.connect(e),e.connect(o),o.connect(this.out),this.bands.push({spec:n,comp:e,makeup:o,chain:s})}this.setAmount(this._amount)}get input(){return this.inGain}get output(){return this.out}setAmount(e){this._amount=rC(iC(e,1),0,1);let t=iC(this.ctx.currentTime,0);for(let e of this.bands){let n=rC(e.spec.threshold*this._amount,-100,0);e.comp.threshold.setTargetAtTime(n,t,.05);let r=1+(e.spec.makeup-1)*this._amount,i=lC(n,e.spec.ratio,e.spec.knee);e.makeup.gain.setTargetAtTime(r*10**(-i/20),t,.05)}return this._amount}getAmount(){return this._amount}getReduction(){let e={};for(let t of this.bands)e[t.spec.name]=iC(t.comp.reduction,0);return e}update(){}dispose(){for(let e of this.bands){for(let t of e.chain)t.disconnect();e.comp.disconnect(),e.makeup.disconnect()}this.inGain.disconnect(),this.out.disconnect()}};function lC(e,t,n=0){let r=Math.min(0,iC(e,0))+Math.max(0,iC(n,0))/2,i=Math.max(1,iC(t,1));return Math.max(0,-.6*Math.min(0,r)*(1-1/i))}var uC=class{constructor(e){this.ctx=e,this.pre=e.createGain(),this.pre.gain.value=1/4,this.shaper=e.createWaveShaper();let t=8193,n=new Float32Array(t),r=.6,i=.39;for(let e=0;e<t;e++){let t=4*(e/8192*2-1),a=Math.abs(t),o=a<=r?a:r+i*Math.tanh((a-r)/i);n[e]=Math.sign(t)*o}this.shaper.curve=n,this.shaper.oversample=`2x`,this.pre.connect(this.shaper)}get input(){return this.pre}get output(){return this.shaper}dispose(){this.pre.disconnect(),this.shaper.disconnect()}},dC=class{constructor(e,t={}){this.ctx=e;let n=-3.0103,r=(t,n,r)=>{let i=e.createBiquadFilter();return i.type=t,i.frequency.value=n,i.Q.value=r,i};this.inGain=e.createGain(),this.lp1=r(`lowpass`,140,n),this.lp2=r(`lowpass`,140,n),this.drive=e.createGain(),this.drive.gain.value=2.2,this.span=e.createGain(),this.span.gain.value=1/4,this.shaper=e.createWaveShaper();let i=4097,a=new Float32Array(i);for(let e=0;e<i;e++){let t=4*(e/4096*2-1),n=Math.tanh(t);a[e]=n+.45*n*n}this.shaper.curve=a,this.shaper.oversample=`2x`,this.hp=r(`highpass`,90,.7),this.lp3=r(`lowpass`,420,.6),this.amount=e.createGain(),this.amount.gain.value=rC(iC(t.amount,.15),0,2),this.inGain.connect(this.lp1),this.lp1.connect(this.lp2),this.lp2.connect(this.drive),this.drive.connect(this.span),this.span.connect(this.shaper),this.shaper.connect(this.hp),this.hp.connect(this.lp3),this.lp3.connect(this.amount)}get input(){return this.inGain}get output(){return this.amount}setAmount(e){this.amount.gain.setTargetAtTime(rC(iC(e,0),0,2),this.ctx.currentTime,.05)}dispose(){for(let e of[this.inGain,this.lp1,this.lp2,this.drive,this.span,this.shaper,this.hp,this.lp3,this.amount])e.disconnect()}},fC=class{constructor(e){this.ctx=e,this.inGain=e.createGain(),this.out=e.createGain(),this.inGain.connect(this.out),this.loops=[.037,.061].map((t,n)=>{let r=e.createGain(),i=e.createDelay(.2);i.delayTime.value=t;let a=e.createBiquadFilter();a.type=`lowpass`,a.frequency.value=n?1900:2600,a.Q.value=.5;let o=e.createBiquadFilter();o.type=`highpass`,o.frequency.value=70,o.Q.value=.5;let s=e.createGain();s.gain.value=0;let c=e.createGain();return c.gain.value=0,this.inGain.connect(r),r.connect(i),i.connect(a),a.connect(o),o.connect(s),s.connect(r),o.connect(c),c.connect(this.out),{sum:r,d:i,lp:a,hp:o,fb:s,wet:c}}),this._env=-1}get input(){return this.inGain}get output(){return this.out}setEnvironment(e){if(e=rC(iC(e,0),0,1),Math.abs(e-this._env)<.001)return;this._env=e;let t=this.ctx.currentTime;this.loops.forEach((n,r)=>{n.fb.gain.setTargetAtTime(.52*e,t,.08),n.wet.gain.setTargetAtTime((r?.3:.38)*e,t,.08)})}dispose(){this.inGain.disconnect(),this.out.disconnect();for(let e of this.loops)for(let t of Object.values(e))t.disconnect()}},pC=`/**
1010
1010
  * combustion-worklet.js — the engine's source, one combustion event at a time.
1011
1011
  *
1012
1012
  * Runs on the audio thread (AudioWorkletProcessor 'engine-combustion').