@joy-ride/joy-ride 0.2.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/npm/bookmarklet.js +1 -1
- package/npm/embed-chunks/{Documentation-DRBCOvgw.js → Documentation-DOrYgUbT.js} +1 -1
- package/npm/embed-chunks/{bookmarklet-DlL5EMxG.js → bookmarklet-BcOPb3dX.js} +3 -3
- package/npm/embed-chunks/src-Bh6tVMxI.js +53 -0
- package/npm/embed.js +1 -1
- package/npm/index.d.ts +4 -0
- package/npm/index.js +1 -1
- package/package.json +11 -9
- package/npm/embed-chunks/src-BH3xIhRK.js +0 -53
|
@@ -45,7 +45,7 @@ vec3 scatterVehicleLight(vec3 baseColor, float density, vec2 canvasPoint, bool d
|
|
|
45
45
|
float scattering = 1.0 - exp(-illumination * transmission * 1.28);
|
|
46
46
|
return mix(ambient, lit, scattering * 0.65) + radiance * 0.045 * transmission;
|
|
47
47
|
}
|
|
48
|
-
`,bc=new Map,xc=0,Sc=96,Cc=new Map;function wc(){return[...bc.values()].reduce((e,t)=>e+t.bytes,0)+Cc.size*Sc*Sc*4}function Tc(e){let t=Cc.get(e);if(t)return t;let n=new Float32Array(9216),r=new Float32Array(1024);for(let t=0;t<r.length;t++)r[t]=us(e+71,t);let i=(e,t)=>{let n=Math.floor(e),i=Math.floor(t),a=e-n,o=t-i,s=a*a*(3-2*a),c=o*o*(3-2*o),l=(e,t)=>r[(e&31)+(t&31)*32];return(l(n,i)*(1-s)+l(n+1,i)*s)*(1-c)+(l(n,i+1)*(1-s)+l(n+1,i+1)*s)*c};for(let e=0;e<Sc;e++)for(let t=0;t<Sc;t++){let r=(t+.5)/Sc,a=(e+.5)/Sc,o=i(r*3+2,a*3+4)*.52+i(r*7+7,a*7+3)*.3+i(r*17,a*17)*.18,s=(r-.5)*2,c=(a-.5)*2,l=Math.hypot(s+(i(r*4,a*4)-.5)*.27,c+(i(r*4+5,a*4)-.5)*.27),u=Math.max(0,Math.min(1,(1-l)*3.5)),d=Math.max(0,o-.24)**1.4*u*u*(3-2*u);n[e*Sc+t]=d}return Cc.set(e,n),n}function Ec(e,t,n){let r=`${t}:${n}`,i=bc.get(r);if(i)return i.used=++xc,i.canvas;let a;if(typeof OffscreenCanvas<`u`)a=new OffscreenCanvas(Sc,Sc);else if(typeof document<`u`)a=document.createElement(`canvas`),a.width=a.height=Sc;else try{a=new e.canvas.constructor(Sc,Sc)}catch{return null}let o=a.getContext(`2d`);if(!o)return null;o.fillStyle=t,o.fillRect(0,0,1,1);let s=o.getImageData(0,0,1,1).data,c=o.createImageData(Sc,Sc),l=Tc(n);for(let e=0;e<l.length;e++)c.data[e*4]=s[0],c.data[e*4+1]=s[1],c.data[e*4+2]=s[2],c.data[e*4+3]=Math.round(l[e]*255);if(o.putImageData(c,0,0),bc.size>=64){let e=``,t=1/0;for(let[n,r]of bc)r.used<t&&(e=n,t=r.used);bc.delete(e)}return bc.set(r,{canvas:a,used:++xc,bytes:36864}),a}function Dc(e,t,n,r,i,a=[]){let o=t.dust??ds(t.x,t.y,t.size,t.seed),s=e.globalAlpha;for(let c of o.parcels){let o=c.radius*c.spread,l=c.z*.22;if(c.x+o*2<n.x||c.x-o*2>n.x+n.width||c.y+o*2<n.y||c.y-l-o*2>n.y+n.height)continue;let u=Math.max(0,Math.min(1,(c.z-1)/7)),d=i===`ground`?1-u:u;if(d===0)continue;let f=r?.12:.7,p=-2.3;for(let e of a){let t=vc(e,c);t>f&&(f=t,p=Math.atan2(e.point.y-c.y,e.point.x-c.x))}let m=Ec(e,t.color,c.seed&3);e.save(),e.translate(c.x,c.y-l);let h=Math.hypot(c.vx,c.vy),g=Math.atan2(Math.sin(Math.atan2(c.vy,c.vx)-c.angle),Math.cos(Math.atan2(c.vy,c.vx)-c.angle));e.rotate(c.angle+g*Math.min(.6,h/100));let _=Math.sqrt(1+Math.min(.8,h/220));if(e.globalAlpha=s*t.opacity*d*(c.mass*9)*.55/(c.spread*c.spread),m)e.drawImage(m,-o*_,-o/_,o*2*_,o*2/_);else{let n=e.createRadialGradient(0,0,0,0,0,o);n.addColorStop(0,t.color),n.addColorStop(1,`transparent`),e.fillStyle=n,e.fillRect(-o,-o,o*2,o*2)}m&&f>.8&&(e.globalCompositeOperation=`screen`,e.globalAlpha*=Math.min(.6,(f-.8)*.2),e.drawImage(m,-o*_,-o/_,o*2*_,o*2/_),e.globalCompositeOperation=`source-over`),e.restore();let v=t.glint??.12;if(v<=0||us(c.seed,45)>.42)continue;let y=Math.max(0,Math.cos(c.angle*2+p+us(c.seed,47)*6.28))**48,b=Math.min(1,v*5)*y*Math.min(1,f)*d*s*t.opacity;if(b<.035)continue;let x=c.x+(us(c.seed,49)-.5)*o*.7,S=c.y-l+(us(c.seed,51)-.5)*o*.7,C=.35+b*.7;e.save(),e.globalAlpha=b,e.fillStyle=r?`#fff2ce`:`#fffefa`,e.beginPath(),e.ellipse(x,S,C,C,0,0,Math.PI*2),e.fill(),b>.45&&(e.lineWidth=.35,e.strokeStyle=`#fff5d7`,e.beginPath(),e.moveTo(x-C*2.5,S),e.lineTo(x+C*2.5,S),e.moveTo(x,S-C*2.5),e.lineTo(x,S+C*2.5),e.stroke()),e.restore()}}function Oc(e,t,n){let r=e.size,i=r*.74,a=0,o=0,s=0;for(let c=0;c<6;c++){let l=t*(c+.5)/6*2,u=n*(c+.5)/6*2,d=e.curlX*l*l*l+e.twist*n*2*l*l,f=e.curlY*u*u*u-e.twist*t*1.3*u*u;a+=Math.cos(d)*r*t/6,o+=Math.cos(f)*i*n/6,s+=Math.sin(d)*r*t/6+Math.sin(f)*i*n/6}let c=Math.max(0,t+n-.62);s+=c*c*r*(.35+e.fold);let l=Math.cos(e.tilt),u=Math.sin(e.tilt);return{x:a,y:o*l-s*u,z:o*u+s*l}}var kc=(e,t)=>{let n=Math.imul((e|0)&15^Math.imul(t+17,374761393),668265263);return n=Math.imul(n^n>>>13,1274126177),((n^n>>>16)>>>0)/4294967296},Ac=new Map,jc=new Map;function Mc(e){let t=Ac.get(e);if(t)return t;let n=e.replace(/^#/,``),r=/^[\da-f]{3}$/i.test(n)?[...n].map(e=>e+e).join(``):n,i=/^[\da-f]{6}$/i.test(r)?[0,2,4].map(e=>parseInt(r.slice(e,e+2),16)):e.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/)?.slice(1,4).map(Number)??[195,190,174];return Ac.size>=128&&Ac.delete(Ac.keys().next().value),Ac.set(e,i),i}function Nc(e,t){let n=Math.round(t),r=`${e}:${n}`,i=jc.get(r);if(i)return i;let a=`rgb(${Mc(e).map(e=>Math.max(0,Math.min(255,e+n))).join(` `)})`;return jc.size>=512&&jc.delete(jc.keys().next().value),jc.set(r,a),a}function Pc(e,t){e.beginPath(),t.forEach(([t,n],r)=>{r?e.lineTo(t,n):e.moveTo(t,n)}),e.closePath()}function Fc(e,t,n){let r=Math.max(0,t.z),i=1+Math.min(.65,r/90);e.save(),e.translate(t.x+r*.13,t.y+r*.1),e.rotate(t.angle),e.fillStyle=`#000`,e.globalAlpha=t.opacity*(n?.12:.15)/(1+r/26),e.beginPath(),e.ellipse(0,0,t.size*.46*i,t.size*.27*i,0,0,Math.PI*2),e.fill(),r<5&&(e.globalAlpha*=(1-r/5)*.6,e.beginPath(),e.ellipse(0,0,t.size*.36,t.size*.19,0,0,Math.PI*2),e.fill()),e.restore()}function Ic(e,t){let n=[];for(let e=0;e<=2;e++)n.push(Array.from({length:9},(n,r)=>Oc(t,r/8-.5,e/2-.5)));let r=t.z<.5?Math.max(0,-Math.min(...n.flat().map(e=>e.z))):0,i=e=>[e.x,e.y-(e.z+r)*.48],a=[];for(let e=0;e<2;e++)for(let t=0;t<8;t++){let r=n[e][t],i=n[e][t+1],o=n[e+1][t+1],s=n[e+1][t],c=i.x-r.x,l=i.y-r.y,u=i.z-r.z,d=s.x-r.x,f=s.y-r.y,p=s.z-r.z,m=l*p-u*f,h=u*d-c*p,g=c*f-l*d,_=Math.max(.001,Math.hypot(m,h,g)),v=g+h*.48>0,y=(m*-.35+h*-.45+Math.abs(g)*.7)/_;a.push({a:r,b:i,c:o,d:s,col:t,row:e,front:v,light:y,depth:(r.z+i.z+o.z+s.z)/4})}a.sort((e,t)=>e.depth-t.depth);for(let n of a){let{a:r,b:a,c:o,d:s,front:c,light:l,row:u,col:d}=n;if(Pc(e,[i(r),i(a),i(o),i(s)]),e.fillStyle=Nc(t.color,(c?0:-32)+(l-.7)*45),e.fill(),c&&d>0&&d<(u===0?6:8)&&u<3){e.strokeStyle=Nc(t.color,-100),e.lineWidth=t.size*(u===0?.027:.013);let n=i({x:(r.x+s.x)*.5,y:(r.y+s.y)*.5,z:(r.z+s.z)*.5}),c=i({x:(a.x+o.x)*.5,y:(a.y+o.y)*.5,z:(a.z+o.z)*.5});if(e.beginPath(),e.moveTo(...n),e.lineTo(...c),e.stroke(),u>0){let t=i({x:r.x*.2+s.x*.8,y:r.y*.2+s.y*.8,z:r.z*.2+s.z*.8}),n=i({x:a.x*.2+o.x*.8,y:a.y*.2+o.y*.8,z:a.z*.2+o.z*.8});e.beginPath(),e.moveTo(...t),e.lineTo(...n),e.stroke()}}}}function Lc(e,t){let n=[],r=.72+Math.abs(Math.cos(t.tilt))*.28;for(let e=0;e<9;e++){let i=e/9*Math.PI*2,a=t.size*(.32+kc(t.seed,e+20)*.18);n.push([Math.cos(i)*a,Math.sin(i)*a*r])}let i=[(kc(t.seed,33)-.5)*t.size*.17,(kc(t.seed,34)-.5)*t.size*.18];for(let r=0;r<n.length;r++){Pc(e,[i,n[r],n[(r+1)%n.length]]);let a=(kc(t.seed,r+40)-.45)*72+Math.sin(t.tilt+r)*9;e.fillStyle=Nc(t.color,a),e.fill()}e.strokeStyle=Nc(t.color,-45),e.lineWidth=.35,e.globalAlpha*=.3;for(let r of[1,4,6])e.beginPath(),e.moveTo(...n[r]),e.lineTo(i[0]+t.size*.08,i[1]),e.stroke()}function Rc(e,t){let n=t.size,r=t.size*(.35+kc(t.seed,51)*.25),i=Math.cos(t.tilt);e.scale(1,Math.abs(i)<.1?.1:i),Pc(e,[[-n*.5,-r*.5],[-n*.43,-r*.31],[-n*.49,-r*.08],[-n*.42,r*.12],[-n*.48,r*.48],[-n*.28,r*.38],[n*.3,r*.43],[n*.5,r*.52],[n*.44,r*.21],[n*.5,-r*.02],[n*.43,-r*.22],[n*.49,-r*.52],[n*.28,-r*.38],[-n*.28,-r*.4]]),e.fillStyle=i<0?`#b9c1c3`:Nc(t.color,24),e.fill(),Pc(e,[[-n*.3,-r/2],[n*.3,-r*.43],[n*.21,r*.35],[-n*.2,r*.4]]),e.fillStyle=Nc(t.color,-16),e.fill(),e.fillStyle=`#e4decd`,e.fillRect(-n*.15,-r*.14,n*.27,r*.19),e.strokeStyle=Nc(t.color,65),e.lineWidth=.45,e.globalAlpha*=.45;for(let t of[-1,1])e.beginPath(),e.moveTo(t*n*.3,-r*.35),e.lineTo(t*n*.38,r*.15),e.lineTo(t*n*.27,r*.35),e.stroke()}function zc(e,t){let n=t.size,r=t.size*(.35+kc(t.seed,61)*.2),i=Math.cos(t.tilt);if(e.scale(1,Math.abs(i)<.08?.08:i),e.beginPath(),e.moveTo(-n*.48,0),e.bezierCurveTo(-n*.15,-r*.7,n*.18,-r*.6,n*.5,-r*.08),e.bezierCurveTo(n*.12,r*.65,-n*.25,r*.45,-n*.48,0),e.fillStyle=Nc(t.color,i<0?14:0),e.fill(),e.beginPath(),e.moveTo(-n*.48,0),e.bezierCurveTo(-n*.15,-r*.7,n*.18,-r*.6,n*.5,-r*.08),e.quadraticCurveTo(0,-r*t.fold*.2,-n*.48,0),e.fillStyle=Nc(t.color,-13-t.fold*9),e.fill(),e.strokeStyle=Nc(t.color,-35),e.lineWidth=.45,e.globalAlpha*=.55,e.beginPath(),e.moveTo(-n*.63,r*.08),e.quadraticCurveTo(-n*.08,-r*t.fold*.2,n*.46,-r*.07),e.stroke(),n>10){e.lineWidth=.3;for(let t of[-.18,.08])e.beginPath(),e.moveTo(n*t,0),e.lineTo(n*(t+.1),-r*.3),e.moveTo(n*t,0),e.lineTo(n*(t-.03),r*.28),e.stroke()}}var Bc=new Map,Vc=0,Hc=0,Uc=()=>({sprites:Bc.size,bytes:Vc+wc()});function Wc(e,t){t.kind===`paper`?Ic(e,t):t.kind===`crumpled-paper`?Lc(e,t):t.kind===`trash`?Rc(e,t):t.kind===`leaf`&&zc(e,t)}function Gc(e){if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(e,e);if(typeof document>`u`||typeof HTMLCanvasElement>`u`)return null;let t=document.createElement(`canvas`);return!(t instanceof HTMLCanvasElement)||!t.getContext?null:(t.width=t.height=e,t)}function Kc(e,t,n){if(t.kind===`dust`||t.z>.1||Math.abs(t.vz)>.1||Math.hypot(t.vx,t.vy)>.75||t.kind===`paper`&&Math.abs(t.curlVelocityX)+Math.abs(t.curlVelocityY)+Math.abs(t.twistVelocity)>.03)return!1;let r=Math.max(4,Math.round(t.size/4)*4),i=Math.round(t.fold*5)/5,a=t.kind===`crumpled-paper`?(Math.round(t.tilt/(Math.PI/4))%8+8)%8:Math.cos(t.tilt)<0?4:0,o=a*Math.PI/4;if(t.kind!==`crumpled-paper`&&Math.abs(Math.sin(t.tilt))>.015)return!1;let s=Math.round(t.curlX*4)/4,c=Math.round(t.curlY*4)/4,l=Math.round(t.twist*4)/4,u=`${s}:${c}:${l}:${t.kind}:${t.seed&15}:${t.color}:${r}:${i}:${a}:${n}`,d=Bc.get(u),f={...t,size:r,fold:i,tilt:o,curlX:s,curlY:c,twist:l,opacity:1};if(!d){let e=r*1.4+4,t=Math.ceil(e*n),i=t*t*4;if(Bc.size>=128||Vc+i>8388608){for(let[e,t]of Bc)if(!(Hc-t.used<120)&&(Bc.delete(e),`close`in t.canvas&&t.canvas.close(),Vc-=t.bytes,Bc.size<128&&Vc+i<=8388608))break}if(Bc.size<128&&Vc+i<=8388608){let r=Gc(t),a=r?.getContext(`2d`);r&&a&&(a.scale(n,n),a.translate(e/2,e/2),Wc(a,f),d={canvas:`transferToImageBitmap`in r?r.transferToImageBitmap():r,extent:e,bytes:i,used:Hc},Bc.set(u,d),Vc+=i)}}return e.scale(t.size/r,t.size/r),d?(d.used=Hc,e.drawImage(d.canvas,-d.extent/2,-d.extent/2,d.extent,d.extent)):(e.save(),Wc(e,f),e.restore()),!0}function qc(e,t,n,r,i=`ground`,a=[]){i===`ground`&&Hc++;let o=e.getTransform(),s=Math.min(8,Math.max(1,Math.ceil(Math.hypot(o.a,o.b)))),c=n.x+n.width,l=n.y+n.height;for(let o of t){if(o.opacity<=0)continue;let t=(o.dust?.radius??o.size)+Math.max(0,o.z)*.35;o.x+t<n.x||o.x-t>c||o.y+t<n.y||o.y-t>l||(o.kind===`dust`?Dc(e,o,n,r,i,a):(i===`ground`&&Fc(e,o,r),i===`ground`==o.z<4&&(e.save(),e.translate(o.x,o.y-Math.max(0,o.z)*.22),e.rotate(o.angle),e.globalAlpha=o.opacity,Kc(e,o,s)||Wc(e,o),e.restore())))}}function Jc(e){let{tireLengthM:t,tireWidthM:n}=e.geometry;return e.image?{length:t*(e.image.wheelVisualScale?.length??.64),width:n*(e.image.wheelVisualScale?.width??.82)}:{length:t,width:n}}function Yc(e,t,n,r,i){let a=Kt(t,e.naturalWidth,e.naturalHeight),o=Math.min(1,512/Math.max(a.source.width,a.source.height)),s=document.createElement(`canvas`);s.width=Math.max(1,Math.round(a.source.width*o)),s.height=Math.max(1,Math.round(a.source.height*o));let c=s.getContext(`2d`);if(!c)return null;n?c.drawImage(n,0,0,s.width,s.height):c.drawImage(e,a.source.x,a.source.y,a.source.width,a.source.height,0,0,s.width,s.height),c.globalCompositeOperation=`source-in`,c.fillStyle=`#101916`,c.fillRect(0,0,s.width,s.height);let l=e=>{let t=Math.ceil(e*4),n=a.lengthM*r,o=a.widthM*r,c=document.createElement(`canvas`);c.width=Math.max(1,Math.ceil((n+t*2)*i)),c.height=Math.max(1,Math.ceil((o+t*2)*i));let l=c.getContext(`2d`);return l?(l.filter=`blur(${e*i}px)`,l.drawImage(s,t*i,t*i,n*i,o*i),{canvas:c,padding:t}):null};return{soft:l(6),close:l(1.5),pixelsPerMeter:r,lengthM:a.lengthM,widthM:a.widthM}}var Xc={width:128,height:60},Zc=8,Qc=14;function $c(e,t,n,r=Zc){let{width:i,height:a}=Xc,o=i/2,s=a/2,c=e.x-t.width/2,l=e.y-t.height/2,u=Math.hypot(c,l)||1,d={x:c/u,y:l/u},f=Math.max(0,t.width/2-o-Qc-Zc),p=Math.max(0,t.height/2-s-Qc-(l<0?r:Zc)),m=Math.min(Math.abs(c)?f/Math.abs(c):1/0,Math.abs(l)?p/Math.abs(l):1/0),h={x:t.width/2+c*(Number.isFinite(m)?m:0),y:t.height/2+l*(Number.isFinite(m)?m:0)},g=Math.min(Math.abs(d.x)?o/Math.abs(d.x):1/0,Math.abs(d.y)?s/Math.abs(d.y):1/0),_={x:d.x*g,y:d.y*g},v={x:_.x+d.x*Qc,y:_.y+d.y*Qc},y=Math.hypot(Math.max(0,-e.x,e.x-t.width),Math.max(0,-e.y,e.y-t.height))/Math.max(.001,n);return{center:h,direction:d,edge:_,tip:v,distance:y>=1e3?`${(y/1e3).toFixed(1)} km away`:`${Math.max(1,Math.round(y))} m away`,width:i,height:a}}var el=class{camera;constructor(e){this.camera=e}captureState(){return E({previousCarVelocity:this.previousCarVelocity,poseOffset:this.poseOffset,poseVelocity:this.poseVelocity,poseForce:this.poseForce,wheelPhase:this.wheelPhase})}restoreState(e){let t=E(e);this.previousCarVelocity=t.previousCarVelocity,this.poseOffset=t.poseOffset,this.poseVelocity=t.poseVelocity,this.poseForce=t.poseForce,this.wheelPhase=t.wheelPhase,this.clearMaterials()}clearMaterials(){this.carImages.clear(),this.pristineShadows=new WeakMap,this.deformedShadows=new WeakMap}reset(){this.markers=[],this.previousCarVelocity=null,this.poseOffset=D(),this.poseVelocity=D(),this.poseForce=D(),this.wheelPhase=[0,0,0,0]}carImages=new Map;pristineShadows=new WeakMap;deformedShadows=new WeakMap;previousCarVelocity=null;poseOffset=D();poseVelocity=D();poseForce=D();wheelPhase=[0,0,0,0];carVisualOffset(e){return A(N(D(this.poseOffset.x,-this.poseOffset.y),-e.body.angle),this.camera.zoom)}updateCarPose(e,t){if(e.mode!==`car`){this.previousCarVelocity=null,this.poseOffset=D(),this.poseVelocity=D(),this.poseForce=D();return}let n=e.body.velocity,r=this.previousCarVelocity?A(k(n,this.previousCarVelocity),1/Math.max(t,1e-4)):D();this.previousCarVelocity={...n};let i=N(r,-e.body.angle),a=1-Math.exp(-t/.11);this.poseForce=O(this.poseForce,A(k(D(P(i.x,-15,15),P(i.y,-15,15)),this.poseForce),a));let o=D(P(-this.poseForce.x*.006,-.055,.055),0);this.poseVelocity=O(this.poseVelocity,A(k(A(k(o,this.poseOffset),65),A(this.poseVelocity,15)),t)),this.poseOffset=O(this.poseOffset,A(this.poseVelocity,t)),e.car.tires.forEach((n,r)=>{this.wheelPhase[r]=(this.wheelPhase[r]+t*Math.abs(n.wheelSurfaceSpeedMps)/Math.max(.18,e.car.preset.geometry.tireLengthM*.45))%1})}line(e,t,n,r,i=1){let a=this.camera.screen(t),o=this.camera.screen(n);e.strokeStyle=r,e.lineWidth=i,e.beginPath(),e.moveTo(a.x,a.y),e.lineTo(o.x,o.y),e.stroke()}outline(e,t,n){e.beginPath(),t.forEach((t,n)=>{let r=this.camera.screen(t);n?e.lineTo(r.x,r.y):e.moveTo(r.x,r.y)}),e.closePath(),e.fillStyle=`${n}15`,e.fill(),e.strokeStyle=n,e.lineWidth=2,e.stroke()}imageFor(e){let t=e.image?.src;if(!t)return null;let n=this.carImages.get(t);return n||(n=new Image,n.crossOrigin=`anonymous`,n.src=t,this.carImages.set(t,n)),n.complete&&n.naturalWidth?n:null}markers=[];markerAt(e){return[...this.markers].reverse().find(t=>Math.abs(e.x-t.x)<=t.width/2+3&&Math.abs(e.y-t.y)<=t.height/2+3)?.vehicle??null}drawVehicleMarkers(e,t,n,r){if(this.markers=[],n)for(let n of t){let{sim:i}=n;if(i.mode!==`car`||i.car.explodedAt!==null)continue;let a=O(this.camera.screen(i.body.position),n===t[0]?this.carVisualOffset(i):D()),o=Math.max(i.car.preset.geometry.lengthM,i.car.preset.geometry.widthM)*this.camera.zoom*.5;if(a.x+o>=0&&a.x-o<=this.camera.width&&a.y+o>=0&&a.y-o<=this.camera.height)continue;let s=$c(a,this.camera,this.camera.zoom,this.camera.overlay?84:8),{width:c,height:l}=s,{x:u,y:d}=s.center;this.markers.push({vehicle:n,x:u,y:d,width:c,height:l});let f=n===r,p=f?`#f05a4f`:`#a9c5d4`;e.save(),e.translate(u,d),e.shadowColor=`#0000004a`,e.shadowBlur=16,e.shadowOffsetY=4,e.fillStyle=`#192126f5`,e.beginPath(),e.roundRect(-c/2,-l/2,c,l,l/2),e.fill(),e.shadowColor=`transparent`,e.strokeStyle=`#ffffff40`,e.lineWidth=1,e.stroke(),e.save(),e.beginPath(),e.arc(-38,0,23,0,Math.PI*2),e.clip(),e.fillStyle=`#313c42`,e.fillRect(-61,-23,46,46),e.strokeStyle=`#ffffff68`,e.lineWidth=1.2,e.setLineDash([5,5]),e.beginPath(),e.moveTo(-38,-23),e.lineTo(-38,23),e.stroke(),e.setLineDash([]);let m=this.imageFor(i.car.preset);if(e.save(),e.translate(-38,0),e.rotate(-i.body.angle),m){let t=Kt(i.car.preset,m.naturalWidth,m.naturalHeight),n=39*t.widthM/t.lengthM;e.drawImage(m,t.source.x,t.source.y,t.source.width,t.source.height,-39/2,-n/2,39,n)}else e.fillStyle=`#edf2f2`,e.beginPath(),e.roundRect(-14,-6,28,12,5),e.fill();e.restore(),e.restore(),e.strokeStyle=`#ffffffa8`,e.lineWidth=1.3,e.beginPath(),e.arc(-38,0,23,0,Math.PI*2),e.stroke(),e.fillStyle=`#f7f9fa`,e.font=`700 10px ui-sans-serif, system-ui, sans-serif`,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(f?`YOUR CAR`:`AI CAR`,-7,-9),e.fillStyle=`#b6c4c9`,e.font=`500 9px ui-sans-serif, system-ui, sans-serif`,e.fillText(s.distance,-7,8);let{direction:h,edge:g,tip:_}=s;e.strokeStyle=p,e.lineWidth=2.5,e.lineCap=`round`,e.beginPath(),e.moveTo(g.x+h.x*2,g.y+h.y*2),e.lineTo(_.x-h.x*5,_.y-h.y*5),e.stroke(),e.fillStyle=p,e.beginPath(),e.moveTo(_.x,_.y),e.lineTo(_.x-h.x*9-h.y*5,_.y-h.y*9+h.x*5),e.lineTo(_.x-h.x*9+h.y*5,_.y-h.y*9-h.x*5),e.closePath(),e.fill(),e.restore()}}shadowFor(e,t,n){let r=this.imageFor(e);if(!r)return null;let i=Kt(e,r.naturalWidth,r.naturalHeight),a=t?.spriteFor(r,i)??null,o=Math.max(1,Math.round(this.camera.zoom/2)*2),s=`${JSON.stringify(e.image?.crop)}|${e.image?.scale}|${e.geometry.lengthM}:${e.geometry.widthM}|${o}:${n}`;if(t&&a){let i=`${s}|${t.geometryRevision}`,c=this.deformedShadows.get(t);if(c?.image===r&&c.key===i)return c.shadow;let l=Yc(r,e,a,o,n);return this.deformedShadows.set(t,{image:r,key:i,shadow:l}),l}let c=this.pristineShadows.get(r);c||(c=new Map,this.pristineShadows.set(r,c));let l=c.get(s);return l||(l=Yc(r,e,a,o,n),c.set(s,l),c.size>12&&c.delete(c.keys().next().value)),l}vehicleBodyPath(e,t,n,r,i){if(!i?.hasDamage){e.roundRect(-t/2,-n/2,t,n,r);return}let a=Math.min(r,n/2),o=[{x:t/2-a,y:-n/2+a,start:-Math.PI/2},{x:t/2-a,y:n/2-a,start:0},{x:-t/2+a,y:n/2-a,start:Math.PI/2},{x:-t/2+a,y:-n/2+a,start:Math.PI}],s=!0;for(let t of o)for(let n=0;n<=8;n++){let r=t.start+n*Math.PI/16,o=D(t.x+Math.cos(r)*a,t.y+Math.sin(r)*a),c=i.point(A(o,1/this.camera.zoom)),l=c.x*this.camera.zoom,u=c.y*this.camera.zoom;s?(e.moveTo(l,u),s=!1):e.lineTo(l,u)}e.closePath()}carGround(e,t,n,r,i){performance.now();let a=t.body,o=t.car.preset.geometry,s=this.camera.screen(a.position),c=o.lengthM*this.camera.zoom,l=o.widthM*this.camera.zoom,u=P(M(this.poseForce)/13,0,1),d=e.globalAlpha;e.save(),e.translate(s.x,s.y),e.rotate(-a.angle),e.save(),e.translate(-this.poseOffset.x*this.camera.zoom*.2+2,this.poseOffset.y*this.camera.zoom*.2+4);let f=i?this.shadowFor(t.car.preset,n,r):null;if(f){let t=f.lengthM*this.camera.zoom,n=f.widthM*this.camera.zoom,r=this.camera.zoom/f.pixelsPerMeter,i=(i,a)=>{let o=i.padding*r;e.drawImage(i.canvas,-t/2-o,-n/2+a-o,t+o*2,n+o*2)};e.globalAlpha=d*(.43+u*.05),f.soft&&i(f.soft,3),e.globalAlpha=d*.14,f.close&&i(f.close,2)}else if(i){e.fillStyle=`rgba(13, 20, 20, ${.18+u*.045})`,e.shadowColor=`rgba(8, 14, 16, 0.43)`,e.shadowBlur=12+u*5,e.shadowOffsetY=2,e.beginPath();let r=t.car.preset.visual,i=r?l*.86:l*.84,a=r?r.shape===`suv`?9:r.shape===`supercar`?24:19:l*.34;this.vehicleBodyPath(e,r?c:c*.96,i,a,n),e.fill()}e.restore(),t.car.tires.forEach((n,r)=>{let i=Jc(t.car.preset),o=i.length*this.camera.zoom,s=i.width*this.camera.zoom;e.save(),e.translate(n.local.x*this.camera.zoom,-n.local.y*this.camera.zoom),e.rotate(-n.angle),e.fillStyle=`#121719`,e.beginPath(),e.roundRect(-o/2,-s/2,o,s,Math.min(3.5,s*.33)),e.fill(),e.save(),e.beginPath(),e.roundRect(-o/2+1,-s/2+1,o-2,s-2,Math.min(3,s*.3)),e.clip();let c=this.wheelPhase[r]??0,l=n.spinning?1:P(M(a.velocity)/24,0,.65),u=Math.max(4.2,o/4);e.strokeStyle=n.spinning?`rgba(170, 181, 178, 0.38)`:`rgba(125, 139, 137, 0.34)`,e.lineWidth=n.spinning?2:1.25;for(let t=-3;t<=4;t++){let n=t*u+c*u;e.beginPath(),e.moveTo(n-l*2,-s*.31),e.lineTo(n+l*2,s*.31),e.stroke()}l>.2&&(e.fillStyle=`rgba(137, 150, 147, ${.08+l*.1})`,e.fillRect(-o*.4,-s*.09,o*.8,s*.18)),e.restore(),e.strokeStyle=`rgba(6, 10, 11, 0.8)`,e.lineWidth=1.2,e.beginPath(),e.roundRect(-o/2,-s/2,o,s,Math.min(3.5,s*.33)),e.stroke(),e.restore()}),e.restore()}car(e,t,n,r,i){let a=n.car.preset,o=a.geometry,s=this.imageFor(a);if(s){let n=this.camera.screen(t.position),o=Kt(a,s.naturalWidth,s.naturalHeight),c=r?.spriteFor(s,o);e.save(),e.translate(n.x,n.y),e.rotate(-t.angle),qa(e,a,this.camera.zoom,o.lengthM,o.widthM,i),c?e.drawImage(c,-o.lengthM*this.camera.zoom/2,-o.widthM*this.camera.zoom/2,o.lengthM*this.camera.zoom,o.widthM*this.camera.zoom):e.drawImage(s,o.source.x,o.source.y,o.source.width,o.source.height,-o.lengthM*this.camera.zoom/2,-o.widthM*this.camera.zoom/2,o.lengthM*this.camera.zoom,o.widthM*this.camera.zoom),e.restore();return}if(a.visual){this.styledCar(e,t,n,r);return}let c=o.lengthM/2,l=o.widthM/2,u=[D(-c,-l),D(c,-l),D(c,l),D(-c,l)].map(e=>t.world(e));this.outline(e,u,`#8ce6c5`),this.line(e,t.world(D(o.wheelbaseM/4,-o.trackWidthM/2)),t.world(D(o.wheelbaseM/4,o.trackWidthM/2)),`#8ce6c5`,2),this.center(e,t,`#8ce6c5`)}exhaustOutlets(e){let t=e.car.preset,n=this.imageFor(t),r=n?Kt(t,n.naturalWidth,n.naturalHeight).lengthM:t.geometry.lengthM,i=t.exhaust.layout,a=t.geometry.widthM*.3;return(i===`left-right`?[-a,a]:i===`left`?[-a]:i===`right`?[a]:[0]).map(e=>D(-r/2-.025,e))}exhaust(e,t){let n=this.camera.screen(t.body.position);e.save(),e.translate(n.x,n.y),e.rotate(-t.body.angle);let r=this.exhaustOutlets(t);for(let t of r)e.fillStyle=`rgba(25, 31, 33, 0.62)`,e.beginPath(),e.ellipse(t.x*this.camera.zoom,-t.y*this.camera.zoom,Math.max(1.3,this.camera.zoom*.065),Math.max(1.2,this.camera.zoom*.055),0,0,Math.PI*2),e.fill();e.restore()}styledCar(e,t,n,r){let{geometry:i,visual:a}=n.car.preset;if(!a)return;let o=this.camera.screen(t.position),s=i.lengthM*this.camera.zoom,c=i.widthM*this.camera.zoom*.86,l=a.shape===`suv`?9:a.shape===`supercar`?24:19;e.save(),e.translate(o.x,o.y),e.rotate(-t.angle),e.beginPath(),this.vehicleBodyPath(e,s,c,l,r),e.fillStyle=a.color,e.fill(),e.strokeStyle=`rgba(18, 29, 27, 0.72)`,e.lineWidth=2,e.stroke(),e.fillStyle=`rgba(16, 32, 36, 0.8)`;let u=s*(a.shape===`suv`?.52:a.shape===`supercar`?.32:.4),d=c*(a.shape===`suv`?.72:.64),f=a.shape===`supercar`?-s*.08:-s*.015;e.beginPath(),e.roundRect(f-u/2,-d/2,u,d,a.shape===`suv`?7:14),e.fill(),e.strokeStyle=`rgba(235, 245, 241, 0.58)`,e.lineWidth=2,e.beginPath(),e.moveTo(f+u*.16,-d/2+3),e.lineTo(f+u*.16,d/2-3),e.stroke(),e.fillStyle=`rgba(255, 246, 205, 0.9)`;let p=tt(n.car.preset);for(let t of[-1,1])e.beginPath(),e.ellipse(p.headlights.xM*this.camera.zoom,t*p.headlights.yM*this.camera.zoom,4,3,0,0,Math.PI*2),e.fill();e.fillStyle=`rgba(139, 28, 21, 0.88)`;for(let t of[-1,1])e.fillRect(p.taillights.xM*this.camera.zoom-2,t*p.taillights.yM*this.camera.zoom-3,4,6);e.restore()}ship(e,t,n){let r=n.ship,i=r.craft,a=t.world(r.counterweight);this.line(e,t.world(O(r.counterweight,D(r.radius))),t.world(O(i,D(-.6))),`#ff6262`,2);let o=this.camera.screen(a);e.beginPath(),e.arc(o.x,o.y,r.radius*this.camera.zoom,0,Math.PI*2),e.fillStyle=`#ff626215`,e.fill(),e.strokeStyle=`#ff6262`,e.lineWidth=2,e.stroke();let s=[D(1.2),D(-.6,-.8),D(-.6,.8)].map(e=>t.world(O(i,N(e,r.headAngle))));this.outline(e,s,`#ff6262`),this.center(e,t,`#ff6262`)}brick(e,t){this.outline(e,[D(-2,-1),D(2,-1),D(2,1),D(-2,1)].map(e=>t.world(e)),`#f6bd79`),this.center(e,t,`#f6bd79`)}center(e,t,n){let r=this.camera.screen(t.position);e.fillStyle=n,e.beginPath(),e.arc(r.x,r.y,3,0,Math.PI*2),e.fill(),!this.camera.overlay&&M(t.velocity)>.1&&this.line(e,t.position,O(t.position,A(t.velocity,.35)),`#658da0`)}};function tl(e,t,n){return n?D(n.x+n.width/2,n.y+n.height/2):D(e/2,t/2)}function nl(e,t,n){let r=tl(e,t,n);return Math.ceil(2*Math.hypot(Math.max(r.x,e-r.x),Math.max(r.y,t-r.y)))}function rl(e,t,n,r){return O(n,N(k(e,t),r))}function il(e,t,n,r){return O(t,N(k(e,n),-r))}function al(e,t,n){return A(D(e,t),n/2)}function ol(e,t,n,r){return e+Math.atan2(Math.sin(t-e),Math.cos(t-e))*(r<=0?1:1-Math.exp(-Math.max(0,n)/r))}function sl(e,t,n){return{x:e.x<n?e.x-n:e.x>t.width-n?e.x-(t.width-n):0,y:e.y<n?e.y-n:e.y>t.height-n?e.y-(t.height-n):0}}var cl={};function ll(e,t={x:0,y:0},n=1){let r=Go();return{x:e.left/n+r.x+t.x,y:e.top/n+r.y+t.y,width:e.width/n,height:e.height/n}}var ul={scale:1,viewportRectToDocument:ll},dl=`[data-jr-overlay],[data-jr-ui],[data-jr-touch-controls],[data-jr-embed],script,style,link`,fl=class{scale=1;signature=``;originals=new Map;viewportRectToDocument(e,t={x:0,y:0}){return ll(e,t,this.scale)}apply(e,t){let n=Go(),r=`${e}:${t.x}:${t.y}:${n.x}:${n.y}:${document.body.children.length}`;if(r!==this.signature||cl.owner!==this){this.signature=r;for(let r of Array.from(document.body.children))if(r instanceof HTMLElement&&!r.matches(dl)){if(!this.originals.has(r)){this.originals.set(r,{translate:r.style.translate,scale:r.style.scale,origin:r.style.transformOrigin});let e=0,t=0;for(let n=r;n;n=n.offsetParent)e+=n.offsetLeft,t+=n.offsetTop;r.style.transformOrigin=`${-e}px ${-t}px`}r.style.scale=String(e),r.style.translate=`${n.x-t.x*e}px ${n.y-t.y*e}px`}this.scale=e,cl.owner=this}}clear(){for(let[e,t]of this.originals)e.style.translate=t.translate,e.style.scale=t.scale,e.style.transformOrigin=t.origin;this.originals.clear(),this.signature=``,this.scale=1,cl.owner===this&&(cl.owner=void 0)}};function pl(e,t,n){let r=Math.min(Math.max(1,t.width-32)/Math.max(1,e.width+160),Math.max(1,t.height-32)/Math.max(1,e.height+160));return Math.max(.1,Math.min(3,n??r))}function ml(e,t){let n=null;for(let r of e){let e=r.bounds;t.x<e.x||t.y<e.y||t.x>=e.x+e.width||t.y>=e.y+e.height||(!n||n.element.contains(r.element)||!r.element.contains(n.element)&&e.width*e.height<n.bounds.width*n.bounds.height)&&(n=r)}return n}var hl=class{projection;regions=[];measuredAt=-1/0;constructor(e=ul){this.projection=e}at(e,t,n){return n-this.measuredAt>120&&(this.measuredAt=n,this.regions=Array.from(document.querySelectorAll(`[data-jr-camera],[data-jr-camera-zoom]`)).filter(e=>!e.closest(`[data-jr-ui],[data-jr-overlay]`)).flatMap(e=>{let n=e.getAttribute(`data-jr-camera`);if(n!==null&&n!==`fixed`&&n!==`follow`)return[];let r=this.projection.viewportRectToDocument(e.getBoundingClientRect(),t);if(r.width<=0||r.height<=0)return[];let i=e.getAttribute(`data-jr-camera-zoom`),a=i?.trim()?Number(i):NaN;return n===null&&(!Number.isFinite(a)||a<=0)?[]:[{element:e,bounds:r,fixed:n===`fixed`,zoom:Number.isFinite(a)&&a>0?a:void 0}]})),ml(this.regions.filter(e=>e.element.isConnected),e)}reset(){this.regions=[],this.measuredAt=-1/0}},gl={minimumScale:.58,startsAtMps:3,fullAtMps:20,responsePerSecond:4};function _l(e,t,n,r,i){return e===`auto`?t&&!n&&(r.x<0||r.y<0||r.x>i.width||r.y>i.height):e}var vl=class{overlay;canvasWorld;requestResize;constructor(e,t,n){this.overlay=e,this.canvasWorld=t,this.requestResize=n,e&&(this.originScroll=D(window.scrollX,window.scrollY),this.observedScroll={...this.originScroll},this.pageSize={width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight})}resize(){this.requestResize()}get pixelSpace(){return this.overlay||this.canvasWorld}get timeSeconds(){return this.lastFrame/1e3}rebaseTime(e){this.lastFrame=e}captureState(){return E({outputWidth:this.outputWidth,outputHeight:this.outputHeight,cameraRotation:this.cameraRotation,cameraLock:this.cameraLock,cameraSmoothing:this.cameraSmoothing,cameraLockInitialized:this.cameraLockInitialized,width:this.width,height:this.height,dpr:this.dpr,smokeMargin:this.smokeMargin,regionScale:this.regionScale,canvasWorldScale:this.canvasWorldScale,cameraFrame:this.cameraFrame,camera:this.camera,zoom:this.zoom,baseZoom:this.baseZoom,speedScale:this.speedScale,slowMoScale:this.slowMoScale,zoomAnchor:this.zoomAnchor,pageSize:this.pageSize,lastFrame:this.lastFrame,speedSamples:this.speedSamples,originScroll:this.originScroll,observedScroll:this.observedScroll,virtualScroll:this.virtualScroll,followInterrupted:this.followInterrupted,deadZone:this.deadZone,speedZoom:this.speedZoom,speedZoomMinimumScale:this.speedZoomMinimumScale})}restoreState(e){let t=E(e);this.vehicleReveal=null,this.outputWidth=t.outputWidth,this.outputHeight=t.outputHeight,this.cameraRotation=t.cameraRotation,this.cameraLock=t.cameraLock,this.cameraSmoothing=t.cameraSmoothing,this.cameraLockInitialized=t.cameraLockInitialized,this.width=t.width,this.height=t.height,this.dpr=t.dpr,this.smokeMargin=t.smokeMargin,this.regionScale=t.regionScale,this.canvasWorldScale=t.canvasWorldScale,this.cameraFrame=t.cameraFrame,this.camera=t.camera,this.zoom=t.zoom,this.baseZoom=t.baseZoom,this.speedScale=t.speedScale,this.slowMoScale=t.slowMoScale,this.zoomAnchor=t.zoomAnchor,this.pageSize=t.pageSize,this.lastFrame=t.lastFrame,this.speedSamples=t.speedSamples,this.originScroll=t.originScroll,this.observedScroll=t.observedScroll,this.virtualScroll=t.virtualScroll,this.followInterrupted=t.followInterrupted,this.deadZone=t.deadZone,this.speedZoom=t.speedZoom,this.speedZoomMinimumScale=t.speedZoomMinimumScale}restorePresentation(){this.setVirtualScroll({...this.virtualScroll}),this.overlay&&(window.scrollTo(this.observedScroll.x,this.observedScroll.y),Ko(),this.resize(),this.cameraRegions.reset(),this.activeCameraRegion||this.regionScale!==1?this.pageScene.apply(this.regionScale,this.sceneScroll()):this.pageScene.clear())}reset(){this.vehicleReveal=null,this.camera=D(),this.cameraLockInitialized=!1,this.speedScale=1,this.slowMoZoom=1,this.zoomAnchor=D(),this.overlay&&(this.pageSize={width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight}),this.pageScene.clear(),this.activeCameraRegion=null,this.cameraRegions.reset(),this.regionScale=this.canvasWorld?this.canvasWorldScale:1,this.resize(),this.setVirtualScroll(D()),this.speedSamples=[]}vehicleReveal=null;revealVehicle(e,t=550){this.overlay&&(this.syncScroll(),this.followInterrupted=!0,this.vehicleReveal={sim:e,start:this.sceneScroll(),started:null,duration:t})}advanceVehicleReveal(e,t){let n=this.vehicleReveal;if(!n)return;n.started??=e;let r=n.duration<=0?1:P((e-n.started)/n.duration,0,1),i=r*r*(3-2*r),a=k(this.documentPoint(n.sim.body.position),D(this.width/2,this.height/2));!this.virtualScroll.x&&a.x>=-this.width/2&&a.x<=this.pageSize.width-this.width/2&&(a.x=P(a.x,0,Math.max(0,this.pageSize.width-this.width))),!this.virtualScroll.y&&a.y>=-this.height/2&&a.y<=this.pageSize.height-this.height/2&&(a.y=P(a.y,0,Math.max(0,this.pageSize.height-this.height))),this.moveSceneTo(O(n.start,A(k(a,n.start),i))),r===1&&(this.vehicleReveal=null,n.sim===t&&(this.followInterrupted=!1))}resetFollow(){this.vehicleReveal=null,this.overlay&&(this.originScroll=D(window.scrollX,window.scrollY),this.observedScroll={...this.originScroll},this.followInterrupted=!1)}dispose(){this.vehicleReveal=null,this.pageScene.clear(),this.setVirtualScroll(D()),Ko()}resizeLayout(e,t,n){this.outputWidth=e,this.outputHeight=t;let r=this.canvasWorld&&this.cameraLock,i=r?nl(e,t,this.cameraFrame):0,a=(r?i:e)/this.regionScale,o=(r?i:t)/this.regionScale;this.overlay&&this.width>1&&(a!==this.width||o!==this.height)&&(this.originScroll.x+=(this.width-a)/2,this.originScroll.y+=(this.height-o)/2),this.width=a,this.height=o;let s=Math.min(e,t);this.baseZoom=this.canvasWorld?28:this.overlay?Math.max(14,Math.min(28,s/11)):Math.max(1,Math.min(s<600?32:28,(s-32)/10,s/25)),this.zoom=this.baseZoom*(this.canvasWorld?1:this.speedScale*(this.overlay?1:this.slowMoZoom)),this.overlay&&this.regionScale===1&&!this.virtualScroll.x&&!this.virtualScroll.y&&this.speedScale>.999&&(this.pageSize={width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight}),this.smokeMargin=this.canvasWorld?96/this.regionScale:this.pixelSpace?Math.min(112,Math.max(72,Math.min(this.width,this.height)*.1)):0;let c=this.width*this.height;this.dpr=Math.min(2*(this.canvasWorld?this.regionScale:1),n*this.regionScale,Math.sqrt(24e6/c),16384/Math.max(this.width,this.height))}outputWidth=1;outputHeight=1;cameraRotation=0;cameraLock=!1;cameraSmoothing=.25;cameraLockInitialized=!1;width=1;height=1;dpr=1;smokeMargin=0;pageScene=new fl;cameraRegions=new hl(this.pageScene);get documentProjection(){return this.pageScene}activeCameraRegion=null;regionScale=1;canvasWorldScale=1;cameraFrame=null;camera=D();zoom=28;baseZoom=28;speedScale=1;slowMoScale=1;get slowMoZoom(){return this.slowMoScale??1}set slowMoZoom(e){this.slowMoScale=e}zoomAnchor=D();pageSize={width:1,height:1};lastFrame=0;speedSamples=[];originScroll=D();observedScroll=D();virtualScroll=D();followInterrupted=!1;deadZone=!0;speedZoom=`auto`;speedZoomMinimumScale=gl.minimumScale;screen(e){return D(this.width/2+(e.x-this.camera.x)*this.zoom,this.height/2-(e.y-this.camera.y)*this.zoom)}world(e){return D(this.camera.x+(e.x-this.width/2)/this.zoom,this.camera.y-(e.y-this.height/2)/this.zoom)}vehicleViewportPosition(e){return this.overlay&&this.syncScroll(),this.screen(e)}sceneScroll(){return this.canvasWorld?D(this.camera.x*28-this.width/2,-this.camera.y*28-this.height/2):O(Go(),this.virtualScroll)}virtualOffset(){return{...this.virtualScroll}}documentPoint(e){return this.canvasWorld?an(e):(this.overlay&&this.syncScroll(),O(this.screen(e),this.sceneScroll()))}worldFromDocument(e){return this.canvasWorld?on(e):(this.overlay&&this.syncScroll(),this.world(k(e,this.sceneScroll())))}documentScale(){return this.canvasWorld?28:this.zoom}particlePoint(e){return this.pixelSpace?this.documentPoint(e):{...e}}particleScale(){return this.pixelSpace?this.documentScale():1}viewportSize(){return{width:this.width,height:this.height}}presentationScale(){return this.regionScale}setCanvasWorldScale(e,t=1.5){if(!this.canvasWorld)return;this.canvasWorldScale=Math.max(.2,Math.min(Math.max(.2,Math.min(4,Number.isFinite(t)?t:1.5)),Number.isFinite(e)?e:1));let n=this.canvasWorldScale*this.speedScale*this.slowMoZoom;this.regionScale!==n&&(this.regionScale=n,this.resize())}setCameraFrame(e){this.cameraFrame=e,this.canvasWorld&&this.cameraLock&&this.resize()}setCameraLock(e){this.canvasWorld&&this.cameraLock!==e&&(this.cameraLock=e,this.cameraLockInitialized=!1,e||(this.cameraRotation=0),this.resize())}viewportFromDocument(e){let t=A(k(e,this.sceneScroll()),this.regionScale);return this.canvasWorld&&this.cameraLock?rl(t,al(this.width,this.height,this.regionScale),tl(this.outputWidth,this.outputHeight,this.cameraFrame),this.cameraRotation):t}documentFromViewport(e){return O(A(this.canvasWorld&&this.cameraLock?il(e,al(this.width,this.height,this.regionScale),tl(this.outputWidth,this.outputHeight,this.cameraFrame),this.cameraRotation):e,1/this.regionScale),this.sceneScroll())}bounds(){this.overlay&&this.syncScroll();let e=this.width/(2*this.zoom)-3/this.zoom,t=this.height/(2*this.zoom)-3/this.zoom;return{left:this.camera.x-e,right:this.camera.x+e,bottom:this.camera.y-t,top:this.camera.y+t}}setVirtualScroll(e){if(!this.overlay)return;this.virtualScroll=D(Math.abs(e.x)<.01?0:e.x,Math.abs(e.y)<.01?0:e.y);let t=document.body;this.virtualScroll.x||this.virtualScroll.y?(t.dataset.jrVirtualCamera===void 0&&(t.dataset.jrVirtualCamera=``),t.style.setProperty(`--joy-ride-scene-x`,`${-this.virtualScroll.x}px`),t.style.setProperty(`--joy-ride-scene-y`,`${-this.virtualScroll.y}px`)):(t.dataset.jrVirtualCamera!==void 0&&delete t.dataset.jrVirtualCamera,t.style.removeProperty(`--joy-ride-scene-x`),t.style.removeProperty(`--joy-ride-scene-y`))}syncScroll(e=!1){let t=D(Go().x,Go().y);e||M(k(t,this.observedScroll))>.5&&(this.followInterrupted=!0),this.observedScroll=t,(this.activeCameraRegion||this.regionScale!==1)&&this.pageScene?.apply(this.regionScale,this.sceneScroll());let n=O(t,this.virtualScroll);this.camera=D((n.x-this.originScroll.x-this.zoomAnchor.x*(this.baseZoom-this.zoom))/this.zoom,-(n.y-this.originScroll.y+this.zoomAnchor.y*(this.baseZoom-this.zoom))/this.zoom)}resumeFollow(){this.vehicleReveal=null,this.overlay&&(this.syncScroll(),this.followInterrupted=!1)}interruptFollow(){this.vehicleReveal=null,this.overlay&&(this.followInterrupted=!0)}restorePage(e){if(!this.overlay||!this.virtualScroll.x&&!this.virtualScroll.y&&!this.activeCameraRegion&&this.regionScale===1)return!1;this.syncScroll(!0);let t=A(this.screen(e.body.position),this.regionScale??1);return(this.activeCameraRegion||this.regionScale!==1)&&(this.slowMoZoom=1,this.pageScene.clear(),this.activeCameraRegion=null,this.regionScale=1,this.resize()),this.setVirtualScroll(D()),this.syncScroll(!0),e.body.position=this.world(t),!0}followDocument(e){if(!this.overlay)return!1;if(this.vehicleReveal||this.activeCameraRegion?.fixed)return!0;if(this.zoomAnchor={...e.body.position},this.syncScroll(),this.followInterrupted)return!1;let t=this.screen(e.body.position),n=Math.max(e.car.preset.geometry.lengthM*this.zoom/2+12,Math.min(this.width,this.height)*.25),r=sl(t,{width:this.width,height:this.height},n);if(r.x||r.y){if(e.barrier)window.scrollBy({left:r.x,top:r.y,behavior:`instant`}),Ko();else{let e=D(r.x*this.virtualScroll.x<0?Math.sign(r.x)*Math.min(Math.abs(r.x),Math.abs(this.virtualScroll.x)):0,r.y*this.virtualScroll.y<0?Math.sign(r.y)*Math.min(Math.abs(r.y),Math.abs(this.virtualScroll.y)):0);this.setVirtualScroll(O(this.virtualScroll,e));let t=k(r,e),n=Go();(t.x||t.y)&&(window.scrollBy({left:t.x,top:t.y,behavior:`instant`}),Ko());let i=k(Go(),n);this.setVirtualScroll(O(this.virtualScroll,k(t,i)))}}return this.syncScroll(!0),!0}moveSceneTo(e){window.scrollBy({left:e.x-Go().x,top:e.y-Go().y,behavior:`instant`}),Ko(),this.setVirtualScroll(D(e.x-Go().x,e.y-Go().y)),this.syncScroll(!0)}updateCameraRegion(e,t){let n=this.cameraFrame??{x:0,y:0,width:window.innerWidth,height:window.innerHeight},r=this.activeCameraRegion!==null&&!e,i=e!==null&&this.activeCameraRegion?.element!==e.element,a=(e?e.fixed?pl(e.bounds,n,e.zoom):Math.max(.1,Math.min(3,e.zoom??1)):1)*this.slowMoZoom,o=this.regionScale,s=A(k(t,this.sceneScroll()),o);if(this.activeCameraRegion=e,r&&this.pageScene.clear(),Math.abs(a-this.regionScale)>1e-4&&(this.regionScale=a,this.resize()),e?.fixed){this.speedScale=1,this.zoom=this.baseZoom;let t=e.bounds;this.moveSceneTo(D(t.x+t.width/2-(n.x+n.width/2)/this.regionScale,t.y+t.height/2-(n.y+n.height/2)/this.regionScale))}else(r||i)&&(this.followInterrupted=!1,this.moveSceneTo(D(t.x-this.width/2,t.y-this.height/2)));!e?.fixed&&!r&&!i&&Math.abs(a-o)>1e-4&&this.moveSceneTo(k(t,A(s,1/a))),e||a!==1?this.pageScene.apply(this.regionScale,this.sceneScroll()):this.pageScene.clear()}cameraStep(e,t){let n=this.lastFrame?P((t-this.lastFrame)/1e3,0,.1):1/60;this.lastFrame=t;let r=e.body;if(this.canvasWorld){if(this.cameraLock){let e=r.angle-Math.PI/2,t=!this.cameraLockInitialized||M(k(r.position,this.camera))>40;this.cameraRotation=t?e:ol(this.cameraRotation,e,n,this.cameraSmoothing),t&&(this.camera={...r.position}),this.cameraLockInitialized=!0}else this.cameraRotation=0}let i=M(r.velocity);for(this.speedSamples.push({time:t,speed:i});this.speedSamples.length>2&&this.speedSamples[1].time<t-1e3;)this.speedSamples.shift();let a=0,o=0;for(let e=0;e<this.speedSamples.length-1;e++){let n=Math.max(t-1e3,this.speedSamples[e].time),r=this.speedSamples[e+1].time;a+=this.speedSamples[e].speed*(r-n),o+=r-n}let s=o>0?a/o:i,c=D(this.width/2+r.position.x*this.baseZoom+this.originScroll.x,this.height/2-r.position.y*this.baseZoom+this.originScroll.y),l=this.overlay?this.cameraRegions.at(c,this.virtualScroll,t):null;this.overlay&&this.updateCameraRegion(l,c);let u=!l&&(this.canvasWorld?this.speedZoom===!0:_l(this.speedZoom,this.overlay,e.barrier,c,this.pageSize))?1-(1-(this.speedZoomMinimumScale??gl.minimumScale))*P((s-gl.startsAtMps)/(gl.fullAtMps-gl.startsAtMps),0,1):1;this.speedScale+=(u-this.speedScale)*(1-Math.exp(-gl.responsePerSecond*n));let d=this.zoom;if(this.canvasWorld){let e=this.canvasWorldScale*this.speedScale*this.slowMoZoom;Math.abs(this.regionScale-e)>1e-4&&(this.regionScale=e,this.resize()),this.zoom=this.baseZoom}else this.zoom=this.baseZoom*this.speedScale*(this.overlay?1:this.slowMoZoom);if(this.overlay){this.zoomAnchor={...r.position},this.syncScroll(),this.advanceVehicleReveal(t,e);return}if(e.barrier)return;let f=d/this.zoom;if(this.camera=D(r.position.x-(r.position.x-this.camera.x)*f,r.position.y-(r.position.y-this.camera.y)*f),this.canvasWorld&&this.cameraLock){let e=this.cameraSmoothing<=0?1:1-Math.exp(-n/this.cameraSmoothing);this.camera=O(this.camera,A(k(r.position,this.camera),e));return}if(!this.deadZone){let e=this.canvasWorld&&!this.cameraLock?this.cameraFrame:null;this.camera=e?D(r.position.x-((e.x+e.width/2)/this.regionScale-this.width/2)/this.zoom,r.position.y+((e.y+e.height/2)/this.regionScale-this.height/2)/this.zoom):{...r.position};return}let p=this.width*.18/this.zoom,m=this.height*.18/this.zoom,h=D(r.position.x-P(r.position.x-this.camera.x,-p,p),r.position.y-P(r.position.y-this.camera.y,-m,m));this.camera=O(this.camera,A(k(h,this.camera),1-Math.exp(-16*n)))}},yl=class{canvas;camera;overlay;canvasWorld;sceneCanvas=null;sceneContext;constructor(e,t,n,r){this.canvas=e,this.camera=t,this.overlay=n,this.canvasWorld=r;let i=e.getContext(`2d`);if(!i)throw Error(`Joy Ride requires a 2D canvas context.`);this.sceneContext=i}get context(){return this.sceneContext}resize(){let e=Math.max(1,this.overlay?window.innerWidth:this.canvas.clientWidth),t=Math.max(1,this.overlay?window.innerHeight:this.canvas.clientHeight),n=e/this.camera.regionScale!==this.camera.width||t/this.camera.regionScale!==this.camera.height;this.camera.resizeLayout(e,t,window.devicePixelRatio||1);let r=this.canvasWorld&&this.camera.cameraLock;r?(this.sceneCanvas??=document.createElement(`canvas`),this.sceneContext=this.sceneCanvas.getContext(`2d`)):this.sceneCanvas&&(this.sceneContext=this.canvas.getContext(`2d`)),this.overlay&&(n||this.canvas.style.width!==`${this.camera.width}px`)&&(this.canvas.style.width=`${this.camera.width}px`,this.canvas.style.height=`${this.camera.height}px`,this.canvas.style.transformOrigin=`0 0`,this.canvas.style.scale=String(this.camera.regionScale));let i=Math.round(this.camera.width*this.camera.dpr),a=Math.round(this.camera.height*this.camera.dpr),o=r?this.sceneCanvas:this.canvas;if((o.width!==i||o.height!==a)&&(o.width=i,o.height=a),r){let n=this.camera.dpr/this.camera.regionScale,r=Math.round(e*n),i=Math.round(t*n);this.canvas.width!==r&&(this.canvas.width=r),this.canvas.height!==i&&(this.canvas.height=i)}return this.sceneContext.setTransform(this.camera.dpr,0,0,this.camera.dpr,0,0),this.canvasWorld?this.camera.dpr:void 0}clear(){this.sceneContext.setTransform(this.camera.dpr,0,0,this.camera.dpr,0,0),this.sceneContext.clearRect(0,0,this.camera.width,this.camera.height)}presentLockedCamera(){if(!this.canvasWorld||!this.camera.cameraLock||!this.sceneCanvas)return;let e=this.canvas.getContext(`2d`),t=this.camera.dpr/this.camera.regionScale,n=tl(this.camera.outputWidth,this.camera.outputHeight,this.camera.cameraFrame);e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,this.canvas.width,this.canvas.height),e.save(),e.translate(n.x*t,n.y*t),e.rotate(this.camera.cameraRotation),e.drawImage(this.sceneCanvas,-this.sceneCanvas.width/2,-this.sceneCanvas.height/2),e.restore()}dispose(){this.sceneCanvas&&=(this.sceneCanvas.width=1,this.sceneCanvas.height=1,null),this.canvas.style.scale=``,this.canvas.style.transformOrigin=``}},bl=class{frameRate=new qo;captureState(){return this.frameRate.captureState()}restoreState(e){this.frameRate.restoreState(e)}draw(e,t,n,r,i){let a=e,o=t.body,s=this.frameRate.sample(n);a.save();let c=Jc(t.car.preset);for(let e of t.car.tires){let t=r(o.world(e.local));a.strokeStyle=e.front?`#00dcff`:`#ffae31`,a.lineWidth=2;let n=[D(-c.length/2,-c.width/2),D(c.length/2,-c.width/2),D(c.length/2,c.width/2),D(-c.length/2,c.width/2)].map(t=>r(o.world(O(e.local,N(t,e.angle)))));a.beginPath(),n.forEach((e,t)=>t?a.lineTo(e.x,e.y):a.moveTo(e.x,e.y)),a.closePath(),a.stroke(),a.beginPath(),a.arc(t.x,t.y,4,0,Math.PI*2),a.stroke(),a.beginPath(),a.moveTo(t.x-7,t.y),a.lineTo(t.x+7,t.y),a.moveTo(t.x,t.y-7),a.lineTo(t.x,t.y+7),a.stroke(),a.font=`bold 10px ui-monospace, SFMono-Regular, monospace`,a.fillStyle=e.front?`#007e91`:`#895000`,a.fillText(`${e.front?`F`:`R`}${e.local.y>0?`L`:`R`}${e.skidding?` SKID`:``}`,t.x+8,t.y-8)}let l=r(o.position),u=(e,t,n)=>{let r=O(l,A(e,n));a.strokeStyle=t,a.fillStyle=t,a.lineWidth=2.5,a.beginPath(),a.moveTo(l.x,l.y),a.lineTo(r.x,r.y),a.stroke();let i=Math.atan2(e.y,e.x);a.beginPath(),a.moveTo(r.x,r.y),a.lineTo(r.x-Math.cos(i-.5)*9,r.y-Math.sin(i-.5)*9),a.lineTo(r.x-Math.cos(i+.5)*9,r.y-Math.sin(i+.5)*9),a.closePath(),a.fill()};u(D(Math.cos(o.angle),-Math.sin(o.angle)),`#00c4df`,67);let d=M(o.velocity);d>.2&&u(D(o.velocity.x/d,-o.velocity.y/d),`#f05bd6`,48+Math.min(32,d));let f=Math.atan2(o.velocity.y,o.velocity.x),p=Math.atan2(Math.sin(o.angle-f),Math.cos(o.angle-f)),m=Math.max(...t.car.tires.filter(e=>e.front).map(e=>e.gripUtilization)),h=Math.max(...t.car.tires.filter(e=>!e.front).map(e=>e.gripUtilization)),g=t.car.tires.map(e=>`${e.front?`F`:`R`}${e.local.y>0?`L`:`R`} ${e.slipSpeedMps.toFixed(1)}${e.skidding?`*`:``}`).join(` `),_=[`${t.car.preset.name} · ${(d*3.6).toFixed(0)} km/h · ${Math.round(s)} FPS`,`input T ${t.lastInput.throttle} S ${t.lastInput.steer} brake ${Number(t.lastInput.action)}`,`body ${Math.round(o.angle*180/Math.PI)}° travel ${Math.round(f*180/Math.PI)}° slip ${Math.round(p*180/Math.PI)}°`,`front load ${(t.car.frontLoadFraction*100).toFixed(0)}% burnout ${Number(t.car.burnout)} charge ${t.car.boostCharge.toFixed(2)}`,`grip use F ${m.toFixed(2)} R ${h.toFixed(2)} drift ${Number(t.car.drifting)} donut ${Number(t.car.donuting)}`,`drift ${Number(t.car.fastDrifting)} countersteer ${Number(t.car.countersteering)}`,`roof rocket ${i.rocketState}`,`side guns ${i.gunState} · ${i.bulletCount} bullets`,`tire slip m/s ${g}`,`fluid ${i.fluidEngine} ${i.quality} ${i.fluidCols}×${i.fluidRows}`,`shared fire ${i.fireCols}×${i.fireRows} · ${i.groundedFireCount} grounded sources`,`cyan = nose/shape pink = travel amber = walls`,`wheel cyan = front wheel amber = rear violet = letters`];a.fillStyle=`rgba(10, 21, 24, 0.87)`,a.fillRect(12,88,Math.min(430,i.width-24),_.length*18+18),a.font=`12px ui-monospace, SFMono-Regular, monospace`,a.fillStyle=`#f1f5f3`,_.forEach((e,t)=>a.fillText(e,22,110+t*18)),a.restore()}},xl=[.82,.91,1],Sl=[1,.045,.018],Cl=e=>Math.max(0,Math.min(1,e));function wl(e){let t=/^#([\da-f]{6})$/i.exec(e);if(!t)return[.4,.9,1];let n=parseInt(t[1],16);return[(n>>16)/255,(n>>8&255)/255,(n&255)/255]}function Tl(e,t,n){let r=Math.cos(e.angle),i=Math.sin(e.angle);return{x:e.center.x+r*t-i*n,y:e.center.y+i*t+r*n}}var El=class{sprites=new WeakMap;halos=new WeakMap;beam=null;sprite(e){let t=e.image;if(!t||!t.complete||!t.naturalWidth)return null;let n=e.source??{x:0,y:0,width:t.naturalWidth,height:t.naturalHeight},r=e.mounts.taillights.map(t=>`${Math.round(t.x/e.width*1e4)},${Math.round(t.y/e.height*1e4)}`).join(`;`),i=`${n.x},${n.y},${n.width},${n.height}|${r}`,a=this.sprites.get(t);if(a||(a=new Map,this.sprites.set(t,a)),a.has(i))return a.get(i)??null;let o=document.createElement(`canvas`);o.width=192,o.height=Math.max(24,Math.round(192*n.height/n.width));let s=o.getContext(`2d`,{willReadFrequently:!0});if(!s)return a.set(i,null),null;s.drawImage(t,n.x,n.y,n.width,n.height,0,0,o.width,o.height);let c;try{c=s.getImageData(0,0,o.width,o.height)}catch{return a.set(i,null),null}let l=s.createImageData(o.width,o.height),u=0;for(let t=0;t<o.height;t++)for(let n=0;n<o.width;n++){let r=(t*o.width+n)*4,i=c.data[r],a=c.data[r+1],s=c.data[r+2],d=c.data[r+3];n<o.width*.27&&i>100&&i>a*1.6&&i>s*1.5&&d>100&&e.mounts.taillights.some(r=>{let i=n-(.5+r.x/e.width)*o.width,a=t-(.5+r.y/e.height)*o.height;return i*i+a*a<(o.height*.18)**2})&&(l.data[r]=255,l.data[r+1]=22,l.data[r+2]=5,l.data[r+3]=Math.min(235,d),u++),c.data[r]=255,c.data[r+1]=255,c.data[r+2]=255,c.data[r+3]=d>90?255:0}s.putImageData(c,0,0);let d=null;u>1&&u<o.width*o.height*.055&&(d=document.createElement(`canvas`),d.width=o.width,d.height=o.height,d.getContext(`2d`)?.putImageData(l,0,0));let f={silhouette:o,brakes:d};return a.size>=8&&a.clear(),a.set(i,f),f}halo(e,t){let n=this.halos.get(e);n||(n=new Map,this.halos.set(e,n));let r=n.get(t);if(r)return r;let i=document.createElement(`canvas`);i.width=e.width+64,i.height=e.height+64;let a=i.getContext(`2d`);a.drawImage(e,32,32),a.globalCompositeOperation=`source-in`,a.fillStyle=t,a.fillRect(0,0,i.width,i.height),a.globalCompositeOperation=`source-over`;let o=document.createElement(`canvas`);o.width=i.width,o.height=i.height,o.getContext(`2d`).drawImage(i,0,0),a.clearRect(0,0,i.width,i.height),a.filter=`blur(14px)`,a.globalAlpha=.92,a.drawImage(o,-2,-5,o.width+4,o.height+10),a.filter=`blur(7px)`,a.globalAlpha=.9,a.drawImage(o,0,0),a.filter=`blur(3px)`,a.globalAlpha=.8,a.strokeStyle=t,a.lineWidth=3,a.lineCap=`round`;for(let t of[-1,1])a.beginPath(),a.moveTo(32+e.width*.18,32+e.height*(.5+t*.34)),a.lineTo(32+e.width*.82,32+e.height*(.5+t*.34)),a.stroke();return a.filter=`none`,a.globalAlpha=1,n.size>8&&n.clear(),n.set(t,i),i}beamImage(){if(this.beam)return this.beam;let e=document.createElement(`canvas`);e.width=256,e.height=128;let t=e.getContext(`2d`),n=t.createImageData(e.width,e.height);for(let t=0;t<e.height;t++)for(let r=0;r<e.width;r++){let i=r/e.width,a=(t/e.height-.5)*2,o=.035+i*.94,s=Cl((1-i)/.4),c=Math.exp(-a*a/(o*o))*s*s*(3-2*s),l=(t*e.width+r)*4;n.data[l]=210,n.data[l+1]=230,n.data[l+2]=255,n.data[l+3]=Math.round(c*255)}return t.putImageData(n,0,0),this.beam=e,e}ground(e,t){let n=t.opacity??1,r=t.options.brakeLights?Cl(t.braking):0;if(!(n<=0||t.width<=0)){if(e.save(),e.translate(t.center.x,t.center.y),e.rotate(t.angle),e.globalCompositeOperation=`screen`,t.dark&&t.options.underglow&&t.options.underglowOpacity>0){let r=this.sprite(t);if(e.globalAlpha=Cl(t.options.underglowOpacity)*n,r){let n=this.halo(r.silhouette,t.options.underglowColor),i=32/r.silhouette.width*t.width,a=32/r.silhouette.height*t.height;e.drawImage(n,-t.width/2-i,-t.height/2-a,t.width+i*2,t.height+a*2)}else e.shadowColor=t.options.underglowColor,e.shadowBlur=t.height*.5,e.fillStyle=t.options.underglowColor,e.beginPath(),e.roundRect(-t.width*.43,-t.height*.38,t.width*.86,t.height*.76,t.height*.22),e.fill(),e.shadowBlur=0}if(t.dark&&t.options.headlights)for(let r of t.mounts.headlights)e.globalAlpha=.085*n,e.drawImage(this.beamImage(),r.x,r.y-t.width*.68,t.width*5.7,t.width*1.36);if(t.dark&&t.options.taillights||r>0){let i=r;for(let{x:r,y:a}of t.mounts.taillights){let o=t.height*(.48+i*.38),s=e.createRadialGradient(r,a,0,r,a,o),c=(t.dark?.12+i*.19:i*.13)*n;s.addColorStop(0,`rgba(255,30,8,${c})`),s.addColorStop(1,`rgba(255,20,4,0)`),e.fillStyle=s,e.fillRect(r-o,a-o,o*2,o*2)}}e.restore()}}glints(e,t){e.save(),e.translate(t.center.x,t.center.y),e.rotate(t.angle),e.globalCompositeOperation=`screen`;let n=t.opacity??1,r=t.options.brakeLights?Cl(t.braking):0;if(r>0){let i=this.sprite(t)?.brakes;i&&(e.globalAlpha=r*n*(t.dark?.9:.52),e.shadowColor=`#ff250d`,e.shadowBlur=t.height*(t.dark?.16:.055),e.drawImage(i,-t.width/2,-t.height/2,t.width,t.height))}for(let i of[!0,!1])if(!(i?!(t.dark&&t.options.headlights):!(t.dark&&t.options.taillights||r>0)))for(let a of t.mounts[i?`headlights`:`taillights`]){e.globalAlpha=n*(i?.75:t.dark?.34+r*.6:r*.45);let o=t.height*(i?.15:.12),s=e.createRadialGradient(a.x,a.y,0,a.x,a.y,o);s.addColorStop(0,i?`#e6f1ffd9`:`#ff3518c0`),s.addColorStop(.28,i?`#c1dcff70`:`#ff230760`),s.addColorStop(1,i?`#c1dcff00`:`#ff230700`),e.fillStyle=s,e.beginPath(),e.arc(a.x,a.y,o,0,Math.PI*2),e.fill()}e.restore()}smokeLights(e){let t=[],n={x:Math.cos(e.angle),y:Math.sin(e.angle)},r=e.opacity??1,i=e.options.brakeLights?Cl(e.braking):0;if(e.dark&&e.options.headlights)for(let i of e.mounts.headlights)t.push({point:Tl(e,i.x,i.y),direction:n,color:xl,range:e.width*6.2,radius:e.height*.075,spread:.14,intensity:1.7*r});if(e.dark&&e.options.taillights||i>0)for(let a of e.mounts.taillights)t.push({point:Tl(e,a.x,a.y),direction:{x:-n.x,y:-n.y},color:Sl,range:e.width*(i>0?1.6:.9),radius:e.height*.15,spread:.46,intensity:r*(e.dark?.24+i*.85:i*.42)});if(e.dark&&e.options.underglow&&e.options.underglowOpacity>0)for(let n of[-.27,0,.27])t.push({point:Tl(e,e.width*n,0),direction:{x:0,y:0},color:wl(e.options.underglowColor),range:e.height,radius:e.height*.8,spread:0,intensity:r*e.options.underglowOpacity*.8});return t}},Dl=Object.freeze({underglow:!1,underglowColor:`#66e6ff`,underglowOpacity:.6,headlights:!0,taillights:!0,brakeLights:!0});function Ol(e={}){return{underglow:typeof e.underglow==`boolean`?e.underglow:Dl.underglow,underglowColor:/^#[\da-f]{6}$/i.test(e.underglowColor??``)?e.underglowColor:Dl.underglowColor,underglowOpacity:Number.isFinite(e.underglowOpacity)?Math.max(0,Math.min(1,e.underglowOpacity)):Dl.underglowOpacity,headlights:typeof e.headlights==`boolean`?e.headlights:Dl.headlights,brakeLights:typeof e.brakeLights==`boolean`?e.brakeLights:Dl.brakeLights,taillights:typeof e.taillights==`boolean`?e.taillights:Dl.taillights}}var kl={light:{ink:`#161c17`,alphaScale:1},dark:{ink:`#a9adb0`,alphaScale:1.7}};function Al(e){let t=e.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i);if(!t)return!1;let[,n,r,i]=t.map(Number);return n*.2126+r*.7152+i*.0722<112}var jl=(e,t)=>{if(typeof e==`number`){if(t===3)return{mode:`rgb`,r:(e>>8&15|e>>4&240)/255,g:(e>>4&15|e&240)/255,b:(e&15|e<<4&240)/255};if(t===4)return{mode:`rgb`,r:(e>>12&15|e>>8&240)/255,g:(e>>8&15|e>>4&240)/255,b:(e>>4&15|e&240)/255,alpha:(e&15|e<<4&240)/255};if(t===6)return{mode:`rgb`,r:(e>>16&255)/255,g:(e>>8&255)/255,b:(e&255)/255};if(t===8)return{mode:`rgb`,r:(e>>24&255)/255,g:(e>>16&255)/255,b:(e>>8&255)/255,alpha:(e&255)/255}}},Ml={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Nl=e=>jl(Ml[e.toLowerCase()],6),Pl=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,Fl=e=>{let t;return(t=e.match(Pl))?jl(parseInt(t[1],16),t[1].length):void 0},Il=`([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)`,Ll=`${Il}%`,Rl=`(?:${Il}%|${Il})`,zl=`(?:${Il}%|${Il}|none)`,Bl=`(?:${Il}(deg|grad|rad|turn)|${Il})`,Vl=`\\s*,\\s*`;RegExp(`^`+zl+`$`);var Hl=RegExp(`^rgba?\\(\\s*${Il}${Vl}${Il}${Vl}${Il}\\s*(?:,\\s*${Rl}\\s*)?\\)$`),Ul=RegExp(`^rgba?\\(\\s*${Ll}${Vl}${Ll}${Vl}${Ll}\\s*(?:,\\s*${Rl}\\s*)?\\)$`),Wl=e=>{let t={mode:`rgb`},n;if(n=e.match(Hl))n[1]!==void 0&&(t.r=n[1]/255),n[2]!==void 0&&(t.g=n[2]/255),n[3]!==void 0&&(t.b=n[3]/255);else if(n=e.match(Ul))n[1]!==void 0&&(t.r=n[1]/100),n[2]!==void 0&&(t.g=n[2]/100),n[3]!==void 0&&(t.b=n[3]/100);else return;return n[4]===void 0?n[5]!==void 0&&(t.alpha=Math.max(0,Math.min(1,+n[5]))):t.alpha=Math.max(0,Math.min(1,n[4]/100)),t},Gl=(e,t)=>e===void 0?void 0:typeof e==`object`?e.mode===void 0?t?{...e,mode:t}:void 0:e:mu(e),Kl=(e=`rgb`)=>t=>(t=Gl(t,e))===void 0?void 0:t.mode===e?t:ql[t.mode][e]?ql[t.mode][e](t):e===`rgb`?ql[t.mode].rgb(t):ql.rgb[e](ql[t.mode].rgb(t)),ql={},Jl={},Yl=[],Xl={},Zl=e=>e,Ql=e=>(ql[e.mode]={...ql[e.mode],...e.toMode},Object.keys(e.fromMode||{}).forEach(t=>{ql[t]||(ql[t]={}),ql[t][e.mode]=e.fromMode[t]}),e.ranges||={},e.difference||={},e.channels.forEach(t=>{if(e.ranges[t]===void 0&&(e.ranges[t]=[0,1]),!e.interpolate[t])throw Error(`Missing interpolator for: ${t}`);typeof e.interpolate[t]==`function`&&(e.interpolate[t]={use:e.interpolate[t]}),e.interpolate[t].fixup||(e.interpolate[t].fixup=Zl)}),Jl[e.mode]=e,(e.parse||[]).forEach(t=>{eu(t,e.mode)}),Kl(e.mode)),$l=e=>Jl[e],eu=(e,t)=>{if(typeof e==`string`){if(!t)throw Error(`'mode' required when 'parser' is a string`);Xl[e]=t}else typeof e==`function`&&Yl.indexOf(e)<0&&Yl.push(e)},tu=/[^\x00-\x7F]|[a-zA-Z_]/,nu=/[^\x00-\x7F]|[-\w]/,I={Function:`function`,Ident:`ident`,Number:`number`,Percentage:`percentage`,ParenClose:`)`,None:`none`,Hue:`hue`,Alpha:`alpha`},L=0;function ru(e){let t=e[L],n=e[L+1];return t===`-`||t===`+`?/\d/.test(n)||n===`.`&&/\d/.test(e[L+2]):t===`.`?/\d/.test(n):/\d/.test(t)}function iu(e){if(L>=e.length)return!1;let t=e[L];if(tu.test(t))return!0;if(t===`-`){if(e.length-L<2)return!1;let t=e[L+1];return!!(t===`-`||tu.test(t))}return!1}var au={deg:1,rad:180/Math.PI,grad:9/10,turn:360};function ou(e){let t=``;if((e[L]===`-`||e[L]===`+`)&&(t+=e[L++]),t+=su(e),e[L]===`.`&&/\d/.test(e[L+1])&&(t+=e[L++]+su(e)),(e[L]===`e`||e[L]===`E`)&&((e[L+1]===`-`||e[L+1]===`+`)&&/\d/.test(e[L+2])?t+=e[L++]+e[L++]+su(e):/\d/.test(e[L+1])&&(t+=e[L++]+su(e))),iu(e)){let n=cu(e);return n===`deg`||n===`rad`||n===`turn`||n===`grad`?{type:I.Hue,value:t*au[n]}:void 0}return e[L]===`%`?(L++,{type:I.Percentage,value:+t}):{type:I.Number,value:+t}}function su(e){let t=``;for(;/\d/.test(e[L]);)t+=e[L++];return t}function cu(e){let t=``;for(;L<e.length&&nu.test(e[L]);)t+=e[L++];return t}function lu(e){let t=cu(e);return e[L]===`(`?(L++,{type:I.Function,value:t}):t===`none`?{type:I.None,value:void 0}:{type:I.Ident,value:t}}function uu(e=``){let t=e.trim(),n=[],r;for(L=0;L<t.length;)if(r=t[L++],r===`
|
|
48
|
+
`,bc=new Map,xc=0,Sc=96,Cc=new Map;function wc(){return[...bc.values()].reduce((e,t)=>e+t.bytes,0)+Cc.size*Sc*Sc*4}function Tc(e){let t=Cc.get(e);if(t)return t;let n=new Float32Array(9216),r=new Float32Array(1024);for(let t=0;t<r.length;t++)r[t]=us(e+71,t);let i=(e,t)=>{let n=Math.floor(e),i=Math.floor(t),a=e-n,o=t-i,s=a*a*(3-2*a),c=o*o*(3-2*o),l=(e,t)=>r[(e&31)+(t&31)*32];return(l(n,i)*(1-s)+l(n+1,i)*s)*(1-c)+(l(n,i+1)*(1-s)+l(n+1,i+1)*s)*c};for(let e=0;e<Sc;e++)for(let t=0;t<Sc;t++){let r=(t+.5)/Sc,a=(e+.5)/Sc,o=i(r*3+2,a*3+4)*.52+i(r*7+7,a*7+3)*.3+i(r*17,a*17)*.18,s=(r-.5)*2,c=(a-.5)*2,l=Math.hypot(s+(i(r*4,a*4)-.5)*.27,c+(i(r*4+5,a*4)-.5)*.27),u=Math.max(0,Math.min(1,(1-l)*3.5)),d=Math.max(0,o-.24)**1.4*u*u*(3-2*u);n[e*Sc+t]=d}return Cc.set(e,n),n}function Ec(e,t,n){let r=`${t}:${n}`,i=bc.get(r);if(i)return i.used=++xc,i.canvas;let a;if(typeof OffscreenCanvas<`u`)a=new OffscreenCanvas(Sc,Sc);else if(typeof document<`u`)a=document.createElement(`canvas`),a.width=a.height=Sc;else try{a=new e.canvas.constructor(Sc,Sc)}catch{return null}let o=a.getContext(`2d`);if(!o)return null;o.fillStyle=t,o.fillRect(0,0,1,1);let s=o.getImageData(0,0,1,1).data,c=o.createImageData(Sc,Sc),l=Tc(n);for(let e=0;e<l.length;e++)c.data[e*4]=s[0],c.data[e*4+1]=s[1],c.data[e*4+2]=s[2],c.data[e*4+3]=Math.round(l[e]*255);if(o.putImageData(c,0,0),bc.size>=64){let e=``,t=1/0;for(let[n,r]of bc)r.used<t&&(e=n,t=r.used);bc.delete(e)}return bc.set(r,{canvas:a,used:++xc,bytes:36864}),a}function Dc(e,t,n,r,i,a=[]){let o=t.dust??ds(t.x,t.y,t.size,t.seed),s=e.globalAlpha;for(let c of o.parcels){let o=c.radius*c.spread,l=c.z*.22;if(c.x+o*2<n.x||c.x-o*2>n.x+n.width||c.y+o*2<n.y||c.y-l-o*2>n.y+n.height)continue;let u=Math.max(0,Math.min(1,(c.z-1)/7)),d=i===`ground`?1-u:u;if(d===0)continue;let f=r?.12:.7,p=-2.3;for(let e of a){let t=vc(e,c);t>f&&(f=t,p=Math.atan2(e.point.y-c.y,e.point.x-c.x))}let m=Ec(e,t.color,c.seed&3);e.save(),e.translate(c.x,c.y-l);let h=Math.hypot(c.vx,c.vy),g=Math.atan2(Math.sin(Math.atan2(c.vy,c.vx)-c.angle),Math.cos(Math.atan2(c.vy,c.vx)-c.angle));e.rotate(c.angle+g*Math.min(.6,h/100));let _=Math.sqrt(1+Math.min(.8,h/220));if(e.globalAlpha=s*t.opacity*d*(c.mass*9)*.55/(c.spread*c.spread),m)e.drawImage(m,-o*_,-o/_,o*2*_,o*2/_);else{let n=e.createRadialGradient(0,0,0,0,0,o);n.addColorStop(0,t.color),n.addColorStop(1,`transparent`),e.fillStyle=n,e.fillRect(-o,-o,o*2,o*2)}m&&f>.8&&(e.globalCompositeOperation=`screen`,e.globalAlpha*=Math.min(.6,(f-.8)*.2),e.drawImage(m,-o*_,-o/_,o*2*_,o*2/_),e.globalCompositeOperation=`source-over`),e.restore();let v=t.glint??.12;if(v<=0||us(c.seed,45)>.42)continue;let y=Math.max(0,Math.cos(c.angle*2+p+us(c.seed,47)*6.28))**48,b=Math.min(1,v*5)*y*Math.min(1,f)*d*s*t.opacity;if(b<.035)continue;let x=c.x+(us(c.seed,49)-.5)*o*.7,S=c.y-l+(us(c.seed,51)-.5)*o*.7,C=.35+b*.7;e.save(),e.globalAlpha=b,e.fillStyle=r?`#fff2ce`:`#fffefa`,e.beginPath(),e.ellipse(x,S,C,C,0,0,Math.PI*2),e.fill(),b>.45&&(e.lineWidth=.35,e.strokeStyle=`#fff5d7`,e.beginPath(),e.moveTo(x-C*2.5,S),e.lineTo(x+C*2.5,S),e.moveTo(x,S-C*2.5),e.lineTo(x,S+C*2.5),e.stroke()),e.restore()}}function Oc(e,t,n){let r=e.size,i=r*.74,a=0,o=0,s=0;for(let c=0;c<6;c++){let l=t*(c+.5)/6*2,u=n*(c+.5)/6*2,d=e.curlX*l*l*l+e.twist*n*2*l*l,f=e.curlY*u*u*u-e.twist*t*1.3*u*u;a+=Math.cos(d)*r*t/6,o+=Math.cos(f)*i*n/6,s+=Math.sin(d)*r*t/6+Math.sin(f)*i*n/6}let c=Math.max(0,t+n-.62);s+=c*c*r*(.35+e.fold);let l=Math.cos(e.tilt),u=Math.sin(e.tilt);return{x:a,y:o*l-s*u,z:o*u+s*l}}var kc=(e,t)=>{let n=Math.imul((e|0)&15^Math.imul(t+17,374761393),668265263);return n=Math.imul(n^n>>>13,1274126177),((n^n>>>16)>>>0)/4294967296},Ac=new Map,jc=new Map;function Mc(e){let t=Ac.get(e);if(t)return t;let n=e.replace(/^#/,``),r=/^[\da-f]{3}$/i.test(n)?[...n].map(e=>e+e).join(``):n,i=/^[\da-f]{6}$/i.test(r)?[0,2,4].map(e=>parseInt(r.slice(e,e+2),16)):e.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/)?.slice(1,4).map(Number)??[195,190,174];return Ac.size>=128&&Ac.delete(Ac.keys().next().value),Ac.set(e,i),i}function Nc(e,t){let n=Math.round(t),r=`${e}:${n}`,i=jc.get(r);if(i)return i;let a=`rgb(${Mc(e).map(e=>Math.max(0,Math.min(255,e+n))).join(` `)})`;return jc.size>=512&&jc.delete(jc.keys().next().value),jc.set(r,a),a}function Pc(e,t){e.beginPath(),t.forEach(([t,n],r)=>{r?e.lineTo(t,n):e.moveTo(t,n)}),e.closePath()}function Fc(e,t,n){let r=Math.max(0,t.z),i=1+Math.min(.65,r/90);e.save(),e.translate(t.x+r*.13,t.y+r*.1),e.rotate(t.angle),e.fillStyle=`#000`,e.globalAlpha=t.opacity*(n?.12:.15)/(1+r/26),e.beginPath(),e.ellipse(0,0,t.size*.46*i,t.size*.27*i,0,0,Math.PI*2),e.fill(),r<5&&(e.globalAlpha*=(1-r/5)*.6,e.beginPath(),e.ellipse(0,0,t.size*.36,t.size*.19,0,0,Math.PI*2),e.fill()),e.restore()}function Ic(e,t){let n=[];for(let e=0;e<=2;e++)n.push(Array.from({length:9},(n,r)=>Oc(t,r/8-.5,e/2-.5)));let r=t.z<.5?Math.max(0,-Math.min(...n.flat().map(e=>e.z))):0,i=e=>[e.x,e.y-(e.z+r)*.48],a=[];for(let e=0;e<2;e++)for(let t=0;t<8;t++){let r=n[e][t],i=n[e][t+1],o=n[e+1][t+1],s=n[e+1][t],c=i.x-r.x,l=i.y-r.y,u=i.z-r.z,d=s.x-r.x,f=s.y-r.y,p=s.z-r.z,m=l*p-u*f,h=u*d-c*p,g=c*f-l*d,_=Math.max(.001,Math.hypot(m,h,g)),v=g+h*.48>0,y=(m*-.35+h*-.45+Math.abs(g)*.7)/_;a.push({a:r,b:i,c:o,d:s,col:t,row:e,front:v,light:y,depth:(r.z+i.z+o.z+s.z)/4})}a.sort((e,t)=>e.depth-t.depth);for(let n of a){let{a:r,b:a,c:o,d:s,front:c,light:l,row:u,col:d}=n;if(Pc(e,[i(r),i(a),i(o),i(s)]),e.fillStyle=Nc(t.color,(c?0:-32)+(l-.7)*45),e.fill(),c&&d>0&&d<(u===0?6:8)&&u<3){e.strokeStyle=Nc(t.color,-100),e.lineWidth=t.size*(u===0?.027:.013);let n=i({x:(r.x+s.x)*.5,y:(r.y+s.y)*.5,z:(r.z+s.z)*.5}),c=i({x:(a.x+o.x)*.5,y:(a.y+o.y)*.5,z:(a.z+o.z)*.5});if(e.beginPath(),e.moveTo(...n),e.lineTo(...c),e.stroke(),u>0){let t=i({x:r.x*.2+s.x*.8,y:r.y*.2+s.y*.8,z:r.z*.2+s.z*.8}),n=i({x:a.x*.2+o.x*.8,y:a.y*.2+o.y*.8,z:a.z*.2+o.z*.8});e.beginPath(),e.moveTo(...t),e.lineTo(...n),e.stroke()}}}}function Lc(e,t){let n=[],r=.72+Math.abs(Math.cos(t.tilt))*.28;for(let e=0;e<9;e++){let i=e/9*Math.PI*2,a=t.size*(.32+kc(t.seed,e+20)*.18);n.push([Math.cos(i)*a,Math.sin(i)*a*r])}let i=[(kc(t.seed,33)-.5)*t.size*.17,(kc(t.seed,34)-.5)*t.size*.18];for(let r=0;r<n.length;r++){Pc(e,[i,n[r],n[(r+1)%n.length]]);let a=(kc(t.seed,r+40)-.45)*72+Math.sin(t.tilt+r)*9;e.fillStyle=Nc(t.color,a),e.fill()}e.strokeStyle=Nc(t.color,-45),e.lineWidth=.35,e.globalAlpha*=.3;for(let r of[1,4,6])e.beginPath(),e.moveTo(...n[r]),e.lineTo(i[0]+t.size*.08,i[1]),e.stroke()}function Rc(e,t){let n=t.size,r=t.size*(.35+kc(t.seed,51)*.25),i=Math.cos(t.tilt);e.scale(1,Math.abs(i)<.1?.1:i),Pc(e,[[-n*.5,-r*.5],[-n*.43,-r*.31],[-n*.49,-r*.08],[-n*.42,r*.12],[-n*.48,r*.48],[-n*.28,r*.38],[n*.3,r*.43],[n*.5,r*.52],[n*.44,r*.21],[n*.5,-r*.02],[n*.43,-r*.22],[n*.49,-r*.52],[n*.28,-r*.38],[-n*.28,-r*.4]]),e.fillStyle=i<0?`#b9c1c3`:Nc(t.color,24),e.fill(),Pc(e,[[-n*.3,-r/2],[n*.3,-r*.43],[n*.21,r*.35],[-n*.2,r*.4]]),e.fillStyle=Nc(t.color,-16),e.fill(),e.fillStyle=`#e4decd`,e.fillRect(-n*.15,-r*.14,n*.27,r*.19),e.strokeStyle=Nc(t.color,65),e.lineWidth=.45,e.globalAlpha*=.45;for(let t of[-1,1])e.beginPath(),e.moveTo(t*n*.3,-r*.35),e.lineTo(t*n*.38,r*.15),e.lineTo(t*n*.27,r*.35),e.stroke()}function zc(e,t){let n=t.size,r=t.size*(.35+kc(t.seed,61)*.2),i=Math.cos(t.tilt);if(e.scale(1,Math.abs(i)<.08?.08:i),e.beginPath(),e.moveTo(-n*.48,0),e.bezierCurveTo(-n*.15,-r*.7,n*.18,-r*.6,n*.5,-r*.08),e.bezierCurveTo(n*.12,r*.65,-n*.25,r*.45,-n*.48,0),e.fillStyle=Nc(t.color,i<0?14:0),e.fill(),e.beginPath(),e.moveTo(-n*.48,0),e.bezierCurveTo(-n*.15,-r*.7,n*.18,-r*.6,n*.5,-r*.08),e.quadraticCurveTo(0,-r*t.fold*.2,-n*.48,0),e.fillStyle=Nc(t.color,-13-t.fold*9),e.fill(),e.strokeStyle=Nc(t.color,-35),e.lineWidth=.45,e.globalAlpha*=.55,e.beginPath(),e.moveTo(-n*.63,r*.08),e.quadraticCurveTo(-n*.08,-r*t.fold*.2,n*.46,-r*.07),e.stroke(),n>10){e.lineWidth=.3;for(let t of[-.18,.08])e.beginPath(),e.moveTo(n*t,0),e.lineTo(n*(t+.1),-r*.3),e.moveTo(n*t,0),e.lineTo(n*(t-.03),r*.28),e.stroke()}}var Bc=new Map,Vc=0,Hc=0,Uc=()=>({sprites:Bc.size,bytes:Vc+wc()});function Wc(e,t){t.kind===`paper`?Ic(e,t):t.kind===`crumpled-paper`?Lc(e,t):t.kind===`trash`?Rc(e,t):t.kind===`leaf`&&zc(e,t)}function Gc(e){if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(e,e);if(typeof document>`u`||typeof HTMLCanvasElement>`u`)return null;let t=document.createElement(`canvas`);return!(t instanceof HTMLCanvasElement)||!t.getContext?null:(t.width=t.height=e,t)}function Kc(e,t,n){if(t.kind===`dust`||t.z>.1||Math.abs(t.vz)>.1||Math.hypot(t.vx,t.vy)>.75||t.kind===`paper`&&Math.abs(t.curlVelocityX)+Math.abs(t.curlVelocityY)+Math.abs(t.twistVelocity)>.03)return!1;let r=Math.max(4,Math.round(t.size/4)*4),i=Math.round(t.fold*5)/5,a=t.kind===`crumpled-paper`?(Math.round(t.tilt/(Math.PI/4))%8+8)%8:Math.cos(t.tilt)<0?4:0,o=a*Math.PI/4;if(t.kind!==`crumpled-paper`&&Math.abs(Math.sin(t.tilt))>.015)return!1;let s=Math.round(t.curlX*4)/4,c=Math.round(t.curlY*4)/4,l=Math.round(t.twist*4)/4,u=`${s}:${c}:${l}:${t.kind}:${t.seed&15}:${t.color}:${r}:${i}:${a}:${n}`,d=Bc.get(u),f={...t,size:r,fold:i,tilt:o,curlX:s,curlY:c,twist:l,opacity:1};if(!d){let e=r*1.4+4,t=Math.ceil(e*n),i=t*t*4;if(Bc.size>=128||Vc+i>8388608){for(let[e,t]of Bc)if(!(Hc-t.used<120)&&(Bc.delete(e),`close`in t.canvas&&t.canvas.close(),Vc-=t.bytes,Bc.size<128&&Vc+i<=8388608))break}if(Bc.size<128&&Vc+i<=8388608){let r=Gc(t),a=r?.getContext(`2d`);r&&a&&(a.scale(n,n),a.translate(e/2,e/2),Wc(a,f),d={canvas:`transferToImageBitmap`in r?r.transferToImageBitmap():r,extent:e,bytes:i,used:Hc},Bc.set(u,d),Vc+=i)}}return e.scale(t.size/r,t.size/r),d?(d.used=Hc,e.drawImage(d.canvas,-d.extent/2,-d.extent/2,d.extent,d.extent)):(e.save(),Wc(e,f),e.restore()),!0}function qc(e,t,n,r,i=`ground`,a=[]){i===`ground`&&Hc++;let o=e.getTransform(),s=Math.min(8,Math.max(1,Math.ceil(Math.hypot(o.a,o.b)))),c=n.x+n.width,l=n.y+n.height;for(let o of t){if(o.opacity<=0)continue;let t=(o.dust?.radius??o.size)+Math.max(0,o.z)*.35;o.x+t<n.x||o.x-t>c||o.y+t<n.y||o.y-t>l||(o.kind===`dust`?Dc(e,o,n,r,i,a):(i===`ground`&&Fc(e,o,r),i===`ground`==o.z<4&&(e.save(),e.translate(o.x,o.y-Math.max(0,o.z)*.22),e.rotate(o.angle),e.globalAlpha=o.opacity,Kc(e,o,s)||Wc(e,o),e.restore())))}}function Jc(e){let{tireLengthM:t,tireWidthM:n}=e.geometry;return e.image?{length:t*(e.image.wheelVisualScale?.length??.64),width:n*(e.image.wheelVisualScale?.width??.82)}:{length:t,width:n}}function Yc(e,t,n,r,i){let a=Kt(t,e.naturalWidth,e.naturalHeight),o=Math.min(1,512/Math.max(a.source.width,a.source.height)),s=document.createElement(`canvas`);s.width=Math.max(1,Math.round(a.source.width*o)),s.height=Math.max(1,Math.round(a.source.height*o));let c=s.getContext(`2d`);if(!c)return null;n?c.drawImage(n,0,0,s.width,s.height):c.drawImage(e,a.source.x,a.source.y,a.source.width,a.source.height,0,0,s.width,s.height),c.globalCompositeOperation=`source-in`,c.fillStyle=`#101916`,c.fillRect(0,0,s.width,s.height);let l=e=>{let t=Math.ceil(e*4),n=a.lengthM*r,o=a.widthM*r,c=document.createElement(`canvas`);c.width=Math.max(1,Math.ceil((n+t*2)*i)),c.height=Math.max(1,Math.ceil((o+t*2)*i));let l=c.getContext(`2d`);return l?(l.filter=`blur(${e*i}px)`,l.drawImage(s,t*i,t*i,n*i,o*i),{canvas:c,padding:t}):null};return{soft:l(6),close:l(1.5),pixelsPerMeter:r,lengthM:a.lengthM,widthM:a.widthM}}var Xc={width:96,height:96},Zc=8,Qc=14;function $c(e,t,n,r=Zc){let{width:i,height:a}=Xc,o=i/2,s=a/2,c=e.x-t.width/2,l=e.y-t.height/2,u=Math.hypot(c,l)||1,d={x:c/u,y:l/u},f=Math.max(0,t.width/2-o-Qc-Zc),p=Math.max(0,t.height/2-s-Qc-(l<0?r:Zc)),m=Math.min(Math.abs(c)?f/Math.abs(c):1/0,Math.abs(l)?p/Math.abs(l):1/0),h={x:t.width/2+c*(Number.isFinite(m)?m:0),y:t.height/2+l*(Number.isFinite(m)?m:0)},g={x:d.x*o,y:d.y*s},_={x:g.x+d.x*Qc,y:g.y+d.y*Qc},v=Math.hypot(Math.max(0,-e.x,e.x-t.width),Math.max(0,-e.y,e.y-t.height))/Math.max(.001,n);return{center:h,direction:d,edge:g,tip:_,distance:v>=1e3?`${(v/1e3).toFixed(1)} km away`:`${Math.max(1,Math.round(v))} m away`,width:i,height:a}}var el=class{camera;constructor(e){this.camera=e}captureState(){return E({previousCarVelocity:this.previousCarVelocity,poseOffset:this.poseOffset,poseVelocity:this.poseVelocity,poseForce:this.poseForce,wheelPhase:this.wheelPhase})}restoreState(e){let t=E(e);this.previousCarVelocity=t.previousCarVelocity,this.poseOffset=t.poseOffset,this.poseVelocity=t.poseVelocity,this.poseForce=t.poseForce,this.wheelPhase=t.wheelPhase,this.clearMaterials()}clearMaterials(){this.carImages.clear(),this.pristineShadows=new WeakMap,this.deformedShadows=new WeakMap}reset(){this.markers=[],this.previousCarVelocity=null,this.poseOffset=D(),this.poseVelocity=D(),this.poseForce=D(),this.wheelPhase=[0,0,0,0]}carImages=new Map;pristineShadows=new WeakMap;deformedShadows=new WeakMap;previousCarVelocity=null;poseOffset=D();poseVelocity=D();poseForce=D();wheelPhase=[0,0,0,0];carVisualOffset(e){return A(N(D(this.poseOffset.x,-this.poseOffset.y),-e.body.angle),this.camera.zoom)}updateCarPose(e,t){if(e.mode!==`car`){this.previousCarVelocity=null,this.poseOffset=D(),this.poseVelocity=D(),this.poseForce=D();return}let n=e.body.velocity,r=this.previousCarVelocity?A(k(n,this.previousCarVelocity),1/Math.max(t,1e-4)):D();this.previousCarVelocity={...n};let i=N(r,-e.body.angle),a=1-Math.exp(-t/.11);this.poseForce=O(this.poseForce,A(k(D(P(i.x,-15,15),P(i.y,-15,15)),this.poseForce),a));let o=D(P(-this.poseForce.x*.006,-.055,.055),0);this.poseVelocity=O(this.poseVelocity,A(k(A(k(o,this.poseOffset),65),A(this.poseVelocity,15)),t)),this.poseOffset=O(this.poseOffset,A(this.poseVelocity,t)),e.car.tires.forEach((n,r)=>{this.wheelPhase[r]=(this.wheelPhase[r]+t*Math.abs(n.wheelSurfaceSpeedMps)/Math.max(.18,e.car.preset.geometry.tireLengthM*.45))%1})}line(e,t,n,r,i=1){let a=this.camera.screen(t),o=this.camera.screen(n);e.strokeStyle=r,e.lineWidth=i,e.beginPath(),e.moveTo(a.x,a.y),e.lineTo(o.x,o.y),e.stroke()}outline(e,t,n){e.beginPath(),t.forEach((t,n)=>{let r=this.camera.screen(t);n?e.lineTo(r.x,r.y):e.moveTo(r.x,r.y)}),e.closePath(),e.fillStyle=`${n}15`,e.fill(),e.strokeStyle=n,e.lineWidth=2,e.stroke()}imageFor(e){let t=e.image?.src;if(!t)return null;let n=this.carImages.get(t);return n||(n=new Image,n.crossOrigin=`anonymous`,n.src=t,this.carImages.set(t,n)),n.complete&&n.naturalWidth?n:null}markers=[];markerAt(e){return[...this.markers].reverse().find(t=>Math.hypot(e.x-t.x,e.y-t.y)<=t.width/2+3)?.vehicle??null}drawVehicleMarkers(e,t,n,r){if(this.markers=[],n)for(let n of t){let{sim:i}=n;if(i.mode!==`car`||i.car.explodedAt!==null)continue;let a=O(this.camera.screen(i.body.position),n===t[0]?this.carVisualOffset(i):D()),o=Math.max(i.car.preset.geometry.lengthM,i.car.preset.geometry.widthM)*this.camera.zoom*.5;if(a.x+o>=0&&a.x-o<=this.camera.width&&a.y+o>=0&&a.y-o<=this.camera.height)continue;let s=$c(a,this.camera,this.camera.zoom,this.camera.overlay?84:8),{width:c,height:l}=s,{x:u,y:d}=s.center;this.markers.push({vehicle:n,x:u,y:d,width:c,height:l});let f=n===r,p=f?`#f05a4f`:`#a9c5d4`;e.save(),e.translate(u,d),e.shadowColor=`#0000004a`,e.shadowBlur=16,e.shadowOffsetY=4,e.fillStyle=`#192126f5`,e.beginPath(),e.arc(0,0,c/2,0,Math.PI*2),e.fill(),e.shadowColor=`transparent`,e.strokeStyle=`#ffffff40`,e.lineWidth=1,e.stroke();let m=this.imageFor(i.car.preset);if(e.save(),e.translate(0,-11),e.rotate(-i.body.angle),m){let t=Kt(i.car.preset,m.naturalWidth,m.naturalHeight),n=52*t.widthM/t.lengthM;e.drawImage(m,t.source.x,t.source.y,t.source.width,t.source.height,-26,-n/2,52,n)}else e.fillStyle=`#edf2f2`,e.beginPath(),e.roundRect(-15,-6,30,12,5),e.fill();e.restore(),e.fillStyle=`#f7f9fa`,e.font=`700 10px ui-sans-serif, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(f?`YOUR CAR`:`AI CAR`,0,25),e.fillStyle=`#b6c4c9`,e.font=`500 9px ui-sans-serif, system-ui, sans-serif`,e.fillText(s.distance,0,38);let{direction:h,edge:g,tip:_}=s;e.strokeStyle=p,e.lineWidth=2.5,e.lineCap=`round`,e.beginPath(),e.moveTo(g.x+h.x*2,g.y+h.y*2),e.lineTo(_.x-h.x*5,_.y-h.y*5),e.stroke(),e.fillStyle=p,e.beginPath(),e.moveTo(_.x,_.y),e.lineTo(_.x-h.x*9-h.y*5,_.y-h.y*9+h.x*5),e.lineTo(_.x-h.x*9+h.y*5,_.y-h.y*9-h.x*5),e.closePath(),e.fill(),e.restore()}}shadowFor(e,t,n){let r=this.imageFor(e);if(!r)return null;let i=Kt(e,r.naturalWidth,r.naturalHeight),a=t?.spriteFor(r,i)??null,o=Math.max(1,Math.round(this.camera.zoom/2)*2),s=`${JSON.stringify(e.image?.crop)}|${e.image?.scale}|${e.geometry.lengthM}:${e.geometry.widthM}|${o}:${n}`;if(t&&a){let i=`${s}|${t.geometryRevision}`,c=this.deformedShadows.get(t);if(c?.image===r&&c.key===i)return c.shadow;let l=Yc(r,e,a,o,n);return this.deformedShadows.set(t,{image:r,key:i,shadow:l}),l}let c=this.pristineShadows.get(r);c||(c=new Map,this.pristineShadows.set(r,c));let l=c.get(s);return l||(l=Yc(r,e,a,o,n),c.set(s,l),c.size>12&&c.delete(c.keys().next().value)),l}vehicleBodyPath(e,t,n,r,i){if(!i?.hasDamage){e.roundRect(-t/2,-n/2,t,n,r);return}let a=Math.min(r,n/2),o=[{x:t/2-a,y:-n/2+a,start:-Math.PI/2},{x:t/2-a,y:n/2-a,start:0},{x:-t/2+a,y:n/2-a,start:Math.PI/2},{x:-t/2+a,y:-n/2+a,start:Math.PI}],s=!0;for(let t of o)for(let n=0;n<=8;n++){let r=t.start+n*Math.PI/16,o=D(t.x+Math.cos(r)*a,t.y+Math.sin(r)*a),c=i.point(A(o,1/this.camera.zoom)),l=c.x*this.camera.zoom,u=c.y*this.camera.zoom;s?(e.moveTo(l,u),s=!1):e.lineTo(l,u)}e.closePath()}carGround(e,t,n,r,i){performance.now();let a=t.body,o=t.car.preset.geometry,s=this.camera.screen(a.position),c=o.lengthM*this.camera.zoom,l=o.widthM*this.camera.zoom,u=P(M(this.poseForce)/13,0,1),d=e.globalAlpha;e.save(),e.translate(s.x,s.y),e.rotate(-a.angle),e.save(),e.translate(-this.poseOffset.x*this.camera.zoom*.2+2,this.poseOffset.y*this.camera.zoom*.2+4);let f=i?this.shadowFor(t.car.preset,n,r):null;if(f){let t=f.lengthM*this.camera.zoom,n=f.widthM*this.camera.zoom,r=this.camera.zoom/f.pixelsPerMeter,i=(i,a)=>{let o=i.padding*r;e.drawImage(i.canvas,-t/2-o,-n/2+a-o,t+o*2,n+o*2)};e.globalAlpha=d*(.43+u*.05),f.soft&&i(f.soft,3),e.globalAlpha=d*.14,f.close&&i(f.close,2)}else if(i){e.fillStyle=`rgba(13, 20, 20, ${.18+u*.045})`,e.shadowColor=`rgba(8, 14, 16, 0.43)`,e.shadowBlur=12+u*5,e.shadowOffsetY=2,e.beginPath();let r=t.car.preset.visual,i=r?l*.86:l*.84,a=r?r.shape===`suv`?9:r.shape===`supercar`?24:19:l*.34;this.vehicleBodyPath(e,r?c:c*.96,i,a,n),e.fill()}e.restore(),t.car.tires.forEach((n,r)=>{let i=Jc(t.car.preset),o=i.length*this.camera.zoom,s=i.width*this.camera.zoom;e.save(),e.translate(n.local.x*this.camera.zoom,-n.local.y*this.camera.zoom),e.rotate(-n.angle),e.fillStyle=`#121719`,e.beginPath(),e.roundRect(-o/2,-s/2,o,s,Math.min(3.5,s*.33)),e.fill(),e.save(),e.beginPath(),e.roundRect(-o/2+1,-s/2+1,o-2,s-2,Math.min(3,s*.3)),e.clip();let c=this.wheelPhase[r]??0,l=n.spinning?1:P(M(a.velocity)/24,0,.65),u=Math.max(4.2,o/4);e.strokeStyle=n.spinning?`rgba(170, 181, 178, 0.38)`:`rgba(125, 139, 137, 0.34)`,e.lineWidth=n.spinning?2:1.25;for(let t=-3;t<=4;t++){let n=t*u+c*u;e.beginPath(),e.moveTo(n-l*2,-s*.31),e.lineTo(n+l*2,s*.31),e.stroke()}l>.2&&(e.fillStyle=`rgba(137, 150, 147, ${.08+l*.1})`,e.fillRect(-o*.4,-s*.09,o*.8,s*.18)),e.restore(),e.strokeStyle=`rgba(6, 10, 11, 0.8)`,e.lineWidth=1.2,e.beginPath(),e.roundRect(-o/2,-s/2,o,s,Math.min(3.5,s*.33)),e.stroke(),e.restore()}),e.restore()}car(e,t,n,r,i){let a=n.car.preset,o=a.geometry,s=this.imageFor(a);if(s){let n=this.camera.screen(t.position),o=Kt(a,s.naturalWidth,s.naturalHeight),c=r?.spriteFor(s,o);e.save(),e.translate(n.x,n.y),e.rotate(-t.angle),qa(e,a,this.camera.zoom,o.lengthM,o.widthM,i),c?e.drawImage(c,-o.lengthM*this.camera.zoom/2,-o.widthM*this.camera.zoom/2,o.lengthM*this.camera.zoom,o.widthM*this.camera.zoom):e.drawImage(s,o.source.x,o.source.y,o.source.width,o.source.height,-o.lengthM*this.camera.zoom/2,-o.widthM*this.camera.zoom/2,o.lengthM*this.camera.zoom,o.widthM*this.camera.zoom),e.restore();return}if(a.visual){this.styledCar(e,t,n,r);return}let c=o.lengthM/2,l=o.widthM/2,u=[D(-c,-l),D(c,-l),D(c,l),D(-c,l)].map(e=>t.world(e));this.outline(e,u,`#8ce6c5`),this.line(e,t.world(D(o.wheelbaseM/4,-o.trackWidthM/2)),t.world(D(o.wheelbaseM/4,o.trackWidthM/2)),`#8ce6c5`,2),this.center(e,t,`#8ce6c5`)}exhaustOutlets(e){let t=e.car.preset,n=this.imageFor(t),r=n?Kt(t,n.naturalWidth,n.naturalHeight).lengthM:t.geometry.lengthM,i=t.exhaust.layout,a=t.geometry.widthM*.3;return(i===`left-right`?[-a,a]:i===`left`?[-a]:i===`right`?[a]:[0]).map(e=>D(-r/2-.025,e))}exhaust(e,t){let n=this.camera.screen(t.body.position);e.save(),e.translate(n.x,n.y),e.rotate(-t.body.angle);let r=this.exhaustOutlets(t);for(let t of r)e.fillStyle=`rgba(25, 31, 33, 0.62)`,e.beginPath(),e.ellipse(t.x*this.camera.zoom,-t.y*this.camera.zoom,Math.max(1.3,this.camera.zoom*.065),Math.max(1.2,this.camera.zoom*.055),0,0,Math.PI*2),e.fill();e.restore()}styledCar(e,t,n,r){let{geometry:i,visual:a}=n.car.preset;if(!a)return;let o=this.camera.screen(t.position),s=i.lengthM*this.camera.zoom,c=i.widthM*this.camera.zoom*.86,l=a.shape===`suv`?9:a.shape===`supercar`?24:19;e.save(),e.translate(o.x,o.y),e.rotate(-t.angle),e.beginPath(),this.vehicleBodyPath(e,s,c,l,r),e.fillStyle=a.color,e.fill(),e.strokeStyle=`rgba(18, 29, 27, 0.72)`,e.lineWidth=2,e.stroke(),e.fillStyle=`rgba(16, 32, 36, 0.8)`;let u=s*(a.shape===`suv`?.52:a.shape===`supercar`?.32:.4),d=c*(a.shape===`suv`?.72:.64),f=a.shape===`supercar`?-s*.08:-s*.015;e.beginPath(),e.roundRect(f-u/2,-d/2,u,d,a.shape===`suv`?7:14),e.fill(),e.strokeStyle=`rgba(235, 245, 241, 0.58)`,e.lineWidth=2,e.beginPath(),e.moveTo(f+u*.16,-d/2+3),e.lineTo(f+u*.16,d/2-3),e.stroke(),e.fillStyle=`rgba(255, 246, 205, 0.9)`;let p=tt(n.car.preset);for(let t of[-1,1])e.beginPath(),e.ellipse(p.headlights.xM*this.camera.zoom,t*p.headlights.yM*this.camera.zoom,4,3,0,0,Math.PI*2),e.fill();e.fillStyle=`rgba(139, 28, 21, 0.88)`;for(let t of[-1,1])e.fillRect(p.taillights.xM*this.camera.zoom-2,t*p.taillights.yM*this.camera.zoom-3,4,6);e.restore()}ship(e,t,n){let r=n.ship,i=r.craft,a=t.world(r.counterweight);this.line(e,t.world(O(r.counterweight,D(r.radius))),t.world(O(i,D(-.6))),`#ff6262`,2);let o=this.camera.screen(a);e.beginPath(),e.arc(o.x,o.y,r.radius*this.camera.zoom,0,Math.PI*2),e.fillStyle=`#ff626215`,e.fill(),e.strokeStyle=`#ff6262`,e.lineWidth=2,e.stroke();let s=[D(1.2),D(-.6,-.8),D(-.6,.8)].map(e=>t.world(O(i,N(e,r.headAngle))));this.outline(e,s,`#ff6262`),this.center(e,t,`#ff6262`)}brick(e,t){this.outline(e,[D(-2,-1),D(2,-1),D(2,1),D(-2,1)].map(e=>t.world(e)),`#f6bd79`),this.center(e,t,`#f6bd79`)}center(e,t,n){let r=this.camera.screen(t.position);e.fillStyle=n,e.beginPath(),e.arc(r.x,r.y,3,0,Math.PI*2),e.fill(),!this.camera.overlay&&M(t.velocity)>.1&&this.line(e,t.position,O(t.position,A(t.velocity,.35)),`#658da0`)}};function tl(e,t,n){return n?D(n.x+n.width/2,n.y+n.height/2):D(e/2,t/2)}function nl(e,t,n){let r=tl(e,t,n);return Math.ceil(2*Math.hypot(Math.max(r.x,e-r.x),Math.max(r.y,t-r.y)))}function rl(e,t,n,r){return O(n,N(k(e,t),r))}function il(e,t,n,r){return O(t,N(k(e,n),-r))}function al(e,t,n){return A(D(e,t),n/2)}function ol(e,t,n,r){return e+Math.atan2(Math.sin(t-e),Math.cos(t-e))*(r<=0?1:1-Math.exp(-Math.max(0,n)/r))}function sl(e,t,n){return{x:e.x<n?e.x-n:e.x>t.width-n?e.x-(t.width-n):0,y:e.y<n?e.y-n:e.y>t.height-n?e.y-(t.height-n):0}}var cl={};function ll(e,t={x:0,y:0},n=1){let r=Go();return{x:e.left/n+r.x+t.x,y:e.top/n+r.y+t.y,width:e.width/n,height:e.height/n}}var ul={scale:1,viewportRectToDocument:ll},dl=`[data-jr-overlay],[data-jr-ui],[data-jr-touch-controls],[data-jr-embed],script,style,link`,fl=class{scale=1;signature=``;originals=new Map;viewportRectToDocument(e,t={x:0,y:0}){return ll(e,t,this.scale)}apply(e,t){let n=Go(),r=`${e}:${t.x}:${t.y}:${n.x}:${n.y}:${document.body.children.length}`;if(r!==this.signature||cl.owner!==this){this.signature=r;for(let r of Array.from(document.body.children))if(r instanceof HTMLElement&&!r.matches(dl)){if(!this.originals.has(r)){this.originals.set(r,{translate:r.style.translate,scale:r.style.scale,origin:r.style.transformOrigin});let e=0,t=0;for(let n=r;n;n=n.offsetParent)e+=n.offsetLeft,t+=n.offsetTop;r.style.transformOrigin=`${-e}px ${-t}px`}r.style.scale=String(e),r.style.translate=`${n.x-t.x*e}px ${n.y-t.y*e}px`}this.scale=e,cl.owner=this}}clear(){for(let[e,t]of this.originals)e.style.translate=t.translate,e.style.scale=t.scale,e.style.transformOrigin=t.origin;this.originals.clear(),this.signature=``,this.scale=1,cl.owner===this&&(cl.owner=void 0)}};function pl(e,t,n){let r=Math.min(Math.max(1,t.width-32)/Math.max(1,e.width+160),Math.max(1,t.height-32)/Math.max(1,e.height+160));return Math.max(.1,Math.min(3,n??r))}function ml(e,t){let n=null;for(let r of e){let e=r.bounds;t.x<e.x||t.y<e.y||t.x>=e.x+e.width||t.y>=e.y+e.height||(!n||n.element.contains(r.element)||!r.element.contains(n.element)&&e.width*e.height<n.bounds.width*n.bounds.height)&&(n=r)}return n}var hl=class{projection;regions=[];measuredAt=-1/0;constructor(e=ul){this.projection=e}at(e,t,n){return n-this.measuredAt>120&&(this.measuredAt=n,this.regions=Array.from(document.querySelectorAll(`[data-jr-camera],[data-jr-camera-zoom]`)).filter(e=>!e.closest(`[data-jr-ui],[data-jr-overlay]`)).flatMap(e=>{let n=e.getAttribute(`data-jr-camera`);if(n!==null&&n!==`fixed`&&n!==`follow`)return[];let r=this.projection.viewportRectToDocument(e.getBoundingClientRect(),t);if(r.width<=0||r.height<=0)return[];let i=e.getAttribute(`data-jr-camera-zoom`),a=i?.trim()?Number(i):NaN;return n===null&&(!Number.isFinite(a)||a<=0)?[]:[{element:e,bounds:r,fixed:n===`fixed`,zoom:Number.isFinite(a)&&a>0?a:void 0}]})),ml(this.regions.filter(e=>e.element.isConnected),e)}reset(){this.regions=[],this.measuredAt=-1/0}},gl={minimumScale:.58,startsAtMps:3,fullAtMps:20,responsePerSecond:4};function _l(e,t,n,r,i){return e===`auto`?t&&!n&&(r.x<0||r.y<0||r.x>i.width||r.y>i.height):e}var vl=class{overlay;canvasWorld;requestResize;constructor(e,t,n){this.overlay=e,this.canvasWorld=t,this.requestResize=n,e&&(this.originScroll=D(window.scrollX,window.scrollY),this.observedScroll={...this.originScroll},this.pageSize={width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight})}resize(){this.requestResize()}get pixelSpace(){return this.overlay||this.canvasWorld}get timeSeconds(){return this.lastFrame/1e3}rebaseTime(e){this.lastFrame=e}captureState(){return E({outputWidth:this.outputWidth,outputHeight:this.outputHeight,cameraRotation:this.cameraRotation,cameraLock:this.cameraLock,cameraSmoothing:this.cameraSmoothing,cameraLockInitialized:this.cameraLockInitialized,width:this.width,height:this.height,dpr:this.dpr,smokeMargin:this.smokeMargin,regionScale:this.regionScale,canvasWorldScale:this.canvasWorldScale,cameraFrame:this.cameraFrame,camera:this.camera,zoom:this.zoom,baseZoom:this.baseZoom,speedScale:this.speedScale,slowMoScale:this.slowMoScale,zoomAnchor:this.zoomAnchor,pageSize:this.pageSize,lastFrame:this.lastFrame,speedSamples:this.speedSamples,originScroll:this.originScroll,observedScroll:this.observedScroll,virtualScroll:this.virtualScroll,followInterrupted:this.followInterrupted,deadZone:this.deadZone,speedZoom:this.speedZoom,speedZoomMinimumScale:this.speedZoomMinimumScale})}restoreState(e){let t=E(e);this.vehicleReveal=null,this.outputWidth=t.outputWidth,this.outputHeight=t.outputHeight,this.cameraRotation=t.cameraRotation,this.cameraLock=t.cameraLock,this.cameraSmoothing=t.cameraSmoothing,this.cameraLockInitialized=t.cameraLockInitialized,this.width=t.width,this.height=t.height,this.dpr=t.dpr,this.smokeMargin=t.smokeMargin,this.regionScale=t.regionScale,this.canvasWorldScale=t.canvasWorldScale,this.cameraFrame=t.cameraFrame,this.camera=t.camera,this.zoom=t.zoom,this.baseZoom=t.baseZoom,this.speedScale=t.speedScale,this.slowMoScale=t.slowMoScale,this.zoomAnchor=t.zoomAnchor,this.pageSize=t.pageSize,this.lastFrame=t.lastFrame,this.speedSamples=t.speedSamples,this.originScroll=t.originScroll,this.observedScroll=t.observedScroll,this.virtualScroll=t.virtualScroll,this.followInterrupted=t.followInterrupted,this.deadZone=t.deadZone,this.speedZoom=t.speedZoom,this.speedZoomMinimumScale=t.speedZoomMinimumScale}restorePresentation(){this.setVirtualScroll({...this.virtualScroll}),this.overlay&&(window.scrollTo(this.observedScroll.x,this.observedScroll.y),Ko(),this.resize(),this.cameraRegions.reset(),this.activeCameraRegion||this.regionScale!==1?this.pageScene.apply(this.regionScale,this.sceneScroll()):this.pageScene.clear())}reset(){this.vehicleReveal=null,this.camera=D(),this.cameraLockInitialized=!1,this.speedScale=1,this.slowMoZoom=1,this.zoomAnchor=D(),this.overlay&&(this.pageSize={width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight}),this.pageScene.clear(),this.activeCameraRegion=null,this.cameraRegions.reset(),this.regionScale=this.canvasWorld?this.canvasWorldScale:1,this.resize(),this.setVirtualScroll(D()),this.speedSamples=[]}vehicleReveal=null;revealVehicle(e,t=550){this.overlay&&(this.syncScroll(),this.followInterrupted=!0,this.vehicleReveal={sim:e,start:this.sceneScroll(),started:null,duration:t})}advanceVehicleReveal(e,t){let n=this.vehicleReveal;if(!n)return;n.started??=e;let r=n.duration<=0?1:P((e-n.started)/n.duration,0,1),i=r*r*(3-2*r),a=k(this.documentPoint(n.sim.body.position),D(this.width/2,this.height/2));!this.virtualScroll.x&&a.x>=-this.width/2&&a.x<=this.pageSize.width-this.width/2&&(a.x=P(a.x,0,Math.max(0,this.pageSize.width-this.width))),!this.virtualScroll.y&&a.y>=-this.height/2&&a.y<=this.pageSize.height-this.height/2&&(a.y=P(a.y,0,Math.max(0,this.pageSize.height-this.height))),this.moveSceneTo(O(n.start,A(k(a,n.start),i))),r===1&&(this.vehicleReveal=null,n.sim===t&&(this.followInterrupted=!1))}resetFollow(){this.vehicleReveal=null,this.overlay&&(this.originScroll=D(window.scrollX,window.scrollY),this.observedScroll={...this.originScroll},this.followInterrupted=!1)}dispose(){this.vehicleReveal=null,this.pageScene.clear(),this.setVirtualScroll(D()),Ko()}resizeLayout(e,t,n){this.outputWidth=e,this.outputHeight=t;let r=this.canvasWorld&&this.cameraLock,i=r?nl(e,t,this.cameraFrame):0,a=(r?i:e)/this.regionScale,o=(r?i:t)/this.regionScale;this.overlay&&this.width>1&&(a!==this.width||o!==this.height)&&(this.originScroll.x+=(this.width-a)/2,this.originScroll.y+=(this.height-o)/2),this.width=a,this.height=o;let s=Math.min(e,t);this.baseZoom=this.canvasWorld?28:this.overlay?Math.max(14,Math.min(28,s/11)):Math.max(1,Math.min(s<600?32:28,(s-32)/10,s/25)),this.zoom=this.baseZoom*(this.canvasWorld?1:this.speedScale*(this.overlay?1:this.slowMoZoom)),this.overlay&&this.regionScale===1&&!this.virtualScroll.x&&!this.virtualScroll.y&&this.speedScale>.999&&(this.pageSize={width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight}),this.smokeMargin=this.canvasWorld?96/this.regionScale:this.pixelSpace?Math.min(112,Math.max(72,Math.min(this.width,this.height)*.1)):0;let c=this.width*this.height;this.dpr=Math.min(2*(this.canvasWorld?this.regionScale:1),n*this.regionScale,Math.sqrt(24e6/c),16384/Math.max(this.width,this.height))}outputWidth=1;outputHeight=1;cameraRotation=0;cameraLock=!1;cameraSmoothing=.25;cameraLockInitialized=!1;width=1;height=1;dpr=1;smokeMargin=0;pageScene=new fl;cameraRegions=new hl(this.pageScene);get documentProjection(){return this.pageScene}activeCameraRegion=null;regionScale=1;canvasWorldScale=1;cameraFrame=null;camera=D();zoom=28;baseZoom=28;speedScale=1;slowMoScale=1;get slowMoZoom(){return this.slowMoScale??1}set slowMoZoom(e){this.slowMoScale=e}zoomAnchor=D();pageSize={width:1,height:1};lastFrame=0;speedSamples=[];originScroll=D();observedScroll=D();virtualScroll=D();followInterrupted=!1;deadZone=!0;speedZoom=`auto`;speedZoomMinimumScale=gl.minimumScale;screen(e){return D(this.width/2+(e.x-this.camera.x)*this.zoom,this.height/2-(e.y-this.camera.y)*this.zoom)}world(e){return D(this.camera.x+(e.x-this.width/2)/this.zoom,this.camera.y-(e.y-this.height/2)/this.zoom)}vehicleViewportPosition(e){return this.overlay&&this.syncScroll(),this.screen(e)}sceneScroll(){return this.canvasWorld?D(this.camera.x*28-this.width/2,-this.camera.y*28-this.height/2):O(Go(),this.virtualScroll)}virtualOffset(){return{...this.virtualScroll}}documentPoint(e){return this.canvasWorld?an(e):(this.overlay&&this.syncScroll(),O(this.screen(e),this.sceneScroll()))}worldFromDocument(e){return this.canvasWorld?on(e):(this.overlay&&this.syncScroll(),this.world(k(e,this.sceneScroll())))}documentScale(){return this.canvasWorld?28:this.zoom}particlePoint(e){return this.pixelSpace?this.documentPoint(e):{...e}}particleScale(){return this.pixelSpace?this.documentScale():1}viewportSize(){return{width:this.width,height:this.height}}presentationScale(){return this.regionScale}setCanvasWorldScale(e,t=1.5){if(!this.canvasWorld)return;this.canvasWorldScale=Math.max(.2,Math.min(Math.max(.2,Math.min(4,Number.isFinite(t)?t:1.5)),Number.isFinite(e)?e:1));let n=this.canvasWorldScale*this.speedScale*this.slowMoZoom;this.regionScale!==n&&(this.regionScale=n,this.resize())}setCameraFrame(e){this.cameraFrame=e,this.canvasWorld&&this.cameraLock&&this.resize()}setCameraLock(e){this.canvasWorld&&this.cameraLock!==e&&(this.cameraLock=e,this.cameraLockInitialized=!1,e||(this.cameraRotation=0),this.resize())}viewportFromDocument(e){let t=A(k(e,this.sceneScroll()),this.regionScale);return this.canvasWorld&&this.cameraLock?rl(t,al(this.width,this.height,this.regionScale),tl(this.outputWidth,this.outputHeight,this.cameraFrame),this.cameraRotation):t}documentFromViewport(e){return O(A(this.canvasWorld&&this.cameraLock?il(e,al(this.width,this.height,this.regionScale),tl(this.outputWidth,this.outputHeight,this.cameraFrame),this.cameraRotation):e,1/this.regionScale),this.sceneScroll())}bounds(){this.overlay&&this.syncScroll();let e=this.width/(2*this.zoom)-3/this.zoom,t=this.height/(2*this.zoom)-3/this.zoom;return{left:this.camera.x-e,right:this.camera.x+e,bottom:this.camera.y-t,top:this.camera.y+t}}setVirtualScroll(e){if(!this.overlay)return;this.virtualScroll=D(Math.abs(e.x)<.01?0:e.x,Math.abs(e.y)<.01?0:e.y);let t=document.body;this.virtualScroll.x||this.virtualScroll.y?(t.dataset.jrVirtualCamera===void 0&&(t.dataset.jrVirtualCamera=``),t.style.setProperty(`--joy-ride-scene-x`,`${-this.virtualScroll.x}px`),t.style.setProperty(`--joy-ride-scene-y`,`${-this.virtualScroll.y}px`)):(t.dataset.jrVirtualCamera!==void 0&&delete t.dataset.jrVirtualCamera,t.style.removeProperty(`--joy-ride-scene-x`),t.style.removeProperty(`--joy-ride-scene-y`))}syncScroll(e=!1){let t=D(Go().x,Go().y);e||M(k(t,this.observedScroll))>.5&&(this.followInterrupted=!0),this.observedScroll=t,(this.activeCameraRegion||this.regionScale!==1)&&this.pageScene?.apply(this.regionScale,this.sceneScroll());let n=O(t,this.virtualScroll);this.camera=D((n.x-this.originScroll.x-this.zoomAnchor.x*(this.baseZoom-this.zoom))/this.zoom,-(n.y-this.originScroll.y+this.zoomAnchor.y*(this.baseZoom-this.zoom))/this.zoom)}resumeFollow(){this.vehicleReveal=null,this.overlay&&(this.syncScroll(),this.followInterrupted=!1)}interruptFollow(){this.vehicleReveal=null,this.overlay&&(this.followInterrupted=!0)}restorePage(e){if(!this.overlay||!this.virtualScroll.x&&!this.virtualScroll.y&&!this.activeCameraRegion&&this.regionScale===1)return!1;this.syncScroll(!0);let t=A(this.screen(e.body.position),this.regionScale??1);return(this.activeCameraRegion||this.regionScale!==1)&&(this.slowMoZoom=1,this.pageScene.clear(),this.activeCameraRegion=null,this.regionScale=1,this.resize()),this.setVirtualScroll(D()),this.syncScroll(!0),e.body.position=this.world(t),!0}followDocument(e){if(!this.overlay)return!1;if(this.vehicleReveal||this.activeCameraRegion?.fixed)return!0;if(this.zoomAnchor={...e.body.position},this.syncScroll(),this.followInterrupted)return!1;let t=this.screen(e.body.position),n=Math.max(e.car.preset.geometry.lengthM*this.zoom/2+12,Math.min(this.width,this.height)*.25),r=sl(t,{width:this.width,height:this.height},n);if(r.x||r.y){if(e.barrier)window.scrollBy({left:r.x,top:r.y,behavior:`instant`}),Ko();else{let e=D(r.x*this.virtualScroll.x<0?Math.sign(r.x)*Math.min(Math.abs(r.x),Math.abs(this.virtualScroll.x)):0,r.y*this.virtualScroll.y<0?Math.sign(r.y)*Math.min(Math.abs(r.y),Math.abs(this.virtualScroll.y)):0);this.setVirtualScroll(O(this.virtualScroll,e));let t=k(r,e),n=Go();(t.x||t.y)&&(window.scrollBy({left:t.x,top:t.y,behavior:`instant`}),Ko());let i=k(Go(),n);this.setVirtualScroll(O(this.virtualScroll,k(t,i)))}}return this.syncScroll(!0),!0}moveSceneTo(e){window.scrollBy({left:e.x-Go().x,top:e.y-Go().y,behavior:`instant`}),Ko(),this.setVirtualScroll(D(e.x-Go().x,e.y-Go().y)),this.syncScroll(!0)}updateCameraRegion(e,t){let n=this.cameraFrame??{x:0,y:0,width:window.innerWidth,height:window.innerHeight},r=this.activeCameraRegion!==null&&!e,i=e!==null&&this.activeCameraRegion?.element!==e.element,a=(e?e.fixed?pl(e.bounds,n,e.zoom):Math.max(.1,Math.min(3,e.zoom??1)):1)*this.slowMoZoom,o=this.regionScale,s=A(k(t,this.sceneScroll()),o);if(this.activeCameraRegion=e,r&&this.pageScene.clear(),Math.abs(a-this.regionScale)>1e-4&&(this.regionScale=a,this.resize()),e?.fixed){this.speedScale=1,this.zoom=this.baseZoom;let t=e.bounds;this.moveSceneTo(D(t.x+t.width/2-(n.x+n.width/2)/this.regionScale,t.y+t.height/2-(n.y+n.height/2)/this.regionScale))}else(r||i)&&(this.followInterrupted=!1,this.moveSceneTo(D(t.x-this.width/2,t.y-this.height/2)));!e?.fixed&&!r&&!i&&Math.abs(a-o)>1e-4&&this.moveSceneTo(k(t,A(s,1/a))),e||a!==1?this.pageScene.apply(this.regionScale,this.sceneScroll()):this.pageScene.clear()}cameraStep(e,t){let n=this.lastFrame?P((t-this.lastFrame)/1e3,0,.1):1/60;this.lastFrame=t;let r=e.body;if(this.canvasWorld){if(this.cameraLock){let e=r.angle-Math.PI/2,t=!this.cameraLockInitialized||M(k(r.position,this.camera))>40;this.cameraRotation=t?e:ol(this.cameraRotation,e,n,this.cameraSmoothing),t&&(this.camera={...r.position}),this.cameraLockInitialized=!0}else this.cameraRotation=0}let i=M(r.velocity);for(this.speedSamples.push({time:t,speed:i});this.speedSamples.length>2&&this.speedSamples[1].time<t-1e3;)this.speedSamples.shift();let a=0,o=0;for(let e=0;e<this.speedSamples.length-1;e++){let n=Math.max(t-1e3,this.speedSamples[e].time),r=this.speedSamples[e+1].time;a+=this.speedSamples[e].speed*(r-n),o+=r-n}let s=o>0?a/o:i,c=D(this.width/2+r.position.x*this.baseZoom+this.originScroll.x,this.height/2-r.position.y*this.baseZoom+this.originScroll.y),l=this.overlay?this.cameraRegions.at(c,this.virtualScroll,t):null;this.overlay&&this.updateCameraRegion(l,c);let u=!l&&(this.canvasWorld?this.speedZoom===!0:_l(this.speedZoom,this.overlay,e.barrier,c,this.pageSize))?1-(1-(this.speedZoomMinimumScale??gl.minimumScale))*P((s-gl.startsAtMps)/(gl.fullAtMps-gl.startsAtMps),0,1):1;this.speedScale+=(u-this.speedScale)*(1-Math.exp(-gl.responsePerSecond*n));let d=this.zoom;if(this.canvasWorld){let e=this.canvasWorldScale*this.speedScale*this.slowMoZoom;Math.abs(this.regionScale-e)>1e-4&&(this.regionScale=e,this.resize()),this.zoom=this.baseZoom}else this.zoom=this.baseZoom*this.speedScale*(this.overlay?1:this.slowMoZoom);if(this.overlay){this.zoomAnchor={...r.position},this.syncScroll(),this.advanceVehicleReveal(t,e);return}if(e.barrier)return;let f=d/this.zoom;if(this.camera=D(r.position.x-(r.position.x-this.camera.x)*f,r.position.y-(r.position.y-this.camera.y)*f),this.canvasWorld&&this.cameraLock){let e=this.cameraSmoothing<=0?1:1-Math.exp(-n/this.cameraSmoothing);this.camera=O(this.camera,A(k(r.position,this.camera),e));return}if(!this.deadZone){let e=this.canvasWorld&&!this.cameraLock?this.cameraFrame:null;this.camera=e?D(r.position.x-((e.x+e.width/2)/this.regionScale-this.width/2)/this.zoom,r.position.y+((e.y+e.height/2)/this.regionScale-this.height/2)/this.zoom):{...r.position};return}let p=this.width*.18/this.zoom,m=this.height*.18/this.zoom,h=D(r.position.x-P(r.position.x-this.camera.x,-p,p),r.position.y-P(r.position.y-this.camera.y,-m,m));this.camera=O(this.camera,A(k(h,this.camera),1-Math.exp(-16*n)))}},yl=class{canvas;camera;overlay;canvasWorld;sceneCanvas=null;sceneContext;constructor(e,t,n,r){this.canvas=e,this.camera=t,this.overlay=n,this.canvasWorld=r;let i=e.getContext(`2d`);if(!i)throw Error(`Joy Ride requires a 2D canvas context.`);this.sceneContext=i}get context(){return this.sceneContext}resize(){let e=Math.max(1,this.overlay?window.innerWidth:this.canvas.clientWidth),t=Math.max(1,this.overlay?window.innerHeight:this.canvas.clientHeight),n=e/this.camera.regionScale!==this.camera.width||t/this.camera.regionScale!==this.camera.height;this.camera.resizeLayout(e,t,window.devicePixelRatio||1);let r=this.canvasWorld&&this.camera.cameraLock;r?(this.sceneCanvas??=document.createElement(`canvas`),this.sceneContext=this.sceneCanvas.getContext(`2d`)):this.sceneCanvas&&(this.sceneContext=this.canvas.getContext(`2d`)),this.overlay&&(n||this.canvas.style.width!==`${this.camera.width}px`)&&(this.canvas.style.width=`${this.camera.width}px`,this.canvas.style.height=`${this.camera.height}px`,this.canvas.style.transformOrigin=`0 0`,this.canvas.style.scale=String(this.camera.regionScale));let i=Math.round(this.camera.width*this.camera.dpr),a=Math.round(this.camera.height*this.camera.dpr),o=r?this.sceneCanvas:this.canvas;if((o.width!==i||o.height!==a)&&(o.width=i,o.height=a),r){let n=this.camera.dpr/this.camera.regionScale,r=Math.round(e*n),i=Math.round(t*n);this.canvas.width!==r&&(this.canvas.width=r),this.canvas.height!==i&&(this.canvas.height=i)}return this.sceneContext.setTransform(this.camera.dpr,0,0,this.camera.dpr,0,0),this.canvasWorld?this.camera.dpr:void 0}clear(){this.sceneContext.setTransform(this.camera.dpr,0,0,this.camera.dpr,0,0),this.sceneContext.clearRect(0,0,this.camera.width,this.camera.height)}presentLockedCamera(){if(!this.canvasWorld||!this.camera.cameraLock||!this.sceneCanvas)return;let e=this.canvas.getContext(`2d`),t=this.camera.dpr/this.camera.regionScale,n=tl(this.camera.outputWidth,this.camera.outputHeight,this.camera.cameraFrame);e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,this.canvas.width,this.canvas.height),e.save(),e.translate(n.x*t,n.y*t),e.rotate(this.camera.cameraRotation),e.drawImage(this.sceneCanvas,-this.sceneCanvas.width/2,-this.sceneCanvas.height/2),e.restore()}dispose(){this.sceneCanvas&&=(this.sceneCanvas.width=1,this.sceneCanvas.height=1,null),this.canvas.style.scale=``,this.canvas.style.transformOrigin=``}},bl=class{frameRate=new qo;captureState(){return this.frameRate.captureState()}restoreState(e){this.frameRate.restoreState(e)}draw(e,t,n,r,i){let a=e,o=t.body,s=this.frameRate.sample(n);a.save();let c=Jc(t.car.preset);for(let e of t.car.tires){let t=r(o.world(e.local));a.strokeStyle=e.front?`#00dcff`:`#ffae31`,a.lineWidth=2;let n=[D(-c.length/2,-c.width/2),D(c.length/2,-c.width/2),D(c.length/2,c.width/2),D(-c.length/2,c.width/2)].map(t=>r(o.world(O(e.local,N(t,e.angle)))));a.beginPath(),n.forEach((e,t)=>t?a.lineTo(e.x,e.y):a.moveTo(e.x,e.y)),a.closePath(),a.stroke(),a.beginPath(),a.arc(t.x,t.y,4,0,Math.PI*2),a.stroke(),a.beginPath(),a.moveTo(t.x-7,t.y),a.lineTo(t.x+7,t.y),a.moveTo(t.x,t.y-7),a.lineTo(t.x,t.y+7),a.stroke(),a.font=`bold 10px ui-monospace, SFMono-Regular, monospace`,a.fillStyle=e.front?`#007e91`:`#895000`,a.fillText(`${e.front?`F`:`R`}${e.local.y>0?`L`:`R`}${e.skidding?` SKID`:``}`,t.x+8,t.y-8)}let l=r(o.position),u=(e,t,n)=>{let r=O(l,A(e,n));a.strokeStyle=t,a.fillStyle=t,a.lineWidth=2.5,a.beginPath(),a.moveTo(l.x,l.y),a.lineTo(r.x,r.y),a.stroke();let i=Math.atan2(e.y,e.x);a.beginPath(),a.moveTo(r.x,r.y),a.lineTo(r.x-Math.cos(i-.5)*9,r.y-Math.sin(i-.5)*9),a.lineTo(r.x-Math.cos(i+.5)*9,r.y-Math.sin(i+.5)*9),a.closePath(),a.fill()};u(D(Math.cos(o.angle),-Math.sin(o.angle)),`#00c4df`,67);let d=M(o.velocity);d>.2&&u(D(o.velocity.x/d,-o.velocity.y/d),`#f05bd6`,48+Math.min(32,d));let f=Math.atan2(o.velocity.y,o.velocity.x),p=Math.atan2(Math.sin(o.angle-f),Math.cos(o.angle-f)),m=Math.max(...t.car.tires.filter(e=>e.front).map(e=>e.gripUtilization)),h=Math.max(...t.car.tires.filter(e=>!e.front).map(e=>e.gripUtilization)),g=t.car.tires.map(e=>`${e.front?`F`:`R`}${e.local.y>0?`L`:`R`} ${e.slipSpeedMps.toFixed(1)}${e.skidding?`*`:``}`).join(` `),_=[`${t.car.preset.name} · ${(d*3.6).toFixed(0)} km/h · ${Math.round(s)} FPS`,`input T ${t.lastInput.throttle} S ${t.lastInput.steer} brake ${Number(t.lastInput.action)}`,`body ${Math.round(o.angle*180/Math.PI)}° travel ${Math.round(f*180/Math.PI)}° slip ${Math.round(p*180/Math.PI)}°`,`front load ${(t.car.frontLoadFraction*100).toFixed(0)}% burnout ${Number(t.car.burnout)} charge ${t.car.boostCharge.toFixed(2)}`,`grip use F ${m.toFixed(2)} R ${h.toFixed(2)} drift ${Number(t.car.drifting)} donut ${Number(t.car.donuting)}`,`drift ${Number(t.car.fastDrifting)} countersteer ${Number(t.car.countersteering)}`,`roof rocket ${i.rocketState}`,`side guns ${i.gunState} · ${i.bulletCount} bullets`,`tire slip m/s ${g}`,`fluid ${i.fluidEngine} ${i.quality} ${i.fluidCols}×${i.fluidRows}`,`shared fire ${i.fireCols}×${i.fireRows} · ${i.groundedFireCount} grounded sources`,`cyan = nose/shape pink = travel amber = walls`,`wheel cyan = front wheel amber = rear violet = letters`];a.fillStyle=`rgba(10, 21, 24, 0.87)`,a.fillRect(12,88,Math.min(430,i.width-24),_.length*18+18),a.font=`12px ui-monospace, SFMono-Regular, monospace`,a.fillStyle=`#f1f5f3`,_.forEach((e,t)=>a.fillText(e,22,110+t*18)),a.restore()}},xl=[.82,.91,1],Sl=[1,.045,.018],Cl=e=>Math.max(0,Math.min(1,e));function wl(e){let t=/^#([\da-f]{6})$/i.exec(e);if(!t)return[.4,.9,1];let n=parseInt(t[1],16);return[(n>>16)/255,(n>>8&255)/255,(n&255)/255]}function Tl(e,t,n){let r=Math.cos(e.angle),i=Math.sin(e.angle);return{x:e.center.x+r*t-i*n,y:e.center.y+i*t+r*n}}var El=class{sprites=new WeakMap;halos=new WeakMap;beam=null;sprite(e){let t=e.image;if(!t||!t.complete||!t.naturalWidth)return null;let n=e.source??{x:0,y:0,width:t.naturalWidth,height:t.naturalHeight},r=e.mounts.taillights.map(t=>`${Math.round(t.x/e.width*1e4)},${Math.round(t.y/e.height*1e4)}`).join(`;`),i=`${n.x},${n.y},${n.width},${n.height}|${r}`,a=this.sprites.get(t);if(a||(a=new Map,this.sprites.set(t,a)),a.has(i))return a.get(i)??null;let o=document.createElement(`canvas`);o.width=192,o.height=Math.max(24,Math.round(192*n.height/n.width));let s=o.getContext(`2d`,{willReadFrequently:!0});if(!s)return a.set(i,null),null;s.drawImage(t,n.x,n.y,n.width,n.height,0,0,o.width,o.height);let c;try{c=s.getImageData(0,0,o.width,o.height)}catch{return a.set(i,null),null}let l=s.createImageData(o.width,o.height),u=0;for(let t=0;t<o.height;t++)for(let n=0;n<o.width;n++){let r=(t*o.width+n)*4,i=c.data[r],a=c.data[r+1],s=c.data[r+2],d=c.data[r+3];n<o.width*.27&&i>100&&i>a*1.6&&i>s*1.5&&d>100&&e.mounts.taillights.some(r=>{let i=n-(.5+r.x/e.width)*o.width,a=t-(.5+r.y/e.height)*o.height;return i*i+a*a<(o.height*.18)**2})&&(l.data[r]=255,l.data[r+1]=22,l.data[r+2]=5,l.data[r+3]=Math.min(235,d),u++),c.data[r]=255,c.data[r+1]=255,c.data[r+2]=255,c.data[r+3]=d>90?255:0}s.putImageData(c,0,0);let d=null;u>1&&u<o.width*o.height*.055&&(d=document.createElement(`canvas`),d.width=o.width,d.height=o.height,d.getContext(`2d`)?.putImageData(l,0,0));let f={silhouette:o,brakes:d};return a.size>=8&&a.clear(),a.set(i,f),f}halo(e,t){let n=this.halos.get(e);n||(n=new Map,this.halos.set(e,n));let r=n.get(t);if(r)return r;let i=document.createElement(`canvas`);i.width=e.width+64,i.height=e.height+64;let a=i.getContext(`2d`);a.drawImage(e,32,32),a.globalCompositeOperation=`source-in`,a.fillStyle=t,a.fillRect(0,0,i.width,i.height),a.globalCompositeOperation=`source-over`;let o=document.createElement(`canvas`);o.width=i.width,o.height=i.height,o.getContext(`2d`).drawImage(i,0,0),a.clearRect(0,0,i.width,i.height),a.filter=`blur(14px)`,a.globalAlpha=.92,a.drawImage(o,-2,-5,o.width+4,o.height+10),a.filter=`blur(7px)`,a.globalAlpha=.9,a.drawImage(o,0,0),a.filter=`blur(3px)`,a.globalAlpha=.8,a.strokeStyle=t,a.lineWidth=3,a.lineCap=`round`;for(let t of[-1,1])a.beginPath(),a.moveTo(32+e.width*.18,32+e.height*(.5+t*.34)),a.lineTo(32+e.width*.82,32+e.height*(.5+t*.34)),a.stroke();return a.filter=`none`,a.globalAlpha=1,n.size>8&&n.clear(),n.set(t,i),i}beamImage(){if(this.beam)return this.beam;let e=document.createElement(`canvas`);e.width=256,e.height=128;let t=e.getContext(`2d`),n=t.createImageData(e.width,e.height);for(let t=0;t<e.height;t++)for(let r=0;r<e.width;r++){let i=r/e.width,a=(t/e.height-.5)*2,o=.035+i*.94,s=Cl((1-i)/.4),c=Math.exp(-a*a/(o*o))*s*s*(3-2*s),l=(t*e.width+r)*4;n.data[l]=210,n.data[l+1]=230,n.data[l+2]=255,n.data[l+3]=Math.round(c*255)}return t.putImageData(n,0,0),this.beam=e,e}ground(e,t){let n=t.opacity??1,r=t.options.brakeLights?Cl(t.braking):0;if(!(n<=0||t.width<=0)){if(e.save(),e.translate(t.center.x,t.center.y),e.rotate(t.angle),e.globalCompositeOperation=`screen`,t.dark&&t.options.underglow&&t.options.underglowOpacity>0){let r=this.sprite(t);if(e.globalAlpha=Cl(t.options.underglowOpacity)*n,r){let n=this.halo(r.silhouette,t.options.underglowColor),i=32/r.silhouette.width*t.width,a=32/r.silhouette.height*t.height;e.drawImage(n,-t.width/2-i,-t.height/2-a,t.width+i*2,t.height+a*2)}else e.shadowColor=t.options.underglowColor,e.shadowBlur=t.height*.5,e.fillStyle=t.options.underglowColor,e.beginPath(),e.roundRect(-t.width*.43,-t.height*.38,t.width*.86,t.height*.76,t.height*.22),e.fill(),e.shadowBlur=0}if(t.dark&&t.options.headlights)for(let r of t.mounts.headlights)e.globalAlpha=.085*n,e.drawImage(this.beamImage(),r.x,r.y-t.width*.68,t.width*5.7,t.width*1.36);if(t.dark&&t.options.taillights||r>0){let i=r;for(let{x:r,y:a}of t.mounts.taillights){let o=t.height*(.48+i*.38),s=e.createRadialGradient(r,a,0,r,a,o),c=(t.dark?.12+i*.19:i*.13)*n;s.addColorStop(0,`rgba(255,30,8,${c})`),s.addColorStop(1,`rgba(255,20,4,0)`),e.fillStyle=s,e.fillRect(r-o,a-o,o*2,o*2)}}e.restore()}}glints(e,t){e.save(),e.translate(t.center.x,t.center.y),e.rotate(t.angle),e.globalCompositeOperation=`screen`;let n=t.opacity??1,r=t.options.brakeLights?Cl(t.braking):0;if(r>0){let i=this.sprite(t)?.brakes;i&&(e.globalAlpha=r*n*(t.dark?.9:.52),e.shadowColor=`#ff250d`,e.shadowBlur=t.height*(t.dark?.16:.055),e.drawImage(i,-t.width/2,-t.height/2,t.width,t.height))}for(let i of[!0,!1])if(!(i?!(t.dark&&t.options.headlights):!(t.dark&&t.options.taillights||r>0)))for(let a of t.mounts[i?`headlights`:`taillights`]){e.globalAlpha=n*(i?.75:t.dark?.34+r*.6:r*.45);let o=t.height*(i?.15:.12),s=e.createRadialGradient(a.x,a.y,0,a.x,a.y,o);s.addColorStop(0,i?`#e6f1ffd9`:`#ff3518c0`),s.addColorStop(.28,i?`#c1dcff70`:`#ff230760`),s.addColorStop(1,i?`#c1dcff00`:`#ff230700`),e.fillStyle=s,e.beginPath(),e.arc(a.x,a.y,o,0,Math.PI*2),e.fill()}e.restore()}smokeLights(e){let t=[],n={x:Math.cos(e.angle),y:Math.sin(e.angle)},r=e.opacity??1,i=e.options.brakeLights?Cl(e.braking):0;if(e.dark&&e.options.headlights)for(let i of e.mounts.headlights)t.push({point:Tl(e,i.x,i.y),direction:n,color:xl,range:e.width*6.2,radius:e.height*.075,spread:.14,intensity:1.7*r});if(e.dark&&e.options.taillights||i>0)for(let a of e.mounts.taillights)t.push({point:Tl(e,a.x,a.y),direction:{x:-n.x,y:-n.y},color:Sl,range:e.width*(i>0?1.6:.9),radius:e.height*.15,spread:.46,intensity:r*(e.dark?.24+i*.85:i*.42)});if(e.dark&&e.options.underglow&&e.options.underglowOpacity>0)for(let n of[-.27,0,.27])t.push({point:Tl(e,e.width*n,0),direction:{x:0,y:0},color:wl(e.options.underglowColor),range:e.height,radius:e.height*.8,spread:0,intensity:r*e.options.underglowOpacity*.8});return t}},Dl=Object.freeze({underglow:!1,underglowColor:`#66e6ff`,underglowOpacity:.6,headlights:!0,taillights:!0,brakeLights:!0});function Ol(e={}){return{underglow:typeof e.underglow==`boolean`?e.underglow:Dl.underglow,underglowColor:/^#[\da-f]{6}$/i.test(e.underglowColor??``)?e.underglowColor:Dl.underglowColor,underglowOpacity:Number.isFinite(e.underglowOpacity)?Math.max(0,Math.min(1,e.underglowOpacity)):Dl.underglowOpacity,headlights:typeof e.headlights==`boolean`?e.headlights:Dl.headlights,brakeLights:typeof e.brakeLights==`boolean`?e.brakeLights:Dl.brakeLights,taillights:typeof e.taillights==`boolean`?e.taillights:Dl.taillights}}var kl={light:{ink:`#161c17`,alphaScale:1},dark:{ink:`#a9adb0`,alphaScale:1.7}};function Al(e){let t=e.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i);if(!t)return!1;let[,n,r,i]=t.map(Number);return n*.2126+r*.7152+i*.0722<112}var jl=(e,t)=>{if(typeof e==`number`){if(t===3)return{mode:`rgb`,r:(e>>8&15|e>>4&240)/255,g:(e>>4&15|e&240)/255,b:(e&15|e<<4&240)/255};if(t===4)return{mode:`rgb`,r:(e>>12&15|e>>8&240)/255,g:(e>>8&15|e>>4&240)/255,b:(e>>4&15|e&240)/255,alpha:(e&15|e<<4&240)/255};if(t===6)return{mode:`rgb`,r:(e>>16&255)/255,g:(e>>8&255)/255,b:(e&255)/255};if(t===8)return{mode:`rgb`,r:(e>>24&255)/255,g:(e>>16&255)/255,b:(e>>8&255)/255,alpha:(e&255)/255}}},Ml={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Nl=e=>jl(Ml[e.toLowerCase()],6),Pl=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,Fl=e=>{let t;return(t=e.match(Pl))?jl(parseInt(t[1],16),t[1].length):void 0},Il=`([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)`,Ll=`${Il}%`,Rl=`(?:${Il}%|${Il})`,zl=`(?:${Il}%|${Il}|none)`,Bl=`(?:${Il}(deg|grad|rad|turn)|${Il})`,Vl=`\\s*,\\s*`;RegExp(`^`+zl+`$`);var Hl=RegExp(`^rgba?\\(\\s*${Il}${Vl}${Il}${Vl}${Il}\\s*(?:,\\s*${Rl}\\s*)?\\)$`),Ul=RegExp(`^rgba?\\(\\s*${Ll}${Vl}${Ll}${Vl}${Ll}\\s*(?:,\\s*${Rl}\\s*)?\\)$`),Wl=e=>{let t={mode:`rgb`},n;if(n=e.match(Hl))n[1]!==void 0&&(t.r=n[1]/255),n[2]!==void 0&&(t.g=n[2]/255),n[3]!==void 0&&(t.b=n[3]/255);else if(n=e.match(Ul))n[1]!==void 0&&(t.r=n[1]/100),n[2]!==void 0&&(t.g=n[2]/100),n[3]!==void 0&&(t.b=n[3]/100);else return;return n[4]===void 0?n[5]!==void 0&&(t.alpha=Math.max(0,Math.min(1,+n[5]))):t.alpha=Math.max(0,Math.min(1,n[4]/100)),t},Gl=(e,t)=>e===void 0?void 0:typeof e==`object`?e.mode===void 0?t?{...e,mode:t}:void 0:e:mu(e),Kl=(e=`rgb`)=>t=>(t=Gl(t,e))===void 0?void 0:t.mode===e?t:ql[t.mode][e]?ql[t.mode][e](t):e===`rgb`?ql[t.mode].rgb(t):ql.rgb[e](ql[t.mode].rgb(t)),ql={},Jl={},Yl=[],Xl={},Zl=e=>e,Ql=e=>(ql[e.mode]={...ql[e.mode],...e.toMode},Object.keys(e.fromMode||{}).forEach(t=>{ql[t]||(ql[t]={}),ql[t][e.mode]=e.fromMode[t]}),e.ranges||={},e.difference||={},e.channels.forEach(t=>{if(e.ranges[t]===void 0&&(e.ranges[t]=[0,1]),!e.interpolate[t])throw Error(`Missing interpolator for: ${t}`);typeof e.interpolate[t]==`function`&&(e.interpolate[t]={use:e.interpolate[t]}),e.interpolate[t].fixup||(e.interpolate[t].fixup=Zl)}),Jl[e.mode]=e,(e.parse||[]).forEach(t=>{eu(t,e.mode)}),Kl(e.mode)),$l=e=>Jl[e],eu=(e,t)=>{if(typeof e==`string`){if(!t)throw Error(`'mode' required when 'parser' is a string`);Xl[e]=t}else typeof e==`function`&&Yl.indexOf(e)<0&&Yl.push(e)},tu=/[^\x00-\x7F]|[a-zA-Z_]/,nu=/[^\x00-\x7F]|[-\w]/,I={Function:`function`,Ident:`ident`,Number:`number`,Percentage:`percentage`,ParenClose:`)`,None:`none`,Hue:`hue`,Alpha:`alpha`},L=0;function ru(e){let t=e[L],n=e[L+1];return t===`-`||t===`+`?/\d/.test(n)||n===`.`&&/\d/.test(e[L+2]):t===`.`?/\d/.test(n):/\d/.test(t)}function iu(e){if(L>=e.length)return!1;let t=e[L];if(tu.test(t))return!0;if(t===`-`){if(e.length-L<2)return!1;let t=e[L+1];return!!(t===`-`||tu.test(t))}return!1}var au={deg:1,rad:180/Math.PI,grad:9/10,turn:360};function ou(e){let t=``;if((e[L]===`-`||e[L]===`+`)&&(t+=e[L++]),t+=su(e),e[L]===`.`&&/\d/.test(e[L+1])&&(t+=e[L++]+su(e)),(e[L]===`e`||e[L]===`E`)&&((e[L+1]===`-`||e[L+1]===`+`)&&/\d/.test(e[L+2])?t+=e[L++]+e[L++]+su(e):/\d/.test(e[L+1])&&(t+=e[L++]+su(e))),iu(e)){let n=cu(e);return n===`deg`||n===`rad`||n===`turn`||n===`grad`?{type:I.Hue,value:t*au[n]}:void 0}return e[L]===`%`?(L++,{type:I.Percentage,value:+t}):{type:I.Number,value:+t}}function su(e){let t=``;for(;/\d/.test(e[L]);)t+=e[L++];return t}function cu(e){let t=``;for(;L<e.length&&nu.test(e[L]);)t+=e[L++];return t}function lu(e){let t=cu(e);return e[L]===`(`?(L++,{type:I.Function,value:t}):t===`none`?{type:I.None,value:void 0}:{type:I.Ident,value:t}}function uu(e=``){let t=e.trim(),n=[],r;for(L=0;L<t.length;)if(r=t[L++],r===`
|
|
49
49
|
`||r===` `||r===` `)for(;L<t.length&&(t[L]===`
|
|
50
50
|
`||t[L]===` `||t[L]===` `);)L++;else{if(r===`,`)return;if(r===`)`)n.push({type:I.ParenClose});else{if(r===`+`){if(L--,ru(t)){n.push(ou(t));continue}return}if(r===`-`){if(L--,ru(t)){n.push(ou(t));continue}if(iu(t)){n.push({type:I.Ident,value:cu(t)});continue}return}if(r===`.`){if(L--,ru(t)){n.push(ou(t));continue}return}if(r===`/`){for(;L<t.length&&(t[L]===`
|
|
51
51
|
`||t[L]===` `||t[L]===` `);)L++;let e;if(ru(t)&&(e=ou(t),e.type!==I.Hue)){n.push({type:I.Alpha,value:e});continue}if(iu(t)&&cu(t)===`none`){n.push({type:I.Alpha,value:{type:I.None,value:void 0}});continue}return}if(/\d/.test(r))L--,n.push(ou(t));else if(tu.test(r))L--,n.push(lu(t));else return}}return n}function du(e){e._i=0;let t=e[e._i++];if(!t||t.type!==I.Function||t.value!==`color`||(t=e[e._i++],t.type!==I.Ident))return;let n=Xl[t.value];if(!n)return;let r={mode:n},i=fu(e,!1);if(!i)return;let a=$l(n).channels;for(let e=0,t,n;e<a.length;e++)t=i[e],n=a[e],t.type!==I.None&&(r[n]=t.type===I.Number?t.value:t.value/100,n===`alpha`&&(r[n]=Math.max(0,Math.min(1,r[n]))));return r}function fu(e,t){let n=[],r;for(;e._i<e.length;)if(r=e[e._i++],r.type===I.None||r.type===I.Number||r.type===I.Alpha||r.type===I.Percentage||t&&r.type===I.Hue)n.push(r);else if(r.type===I.ParenClose){if(e._i<e.length)return}else return;if(!(n.length<3||n.length>4)){if(n.length===4){if(n[3].type!==I.Alpha)return;n[3]=n[3].value}return n.length===3&&n.push({type:I.None,value:void 0}),n.every(e=>e.type!==I.Alpha)?n:void 0}}function pu(e,t){e._i=0;let n=e[e._i++];if(!n||n.type!==I.Function)return;let r=fu(e,t);if(r)return r.unshift(n.value),r}var mu=e=>{if(typeof e!=`string`)return;let t=uu(e),n=t?pu(t,!0):void 0,r,i=0,a=Yl.length;for(;i<a;)if((r=Yl[i++](e,n))!==void 0)return r;return t?du(t):void 0};function hu(e,t){if(!t||t[0]!==`rgb`&&t[0]!==`rgba`)return;let n={mode:`rgb`},[,r,i,a,o]=t;if(r.type!==I.Hue&&i.type!==I.Hue&&a.type!==I.Hue)return r.type!==I.None&&(n.r=r.type===I.Number?r.value/255:r.value/100),i.type!==I.None&&(n.g=i.type===I.Number?i.value/255:i.value/100),a.type!==I.None&&(n.b=a.type===I.Number?a.value/255:a.value/100),o.type!==I.None&&(n.alpha=Math.min(1,Math.max(0,o.type===I.Number?o.value:o.value/100))),n}var gu=e=>e===`transparent`?{mode:`rgb`,r:0,g:0,b:0,alpha:0}:void 0,_u=(e,t,n)=>e+n*(t-e),vu=e=>{let t=[];for(let n=0;n<e.length-1;n++){let r=e[n],i=e[n+1];r===void 0&&i===void 0?t.push(void 0):r!==void 0&&i!==void 0?t.push([r,i]):t.push(r===void 0?[i,i]:[r,r])}return t},R=(e=>t=>{let n=vu(t);return t=>{let r=t*n.length,i=t>=1?n.length-1:Math.max(Math.floor(r),0),a=n[i];return a===void 0?void 0:e(a[0],a[1],r-i)}})(_u),yu=e=>{let t=!1,n=e.map(e=>e===void 0?1:(t=!0,e));return t?n:e},bu={mode:`rgb`,channels:[`r`,`g`,`b`,`alpha`],parse:[hu,Fl,Wl,Nl,gu,`srgb`],serialize:`srgb`,interpolate:{r:R,g:R,b:R,alpha:{use:R,fixup:yu}},gamut:!0,white:{r:1,g:1,b:1},black:{r:0,g:0,b:0}},xu=(e=0)=>Math.abs(e)**(563/256)*Math.sign(e),Su=e=>{let t=xu(e.r),n=xu(e.g),r=xu(e.b),i={mode:`xyz65`,x:.5766690429101305*t+.1855582379065463*n+.1882286462349947*r,y:.297344975250536*t+.6273635662554661*n+.0752914584939979*r,z:.0270313613864123*t+.0706888525358272*n+.9913375368376386*r};return e.alpha!==void 0&&(i.alpha=e.alpha),i},Cu=e=>Math.abs(e)**(256/563)*Math.sign(e),wu=({x:e,y:t,z:n,alpha:r})=>{e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i={mode:`a98`,r:Cu(e*2.0415879038107465-t*.5650069742788597-.3447313507783297*n),g:Cu(e*-.9692436362808798+t*1.8759675015077206+.0415550574071756*n),b:Cu(e*.0134442806320312-t*.1183623922310184+1.0151749943912058*n)};return r!==void 0&&(i.alpha=r),i},Tu=(e=0)=>{let t=Math.abs(e);return t<=.04045?e/12.92:(Math.sign(e)||1)*((t+.055)/1.055)**2.4},Eu=({r:e,g:t,b:n,alpha:r})=>{let i={mode:`lrgb`,r:Tu(e),g:Tu(t),b:Tu(n)};return r!==void 0&&(i.alpha=r),i},Du=e=>{let{r:t,g:n,b:r,alpha:i}=Eu(e),a={mode:`xyz65`,x:.4123907992659593*t+.357584339383878*n+.1804807884018343*r,y:.2126390058715102*t+.715168678767756*n+.0721923153607337*r,z:.0193308187155918*t+.119194779794626*n+.9505321522496607*r};return i!==void 0&&(a.alpha=i),a},Ou=(e=0)=>{let t=Math.abs(e);return t>.0031308?(Math.sign(e)||1)*(1.055*t**(1/2.4)-.055):e*12.92},ku=({r:e,g:t,b:n,alpha:r},i=`rgb`)=>{let a={mode:i,r:Ou(e),g:Ou(t),b:Ou(n)};return r!==void 0&&(a.alpha=r),a},Au=({x:e,y:t,z:n,alpha:r})=>{e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i=ku({r:e*3.2409699419045226-t*1.537383177570094-.4986107602930034*n,g:e*-.9692436362808796+t*1.8759675015077204+.0415550574071756*n,b:e*.0556300796969936-t*.2039769588889765+1.0569715142428784*n});return r!==void 0&&(i.alpha=r),i},ju={...bu,mode:`a98`,parse:[`a98-rgb`],serialize:`a98-rgb`,fromMode:{rgb:e=>wu(Du(e)),xyz65:wu},toMode:{rgb:e=>Au(Su(e)),xyz65:Su}},Mu=e=>(e%=360)<0?e+360:e,Nu=(e,t)=>e.map((n,r,i)=>{if(n===void 0)return n;let a=Mu(n);return r===0||e[r-1]===void 0?a:t(a-Mu(i[r-1]))}).reduce((e,t)=>!e.length||t===void 0||e[e.length-1]===void 0?(e.push(t),e):(e.push(t+e[e.length-1]),e),[]),Pu=e=>Nu(e,e=>Math.abs(e)<=180?e:e-360*Math.sign(e)),Fu=(e,t)=>{if(e.h===void 0||t.h===void 0||!e.s||!t.s)return 0;let n=Mu(e.h),r=Mu(t.h),i=Math.sin((r-n+360)/2*Math.PI/180);return 2*Math.sqrt(e.s*t.s)*i},Iu=(e,t)=>{if(e.h===void 0||t.h===void 0)return 0;let n=Mu(e.h),r=Mu(t.h);return Math.abs(r-n)>180?n-(r-360*Math.sign(r-n)):r-n},Lu=(e,t)=>{if(e.h===void 0||t.h===void 0||!e.c||!t.c)return 0;let n=Mu(e.h),r=Mu(t.h),i=Math.sin((r-n+360)/2*Math.PI/180);return 2*Math.sqrt(e.c*t.c)*i},Ru=e=>{let t=e.reduce((e,t)=>{if(t!==void 0){let n=t*Math.PI/180;e.sin+=Math.sin(n),e.cos+=Math.cos(n)}return e},{sin:0,cos:0}),n=Math.atan2(t.sin,t.cos)*180/Math.PI;return n<0?360+n:n},zu=({l:e,a:t,b:n,alpha:r},i=`lch`)=>{t===void 0&&(t=0),n===void 0&&(n=0);let a=Math.sqrt(t*t+n*n),o={mode:i,l:e,c:a};return a&&(o.h=Mu(Math.atan2(n,t)*180/Math.PI)),r!==void 0&&(o.alpha=r),o},Bu=({l:e,c:t,h:n,alpha:r},i=`lab`)=>{n===void 0&&(n=0);let a={mode:i,l:e,a:t?t*Math.cos(n/180*Math.PI):0,b:t?t*Math.sin(n/180*Math.PI):0};return r!==void 0&&(a.alpha=r),a},Vu={X:.3457/.3585,Y:1,Z:.2958/.3585};function Hu({h:e,s:t,l:n,alpha:r}){e=Mu(e===void 0?0:e),t===void 0&&(t=0),n===void 0&&(n=0);let i=n+t*(n<.5?n:1-n),a=i-(i-n)*2*Math.abs(e/60%2-1),o;switch(Math.floor(e/60)){case 0:o={r:i,g:a,b:2*n-i};break;case 1:o={r:a,g:i,b:2*n-i};break;case 2:o={r:2*n-i,g:i,b:a};break;case 3:o={r:2*n-i,g:a,b:i};break;case 4:o={r:a,g:2*n-i,b:i};break;case 5:o={r:i,g:2*n-i,b:a};break;default:o={r:2*n-i,g:2*n-i,b:2*n-i}}return o.mode=`rgb`,r!==void 0&&(o.alpha=r),o}function Uu({r:e,g:t,b:n,alpha:r}){e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i=Math.max(e,t,n),a=Math.min(e,t,n),o={mode:`hsl`,s:i===a?0:(i-a)/(1-Math.abs(i+a-1)),l:.5*(i+a)};return i-a!==0&&(o.h=(i===e?(t-n)/(i-a)+(t<n)*6:i===t?(n-e)/(i-a)+2:(e-t)/(i-a)+4)*60),r!==void 0&&(o.alpha=r),o}var Wu=(e,t)=>{switch(t){case`deg`:return+e;case`rad`:return e/Math.PI*180;case`grad`:return e/10*9;case`turn`:return e*360}},Gu=RegExp(`^hsla?\\(\\s*${Bl}${Vl}${Ll}${Vl}${Ll}\\s*(?:,\\s*${Rl}\\s*)?\\)$`),Ku=e=>{let t=e.match(Gu);if(!t)return;let n={mode:`hsl`};return t[3]===void 0?t[1]!==void 0&&t[2]!==void 0&&(n.h=Wu(t[1],t[2])):n.h=+t[3],t[4]!==void 0&&(n.s=Math.min(Math.max(0,t[4]/100),1)),t[5]!==void 0&&(n.l=Math.min(Math.max(0,t[5]/100),1)),t[6]===void 0?t[7]!==void 0&&(n.alpha=Math.max(0,Math.min(1,+t[7]))):n.alpha=Math.max(0,Math.min(1,t[6]/100)),n};function qu(e,t){if(!t||t[0]!==`hsl`&&t[0]!==`hsla`)return;let n={mode:`hsl`},[,r,i,a,o]=t;if(r.type!==I.None){if(r.type===I.Percentage)return;n.h=r.value}if(i.type!==I.None){if(i.type===I.Hue)return;n.s=i.value/100}if(a.type!==I.None){if(a.type===I.Hue)return;n.l=a.value/100}return o.type!==I.None&&(n.alpha=Math.min(1,Math.max(0,o.type===I.Number?o.value:o.value/100))),n}var Ju={mode:`hsl`,toMode:{rgb:Hu},fromMode:{rgb:Uu},channels:[`h`,`s`,`l`,`alpha`],ranges:{h:[0,360]},gamut:`rgb`,parse:[qu,Ku],serialize:e=>`hsl(${e.h===void 0?`none`:e.h} ${e.s===void 0?`none`:e.s*100+`%`} ${e.l===void 0?`none`:e.l*100+`%`}${e.alpha<1?` / ${e.alpha}`:``})`,interpolate:{h:{use:R,fixup:Pu},s:R,l:R,alpha:{use:R,fixup:yu}},difference:{h:Fu},average:{h:Ru}};function Yu({h:e,s:t,v:n,alpha:r}){e=Mu(e===void 0?0:e),t===void 0&&(t=0),n===void 0&&(n=0);let i=Math.abs(e/60%2-1),a;switch(Math.floor(e/60)){case 0:a={r:n,g:n*(1-t*i),b:n*(1-t)};break;case 1:a={r:n*(1-t*i),g:n,b:n*(1-t)};break;case 2:a={r:n*(1-t),g:n,b:n*(1-t*i)};break;case 3:a={r:n*(1-t),g:n*(1-t*i),b:n};break;case 4:a={r:n*(1-t*i),g:n*(1-t),b:n};break;case 5:a={r:n,g:n*(1-t),b:n*(1-t*i)};break;default:a={r:n*(1-t),g:n*(1-t),b:n*(1-t)}}return a.mode=`rgb`,r!==void 0&&(a.alpha=r),a}function Xu({r:e,g:t,b:n,alpha:r}){e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i=Math.max(e,t,n),a=Math.min(e,t,n),o={mode:`hsv`,s:i===0?0:1-a/i,v:i};return i-a!==0&&(o.h=(i===e?(t-n)/(i-a)+(t<n)*6:i===t?(n-e)/(i-a)+2:(e-t)/(i-a)+4)*60),r!==void 0&&(o.alpha=r),o}function Zu({h:e,w:t,b:n,alpha:r}){if(t===void 0&&(t=0),n===void 0&&(n=0),t+n>1){let e=t+n;t/=e,n/=e}return Yu({h:e,s:n===1?1:1-t/(1-n),v:1-n,alpha:r})}function Qu(e){let t=Xu(e);if(t===void 0)return;let n=t.s===void 0?0:t.s,r=t.v===void 0?0:t.v,i={mode:`hwb`,w:(1-n)*r,b:1-r};return t.h!==void 0&&(i.h=t.h),t.alpha!==void 0&&(i.alpha=t.alpha),i}function $u(e,t){if(!t||t[0]!==`hwb`)return;let n={mode:`hwb`},[,r,i,a,o]=t;if(r.type!==I.None){if(r.type===I.Percentage)return;n.h=r.value}if(i.type!==I.None){if(i.type===I.Hue)return;n.w=i.value/100}if(a.type!==I.None){if(a.type===I.Hue)return;n.b=a.value/100}return o.type!==I.None&&(n.alpha=Math.min(1,Math.max(0,o.type===I.Number?o.value:o.value/100))),n}var ed={mode:`hwb`,toMode:{rgb:Zu},fromMode:{rgb:Qu},channels:[`h`,`w`,`b`,`alpha`],ranges:{h:[0,360]},gamut:`rgb`,parse:[$u],serialize:e=>`hwb(${e.h===void 0?`none`:e.h} ${e.w===void 0?`none`:e.w*100+`%`} ${e.b===void 0?`none`:e.b*100+`%`}${e.alpha<1?` / ${e.alpha}`:``})`,interpolate:{h:{use:R,fixup:Pu},w:R,b:R,alpha:{use:R,fixup:yu}},difference:{h:Iu},average:{h:Ru}},td=29**3/27,nd=216/29**3,rd=e=>e**3>nd?e**3:(116*e-16)/td,id=({l:e,a:t,b:n,alpha:r})=>{e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i=(e+16)/116,a=t/500+i,o=i-n/200,s={mode:`xyz50`,x:rd(a)*Vu.X,y:rd(i)*Vu.Y,z:rd(o)*Vu.Z};return r!==void 0&&(s.alpha=r),s},ad=({x:e,y:t,z:n,alpha:r})=>{e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i=ku({r:e*3.1341359569958707-t*1.6173863321612538-.4906619460083532*n,g:e*-.978795502912089+t*1.916254567259524+.03344273116131949*n,b:e*.07195537988411677-t*.2289768264158322+1.405386058324125*n});return r!==void 0&&(i.alpha=r),i},od=e=>ad(id(e)),sd=e=>{let{r:t,g:n,b:r,alpha:i}=Eu(e),a={mode:`xyz50`,x:.436065742824811*t+.3851514688337912*n+.14307845442264197*r,y:.22249319175623702*t+.7168870538238823*n+.06061979053616537*r,z:.013923904500943465*t+.09708128566574634*n+.7140993584005155*r};return i!==void 0&&(a.alpha=i),a},cd=e=>e>nd?Math.cbrt(e):(td*e+16)/116,ld=({x:e,y:t,z:n,alpha:r})=>{e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i=cd(e/Vu.X),a=cd(t/Vu.Y),o=cd(n/Vu.Z),s={mode:`lab`,l:116*a-16,a:500*(i-a),b:200*(a-o)};return r!==void 0&&(s.alpha=r),s},ud=e=>{let t=ld(sd(e));return e.r===e.b&&e.b===e.g&&(t.a=t.b=0),t};function dd(e,t){if(!t||t[0]!==`lab`)return;let n={mode:`lab`},[,r,i,a,o]=t;if(r.type!==I.Hue&&i.type!==I.Hue&&a.type!==I.Hue)return r.type!==I.None&&(n.l=Math.min(Math.max(0,r.value),100)),i.type!==I.None&&(n.a=i.type===I.Number?i.value:i.value*125/100),a.type!==I.None&&(n.b=a.type===I.Number?a.value:a.value*125/100),o.type!==I.None&&(n.alpha=Math.min(1,Math.max(0,o.type===I.Number?o.value:o.value/100))),n}var fd={mode:`lab`,toMode:{xyz50:id,rgb:od},fromMode:{xyz50:ld,rgb:ud},channels:[`l`,`a`,`b`,`alpha`],ranges:{l:[0,100],a:[-125,125],b:[-125,125]},parse:[dd],serialize:e=>`lab(${e.l===void 0?`none`:e.l} ${e.a===void 0?`none`:e.a} ${e.b===void 0?`none`:e.b}${e.alpha<1?` / ${e.alpha}`:``})`,interpolate:{l:R,a:R,b:R,alpha:{use:R,fixup:yu}}};function pd(e,t){if(!t||t[0]!==`lch`)return;let n={mode:`lch`},[,r,i,a,o]=t;if(r.type!==I.None){if(r.type===I.Hue)return;n.l=Math.min(Math.max(0,r.value),100)}if(i.type!==I.None&&(n.c=Math.max(0,i.type===I.Number?i.value:i.value*150/100)),a.type!==I.None){if(a.type===I.Percentage)return;n.h=a.value}return o.type!==I.None&&(n.alpha=Math.min(1,Math.max(0,o.type===I.Number?o.value:o.value/100))),n}var md={mode:`lch`,toMode:{lab:Bu,rgb:e=>od(Bu(e))},fromMode:{rgb:e=>zu(ud(e)),lab:zu},channels:[`l`,`c`,`h`,`alpha`],ranges:{l:[0,100],c:[0,150],h:[0,360]},parse:[pd],serialize:e=>`lch(${e.l===void 0?`none`:e.l} ${e.c===void 0?`none`:e.c} ${e.h===void 0?`none`:e.h}${e.alpha<1?` / ${e.alpha}`:``})`,interpolate:{h:{use:R,fixup:Pu},c:R,l:R,alpha:{use:R,fixup:yu}},difference:{h:Lu},average:{h:Ru}},hd={...bu,mode:`lrgb`,toMode:{rgb:ku},fromMode:{rgb:Eu},parse:[`srgb-linear`],serialize:`srgb-linear`},gd=({r:e,g:t,b:n,alpha:r})=>{e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i=Math.cbrt(.412221469470763*e+.5363325372617348*t+.0514459932675022*n),a=Math.cbrt(.2119034958178252*e+.6806995506452344*t+.1073969535369406*n),o=Math.cbrt(.0883024591900564*e+.2817188391361215*t+.6299787016738222*n),s={mode:`oklab`,l:.210454268309314*i+.7936177747023054*a-.0040720430116193*o,a:1.9779985324311684*i-2.42859224204858*a+.450593709617411*o,b:.0259040424655478*i+.7827717124575296*a-.8086757549230774*o};return r!==void 0&&(s.alpha=r),s},_d=e=>{let t=gd(Eu(e));return e.r===e.b&&e.b===e.g&&(t.a=t.b=0),t},vd=({l:e,a:t,b:n,alpha:r})=>{e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i=(e+.3963377773761749*t+.2158037573099136*n)**3,a=(e-.1055613458156586*t-.0638541728258133*n)**3,o=(e-.0894841775298119*t-1.2914855480194092*n)**3,s={mode:`lrgb`,r:4.076741636075957*i-3.3077115392580616*a+.2309699031821044*o,g:-1.2684379732850317*i+2.6097573492876887*a-.3413193760026573*o,b:-.0041960761386756*i-.7034186179359362*a+1.7076146940746117*o};return r!==void 0&&(s.alpha=r),s},yd=e=>ku(vd(e));function bd(e,t){if(!t||t[0]!==`oklab`)return;let n={mode:`oklab`},[,r,i,a,o]=t;if(r.type!==I.Hue&&i.type!==I.Hue&&a.type!==I.Hue)return r.type!==I.None&&(n.l=Math.min(Math.max(0,r.type===I.Number?r.value:r.value/100),1)),i.type!==I.None&&(n.a=i.type===I.Number?i.value:i.value*.4/100),a.type!==I.None&&(n.b=a.type===I.Number?a.value:a.value*.4/100),o.type!==I.None&&(n.alpha=Math.min(1,Math.max(0,o.type===I.Number?o.value:o.value/100))),n}var xd={...fd,mode:`oklab`,toMode:{lrgb:vd,rgb:yd},fromMode:{lrgb:gd,rgb:_d},ranges:{l:[0,1],a:[-.4,.4],b:[-.4,.4]},parse:[bd],serialize:e=>`oklab(${e.l===void 0?`none`:e.l} ${e.a===void 0?`none`:e.a} ${e.b===void 0?`none`:e.b}${e.alpha<1?` / ${e.alpha}`:``})`};function Sd(e,t){if(!t||t[0]!==`oklch`)return;let n={mode:`oklch`},[,r,i,a,o]=t;if(r.type!==I.None){if(r.type===I.Hue)return;n.l=Math.min(Math.max(0,r.type===I.Number?r.value:r.value/100),1)}if(i.type!==I.None&&(n.c=Math.max(0,i.type===I.Number?i.value:i.value*.4/100)),a.type!==I.None){if(a.type===I.Percentage)return;n.h=a.value}return o.type!==I.None&&(n.alpha=Math.min(1,Math.max(0,o.type===I.Number?o.value:o.value/100))),n}var Cd={...md,mode:`oklch`,toMode:{oklab:e=>Bu(e,`oklab`),rgb:e=>yd(Bu(e,`oklab`))},fromMode:{rgb:e=>zu(_d(e),`oklch`),oklab:e=>zu(e,`oklch`)},parse:[Sd],serialize:e=>`oklch(${e.l===void 0?`none`:e.l} ${e.c===void 0?`none`:e.c} ${e.h===void 0?`none`:e.h}${e.alpha<1?` / ${e.alpha}`:``})`,ranges:{l:[0,1],c:[0,.4],h:[0,360]}},wd=e=>{let{r:t,g:n,b:r,alpha:i}=Eu(e),a={mode:`xyz65`,x:.486570948648216*t+.265667693169093*n+.1982172852343625*r,y:.2289745640697487*t+.6917385218365062*n+.079286914093745*r,z:0*t+.0451133818589026*n+1.043944368900976*r};return i!==void 0&&(a.alpha=i),a},Td=({x:e,y:t,z:n,alpha:r})=>{e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i=ku({r:e*2.4934969119414263-t*.9313836179191242-.402710784450717*n,g:e*-.8294889695615749+t*1.7626640603183465+.0236246858419436*n,b:e*.0358458302437845-t*.0761723892680418+.9568845240076871*n},`p3`);return r!==void 0&&(i.alpha=r),i},Ed={...bu,mode:`p3`,parse:[`display-p3`],serialize:`display-p3`,fromMode:{rgb:e=>Td(Du(e)),xyz65:Td},toMode:{rgb:e=>Au(wd(e)),xyz65:wd}},Dd=e=>{let t=Math.abs(e);return t>=1/512?Math.sign(e)*t**(1/1.8):16*e},Od=({x:e,y:t,z:n,alpha:r})=>{e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i={mode:`prophoto`,r:Dd(e*1.3457868816471585-t*.2555720873797946-.0511018649755453*n),g:Dd(e*-.5446307051249019+t*1.5082477428451466+.0205274474364214*n),b:Dd(e*0+t*0+1.2119675456389452*n)};return r!==void 0&&(i.alpha=r),i},kd=(e=0)=>{let t=Math.abs(e);return t>=16/512?Math.sign(e)*t**1.8:e/16},Ad=e=>{let t=kd(e.r),n=kd(e.g),r=kd(e.b),i={mode:`xyz50`,x:.7977666449006423*t+.1351812974005331*n+.0313477341283922*r,y:.2880748288194013*t+.7118352342418731*n+899369387256e-16*r,z:0*t+0*n+.8251046025104602*r};return e.alpha!==void 0&&(i.alpha=e.alpha),i},jd={...bu,mode:`prophoto`,parse:[`prophoto-rgb`],serialize:`prophoto-rgb`,fromMode:{xyz50:Od,rgb:e=>Od(sd(e))},toMode:{xyz50:Ad,rgb:e=>ad(Ad(e))}},Md=1.09929682680944,Nd=.018053968510807,Pd=e=>{let t=Math.abs(e);return t>Nd?(Math.sign(e)||1)*(Md*t**.45-.09929682680944008):4.5*e},Fd=({x:e,y:t,z:n,alpha:r})=>{e===void 0&&(e=0),t===void 0&&(t=0),n===void 0&&(n=0);let i={mode:`rec2020`,r:Pd(e*1.7166511879712683-t*.3556707837763925-.2533662813736599*n),g:Pd(e*-.6666843518324893+t*1.6164812366349395+.0157685458139111*n),b:Pd(e*.0176398574453108-t*.0427706132578085+.9421031212354739*n)};return r!==void 0&&(i.alpha=r),i},Id=1.09929682680944,Ld=.018053968510807,Rd=(e=0)=>{let t=Math.abs(e);return t<Ld*4.5?e/4.5:(Math.sign(e)||1)*((t+Id-1)/Id)**(1/.45)},zd=e=>{let t=Rd(e.r),n=Rd(e.g),r=Rd(e.b),i={mode:`xyz65`,x:.6369580483012911*t+.1446169035862083*n+.1688809751641721*r,y:.262700212011267*t+.6779980715188708*n+.059301716469862*r,z:0*t+.0280726930490874*n+1.0609850577107909*r};return e.alpha!==void 0&&(i.alpha=e.alpha),i},Bd={...bu,mode:`rec2020`,fromMode:{xyz65:Fd,rgb:e=>Fd(Du(e))},toMode:{xyz65:zd,rgb:e=>Au(zd(e))},parse:[`rec2020`],serialize:`rec2020`},Vd={mode:`xyz50`,parse:[`xyz-d50`],serialize:`xyz-d50`,toMode:{rgb:ad,lab:ld},fromMode:{rgb:sd,lab:id},channels:[`x`,`y`,`z`,`alpha`],ranges:{x:[0,.964],y:[0,.999],z:[0,.825]},interpolate:{x:R,y:R,z:R,alpha:{use:R,fixup:yu}}},Hd={mode:`xyz65`,toMode:{rgb:Au,xyz50:e=>{let{x:t,y:n,z:r,alpha:i}=e;t===void 0&&(t=0),n===void 0&&(n=0),r===void 0&&(r=0);let a={mode:`xyz50`,x:1.0479298208405488*t+.0229467933410191*n-.0501922295431356*r,y:.0296278156881593*t+.990434484573249*n-.0170738250293851*r,z:-.0092430581525912*t+.0150551448965779*n+.7518742899580008*r};return i!==void 0&&(a.alpha=i),a}},fromMode:{rgb:Du,xyz50:e=>{let{x:t,y:n,z:r,alpha:i}=e;t===void 0&&(t=0),n===void 0&&(n=0),r===void 0&&(r=0);let a={mode:`xyz65`,x:.9554734527042182*t-.0230985368742614*n+.0632593086610217*r,y:-.0283697069632081*t+1.0099954580058226*n+.021041398966943*r,z:.0123140016883199*t-.0205076964334779*n+1.3303659366080753*r};return i!==void 0&&(a.alpha=i),a}},ranges:{x:[0,.95],y:[0,1],z:[0,1.088]},channels:[`x`,`y`,`z`,`alpha`],parse:[`xyz`,`xyz-d65`],serialize:`xyz-d65`,interpolate:{x:R,y:R,z:R,alpha:{use:R,fixup:yu}}},Ud=Ql(bu);Ql(hd),Ql(Ju),Ql(ed),Ql(fd),Ql(md),Ql(xd);var Wd=Ql(Cd);Ql(Ed),Ql(ju),Ql(jd),Ql(Bd),Ql(Vd),Ql(Hd);var Gd=new Map,Kd=e=>Math.max(0,Math.min(1,e));function qd(e){let t=e.trim().toLowerCase();if(!t||t===`transparent`)return null;if(Gd.has(t))return Gd.get(t);let n=Ud(t),r=null;if(n){let e=[n.r??0,n.g??0,n.b??0],t=n.alpha??1;if([...e,t].every(Number.isFinite)){let[n,i,a]=e.map(Kd),o=Kd(t),s=Wd({mode:`rgb`,r:n,g:i,b:a});r=Object.freeze({paint:Object.freeze({color:`rgb(${[n,i,a].map(e=>Math.round(e*255)).join(` `)})`,alpha:o}),appearance:Object.freeze({lightness:s.l,chroma:s.c,alpha:o})})}}return Gd.size>=256&&Gd.delete(Gd.keys().next().value),Gd.set(t,r),r}function Jd(e){return qd(e)?.paint??null}function Yd(e){return qd(e)?.appearance??null}function Xd(e){let t=0,n=0,r=0,i=0;for(let a of e.layers){let e=`layers`in a?Xd(a):[a.color[0]*a.alpha,a.color[1]*a.alpha,a.color[2]*a.alpha,a.alpha];if(t+=(1-i)*e[0],n+=(1-i)*e[1],r+=(1-i)*e[2],i+=(1-i)*e[3],i>=.9999)break}return[t*e.opacity,n*e.opacity,r*e.opacity,i*e.opacity]}function Zd(e,t=!1){let n={opacity:1,layers:[]},r=new Map,i=new Map,a=e=>{let t=r.get(e);return t||(t=getComputedStyle(e),r.set(e,t)),t},o=e=>{let t=i.get(e);if(t)return t;let r=e.parentElement?o(e.parentElement):n,s=Number.parseFloat(a(e).opacity),c=Number.isFinite(s)?Math.max(0,Math.min(1,s)):1,l=r;return c<1&&(l={opacity:c,layers:[]},r.layers.push(l)),i.set(e,l),l};for(let t of document.elementsFromPoint(e.x,e.y)){if(!(t instanceof HTMLElement)||t.closest(`[data-jr-overlay],[data-jr-embed],[data-jr-touch-controls]`))continue;let e=Jd(a(t).backgroundColor);if(!e||e.alpha<=0)continue;let n=e.color.match(/[\d.]+/g).slice(0,3).map(Number);o(t).layers.push({color:n,alpha:e.alpha})}let[s,c,l,u]=Xd(n);if(u<=0)return null;let d=t?0:255;return Al(`rgb(${s+d*(1-u)} ${c+d*(1-u)} ${l+d*(1-u)})`)}var Qd=class{resolve;samples=new WeakMap;constructor(e=Zd){this.resolve=e}at(e,t,n,r=performance.now()){let i=this.samples.get(e);if(i&&i.fallback===n&&r-i.at<80&&Math.hypot(t.x-i.x,t.y-i.y)<48)return i.dark;let a=this.resolve(t,n)??n;return this.samples.set(e,{x:t.x,y:t.y,at:r,dark:a,fallback:n}),a}},z={lightColor:[.012,.015,.021],darkColor:[.98,.985,1],vorticity:23,maxMotionSpeedPxPerSecond:260,emissionFactor:1.2,wakeSpeedPxPerSecond:260,wakeEmissionFactor:1.6,wakeFlowFactor:.18,wallSmokeFactor:1.45,emergenceSmokeFactor:1.7,emergenceFadeSeconds:.8,spriteBlurPx:1.15,insideWallSpriteOpacity:.1,styles:{specter:{emissionPerSecond:1.05,driftPixelsPerSecond:33,radiusFactor:.24,bodyInfluence:.28,spriteAlpha:{light:.69,dark:.58},shadowBlurDark:3},phantom:{emissionPerSecond:.82,driftPixelsPerSecond:27,radiusFactor:.17,bodyInfluence:.24,spriteAlpha:{light:.18,dark:.17},contourAlpha:.48,shadowBlurDark:3},wraith:{emissionPerSecond:.72,driftPixelsPerSecond:40,radiusFactor:.25,bodyInfluence:.3,spriteAlpha:{light:.35,dark:.32},shadowBlurDark:4}}};function $d(e,t,n,r,i){if(!i.length)return 0;let a=D(-t.y,t.x),o=Math.abs(t.x)*n+Math.abs(a.x)*r,s=Math.abs(t.y)*n+Math.abs(a.y)*r,c=i.filter(t=>t.x<=e.x+o&&t.x+t.width>=e.x-o&&t.y<=e.y+s&&t.y+t.height>=e.y-s);if(!c.length)return 0;let l=0;for(let i=0;i<5;i++)for(let o=0;o<7;o++){let s=((o+.5)/7*2-1)*n,u=((i+.5)/5*2-1)*r,d=e.x+t.x*s+a.x*u,f=e.y+t.y*s+a.y*u;c.some(e=>d>=e.x&&d<=e.x+e.width&&f>=e.y&&f<=e.y+e.height)&&l++}return l/35}var ef=new WeakMap;function tf(e,t=`high`){let n=ef.get(e),r=n?.get(t);if(r)return r;let i=[],a=t===`high`?4:t===`medium`?2:1,o=4*a,s=9*a,c=(t,n)=>{if(t<0||t>=o||n<0||n>=s)return!1;let r=Math.min(e.columns-1,Math.floor((n+.5)/s*e.columns)),i=Math.min(e.rows-1,Math.floor((t+.5)/o*e.rows));return!!e.solid[i*e.columns+r]};for(let e=0;e<o;e++)for(let t=0;t<s;t++)c(e,t)&&(c(e-1,t)&&c(e+1,t)&&c(e,t-1)&&c(e,t+1)||i.push(D((t+.5)/s*2-1,(e+.5)/o*2-1)));return i.length||i.push(D()),n||ef.set(e,n=new Map),n.set(t,i),i}var nf=e=>Math.max(0,Math.min(1,e)),rf=class{cache=new WeakMap;get(e,t){let n=this.cache.get(e);if(n)return n;let r=Math.max(1,Math.min(512,Math.round(t.width))),i=Math.max(1,Math.round(t.height/t.width*r)),a=document.createElement(`canvas`);a.width=r,a.height=i;let o=a.getContext(`2d`,{willReadFrequently:!0});if(!o)throw Error(`Ghost material requires a 2D canvas`);o.drawImage(e,t.x,t.y,t.width,t.height,0,0,r,i);let s=o.getImageData(0,0,r,i).data,c=document.createElement(`canvas`),l=document.createElement(`canvas`),u=document.createElement(`canvas`),d=document.createElement(`canvas`);for(let e of[c,l,u,d])e.width=r,e.height=i;let f=c.getContext(`2d`),p=l.getContext(`2d`),m=u.getContext(`2d`),h=d.getContext(`2d`);if(!f||!p||!m||!h)throw Error(`Ghost material requires a 2D canvas`);let g=f.createImageData(r,i),_=p.createImageData(r,i),v=m.createImageData(r,i),y=h.createImageData(r,i),b=(e,t)=>(Math.max(0,Math.min(i-1,t))*r+Math.max(0,Math.min(r-1,e)))*4,x=e=>(s[e]*.2126+s[e+1]*.7152+s[e+2]*.0722)/255;for(let e=0;e<i;e++)for(let t=0;t<r;t++){let n=b(t,e),r=s[n+3];if(!r)continue;let i=x(n),a=b(t-2,e),o=b(t+2,e),c=b(t,e-2),l=b(t,e+2),u=nf(Math.max(Math.abs(i-x(a)),Math.abs(i-x(o)),Math.abs(i-x(c)),Math.abs(i-x(l)))*2.8),d=nf((r-s[a+3]+(r-s[c+3]))/360),f=nf(u*.65+d*.8),p=Math.round(7+f*220),m=Math.round(242-(1-i)*105+d*13),h=Math.round(247-(1-i)*114+d*8);g.data[n]=p,g.data[n+1]=Math.min(255,p+2),g.data[n+2]=Math.min(255,p+6),g.data[n+3]=r,_.data[n]=Math.min(255,m),_.data[n+1]=Math.min(255,h),_.data[n+2]=Math.min(255,h+5),_.data[n+3]=r;let S=Math.round(r*nf(u*.6+d*.9));v.data[n]=Math.round(13+d*214),v.data[n+1]=Math.round(17+d*214),v.data[n+2]=Math.round(22+d*214),v.data[n+3]=S,y.data[n]=Math.round(185+d*70),y.data[n+1]=Math.round(192+d*63),y.data[n+2]=Math.round(204+d*51),y.data[n+3]=S}f.putImageData(g,0,0),p.putImageData(_,0,0),m.putImageData(v,0,0),h.putImageData(y,0,0);let S={light:c,dark:l,contourLight:u,contourDark:d};return this.cache.set(e,S),S}},af=class{materials=new rf;clearMaterials(){this.materials=new rf}draw(e,t,n){let{imageFor:r,screen:i,visualOffset:a,zoom:o,width:s,height:c,pixelSpace:l,walls:u,scroll:d,dark:f,styleName:p}=n,{sim:m}=e,h=r(m.car.preset),g=t,_=z.styles[p],v=f?z.darkColor:z.lightColor,y=O(i(m.body.position),a(m)),b=m.car.preset.geometry.lengthM*o,x=m.car.preset.geometry.widthM*o,S=null;if(h){let t=Kt(m.car.preset,h.naturalWidth,h.naturalHeight),n=e.damage.spriteFor(h,t);b=t.lengthM*o,x=t.widthM*o,S=this.materials.get(n??h,n?{x:0,y:0,width:n.width,height:n.height}:t.source)}let C=e=>{g.save(),g.translate(y.x,y.y),g.rotate(-m.body.angle),g.filter=`blur(${z.spriteBlurPx}px)`,g.globalAlpha=_.spriteAlpha[f?`dark`:`light`]*e,g.shadowColor=`rgb(${v.map(e=>Math.round(e*255)).join(` `)})`,g.shadowBlur=f?_.shadowBlurDark:0,S?(g.drawImage(S[f?`dark`:`light`],-b/2,-x/2,b,x),p===`phantom`&&(g.globalAlpha=z.styles.phantom.contourAlpha*e,g.drawImage(S[f?`contourDark`:`contourLight`],-b/2,-x/2,b,x))):(g.fillStyle=f?`#f0f5ff`:`#0b0d0f`,g.beginPath(),g.roundRect(-b/2,-x/2,b,x,12),g.fill()),g.restore()},w=[];if(l&&u.length){let e=Math.abs(Math.cos(m.body.angle)),t=Math.abs(Math.sin(m.body.angle)),n=(e*b+t*x)/2+z.spriteBlurPx*2,r=(t*b+e*x)/2+z.spriteBlurPx*2;for(let e of u){let t=e.x-d.x,i=e.y-d.y;t>=y.x+n||t+e.width<=y.x-n||i>=y.y+r||i+e.height<=y.y-r||w.push({x:t,y:i,width:e.width,height:e.height})}}if(!w.length)C(1);else{g.save();for(let e of w)g.beginPath(),g.rect(0,0,s,c),g.rect(e.x,e.y,e.width,e.height),g.clip(`evenodd`);C(1),g.restore(),g.save(),g.beginPath();for(let e of w)g.rect(e.x,e.y,e.width,e.height);g.clip(),C(z.insideWallSpriteOpacity),g.restore()}}},of=64,sf=e=>e.width>0&&e.height>0&&e.width<=64&&e.height<=64&&e.pixelWidth<=128&&e.pixelHeight<=128&&e.fixedRadius===void 0&&e.blastAge===void 0&&!e.smokeOnly,cf=class{groups=new Map;combine(e,t,n){let r=e.filter(sf);if(r.length<of)return[...e];let i=Math.ceil(t/2),a=Math.ceil(n/2),o=e.filter(e=>!sf(e)),s=new Map;for(let e of r){let t=Math.max(0,Math.min(.999,e.age/Math.max(.01,e.burnSeconds))),n=Math.floor(t*4),r=s.get(n)??[];r.push(e),s.set(n,r)}for(let[e,r]of s){let s=this.groups.get(e);s&&s.alpha.length===i*a||(s={key:{},alpha:new Uint8Array(i*a),revision:0},this.groups.set(e,s)),s.alpha.fill(0);let c=!1;for(let e of r)c=this.rasterize(s.alpha,i,a,e,t,n)||c;if(!c)continue;s.revision++;let l=r.reduce((e,t)=>e+t.age/Math.max(.01,t.burnSeconds),0)/r.length;o.push({key:s.key,alpha:s.alpha,pixelWidth:i,pixelHeight:a,x:0,y:0,width:t,height:n,origin:{x:t/2,y:n/2},age:l,farthest:Math.max(t,n),spreadSeconds:0,burnSeconds:1,smokeRate:r.reduce((e,t)=>e+(t.smokeRate??13),0)/r.length,revision:s.revision})}return o}rasterize(e,t,n,r,i,a){let o=t/i,s=n/a,c=r.x+r.width/2,l=r.y+r.height/2,u=Math.cos(r.angle??0),d=Math.sin(r.angle??0),f=Math.hypot(r.width,r.height)/2,p=Math.max(0,Math.floor((c-f)*o)),m=Math.min(t-1,Math.ceil((c+f)*o)),h=Math.max(0,Math.floor((l-f)*s)),g=Math.min(n-1,Math.ceil((l+f)*s)),_=!1;for(let n=h;n<=g;n++){let i=(n+.5)/s-l;for(let a=p;a<=m;a++){let s=(a+.5)/o-c,l=s*u+i*d+r.width/2,f=-s*d+i*u+r.height/2;if(l<0||l>=r.width||f<0||f>=r.height)continue;let p=Math.floor(l/r.width*r.pixelWidth),m=Math.floor(f/r.height*r.pixelHeight),h=Math.round((r.alpha[m*r.pixelWidth+p]??0)*(r.intensity??1)),g=n*t+a;h>e[g]&&(e[g]=h),_||=h>0}}return _}},lf=class{points=[];get count(){return this.points.length}get managedBytes(){return this.points.length*40}captureState(){return{points:this.points.map(({point:e,...t})=>({point:{...e},...t})),dispose:()=>void 0}}restoreState(e){this.points=e?.points.map(({point:e,...t})=>({point:{...e},...t}))??[]}reset(){this.points=[]}dispose(){this.reset()}ignite(e,t,n,r,i){let a=k(t,e),o=Math.max(1,Math.ceil(M(a)/Math.max(1,i)));for(let t=1;t<=o;t++)this.points.push({point:O(e,A(a,t/o)),width:n,age:0,lifetime:r});this.points.length>1200&&this.points.splice(0,this.points.length-1200)}step(e){let t=0;for(let n of this.points)n.age+=e,n.age<n.lifetime&&(this.points[t++]=n);this.points.length=t}stamps(){return this.points.map(({point:e,width:t,age:n,lifetime:r})=>({point:e,radius:Math.max(5,t*.8),progress:.42,flow:D(0,-25),strength:Math.max(0,1-(n/r)**2)*1.85,stir:!1}))}emberSource(){if(!this.points.length)return null;let e=this.points[Math.floor(Math.random()*this.points.length)];return{point:e.point,radius:e.width*.42,heat:Math.max(0,1-(e.age/e.lifetime)**2)}}},uf=5120,df=5121,ff=5122,pf=5123,mf=5124,hf=5125,gf=5126,_f=32819,vf=32820,yf=33635,bf=5131,xf=33640,Sf=35899,Cf=35902,wf=36269,Tf=34042,Ef={};{let e=Ef;e[uf]=Int8Array,e[df]=Uint8Array,e[ff]=Int16Array,e[pf]=Uint16Array,e[mf]=Int32Array,e[hf]=Uint32Array,e[gf]=Float32Array,e[_f]=Uint16Array,e[vf]=Uint16Array,e[yf]=Uint16Array,e[bf]=Uint16Array,e[xf]=Uint32Array,e[Sf]=Uint32Array,e[Cf]=Uint32Array,e[wf]=Uint32Array,e[Tf]=Uint32Array}function Df(...e){console.error(...e)}var Of=new Map;function kf(e,t){if(!e||typeof e!=`object`)return!1;let n=Of.get(t);n||(n=new WeakMap,Of.set(t,n));let r=n.get(e);if(r===void 0){let i=Object.prototype.toString.call(e);r=i.substring(8,i.length-1)===t,n.set(e,r)}return r}function Af(e,t){return typeof WebGLBuffer<`u`&&kf(t,`WebGLBuffer`)}function jf(e,t){return typeof WebGLTexture<`u`&&kf(t,`WebGLTexture`)}function Mf(e,t){return typeof WebGLSampler<`u`&&kf(t,`WebGLSampler`)}var Nf=35044,Pf=34962;function Ff(e,t,n,r,i){e.bindBuffer(t,n),e.bufferData(t,r,i||Nf)}function If(e,t,n,r){if(Af(e,t))return t;n||=Pf;let i=e.createBuffer();return Ff(e,n,i,t,r),i}function Lf(e){return!!e.texStorage2D}var Rf=function(){let e={},t={};function n(n){let r=n.constructor.name;if(!e[r]){for(let e in n)if(typeof n[e]==`number`){let r=t[n[e]];t[n[e]]=r?`${r} | ${e}`:e}e[r]=!0}}return function(e,r){return n(e),t[r]||(typeof r==`number`?`0x${r.toString(16)}`:r)}}();new Uint8Array([128,192,255,255]);var zf=6406,Bf=6407,Vf=6408,Hf=6409,Uf=6410,Wf=6402,Gf=34041,Kf=3553,qf=34067,Jf=32879,Yf=35866,Xf=34069,Zf=10241,Qf=10240,$f=10242,ep=10243,tp=32882,np=33082,rp=33083,ip=33084,ap=33085,op=34892,sp=34893,cp=37443,lp=37441,up=37440,dp=33321,fp=36756,pp=33325,mp=33326,hp=33330,gp=33329,_p=33338,vp=33337,yp=33340,bp=33339,xp=33323,Sp=36757,Cp=33327,wp=33328,Tp=33336,Ep=33335,Dp=33332,Op=33331,kp=33334,Ap=33333,jp=32849,Mp=35905,Np=36194,Pp=36758,Fp=35898,Ip=35901,Lp=34843,Rp=34837,zp=36221,Bp=36239,Vp=36215,Hp=36233,Up=36209,Wp=36227,Gp=32856,Kp=35907,qp=36759,Jp=32855,Yp=32854,Xp=32857,Zp=34842,Qp=34836,$p=36220,em=36238,tm=36975,nm=36214,rm=36232,im=36226,am=36208,om=33189,sm=33190,cm=36012,lm=36013,um=35056,dm=5120,fm=5121,pm=5122,mm=5123,hm=5124,gm=5125,_m=5126,vm=32819,ym=32820,bm=33635,xm=5131,Sm=36193,Cm=33640,wm=35899,Tm=35902,Em=36269,Dm=34042,Om=33319,km=33320,Am=6403,jm=36244,Mm=36248,Nm=36249,Pm=33776,Fm=33777,Im=33778,Lm=33779,Rm=35916,zm=35917,Bm=35918,Vm=35919,Hm=36196,Um=37488,Wm=37489,Gm=37490,Km=37491,qm=37492,Jm=37493,Ym=37494,Xm=37495,Zm=37496,Qm=37497,$m=35840,eh=35841,th=35842,nh=35843,rh=37808,ih=37809,ah=37810,oh=37811,sh=37812,ch=37813,lh=37814,uh=37815,dh=37816,fh=37817,ph=37818,mh=37819,hh=37820,gh=37821,_h=37840,vh=37841,yh=37842,bh=37843,xh=37844,Sh=37845,Ch=37846,wh=37847,Th=37848,Eh=37849,Dh=37850,Oh=37851,kh=37852,Ah=37853,jh=36492,Mh=36493,Nh=36494,Ph=36495,Fh=36283,Ih=36284,Lh=36285,Rh=36286,zh={};{let e=zh;e[zf]={numColorComponents:1},e[Hf]={numColorComponents:1},e[Uf]={numColorComponents:2},e[Bf]={numColorComponents:3},e[Vf]={numColorComponents:4},e[Am]={numColorComponents:1},e[jm]={numColorComponents:1},e[Om]={numColorComponents:2},e[km]={numColorComponents:2},e[Bf]={numColorComponents:3},e[Mm]={numColorComponents:3},e[Vf]={numColorComponents:4},e[Nm]={numColorComponents:4},e[Wf]={numColorComponents:1},e[Gf]={numColorComponents:2}}var Bh;function Vh(e){if(!Bh){let e={};e[zf]={textureFormat:zf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[fm,xm,Sm,_m]},e[Hf]={textureFormat:Hf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[fm,xm,Sm,_m]},e[Uf]={textureFormat:Uf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2,4,4,8],type:[fm,xm,Sm,_m]},e[Bf]={textureFormat:Bf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,6,6,12,2],type:[fm,xm,Sm,_m,bm]},e[Vf]={textureFormat:Vf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,8,8,16,2,2],type:[fm,xm,Sm,_m,vm,ym]},e[Wf]={textureFormat:Wf,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[gm,mm]},e[dp]={textureFormat:Am,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1],type:[fm]},e[fp]={textureFormat:Am,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[1],type:[dm]},e[pp]={textureFormat:Am,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4,2],type:[_m,xm]},e[mp]={textureFormat:Am,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[4],type:[_m]},e[hp]={textureFormat:jm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[fm]},e[gp]={textureFormat:jm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[dm]},e[Dp]={textureFormat:jm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[mm]},e[Op]={textureFormat:jm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[pm]},e[kp]={textureFormat:jm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[gm]},e[Ap]={textureFormat:jm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[hm]},e[xp]={textureFormat:Om,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2],type:[fm]},e[Sp]={textureFormat:Om,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[2],type:[dm]},e[Cp]={textureFormat:Om,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[8,4],type:[_m,xm]},e[wp]={textureFormat:Om,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[8],type:[_m]},e[Tp]={textureFormat:km,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[fm]},e[Ep]={textureFormat:km,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[dm]},e[_p]={textureFormat:km,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[mm]},e[vp]={textureFormat:km,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[pm]},e[yp]={textureFormat:km,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[gm]},e[bp]={textureFormat:km,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[hm]},e[jp]={textureFormat:Bf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3],type:[fm]},e[Mp]={textureFormat:Bf,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[fm]},e[Np]={textureFormat:Bf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,2],type:[fm,bm]},e[Pp]={textureFormat:Bf,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[dm]},e[Fp]={textureFormat:Bf,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[_m,xm,wm]},e[Ip]={textureFormat:Bf,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[_m,xm,Tm]},e[Lp]={textureFormat:Bf,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6],type:[_m,xm]},e[Rp]={textureFormat:Bf,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[_m]},e[zp]={textureFormat:Mm,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[fm]},e[Bp]={textureFormat:Mm,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[dm]},e[Vp]={textureFormat:Mm,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[mm]},e[Hp]={textureFormat:Mm,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[pm]},e[Up]={textureFormat:Mm,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[gm]},e[Wp]={textureFormat:Mm,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[hm]},e[Gp]={textureFormat:Vf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[fm]},e[Kp]={textureFormat:Vf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[fm]},e[qp]={textureFormat:Vf,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4],type:[dm]},e[Jp]={textureFormat:Vf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2,4],type:[fm,ym,Cm]},e[Yp]={textureFormat:Vf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2],type:[fm,vm]},e[Xp]={textureFormat:Vf,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[Cm]},e[Zp]={textureFormat:Vf,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[16,8],type:[_m,xm]},e[Qp]={textureFormat:Vf,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[16],type:[_m]},e[$p]={textureFormat:Nm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[fm]},e[em]={textureFormat:Nm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[dm]},e[tm]={textureFormat:Nm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Cm]},e[nm]={textureFormat:Nm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[mm]},e[rm]={textureFormat:Nm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[pm]},e[im]={textureFormat:Nm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[hm]},e[am]={textureFormat:Nm,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[gm]},e[om]={textureFormat:Wf,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[mm,gm]},e[sm]={textureFormat:Wf,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[gm]},e[cm]={textureFormat:Wf,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[_m]},e[um]={textureFormat:Gf,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Dm]},e[lm]={textureFormat:Gf,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Em]},Object.keys(e).forEach(function(t){let n=e[t];n.bytesPerElementMap={},n.bytesPerElement.forEach(function(e,t){let r=n.type[t];n.bytesPerElementMap[r]=e})});let t={bytes:8,width:4,height:4},n={bytes:16,width:4,height:4};e[Pm]={textureFormat:Pm,colorRenderable:!1,textureFilterable:!0,block:t},e[Fm]={textureFormat:Fm,colorRenderable:!1,textureFilterable:!0,block:t},e[Im]={textureFormat:Im,colorRenderable:!1,textureFilterable:!0,block:n},e[Lm]={textureFormat:Lm,colorRenderable:!1,textureFilterable:!0,block:n},e[Rm]={textureFormat:Rm,colorRenderable:!1,textureFilterable:!0,block:t},e[zm]={textureFormat:zm,colorRenderable:!1,textureFilterable:!0,block:t},e[Bm]={textureFormat:Bm,colorRenderable:!1,textureFilterable:!0,block:n},e[Vm]={textureFormat:Vm,colorRenderable:!1,textureFilterable:!0,block:n},e[Hm]={textureFormat:Hm,colorRenderable:!1,textureFilterable:!0,block:t},e[Um]={textureFormat:Um,colorRenderable:!1,textureFilterable:!0,block:t},e[Wm]={textureFormat:Wm,colorRenderable:!1,textureFilterable:!0,block:t},e[Gm]={textureFormat:Gm,colorRenderable:!1,textureFilterable:!0,block:n},e[Km]={textureFormat:Km,colorRenderable:!1,textureFilterable:!0,block:n},e[qm]={textureFormat:qm,colorRenderable:!1,textureFilterable:!0,block:t},e[Jm]={textureFormat:Jm,colorRenderable:!1,textureFilterable:!0,block:t},e[Ym]={textureFormat:Ym,colorRenderable:!1,textureFilterable:!0,block:t},e[Xm]={textureFormat:Xm,colorRenderable:!1,textureFilterable:!0,block:t},e[Zm]={textureFormat:Zm,colorRenderable:!1,textureFilterable:!0,block:n},e[Qm]={textureFormat:Qm,colorRenderable:!1,textureFilterable:!0,block:n},e[$m]={textureFormat:$m,colorRenderable:!1,textureFilterable:!0,block:{bytes:32,width:8,height:8}},e[eh]={textureFormat:eh,colorRenderable:!1,textureFilterable:!0,block:{bytes:32,width:16,height:8}},e[th]={textureFormat:th,colorRenderable:!1,textureFilterable:!0,block:{bytes:32,width:8,height:8}},e[nh]={textureFormat:nh,colorRenderable:!1,textureFilterable:!0,block:{bytes:32,width:16,height:8}},e[rh]={textureFormat:rh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:4,height:4}},e[ih]={textureFormat:ih,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:5,height:4}},e[ah]={textureFormat:ah,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:5,height:5}},e[oh]={textureFormat:oh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:6,height:5}},e[sh]={textureFormat:sh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:6,height:6}},e[ch]={textureFormat:ch,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:5}},e[lh]={textureFormat:lh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:6}},e[uh]={textureFormat:uh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:8}},e[dh]={textureFormat:dh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:5}},e[fh]={textureFormat:fh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:6}},e[ph]={textureFormat:ph,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:8}},e[mh]={textureFormat:mh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:10}},e[hh]={textureFormat:hh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:12,height:10}},e[gh]={textureFormat:gh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:12,height:12}},e[_h]={textureFormat:_h,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:4,height:4}},e[vh]={textureFormat:vh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:5,height:4}},e[yh]={textureFormat:yh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:5,height:5}},e[bh]={textureFormat:bh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:6,height:5}},e[xh]={textureFormat:xh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:6,height:6}},e[Sh]={textureFormat:Sh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:5}},e[Ch]={textureFormat:Ch,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:6}},e[wh]={textureFormat:wh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:8}},e[Th]={textureFormat:Th,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:5}},e[Eh]={textureFormat:Eh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:6}},e[Dh]={textureFormat:Dh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:8}},e[Oh]={textureFormat:Oh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:10}},e[kh]={textureFormat:kh,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:12,height:10}},e[Ah]={textureFormat:Ah,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:12,height:12}},e[jh]={textureFormat:jh,colorRenderable:!1,textureFilterable:!0,block:n},e[Mh]={textureFormat:Mh,colorRenderable:!1,textureFilterable:!0,block:n},e[Nh]={textureFormat:Nh,colorRenderable:!1,textureFilterable:!0,block:n},e[Ph]={textureFormat:Ph,colorRenderable:!1,textureFilterable:!0,block:n},e[Fh]={textureFormat:Fh,colorRenderable:!1,textureFilterable:!0,block:t},e[Ih]={textureFormat:Ih,colorRenderable:!1,textureFilterable:!0,block:t},e[Lh]={textureFormat:Lh,colorRenderable:!1,textureFilterable:!0,block:t},e[Rh]={textureFormat:Rh,colorRenderable:!1,textureFilterable:!0,block:t},Bh=e}let t=Bh[e];if(!t)throw Error(`unknown internal format`);return t}function Hh(e){let t=Vh(e);if(!t)throw Error(`unknown internal format`);return{format:t.textureFormat,type:t.type?.[0]??fm}}function Uh(e,t,n){let r,i,a;t.colorspaceConversion!==void 0&&(r=e.getParameter(cp),e.pixelStorei(cp,t.colorspaceConversion)),t.premultiplyAlpha!==void 0&&(i=e.getParameter(lp),e.pixelStorei(lp,t.premultiplyAlpha)),t.flipY!==void 0&&(a=e.getParameter(up),e.pixelStorei(up,t.flipY)),n(),r!==void 0&&e.pixelStorei(cp,r),i!==void 0&&e.pixelStorei(lp,i),a!==void 0&&e.pixelStorei(up,a)}function Wh(e,t,n,r){r.minMag&&(n.call(e,t,Zf,r.minMag),n.call(e,t,Qf,r.minMag)),r.min&&n.call(e,t,Zf,r.min),r.mag&&n.call(e,t,Qf,r.mag),r.wrap&&(n.call(e,t,$f,r.wrap),n.call(e,t,ep,r.wrap),(t===Jf||Mf(e,t))&&n.call(e,t,tp,r.wrap)),r.wrapR&&n.call(e,t,tp,r.wrapR),r.wrapS&&n.call(e,t,$f,r.wrapS),r.wrapT&&n.call(e,t,ep,r.wrapT),r.minLod!==void 0&&n.call(e,t,np,r.minLod),r.maxLod!==void 0&&n.call(e,t,rp,r.maxLod),r.baseLevel!==void 0&&n.call(e,t,ip,r.baseLevel),r.maxLevel!==void 0&&n.call(e,t,ap,r.maxLevel),r.compareFunc!==void 0&&n.call(e,t,sp,r.compareFunc),r.compareMode!==void 0&&n.call(e,t,op,r.compareMode)}function Gh(e,t,n){let r=n.target||Kf;e.bindTexture(r,t),Wh(e,r,e.texParameteri,n)}function Kh(e,t,n){let r=n.target||Kf;e.bindTexture(r,t);let i=n.level||0,a=n.internalFormat||n.format||Vf,o=Hh(a),s=n.format||o.format,c=n.type||o.type;Uh(e,n,()=>{if(r===qf)for(let t=0;t<6;++t)e.texImage2D(Xf+t,i,a,n.width,n.height,0,s,c,null);else r===Jf||r===Yf?e.texImage3D(r,i,a,n.width,n.height,n.depth,0,s,c,null):e.texImage2D(r,i,a,n.width,n.height,0,s,c,null)})}var qh=Df;function Jh(e){return typeof document<`u`&&document.getElementById?document.getElementById(e):null}var Yh=33984,Xh=34962,Zh=34963,Qh=35713,$h=35714,eg=35632,tg=35633,ng=35981,rg=35718,ig=35721,ag=35971,og=35382,sg=35396,cg=35398,lg=35392,ug=35395,dg=5126,fg=35664,pg=35665,mg=35666,hg=5124,gg=35667,_g=35668,vg=35669,yg=35670,bg=35671,xg=35672,Sg=35673,Cg=35674,wg=35675,Tg=35676,Eg=35678,Dg=35680,Og=35679,kg=35682,Ag=35685,jg=35686,Mg=35687,Ng=35688,Pg=35689,Fg=35690,Ig=36289,Lg=36292,Rg=36293,zg=5125,Bg=36294,Vg=36295,Hg=36296,Ug=36298,Wg=36299,Gg=36300,Kg=36303,qg=36306,Jg=36307,Yg=36308,Xg=36311,Zg=3553,Qg=34067,$g=32879,e_=35866,B={};function t_(e,t){return B[t].bindPoint}function n_(e,t){return function(n){e.uniform1f(t,n)}}function r_(e,t){return function(n){e.uniform1fv(t,n)}}function i_(e,t){return function(n){e.uniform2fv(t,n)}}function a_(e,t){return function(n){e.uniform3fv(t,n)}}function o_(e,t){return function(n){e.uniform4fv(t,n)}}function s_(e,t){return function(n){e.uniform1i(t,n)}}function c_(e,t){return function(n){e.uniform1iv(t,n)}}function l_(e,t){return function(n){e.uniform2iv(t,n)}}function u_(e,t){return function(n){e.uniform3iv(t,n)}}function d_(e,t){return function(n){e.uniform4iv(t,n)}}function f_(e,t){return function(n){e.uniform1ui(t,n)}}function p_(e,t){return function(n){e.uniform1uiv(t,n)}}function m_(e,t){return function(n){e.uniform2uiv(t,n)}}function h_(e,t){return function(n){e.uniform3uiv(t,n)}}function g_(e,t){return function(n){e.uniform4uiv(t,n)}}function __(e,t){return function(n){e.uniformMatrix2fv(t,!1,n)}}function v_(e,t){return function(n){e.uniformMatrix3fv(t,!1,n)}}function y_(e,t){return function(n){e.uniformMatrix4fv(t,!1,n)}}function b_(e,t){return function(n){e.uniformMatrix2x3fv(t,!1,n)}}function x_(e,t){return function(n){e.uniformMatrix3x2fv(t,!1,n)}}function S_(e,t){return function(n){e.uniformMatrix2x4fv(t,!1,n)}}function C_(e,t){return function(n){e.uniformMatrix4x2fv(t,!1,n)}}function w_(e,t){return function(n){e.uniformMatrix3x4fv(t,!1,n)}}function T_(e,t){return function(n){e.uniformMatrix4x3fv(t,!1,n)}}function E_(e,t,n,r){let i=t_(e,t);return Lf(e)?function(t){let a,o;!t||jf(e,t)?(a=t,o=null):(a=t.texture,o=t.sampler),e.uniform1i(r,n),e.activeTexture(Yh+n),e.bindTexture(i,a),e.bindSampler(n,o)}:function(t){e.uniform1i(r,n),e.activeTexture(Yh+n),e.bindTexture(i,t)}}function D_(e,t,n,r,i){let a=t_(e,t),o=new Int32Array(i);for(let e=0;e<i;++e)o[e]=n+e;return Lf(e)?function(t){e.uniform1iv(r,o),t.forEach(function(t,r){e.activeTexture(Yh+o[r]);let i,s;!t||jf(e,t)?(i=t,s=null):(i=t.texture,s=t.sampler),e.bindSampler(n,s),e.bindTexture(a,i)})}:function(t){e.uniform1iv(r,o),t.forEach(function(t,n){e.activeTexture(Yh+o[n]),e.bindTexture(a,t)})}}B[dg]={Type:Float32Array,size:4,setter:n_,arraySetter:r_},B[fg]={Type:Float32Array,size:8,setter:i_,cols:2},B[pg]={Type:Float32Array,size:12,setter:a_,cols:3},B[mg]={Type:Float32Array,size:16,setter:o_,cols:4},B[hg]={Type:Int32Array,size:4,setter:s_,arraySetter:c_},B[gg]={Type:Int32Array,size:8,setter:l_,cols:2},B[_g]={Type:Int32Array,size:12,setter:u_,cols:3},B[vg]={Type:Int32Array,size:16,setter:d_,cols:4},B[zg]={Type:Uint32Array,size:4,setter:f_,arraySetter:p_},B[Bg]={Type:Uint32Array,size:8,setter:m_,cols:2},B[Vg]={Type:Uint32Array,size:12,setter:h_,cols:3},B[Hg]={Type:Uint32Array,size:16,setter:g_,cols:4},B[yg]={Type:Uint32Array,size:4,setter:s_,arraySetter:c_},B[bg]={Type:Uint32Array,size:8,setter:l_,cols:2},B[xg]={Type:Uint32Array,size:12,setter:u_,cols:3},B[Sg]={Type:Uint32Array,size:16,setter:d_,cols:4},B[Cg]={Type:Float32Array,size:32,setter:__,rows:2,cols:2},B[wg]={Type:Float32Array,size:48,setter:v_,rows:3,cols:3},B[Tg]={Type:Float32Array,size:64,setter:y_,rows:4,cols:4},B[Ag]={Type:Float32Array,size:32,setter:b_,rows:2,cols:3},B[jg]={Type:Float32Array,size:32,setter:S_,rows:2,cols:4},B[Mg]={Type:Float32Array,size:48,setter:x_,rows:3,cols:2},B[Ng]={Type:Float32Array,size:48,setter:w_,rows:3,cols:4},B[Pg]={Type:Float32Array,size:64,setter:C_,rows:4,cols:2},B[Fg]={Type:Float32Array,size:64,setter:T_,rows:4,cols:3},B[Eg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:Zg},B[Dg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:Qg},B[Og]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:$g},B[kg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:Zg},B[Ig]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:e_},B[Lg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:e_},B[Rg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:Qg},B[Ug]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:Zg},B[Wg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:$g},B[Gg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:Qg},B[Kg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:e_},B[qg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:Zg},B[Jg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:$g},B[Yg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:Qg},B[Xg]={Type:null,size:0,setter:E_,arraySetter:D_,bindPoint:e_};function O_(e,t){return function(n){if(n.value)switch(e.disableVertexAttribArray(t),n.value.length){case 4:e.vertexAttrib4fv(t,n.value);break;case 3:e.vertexAttrib3fv(t,n.value);break;case 2:e.vertexAttrib2fv(t,n.value);break;case 1:e.vertexAttrib1fv(t,n.value);break;default:throw Error(`the length of a float constant value must be between 1 and 4!`)}else e.bindBuffer(Xh,n.buffer),e.enableVertexAttribArray(t),e.vertexAttribPointer(t,n.numComponents||n.size,n.type||dg,n.normalize||!1,n.stride||0,n.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,n.divisor||0)}}function k_(e,t){return function(n){if(n.value){if(e.disableVertexAttribArray(t),n.value.length===4)e.vertexAttrib4iv(t,n.value);else throw Error(`The length of an integer constant value must be 4!`)}else e.bindBuffer(Xh,n.buffer),e.enableVertexAttribArray(t),e.vertexAttribIPointer(t,n.numComponents||n.size,n.type||hg,n.stride||0,n.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,n.divisor||0)}}function A_(e,t){return function(n){if(n.value){if(e.disableVertexAttribArray(t),n.value.length===4)e.vertexAttrib4uiv(t,n.value);else throw Error(`The length of an unsigned integer constant value must be 4!`)}else e.bindBuffer(Xh,n.buffer),e.enableVertexAttribArray(t),e.vertexAttribIPointer(t,n.numComponents||n.size,n.type||zg,n.stride||0,n.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,n.divisor||0)}}function j_(e,t,n){let r=n.size,i=n.count;return function(n){e.bindBuffer(Xh,n.buffer);let a=n.size||n.numComponents||r,o=a/i,s=n.type||dg,c=B[s].size*a,l=n.normalize||!1,u=n.offset||0,d=c/i;for(let r=0;r<i;++r)e.enableVertexAttribArray(t+r),e.vertexAttribPointer(t+r,o,s,l,c,u+d*r),e.vertexAttribDivisor&&e.vertexAttribDivisor(t+r,n.divisor||0)}}var M_={};M_[dg]={size:4,setter:O_},M_[fg]={size:8,setter:O_},M_[pg]={size:12,setter:O_},M_[mg]={size:16,setter:O_},M_[hg]={size:4,setter:k_},M_[gg]={size:8,setter:k_},M_[_g]={size:12,setter:k_},M_[vg]={size:16,setter:k_},M_[zg]={size:4,setter:A_},M_[Bg]={size:8,setter:A_},M_[Vg]={size:12,setter:A_},M_[Hg]={size:16,setter:A_},M_[yg]={size:4,setter:k_},M_[bg]={size:8,setter:k_},M_[xg]={size:12,setter:k_},M_[Sg]={size:16,setter:k_},M_[Cg]={size:4,setter:j_,count:2},M_[wg]={size:9,setter:j_,count:3},M_[Tg]={size:16,setter:j_,count:4};var N_=/ERROR:\s*\d+:(\d+)/gi;function P_(e,t=``,n=0){let r=[...t.matchAll(N_)],i=new Map(r.map((e,n)=>{let i=parseInt(e[1]),a=r[n+1],o=a?a.index:t.length,s=t.substring(e.index,o);return[i-1,s]}));return e.split(`
|
|
@@ -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').
|