@joy-ride/joy-ride 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1237 +0,0 @@
1
- var e=Object.freeze({speedFactor:.5,rampMs:300,zoomFactor:0,curve:`ease-in-out`}),t={linear:e=>e,"ease-in":e=>e*e,"ease-out":e=>e*(2-e),"ease-in-out":e=>e*e*(3-2*e)},n={linear:e=>e*e/2,"ease-in":e=>e*e*e/3,"ease-out":e=>e*e-e*e*e/3,"ease-in-out":e=>e*e*e-e*e*e*e/2},r=class{settings={...e};enabled=!1;speed=1;zoom=1;fromSpeed=1;fromZoom=1;elapsed=0;constructor(e={}){this.configure(e)}get options(){return{...this.settings}}get active(){return this.enabled}get speedFactor(){return this.speed}get zoomFactor(){return this.zoom}configure(e){let n={...this.settings,...e};if(!Number.isFinite(n.speedFactor)||n.speedFactor<=0||n.speedFactor>1)throw RangeError(`Slow-mo speedFactor must be greater than zero and at most one.`);if(!Number.isFinite(n.rampMs)||n.rampMs<0)throw RangeError(`Slow-mo rampMs must be a nonnegative number.`);if(!Number.isFinite(n.zoomFactor)||n.zoomFactor<0||n.zoomFactor>4)throw RangeError(`Slow-mo zoomFactor must be between 0 and 4.`);if(!Object.hasOwn(t,n.curve))throw TypeError(`Unknown slow-mo curve.`);this.settings=n,this.beginRamp()}setActive(e){this.enabled!==e&&(this.enabled=e,this.beginRamp())}start(){this.setActive(!0)}stop(){this.setActive(!1)}beginRamp(){this.fromSpeed=this.speed,this.fromZoom=this.zoom,this.elapsed=0,this.settings.rampMs||this.advance(0)}advance(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Slow-mo elapsed time must be a nonnegative number.`);let r=this.enabled?this.settings.speedFactor:1,i=this.enabled&&this.settings.zoomFactor||1,a=this.settings.rampMs/1e3;if(!a||this.elapsed>=a)return this.speed=r,this.zoom=i,e*r;let o=this.elapsed/a,s=Math.min(e,a-this.elapsed);this.elapsed+=s;let c=Math.min(1,this.elapsed/a),l=t[this.settings.curve](c);this.speed=this.fromSpeed+(r-this.fromSpeed)*l,this.zoom=this.fromZoom+(i-this.fromZoom)*l;let u=n[this.settings.curve](c)-n[this.settings.curve](o);return s*this.fromSpeed+a*(r-this.fromSpeed)*u+(e-s)*r}reset(){this.enabled=!1,this.speed=this.zoom=this.fromSpeed=this.fromZoom=1,this.elapsed=0}captureState(){return{options:{...this.settings},active:this.enabled,speed:this.speed,zoom:this.zoom,fromSpeed:this.fromSpeed,fromZoom:this.fromZoom,elapsed:this.elapsed}}restoreState(e){this.settings={...e.options},this.enabled=e.active,this.speed=e.speed,this.zoom=e.zoom,this.fromSpeed=e.fromSpeed,this.fromZoom=e.fromZoom,this.elapsed=e.elapsed}},i=new WeakMap;function a(e){let t=i.get(e);return!t&&typeof e.createConstantSource==`function`&&(t=e.createConstantSource(),t.offset.value=0,t.start(),i.set(e,t)),t}function o(e,t){let n=a(e);if(!n)return;let r=1200*Math.log2(Number.isFinite(t)&&t>0?Math.min(1,t):1),i=e.currentTime;n.offset.cancelScheduledValues(i),n.offset.setValueAtTime(n.offset.value,i),n.offset.linearRampToValueAtTime(r,i+1/120)}function s(e){let t=i.get(e);t&&(t.stop(),t.disconnect(),i.delete(e))}function c(e){if(!e.detune||!e.context)return e;let t=a(e.context);return t&&(t.connect(e.detune),e.addEventListener(`ended`,()=>{try{t.disconnect(e.detune)}catch{}},{once:!0})),e}var l=`data:audio/mpeg;base64,SUQzBAAAAAAAIlRTU0UAAAAOAAADTGF2ZjYzLjEuMTAyAAAAAAAAAAAAAAD/83DAAAAAAAAAAAAASW5mbwAAAA8AAAAPAAAJ5QAiIiIiIiIyMjIyMjIyQUFBQUFBUVFRUVFRUWFhYWFhYWFxcXFxcXGBgYGBgYGBkZGRkZGRkaCgoKCgoLCwsLCwsLDAwMDAwMDA0NDQ0NDQ4ODg4ODg4PDw8PDw8PD///////8AAAAATGF2YzYzLjEuAAAAAAAAAAAAAAAAJAQSAAAAAAAACe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B7GuB7GuB7BTB7NVB7VXB7VYB7VZB7RaB7NbB7JbB7BbB69bB65bB65bB65cB61fB6thB6xkB6xwB6xvB6xwB6txB6h1CKh1CKl0CKpzCKpyCKpxCKo8B6s8B6s7B6o6B6l2CKd3CKReB6NeB6VdB6ddB6biCKXiCKTMCKTLCKPKCKLICJ+PCJyNCJyMCJq2CJ21CJ60CJ60CJ2zCJqyCJexCJPNCI+sBpCtBpCuBo6vBouxBoeyBoKzBnvMCHjKCHfJCHbHCHXHCHPHCHDJCGzLCGaYCGOZCGCZCFvZCFjbCFTbCE8KCUoJCUMJCTsJCTEKCSSwCBc=`;function v(e){let t=e;return()=>(t^=t<<13,t^=t>>>17,t^=t<<5,(t>>>0)/2147483648-1)}var y={"collision-soft":{level:.11,decay:.085,strikes:[[.006,1],[.029,.26]]},"collision-medium":{level:.16,decay:.14,strikes:[[.007,1],[.026,.42],[.057,.2]]},"collision-hard":{level:.22,decay:.2,strikes:[[.008,1],[.024,.47],[.048,.32],[.081,.18]]}};function b(e,t,n){let r=y[n],i=[570,1010,1690,2680,4230],a=[.48,.4,.3,.2,.12],o=[.2,1.7,3.1,4.6,5.8],s=i.map(()=>0),c=r.strikes,l=0,u=0,d=0,f=v(n===`collision-soft`?403364:n===`collision-medium`?581137:1011779);for(let n=0;n<e.length;n++){let p=n/t;for(;l<c.length&&p>=c[l][0];){let e=c[l][1];for(let t=0;t<s.length;t++)s[t]+=e;u+=e,l++}let m=0;for(let e=0;e<s.length;e++){let n=r.decay*(1-e*.14);s[e]*=Math.exp(-1/(t*n));let c=1+.018*Math.exp(-p/.035);o[e]+=2*Math.PI*i[e]*c/t,m+=Math.sin(o[e])*s[e]*a[e]}let h=f();d+=(h-d)*.29,u*=Math.exp(-1/(t*.022)),e[n]+=r.level*(m*.63+(h-d)*u*.22)}}function x(e,t){let n=[[.004,1],[.012,.75],[.023,.55],[.035,.28]],r=[[.029,1],[.065,.38]],i=v(504037),a=0,o=0,s=0,c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=1-Math.exp(-2*Math.PI*5200/t);for(let _=0;_<e.length;_++){let v=_/t;for(;d<n.length&&v>=n[d][0];)s+=n[d][1],c+=n[d][1],d++;for(;f<r.length&&v>=r[f][0];)l+=r[f][1],f++;let y=i();a+=(y-a)*.09,o+=(y-o)*.32,u+=(i()-u)*.006,s*=Math.exp(-1/(t*.0045)),c*=Math.exp(-1/(t*.018)),l*=Math.exp(-1/(t*.052));let b=o-a,x=(y-o)*.27+b*.55,S=(a*1.05+b*.18)*(.85+u*.5),C=2.3*(e[_]*.17+x*s*.65+b*c*.15+S*l*1.2);p+=(C-p)*g,m+=(p-m)*g,h+=(m-h)*g,e[_]=h}}function S(e,t,n){if(n===`crush`)x(e,t);else if(n===`collision-soft`||n===`collision-medium`||n===`collision-hard`)b(e,t,n);else return;for(let t=0;t<e.length;t++){let n=Math.abs(e[t]);n>.8&&(e[t]=Math.sign(e[t])*(.8+.18*Math.tanh((n-.8)/.18)))}}function C(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/e.length)}function w(e,t){let n=C(e),r=v(989808),i=[[.31,.45],[.52,.7],[.79,.5],[1.04,.8],[1.28,.55]],a=0,o=0,s=0,c=0,l=1-Math.exp(-2*Math.PI*170/t),u=1-Math.exp(-2*Math.PI*1500/t),d=Math.exp(-1/(t*.006));for(let n=0;n<e.length;n++){let f=n/t;for(;c<i.length&&f>=i[c][0];)s+=i[c][1],c++;let p=e[n];a+=(p-a)*l,o+=(p-o)*u,s*=d,e[n]=a*.55+(o-a)*.5+(p-o)*.42+r()*s*.04}let f=n/Math.max(1e-6,C(e))*.9;for(let t=0;t<e.length;t++)e[t]*=f}function ee(e,t){let[n,r]=t.tracks;if(!n||!r)return;let i=t.sampleRate,a=v(466480),o=[110,145].map(e=>Math.exp(-Math.PI*e/i)),s=[n.frequency[0],r.frequency[0]],c=[0,0],l=[0,0],u=1-Math.exp(-1/(i*.025)),d=0,f=0,p=0,m=0,h=0,g=1-Math.exp(-2*Math.PI*650/i);for(let _=0;_<e.length;_++){let v=Math.min(t.frames-2,Math.floor(_/t.hop)),y=(_-v*t.hop)/t.hop,b=10**((t.envelope[Math.min(t.envelope.length-1,Math.floor(_/t.envelopeHop))]*90/255-90)/20);h+=(b-h)*u,d+=(a()-d)*.003;let x=[n,r],S=0;for(let e=0;e<2;e++){let t=x[e].frequency[v]*(1-y)+x[e].frequency[v+1]*y;s[e]+=(t-s[e])*u;let n=s[e]*(1+d*.03),r=o[e],f=a()*(e===0?.008:.011),p=2*r*Math.cos(2*Math.PI*n/i)*c[e]-r*r*l[e]+f;l[e]=c[e],c[e]=p,S+=p*(e===0?1.15:.9)}let C=Math.min(1.6,h/.18);f+=(e[_]-f)*.11;let w=(e[_]-f)*.65+S*C*1.25;p+=(w-p)*g;let ee=w-p;m+=(ee-m)*g,e[_]=(ee-m)*1.15}}function te(e,t){if(t.id===`burning-fire`)w(e,t.sampleRate);else if(t.id===`tire-screech`)ee(e,t);else return;for(let t=0;t<e.length;t++){let n=Math.abs(e[t]);n>.8&&(e[t]=Math.sign(e[t])*(.8+.18*Math.tanh((n-.8)/.18)))}}var ne=[60,90,130,190,270,380,530,730,1e3,1400,1950,2700,3700,5100,7e3,9600,13200,15600],re=1024,ie=Float32Array.from({length:re},(e,t)=>.5-.5*Math.cos(2*Math.PI*t/1023)),ae=ie.reduce((e,t)=>e+t,0),oe=Float32Array.from({length:256},(e,t)=>10**((t*90/255-90)/20));function se(e){let t=new DataView(e),n=0,r=()=>t.getUint8(n++),i=()=>{let e=t.getUint16(n,!0);return n+=2,e},a=()=>{let e=t.getUint32(n,!0);return n+=4,e};if(String.fromCharCode(r(),r(),r(),r())!==`JRSM`||r()!==1)throw Error(`Unsupported spectral model format.`);let o=r();if(o!==ne.length)throw Error(`Unexpected spectral band count.`);let s=i(),c=i(),l=i(),u=r(),d=new Map;for(let t=0;t<u;t++){let t=r(),u=new TextDecoder().decode(new Uint8Array(e,n,t));n+=t;let f=a(),p=i(),m=i(),h=r(),g=new Uint8Array(e,n,p*o);n+=g.length;let _=new Uint8Array(e,n,m);n+=_.length;let v=[];for(let e=0;e<h;e++){let e=new Uint16Array(p),t=new Uint8Array(p);for(let n=0;n<p;n++)e[n]=i(),t[n]=r();v.push({frequency:e,amplitude:t})}d.set(u,{id:u,sampleRate:s,hop:c,envelopeHop:l,samples:f,frames:p,bands:g,envelope:_,tracks:v})}if(n!==e.byteLength)throw Error(`Spectral model contains unexpected trailing data.`);return d}function ce(e,t){let n=e.length;for(let r=1,i=0;r<n;r++){let a=n>>1;for(;i&a;)i^=a,a>>=1;i^=a,r<i&&([e[r],e[i]]=[e[i],e[r]],[t[r],t[i]]=[t[i],t[r]])}for(let r=2;r<=n;r*=2){let i=r/2,a=2*Math.PI/r;for(let o=0;o<n;o+=r)for(let n=0;n<i;n++){let r=n*a,s=Math.cos(r),c=Math.sin(r),l=o+n,u=l+i,d=s*e[u]-c*t[u],f=s*t[u]+c*e[u];e[u]=e[l]-d,t[u]=t[l]-f,e[l]+=d,t[l]+=f}}for(let t=0;t<n;t++)e[t]/=n}function le(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return t>>>0}function*ue(e){let t=new Float32Array(e.samples),n=new Float32Array(e.samples),r=new Float32Array(re),i=new Float32Array(re),a=ne.length,o=le(e.id),s=()=>(o^=o<<13,o^=o>>>17,o^=o<<5,(o>>>0)/4294967296),c=Array.from({length:513},(t,n)=>{let r=n*e.sampleRate/re,i=ne.findIndex(e=>e>=r);i<0&&(i=ne.length-1);let a=Math.max(0,i-1),o=a===i?0:Math.max(0,Math.min(1,Math.log(r/ne[a])/Math.log(ne[i]/ne[a])));return{left:a,right:i,fraction:o}});for(let o=0;o<e.frames;o++){o%16==0&&(yield),r.fill(0),i.fill(0);let l=o*a;for(let t=1;t<re/2;t++){let{left:n,right:a,fraction:u}=c[t],d=oe[e.bands[l+n]],f=oe[e.bands[l+a]],p=Math.exp(Math.log(d)*(1-u)+Math.log(f)*u)*ae/2;for(let n of e.tracks)Math.abs(t*e.sampleRate/re-n.frequency[o])<42&&(p*=.62);let m=s()*2*Math.PI;r[t]=p*Math.cos(m),i[t]=p*Math.sin(m),r[re-t]=r[t],i[re-t]=-i[t]}ce(r,i);let u=o*e.hop-re/2;for(let e=0;e<re;e++){let i=u+e;i<0||i>=t.length||(t[i]+=r[e]*ie[e],n[i]+=ie[e]*ie[e])}}for(let e=0;e<t.length;e++)t[e]/=Math.max(.05,n[e]);for(let n of e.tracks){let r=0;for(let i=0;i<t.length;i++){i%8192==0&&(yield);let a=Math.min(e.frames-2,Math.floor(i/e.hop)),o=(i-a*e.hop)/e.hop,s=n.frequency[a]*(1-o)+n.frequency[a+1]*o,c=oe[n.amplitude[a]]*(1-o)+oe[n.amplitude[a+1]]*o;r+=2*Math.PI*s/e.sampleRate,t[i]+=Math.sin(r)*c*.42}}e.id===`crush`&&S(t,e.sampleRate,e.id);let l=new Float32Array(e.envelope.length);for(let n=0;n<l.length;n++){let r=n*e.envelopeHop,i=Math.min(t.length,r+e.envelopeHop),a=0;for(let e=r;e<i;e++)a+=t[e]**2;let o=Math.sqrt(a/Math.max(1,i-r));l[n]=Math.min(8,oe[e.envelope[n]]/Math.max(1e-4,o))}for(let n=0;n<t.length;n++){n%8192==0&&(yield);let r=Math.min(l.length-2,Math.floor(n/e.envelopeHop)),i=Math.min(1,(n-r*e.envelopeHop)/e.envelopeHop);t[n]*=l[r]*(1-i)+l[r+1]*i;let a=Math.abs(t[n]);a>.8&&(t[n]=Math.sign(t[n])*(.8+.18*Math.tanh((a-.8)/.18)))}return e.id!==`crush`&&S(t,e.sampleRate,e.id),te(t,e),t}var de=new WeakMap,fe=new WeakMap,pe=new WeakMap;function me(e,t){let n=pe.get(e);n||(n=new Map,pe.set(e,n));let r=n.get(t);if(r)return r;let i=de.get(t);if(!i){let e=ue(t),n=e.next();for(;!n.done;)n=e.next();i=n.value,de.set(t,i)}let a=e.createBuffer(1,i.length,t.sampleRate);return a.getChannelData(0).set(i),n.set(t,a),a}async function he(e,t,n){if(n?.throwIfAborted(),!de.has(t)){let e=fe.get(t);e||(e=(async()=>{let e=ue(t),n=e.next();for(;!n.done;)await new Promise(e=>setTimeout(e,0)),n=e.next();de.set(t,n.value)})().then(()=>de.get(t)),fe.set(t,e),e.finally(()=>fe.delete(t)).catch(()=>{})),await e}return n?.throwIfAborted(),me(e,t)}var ge={"electric-charge":.8,"electric-bolt":.68,"ghost-mode":1,attractor:.8},_e={"electric-charge":4310822,"electric-bolt":7516190,"ghost-mode":6882682,attractor:4880300};function ve(e,t){if(!Number.isFinite(t)||t<8e3)throw RangeError(`Invalid sample rate`);let n=Math.round(ge[e]*t),r=new Float32Array(n),i=v(_e[e]),a=()=>(i()+1)*.5,o=0,s=0,c=0;for(let i=0;i<n;i++){let l=i/t,u=i/n,d=a()*2-1;o+=(d-o)*.055;let f=d-o,p=f-s;if(s=f,e===`electric-charge`){let e=.56+.44*Math.sin(2*Math.PI*5*l)**2;a()<.0017&&(c=1),c*=.985;let t=Math.sin(2*Math.PI*90*l+.8*Math.sin(2*Math.PI*5*l))*.18+Math.sin(2*Math.PI*270*l)*.09;r[i]=(t+f*.22+p*c*.27)*e}else if(e===`electric-bolt`){let e=Math.exp(-l*125),t=Math.exp(-l*14),n=Math.exp(-l*5.5),a=Math.exp(-Math.max(0,l-.052)*100)*+(l>=.052)*.32+Math.exp(-Math.max(0,l-.11)*90)*+(l>=.11)*.15;r[i]=p*(.58*e+a)+o*2.2*t+f*.1*n+Math.sin(2*Math.PI*(165*l+950*l*l))*.12*t}else if(e===`ghost-mode`){let e=Math.sin(2*Math.PI*2*u),t=.6+.4*e*e;r[i]=(Math.sin(2*Math.PI*80*l+1.8*e)*.12+Math.sin(2*Math.PI*160*l-1.1*e)*.075+o*.7+f*.075)*t}else{let e=.65+.35*Math.sin(2*Math.PI*5*u)**2;r[i]=(Math.sin(2*Math.PI*100*l+.2*Math.sin(2*Math.PI*5*l))*.19+Math.sin(2*Math.PI*300*l)*.09+Math.sin(2*Math.PI*700*l)*.035+o*.6+f*.12)*e}}for(let e=0;e<n;e++)r[e]=.98*Math.tanh(r[e]/.98);if(e!==`electric-bolt`){let e=Math.round(t*.06),i=new Float32Array(n-e);i.set(r.subarray(e));for(let t=0;t<e;t++){let a=t/(e-1)*(Math.PI/2);i[i.length-e+t]=r[n-e+t]*Math.cos(a)+r[t]*Math.sin(a)}let a=i[0]-i[i.length-1],o=Math.round(t*.003);for(let e=0;e<o;e++)i[i.length-o+e]+=a*(e/(o-1));return i}{let e=Math.round(t*.04);for(let t=0;t<e;t++)r[n-e+t]*=1-t/e}return r}function ye(e,t){let n=ve(t,e.sampleRate),r=e.createBuffer(1,n.length,e.sampleRate);return r.getChannelData(0).set(n),r}var be={"collision-soft":{kind:`recording`,url:l},"collision-medium":{kind:`recording`,url:u},"collision-hard":{kind:`recording`,url:d},crush:{kind:`recording`,url:f},"burning-fire":{kind:`recording`,url:p},"tire-screech":{kind:`recording`,url:m},"starter-light":{kind:`recording`,url:h},"starter-heavy":{kind:`recording`,url:g},"machine-gun":{kind:`synthetic`,model:`machine-gun`},"bullet-ricochet-1":{kind:`synthetic`,model:`bullet-ricochet-1`},"bullet-ricochet-2":{kind:`synthetic`,model:`bullet-ricochet-2`},"bullet-ricochet-3":{kind:`synthetic`,model:`bullet-ricochet-3`},"rocket-launch":{kind:`synthetic`,model:`rocket-launch`},"rocket-explosion":{kind:`synthetic`,model:`rocket-explosion`},"combustible-explosion":{kind:`synthetic`,model:`combustible-explosion`},"electric-charge":{kind:`procedural`,effect:`electric-charge`},"electric-bolt":{kind:`procedural`,effect:`electric-bolt`},"ghost-mode":{kind:`procedural`,effect:`ghost-mode`},attractor:{kind:`procedural`,effect:`attractor`}};async function xe(e,t){if(e.startsWith(`data:`)){let t=atob(e.slice(e.indexOf(`,`)+1));return Uint8Array.from(t,e=>e.charCodeAt(0)).buffer}let n=await fetch(e,{signal:t});if(!n.ok)throw Error(`Audio asset HTTP ${n.status}`);return n.arrayBuffer()}var Se;function Ce(){return Se??=xe(_).then(se).catch(e=>{throw Se=void 0,e}),Se}var we=class{context;buffers=new Map;abort=new AbortController;disposed=!1;constructor(e){this.context=e}async initialize(){return Promise.allSettled(Object.keys(be).filter(e=>be[e].kind!==`procedural`).map(e=>this.load(e)))}load(e){let t=be[e];return this.prepare(e,async()=>{if(t.kind===`recording`)return this.decode(t.url);if(t.kind===`procedural`)return ye(this.context,t.effect);let e=(await Ce()).get(t.model);if(!e)throw Error(`Missing sound model: ${t.model}`);return this.assertLive(),he(this.context,e,this.abort.signal)})}loadUri(e){return this.prepare(e,()=>this.decode(e))}async decode(e){let t=await xe(e,this.abort.signal);return this.assertLive(),this.context.decodeAudioData(t)}prepare(e,t){if(this.disposed)return Promise.reject(Error(`Sound bank is disposed.`));let n=this.buffers.get(e);if(n)return n;let r=t().then(e=>(this.assertLive(),e)).catch(t=>{throw this.buffers.delete(e),t});return this.buffers.set(e,r),r}assertLive(){this.abort.signal.throwIfAborted()}dispose(){this.disposed=!0,this.abort.abort(),this.buffers.clear()}},Te=new WeakMap;function Ee(e){let t=Te.get(e);return t||(t=new we(e),Te.set(e,t)),t}function De(e){Te.get(e)?.dispose(),Te.delete(e)}function Oe(e,t){let n=Ee(e);return Object.hasOwn(be,t)?n.load(t):n.loadUri(t)}var ke={engine:-9.9,starter:-8.4,tire:-19.2,horn:-20,boost:-24.4,flamethrower:-20.9,rocketFlight:-6.9,collision:-15.4,crush:-14,machineGun:-17.7,ricochet:-15.4,rocketLaunch:-12.8,rocketExplosion:-17.1,combustibleExplosion:-17.1,burningFire:-15.9,electricCharge:-20,electricBolt:-12,ghostMode:-23,attractor:-21},Ae=e=>10**(e/20),je={pitchShiftSemitones:-3,pitchDynamics:1.8},Me=(e,t=0,n=1)=>Math.max(t,Math.min(n,e)),Ne=e=>{let t=Me(e);return t*t*(3-2*t)},Pe={start:.981,end:1.4505,crossfade:.04};function Fe(e,t){let{sampleRate:n}=t,r=Math.round(Pe.start*n),i=Math.round(Pe.end*n),a=Math.round(Pe.crossfade*n);if(t.length<i)throw Error(`Tire recording is shorter than its loop region.`);let o=i-r-a,s=e.createBuffer(t.numberOfChannels,o,n);for(let e=0;e<t.numberOfChannels;e++){let n=t.getChannelData(e),c=s.getChannelData(e),l=0;for(let e=r;e<i;e++)l+=n[e];l/=i-r;let u=0,d=0,f=0;for(let e=0;e<a;e++){let t=n[r+e]-l,o=n[i-a+e]-l;u+=t*t,d+=o*o,f+=t*o}let p=Me(f/Math.sqrt(u*d||1),0,1);for(let e=0;e<o-a;e++)c[e]=n[r+a+e]-l;for(let e=0;e<a;e++){let t=e/(a-1)*Math.PI*.5,s=Math.cos(t),u=Math.sin(t),d=Math.sqrt(1+2*p*s*u);c[o-a+e]=((n[i-a+e]-l)*s+(n[r+e]-l)*u)/d}}return s}function Ie({car:e,body:t},n){return e.tires.map((r,i)=>{let a=t.velocityAt(t.world(r.local)),o=t.angle+r.angle,s=Math.abs(a.x*Math.cos(o)+a.y*Math.sin(o)),c=r.spinning?Math.abs(r.wheelSurfaceSpeedMps)||s+r.slipSpeedMps:n&&!r.front?s*.35:s;return{skidding:r.skidding,slipMps:r.slipSpeedMps,speedMps:Math.hypot(a.x,a.y),wheelSpeedMps:c,loadN:t.mass*9.81*(r.front?e.frontLoadFraction:1-e.frontLoadFraction)*.5,heat:r.heat,grip:e.statusEffects.factor(`grip`,i)}})}var Le=class{context;ready;output;highpass;voices=new Set;config;clip=null;disposed=!1;constructor(e,t=e.destination,n={}){this.context=e,this.config={...je,...n},this.output=e.createGain(),this.output.gain.value=Ae(ke.tire),this.highpass=e.createBiquadFilter(),this.highpass.type=`highpass`,this.highpass.frequency.value=380,this.highpass.Q.value=.55,this.output.connect(this.highpass).connect(t),this.ready=this.load()}async load(){try{let e=await Ee(this.context).load(`tire-screech`);this.disposed||(this.clip=Fe(this.context,e))}catch(e){this.disposed||console.warn(`Joy Ride tire sound could not load.`,e)}}startVoice(e,t,n){if(!this.clip)return null;let r=c(this.context.createBufferSource()),i=this.context.createBiquadFilter(),a=this.context.createGain();r.buffer=this.clip,r.loop=!0,r.playbackRate.value=t,i.type=`lowpass`,i.frequency.value=n,i.Q.value=.55,a.gain.value=0,r.connect(i).connect(a).connect(this.output);let o={index:e,source:r,filter:i,gain:a,level:0,travel:e*.37,stopping:!1};return this.voices.add(o),r.onended=()=>{r.disconnect(),i.disconnect(),a.disconnect(),this.voices.delete(o),this.disposed&&!this.voices.size&&this.disconnect()},r.start(this.context.currentTime,e*.271%1*this.clip.duration),o}update(e,t,n){if(this.disposed)return;let r=this.context.currentTime,i=Me(e,0,.1),a=Me((1200/Math.max(200,n))**.12,.86,1.12),o=[...this.voices].filter(e=>!e.stopping);for(let e=0;e<Math.max(4,t.length);e++){let n=t[e],s=o.find(t=>t.index===e),c=Math.max(0,n?.slipMps??0),l=Math.sqrt(1-Math.exp(-c/5)),u=Math.sqrt(Math.max(0,n?.speedMps??0)/(12+Math.max(0,n?.speedMps??0))),d=Math.max(0,n?.wheelSpeedMps??0),f=Me(n?.heat??0),p=Math.sqrt(Me((n?.loadN??0)/2943,0,2.5)),m=Math.sqrt(Me(n?.grip??1,0,1.3)),h=n?.skidding?.38*Ne((c-.7)/1.1)*l*(.42+u*.58)*p*m*(.72+f*.28):0,g=.8+l*.3+Math.tanh(d/28)*.16-f*.045,_=2**(this.config.pitchShiftSemitones/12)*g**this.config.pitchDynamics*a*(1+(e-1.5)*.009),v=Math.min(this.context.sampleRate*.45,2200+l*2400+u*1500-f*550);if(!s&&h>.004&&(s=this.startVoice(e,_,v)??void 0),!s)continue;s.travel+=(d+c)*i;let y=Math.sin(s.travel*3.7+e)*.6+Math.sin(s.travel*7.13)*.4,b=h*(1+y*.035),x=b>s.level?.055:.14;s.level+=(b-s.level)*(1-Math.exp(-i/x)),s.gain.gain.setTargetAtTime(b,r,x),s.source.playbackRate.setTargetAtTime(_*(1+y*.008),r,.09),s.filter.frequency.setTargetAtTime(v,r,.11),h===0&&s.level<5e-4&&this.releaseVoice(s)}}releaseVoice(e){e.stopping||(e.stopping=!0,e.gain.gain.setTargetAtTime(0,this.context.currentTime,.008),e.source.stop(this.context.currentTime+.06))}silence(){for(let e of this.voices)this.releaseVoice(e)}disconnect(){this.output.disconnect(),this.highpass.disconnect()}dispose(){this.disposed||(this.disposed=!0,this.clip=null,this.silence(),this.voices.size||this.disconnect())}};function Re(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):1}function ze(e,t,n){if(n)return 1;let r=(e.x-t.width/2)/Math.max(1,t.width),i=(e.y-t.height/2)/Math.max(1,t.height);return Re(1-Math.hypot(r,i))}function Be(e,t,n){return ze({x:e.x-t.x,y:e.y-t.y},n,!1)}var Ve=new URL(`../embed-assets/porsche-911-997-top-BE6uRNL4.webp`,import.meta.url).href,He=new URL(`../embed-assets/ford-mustang-gt-top-DVzZTm7G.webp`,import.meta.url).href,Ue=new URL(`../embed-assets/bmw-m4-top-GKSf0h28.webp`,import.meta.url).href,We=new URL(`../embed-assets/jeep-wrangler-top-Dr43LU9c.webp`,import.meta.url).href,Ge=new URL(`../embed-assets/subaru-wrx-top-dLvMFYDs.webp`,import.meta.url).href,Ke=new URL(`../embed-assets/audi-rs3-top-Zwm7ZQ20.webp`,import.meta.url).href,qe=new URL(`../embed-assets/lamborghini-huracan-evo-top-BCJJwrTj.webp`,import.meta.url).href,Je=new URL(`../embed-assets/electric-gt-top-DTcvEjMR.webp`,import.meta.url).href,Ye={xM:-.22,revealM:.36,roundsPerSecond:11,bulletSpeedMps:72,bulletLifetimeSeconds:1.35};function Xe(e){let t={...Ye,...e.machineGuns},n=(e,t,n,r)=>Number.isFinite(e)?Math.max(n,Math.min(r,e)):t;return{xM:n(t.xM,Ye.xM,-e.geometry.lengthM/2+.5,e.geometry.lengthM/2-.5),revealM:n(t.revealM,Ye.revealM,.12,.5),roundsPerSecond:n(t.roundsPerSecond,Ye.roundsPerSecond,2,20),bulletSpeedMps:n(t.bulletSpeedMps,Ye.bulletSpeedMps,20,150),bulletLifetimeSeconds:n(t.bulletLifetimeSeconds,Ye.bulletLifetimeSeconds,.25,3)}}var Ze={rangeM:6.5,ignitionSeconds:.45,spreadSeconds:2.2,spreadRadiusPx:24,burnSeconds:4,smokePerSecond:13,jetWidthM:.5,flowRate:1};function Qe(e){let t={...Ze,...e.flamethrower},n=(e,t,n,r)=>Number.isFinite(e)?Math.max(n,Math.min(r,e)):t;return{rangeM:n(t.rangeM,Ze.rangeM,1,12),ignitionSeconds:n(t.ignitionSeconds,Ze.ignitionSeconds,.1,10),spreadSeconds:n(t.spreadSeconds,Ze.spreadSeconds,.5,30),spreadRadiusPx:n(t.spreadRadiusPx,Ze.spreadRadiusPx,0,96),burnSeconds:n(t.burnSeconds,Ze.burnSeconds,.5,30),smokePerSecond:n(t.smokePerSecond,Ze.smokePerSecond,0,50),jetWidthM:n(t.jetWidthM,Ze.jetWidthM,.2,.9),flowRate:n(t.flowRate,Ze.flowRate,.2,2)}}var $e={roundsPerSecond:1.25,launchSpeedMps:18,accelerationMps2:24,maxSpeedMps:44,lifetimeSeconds:3.1,smokePerSecond:22};function et(e){let t={...$e,...e.rockets},n=(e,t,n,r)=>Number.isFinite(e)?Math.max(n,Math.min(r,e)):t;return{roundsPerSecond:n(t.roundsPerSecond,$e.roundsPerSecond,.25,5),launchSpeedMps:n(t.launchSpeedMps,$e.launchSpeedMps,5,60),accelerationMps2:n(t.accelerationMps2,$e.accelerationMps2,0,100),maxSpeedMps:n(t.maxSpeedMps,$e.maxSpeedMps,10,100),lifetimeSeconds:n(t.lifetimeSeconds,$e.lifetimeSeconds,.5,8),smokePerSecond:n(t.smokePerSecond,$e.smokePerSecond,0,60)}}function tt(e){return{headlights:{xM:e.geometry.lengthM*.4,yM:e.geometry.widthM*.3,...e.lights?.headlights},taillights:{xM:-e.geometry.lengthM*.43,yM:e.geometry.widthM*.3,...e.lights?.taillights}}}function nt(e){return e.serviceBrakeDecelerationMps2??12}var rt={porsche911997:{id:`porsche-911-997`,name:`Porsche 911 (997)`,description:`A quick, responsive rear-engine 911 with a naturally aspirated flat-six sound profile.`,make:`Porsche`,model:`911 (997)`,year:`2004–2012`,massKg:1380,frontWeightFraction:.4,sound:{engineId:`flat6`,vehicleId:`sports`,engineLabel:`Simulated flat-six · 3.8 L`,horn:{lowHz:335,highHz:400,tone:`disc`,level:.88}},geometry:{lengthM:4.43,widthM:2.03,wheelbaseM:2.35,trackWidthM:1.68,frontTrackWidthM:1.62,rearTrackWidthM:1.74,tireLengthM:.67,tireWidthM:.29},exhaust:{layout:`left-right`},lights:{headlights:{xM:1.728,yM:.608},taillights:{xM:-1.927,yM:.649}},roofRocket:{xM:-.16,yM:0,sizeM:.76,panelColor:`#a8b0b3`},machineGuns:{xM:-.14},engineForceN:18500,reversePowerRatio:.72,rollingResistance:39,coastDecelerationMps2:4,handbrakeDecelerationMps2:10.5,lateralResistance:1750,corneringAccelerationMps2:40,maxSteerAngleRad:.67,handbrakeStrength:.68,drift:{entrySpeedMps:4.5,slipAngleRad:.3},launch:{minRpm:2200,boostMps:.6,boostedBoostMps:1.8,assistDurationSeconds:.7,burnoutRampSeconds:1.05,chargedSpinSeconds:1.35,fireLifetimeSeconds:5.3},driveBoost:{gainMps:5.2,durationSeconds:2.6,cooldownSeconds:2.2},image:{src:Ve,crop:{x:90/1774,y:74/887,width:1602/1774,height:733/887},wheelEdgeHalfWidthM:{front:.885,rear:.944}}},fordMustangGt:{id:`ford-mustang-gt-2024`,name:`Ford Mustang GT`,description:`A burbling V8 muscle car with strong acceleration and a willing rear axle.`,make:`Ford`,model:`Mustang GT`,year:`2024`,massKg:1730,frontWeightFraction:.54,sound:{engineId:`v8cross`,vehicleId:`muscle`,engineLabel:`Simulated cross-plane V8 · 5.0 L`,horn:{lowHz:330,highHz:430,tone:`trumpet`,level:1}},visual:{color:`#cc6249`,shape:`coupe`},geometry:{lengthM:4.81,widthM:1.92,wheelbaseM:2.72,trackWidthM:1.59,tireLengthM:.72,tireWidthM:.3},exhaust:{layout:`left-right`},lights:{headlights:{xM:1.826,yM:.576},taillights:{xM:-1.998,yM:.538}},roofRocket:{xM:-.1,yM:0,sizeM:.82,panelColor:`#777d80`},engineForceN:19500,reversePowerRatio:.7,rollingResistance:42,coastDecelerationMps2:3.7,handbrakeDecelerationMps2:9.2,lateralResistance:1580,corneringAccelerationMps2:35,maxSteerAngleRad:.6,handbrakeStrength:.72,drift:{entrySpeedMps:4,slipAngleRad:.3},launch:{minRpm:2600,boostMps:.5,boostedBoostMps:1.6,assistDurationSeconds:.75,burnoutRampSeconds:1.2,chargedSpinSeconds:1.5,fireLifetimeSeconds:5.6},driveBoost:{gainMps:4.3,durationSeconds:2.8,cooldownSeconds:2.4},image:{src:He,crop:{x:41/1774,y:64/887,width:1687/1774,height:754/887},wheelEdgeHalfWidthM:{front:.868,rear:.87}}},bmwM4:{id:`bmw-m4-2024`,name:`BMW M4`,description:`A quick turbo straight-six coupe that rotates cleanly and rewards precise countersteer.`,make:`BMW`,model:`M4`,year:`2024`,massKg:1750,frontWeightFraction:.52,sound:{engineId:`i6`,vehicleId:`sports`,engineLabel:`Simulated turbo inline-six · 3.0 L`,turbo:!0,horn:{lowHz:345,highHz:415,tone:`disc`,level:.86}},visual:{color:`#587d9a`,shape:`coupe`},geometry:{lengthM:4.79,widthM:1.89,wheelbaseM:2.86,trackWidthM:1.54,tireLengthM:.71,tireWidthM:.29},exhaust:{layout:`left-right`},lights:{headlights:{xM:1.876,yM:.661},taillights:{xM:-1.941,yM:.661}},roofRocket:{xM:-.12,yM:0,sizeM:.8,panelColor:`#6c7d88`},engineForceN:22500,reversePowerRatio:.72,rollingResistance:42,coastDecelerationMps2:4.2,handbrakeDecelerationMps2:10,lateralResistance:1900,corneringAccelerationMps2:39,maxSteerAngleRad:.64,handbrakeStrength:.65,drift:{entrySpeedMps:4.5,slipAngleRad:.3},launch:{minRpm:2300,boostMps:.7,boostedBoostMps:1.8,assistDurationSeconds:.7,burnoutRampSeconds:1.1,chargedSpinSeconds:1.35,fireLifetimeSeconds:5.1},driveBoost:{gainMps:4.8,durationSeconds:2.6,cooldownSeconds:2.3},image:{src:Ue,crop:{x:22/1774,y:47/887,width:1731/1774,height:795/887},scale:1.06,wheelEdgeHalfWidthM:{front:.842,rear:.851}}},jeepWrangler:{id:`jeep-wrangler-2026`,name:`Jeep Wrangler`,description:`A tall, heavy four-door SUV with deliberate steering and a wide, steady slide.`,make:`Jeep`,model:`Wrangler`,year:`2026`,massKg:2050,frontWeightFraction:.53,sound:{engineId:`v6`,vehicleId:`truck`,engineLabel:`Simulated V6 · 3.6 L`,horn:{lowHz:300,highHz:400,tone:`trumpet`,level:1}},visual:{color:`#7d8060`,shape:`suv`},geometry:{lengthM:4.78,widthM:1.88,wheelbaseM:3.01,trackWidthM:1.58,tireLengthM:.76,tireWidthM:.32},exhaust:{layout:`right`},lights:{headlights:{xM:1.818,yM:.645},taillights:{xM:-1.947,yM:.645}},roofRocket:{xM:0,yM:0,sizeM:.9,panelColor:`#777a65`},engineForceN:12500,reversePowerRatio:.73,rollingResistance:58,coastDecelerationMps2:4.8,handbrakeDecelerationMps2:11.5,lateralResistance:1850,corneringAccelerationMps2:28,maxSteerAngleRad:.53,handbrakeStrength:.64,drift:{entrySpeedMps:4.2,slipAngleRad:.3},launch:{minRpm:2200,boostMps:0,boostedBoostMps:.8,assistDurationSeconds:.8,burnoutRampSeconds:1.35,chargedSpinSeconds:1.65,fireLifetimeSeconds:5.8},driveBoost:{gainMps:2.8,durationSeconds:3,cooldownSeconds:2.7},image:{src:We,crop:{x:52/1774,y:47/887,width:1720/1774,height:786/887},scale:1.04,wheelEdgeHalfWidthM:{front:.869,rear:.874}}},subaruWrx:{id:`subaru-wrx-2024`,name:`Subaru WRX`,description:`A compact turbo boxer sedan with brisk turn-in and a playful handbrake slide.`,make:`Subaru`,model:`WRX`,year:`2024`,massKg:1550,frontWeightFraction:.54,sound:{engineId:`boxer4`,vehicleId:`sports`,engineLabel:`Simulated turbo flat-four · 2.4 L`,turbo:!0,horn:{lowHz:370,highHz:450,tone:`disc`,level:.88}},visual:{color:`#547aaf`,shape:`sedan`},geometry:{lengthM:4.67,widthM:1.83,wheelbaseM:2.67,trackWidthM:1.48,tireLengthM:.69,tireWidthM:.27},exhaust:{layout:`left-right`},lights:{headlights:{xM:1.665,yM:.635},taillights:{xM:-1.784,yM:.616}},roofRocket:{xM:-.1,yM:0,sizeM:.78,panelColor:`#60758d`},engineForceN:16600,reversePowerRatio:.73,rollingResistance:39,coastDecelerationMps2:4,handbrakeDecelerationMps2:10,lateralResistance:1740,corneringAccelerationMps2:38,maxSteerAngleRad:.65,handbrakeStrength:.69,drift:{entrySpeedMps:4,slipAngleRad:.3},launch:{minRpm:2400,boostMps:.4,boostedBoostMps:1.3,assistDurationSeconds:.7,burnoutRampSeconds:1.1,chargedSpinSeconds:1.25,fireLifetimeSeconds:4.8},driveBoost:{gainMps:3.8,durationSeconds:2.8,cooldownSeconds:2.4},image:{src:Ge,crop:{x:45/1774,y:48/887,width:1684/1774,height:793/887},scale:1.02,wheelEdgeHalfWidthM:{front:.801,rear:.811}}},audiRs3:{id:`audi-rs3-2024`,name:`Audi RS 3`,description:`A sharp five-cylinder sport sedan with punchy acceleration and fast grip recovery.`,make:`Audi`,model:`RS 3`,year:`2024`,massKg:1580,frontWeightFraction:.57,sound:{engineId:`i5`,vehicleId:`sports`,engineLabel:`Simulated turbo inline-five · 2.5 L`,turbo:!0,horn:{lowHz:400,highHz:500,tone:`disc`,level:.91}},visual:{color:`#5e7275`,shape:`sedan`},geometry:{lengthM:4.54,widthM:1.85,wheelbaseM:2.63,trackWidthM:1.52,tireLengthM:.7,tireWidthM:.28},exhaust:{layout:`left-right`},lights:{headlights:{xM:1.64,yM:.61},taillights:{xM:-1.738,yM:.61}},roofRocket:{xM:-.12,yM:0,sizeM:.76,panelColor:`#667377`},engineForceN:21e3,reversePowerRatio:.72,rollingResistance:40,coastDecelerationMps2:4.4,handbrakeDecelerationMps2:10.4,lateralResistance:1950,corneringAccelerationMps2:40,maxSteerAngleRad:.63,handbrakeStrength:.66,drift:{entrySpeedMps:4.5,slipAngleRad:.3},launch:{minRpm:2200,boostMps:.6,boostedBoostMps:1.7,assistDurationSeconds:.7,burnoutRampSeconds:1.05,chargedSpinSeconds:1.35,fireLifetimeSeconds:5.1},driveBoost:{gainMps:4.3,durationSeconds:2.7,cooldownSeconds:2.3},image:{src:Ke,crop:{x:38/1774,y:34/887,width:1699/1774,height:805/887},wheelEdgeHalfWidthM:{front:.826,rear:.83}}},lamborghiniHuracanEvo:{id:`lamborghini-huracan-evo-2023`,name:`Lamborghini Huracán EVO`,description:`A low V10 supercar with fierce acceleration, quick response, and a high-revving voice.`,make:`Lamborghini`,model:`Huracán EVO`,year:`2023`,massKg:1450,frontWeightFraction:.43,sound:{engineId:`v10`,vehicleId:`supercar`,engineLabel:`Simulated V10 · 5.2 L`,horn:{lowHz:405,highHz:515,tone:`trumpet`,level:.92}},visual:{color:`#e0a84b`,shape:`supercar`},geometry:{lengthM:4.52,widthM:1.93,wheelbaseM:2.62,trackWidthM:1.49,frontTrackWidthM:1.43,rearTrackWidthM:1.54,tireLengthM:.69,tireWidthM:.3},exhaust:{layout:`center`},lights:{headlights:{xM:1.567,yM:.675},taillights:{xM:-1.72,yM:.695}},roofRocket:{xM:-.16,yM:0,sizeM:.7,panelColor:`#b79c57`},engineForceN:26500,reversePowerRatio:.68,rollingResistance:43,coastDecelerationMps2:4.7,handbrakeDecelerationMps2:11,lateralResistance:2250,corneringAccelerationMps2:44,maxSteerAngleRad:.63,handbrakeStrength:.7,drift:{entrySpeedMps:5,slipAngleRad:.3},launch:{minRpm:2800,boostMps:.9,boostedBoostMps:2.1,assistDurationSeconds:.65,burnoutRampSeconds:.95,chargedSpinSeconds:1.5,fireLifetimeSeconds:5.6},driveBoost:{gainMps:5.7,durationSeconds:2.5,cooldownSeconds:2.1},image:{src:qe,crop:{x:46/1774,y:13/887,width:1687/1774,height:852/887},wheelEdgeHalfWidthM:{front:.792,rear:.847}}},electricGt:{id:`electric-gt`,name:`Joy Ride Electric GT`,description:`An original electric fastback with instant response and a soft, choir-like low-speed warning tone.`,make:`Joy Ride`,model:`Electric GT`,year:`2026`,massKg:1850,frontWeightFraction:.5,sound:{engineId:`i4`,vehicleId:`sports`,engineLabel:`Procedural electric motor + choir-like warning tone`,electric:{fadeStartMps:20/3.6,fadeEndMps:30/3.6,motorFadeStartMps:120/3.6,motorFadeEndMps:50},horn:{lowHz:420,highHz:500,tone:`electronic`,level:.8}},visual:{color:`#dce9ed`,shape:`sedan`},geometry:{lengthM:4.75,widthM:1.9,wheelbaseM:2.88,trackWidthM:1.59,tireLengthM:.7,tireWidthM:.29},exhaust:{layout:`center`},lights:{headlights:{xM:1.964,yM:.665},taillights:{xM:-2.008,yM:.705}},roofRocket:{xM:-.12,yM:0,sizeM:.8,panelColor:`#b9cbd1`},engineForceN:23e3,reversePowerRatio:.68,rollingResistance:42,coastDecelerationMps2:4.8,handbrakeDecelerationMps2:10.5,lateralResistance:1940,corneringAccelerationMps2:37,maxSteerAngleRad:.63,handbrakeStrength:.69,drift:{entrySpeedMps:4.4,slipAngleRad:.3},launch:{minRpm:0,boostMps:0,boostedBoostMps:1.4,assistDurationSeconds:.65,burnoutRampSeconds:.95,chargedSpinSeconds:1.3,fireLifetimeSeconds:4.6},driveBoost:{gainMps:4.5,durationSeconds:2.6,cooldownSeconds:2.2},image:{src:Je,crop:{x:31/1774,y:50/887,width:1713/1774,height:773/887},scale:1.06,wheelEdgeHalfWidthM:{front:.86,rear:.858}}}};function it(e){return e.geometry.wheelbaseM/Math.tan(e.maxSteerAngleRad)}function at(e){if(typeof e==`string`){if(!/^#[\da-f]{6}$/i.test(e))throw RangeError(`Use a six-digit hex color or an RGB tuple.`);return[1,3,5].map(t=>parseInt(e.slice(t,t+2),16))}if(!Array.isArray(e)||e.length!==3||e.some(e=>!Number.isFinite(e)||e<0||e>255))throw RangeError(`RGB channels must be finite numbers from 0 to 255.`);return[...e]}function ot(e){let t=typeof e==`string`?e:e.kind;if(!Object.hasOwn(T,t))throw Error(`Unknown liquid: ${t}`);return t}var st={oil:{family:`oil`,conductive:!1,burnable:!0,deformation:1,thickness:.86,alpha:1,color:[5,8,9],effectDistanceM:30,treadDistanceM:30,minimumGrip:.28,burnSeconds:12,burnLifetime:12,fireSpreadMps:3.2},water:{family:`water`,conductive:!0,burnable:!1,deformation:1,thickness:.14,alpha:.52,color:[116,172,196],effectDistanceM:0,treadDistanceM:15,minimumGrip:1},paint:{family:`paint`,conductive:!1,burnable:!1,deformation:1,thickness:.78,alpha:1,color:[205,49,57],effectDistanceM:0,treadDistanceM:30,minimumGrip:1},mud:{family:`mud`,conductive:!1,burnable:!1,deformation:1,thickness:.98,alpha:1,color:[104,72,45],effectDistanceM:18,treadDistanceM:34,minimumGrip:.45,speedFactor:.78,driveForceFactor:.82,contactGrip:.52,contactSpeedFactor:.72,contactDriveForceFactor:.8}},ct={gloss:0,relief:0,film:0,grain:0,fineSpray:1},T={...st,"iridescent-oil":{...st.oil,color:[22,29,31]},"clear-water":{...st.water,color:[115,173,187]},"wet-clay":{...st.mud,color:[133,91,59]},"concept-water":{...st.water,color:[104,151,159]},"concept-oil":{...st.oil,color:[17,22,24]},"concept-syrup":{...st.paint,color:[159,75,14]},"concept-clay":{...st.mud,color:[114,82,61]},"concept-lava":{...st.mud,color:[62,30,22]},"concept-acid":{...st.water,alpha:.82,color:[137,182,31]},"concept-paint":{...st.paint}},lt={oil:ct,water:ct,paint:ct,mud:ct,"iridescent-oil":{gloss:.72,relief:.7,film:.65,grain:0,fineSpray:1},"clear-water":{gloss:.85,relief:.85,film:0,grain:0,fineSpray:1},"wet-clay":{gloss:.28,relief:.55,film:0,grain:.7,fineSpray:1},"concept-water":{...ct,fineSpray:1},"concept-oil":{...ct,fineSpray:1},"concept-syrup":{...ct,fineSpray:1},"concept-clay":{...ct,fineSpray:1},"concept-lava":{...ct,fineSpray:1},"concept-acid":{...ct,fineSpray:1},"concept-paint":{...ct,fineSpray:1}};function ut(e){return T[e].family}var dt={"concept-water":{name:`Water`,description:`Fast spreading · low viscosity · clear wakes`,gravity:1800,viscosity:2.5,cohesion:20,yieldStress:0,contactDepth:.06,wetting:.3,roughness:.07,absorption:.22,iridescence:0,sediment:0,settleSeconds:12},"concept-oil":{name:`Motor oil`,description:`Slow sheets · high viscosity · persistent tire coating`,gravity:650,viscosity:12,cohesion:16,yieldStress:0,contactDepth:.16,wetting:4,roughness:.12,absorption:20,iridescence:.45,sediment:0,settleSeconds:10},"concept-syrup":{name:`Amber syrup`,description:`Slow leveling · cohesive flow · persistent coating`,gravity:220,viscosity:30,cohesion:25,yieldStress:.05,contactDepth:.32,wetting:34,roughness:.09,absorption:1.7,iridescence:0,sediment:0,settleSeconds:10},"concept-clay":{name:`Clay slurry`,description:`Yield resistance · persistent furrows · suspended sediment`,gravity:120,viscosity:22,cohesion:12,yieldStress:.8,contactDepth:.22,wetting:18,roughness:.58,absorption:5,iridescence:0,sediment:.6,settleSeconds:8},"concept-lava":{name:`Basalt lava`,description:`High yield resistance · slow transport · heavy spray`,gravity:100,viscosity:38,cohesion:30,yieldStress:1.2,contactDepth:.35,wetting:35,roughness:.65,absorption:16,iridescence:0,sediment:.85,settleSeconds:14,thermal:[1,.9,.05,0],atmosphere:{emission:.65,emissionColor:[255,112,18],pulseSeconds:7.5,vaporOpacity:.56,vaporRise:22,vaporColor:[207,104,40],embers:{density:.45,color:[255,143,35],rise:20,size:.7,brightness:.85}}},"concept-acid":{name:`Acid`,description:`Fast wetting · low viscosity · fine spray`,gravity:2100,viscosity:1.2,cohesion:14,yieldStress:0,contactDepth:.045,wetting:.1,roughness:.045,absorption:.65,iridescence:.08,sediment:0,settleSeconds:12,thermal:[.08,0,.45,.8],atmosphere:{emission:.75,emissionColor:[168,255,38],pulseSeconds:6.5,vaporOpacity:.58,vaporRise:18,vaporColor:[119,181,34]}},"concept-paint":{name:`Paint`,description:`Opaque pigment · local color mixing · marbled tire pickup`,gravity:420,viscosity:18,cohesion:18,yieldStress:.1,contactDepth:.2,wetting:9,roughness:.18,absorption:24,iridescence:0,sediment:0,settleSeconds:12,mixing:!0,surface:{microRelief:0,heightNormalScale:2.4,clearcoat:1}}};function ft(e){if(e.startsWith(`custom:`))return ht.get(e)??null;let t=e===`paint`?`concept-paint`:e===`iridescent-oil`?`concept-oil`:e===`clear-water`?`concept-water`:e===`wet-clay`?`concept-clay`:e;return t in dt?dt[t]:null}var pt={water:{coverage:.5,breakup:.32,film:.08,gloss:.9,iridescence:0,grain:0,drain:2.3,pitchM:.12,spray:1.1,impact:.3,carryM:5,emission:0},oil:{coverage:.82,breakup:.18,film:.78,gloss:.85,iridescence:.55,grain:0,drain:1.5,pitchM:.12,spray:.8,impact:.6,carryM:23,emission:0},paint:{coverage:.96,breakup:.08,film:.94,gloss:.38,iridescence:0,grain:0,drain:1.15,pitchM:.12,spray:.5,impact:.8,carryM:26,emission:0},mud:{coverage:.92,breakup:.36,film:.66,gloss:.3,iridescence:0,grain:.9,drain:1.3,pitchM:.12,spray:.45,impact:1,carryM:20,emission:0}};function mt(e){let t=pt[ut(e)],n=ft(e);return n?{...t,gloss:0,iridescence:0,grain:n.sediment,spray:1/(1+n.viscosity*.06),impact:Math.min(1,n.cohesion/30),emission:0,carryM:Math.min(28,4+n.viscosity*.7),breakup:Math.min(.65,.16+n.yieldStress*.3),drain:1.2+2/(1+n.viscosity)}:{...t,gloss:0,iridescence:0,emission:0}}var ht=new Map,gt=new Map;function _t(e){return gt.get(e)}function vt(e,t){if(!/^[a-z][a-z0-9-]{0,63}$/.test(e))throw Error(`Liquid names use lowercase letters, digits and hyphens.`);let n=`custom:${e}`;for(let e of[`conductive`,`burnable`])if(t[e]!==void 0&&typeof t[e]!=`boolean`)throw TypeError(`Liquid ${e} must be a boolean.`);if(Object.hasOwn(T,n))throw Error(`Liquid already defined: ${e}`);if(!Object.hasOwn(T,t.base))throw Error(`Choose a defined base liquid.`);for(let e of[t.thickness,t.opacity])if(e!==void 0&&(!Number.isFinite(e)||e<0||e>1))throw RangeError(`Thickness and opacity must be between 0 and 1.`);if(t.deformation!==void 0&&(!Number.isFinite(t.deformation)||t.deformation<0||t.deformation>4))throw RangeError(`Deformation must be between 0 and 4.`);let r=t.effect;for(let e of[t.burnLifetime,t.fireSpreadMps])if(e!==void 0&&(!Number.isFinite(e)||e<=0))throw RangeError(`Liquid burn lifetime and fire spread speed must be positive finite numbers.`);if(r&&(![`seconds`,`distanceM`].includes(r.lifetime.unit)||!Number.isFinite(r.lifetime.amount)||r.lifetime.amount<=0||Object.values(r.modifiers).some(e=>e!==void 0&&(!Number.isFinite(e)||e<0))||Object.values(r.additiveModifiers??{}).some(e=>e!==void 0&&!Number.isFinite(e))))throw RangeError(`Invalid liquid status effect.`);let i=T[t.base],a=t.burnable??i.burnable,o={...i,conductive:t.conductive??i.conductive,burnable:a,color:at(t.color??i.color),thickness:t.thickness??i.thickness,deformation:t.deformation??i.deformation,alpha:t.opacity??i.alpha,burnLifetime:t.burnLifetime??i.burnLifetime??i.burnSeconds??(a?st.oil.burnLifetime:void 0),fireSpreadMps:t.fireSpreadMps??i.fireSpreadMps??(a?st.oil.fireSpreadMps:void 0)};T[n]=Object.freeze(o),lt[n]={...lt[t.base]};let s=ft(t.base),c=o.thickness/Math.max(.05,i.thickness);return ht.set(n,s?{...s,viscosity:s.viscosity*Math.max(.05,c),yieldStress:s.yieldStress*c}:null),r&&gt.set(n,{...r,lifetime:{...r.lifetime},modifiers:{...r.modifiers},additiveModifiers:r.additiveModifiers?{...r.additiveModifiers}:void 0}),Object.freeze({kind:n})}function yt(e){e.startsWith(`custom:`)&&(delete T[e],delete lt[e],ht.delete(e),gt.delete(e))}function E(e,t=new WeakMap){if(typeof e==`function`)throw Error(`Functions are not checkpoint state`);if(typeof e!=`object`||!e)return e;if(t.has(e))return t.get(e);if(typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement){let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.getContext(`2d`)?.drawImage(e,0,0),t.set(e,n),n}if(typeof Node<`u`&&e instanceof Node||typeof Range<`u`&&e instanceof Range)return e;if(typeof ImageData<`u`&&e instanceof ImageData)return new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let n=[];t.set(e,n);for(let r of e)n.push(E(r,t));return n}if(ArrayBuffer.isView(e))return e instanceof DataView?new DataView(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)):new e.constructor(e);if(e instanceof Map){let n=new Map;t.set(e,n);for(let[r,i]of e)n.set(E(r,t),E(i,t));return n}if(e instanceof Set){let n=new Set;t.set(e,n);for(let r of e)n.add(E(r,t));return n}let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&!Object.keys(e).length)throw Error(`Cannot checkpoint ${e.constructor?.name??`unknown engine resource`}`);let r=Object.create(n);t.set(e,r);for(let[n,i]of Object.entries(e))r[n]=E(i,t);return r}function bt(e,t){return{lifetime:{unit:`seconds`,amount:1},modifiers:{driveForce:1.08,grip:1.04},additiveModifiers:{forwardAccelerationMps2:e/Math.max(.1,t)}}}var xt={oil:{lifetime:{unit:`distanceM`,amount:T.oil.effectDistanceM},modifiers:{grip:T.oil.minimumGrip}},mud:{lifetime:{unit:`distanceM`,amount:T.mud.effectDistanceM},modifiers:{grip:T.mud.minimumGrip,speed:T.mud.speedFactor,driveForce:T.mud.driveForceFactor}}},St={mud:{grip:T.mud.contactGrip,speed:T.mud.contactSpeedFactor,driveForce:T.mud.contactDriveForceFactor}};function Ct(e,t=0){let n=e.definition.lifetime.unit===`seconds`?Math.max(0,e.remaining-t):e.remaining,r=Math.min(1,n/e.definition.lifetime.amount);return e.definition.intensity===`constant`?+(n>0):e.definition.intensity===`pulse`?Math.sin(Math.PI*(1-r)):r}var wt=class{active=new Map;contacts=new Map;captureState(){return E({active:this.active,contacts:this.contacts})}restoreState(e){let t=E(e);this.active=t.active,this.contacts=t.contacts}setContacts(e,t,n){n.length?this.contacts.set(e,new Map(n.map(e=>[e,t]))):this.contacts.delete(e)}apply(e,t,n){if(t.lifetime.amount<=0)return;let r=this.active.get(e);r||(r=new Map,this.active.set(e,r)),r.set(n??`vehicle`,{remaining:t.lifetime.amount,definition:t})}remaining(e,t){let n=this.active.get(e);return t===void 0?Math.max(0,...[...n?.values()??[]].map(e=>e.remaining)):n?.get(t)?.remaining??0}remove(e){this.active.delete(e)}bonus(e,t,n=4,r=0){if(t===void 0){let t=0;for(let i=0;i<n;i++)t+=this.bonus(e,i,n,r);return t/n}let i=0;for(let n of this.active.values())for(let a of[`vehicle`,t]){let t=n.get(a);i+=(t?.definition.additiveModifiers?.[e]??0)*(t?Ct(t,r):0)}return i}indicators(){return[...new Set([...this.active.keys(),...this.contacts.keys()])].map(e=>{let t=this.active.get(e),n=Math.max(0,...[...t?.values()??[]].map(e=>Math.min(1,e.remaining/e.definition.lifetime.amount)));return{label:e.charAt(0).toUpperCase()+e.slice(1),fraction:this.contacts.has(e)?1:n}})}factor(e,t,n=4){return this.factorFrom(null,e,t,n)}factorFrom(e,t,n,r=4){if(n===void 0){let n=0;for(let i=0;i<r;i++)n+=this.factorFrom(e,t,i);return n/r}let i=1;for(let[r,a]of this.active)for(let o of[`vehicle`,n]){if(e!==null&&r!==e)continue;let n=a.get(o),s=n?.definition.modifiers[t];if(n&&s!==void 0){let e=Ct(n);i*=1+(s-1)*e}}for(let[r,a]of this.contacts)for(let o of[`vehicle`,n])(e===null||r===e)&&(i*=a.get(o)?.[t]??1);return i}advance(e,t){for(let[n,r]of this.active){for(let[n,i]of r){let a=i.definition.lifetime.unit===`distanceM`?e:t;i.remaining=Math.max(0,i.remaining-Math.max(0,a)),i.remaining===0&&r.delete(n)}r.size===0&&this.active.delete(n)}}clearTire(e){for(let[t,n]of this.active)n.delete(e),n.size===0&&this.active.delete(t);for(let[t,n]of this.contacts)n.delete(e),n.size===0&&this.contacts.delete(t)}clear(){this.active.clear(),this.contacts.clear()}},Tt={defaultHealth:100,smokeFraction:.5,smoulderFraction:.35,ignitionFraction:.25,damagePerSecond:48,burnDownSeconds:8,impactDamagePerMps:3.5,explosionSeconds:.8,fireballSeconds:.38,blastRadiusPx:78},Et={pixelsPerTenPoints:2500,minimum:10,maximum:1e3};function Dt(e,t,n){let r=Math.max(0,t)*Math.max(0,n);return Rt(e,`data-jr-points`,Math.min(Et.maximum,Math.max(Et.minimum,Math.round(r/Et.pixelsPerTenPoints)*10)))}var Ot=class{maxHealth;health;explodedAt=null;blastQueued=!1;blastAge=0;lastBlastEmission=-1/0;lastDamageAt=-1/0;healthBarShownAt=-1/0;constructor(e=Tt.defaultHealth){this.maxHealth=e,this.maxHealth=Math.max(1,e),this.health=this.maxHealth}get stage(){return At(this.health,this.maxHealth)}get healthFraction(){return this.health/this.maxHealth}resetBurnable(e=this.maxHealth){let t=this.health!==Math.max(1,e);this.maxHealth=Math.max(1,e),this.health=this.maxHealth,this.explodedAt=null,this.blastQueued=!1,this.blastAge=0,this.lastBlastEmission=-1/0,this.lastDamageAt=t?performance.now():-1/0,this.healthBarShownAt=this.lastDamageAt}damage(e,t=performance.now()){return this.explodedAt!==null||!Number.isFinite(e)||e<=0||(this.health=Math.max(0,this.health-e),t-this.lastDamageAt>=2900&&(this.healthBarShownAt=t),this.lastDamageAt=t,this.health>0)?!1:(this.explodedAt=t,!0)}healthBarAlpha(e=performance.now()){let t=e-this.lastDamageAt;return this.stage===`burning`&&this.health>0?Math.max(0,Math.min(1,(e-this.healthBarShownAt)/120)):t<0||t>=2900?0:Math.min(1,(e-this.healthBarShownAt)/120,(2900-t)/650)}},kt={defaultHealth:600,impactThresholdMps:3,impactDamagePerMps:5.5,maxImpactDamageFraction:.3,burningDamagePerSecond:14,respawnSeconds:2.5};function At(e,t){if(e<=0)return`exploded`;let n=e/Math.max(t,.001);return n<=Tt.ignitionFraction?`burning`:n<=Tt.smoulderFraction?`smouldering`:n<=Tt.smokeFraction?`smoking`:`intact`}function jt(e,t){let n=e/Math.max(t,.001);return Math.max(0,Math.min(1,(Tt.smokeFraction-n)/Tt.smokeFraction))}function Mt(e,t,n){let r=Math.max(1,Math.min(e,t));return Math.max(13,r*.28)+r*.52*Math.max(0,Math.min(1,n))}function Nt(e,t,n,r){let i=At(e,t);if(i===`intact`||i===`exploded`)return null;let a=jt(e,t),o=i===`burning`?Math.max(0,1-e/Math.max(t*Tt.ignitionFraction,.001)):0;return{stage:i,age:.19,spreadSeconds:0,burnSeconds:.8,fixedRadius:Mt(n,r,a),intensity:i===`burning`?.65+o*1.4:0,smokeOnly:i!==`burning`,smokeRate:i===`burning`?10+o*4:18+a*12}}function Pt(e){return{age:e,spreadSeconds:0,burnSeconds:Tt.fireballSeconds,blastAge:e,blastSeconds:Tt.fireballSeconds,smokeRate:12}}function Ft(e,t){return At(e,t)===`intact`||e<=0?0:.06+jt(e,t)*.94}function It(e,t,n=0){let r=Tt.damagePerSecond;return e===`bullet`?r/(2*Xe(t).roundsPerSecond):e===`rocket`?r/et(t).roundsPerSecond:r*Math.max(0,n)}function Lt(e,t,n){return e*Tt.ignitionFraction*t/n}function Rt(e,t,n){let r=Number(e.getAttribute(t));return Number.isFinite(r)&&r>=0&&e.hasAttribute(t)?r:n}var D=(e=0,t=0)=>({x:e,y:t}),O=(e,t)=>D(e.x+t.x,e.y+t.y),k=(e,t)=>D(e.x-t.x,e.y-t.y),A=(e,t)=>D(e.x*t,e.y*t),j=(e,t)=>e.x*t.x+e.y*t.y,zt=(e,t)=>e.x*t.y-e.y*t.x,M=e=>Math.hypot(e.x,e.y),N=(e,t)=>{let n=Math.cos(t),r=Math.sin(t);return D(e.x*n-e.y*r,e.x*r+e.y*n)},P=(e,t,n)=>Math.max(t,Math.min(n,e)),Bt=e=>Math.atan2(Math.sin(e),Math.cos(e));function Vt(e){let t=P(5.8+e.engineForceN/e.massKg*.12,6.5,8.5);return{speed:t,radius:t/P(t*Math.tan(e.maxSteerAngleRad)/e.geometry.wheelbaseM*.62,1.3,1.8)}}var Ht=class{mass=1e3;inertia=this.mass*20/12;position=D();velocity=D();angle=0;spin=0;force=D();torque=0;captureState(){return E({mass:this.mass,inertia:this.inertia,position:this.position,velocity:this.velocity,angle:this.angle,spin:this.spin,force:this.force,torque:this.torque})}restoreState(e){let t=E(e);this.mass=t.mass,this.inertia=t.inertia,this.position=t.position,this.velocity=t.velocity,this.angle=t.angle,this.spin=t.spin,this.force=t.force,this.torque=t.torque}reset(){this.position=D(),this.velocity=D(),this.angle=0,this.spin=0,this.force=D(),this.torque=0}world(e){return O(this.position,N(e,this.angle))}local(e){return N(k(e,this.position),-this.angle)}velocityAt(e){let t=k(e,this.position);return O(this.velocity,D(-this.spin*t.y,this.spin*t.x))}push(e,t=this.position){this.force=O(this.force,e),this.torque+=zt(k(t,this.position),e)}impulse(e,t=this.position){this.velocity=O(this.velocity,A(e,1/this.mass)),this.spin+=zt(k(t,this.position),e)/this.inertia}tick(e){this.velocity=O(this.velocity,A(this.force,e/this.mass)),this.spin+=this.torque*e/this.inertia,this.position=O(this.position,A(this.velocity,e)),this.angle+=this.spin*e,this.force=D(),this.torque=0}},Ut=class extends Ot{destructible=!0;get stage(){return this.destructible?super.stage:`intact`}damage(e,t=performance.now()){return this.destructible?super.damage(e,t):!1}tires=[];engineForce=0;rollingResistance=0;lateralResistance=0;handbrakeStrength=0;drifting=!1;donuting=!1;burnout=!1;launchSpinSeconds=0;boostCharge=0;boostReady=!1;get boostActive(){return this.statusEffects.remaining(`boost`)>0}burnOriginLocal=D(.7,0);statusEffects=new wt;get oilDistanceRemainingM(){return this.statusEffects.remaining(`oil`)}get oilGripFactor(){return this.statusEffects.factorFrom(`oil`,`grip`,void 0,this.tires.length||4)}oilGripFactorFor(e){return this.statusEffects.factorFrom(`oil`,`grip`,e)}coatWithOil(e){if(e===void 0)for(let e=0;e<this.tires.length;e++)this.statusEffects.apply(`oil`,xt.oil,e);else e>=0&&e<this.tires.length&&this.statusEffects.apply(`oil`,xt.oil,e)}coatWithMud(e){if(e===void 0)for(let e=0;e<this.tires.length;e++)this.statusEffects.apply(`mud`,xt.mud,e);else e>=0&&e<this.tires.length&&this.statusEffects.apply(`mud`,xt.mud,e)}washWheel(e){e>=0&&e<this.tires.length&&(this.statusEffects.clearTire(e),this.tires[e].heat=0)}advanceOil(e){this.statusEffects.advance(e,0)}frontLoadFraction=.5;slideAngleRad=0;countersteering=!1;driftDirection=0;driftStart=null;donutDirection=0;steeringAngle=0;steeringReferenceSpeed=0;previousVelocity=null;longitudinalAcceleration=0;burnoutSeconds=0;boostChargeSeconds=0;launchPeakRpm=0;launchAssistElapsed=0;launchAssistGainMps=0;preset=rt.porsche911997;constructor(){super(kt.defaultHealth),this.configure(rt.porsche911997)}captureState(){return E({maxHealth:this.maxHealth,health:this.health,explodedAt:this.explodedAt,blastQueued:this.blastQueued,blastAge:this.blastAge,lastBlastEmission:this.lastBlastEmission,lastDamageAt:this.lastDamageAt,healthBarShownAt:this.healthBarShownAt,destructible:this.destructible,tires:this.tires,engineForce:this.engineForce,rollingResistance:this.rollingResistance,lateralResistance:this.lateralResistance,handbrakeStrength:this.handbrakeStrength,drifting:this.drifting,donuting:this.donuting,burnout:this.burnout,launchSpinSeconds:this.launchSpinSeconds,boostCharge:this.boostCharge,boostReady:this.boostReady,burnOriginLocal:this.burnOriginLocal,frontLoadFraction:this.frontLoadFraction,slideAngleRad:this.slideAngleRad,countersteering:this.countersteering,driftDirection:this.driftDirection,driftStart:this.driftStart,donutDirection:this.donutDirection,steeringAngle:this.steeringAngle,steeringReferenceSpeed:this.steeringReferenceSpeed,previousVelocity:this.previousVelocity,longitudinalAcceleration:this.longitudinalAcceleration,burnoutSeconds:this.burnoutSeconds,boostChargeSeconds:this.boostChargeSeconds,launchPeakRpm:this.launchPeakRpm,launchAssistElapsed:this.launchAssistElapsed,launchAssistGainMps:this.launchAssistGainMps,statusEffects:this.statusEffects.captureState()})}restoreState(e){let t=E(e);this.maxHealth=t.maxHealth,this.health=t.health,this.explodedAt=t.explodedAt,this.blastQueued=t.blastQueued,this.blastAge=t.blastAge,this.lastBlastEmission=t.lastBlastEmission,this.lastDamageAt=t.lastDamageAt,this.healthBarShownAt=t.healthBarShownAt,this.destructible=t.destructible,this.tires=t.tires,this.engineForce=t.engineForce,this.rollingResistance=t.rollingResistance,this.lateralResistance=t.lateralResistance,this.handbrakeStrength=t.handbrakeStrength,this.drifting=t.drifting,this.donuting=t.donuting,this.burnout=t.burnout,this.launchSpinSeconds=t.launchSpinSeconds,this.boostCharge=t.boostCharge,this.boostReady=t.boostReady,this.burnOriginLocal=t.burnOriginLocal,this.frontLoadFraction=t.frontLoadFraction,this.slideAngleRad=t.slideAngleRad,this.countersteering=t.countersteering,this.driftDirection=t.driftDirection,this.driftStart=t.driftStart,this.donutDirection=t.donutDirection,this.steeringAngle=t.steeringAngle,this.steeringReferenceSpeed=t.steeringReferenceSpeed,this.previousVelocity=t.previousVelocity,this.longitudinalAcceleration=t.longitudinalAcceleration,this.burnoutSeconds=t.burnoutSeconds,this.boostChargeSeconds=t.boostChargeSeconds,this.launchPeakRpm=t.launchPeakRpm,this.launchAssistElapsed=t.launchAssistElapsed,this.launchAssistGainMps=t.launchAssistGainMps,this.statusEffects.restoreState(t.statusEffects)}takeImpact(e,t=D(.7,0)){let n=this.stage===`burning`,r=Math.max(0,e-kt.impactThresholdMps)*kt.impactDamagePerMps,i=this.damage(Math.min(r,this.maxHealth*kt.maxImpactDamageFraction));return!n&&this.health>0&&this.healthFraction<=Tt.ignitionFraction&&(this.burnOriginLocal={...t}),i}advanceBurn(e){return this.stage===`burning`&&this.damage(kt.burningDamagePerSecond*Math.max(0,e))}configure(e){this.preset=e,this.engineForce=e.engineForceN,this.rollingResistance=e.rollingResistance,this.lateralResistance=e.lateralResistance,this.handbrakeStrength=e.handbrakeStrength;let{geometry:t}=e;this.tires=[{x:t.rearAxleXM??-t.wheelbaseM/2,track:t.rearTrackWidthM??t.trackWidthM,front:!1},{x:t.frontAxleXM??t.wheelbaseM/2,track:t.frontTrackWidthM??t.trackWidthM,front:!0}].flatMap(({x:e,track:t,front:n})=>[-t/2,t/2].map(t=>({local:D(e,t),front:n,angle:0,skidding:!1,lateralSpeed:0,slipSpeedMps:0,wheelSurfaceSpeedMps:0,slip:0,heat:0,spinning:!1,lateralForceN:0,gripUtilization:0}))),this.reset()}reset(){this.resetBurnable(this.preset.health??kt.defaultHealth),this.burnOriginLocal=D(.7,0),this.drifting=!1,this.donuting=!1,this.frontLoadFraction=this.preset.frontWeightFraction??.5,this.slideAngleRad=0,this.countersteering=!1,this.driftDirection=0,this.driftStart=null,this.donutDirection=0,this.steeringAngle=0,this.steeringReferenceSpeed=0,this.previousVelocity=null,this.longitudinalAcceleration=0,this.burnout=!1,this.burnoutSeconds=0,this.launchPeakRpm=0,this.boostChargeSeconds=0,this.boostCharge=0,this.boostReady=!1,this.launchSpinSeconds=0,this.launchAssistElapsed=0,this.launchAssistGainMps=0,this.statusEffects.clear();for(let e of this.tires)e.angle=0,e.skidding=!1,e.lateralSpeed=0,e.slipSpeedMps=0,e.wheelSurfaceSpeedMps=0,e.slip=0,e.heat=0,e.spinning=!1,e.lateralForceN=0,e.gripUtilization=0}get fastDrifting(){return this.driftDirection!==0}prepareDrift(e,t){let n=M(e.velocity),r=j(e.velocity,N(D(1,0),e.angle)),i=this.preset.drift;this.fastDrifting&&(!t.action||Math.abs(t.steer)<=.2||n<i.entrySpeedMps*.65||t.throttle<=.5)&&(this.driftDirection=0),!this.fastDrifting&&t.action&&Math.abs(t.steer)>.2&&r>i.entrySpeedMps&&t.throttle>.5&&(this.driftDirection=Math.sign(t.steer),this.statusEffects.remove(`boost`)),this.driftStart=this.fastDrifting?{position:{...e.position},velocity:{...e.velocity},angle:e.angle,spin:e.spin}:null}tick(e,t,n,r){this.prepareDrift(e,t);let i=this.fastDrifting?{...t,action:!1}:t;this.tickForces(e,i,n,r)}tickForces(e,t,n,r){let i=this.burnout,a=this.boostReady&&!!t.boost;if(t.boost&&t.throttle>.5&&!t.action&&!this.fastDrifting?this.statusEffects.apply(`boost`,bt(this.preset.driveBoost.gainMps,this.preset.driveBoost.durationSeconds)):this.statusEffects.remove(`boost`),this.burnout=t.action&&t.throttle>.5&&M(e.velocity)<1.2,this.burnout){this.burnoutSeconds+=n,this.boostChargeSeconds=t.boost?this.boostChargeSeconds+n:0;let e=Math.max(.1,this.preset.launch.burnoutRampSeconds);this.boostCharge=P(this.boostChargeSeconds/e,0,1),this.boostReady=this.boostChargeSeconds>=e&&this.burnoutSeconds>=e;let i=Math.max(r??0,this.preset.launch.minRpm*Math.min(1,this.burnoutSeconds/.9));this.launchPeakRpm=Math.max(this.launchPeakRpm,i)}else i&&!t.action&&t.throttle>.5?(this.burnoutSeconds>=.25&&this.launchPeakRpm>=this.preset.launch.minRpm&&(this.launchAssistGainMps=a?this.preset.launch.boostedBoostMps:this.preset.launch.boostMps,this.launchAssistElapsed=0),this.launchSpinSeconds=a?this.preset.launch.chargedSpinSeconds:.4):this.launchSpinSeconds=Math.max(0,this.launchSpinSeconds-n),this.burnoutSeconds=0,this.launchPeakRpm=0,this.boostChargeSeconds=0,this.boostCharge=0,this.boostReady=!1;let o=N(D(1,0),e.angle),s=Math.max(.1,this.preset.launch.assistDurationSeconds);if(this.launchAssistGainMps>0&&t.throttle>.5&&!t.action){let t=Math.min(s,this.launchAssistElapsed+n*.5),r=Math.sin(Math.PI*t/s);e.push(A(o,e.mass*this.launchAssistGainMps*Math.PI*r/(2*s))),this.launchAssistElapsed+=n,this.launchAssistElapsed>=s&&(this.launchAssistGainMps=0)}else this.launchAssistGainMps=0;let c=this.statusEffects.bonus(`forwardAccelerationMps2`,void 0,this.tires.length,n*.5);c>0&&t.throttle>.5&&!t.action&&e.push(A(o,e.mass*c));let l=D(-o.y,o.x),u=M(e.velocity),d=j(e.velocity,o),f=j(e.velocity,l),p=this.previousVelocity===null?0:P(j(k(e.velocity,this.previousVelocity),o)/Math.max(n,1e-4),-16,16);this.previousVelocity={...e.velocity},this.longitudinalAcceleration+=(p-this.longitudinalAcceleration)*(1-Math.exp(-n/.12));let m=this.preset.frontWeightFraction??.5;this.frontLoadFraction=P(m-this.longitudinalAcceleration*.012,.34,.68),this.slideAngleRad=Math.atan2(f,Math.max(2,Math.abs(d)));let h=Math.abs(t.steer),g=t.throttle>.5&&h>.8&&!t.action&&!this.fastDrifting;if(this.donuting?g&&Math.sign(t.steer)===this.donutDirection||(this.donuting=!1,this.donutDirection=0):g&&u<4.5&&(this.donuting=!0,this.donutDirection=Math.sign(t.steer)),this.drifting=this.fastDrifting||this.donuting,this.countersteering=this.fastDrifting&&t.steer*this.driftDirection<0,!this.drifting&&!t.action&&u>4&&d>0){let t=P(Math.abs(this.slideAngleRad)-.05,0,.8);e.spin+=Math.sign(this.slideAngleRad)*t*40*n}let _=t.throttle<0&&j(e.velocity,o)<=0,v=(t.action?.18:1)*(1-P(t.brake??0,0,1));e.push(A(o,t.throttle*v*this.engineForce*this.statusEffects.factor(`driveForce`,void 0,this.tires.length)*(_?this.preset.reversePowerRatio:1))),this.steeringReferenceSpeed=t.steer?Math.max(u,this.steeringReferenceSpeed-8*n):u;let y=Math.atan(this.preset.geometry.wheelbaseM*this.preset.corneringAccelerationMps2/(this.steeringReferenceSpeed**2+16)),b=t.steer*(this.donuting?this.preset.maxSteerAngleRad:Math.min(this.preset.maxSteerAngleRad,y));this.steeringAngle+=(b-this.steeringAngle)*(1-Math.exp(-n/(t.steer?.06:.04)));for(let[r,i]of this.tires.entries()){i.angle=i.front?this.steeringAngle:0;let a=e.world(i.local),o=e.velocityAt(a),s=e.angle+i.angle,c=D(Math.cos(s),Math.sin(s)),l=D(-c.y,c.x),d=j(o,c),f=j(o,l);i.lateralSpeed=Math.abs(f),i.spinning=!i.front&&(this.burnout||this.launchSpinSeconds>0||this.donuting);let p=!i.front&&t.action?Math.abs(d)*.65:0,h=this.burnout?5.2*(.3+.7*P(this.burnoutSeconds/Math.max(.1,this.preset.launch.burnoutRampSeconds),0,1)):5.2;i.wheelSurfaceSpeedMps=i.spinning?d+h:!i.front&&t.action?d*.35:d,i.slipSpeedMps=Math.max(i.lateralSpeed,p,Math.abs(i.wheelSurfaceSpeedMps-d)),i.slip=P((i.slipSpeedMps-.45)/4.8,0,1);let g=P((i.slipSpeedMps-.4)/5.2,0,1),_=g>i.heat?.65:2.2;i.heat+=(g-i.heat)*(1-Math.exp(-n/_));let v=i.front?this.frontLoadFraction:1-this.frontLoadFraction,y=P(v/(i.front?m:1-m),.65,1.35),b=(!i.front&&this.donuting?.5:1)*(1-i.heat*(i.front?.06:.12))*this.statusEffects.factor(`grip`,r),x=this.lateralResistance*(1+Math.min(u,40)/18)*y*b,S=e.mass*this.preset.corneringAccelerationMps2*v*.5*b,C=-x*f,w=P(C,-S,S);i.lateralForceN=w,i.gripUtilization=Math.abs(C)/Math.max(1,S);let ee=Math.abs(C)>S*.92,te=i.skidding?1.2:1.8;i.skidding=i.spinning||i.slipSpeedMps>te&&(ee||i.lateralSpeed>(i.front?2.8:2.1)||p>2.4);let ne=this.rollingResistance*(!i.front&&t.action?1+this.handbrakeStrength*7:1);e.push(O(A(c,-ne*d),A(l,w)),a)}}slow(e,t,n){let r=(t.throttle===0?this.preset.coastDecelerationMps2:0)+(t.action?this.preset.handbrakeDecelerationMps2:0),i=M(e.velocity);if(i===0)return;r&&(e.velocity=A(e.velocity,Math.max(0,i-r*n)/i));let a=P(t.brake??0,0,1);if(!a)return;let o=D(Math.cos(e.angle),Math.sin(e.angle)),s=j(e.velocity,o),c=Math.min(Math.abs(s),a*nt(this.preset)*Math.max(.35,this.statusEffects.factor(`grip`,void 0,this.tires.length))*n);e.velocity=k(e.velocity,A(o,Math.sign(s)*c))}finishDrift(e,t,n){let r=this.driftStart;if(!this.fastDrifting||!r)return;let i=M(r.velocity),a=P(i/12,.55,1.2),o=this.driftDirection*(.92+.24*a)+P(t.steer,-1,1)*.47;e.spin=r.spin+(o-r.spin)*(1-Math.exp(-12*n)),e.angle=r.angle+e.spin*n;let s=M(e.velocity),c=Math.max(s,i-.5*n),l=Math.atan2(r.velocity.y,r.velocity.x),u=l+P(Bt(e.angle-this.driftDirection*this.preset.drift.slipAngleRad-l)*(1-Math.exp(-7*n)),-3.5*n,3.5*n);e.velocity=D(Math.cos(u)*c,Math.sin(u)*c),e.position=O(r.position,A(e.velocity,n)),this.slideAngleRad=Bt(u-e.angle);for(let e of this.tires)e.front||(e.skidding=!0,e.lateralSpeed=c*Math.sin(this.preset.drift.slipAngleRad),e.slipSpeedMps=Math.max(e.slipSpeedMps,e.lateralSpeed),e.slip=P(e.slipSpeedMps/4,0,1),e.heat+=(.8-e.heat)*(1-Math.exp(-2*n)),e.gripUtilization=Math.max(e.gripUtilization,1))}arcadeAssist(e,t,n){let r=M(e.velocity),{speed:i,radius:a}=Vt(this.preset);if(this.donuting){let t=i*this.statusEffects.factor(`speed`,void 0,this.tires.length),o=Math.atan2(e.velocity.y,e.velocity.x),s=e.angle-this.donutDirection*.22,c=Math.atan2(Math.sin(s-o),Math.cos(s-o))*(1-Math.exp(-n/.11)),l=r+(t-r)*(1-Math.exp(-n/.28));e.velocity=A(D(Math.cos(o+c),Math.sin(o+c)),l),e.spin=this.donutDirection*l/a;return}let o=N(D(1,0),e.angle);if(j(e.velocity,o)<-.35&&t.throttle<0&&!t.action){let i=this.preset.maxReverseSpeedMps??7;r>i&&(e.velocity=A(e.velocity,i/r)),e.spin=-t.steer*Math.min(r,i)/a;let s=A(o,-1),c=Math.atan2(zt(s,e.velocity),j(s,e.velocity));e.velocity=N(e.velocity,-P(c,-.45,.45)*(1-Math.exp(-5*n)));return}if(r<2||this.drifting||t.action||j(e.velocity,o)<=0)return;let s=Math.atan2(zt(o,e.velocity),j(o,e.velocity)),c=P((r-2)/10,0,1)*(t.steer?4.5:6)*this.statusEffects.factor(`grip`,void 0,this.tires.length),l=-P(s,-.55,.55)*(1-Math.exp(-c*n));e.velocity=N(e.velocity,l),t.steer||(e.spin*=Math.exp(-4.5*n))}},Wt=class{headAngle=0;appliedForce=D();craft=D(4,0);counterweight=D(-2,0);radius=.9;captureState(){return E({headAngle:this.headAngle,appliedForce:this.appliedForce,craft:this.craft,counterweight:this.counterweight,radius:this.radius})}restoreState(e){let t=E(e);this.headAngle=t.headAngle,this.appliedForce=t.appliedForce,Object.assign(this,{craft:t.craft,counterweight:t.counterweight,radius:t.radius})}reset(){this.headAngle=0,this.appliedForce=D()}tick(e,t,n){this.headAngle+=t.steer*2.5*n;let r=(t.throttle||+!!t.action)*5e3*(t.action?2:1);this.appliedForce=N(D(r,0),this.headAngle),e.push(N(this.appliedForce,e.angle),e.world(this.craft)),e.push(A(e.velocity,-e.mass*.12)),e.spin*=Math.exp(-.35*n)}},Gt=class{body=new Ht;car=new Ut;ship=new Wt;mode=`car`;gravity=!1;barrier=!1;paused=!1;lastInput={throttle:0,steer:0,action:!1};brickForce=null;captureState(){return{at:performance.now(),preset:E(this.car.preset),simulation:E({mode:this.mode,gravity:this.gravity,barrier:this.barrier,paused:this.paused,lastInput:this.lastInput,brickForce:this.brickForce}),body:this.body.captureState(),car:this.car.captureState(),ship:this.ship.captureState()}}restoreState(e){let t=E(e);this.setPreset(t.preset),this.body.restoreState(t.body),this.car.restoreState(t.car),this.ship.restoreState(t.ship),this.mode=t.simulation.mode,this.gravity=t.simulation.gravity,this.barrier=t.simulation.barrier,this.paused=t.simulation.paused,this.lastInput=t.simulation.lastInput,this.brickForce=t.simulation.brickForce;let n=performance.now()-t.at;this.car.explodedAt!==null&&(this.car.explodedAt+=n),Number.isFinite(this.car.lastBlastEmission)&&(this.car.lastBlastEmission+=n)}setPreset(e){this.car.configure(e),this.mode===`car`&&(this.body.mass=e.massKg,this.body.inertia=e.massKg*(e.geometry.lengthM**2+e.geometry.widthM**2)/12)}setMode(e){this.mode=e,this.body.mass=e===`car`?this.car.preset.massKg:1e3,this.body.inertia=e===`ship`?this.body.mass*(1/3*(1.8**2/18+.8**2/6+16)+2/3*(.9**2/2+4)):this.body.mass*(this.car.preset.geometry.lengthM**2+this.car.preset.geometry.widthM**2)/12,this.car.reset(),this.ship.reset(),this.brickForce=null}reset(){this.body.reset(),this.car.reset(),this.ship.reset(),this.brickForce=null,this.lastInput={throttle:0,steer:0,action:!1}}resetAtCurrentPose(){let e={...this.body.position},t=this.body.angle;this.reset(),this.body.position=e,this.body.angle=t}tick(e,t,n){if(this.paused)return;if(this.mode===`car`&&this.car.explodedAt!==null){this.body.velocity=D(),this.body.spin=0,this.lastInput={throttle:0,steer:0,action:!1,boost:!1};return}this.lastInput={...e};let r=this.body,i={...r.position};if(this.gravity){let e=r.mass*3/30;r.push(D(-e*r.velocity.x,-r.mass*3-e*r.velocity.y))}if(this.mode===`car`&&this.car.tick(r,e,t,n),this.mode===`ship`){let n=r.angle;this.ship.tick(r,e,t),r.tick(t),this.ship.headAngle-=r.angle-n}else if(this.mode===`brick`&&this.brickForce&&r.push(this.brickForce.force,r.world(this.brickForce.local)),r.tick(t),this.mode===`car`){let n=this.car.fastDrifting?{...e,action:!1}:e;this.car.slow(r,n,t),this.car.fastDrifting?this.car.finishDrift(r,e,t):this.car.arcadeAssist(r,n,t);let a=this.car.statusEffects.factor(`speed`,void 0,this.car.tires.length);a<1&&(r.velocity=A(r.velocity,Math.exp(-5*(1-a)*t))),this.car.statusEffects.advance(M(k(r.position,i)),t)}}contain(e){let t=this.body,n=this.mode===`car`?this.car.preset.geometry.lengthM/2:2,r=this.mode===`car`?this.car.preset.geometry.widthM/2:1,i=this.mode===`ship`?[D(1.2,0),D(-.6,-.8),D(-.6,.8)].map(e=>t.world(O(this.ship.craft,N(e,this.ship.headAngle)))):[D(-n,-r),D(n,-r),D(n,r),D(-n,r)].map(e=>t.world(e));this.mode===`ship`&&i.push(t.world(this.ship.counterweight));let a=[[D(1),e.left],[D(-1),-e.right],[D(0,1),e.bottom],[D(0,-1),-e.top]];for(let e=0;e<4;e++)for(let[e,n]of a){let r=i.map(t=>j(t,e)-(this.mode===`ship`?this.ship.radius:0)),a=Math.min(...r),o=n-a;if(o<-1e-8)continue;let s=i[r.indexOf(a)],c=A(e,Math.max(0,o));t.position=O(t.position,c);for(let e of i)e.x+=c.x,e.y+=c.y;let l=O(s,A(e,this.mode===`ship`?-this.ship.radius:0)),u=j(t.velocityAt(l),e);if(u>=0)continue;let d=zt(k(l,t.position),e),f=1/t.mass+d*d/t.inertia;t.impulse(A(e,-(1+(u<-.5?.55:0))*u/f),l)}}};function Kt(e,t,n){let r=e.image?.crop??{x:0,y:0,width:1,height:1},i={x:r.x*t,y:r.y*n,width:r.width*t,height:r.height*n},a=i.width/i.height,o=e.geometry,s=o.lengthM/o.widthM,c=e.image?.scale??1;return{source:i,lengthM:(a>s?o.lengthM:o.widthM*a)*c,widthM:(a>s?o.lengthM/a:o.widthM)*c}}function qt(e,t,n,r,i){if(n<1||r<1||i.length!==n*r*4)throw Error(`Invalid vehicle image pixels.`);let a=n,o=r,s=-1,c=-1;for(let e=0;e<r;e++)for(let t=0;t<n;t++)i[(e*n+t)*4+3]<48||(a=Math.min(a,t),o=Math.min(o,e),s=Math.max(s,t),c=Math.max(c,e));if(s<a)throw Error(`This image is empty. Upload a visible vehicle cutout.`);let l=(s-a+1)/240,u=(c-o+1)/240;if(l<1||u<.5)throw Error(`The vehicle is too small. Use a larger cutout on a 1200 × 600 artboard.`);let d=structuredClone(e),f=d.geometry,p=l/f.lengthM,m=u/f.widthM;if(f.lengthM=l,f.widthM=u,f.wheelbaseM*=p,f.trackWidthM*=m,f.frontAxleXM!==void 0&&(f.frontAxleXM*=p),f.rearAxleXM!==void 0&&(f.rearAxleXM*=p),f.frontTrackWidthM!==void 0&&(f.frontTrackWidthM*=m),f.rearTrackWidthM!==void 0&&(f.rearTrackWidthM*=m),f.tireLengthM*=p,f.tireWidthM*=m,d.roofRocket.xM*=p,d.roofRocket.yM*=m,d.roofRocket.sizeM*=Math.min(p,m),d.machineGuns?.xM!==void 0&&(d.machineGuns.xM*=p),d.lights)for(let e of Object.values(d.lights))e.xM*=p,e.yM*=m;return d.image={src:t,crop:{x:a/n,y:o/r,width:(s-a+1)/n,height:(c-o+1)/r}},d}function Jt(e,t){let n=1/0,r=-1/0,i=1/0,a=-1/0,o=2*t.halfLength/e.columns,s=2*t.halfWidth/e.rows,c=Math.max(o,s)*.5;for(let c=0;c<e.rows;c++){let l=(c+.5)*s-t.halfWidth;for(let s=0;s<e.columns;s++){if(!e.solid[c*e.columns+s])continue;let u=(s+.5)*o-t.halfLength,d=t.center.x+t.forward.x*u+t.side.x*l,f=t.center.y+t.forward.y*u+t.side.y*l;n=Math.min(n,d),r=Math.max(r,d),i=Math.min(i,f),a=Math.max(a,f)}}return Number.isFinite(n)?{x:n-c,y:i-c,width:r-n+c*2,height:a-i+c*2}:{x:t.center.x,y:t.center.y,width:0,height:0}}function Yt(e,t,n){let r=-1/0,i=t.center;for(let a=0;a<e.rows;a++){let o=(2*(a+.5)/e.rows-1)*t.halfWidth;for(let s=0;s<e.columns;s++){if(!e.solid[a*e.columns+s])continue;let c=(2*(s+.5)/e.columns-1)*t.halfLength,l=O(t.center,O(A(t.forward,c),A(t.side,o))),u=j(l,n);u>r&&(r=u,i=l)}}return{...i}}var Xt=(e,t,n)=>{let{columns:r,rows:i,solid:a}=e,o=n*r+t;return!!a[o]&&(t===0||t===r-1||n===0||n===i-1||!a[o-1]||!a[o+1]||!a[o-r]||!a[o+r])};function Zt(e,t,n){let r=1/0,i=t.center;for(let a=0;a<e.rows;a++){let o=(2*(a+.5)/e.rows-1)*t.halfWidth;for(let s=0;s<e.columns;s++){if(!Xt(e,s,a))continue;let c=(2*(s+.5)/e.columns-1)*t.halfLength,l=O(t.center,O(A(t.forward,c),A(t.side,o))),u=Math.max(n.x-l.x,0,l.x-n.x-n.width),d=Math.max(n.y-l.y,0,l.y-n.y-n.height),f=u*u+d*d+(u||d?0:Math.min(l.x-n.x,n.x+n.width-l.x,l.y-n.y,n.y+n.height-l.y)**2);f<r&&(r=f,i=l)}}return{...i}}function Qt(e,t,n){let r=k(n,t.center),i=j(r,t.forward)/t.halfLength,a=j(r,t.side)/t.halfWidth,o=Math.floor((i+1)*e.columns/2),s=Math.floor((a+1)*e.rows/2);return o>=0&&o<e.columns&&s>=0&&s<e.rows&&!!e.solid[s*e.columns+o]}function $t(e,t,n){if(t.halfLength<=0||t.halfWidth<=0||Math.abs(n.halfX.x*n.halfY.y-n.halfX.y*n.halfY.x)<1e-4)return 0;let r=0;for(let i=0;i<16;i++){let a=2*(i+.5)/16-1;for(let i=0;i<16;i++){let o=2*(i+.5)/16-1;Qt(e,t,{x:n.center.x+n.halfX.x*o+n.halfY.x*a,y:n.center.y+n.halfX.y*o+n.halfY.y*a})&&r++}}return r/256}function en(e,t,n){let r=t.halfLength*2/e.columns,i=t.halfWidth*2/e.rows,a=t.forward,o=t.side,s=Number(Qt(e,t,O(n,A(a,-r))))-Number(Qt(e,t,O(n,A(a,r)))),c=Number(Qt(e,t,O(n,A(o,-i))))-Number(Qt(e,t,O(n,A(o,i)))),l=O(A(a,s),A(o,c)),u=Math.hypot(l.x,l.y);if(u>.001)return A(l,1/u);let d=k(n,t.center),f=O(A(a,j(d,a)/Math.max(r,t.halfLength)),A(o,j(d,o)/Math.max(i,t.halfWidth))),p=Math.hypot(f.x,f.y);return p>.001?A(f,1/p):{...a}}function tn(e,t,n){if(n.width<=0||n.height<=0||t.halfLength<=0||t.halfWidth<=0)return!1;let r=[D(n.x,n.y),D(n.x+n.width,n.y),D(n.x,n.y+n.height),D(n.x+n.width,n.y+n.height)].map(e=>{let n=k(e,t.center);return D(j(n,t.forward),j(n,t.side))}),i=e.columns,a=e.rows,o=(e,t,n)=>Math.floor((e/t+1)*n/2),s=Math.max(0,o(Math.min(...r.map(e=>e.x)),t.halfLength,i)-1),c=Math.min(i-1,o(Math.max(...r.map(e=>e.x)),t.halfLength,i)+1),l=Math.max(0,o(Math.min(...r.map(e=>e.y)),t.halfWidth,a)-1),u=Math.min(a-1,o(Math.max(...r.map(e=>e.y)),t.halfWidth,a)+1);if(s>c||l>u)return!1;let d=Math.min(1,Math.max(t.halfLength/i,t.halfWidth/a));for(let r=l;r<=u;r++)for(let o=s;o<=c;o++){if(!e.solid[r*i+o])continue;let s=(2*(o+.5)/i-1)*t.halfLength,c=(2*(r+.5)/a-1)*t.halfWidth,l=t.center.x+t.forward.x*s+t.side.x*c,u=t.center.y+t.forward.y*s+t.side.y*c;if(l>=n.x-d&&l<=n.x+n.width+d&&u>=n.y-d&&u<=n.y+n.height+d)return!0}return!1}function nn(e,t,n,r,i){if(!tn(e,t,n))return 0;let a=0,o=Math.max(1,i);for(let i=0;i<3&&tn(e,{...t,center:O(t.center,A(r,o))},n);i++)o*=2;for(let i=0;i<10;i++){let i=(a+o)/2;tn(e,{...t,center:O(t.center,A(r,i))},n)?a=i:o=i}return o+.25}var rn=class{loaded=new Map;pending=new Set;failed=new Set;fallback=new Map;keys=new WeakMap;assembled=new WeakMap;forPreset(e){let t=this.assembled.get(e);if(t)return t;let n=e.image?.src;if(n){let t=this.keys.get(e);t||(t=`${n}|${JSON.stringify(e.image?.crop??null)}`,this.keys.set(e,t));let r=this.loaded.get(t);if(r){let t=Kt(e,r.imageWidth,r.imageHeight),n={alpha:r,lengthM:t.lengthM,widthM:t.widthM};return this.assembled.set(e,n),n}!this.pending.has(t)&&!this.failed.has(t)&&this.load(t,n,e)}let r=`${e.geometry.lengthM}:${e.geometry.widthM}`,i=this.fallback.get(r);i||(i={columns:96,rows:48,solid:new Uint8Array(4608).fill(1)},this.fallback.set(r,i));let a={alpha:i,lengthM:e.geometry.lengthM,widthM:e.geometry.widthM};return(!n||this.failed.has(this.keys.get(e)??``))&&this.assembled.set(e,a),a}load(e,t,n){this.pending.add(e);let r=new Image;r.crossOrigin=`anonymous`,r.onload=()=>{try{let t=Kt(n,r.naturalWidth,r.naturalHeight),i=Math.max(24,Math.round(128*t.source.height/t.source.width)),a=document.createElement(`canvas`);a.width=128,a.height=i;let o=a.getContext(`2d`,{willReadFrequently:!0});if(!o)throw Error(`No 2D canvas for vehicle alpha mask`);o.drawImage(r,t.source.x,t.source.y,t.source.width,t.source.height,0,0,128,i);let s=o.getImageData(0,0,128,i).data,c=new Uint8Array(128*i);for(let e=0;e<c.length;e++)c[e]=+(s[e*4+3]>=96);this.loaded.set(e,{columns:128,rows:i,solid:c,imageWidth:r.naturalWidth,imageHeight:r.naturalHeight})}catch{this.failed.add(e)}finally{this.pending.delete(e)}},r.onerror=()=>{this.pending.delete(e),this.failed.add(e)},r.src=t}},an=e=>({x:e.x*28,y:-e.y*28}),on=e=>({x:e.x/28,y:-e.y/28}),sn=class{masks=new rn;events;get totalPoints(){return 0}get managedBytes(){return 0}setEvents(e){this.events=e}prepare(e){this.masks.forPreset(e)}vehicleMask(e,t){let n=this.masks.forPreset(e);return t?t.maskFor(n):n}wallRects(){return[]}beginStep(e,t){}stepVehicle(e,t,n=!1,r,i,a=!1){}endStep(e,t){}forgetVehicle(e){}tirePaintAt(e){return e.map(()=>null)}projectileHit(e,t,n){return null}arcTargets(e,t){return[]}applyAreaImpact(e,t,n){}bulletImpact(e,t,n,r){return this.projectileHit(e,t,n)?.point??null}rocketImpact(e,t,n,r=1,i){return this.projectileHit(e,t,n)?.point??null}flameContact(e,t,n,r,i){return this.projectileHit(e,t,n)?.point??null}burningProximity(e){return 0}draw(e,t,n){}captureState(){return null}restoreState(e){}destroy(){}};function cn(e,t){}function ln(e,t=1){}var un=[1,2,3,4,5,6,7,8,9],dn=[`eject`,`machineGun`,`flamethrower`,`rocket`,`ghost`,`attractor`,`lightning`,`boost`],fn=Symbol(`prepared vehicle slots`),pn=Object.freeze({1:Object.freeze({action:`eject`,liquid:`oil`,activation:`hold`,rate:6,amount:.65}),2:Object.freeze({action:`machineGun`,activation:`hold`}),3:Object.freeze({action:`flamethrower`,activation:`hold`}),4:Object.freeze({action:`rocket`,activation:`hold`}),5:Object.freeze({action:`ghost`,activation:`hold`}),6:Object.freeze({action:`attractor`,activation:`hold`}),7:Object.freeze({action:`lightning`,activation:`hold`})});function mn(e){if(!Number.isInteger(e)||e<1||e>9)throw RangeError(`Vehicle slots use whole numbers from 1 to 9.`);return e}var hn=new Set(dn),gn=new Set([`action`,`activation`]),_n=new Set([...gn,`liquid`,`rate`,`amount`]);function vn(e,t=`slots`,n=!0,r=(e,t)=>{throw TypeError(`${e}: ${t}`)}){(!e||typeof e!=`object`||Array.isArray(e))&&r(t,`expected a slot configuration object.`);for(let[i,a]of Object.entries(e)){if(/^[1-9]$/.test(i)||r(`${t}.${i}`,`slot must be from 1 to 9.`),a===!1)continue;(!a||typeof a!=`object`||Array.isArray(a))&&r(`${t}.${i}`,`expected an action or false.`);let e=a;!n&&e.action===void 0||typeof e.action==`string`&&hn.has(e.action)||r(`${t}.${i}.action`,`choose a supported vehicle action.`),e.activation!==void 0&&e.activation!==`tap`&&e.activation!==`hold`&&r(`${t}.${i}.activation`,`choose tap or hold.`);let o=e.action===`eject`||!n&&e.action===void 0?_n:gn;for(let n of Object.keys(e))o.has(n)||r(`${t}.${i}.${n}`,`unsupported option for this action.`);e.action===`eject`&&n&&(typeof e.liquid!=`string`||!e.liquid.trim())&&r(`${t}.${i}.liquid`,`choose a liquid definition.`),e.liquid===void 0||typeof e.liquid==`string`&&e.liquid.trim()||r(`${t}.${i}.liquid`,`choose a liquid definition.`);for(let n of[`rate`,`amount`])e[n]!==void 0&&(typeof e[n]!=`number`||!Number.isFinite(e[n])||e[n]<=0)&&r(`${t}.${i}.${n}`,`expected a positive finite amount.`)}}function yn(e){if(e&&typeof e==`object`&&e[fn])return e;vn(e);let t={...pn};for(let n of un){let r=e[n];r!==void 0&&(t[n]=r===!1?!1:r.action===`eject`?Object.freeze({activation:`hold`,rate:6,amount:.65,...r}):Object.freeze({activation:`hold`,...r}))}for(let e of Object.values(t))e&&e.action===`eject`&&ot(e.liquid);return Object.defineProperty(t,fn,{value:!0}),Object.freeze(t)}function bn(e){if(!e.detached)return e.ink;let t=Math.cos(e.angle),n=Math.sin(e.angle),r=e.ink.width/2,i=e.ink.height/2,a=e.ink.x+r-e.base.x-e.base.width/2,o=e.ink.y+i-e.base.y-e.base.height/2,s=e.base.x+e.base.width/2+e.offset.x+a*t-o*n,c=e.base.y+e.base.height/2+e.offset.y+a*n+o*t,l=Math.abs(t)*r+Math.abs(n)*i,u=Math.abs(n)*r+Math.abs(t)*i;return{x:s-l,y:c-u,width:2*l,height:2*u}}function xn(e,t){let{ink:n}=e;if(!e.detached)return n.x<t.x+t.width&&n.x+n.width>t.x&&n.y<t.y+t.height&&n.y+n.height>t.y;let r=e.base.x+e.base.width/2,i=e.base.y+e.base.height/2,a=Math.max(Math.abs(n.x-r),Math.abs(n.x+n.width-r)),o=Math.max(Math.abs(n.y-i),Math.abs(n.y+n.height-i)),s=Math.sqrt(a*a+o*o),c=r+e.offset.x,l=i+e.offset.y;return c-s<t.x+t.width&&c+s>t.x&&l-s<t.y+t.height&&l+s>t.y}function Sn(e,t,n,r){let i=O(t,A(e.velocity,-1));e.detached=!0,e.velocity=O(A(e.velocity,.35),O(A(i,.55),A(n,80+Math.min(220,M(i)*.3)))),e.spin=e.spin*.3+r,e.offset=O(e.offset,A(n,2)),e.impactCooldown=.12}function Cn(e,t){e.impactCooldown=Math.max(0,e.impactCooldown-t),e.detached&&(e.velocity=A(e.velocity,Math.exp(-(e.attractorInfluenced?.35:1.6)*t)),e.offset=O(e.offset,A(e.velocity,t)),e.angle+=e.spin*t,e.spin*=Math.exp(-1.25*t))}function wn(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 Tn(e,t,n){let r=-1/0,i=1/0,a={x:0,y:0};for(let o of[`x`,`y`]){let s=n[o],c=s+(o===`x`?n.width:n.height),l=e[o],u=t[o],d=l+(o===`x`?e.width:e.height),f=u+(o===`x`?t.width:t.height);for(let[e,t,n]of[[d-s,f-d,-1],[c-l,l-u,1]]){if(Math.abs(t)<1e-8){if(e<0)return null;continue}let s=-e/t;t>0&&s>r?(r=s,a=o===`x`?{x:n,y:0}:{x:0,y:n}):t<0&&(i=Math.min(i,s))}if(r>i)return null}return r>=0&&r<=1&&r<=i&&i>=0&&(a.x!==0||a.y!==0)?{time:r,normal:a}:null}function En(e,t){let n=bn(e);if(!wn(n,t))return null;let r=[{amount:t.x-n.x-n.width-.1,normal:{x:-1,y:0}},{amount:t.x+t.width-n.x+.1,normal:{x:1,y:0}},{amount:t.y-n.y-n.height-.1,normal:{x:0,y:-1}},{amount:t.y+t.height-n.y+.1,normal:{x:0,y:1}}].reduce((e,t)=>Math.abs(t.amount)<Math.abs(e.amount)?t:e);return r.normal.x?e.offset.x+=r.amount:e.offset.y+=r.amount,r.normal}function Dn(e,t){let n=e.velocity.x*t.x+e.velocity.y*t.y;n>=0||(e.velocity=O(A(e.velocity,.82),A(t,-n*1.1)),e.spin*=-.45)}function On(e,t,n){if(e.detached)for(let t of n){if(wn(e.ink,t))continue;let n=En(e,t);n&&Dn(e,n)}if(!e.detached||n.length===0){Cn(e,t);return}let r=bn(e);Cn(e,t);let i=bn(e),a=null;for(let t of n){if(wn(e.ink,t))continue;let n=Tn(r,i,t);n&&(!a||n.time<a.time)&&(a={...n,wall:t})}if(a){let t=1-a.time;e.offset.x-=(i.x+i.width/2-r.x-r.width/2)*t,e.offset.y-=(i.y+i.height/2-r.y-r.height/2)*t,En(e,a.wall),Dn(e,a.normal)}for(let t=0;t<3;t++){let t=!1;for(let r of n){if(wn(e.ink,r))continue;let n=En(e,r);n&&(Dn(e,n),t=!0)}if(!t)break}}function kn(e,t,n,r=!1){if(!t||t.radiusPx<=0||!e.detached&&!r)return e.attractorInfluenced=!1,!1;let i=bn(e),a=k({x:i.x+i.width/2,y:i.y+i.height/2},t.center),o=M(a);if(o>t.radiusPx)return e.attractorInfluenced=!1,!1;e.detached||=!0,e.attractorInfluenced=!0;let s=O(A(a,-Math.min(1,300/Math.max(1,o*5))*5),A(k(t.velocity,e.velocity),.15));return e.velocity=O(e.velocity,A(s,Math.max(0,n))),e.spin*=Math.exp(-.7*Math.max(0,n)),!0}var An={rangeM:10,forwardBias:1.5,chargeSeconds:1.1,statusSeconds:4,speedFactor:.5,impactRadiusM:1.6,damage:75,impulse:1,ignite:!0};function jn(e){let t={...An,...e.lightning};for(let e of Object.keys(An)){if(e===`ignite`)continue;let n=t[e];(!Number.isFinite(n)||n<0)&&(t[e]=An[e])}return t.forwardBias=Math.max(0,Math.min(4,t.forwardBias)),t.rangeM=Math.max(1,Math.min(30,t.rangeM)),t.chargeSeconds=Math.max(.1,Math.min(10,t.chargeSeconds)),t.speedFactor=Math.max(.1,Math.min(1,t.speedFactor)),t.statusSeconds=Math.max(.1,Math.min(30,t.statusSeconds)),t.impactRadiusM=Math.max(.1,Math.min(10,t.impactRadiusM)),t.damage=Math.min(1e4,t.damage),t.impulse=Math.min(4,t.impulse),t.ignite=typeof t.ignite==`boolean`?t.ignite:An.ignite,t}function Mn(e,t,n=28){let r=jn(e);return e.lightning?.rangeM!==void 0||!Number.isFinite(t)||!t||n<=0?r.rangeM:Math.max(4,Math.min(60,t/(3*n)))}function Nn(e,t,n,r){let i=t.x-e.x,a=t.y-e.y,o=Math.hypot(i,a),s=o>.001?(i*Math.cos(n)-a*Math.sin(n))/o:1;return o*(1+Math.max(0,r)*(1-Math.max(-1,Math.min(1,s))))}var Pn=class{charging=!1;charge=0;target=null;dischargeAge=1/0;dischargeId=0;dischargeTargets=[];dischargePaths=[];pending=!1;elapsed=0;captureState(){return E({charging:this.charging,charge:this.charge,target:this.target,dischargeAge:this.dischargeAge,dischargeId:this.dischargeId,dischargeTargets:this.dischargeTargets,dischargePaths:this.dischargePaths,pending:this.pending,elapsed:this.elapsed})}restoreState(e){let t=E(e);this.charging=t.charging,this.charge=t.charge,this.target=t.target,this.dischargeAge=t.dischargeAge,this.dischargeId=t.dischargeId,this.dischargeTargets=t.dischargeTargets,this.dischargePaths=t.dischargePaths,this.pending=t.pending,this.elapsed=t.elapsed}get visual(){let e=this.dischargeAge<.6;return{phase:e?`discharged`:this.charging?`charging`:`idle`,charge:this.charge,target:e?this.dischargeTargets[0]??this.dischargePaths[0]?.[0]??null:this.target,dischargeAge:this.dischargeAge,dischargeId:this.dischargeId,branches:this.dischargeTargets,paths:this.dischargePaths}}step(e,t,n,r){this.dischargeAge+=e,this.dischargeAge>.6&&(this.dischargeTargets=[],this.dischargePaths=[]),this.charging=t,t?(this.elapsed+=e,this.charge=Math.min(1,r===void 0?this.elapsed/n:1-r),(r===void 0?this.elapsed>=n:r<=0)&&(this.charge=1,this.pending=!0,this.elapsed=0,this.charging=!1)):(this.charge=this.elapsed=0,this.target=null)}takeDischarge(){let e=this.pending;return this.pending=!1,e}discharge(e,t=[]){this.dischargeTargets=e.map(e=>({...e})),this.dischargePaths=t.map(e=>e.map(e=>({...e}))),this.dischargeAge=0,this.dischargeId++}reset(){this.charging=this.pending=!1,this.charge=this.elapsed=this.dischargeId=0,this.target=null,this.dischargeAge=1/0,this.dischargeTargets=[],this.dischargePaths=[]}},Fn={radiusPx:92,coreRadiusPx:25,damage:100,impulse:1,ignite:!0};function In(e=1){let t=Number.isFinite(e)?Math.max(.1,Math.min(3,e)):1;return{radiusPx:Math.max(40,Fn.radiusPx*t),coreRadiusPx:Fn.coreRadiusPx*t,damage:Fn.damage*t,impulse:Fn.impulse*t,ignite:Fn.ignite}}function Ln(){if(typeof globalThis<`u`)return globalThis;if(typeof self<`u`)return self;if(typeof window<`u`)return window;if(typeof global<`u`)return global}function Rn(){let e=Ln();if(e.__xstate__)return e.__xstate__}var zn=e=>{if(typeof window>`u`)return;let t=Rn();t&&t.register(e)},Bn=class{constructor(e){this._process=e,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(e){let t={value:e,next:null};this._current?(this._last.next=t,this._last=t):(this._current=t,this._last=t,this._active&&this.flush())}flush(){for(;this._current;){let e=this._current;this._process(e.value),this._current=e.next}this._last=null}},Vn=``,Hn=`#`,Un=`*`,Wn=`xstate.init`,Gn=`xstate.stop`;function Kn(e,t){return{type:`xstate.after.${e}.${t}`}}function qn(e,t){return{type:`xstate.done.state.${e}`,output:t}}function Jn(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function Yn(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function Xn(e){return{type:Wn,input:e}}function Zn(e){setTimeout(()=>{throw e})}var Qn=typeof Symbol==`function`&&Symbol.observable||`@@observable`;function $n(e,t){let n=tr(e),r=tr(t);return typeof r==`string`?typeof n==`string`&&r===n:typeof n==`string`?n in r:Object.keys(n).every(e=>e in r&&$n(n[e],r[e]))}function er(e){if(sr(e))return e;let t=[],n=``;for(let r=0;r<e.length;r++){switch(e.charCodeAt(r)){case 92:n+=e[r+1],r++;continue;case 46:t.push(n),n=``;continue}n+=e[r]}return t.push(n),t}function tr(e){return Fi(e)?e.value:typeof e==`string`?nr(er(e)):e}function nr(e){if(e.length===1)return e[0];let t={},n=t;for(let t=0;t<e.length-1;t++)if(t===e.length-2)n[e[t]]=e[t+1];else{let r=n;n={},r[e[t]]=n}return t}function rr(e,t){let n={},r=Object.keys(e);for(let i=0;i<r.length;i++){let a=r[i];n[a]=t(e[a],a,e,i)}return n}function ir(e){return sr(e)?e:[e]}function ar(e){return e===void 0?[]:ir(e)}function or(e,t,n,r){return typeof e==`function`?e({context:t,event:n,self:r}):e}function sr(e){return Array.isArray(e)}function cr(e){return e.type.startsWith(`xstate.error.actor`)}function lr(e){return ir(e).map(e=>e===void 0||typeof e==`string`?{target:e}:e)}function ur(e){if(e!==void 0&&e!==Vn)return ar(e)}function dr(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}function fr(e,t){return`${t}.${e}`}function pr(e,t){let n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];let[,r,i]=n,a=e.getStateNodeById(i).config.invoke;return(Array.isArray(a)?a[r]:a).src}function mr(e,t){if(t===e||t===Un)return!0;if(!t.endsWith(`.*`))return!1;let n=t.split(`.`),r=e.split(`.`);for(let e=0;e<n.length;e++){let t=n[e],i=r[e];if(t===`*`)return e===n.length-1;if(t!==i)return!1}return!0}function hr(e,t){return`${e.sessionId}.${t}`}var gr=0;function _r(e,t){let n=new Map,r=new Map,i=new WeakMap,a=new Set,o={},{clock:s,logger:c}=t,l={schedule:(e,t,n,r,i=Math.random().toString(36).slice(2))=>{let a={source:e,target:t,event:n,delay:r,id:i,startedAt:Date.now()},c=hr(e,i);u._snapshot._scheduledEvents[c]=a;let l=s.setTimeout(()=>{delete o[c],delete u._snapshot._scheduledEvents[c],u._relay(e,t,n)},r);o[c]=l},cancel:(e,t)=>{let n=hr(e,t),r=o[n];delete o[n],delete u._snapshot._scheduledEvents[n],r!==void 0&&s.clearTimeout(r)},cancelAll:e=>{for(let t in u._snapshot._scheduledEvents){let n=u._snapshot._scheduledEvents[t];n.source===e&&l.cancel(e,n.id)}}},u={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${gr++}`,_register:(e,t)=>(n.set(e,t),e),_unregister:e=>{n.delete(e.sessionId);let t=i.get(e);t!==void 0&&(r.delete(t),i.delete(e))},get:e=>r.get(e),getAll:()=>Object.fromEntries(r.entries()),_set:(e,t)=>{let n=r.get(e);if(n&&n!==t)throw Error(`Actor with system ID '${e}' already exists.`);r.set(e,t),i.set(t,e)},inspect:e=>{let t=dr(e);return a.add(t),{unsubscribe(){a.delete(t)}}},_sendInspectionEvent:t=>{if(!a.size)return;let n={...t,rootId:e.sessionId};a.forEach(e=>e.next?.(n))},_relay:(e,t,n)=>{u._sendInspectionEvent({type:`@xstate.event`,sourceRef:e,actorRef:t,event:n}),t._send(n)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{let e=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(let t in e){let{source:n,target:r,event:i,delay:a,id:o}=e[t];l.schedule(n,r,i,a,o)}},_clock:s,_logger:c};return u}var vr=!1,yr=function(e){return e[e.NotStarted=0]=`NotStarted`,e[e.Running=1]=`Running`,e[e.Stopped=2]=`Stopped`,e}({}),br={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1},xr=class{constructor(e,t){this.logic=e,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Bn(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=yr.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];let n={...br,...t},{clock:r,logger:i,parent:a,syncSnapshot:o,id:s,systemId:c,inspect:l}=n;this.system=a?a.system:_r(this,{clock:r,logger:i}),l&&!a&&this.system.inspect(dr(l)),this.sessionId=this.system._bookId(),this.id=s??this.sessionId,this.logger=t?.logger??this.system._logger,this.clock=t?.clock??this.system._clock,this._parent=a,this._syncSnapshot=o,this.options=n,this.src=n.src??e,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:e=>{this._deferred.push(e)},system:this.system,stopChild:e=>{if(e._parent!==this)throw Error(`Cannot stop child actor ${e.id} of ${this.id} because it is not a child`);e._stop()},emit:e=>{let t=this.eventListeners.get(e.type),n=this.eventListeners.get(`*`);if(!t&&!n)return;let r=[...t?t.values():[],...n?n.values():[]];for(let t of r)try{t(e)}catch(e){Zn(e)}},actionExecutor:e=>{let t=()=>{if(this._actorScope.system._sendInspectionEvent({type:`@xstate.action`,actorRef:this,action:{type:e.type,params:e.params}}),!e.exec)return;let t=vr;try{vr=!0,e.exec(e.info,e.params)}finally{vr=t}};this._processingStatus===yr.Running?t():this._deferred.push(t)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:`@xstate.actor`,actorRef:this}),c&&(this.systemId=c,this.system._set(c,this)),this._initState(t?.snapshot??t?.state),c&&this._snapshot.status!==`active`&&this.system._unregister(this)}_initState(e){try{this._snapshot=e?this.logic.restoreSnapshot?this.logic.restoreSnapshot(e,this._actorScope):e:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(e){this._snapshot={status:`error`,output:void 0,error:e}}}update(e,t){this._snapshot=e;let n;for(;n=this._deferred.shift();)try{n()}catch(t){this._deferred.length=0,this._snapshot={...e,status:`error`,error:t}}switch(this._snapshot.status){case`active`:for(let t of this.observers)try{t.next?.(e)}catch(e){Zn(e)}break;case`done`:for(let t of this.observers)try{t.next?.(e)}catch(e){Zn(e)}this._stopProcedure(),this._complete(),this._doneEvent=Jn(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case`error`:this._error(this._snapshot.error)}this.system._sendInspectionEvent({type:`@xstate.snapshot`,actorRef:this,event:t,snapshot:e})}subscribe(e,t,n){let r=dr(e,t,n);if(this._processingStatus!==yr.Stopped)this.observers.add(r);else switch(this._snapshot.status){case`done`:try{r.complete?.()}catch(e){Zn(e)}break;case`error`:{let e=this._snapshot.error;if(!r.error)Zn(e);else try{r.error(e)}catch(e){Zn(e)}break}}return{unsubscribe:()=>{this.observers.delete(r)}}}on(e,t){let n=this.eventListeners.get(e);n||(n=new Set,this.eventListeners.set(e,n));let r=t.bind(void 0);return n.add(r),{unsubscribe:()=>{n.delete(r)}}}select(e,t=Object.is){return{subscribe:n=>{let r=dr(n),i=e(this.getSnapshot());return this.subscribe(n=>{let a=e(n);t(i,a)||(i=a,r.next?.(a))})},get:()=>e(this.getSnapshot())}}start(){if(this._processingStatus===yr.Running)return this;this._syncSnapshot&&this.subscribe({next:e=>{e.status===`active`&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:e})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=yr.Running;let e=Xn(this.options.input);switch(this.system._sendInspectionEvent({type:`@xstate.event`,sourceRef:this._parent,actorRef:this,event:e}),this._snapshot.status){case`done`:return this.update(this._snapshot,e),this;case`error`:return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(e){return this._snapshot={...this._snapshot,status:`error`,error:e},this._error(e),this}return this.update(this._snapshot,e),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(e){let t,n;try{t=this.logic.transition(this._snapshot,e,this._actorScope)}catch(e){n={err:e}}if(n){let{err:e}=n;this._snapshot={...this._snapshot,status:`error`,error:e},this._error(e)}else this.update(t,e),e.type===`xstate.stop`&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===yr.Stopped?this:(this.mailbox.clear(),this._processingStatus===yr.NotStarted?(this._processingStatus=yr.Stopped,this):(this.mailbox.enqueue({type:Gn}),this))}stop(){if(this._parent)throw Error(`A non-root actor cannot be stopped directly.`);return this._stop()}_complete(){for(let e of this.observers)try{e.complete?.()}catch(e){Zn(e)}this.observers.clear(),this.eventListeners.clear()}_reportError(e){if(!this.observers.size){this._parent||Zn(e),this.eventListeners.clear();return}let t=!1;for(let n of this.observers){let r=n.error;t||=!r;try{r?.(e)}catch(e){Zn(e)}}this.observers.clear(),this.eventListeners.clear(),t&&Zn(e)}_error(e){this._stopProcedure(),this._reportError(e),this._parent&&this.system._relay(this,this._parent,Yn(this.id,e))}_stopProcedure(){return this._processingStatus===yr.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Bn(this._process.bind(this)),this._processingStatus=yr.Stopped,this.system._unregister(this)),this}_send(e){this._processingStatus!==yr.Stopped&&this.mailbox.enqueue(e)}send(e){this.system._relay(void 0,this,e)}attachDevTools(){let{devTools:e}=this.options;e&&(typeof e==`function`?e:zn)(this)}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[Qn](){return this}getSnapshot(){return this._snapshot}};function Sr(e,...[t]){return new xr(e,t)}function Cr(e,t,n,r,{sendId:i}){return[t,{sendId:typeof i==`function`?i(n,r):i},void 0]}function wr(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t.sendId)})}function Tr(e){function t(e,t){}return t.type=`xstate.cancel`,t.sendId=e,t.resolve=Cr,t.execute=wr,t}function Er(e,t,n,r,{id:i,systemId:a,src:o,input:s,syncSnapshot:c}){let l=typeof o==`string`?pr(t.machine,o):o,u=typeof i==`function`?i(n):i,d,f;return l&&(f=typeof s==`function`?s({context:t.context,event:n.event,self:e.self}):s,d=Sr(l,{id:u,src:o,parent:e.self,syncSnapshot:c,systemId:a,input:f})),[Hi(t,{children:{...t.children,[u]:d}}),{id:i,systemId:a,actorRef:d,src:o,input:f},void 0]}function Dr(e,{actorRef:t}){t&&e.defer(()=>{t._processingStatus!==yr.Stopped&&t.start()})}function Or(...[e,{id:t,systemId:n,input:r,syncSnapshot:i=!1}={}]){function a(e,t){}return a.type=`xstate.spawnChild`,a.id=t,a.systemId=n,a.src=e,a.input=r,a.syncSnapshot=i,a.resolve=Er,a.execute=Dr,a}function kr(e,t,n,r,{actorRef:i}){let a=typeof i==`function`?i(n,r):i,o=typeof a==`string`?t.children[a]:a,s=t.children;return o&&(s={...s},delete s[o.id]),[Hi(t,{children:s}),o,void 0]}function Ar(e,t){let n=t.getSnapshot();if(n&&`children`in n)for(let t of Object.values(n.children))Ar(e,t);e.system._unregister(t)}function jr(e,t){t&&(Ar(e,t),t._processingStatus===yr.Running?e.defer(()=>{e.stopChild(t)}):e.stopChild(t))}function Mr(e){function t(e,t){}return t.type=`xstate.stopChild`,t.actorRef=e,t.resolve=kr,t.execute=jr,t}function Nr(e,{context:t,event:n},{guards:r}){return r.every(r=>Fr(r,t,n,e))}function Pr(e){function t(e,t){return!1}return t.check=Nr,t.guards=e,t}function Fr(e,t,n,r){let{machine:i}=r,a=typeof e==`function`,o=a?e:i.implementations.guards[typeof e==`string`?e:e.type];if(!a&&!o)throw Error(`Guard '${typeof e==`string`?e:e.type}' is not implemented.'.`);if(typeof o!=`function`)return Fr(o,t,n,r);let s={context:t,event:n},c=a||typeof e==`string`?void 0:`params`in e?typeof e.params==`function`?e.params({context:t,event:n}):e.params:void 0;return`check`in o?o.check(r,s,o):o(s,c)}function Ir(e){return e.type===`atomic`||e.type===`final`}function Lr(e){return Object.values(e.states).filter(e=>e.type!==`history`)}function Rr(e,t){let n=[];if(t===e)return n;let r=e.parent;for(;r&&r!==t;)n.push(r),r=r.parent;return n}function zr(e){let t=new Set(e),n=Vr(t);for(let e of t)if(e.type===`compound`&&(!n.get(e)||!n.get(e).length))ei(e).forEach(e=>t.add(e));else if(e.type===`parallel`){for(let n of Lr(e))if(n.type!==`history`&&!t.has(n)){let e=ei(n);for(let n of e)t.add(n)}}for(let e of t){let n=e.parent;for(;n;)t.add(n),n=n.parent}return t}function Br(e,t){let n=t.get(e);if(!n)return{};if(e.type===`compound`){let e=n[0];if(e){if(Ir(e))return e.key}else return{}}let r={};for(let e of n)r[e.key]=Br(e,t);return r}function Vr(e){let t=new Map;for(let n of e)t.has(n)||t.set(n,[]),n.parent&&(t.has(n.parent)||t.set(n.parent,[]),t.get(n.parent).push(n));return t}function Hr(e,t){return Br(e,Vr(zr(t)))}function Ur(e,t){return t.type===`compound`?Lr(t).some(t=>t.type===`final`&&e.has(t)):t.type===`parallel`?Lr(t).every(t=>Ur(e,t)):t.type===`final`}var Wr=e=>e[0]===Hn;function Gr(e,t){let n=e.transitions.get(t),r=[...e.transitions.keys()].filter(e=>e!==t&&mr(t,e)).sort((e,t)=>t.length-e.length).flatMap(t=>e.transitions.get(t));return n?[...n,...r]:r}function Kr(e){let t=e.config.after;if(!t)return[];let n=t=>{let n=Kn(t,e.id),r=n.type;return e.entry.push(Ji(n,{id:r,delay:t})),e.exit.push(Tr(r)),r};return Object.keys(t).flatMap(e=>{let r=t[e],i=typeof r==`string`?{target:r}:r,a=Number.isNaN(+e)?e:+e,o=n(a);return ar(i).map(e=>({...e,event:o,delay:a}))}).map(t=>{let{delay:n}=t;return{...qr(e,t.event,t),delay:n}})}function qr(e,t,n){let r=ur(n.target),i=n.reenter??!1,a=Zr(e,r),o={...n,actions:ar(n.actions),guard:n.guard,target:a,source:e,reenter:i,eventType:t,toJSON:()=>({...o,source:`#${e.id}`,target:a?a.map(e=>`#${e.id}`):void 0})};return o}function Jr(e){let t=new Map;if(e.config.on)for(let n of Object.keys(e.config.on)){if(n===``)throw Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');let r=e.config.on[n];t.set(n,lr(r).map(t=>qr(e,n,t)))}if(e.config.onDone){let n=`xstate.done.state.${e.id}`;t.set(n,lr(e.config.onDone).map(t=>qr(e,n,t)))}for(let n of e.invoke){if(n.onDone){let r=`xstate.done.actor.${n.id}`;t.set(r,lr(n.onDone).map(t=>qr(e,r,t)))}if(n.onError){let r=`xstate.error.actor.${n.id}`;t.set(r,lr(n.onError).map(t=>qr(e,r,t)))}if(n.onSnapshot){let r=`xstate.snapshot.${n.id}`;t.set(r,lr(n.onSnapshot).map(t=>qr(e,r,t)))}}for(let n of e.after){let e=t.get(n.eventType);e||(e=[],t.set(n.eventType,e)),e.push(n)}return t}function Yr(e){let t=[],n=r=>{Object.values(r).forEach(r=>{if(r.config.route&&r.config.id){let n=r.config.id,i=r.config.route.guard,a=({event:e})=>e.to===`#${n}`,o={...r.config.route,guard:i?Pr([a,i]):a,target:`#${n}`};t.push(qr(e,`xstate.route`,o))}r.states&&n(r.states)})};n(e.states),t.length>0&&e.transitions.set(`xstate.route`,t)}function Xr(e,t){let n=typeof t==`string`?e.states[t]:t?e.states[t.target]:void 0;if(!n&&t)throw Error(`Initial state node "${t}" not found on parent state node #${e.id}`);let r={source:e,actions:!t||typeof t==`string`?[]:ar(t.actions),eventType:null,reenter:!1,target:n?[n]:[],meta:typeof t==`object`?t.meta:void 0,description:typeof t==`object`?t.description:void 0,toJSON:()=>({...r,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return r}function Zr(e,t){if(t!==void 0)return t.map(t=>{if(typeof t!=`string`)return t;if(Wr(t))return e.machine.getStateNodeById(t);let n=t[0]===`.`;if(n&&!e.parent)return ri(e,t.slice(1));let r=n?e.key+t:t;if(e.parent)try{return ri(e.parent,r)}catch(t){throw Error(`Invalid transition definition for state node '${e.id}':\n${t.message}`)}throw Error(`Invalid target: "${t}" is not a valid target from the root node. Did you mean ".${t}"?`)})}function Qr(e){let t=ur(e.config.target);return t?{target:t.map(t=>typeof t==`string`?ri(e.parent,t):t)}:e.parent.type===`parallel`?{target:[e.parent]}:e.parent.initial}function $r(e){return e.type===`history`}function ei(e){let t=ti(e);for(let n of t)for(let r of Rr(n,e))t.add(r);return t}function ti(e){let t=new Set;function n(e){if(!t.has(e)){if(t.add(e),e.type===`compound`)n(e.initial.target[0]);else if(e.type===`parallel`)for(let t of Lr(e))n(t)}}return n(e),t}function ni(e,t){if(Wr(t))return e.machine.getStateNodeById(t);if(!e.states)throw Error(`Unable to retrieve child state '${t}' from '${e.id}'; no child states exist.`);let n=e.states[t];if(!n)throw Error(`Child state '${t}' does not exist on '${e.id}'`);return n}function ri(e,t){if(typeof t==`string`&&Wr(t))try{return e.machine.getStateNodeById(t)}catch{}let n=er(t).slice(),r=e;for(;n.length;){let e=n.shift();if(!e.length)break;r=ni(r,e)}return r}function ii(e,t){if(typeof t==`string`){let n=e.states[t];if(!n)throw Error(`State '${t}' does not exist on '${e.id}'`);return[e,n]}let n=Object.keys(t),r=n.map(t=>ni(e,t)).filter(Boolean);return[e.machine.root,e].concat(r,n.reduce((n,r)=>{let i=ni(e,r);if(!i)return n;let a=ii(i,t[r]);return n.concat(a)},[]))}function ai(e,t,n,r){let i=ni(e,t).next(n,r);return!i||!i.length?e.next(n,r):i}function oi(e,t,n,r){let i=Object.keys(t),a=ci(ni(e,i[0]),t[i[0]],n,r);return!a||!a.length?e.next(n,r):a}function si(e,t,n,r){let i=[];for(let a of Object.keys(t)){let o=t[a];if(!o)continue;let s=ci(ni(e,a),o,n,r);s&&i.push(...s)}return i.length?i:e.next(n,r)}function ci(e,t,n,r){return typeof t==`string`?ai(e,t,n,r):Object.keys(t).length===1?oi(e,t,n,r):si(e,t,n,r)}function li(e){return Object.keys(e.states).map(t=>e.states[t]).filter(e=>e.type===`history`)}function ui(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function di(e,t){let n=new Set(e),r=new Set(t);for(let e of n)if(r.has(e))return!0;for(let e of r)if(n.has(e))return!0;return!1}function fi(e,t,n){let r=new Set;for(let i of e){let e=!1,a=new Set;for(let o of r)if(di(gi([i],t,n),gi([o],t,n))){if(ui(i.source,o.source))a.add(o);else{e=!0;break}}if(!e){for(let e of a)r.delete(e);r.add(i)}}return Array.from(r)}function pi(e){let[t,...n]=e;for(let e of Rr(t,void 0))if(n.every(t=>ui(t,e)))return e}function mi(e,t){if(!e.target)return[];let n=new Set;for(let r of e.target)if($r(r)){if(t[r.id])for(let e of t[r.id])n.add(e);else for(let e of mi(Qr(r),t))n.add(e)}else n.add(r);return[...n]}function hi(e,t){let n=mi(e,t);if(!n)return;if(!e.reenter&&n.every(t=>t===e.source||ui(t,e.source)))return e.source;let r=pi(n.concat(e.source));if(r)return r;if(!e.reenter)return e.source.machine.root}function gi(e,t,n){let r=new Set;for(let i of e)if(i.target?.length){let e=hi(i,n);i.reenter&&i.source===e&&r.add(e);for(let n of t)ui(n,e)&&r.add(n)}return[...r]}function _i(e,t){if(e.length!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function vi(e,t,n,r,i){return yi([{target:[...ti(e)],source:e,reenter:!0,actions:[],eventType:null,toJSON:null}],t,n,r,!0,i)}function yi(e,t,n,r,i,a){let o=[];if(!e.length)return[t,o];let s=n.actionExecutor;n.actionExecutor=e=>{o.push(e),s(e)};try{let s=new Set(t._nodes),c=t.historyValue,l=fi(e,s,c),u=t;i||([u,c]=Ei(u,r,n,l,s,c,a,n.actionExecutor)),u=ki(u,r,n,l.flatMap(e=>e.actions),a,void 0),u=xi(u,r,n,l,s,a,c,i);let d=[...s];u.status===`done`&&(u=ki(u,r,n,d.sort((e,t)=>t.order-e.order).flatMap(e=>e.exit),a,void 0));try{return c===t.historyValue&&_i(t._nodes,s)?[u,o]:[Hi(u,{_nodes:d,historyValue:c}),o]}catch(e){throw e}}finally{n.actionExecutor=s}}function bi(e,t,n,r,i){if(r.output===void 0)return;let a=qn(i.id,i.output!==void 0&&i.parent?or(i.output,e.context,t,n.self):void 0);return or(r.output,e.context,a,n.self)}function xi(e,t,n,r,i,a,o,s){let c=e,l=new Set,u=new Set;Si(r,o,u,l),s&&u.add(e.machine.root);let d=new Set;for(let e of[...l].sort((e,t)=>e.order-t.order)){i.add(e);let r=[];r.push(...e.entry);for(let t of e.invoke)r.push(Or(t.src,{...t,syncSnapshot:!!t.onSnapshot}));if(u.has(e)){let t=e.initial.actions;r.push(...t)}if(c=ki(c,t,n,r,a,e.invoke.map(e=>e.id)),e.type===`final`){let r=e.parent,o=r?.type===`parallel`?r:r?.parent,s=o||e;for(r?.type===`compound`&&a.push(qn(r.id,e.output===void 0?void 0:or(e.output,c.context,t,n.self)));o?.type===`parallel`&&!d.has(o)&&Ur(i,o);)d.add(o),a.push(qn(o.id)),s=o,o=o.parent;if(o)continue;c=Hi(c,{status:`done`,output:bi(c,t,n,c.machine.root,s)})}}return c}function Si(e,t,n,r){for(let i of e){let e=hi(i,t);for(let a of i.target||[])!$r(a)&&(i.source!==a||i.source!==e||i.reenter)&&(r.add(a),n.add(a)),Ci(a,t,n,r);let a=mi(i,t);for(let o of a){let a=Rr(o,e);e?.type===`parallel`&&a.push(e),wi(r,t,n,a,!i.source.parent&&i.reenter?void 0:e)}}}function Ci(e,t,n,r){if($r(e)){if(t[e.id]){let i=t[e.id];for(let e of i)r.add(e),Ci(e,t,n,r);for(let a of i)Ti(a,e.parent,r,t,n)}else{let i=Qr(e);for(let a of i.target)r.add(a),i===e.parent?.initial&&n.add(e.parent),Ci(a,t,n,r);for(let a of i.target)Ti(a,e.parent,r,t,n)}}else if(e.type===`compound`){let[i]=e.initial.target;$r(i)||(r.add(i),n.add(i)),Ci(i,t,n,r),Ti(i,e,r,t,n)}else if(e.type===`parallel`)for(let i of Lr(e).filter(e=>!$r(e)))[...r].some(e=>ui(e,i))||($r(i)||(r.add(i),n.add(i)),Ci(i,t,n,r))}function wi(e,t,n,r,i){for(let a of r)if((!i||ui(a,i))&&e.add(a),a.type===`parallel`)for(let r of Lr(a).filter(e=>!$r(e)))[...e].some(e=>ui(e,r))||(e.add(r),Ci(r,t,n,e))}function Ti(e,t,n,r,i){wi(n,r,i,Rr(e,t))}function Ei(e,t,n,r,i,a,o,s){let c=e,l=gi(r,i,a);l.sort((e,t)=>t.order-e.order);let u;for(let e of l)for(let t of li(e)){let n;n=t.history===`deep`?t=>Ir(t)&&ui(t,e):t=>t.parent===e,u??={...a},u[t.id]=Array.from(i).filter(n)}for(let e of l)c=ki(c,t,n,[...e.exit,...e.invoke.map(e=>Mr(e.id))],o,void 0),i.delete(e);return[c,u||a]}function Di(e,t){return e.implementations.actions[t]}function Oi(e,t,n,r,i,a){let{machine:o}=e,s=e;for(let e of r){let r=typeof e==`function`,c=r?e:Di(o,typeof e==`string`?e:e.type),l={context:s.context,event:t,self:n.self,system:n.system},u=r||typeof e==`string`?void 0:`params`in e?typeof e.params==`function`?e.params({context:s.context,event:t}):e.params:void 0;if(!c||!(`resolve`in c)){n.actionExecutor({type:typeof e==`string`?e:typeof e==`object`?e.type:e.name||`(anonymous)`,info:l,params:u,exec:c});continue}let d=c,[f,p,m]=d.resolve(n,s,l,u,c,i);s=f,`retryResolve`in d&&a?.push([d,p]),`execute`in d&&n.actionExecutor({type:d.type,info:l,params:p,exec:d.execute.bind(null,n,p)}),m&&(s=Oi(s,t,n,m,i,a))}return s}function ki(e,t,n,r,i,a){let o=a?[]:void 0,s=Oi(e,t,n,r,{internalQueue:i,deferredActorIds:a},o);return o?.forEach(([e,t])=>{e.retryResolve(n,s,t)}),s}function Ai(e,t,n,r){let i=e,a=[];function o(e,t,r){n.system._sendInspectionEvent({type:`@xstate.microstep`,actorRef:n.self,event:t,snapshot:e[0],_transitions:r}),a.push(e)}if(t.type===`xstate.stop`)return i=Hi(ji(i,t,n),{status:`stopped`}),o([i,[]],t,[]),{snapshot:i,microsteps:a};let s=t;if(s.type!==Wn){let t=s,c=cr(t),l=Mi(t,i);if(c&&!l.length)return i=Hi(ji(i,t,n),{status:`error`,error:t.error}),o([i,[]],t,[]),{snapshot:i,microsteps:a};let u=yi(l,e,n,s,!1,r);i=u[0],o(u,t,l)}let c=!0,l=e.machine.options?.maxIterations??1/0,u=0;for(;i.status===`active`;){if(u++,u>l)throw Error(`Infinite loop detected: the machine has processed more than ${l} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`);let e=c?Ni(i,s):[],t=e.length?i:void 0;if(!e.length){if(!r.length)break;s=r.shift(),e=Mi(s,i)}let a=yi(e,i,n,s,!1,r);i=a[0],c=i!==t,o(a,s,e)}return i.status!==`active`&&ji(i,s,n),{snapshot:i,microsteps:a}}function ji(e,t,n){return ki(e,t,n,Object.values(e.children).map(e=>Mr(e)),[],void 0)}function Mi(e,t){return t.machine.getTransitionData(t,e)}function Ni(e,t){let n=new Set,r=e._nodes.filter(Ir);for(let i of r)loop:for(let r of[i].concat(Rr(i,void 0)))if(r.always){for(let i of r.always)if(i.guard===void 0||Fr(i.guard,e.context,t,e)){n.add(i);break loop}}return fi(Array.from(n),new Set(e._nodes),e.historyValue)}function Pi(e,t){return Hr(e,[...zr(ii(e,t))])}function Fi(e){return!!e&&typeof e==`object`&&`machine`in e&&`value`in e}var Ii=function(e){return $n(e,this.value)},Li=function(e){return this.tags.has(e)},Ri=function(e){let t=this.machine.getTransitionData(this,e);return!!t?.length&&t.some(e=>e.target!==void 0||e.actions.length)},zi=function(){let{_nodes:e,tags:t,machine:n,getMeta:r,toJSON:i,can:a,hasTag:o,matches:s,...c}=this;return{...c,tags:Array.from(t)}},Bi=function(){return this._nodes.reduce((e,t)=>(t.meta!==void 0&&(e[t.id]=t.meta),e),{})};function Vi(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:Hr(t.root,e._nodes),tags:new Set(e._nodes.flatMap(e=>e.tags)),children:e.children,historyValue:e.historyValue||{},matches:Ii,hasTag:Li,can:Ri,getMeta:Bi,toJSON:zi}}function Hi(e,t={}){return Vi({...e,...t},e.machine)}function Ui(e){if(typeof e!=`object`||!e)return{};let t={};for(let n in e){let r=e[n];Array.isArray(r)&&(t[n]=r.map(e=>({id:e.id})))}return t}function Wi(e,t){let{_nodes:n,tags:r,machine:i,children:a,context:o,can:s,hasTag:c,matches:l,getMeta:u,toJSON:d,...f}=e,p={};for(let e in a){let n=a[e];p[e]={snapshot:n.getPersistedSnapshot(t),src:n.src,systemId:n.systemId,syncSnapshot:n._syncSnapshot}}return{...f,context:Gi(o),children:p,historyValue:Ui(f.historyValue)}}function Gi(e){let t;for(let n in e){let r=e[n];if(r&&typeof r==`object`){if(`sessionId`in r&&`send`in r&&`ref`in r)t??=Array.isArray(e)?e.slice():{...e},t[n]={xstate$$type:1,id:r.id};else{let i=Gi(r);i!==r&&(t??=Array.isArray(e)?e.slice():{...e},t[n]=i)}}}return t??e}function Ki(e,t,n,r,{event:i,id:a,delay:o},{internalQueue:s}){let c=t.machine.implementations.delays;if(typeof i==`string`)throw Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);let l=typeof i==`function`?i(n,r):i,u;if(typeof o==`string`){let e=c&&c[o];u=typeof e==`function`?e(n,r):e}else u=typeof o==`function`?o(n,r):o;return typeof u!=`number`&&s.push(l),[t,{event:l,id:a,delay:u},void 0]}function qi(e,t){let{event:n,delay:r,id:i}=t;typeof r==`number`&&e.defer(()=>{let t=e.self;e.system.scheduler.schedule(t,t,n,r,i)})}function Ji(e,t){function n(e,t){}return n.type=`xstate.raise`,n.event=e,n.id=t?.id,n.delay=t?.delay,n.resolve=Ki,n.execute=qi,n}function Yi(e,{machine:t,context:n},r,i){let a=(a,o)=>{if(typeof a==`string`){let s=pr(t,a);if(!s)throw Error(`Actor logic '${a}' not implemented in machine '${t.id}'`);let c=Sr(s,{id:o?.id,parent:e.self,syncSnapshot:o?.syncSnapshot,input:typeof o?.input==`function`?o.input({context:n,event:r,self:e.self}):o?.input,src:a,systemId:o?.systemId});return i[c.id]=c,c}return Sr(a,{id:o?.id,parent:e.self,syncSnapshot:o?.syncSnapshot,input:o?.input,src:a,systemId:o?.systemId})};return(t,n)=>{let r=a(t,n);return i[r.id]=r,e.defer(()=>{r._processingStatus!==yr.Stopped&&r.start()}),r}}function Xi(e,t,n,r,{assignment:i}){if(!t.context)throw Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");let a={},o={context:t.context,event:n.event,spawn:Yi(e,t,n.event,a),self:e.self,system:e.system},s={};if(typeof i==`function`)s=i(o,r);else for(let e of Object.keys(i)){let t=i[e];s[e]=typeof t==`function`?t(o,r):t}return[Hi(t,{context:Object.assign({},t.context,s),children:Object.keys(a).length?{...t.children,...a}:t.children}),void 0,void 0]}function Zi(e){function t(e,t){}return t.type=`xstate.assign`,t.assignment=e,t.resolve=Xi,t}var Qi=new WeakMap;function $i(e,t,n){let r=Qi.get(e);return r?t in r||(r[t]=n()):(r={[t]:n()},Qi.set(e,r)),r[t]}var ea={},ta=e=>typeof e==`string`?{type:e}:typeof e==`function`?`resolve`in e?{type:e.type}:{type:e.name}:e,na=class e{constructor(t,n){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(`.`),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?`compound`:this.config.history?`history`:`atomic`),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?rr(this.config.states,(t,n)=>new e(t,{_parent:this,_key:n,_machine:this.machine})):ea,this.type===`compound`&&!this.config.initial)throw Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?`shallow`:this.config.history||!1,this.entry=ar(this.config.entry).slice(),this.exit=ar(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type===`final`||!this.parent?this.config.output:void 0,this.tags=ar(t.tags).slice()}_initialize(){this.transitions=Jr(this),this.config.always&&(this.always=lr(this.config.always).map(e=>qr(this,``,e))),Object.keys(this.states).forEach(e=>{this.states[e]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(ta),eventType:null,reenter:!1,meta:this.initial.meta,description:this.initial.description,toJSON:()=>({target:this.initial.target.map(e=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ta),eventType:null,meta:this.initial.meta,description:this.initial.description})}:void 0,history:this.history,states:rr(this.states,e=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(e=>({...e,actions:e.actions.map(ta)})),entry:this.entry.map(ta),exit:this.exit.map(ta),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return $i(this,`invoke`,()=>ar(this.config.invoke).map((e,t)=>{let{src:n,systemId:r}=e,i=e.id??fr(this.id,t),a=typeof n==`string`?n:`xstate.invoke.${fr(this.id,t)}`;return{...e,src:a,id:i,systemId:r,toJSON(){let{onDone:t,onError:n,...r}=e;return{...r,type:`xstate.invoke`,src:a,id:i}}}}))}get on(){return $i(this,`on`,()=>[...this.transitions].flatMap(([e,t])=>t.map(t=>[e,t])).reduce((e,[t,n])=>(e[t]=e[t]||[],e[t].push(n),e),{}))}get after(){return $i(this,`delayedTransitions`,()=>Kr(this))}get initial(){return $i(this,`initial`,()=>Xr(this,this.config.initial))}next(e,t){let n=t.type,r=[],i,a=$i(this,`candidates-${n}`,()=>Gr(this,n));for(let o of a){let{guard:a}=o,s=e.context,c=!1;try{c=!a||Fr(a,s,t,e)}catch(e){let t=typeof a==`string`?a:typeof a==`object`?a.type:void 0;throw Error(`Unable to evaluate guard ${t?`'${t}' `:``}in transition for event '${n}' in state node '${this.id}':\n${e.message}`)}if(c){r.push(...o.actions),i=o;break}}return i?[i]:void 0}get events(){return $i(this,`events`,()=>{let{states:e}=this,t=new Set(this.ownEvents);if(e)for(let n of Object.keys(e)){let r=e[n];if(r.states)for(let e of r.events)t.add(`${e}`)}return Array.from(t)})}get ownEvents(){let e=Object.keys(Object.fromEntries(this.transitions)),t=new Set(e.filter(e=>this.transitions.get(e).some(e=>!(!e.target&&!e.actions.length&&!e.reenter))));return Array.from(t)}},ra=class e{constructor(e,t){this.config=e,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=e.id||`(machine)`,this.implementations={actors:t?.actors??{},actions:t?.actions??{},delays:t?.delays??{},guards:t?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new na(e,{_key:this.id,_machine:this}),this.root._initialize(),Yr(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){let{actions:n,guards:r,actors:i,delays:a}=this.implementations;return new e(this.config,{actions:{...n,...t.actions},guards:{...r,...t.guards},actors:{...i,...t.actors},delays:{...a,...t.delays}})}resolveState(e){let t=Pi(this.root,e.value),n=zr(ii(this.root,t));return Vi({_nodes:[...n],context:e.context||{},children:{},status:Ur(n,this.root)?`done`:e.status||`active`,output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,t,n){return Ai(e,t,n,[]).snapshot}microstep(e,t,n){return Ai(e,t,n,[]).microsteps.map(([e])=>e)}getTransitionData(e,t){return ci(this.root,e.value,e,t)||[]}_getPreInitialState(e,t,n){let{context:r}=this.config,i=Vi({context:typeof r!=`function`&&r?r:{},_nodes:[this.root],children:{},status:`active`},this);return typeof r==`function`?ki(i,t,e,[Zi(({spawn:e,event:t,self:n})=>r({spawn:e,input:t.input,self:n}))],n,void 0):i}getInitialSnapshot(e,t){let n=Xn(t),r=[],i=Vi({context:typeof this.config.context!=`function`&&this.config.context?this.config.context:{},_nodes:[this.root],children:{},status:`active`},this);try{i=this._getPreInitialState(e,n,r);let[t]=vi(this.root,i,e,n,r),{snapshot:a}=Ai(t,n,e,r);return a}catch(e){return Hi(i,{status:`error`,error:e})}}start(e){Object.values(e.children).forEach(e=>{e.getSnapshot().status===`active`&&e.start()})}getStateNodeById(e){let t=er(e),n=t.slice(1),r=Wr(t[0])?t[0].slice(1):t[0],i=this.idMap.get(r);if(!i)throw Error(`Child state node '#${r}' does not exist on machine '${this.id}'`);return ri(i,n)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(e,t){return Wi(e,t)}restoreSnapshot(e,t){let n={},r=e.children;Object.keys(r).forEach(e=>{let i=r[e],a=i.snapshot,o=i.src,s=typeof o==`string`?pr(this,o):o;if(!s)return;let c=Sr(s,{id:e,parent:t.self,syncSnapshot:i.syncSnapshot,snapshot:a,src:o,systemId:i.systemId});n[e]=c});function i(e,t){if(t instanceof na)return t;try{return e.machine.getStateNodeById(t.id)}catch{}}function a(e,t){if(!t||typeof t!=`object`)return{};let n={};for(let r in t){let a=t[r];for(let t of a){let a=i(e,t);a&&(n[r]??=[],n[r].push(a))}}return n}let o=a(this.root,e.historyValue),s=Vi({...e,children:n,_nodes:Array.from(zr(ii(this.root,e.value))),historyValue:o},this),c=new Set;function l(e,t){if(!c.has(e)){c.add(e);for(let n in e){let r=e[n];if(r&&typeof r==`object`){if(`xstate$$type`in r&&r.xstate$$type===1){e[n]=t[r.id];continue}l(r,t)}}}}return l(s.context,n),s}};function ia(e,t,n,r,{event:i}){return[t,{event:typeof i==`function`?i(n,r):i},void 0]}function aa(e,{event:t}){e.defer(()=>e.emit(t))}function oa(e){function t(e,t){}return t.type=`xstate.emit`,t.event=e,t.resolve=ia,t.execute=aa,t}var sa=function(e){return e.Parent=`#_parent`,e.Internal=`#_internal`,e}({});function ca(e,t,n,r,{to:i,event:a,id:o,delay:s},c){let l=t.machine.implementations.delays;if(typeof a==`string`)throw Error(`Only event objects may be used with sendTo; use sendTo({ type: "${a}" }) instead`);let u=typeof a==`function`?a(n,r):a,d;if(typeof s==`string`){let e=l&&l[s];d=typeof e==`function`?e(n,r):e}else d=typeof s==`function`?s(n,r):s;let f=typeof i==`function`?i(n,r):i,p;if(typeof f==`string`){if(p=f===sa.Parent?e.self._parent:f===sa.Internal?e.self:f.startsWith(`#_`)?t.children[f.slice(2)]:c.deferredActorIds?.includes(f)?f:t.children[f],!p)throw Error(`Unable to send event to actor '${f}' from machine '${t.machine.id}'.`)}else p=f||e.self;return[t,{to:p,targetId:typeof f==`string`?f:void 0,event:u,id:o,delay:d},void 0]}function la(e,t,n){typeof n.to==`string`&&(n.to=t.children[n.to])}function ua(e,t){e.defer(()=>{let{to:n,event:r,delay:i,id:a}=t;typeof i==`number`?e.system.scheduler.schedule(e.self,n,r,i,a):e.system._relay(e.self,n,r.type===`xstate.error`?Yn(e.self.id,r.data):r)})}function da(e,t,n){function r(e,t){}return r.type=`xstate.sendTo`,r.to=e,r.event=t,r.id=n?.id,r.delay=n?.delay,r.resolve=ca,r.retryResolve=la,r.execute=ua,r}function fa(e,t){return da(sa.Parent,e,t)}function pa(e,t,n,r,{collect:i}){let a=[],o=function(e){a.push(e)};return o.assign=(...e)=>{a.push(Zi(...e))},o.cancel=(...e)=>{a.push(Tr(...e))},o.raise=(...e)=>{a.push(Ji(...e))},o.sendTo=(...e)=>{a.push(da(...e))},o.sendParent=(...e)=>{a.push(fa(...e))},o.spawnChild=(...e)=>{a.push(Or(...e))},o.stopChild=(...e)=>{a.push(Mr(...e))},o.emit=(...e)=>{a.push(oa(...e))},i({context:n.context,event:n.event,enqueue:o,check:e=>Fr(e,t.context,n.event,t),self:e.self,system:e.system},r),[t,void 0,a]}function ma(e){function t(e,t){}return t.type=`xstate.enqueueActions`,t.collect=e,t.resolve=pa,t}function ha(e,t,n,r,{value:i,label:a}){return[t,{value:typeof i==`function`?i(n,r):i,label:a},void 0]}function ga({logger:e},{value:t,label:n}){n?e(n,t):e(t)}function _a(e=({context:e,event:t})=>({context:e,event:t}),t){function n(e,t){}return n.type=`xstate.log`,n.value=e,n.label=t,n.resolve=ha,n.execute=ga,n}function va(e,t){return new ra(e,t)}function ya({schemas:e,actors:t,actions:n,guards:r,delays:i}){return{assign:Zi,sendTo:da,raise:Ji,log:_a,cancel:Tr,stopChild:Mr,enqueueActions:ma,emit:oa,spawnChild:Or,createStateConfig:e=>e,createAction:e=>e,createMachine:a=>va({...a,schemas:e},{actors:t,actions:n,guards:r,delays:i}),extend:a=>ya({schemas:e,actors:t,actions:{...n,...a.actions},guards:{...r,...a.guards},delays:{...i,...a.delays}})}}var ba=(e,t,n)=>Math.max(t,Math.min(n,e)),xa=class{dents=[];revision=0;enabled=!1;maxDepthM=0;maskCache=new WeakMap;spriteCache=null;captureState(){return E({dents:this.dents,revision:this.revision,enabled:this.enabled,maxDepthM:this.maxDepthM})}restoreState(e){let t=E(e);this.dents=t.dents,this.revision=t.revision,this.enabled=t.enabled,this.maxDepthM=t.maxDepthM,this.maskCache=new WeakMap,this.spriteCache=null}get hasDamage(){return this.enabled&&this.dents.length>0}get geometryRevision(){return this.revision}setEnabled(e){this.enabled!==e&&(this.enabled=e,e||this.reset())}reset(){this.dents=[],this.maxDepthM=0,this.revision++,this.spriteCache=null}hit(e,t,n,r,i){if(!this.enabled||r<=2.5||!Number.isFinite(r))return!1;let a=Math.max(1,i),o=k(e,n.center),s=D(j(o,n.forward)/a,j(o,n.side)/a),c=D(j(t,n.forward),j(t,n.side)),l=M(c);if(l<.001)return!1;let u=ba((r-2.5)/17.5,0,1)**1.5;return this.maxDepthM=Math.min(.25,8/a),this.dents.push({center:s,inward:A(c,1/l),depthM:this.maxDepthM*u,radiusAlongM:.65+u*.5,radiusAcrossM:.55+u*.55}),this.dents.length>12&&this.dents.shift(),this.revision++,this.spriteCache=null,!0}point(e){if(!this.hasDamage)return e;let t=D();for(let n of this.dents){let r=(e.x-n.center.x)/n.radiusAlongM,i=(e.y-n.center.y)/n.radiusAcrossM,a=Math.hypot(r,i);if(a>=1)continue;let o=(1-a*a)**2;t=O(t,A(n.inward,n.depthM*o))}let n=M(t);return n>this.maxDepthM&&(t=A(t,this.maxDepthM/n)),O(e,t)}maskFor(e){if(!this.hasDamage)return e;let t=this.maskCache.get(e);if(t?.revision===this.revision)return t.value;let{columns:n,rows:r,solid:i}=e.alpha,a=new Uint8Array(i.length),o=e.lengthM/n,s=e.widthM/r;for(let t=0;t<r;t++)for(let c=0;c<n;c++){let l=D((c+.5)*o-e.lengthM/2,(t+.5)*s-e.widthM/2),u=l;for(let e=0;e<5;e++)u=O(u,k(l,this.point(u)));let d=Math.floor((u.x/e.lengthM+.5)*n),f=Math.floor((u.y/e.widthM+.5)*r);d>=0&&d<n&&f>=0&&f<r&&(a[t*n+c]=i[f*n+d])}let c={...e,alpha:{columns:n,rows:r,solid:a}};return this.maskCache.set(e,{revision:this.revision,value:c}),c}spriteFor(e,t){if(!this.hasDamage)return null;let n=`${t.source.x}:${t.source.y}:${t.source.width}:${t.source.height}:${t.lengthM}:${t.widthM}`;if(this.spriteCache?.image===e&&this.spriteCache.key===n&&this.spriteCache.revision===this.revision)return this.spriteCache.canvas;let r=document.createElement(`canvas`);r.width=Math.max(1,Math.round(t.source.width)),r.height=Math.max(1,Math.round(t.source.height));let i=r.getContext(`2d`);if(!i)return null;let a=e=>{let n=D((e.x/r.width-.5)*t.lengthM,(e.y/r.height-.5)*t.widthM),i=this.point(n);return D((i.x/t.lengthM+.5)*r.width,(i.y/t.widthM+.5)*r.height)};for(let n=0;n<10;n++)for(let o=0;o<20;o++){let s=o*r.width/20,c=(o+1)*r.width/20,l=n*r.height/10,u=(n+1)*r.height/10,d=D(s,l),f=D(c,l),p=D(s,u),m=D(c,u);this.drawTriangle(i,e,t,[d,f,p],[a(d),a(f),a(p)]),this.drawTriangle(i,e,t,[m,p,f],[a(m),a(p),a(f)])}return this.spriteCache={image:e,key:n,revision:this.revision,canvas:r},r}drawTriangle(e,t,n,r,i){let[a,o,s]=r,[c,l,u]=i,d=o.x-a.x,f=o.y-a.y,p=s.x-a.x,m=s.y-a.y,h=d*m-p*f;if(Math.abs(h)<1e-4)return;let g=l.x-c.x,_=l.y-c.y,v=u.x-c.x,y=u.y-c.y,b=(g*m-v*f)/h,x=(_*m-y*f)/h,S=(v*d-g*p)/h,C=(y*d-_*p)/h,w=c.x-b*a.x-S*a.y,ee=c.y-x*a.x-C*a.y;e.save(),e.beginPath(),e.moveTo(c.x,c.y),e.lineTo(l.x,l.y),e.lineTo(u.x,u.y),e.closePath(),e.clip(),e.transform(b,x,S,C,w,ee),e.drawImage(t,n.source.x,n.source.y,n.source.width,n.source.height,0,0,e.canvas.width,e.canvas.height),e.restore()}};function Sa(e,t,n,r,i,a,o=Math.random){let s=Math.hypot(t.x,t.y)||1,c={x:t.x/s,y:t.y/s},l={x:-c.y,y:c.x},u=Math.max(.4,Math.min(2,i)),d=[];for(let t=0;t<r;t++){let t=o()<.985-a*.045,r=(t?1+o()**.65*(12+u*15):.8+o()*7)*(1-a*.38),i=(o()+o()-1)*r*(.1+o()*.32),s=t?.025+o()**2.8*n*.14:n*(.16+o()**2*(.2+a*.35));d.push({x:e.x+n*(c.x*r+l.x*i),y:e.y+n*(c.y*r+l.y*i),radius:s,angularity:t?u*(.25+o()*.75):u*o(),opacity:t?.28+o()*.62:.85+o()*.15})}return d}var Ca=e=>{let t=Math.sin(e*127.1+311.7)*43758.5453;return t-Math.floor(t)};function wa(e,t,n,r,i,a,o=1){let s=t.material;e.save();let c=t.exit?.leadInM,l=c?Math.max(.05,c-Math.max(t.widthM*1.5,.25)):0,u=c?Math.max(0,Math.min(1,(c+(t.exit.fromM+t.exit.toM)*.5)/l)):1,d=o*u*u*(3-2*u);if(e.strokeStyle=t.color,e.fillStyle=t.color,e.globalAlpha=t.opacity*d,t.droplet){e.translate(r.x,r.y),e.rotate(t.angle),e.beginPath(),e.ellipse(0,0,i/2,i*t.droplet.aspect/2,0,0,Math.PI*2),e.fill(),e.restore();return}let f=r.x-n.x,p=r.y-n.y,m=Math.hypot(f,p);if(!s){e.lineWidth=i,e.lineCap=`round`,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(r.x,r.y),e.stroke(),e.restore();return}e.translate(n.x,n.y),e.rotate(m>.01?Math.atan2(p,f):t.angle);let h=t.wetness??1,g=t.slip??0,_=Math.max(1.5,s.pitchM*a),v=(t.phaseM??0)*a%_,y=t.opacity*d*s.coverage,b=Math.min(1,s.film*(.35+.65*h)+g*.3);if(t.exit){let e=Math.max(0,(t.exit.fromM+t.exit.toM)*.5),n=Math.min(1,e/t.exit.lengthM);b+=(1-b)*(1-n)*(1-n)}b>.005&&m>0&&(e.globalAlpha=y*b,e.lineWidth=i*.88,e.lineCap=t.exit?`round`:`butt`,e.beginPath(),e.moveTo(0,0),e.lineTo(m,0),e.stroke());let x=m<.01?0:_-v;for(let n=x,r=0;n<=m+.001&&r<256;n+=_,r++){let r=Math.round(((t.phaseM??0)*a+n)/_);for(let a=0;a<4;a++){let o=Ca(r*17+a*7);if(o<s.breakup*(1-h*.65))continue;let c=(a-1.5)*i*.245,l=i*(.19+o*.025),u=_*(.5+g*.35),d=(a<2?1:-1)*l*.4;e.globalAlpha=y*(.62+o*.38)*(1-b*.65),e.fillStyle=t.color,e.beginPath(),e.moveTo(n-u*.5,c-l*.5),e.lineTo(n+u*.5,c-l*.5+d),e.lineTo(n+u*.5,c+l*.5+d),e.lineTo(n-u*.5,c+l*.5),e.closePath(),e.fill(),(s.gloss>.1||s.emission>0)&&(e.strokeStyle=s.emission>.5?`#ff9b25`:s.iridescence>.15?r%3?`#7faaa3`:`#9d7d99`:`#e2e8db`,e.globalAlpha=y*h*(s.emission>.5?.7:.11+s.gloss*.16),e.lineWidth=Math.max(.2,i*.035),e.beginPath(),e.moveTo(n-u*.4,c-l*.4),e.lineTo(n+u*.4,c-l*.4+d),e.stroke()),s.grain>.1&&o>.45&&(e.globalAlpha=y*s.grain*.35,e.fillStyle=`#372b22`,e.fillRect(n+u*.1,c,Math.max(.25,i*.05),Math.max(.3,i*.1)))}}e.restore()}var Ta=new Map,Ea=null;function Da(e){let t=e.match(/^#([\da-f]{3}|[\da-f]{6})$/i)?.[1];if(t){let e=t.length===3?[...t].map(e=>e+e).join(``):t;return[0,2,4].map(t=>parseInt(e.slice(t,t+2),16))}let n=e.match(/^rgba?\(\s*(\d{1,3})[,\s]+(\d{1,3})[,\s]+(\d{1,3})/i);return n?[P(+n[1],0,255),P(+n[2],0,255),P(+n[3],0,255)]:null}function Oa(e){let t=Da(e);if(t)return t;if(Ta.has(e))return Ta.get(e);let n=null;return typeof document<`u`&&(Ea??=document.createElement(`canvas`).getContext(`2d`),Ea&&(Ea.fillStyle=`#010203`,Ea.fillStyle=e,Ea.fillStyle!==`#010203`&&(n=Da(Ea.fillStyle)))),Ta.set(e,n),n}var ka=[[0,0],[60,120],[120,180],[240,240],[300,300],[360,360]];function Aa(e,t=!1){let n=(e%360+360)%360;for(let e=1;e<ka.length;e++){let[r,i]=ka[e-1],[a,o]=ka[e],s=t?i:r,c=t?o:a;if(n<=c){let e=(n-s)/(c-s);return(t?r+(a-r)*e:i+(o-i)*e)%360}}return 0}function ja([e,t,n]){let r=e/255,i=t/255,a=n/255,o=Math.max(r,i,a),s=Math.min(r,i,a),c=o-s,l=(o+s)/2;if(c===0)return{hue:0,saturation:0,light:l};let u=c/(1-Math.abs(2*l-1));return{hue:((o===r?(i-a)/c%6:o===i?(a-r)/c+2:(r-i)/c+4)*60+360)%360,saturation:u,light:l}}function Ma(e,t,n){let r=(1-Math.abs(2*n-1))*t,i=r*(1-Math.abs(e/60%2-1)),a=Math.floor(e/60)%6,o=[[r,i,0],[i,r,0],[0,r,i],[0,i,r],[i,0,r],[r,0,i]][a],s=n-r/2;return`rgb(${o.map(e=>Math.round((e+s)*255)).join(` `)})`}function Na(e){let t=e.filter(e=>e.strength>0&&Oa(e.color));if(!t.length)return e.at(-1)?.color??`rgb(0 0 0)`;if(t.length===1)return`rgb(${Oa(t[0].color).join(` `)})`;let n=0,r=0,i=0,a=0,o=0;for(let e of t){let t=ja(Oa(e.color)),s=Aa(t.hue)*Math.PI/180,c=e.strength*t.saturation;n+=Math.cos(s)*c,r+=Math.sin(s)*c,i+=t.light*e.strength,a+=c,o+=e.strength}return Ma(Aa((Math.atan2(r,n)*180/Math.PI+360)%360,!0),Math.min(1,a/o),i/o)}var Pa=class{coatings=new Map;previous=new Map;travelM=new Map;previousLayer=new Map;wetPaths=new Map;exits=new Map;sprayRemainder=new Map;marks=[];markCount=0;captureState(){return E({coatings:this.coatings,previous:this.previous,travelM:this.travelM,previousLayer:this.previousLayer,wetPaths:this.wetPaths,exits:this.exits,sprayRemainder:this.sprayRemainder,marks:this.marks,markCount:this.markCount})}restoreState(e){let t=E(e);this.coatings=t.coatings,this.previous=t.previous,this.travelM=t.travelM,this.previousLayer=t.previousLayer,this.wetPaths=t.wetPaths,this.exits=t.exits,this.sprayRemainder=t.sprayRemainder,this.marks.length=0;for(let e of t.marks)this.marks.push(e);this.markCount=t.markCount}get totalMarks(){return this.markCount}get managedBytes(){return this.marks.length*136+this.travelM.size*16+[...this.coatings.values()].reduce((e,t)=>e+t.size*72,0)+this.previous.size*24+this.previousLayer.size*8+[...this.wetPaths.values()].reduce((e,t)=>e+t.marks.length*160,0)+this.exits.size*24+this.sprayRemainder.size*16}reset(){this.travelM.clear(),this.coatings.clear(),this.previous.clear(),this.previousLayer.clear(),this.wetPaths.clear(),this.exits.clear(),this.sprayRemainder.clear(),this.marks.length=0,this.markCount=0}step(e){e.forEach((e,t)=>this.travelM.set(t,(this.travelM.get(t)??0)+Math.max(0,e)));for(let[t,n]of this.coatings){let r=Math.max(0,e[t]??0);for(let[e,t]of n)t.remaining=Math.max(0,t.remaining-r),t.remaining===0&&n.delete(e);n.size===0&&(this.coatings.delete(t),this.previous.delete(t),this.previousLayer.delete(t),this.wetPaths.delete(t),this.exits.delete(t))}}touch(e,t){if(!t||t.opacity<=0||t.distanceM<=0)return;let n=this.coatings.get(e);n||(n=new Map,this.coatings.set(e,n));let r=t.id??t.color,i=n.get(r);if(n.set(r,{...t,opacity:Math.max(i?.opacity??0,P(t.opacity,0,1)),remaining:t.distanceM}),n.size>16){let e=[...n.entries()].filter(([e])=>e!==r).sort((e,t)=>e[1].opacity*e[1].remaining/e[1].distanceM-t[1].opacity*t[1].remaining/t[1].distanceM)[0];e&&n.delete(e[0])}}wash(e,t=[]){let n=this.coatings.get(e);if(n&&t.length){let e=new Set(t.map(e=>e.id??e.color));for(let t of n.keys())e.has(t)||n.delete(t);if(n.size)return}this.coatings.delete(e),this.previous.delete(e),this.previousLayer.delete(e),this.sprayRemainder.delete(e),this.wetPaths.delete(e),this.exits.delete(e)}splatter(e,t,n,r,i,a,o){let s=this.coating(e);if(!s||i<=0||o<=0)return;let c=T.paint.thickness,l=(this.sprayRemainder.get(e)??0)+i*(9+(1-c)*7)*(s.material?.spray??.5),u=Math.min(24,Math.floor(l));this.sprayRemainder.set(e,l-Math.floor(l));for(let e of Sa(t,n,r,u,a,c)){let t=1+e.angularity*1.7,r={x:e.x,y:e.y};this.marks.push({from:r,point:r,angle:Math.atan2(n.y,n.x),widthM:e.radius*2*t/(o*.76),color:s.color,opacity:s.opacity*e.opacity,droplet:{aspect:(.5+Math.random()*.45)/t}}),this.markCount++}this.marks.length>3e4&&this.marks.splice(0,1e3)}trackWet(e,t,n,r,i,a=0,o=!1){let s=this.coating(e);if(!s){this.pauseTrack(e);return}let c=this.previous.get(e),l=this.wetPaths.get(e);if(!l||!c||M(k(t,c))>=1.5*i)l={marks:[],distanceM:0},this.wetPaths.set(e,l),o&&(this.marks.push({...s,from:{...t},point:{...t},angle:n,widthM:r,phaseM:this.travelM.get(e)??0,slip:P(a,0,1),overPuddle:!0}),this.markCount++);else{let u=l.marks.at(-1),d=u&&M(k(u.point,u.from))/i<.02,f=d?u.from:c;d&&(l.distanceM-=M(k(u.point,u.from))/i);let p=M(k(t,f))/i,m={...s,from:{...f},point:{...t},angle:n,widthM:r,phaseM:(this.travelM.get(e)??0)-p,slip:P(a,0,1)};d?l.marks[l.marks.length-1]=m:l.marks.push(m),l.distanceM+=p,o&&p>=.02&&(this.marks.push({...m,overPuddle:!0}),this.markCount++,this.marks.length>3e4&&this.marks.splice(0,1e3));let h=Math.max(.5,r*6);for(;l.marks.length>1&&(l.distanceM>h||l.marks.length>128);){let e=l.marks.shift();l.distanceM-=M(k(e.point,e.from))/i}}this.exits.delete(e),this.previous.set(e,{...t}),this.previousLayer.set(e,!1)}pauseTrack(e){this.wetPaths.delete(e),this.exits.delete(e),this.previous.delete(e),this.previousLayer.delete(e)}track(e,t,n,r,i,a=!1,o=0){let s=this.coating(e);if(!s)return;let c=this.previous.get(e),l=c?M(k(t,c)):0,u=this.wetPaths.has(e)||this.exits.has(e)?.01:.05;if(c&&l<u*i)return;let d=c&&l<1.5*i,f=this.wetPaths.get(e);if(f&&d){let t=Math.max(.35,r*(2+4*(s.material?.film??.6))),n=-f.distanceM;for(let e of f.marks){let r=n+M(k(e.point,e.from))/i;this.marks.push({...e,overPuddle:!1,exit:{fromM:n,toM:r,lengthM:t,leadInM:f.distanceM}}),this.markCount++,n=r}this.exits.set(e,{distanceM:0,lengthM:t})}else d||this.exits.delete(e);this.wetPaths.delete(e);let p=this.exits.get(e),m=p&&p.distanceM<p.lengthM?{fromM:p.distanceM,toM:p.distanceM+l/i,lengthM:p.lengthM}:void 0;p&&(p.distanceM+=l/i,p.distanceM>=p.lengthM&&this.exits.delete(e)),this.marks.push({from:d?{...c}:{...t},point:{...t},angle:n,widthM:r,phaseM:(this.travelM.get(e)??0)-(d?M(k(t,c))/i:0),wetness:s.wetness,material:s.material,slip:P(o,0,1),color:s.color,opacity:s.opacity,overPuddle:a,exit:m}),this.markCount++,this.previous.set(e,{...t}),this.previousLayer.set(e,a),this.marks.length>3e4&&this.marks.splice(0,1e3)}coating(e){let t=this.coatings.get(e);if(!t?.size)return null;let n=[...t.values()].map(e=>({color:e.color,strength:e.opacity*P(e.remaining/e.distanceM,0,1)})),r=[...t.values()].sort((e,t)=>t.opacity*t.remaining/t.distanceM-e.opacity*e.remaining/e.distanceM)[0],i=P(r.remaining/r.distanceM,0,1);return{material:r.material,wetness:i,color:Na(n),opacity:Math.max(...n.map(e=>e.strength))*i**+Math.max(0,(r.material?.drain??1)-1),remaining:Math.max(...[...t.values()].map(e=>e.remaining)),distanceM:Math.max(...[...t.values()].map(e=>e.distanceM))}}},Fa={gun:new URL(`../embed-assets/side-gun-v1-BnpvZN1b.webp`,import.meta.url).href,rocket:new URL(`../embed-assets/roof-rocket-v1-Bs4IEw-s.webp`,import.meta.url).href},Ia={gun:.55,rocket:.5},La=new Map;function Ra(e){if(typeof Image>`u`)return null;let t=La.get(e);return t||(t=new Image,t.decoding=`async`,t.crossOrigin=`anonymous`,t.src=Fa[e],La.set(e,t)),t.complete&&t.naturalWidth>0?t:null}function za(){Ra(`gun`),Ra(`rocket`)}function Ba(e,t,n,r,i){let a=Ra(t);if(!a)return!1;let o=i*a.naturalHeight/a.naturalWidth;return e.drawImage(a,n,r-o*Ia[t],i,o),!0}var Va={opening:.32,raising:.52,igniting:.48,closing:.36},Ha=class{previewOpen=!1;inspecting=!1;phase=`idle`;elapsed=0;held=!1;presetId=null;flights=[];launchClock=0;queuedShots=0;launches=0;ignitionDuration=Va.igniting;captureState(){return E({previewOpen:this.previewOpen,inspecting:this.inspecting,phase:this.phase,elapsed:this.elapsed,held:this.held,presetId:this.presetId,flights:this.flights,launchClock:this.launchClock,queuedShots:this.queuedShots,launches:this.launches,ignitionDuration:this.ignitionDuration})}restoreState(e){let t=E(e);this.previewOpen=t.previewOpen,this.inspecting=t.inspecting,this.phase=t.phase,this.elapsed=t.elapsed,this.held=t.held,this.presetId=t.presetId,this.flights=t.flights,this.launchClock=t.launchClock,this.queuedShots=t.queuedShots,this.launches=t.launches,this.ignitionDuration=t.ignitionDuration}get state(){return this.phase}get projectile(){let e=this.flights[0];return e?{...e,position:{...e.position}}:null}get projectileCount(){return this.flights.length}get managedBytes(){return this.flights.length*64}get launchCount(){return this.launches}reset(){this.previewOpen=!1,this.inspecting=!1,this.phase=`idle`,this.elapsed=0,this.held=!1,this.flights=[],this.launchClock=0,this.queuedShots=0,this.launches=0,this.ignitionDuration=Va.igniting,this.presetId=null}disarm(){this.held=!1,this.queuedShots=0,(this.phase===`opening`||this.phase===`raising`||this.phase===`igniting`)&&this.transition(`closing`)}transition(e){this.phase=e,this.elapsed=0}step(e,t,n,r,i,a,o,s){if(t.mode!==`car`){this.reset();return}if(this.presetId&&this.presetId!==t.car.preset.id&&this.reset(),this.previewOpen){this.inspecting=!0,this.presetId=t.car.preset.id,(this.phase===`idle`||this.phase===`closing`)&&this.transition(`opening`),this.elapsed+=e,this.phase===`opening`&&this.elapsed>=Va.opening&&this.transition(`raising`),this.phase===`raising`&&(this.elapsed=Math.min(this.elapsed,Va.raising));return}this.inspecting&&(this.inspecting=!1,this.transition(`closing`));let c=!!t.lastInput.rocket;c&&!this.held&&(this.queuedShots++,(this.phase===`idle`||this.phase===`closing`)&&(this.presetId=t.car.preset.id,this.transition(`opening`))),this.held=c;let l=et(t.car.preset);if(this.phase===`idle`&&!this.flights.length)return;this.elapsed+=e,this.launchClock+=e;let u=t.car.preset.roofRocket,d=Math.max(1.05,u.sizeM*1.12);if(this.phase===`opening`&&this.elapsed>=Va.opening)this.transition(`raising`);else if(this.phase===`raising`&&this.elapsed>=Va.raising)this.ignitionDuration=Va.igniting,this.transition(`igniting`),s?.(t.body.world(D(u.xM,u.yM)));else if(this.phase===`igniting`&&this.elapsed>=this.ignitionDuration){let e=N(D(1,0),t.body.angle),n=t.body.world(D(u.xM,u.yM));this.flights.push({position:n,angle:t.body.angle,speedMps:l.launchSpeedMps+Math.max(0,j(t.body.velocity,e)),distanceM:0,age:0}),this.launches++,a?.(n),this.queuedShots=Math.max(0,this.queuedShots-1),this.launchClock=0,this.transition(`flying`)}else this.phase===`closing`&&this.elapsed>=Va.closing&&this.transition(`idle`);if(this.phase===`igniting`){let r=P(this.elapsed/Math.min(.27,this.ignitionDuration*.65),0,.9),a=N(D(-1,0),t.body.angle),o=t.body.world(D(u.xM-d*.52,u.yM));n({point:o,flow:A(a,3.5),amount:e*14*r,radiusM:.2}),i?.({from:o,to:o,flow:A(a,12),widthM:.16,intensity:r*.75})}this.phase===`flying`&&(!c&&this.queuedShots===0?this.transition(`closing`):this.launchClock>=Math.max(0,1/l.roundsPerSecond-Math.min(Va.igniting,.7/l.roundsPerSecond))&&(this.ignitionDuration=Math.min(Va.igniting,.7/l.roundsPerSecond),this.transition(`igniting`),s?.(t.body.world(D(u.xM,u.yM)))));for(let t=this.flights.length-1;t>=0;t--){let a=this.flights[t],s=N(D(1,0),a.angle);a.speedMps=Math.min(l.maxSpeedMps,a.speedMps+l.accelerationMps2*e);let c=a.speedMps*e,f=a.position,p=O(f,A(s,c)),m=r?.(f,p,u.sizeM*.18);a.position=m??p,a.distanceM+=c,a.age+=e;let h=O(a.position,A(s,-d*.53)),g=O(f,A(s,-d*.53));if(n({point:h,flow:A(s,-5),amount:e*l.smokePerSecond,radiusM:.2}),i?.({from:g,to:h,flow:A(s,-18),widthM:.13,intensity:.9}),m){o?.(m);for(let e=0;e<7;e++)n({point:m,flow:A(N(D(1,0),e*Math.PI*2/7),5.5),amount:.18,radiusM:.22});this.flights.splice(t,1)}else(a.age>=l.lifetimeSeconds||a.distanceM>100)&&this.flights.splice(t,1)}this.phase===`closing`&&this.elapsed>=Va.closing&&this.transition(`idle`)}get open(){return this.phase===`idle`?0:this.phase===`opening`?P(this.elapsed/Va.opening,0,1):this.phase===`closing`?1-P(this.elapsed/Va.closing,0,1):1}drawMount(e,t,n,r,i,a=1,o){let s=this.open;if(s<=0)return;za();let c=r.roofRocket,l=c.sizeM*i,u=s*s*(3-2*s);e.save(),e.translate(t.x,t.y),e.rotate(-n),e.translate(c.xM*i,-c.yM*i),e.globalAlpha*=a;let d=e.createLinearGradient(0,-l/2,0,l/2);d.addColorStop(0,`#11171b`),d.addColorStop(.45,`#030609`),d.addColorStop(1,`#222a2e`),e.fillStyle=d,e.beginPath(),e.roundRect(-l/2,-l/2,l,l,l*.06),e.fill(),e.strokeStyle=`#525c62`,e.lineWidth=Math.max(.45,i*.018),e.stroke();for(let t of[-1,1]){e.fillStyle=`#687279`,e.fillRect(-l*.42,t*l*.2,l*.84,l*.035),e.fillStyle=`#161d22`,e.fillRect(-l*.34,-l*.28,l*.065,l*.56);let n=l*.5*(1-u*.78),r=t*(l*.25+u*l*.22);if(e.save(),e.translate(0,r),e.shadowColor=`rgba(0,0,0,.55)`,e.shadowBlur=l*.08,e.shadowOffsetY=l*.035,e.fillStyle=c.panelColor,e.beginPath(),e.roundRect(-l/2,-n/2,l,n,l*.035),e.fill(),e.shadowBlur=0,e.shadowOffsetY=0,o){e.save(),e.clip();let r=o.source.x+(c.xM-c.sizeM/2+o.lengthM/2)/o.lengthM*o.source.width,i=o.source.y+(-c.yM+(t<0?-c.sizeM/2:0)+o.widthM/2)/o.widthM*o.source.height;e.drawImage(o.image,r,i,c.sizeM/o.lengthM*o.source.width,c.sizeM/2/o.widthM*o.source.height,-l/2,-n/2,l,n),e.restore()}e.strokeStyle=`rgba(8,13,17,.7)`,e.lineWidth=Math.max(.45,i*.018),e.stroke(),e.restore()}if(this.phase===`raising`||this.phase===`igniting`){let t=this.phase===`igniting`?1:P(this.elapsed/Va.raising,0,1);e.save(),e.globalAlpha*=t,e.scale(.35+t*.65,.35+t*.65),this.drawBody(e,Math.max(1.05,c.sizeM*1.12)*i,1),e.restore()}e.restore()}drawFlight(e,t,n,r,i=1){for(let a of this.flights){let o=t(a.position);e.save(),e.translate(o.x,o.y),e.rotate(-a.angle),e.globalAlpha=i,this.drawBody(e,Math.max(1.05,n.roofRocket.sizeM*1.12)*r,1),e.restore()}}drawBody(e,t,n){if(e.save(),e.globalAlpha*=n,e.shadowColor=`rgba(0,0,0,.5)`,e.shadowBlur=t*.055,e.shadowOffsetY=t*.025,!Ba(e,`rocket`,-t*.53,0,t*1.06)){let n=e.createLinearGradient(0,-t*.045,0,t*.045);n.addColorStop(0,`#3b454d`),n.addColorStop(.35,`#d8dddc`),n.addColorStop(1,`#3e484f`),e.fillStyle=n,e.beginPath(),e.moveTo(-t*.53,-t*.045),e.lineTo(t*.3,-t*.045),e.lineTo(t*.53,0),e.lineTo(t*.3,t*.045),e.lineTo(-t*.53,t*.045),e.closePath(),e.fill(),e.fillStyle=`#30383e`;for(let n of[-1,1])e.beginPath(),e.moveTo(-t*.48,n*t*.12),e.lineTo(-t*.22,n*t*.04),e.lineTo(-t*.44,n*t*.04),e.closePath(),e.fill()}e.restore()}},Ua=-.65,Wa=.35,Ga=1.04;function Ka(e,t){let n=Xe(e);return{x:n.xM+Wa,y:t*(e.geometry.widthM/2+n.revealM*.45)}}function qa(e,t,n,r,i,a){if(a<=0)return;let o=a*a*(3-2*a),s=Xe(t),c=t.geometry.widthM*n/2,l=n*.16*o;e.beginPath(),e.rect(-r*n/2,-i*n/2,r*n,i*n);for(let t of[-1,1])e.rect((s.xM+Ua)*n,t>0?-c:c-l,n*Ga,l);e.clip(`evenodd`)}function Ja(e,t,n,r,i,a,o,s=0,c=1,l){if(a<=0)return;za();let u=Xe(r),d=r.geometry.widthM*i/2,f=a*a*(3-2*a),p=u.revealM*f*i,m=i*.08*(1-f*.7);e.save(),e.translate(t.x,t.y),e.rotate(-n),e.globalAlpha*=c*Math.min(1,a*10);for(let t of[-1,1]){e.save(),e.translate(u.xM*i,-t*d),e.scale(1,-t);let n=e.createLinearGradient(0,-i*.16,0,i*.045);n.addColorStop(0,`#070b0e`),n.addColorStop(.75,`#252d31`),n.addColorStop(1,`rgba(12,18,22,0)`),e.fillStyle=n,e.fillRect(i*Ua,-i*.16*f,i*Ga,i*.205*f);let a=Math.max(0,p-m);if(a>0){e.save(),e.beginPath(),e.rect(i*Ua,0,i*1.34,a),e.clip();for(let t of[-.5,.16]){let n=e.createLinearGradient((t-.02)*i,0,(t+.02)*i,0);n.addColorStop(0,`#1b2227`),n.addColorStop(.45,`#b8c2c7`),n.addColorStop(.6,`#68767d`),n.addColorStop(1,`#242d32`),e.fillStyle=n,e.fillRect((t-.022)*i,0,i*.044,a)}let t=p*.45;e.translate(0,t);let n=o===`gun`?s*i*.018:0;if(e.shadowColor=`rgba(0,0,0,.6)`,e.shadowBlur=i*.045,e.shadowOffsetY=i*.025,!Ba(e,`gun`,Ua*i-n,0,i)){let t=e.createLinearGradient(0,-i*.07,0,i*.07);t.addColorStop(0,`#30383c`),t.addColorStop(.3,`#adb5b6`),t.addColorStop(.55,`#59646a`),t.addColorStop(1,`#141b20`),e.fillStyle=t,e.fillRect(Ua*i,-i*.085,i*.43,i*.17),e.fillRect(-i*.22,-i*.035,i*.57,i*.07)}if(e.shadowBlur=0,e.shadowOffsetY=0,s>0){e.save(),e.globalAlpha*=s;let t=Wa*i,n=i*(o===`flame`?.075:.14),r=e.createRadialGradient(t,0,0,t,0,n);r.addColorStop(0,o===`flame`?`#b2d8ff`:`#fffbea`),r.addColorStop(.22,o===`flame`?`#ffb14d`:`#ffcf75`),r.addColorStop(1,`rgba(255,128,24,0)`),e.fillStyle=r,e.fillRect(t-n,-n,n*2,n*2),o===`gun`&&(e.fillStyle=`#fff4c7`,e.beginPath(),e.moveTo(t,-i*.025),e.lineTo(t+i*.19,-i*.008),e.lineTo(t+i*.24,0),e.lineTo(t+i*.19,i*.008),e.lineTo(t,i*.025),e.closePath(),e.fill()),e.restore()}e.restore()}if(e.fillStyle=r.roofRocket.panelColor,e.strokeStyle=`#22292b`,e.lineWidth=Math.max(.8,i*.025),e.beginPath(),e.roundRect(i*Ua,p-m,i*Ga,m*2,i*.025),e.fill(),e.stroke(),l){let n=Ga/l.lengthM*l.source.width,a=.16/l.widthM*l.source.height,o=l.source.x+(u.xM+Ua+l.lengthM/2)/l.lengthM*l.source.width,s=-t*(r.geometry.widthM/2-.08),c=l.source.y+(s-.08+l.widthM/2)/l.widthM*l.source.height;e.save(),e.scale(1,-t),e.beginPath(),e.roundRect(i*Ua,-t*p-m,i*Ga,m*2,i*.025),e.clip(),e.drawImage(l.image,o,c,n,a,i*Ua,-t*p-m,i*Ga,m*2),e.restore()}e.restore()}e.restore()}var Ya=.22,Xa=.24,Za=class{phase=`closed`;phaseTime=0;shotClock=0;flashAge=1/0;presetId=null;bullets=[];captureState(){return E({phase:this.phase,phaseTime:this.phaseTime,shotClock:this.shotClock,flashAge:this.flashAge,presetId:this.presetId,bullets:this.bullets})}restoreState(e){let t=E(e);this.phase=t.phase,this.phaseTime=t.phaseTime,this.shotClock=t.shotClock,this.flashAge=t.flashAge,this.presetId=t.presetId,this.bullets=t.bullets}get state(){return this.phase}get openAmount(){return this.open}get projectileCount(){return this.bullets.length}get managedBytes(){return this.bullets.length*56}reset(){this.phase=`closed`,this.phaseTime=0,this.shotClock=0,this.flashAge=1/0,this.presetId=null,this.bullets=[]}step(e,t,n,r,i){if(t.mode!==`car`){this.reset();return}this.presetId&&this.presetId!==t.car.preset.id&&this.reset();let a=Xe(t.car.preset),o=!!t.lastInput.machineGun;if(o&&(this.phase===`closed`||this.phase===`closing`)){this.presetId=t.car.preset.id;let e=this.open;this.phase=`opening`,this.phaseTime=e*Ya}else if(!o&&(this.phase===`opening`||this.phase===`active`)){let e=this.open;this.phase=`closing`,this.phaseTime=(1-e)*Xa}if(this.phaseTime+=e,this.flashAge+=e,this.phase===`opening`&&this.phaseTime>=Ya&&(this.phase=`active`,this.phaseTime=0,this.shotClock=1/a.roundsPerSecond),this.phase===`active`){if(o){let n=1/Math.max(1,a.roundsPerSecond);this.shotClock+=e;for(let e=0;this.shotClock>=n&&e<4;e++)this.shotClock-=n,this.fire(t),r?.()}}else this.phase===`closing`&&this.phaseTime>=Xa&&(this.phase=`closed`,this.phaseTime=0);for(let t=this.bullets.length-1;t>=0;t--){let r=this.bullets[t],o=r.position,s=O(o,A(r.velocity,e)),c=n?.(o,s,.075);r.age+=e,c||r.age>=a.bulletLifetimeSeconds?(c&&i?.(c,r.velocity),this.bullets.splice(t,1)):r.position=s}}fire(e){let t=Xe(e.car.preset),n=N(D(1,0),e.body.angle);for(let r of[-1,1]){let i=e.body.world(Ka(e.car.preset,r)),a=O(A(n,t.bulletSpeedMps),e.body.velocityAt(i));this.bullets.push({position:i,velocity:a,age:0})}this.flashAge=0}get open(){return this.phase===`closed`?0:this.phase===`opening`?P(this.phaseTime/Ya,0,1):this.phase===`closing`?1-P(this.phaseTime/Xa,0,1):1}drawMount(e,t,n,r,i,a=1,o){Ja(e,t,n,r,i,this.open,`gun`,Math.max(0,1-this.flashAge/.075),a,o)}drawProjectiles(e,t,n,r=1){e.save(),e.lineCap=`round`;for(let i of this.bullets){let a=t(i.position),o=Math.hypot(i.velocity.x,i.velocity.y),s=t(O(i.position,A(i.velocity,-.75/Math.max(1,o)))),c=e.createLinearGradient(s.x,s.y,a.x,a.y);c.addColorStop(0,`rgba(224,153,63,0)`),c.addColorStop(.7,`rgba(224,153,63,.25)`),c.addColorStop(1,`rgba(255,225,157,.7)`),e.globalAlpha=r,e.strokeStyle=c,e.lineWidth=Math.max(.65,n*.025),e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(a.x,a.y),e.stroke();let l=t(O(i.position,A(i.velocity,-.09/Math.max(1,o))));e.strokeStyle=`#fff6d7`,e.lineWidth=Math.max(.55,n*.018),e.beginPath(),e.moveTo(l.x,l.y),e.lineTo(a.x,a.y),e.stroke()}e.restore()}},Qa=.22,$a=.24,eo=1/45,to=class{phase=`closed`;phaseTime=0;emitting=!1;presetId=null;fireClock=0;jets=[];captureState(){return E({phase:this.phase,phaseTime:this.phaseTime,emitting:this.emitting,presetId:this.presetId,fireClock:this.fireClock,jets:this.jets})}restoreState(e){let t=E(e);this.phase=t.phase,this.phaseTime=t.phaseTime,this.emitting=t.emitting,this.presetId=t.presetId,this.fireClock=t.fireClock,this.jets=t.jets}get state(){return this.phase}get firing(){return this.emitting}get openAmount(){return this.open}get managedBytes(){return this.jets.length*64}reset(){this.phase=`closed`,this.phaseTime=0,this.emitting=!1,this.presetId=null,this.fireClock=0,this.jets=[]}step(e,t,n,r,i){if(t.mode!==`car`){(this.phase!==`closed`||this.jets.length)&&this.reset();return}this.presetId&&this.presetId!==t.car.preset.id&&this.reset();let a=!!t.lastInput.flamethrower,o=Qe(t.car.preset);if(a&&(this.phase===`closed`||this.phase===`closing`)){this.presetId=t.car.preset.id;let e=this.open;this.phase=`opening`,this.phaseTime=e*Qa}else if(!a&&(this.phase===`opening`||this.phase===`active`)){let e=this.open;this.phase=`closing`,this.phaseTime=(1-e)*$a}if(this.phaseTime+=e,this.phase===`opening`&&this.phaseTime>=Qa&&(this.phase=`active`,this.phaseTime=0,this.fireClock=eo),this.emitting=this.phase===`active`&&a,this.phase===`closing`&&this.phaseTime>=$a&&(this.phase=`closed`,this.phaseTime=0),this.emitting){let r=N(D(1,0),t.body.angle),i=o.rangeM/.3;for(this.fireClock+=e;this.fireClock>=eo;){this.fireClock-=eo;for(let e of[-1,1]){let n=t.body.world(Ka(t.car.preset,e));this.jets.push({point:n,velocity:O(A(r,i),A(t.body.velocity,.25)),traveled:0,range:o.rangeM,speed:i,width:o.jetWidthM*o.flowRate})}}for(let i of[-1,1])n({point:O(t.body.world(Ka(t.car.preset,i)),A(r,.06)),flow:A(r,5.5),amount:e*o.smokePerSecond*o.flowRate*.38,radiusM:.12})}let s=[];for(let t of this.jets){let a=Math.min(t.range-t.traveled,t.speed*e),c=t.point,l=O(c,A(t.velocity,a/t.speed)),u=(t.traveled+a)/t.range,d=t.width*(.65+1.45*u),f=r?.(c,l,Math.max(.3,d*1.25),eo*o.flowRate),p=f??l;t.point=p,t.traveled+=a,i?.(c,p,d,t.velocity,u),(u>.62||f)&&n({point:p,flow:A(t.velocity,.42),amount:e*o.smokePerSecond*o.flowRate*(f?.42:.18),radiusM:Math.max(.11,d*.48)}),f?i?.(p,p,d*1.35,t.velocity,u):t.traveled+1e-6<t.range&&s.push(t)}this.jets=s}get open(){return this.phase===`closed`?0:this.phase===`opening`?P(this.phaseTime/Qa,0,1):this.phase===`closing`?1-P(this.phaseTime/$a,0,1):1}drawMount(e,t,n,r,i,a=1,o){Ja(e,t,n,r,i,this.open,`flame`,this.phase===`active`?.8:0,a,o)}},no=class{rocket=new Ha;machineGuns=new Za;flamethrower=new to;lightning=new Pn;reset(){this.rocket.reset(),this.machineGuns.reset(),this.flamethrower.reset(),this.lightning.reset()}stopFiring(){this.rocket.disarm(),this.lightning.reset()}captureState(){return{rocket:this.rocket.captureState(),machineGuns:this.machineGuns.captureState(),flamethrower:this.flamethrower.captureState(),lightning:this.lightning.captureState()}}restoreState(e){this.rocket.restoreState(e.rocket),this.machineGuns.restoreState(e.machineGuns),this.flamethrower.restoreState(e.flamethrower),e.lightning?this.lightning.restoreState(e.lightning):this.lightning.reset()}get managedBytes(){return this.rocket.managedBytes+this.machineGuns.managedBytes+this.flamethrower.managedBytes}},ro={boost:{capacity:2.6,partialRecharge:1.1,emptyRecharge:2,partialPause:.35,emptyPause:.9,label:`Boost`},eject:{capacity:4,partialRecharge:2.2,emptyRecharge:4.5,partialPause:.3,emptyPause:1.1,label:`Liquid`},machineGun:{capacity:5,partialRecharge:2.4,emptyRecharge:5,partialPause:.3,emptyPause:1.2,label:`Machine guns`},flamethrower:{capacity:3.5,partialRecharge:2.8,emptyRecharge:5.2,partialPause:.4,emptyPause:1.4,label:`Flamethrower`},rocket:{capacity:4.5,partialRecharge:3,emptyRecharge:5.5,partialPause:.4,emptyPause:1.5,label:`Rocket`},ghost:{capacity:5,partialRecharge:3,emptyRecharge:5,partialPause:.35,emptyPause:1.2,label:`Ghost`},lightning:{capacity:1.1,partialRecharge:.8,emptyRecharge:2.4,partialPause:.2,emptyPause:.6,label:`Lightning`}},io=Object.keys(ro),ao=class{reserves=new Map;time=0;stepScales=new Map;enabled=!0;reset(){this.reserves.clear(),this.stepScales.clear(),this.time=0}captureState(){return{enabled:this.enabled,time:this.time,stepScales:[...this.stepScales],reserves:[...this.reserves].map(([e,t])=>[e,{...t}])}}restoreState(e){this.enabled=e.enabled,this.time=e.time,this.stepScales=new Map(e.stepScales),this.reserves=new Map(e.reserves.map(([e,t])=>[e,{...t}]))}consumptionScale(e){return this.enabled?this.stepScales.get(e)??1:1}fraction(e){return this.reserves.get(e)?.fill??1}step(e,t,n,r={}){if(this.stepScales.clear(),!this.enabled)return e;this.time+=Math.max(0,t);let i={...e},a=this.time;for(let o of io){let s=ro[o],c=o===`boost`&&n?{...s,capacity:Math.max(.1,n.durationSeconds),partialRecharge:Math.max(.1,n.cooldownSeconds*.55),emptyRecharge:Math.max(.1,n.cooldownSeconds)}:s,l=this.reserves.get(o)??{fill:1,pause:0,exhausted:!1,lastUsedAt:-1/0},u=!!e[o]&&(o!==`boost`||e.throttle>.5)&&!l.exhausted&&l.fill>0;i[o]=u;let d=Math.max(0,t)*Math.max(0,r[o]??1)/c.capacity,f=u&&d>0?Math.min(1,l.fill/d):+!!u;this.stepScales.set(o,f),u?(l.fill=Math.max(0,l.fill-d*f),l.pause=c.partialPause,l.lastUsedAt=a,l.fill===0&&(l.exhausted=!0,l.pause=c.emptyPause)):l.fill<1&&(l.pause=Math.max(0,l.pause-Math.max(0,t)),l.pause===0&&(l.fill=Math.min(1,l.fill+Math.max(0,t)/(l.exhausted?c.emptyRecharge:c.partialRecharge)),l.fill===1&&(l.exhausted=!1))),l.fill<1||a-l.lastUsedAt<1.8?this.reserves.set(o,l):this.reserves.delete(o)}return i}indicator(e=this.time){if(!this.enabled)return null;let t=[...this.reserves].sort((e,t)=>t[1].lastUsedAt-e[1].lastUsedAt)[0];if(!t)return null;let[n,r]=t,i=e-r.lastUsedAt;if(r.fill>=1&&i>=1.8)return null;let a=r.fill<1?1:Math.min(1,(1.8-i)/.45);return{label:ro[n].label,fraction:r.fill,alpha:a,depleted:r.exhausted||r.fill===0,recharging:r.fill<1&&r.pause===0}}},oo=[{id:`boost`,label:`Boost`,keys:[`Shift`],description:`Burn rear tracks while held`,sfw:!0,weapon:!1},{id:`eject`,label:`Liquid`,keys:[`1`],description:`Pour while held`,sfw:!0,weapon:!1},{id:`machineGun`,label:`Machine guns`,keys:[`2`],description:`Fire while held`,sfw:!1,weapon:!0},{id:`flamethrower`,label:`Flamethrower`,keys:[`3`],description:`Burn objects while held`,sfw:!0,weapon:!0},{id:`rocket`,label:`Roof rockets`,keys:[`4`],description:`Launch, then repeat while held`,sfw:!1,weapon:!0},{id:`ghost`,label:`Ghost mode`,keys:[`5`],description:`Phase while held`,sfw:!0,weapon:!1},{id:`attractor`,label:`Attractor`,keys:[`6`],description:`Pull nearby letters and debris`,sfw:!0,weapon:!1},{id:`lightning`,label:`Lightning`,keys:[`7`],description:`Hold to charge; discharge when the reserve empties`,sfw:!0,weapon:!0}];function so(e,t=!0,n=pn){return oo.filter(n=>e.includes(n.id)&&(t||!n.weapon)).map(e=>({...e,keys:[...e.id===`boost`?[`Shift`]:[],...un.filter(t=>{let r=n[t];return r&&r.action===e.id}).map(String)]}))}var co=oo.map(e=>e.id);function lo(e,t=co,n=!0){let r=e;for(let i of oo)(!t.includes(i.id)||!n&&i.weapon)&&(r===e&&(r={...e}),r[i.id]=!1);return r.ghost&&(r===e&&(r={...e}),r.boost=r.eject=r.machineGun=r.flamethrower=r.rocket=r.attractor=r.lightning=!1),r}var uo=e=>({...e,slots:e.slots?[...e.slots]:void 0,slotPresses:e.slotPresses?[...e.slotPresses]:void 0}),fo=ya({types:{events:{}}}).createMachine({id:`vehicleLifecycle`,initial:`drivable`,states:{drivable:{on:{DESTROYED:`destroyed`}},destroyed:{on:{RESPAWNED:`drivable`}}}}),po=class{id;sim;damage=new xa;weapons=new no;weaponReserves=new ao;tirePaint=new Pa;lifecycle=Sr(fo).start();controls={throttle:0,steer:0,action:!1};controlSource=`player`;label=``;appearance=`auto`;slotConfiguration=pn;slotHeld=new Set;slotPulses=new Set;slotPresses=new Set;disposed=!1;previousSlotInput=new Set;activeEmitters=[];get slots(){return this.slotConfiguration}set slots(e){if(this.disposed)throw Error(`Vehicle is disposed.`);let t=yn(e);for(let e of un)JSON.stringify(t[e])!==JSON.stringify(this.slotConfiguration[e])&&(this.slotHeld.delete(e),this.slotPulses.delete(e),this.slotPresses.delete(e),this.previousSlotInput.delete(e));this.slotConfiguration=t,this.activeEmitters=[]}liquidEmissions(e){return!this.sim.lastInput.eject||this.isGhost||this.lifecycleState!==`drivable`?[]:this.activeEmitters.map(({slot:t,liquid:n,pulse:r,rate:i,amount:a})=>({slot:t,liquid:n,amount:(r?a:Math.max(0,e)*i)*this.weaponReserves.consumptionScale(`eject`)})).filter(e=>e.amount>0)}useSlot(e){let t=mn(e);return this.disposed||!this.slotConfiguration[t]||this.lifecycleState!==`drivable`?!1:(this.slotPulses.add(t),!0)}startSlot(e){let t=mn(e);return this.disposed||!this.slotConfiguration[t]||this.lifecycleState!==`drivable`?!1:(this.slotHeld.has(t)||this.slotPresses.add(t),this.slotHeld.add(t),!0)}stopSlot(e){this.slotHeld.delete(mn(e))}clearSlotInput(){this.slotHeld.clear(),this.slotPulses.clear(),this.slotPresses.clear(),this.previousSlotInput.clear(),this.activeEmitters=[]}resolveSlots(e){let t=new Set([...this.slotHeld,...(e.slots??[]).map(mn)]),n=new Set([...this.slotPresses,...(e.slotPresses??[]).map(mn)]),r=uo(e);this.activeEmitters=[];for(let e of un){let i=this.slotConfiguration[e];if(!i)continue;let a=t.has(e)&&!this.previousSlotInput.has(e),o=this.slotPulses.has(e)||(i.activation===`tap`?a||n.has(e):n.has(e)&&!t.has(e));(o||i.activation!==`tap`&&t.has(e))&&(i.action===`eject`?(r.eject=!0,this.activeEmitters.push({slot:e,liquid:i.liquid,pulse:o,rate:i.rate??6,amount:i.amount??.65})):r[i.action]=!0)}if(e.eject&&!this.activeEmitters.length)for(let e of un){let t=this.slotConfiguration[e];if(t&&t.action===`eject`){this.activeEmitters.push({slot:e,liquid:t.liquid,pulse:!1,rate:t.rate??6,amount:t.amount??.65});break}}return this.previousSlotInput=t,r}tourCommands;constructor(e,t){this.id=e,this.sim=t}get lifecycleState(){return this.lifecycle.getSnapshot().value}get isGhost(){return this.sim.mode===`car`&&this.lifecycleState===`drivable`&&!!this.controls.ghost}bindTourCommands(e){this.tourCommands=e}driveTo(e,t){return this.tour([e],t)}tour(e,t){return this.tourCommands?.start(e,t)??!1}stopTour(){return this.tourCommands?.stop()??!1}setControls(e,t,n={}){this.controls=lo(this.resolveSlots(e),n.enabledTools,n.weaponsEnabled),this.controlSource=t}step(e,t,n=!1){n?(this.weaponReserves.step({throttle:0,steer:0,action:!1},e,this.sim.car.preset.driveBoost),this.sim.lastInput={throttle:0,steer:0,action:!1,boost:!1}):this.sim.tick(this.lifecycleState===`drivable`?this.weaponReserves.step(this.controls,e,this.sim.car.preset.driveBoost,{lightning:ro.lightning.capacity/jn(this.sim.car.preset).chargeSeconds,eject:e>0?this.activeEmitters.reduce((t,n)=>t+(n.pulse?n.amount:n.rate*e),0)/(e*6):0}):this.weaponReserves.step({throttle:0,steer:0,action:!1},e,this.sim.car.preset.driveBoost),e,t),this.weapons.lightning.step(e,!n&&!!this.sim.lastInput.lightning&&this.lifecycleState===`drivable`,jn(this.sim.car.preset).chargeSeconds,this.weaponReserves.enabled?this.weaponReserves.fraction(`lightning`):void 0),this.slotPulses.clear(),this.slotPresses.clear()}synchronizeLifecycle(){let e=this.sim.car.explodedAt!==null;e&&this.lifecycleState===`drivable`?(this.lifecycle.send({type:`DESTROYED`}),this.weapons.stopFiring(),this.clearSlotInput(),this.sim.lastInput={throttle:0,steer:0,action:!1,boost:!1}):!e&&this.lifecycleState===`destroyed`&&this.lifecycle.send({type:`RESPAWNED`})}reset(){this.clearSlotInput(),this.sim.reset(),this.damage.reset(),this.weapons.reset(),this.weaponReserves.reset(),this.tirePaint.reset(),this.synchronizeLifecycle()}restoreHealth(){this.sim.car.resetBurnable(),this.synchronizeLifecycle()}setMode(e){this.clearSlotInput(),this.sim.setMode(e),this.damage.reset(),this.weapons.reset(),this.weaponReserves.reset(),this.tirePaint.reset(),this.synchronizeLifecycle()}setPreset(e){this.clearSlotInput(),this.sim.setPreset(e),this.damage.reset(),this.weapons.reset(),this.weaponReserves.reset(),this.tirePaint.reset(),this.synchronizeLifecycle()}advanceBurn(e){if(this.sim.mode!==`car`)return null;let{car:t}=this.sim;t.advanceBurn(e),this.synchronizeLifecycle();let n=t.stage;if(n===`intact`)return null;let r=!1,i=!1;this.lifecycleState===`destroyed`&&(t.blastQueued||(t.blastQueued=!0,r=!0),t.blastAge+=e,t.blastAge<.36&&t.blastAge-t.lastBlastEmission>=1/30&&(i=!0,t.lastBlastEmission=t.blastAge));let a={stage:n,health:t.health,maxHealth:t.maxHealth,key:t,burnOriginLocal:{...t.burnOriginLocal},blastAge:t.blastAge,explosionStarted:r,blastPulse:i};return this.lifecycleState===`destroyed`&&t.blastAge>=kt.respawnSeconds&&(this.sim.resetAtCurrentPose(),this.damage.reset(),this.synchronizeLifecycle()),a}captureState(){return{id:this.id,label:this.label,appearance:this.appearance,slots:structuredClone(this.slots),slotHeld:[...this.slotHeld],slotPulses:[...this.slotPulses],slotPresses:[...this.slotPresses],previousSlotInput:[...this.previousSlotInput],activeEmitters:this.activeEmitters.map(e=>({...e})),simulation:this.sim.captureState(),damage:this.damage.captureState(),weapons:this.weapons.captureState(),weaponReserves:this.weaponReserves.captureState(),tirePaint:this.tirePaint.captureState(),controls:uo(this.controls),controlSource:this.controlSource,lifecycle:this.lifecycle.getPersistedSnapshot()}}restoreState(e){if(e.id!==this.id)throw Error(`Checkpoint vehicle does not match`);this.label=e.label,this.appearance=e.appearance,this.slots=structuredClone(e.slots),this.slotHeld=new Set(e.slotHeld),this.slotPulses=new Set(e.slotPulses),this.slotPresses=new Set(e.slotPresses),this.previousSlotInput=new Set(e.previousSlotInput),this.activeEmitters=e.activeEmitters.map(e=>({...e})),this.sim.restoreState(e.simulation),this.damage.restoreState(e.damage),this.weapons.restoreState(e.weapons),this.weaponReserves.restoreState(e.weaponReserves),this.tirePaint.restoreState(e.tirePaint),this.controls=uo(e.controls),this.controlSource=e.controlSource,this.lifecycle.stop(),this.lifecycle=Sr(fo,{snapshot:e.lifecycle}).start()}dispose(){this.disposed=!0,this.clearSlotInput(),this.lifecycle.stop()}};function mo(e,t,n,r){if(r.width<=0||r.height<=0)return null;let i=0,a=1;for(let o of[`x`,`y`]){let s=t[o]-e[o],c=r[o]-n,l=c+(o===`x`?r.width:r.height)+n*2;if(Math.abs(s)<1e-8){if(e[o]<c||e[o]>l)return null;continue}let u=(c-e[o])/s,d=(l-e[o])/s;if(i=Math.max(i,Math.min(u,d)),a=Math.min(a,Math.max(u,d)),i>a)return null}return i<=1&&a>=0?i:null}var ho=new WeakMap;function go(e){let t=ho.get(e);if(t)return t;let n=[],{columns:r,rows:i,solid:a}=e;for(let e=0;e<i;e++)for(let t=0;t<r;t++){let o=e*r+t;a[o]&&(t!==0&&t!==r-1&&e!==0&&e!==i-1&&a[o-1]&&a[o+1]&&a[o-r]&&a[o+r]||n.push(D(2*(t+.5)/r-1,2*(e+.5)/i-1)))}return ho.set(e,n),n}function _o(e,t){for(let[n,r]of[[e,t],[t,e]]){let e=n.shape;for(let t of go(n.mask.alpha)){let n=O(e.center,O(A(e.forward,t.x*e.halfLength),A(e.side,t.y*e.halfWidth)));if(Qt(r.mask.alpha,r.shape,n))return!0}}return!1}function vo(e,t){let n=k(e.center,t.center),r=1/0,i=D(1);for(let a of[e.forward,e.side,t.forward,t.side]){let o=e.halfLength*Math.abs(j(a,e.forward))+e.halfWidth*Math.abs(j(a,e.side)),s=t.halfLength*Math.abs(j(a,t.forward))+t.halfWidth*Math.abs(j(a,t.side)),c=j(n,a),l=o+s-Math.abs(c);if(l<=0)return null;l<r&&(r=l,i=A(a,c<0?-1:1))}return{normal:i,depth:r}}function yo(e,t,n){let{sim:r}=e,i=t.documentScale(),a=D(Math.cos(r.body.angle),-Math.sin(r.body.angle));return{center:O(t.documentPoint(r.body.position),t.carVisualOffset(r)),forward:a,side:D(-a.y,a.x),halfLength:n.lengthM*i/2,halfWidth:n.widthM*i/2}}function bo(e,t,n,r,i,a){if(e.sim.mode!==`car`||e.sim.car.explodedAt!==null||e.isGhost)return null;let o=yo(e,t,n),s=mo(r,i,a,Jt(n.alpha,o));if(s===null)return null;let c=k(i,r),l=Math.min(256,Math.max(1,Math.ceil(Math.hypot(c.x,c.y)/Math.max(2,a)))),u=Math.max(0,Math.floor(s*l)-1),d=a>0?[D(),D(a,0),D(-a,0),D(0,a),D(0,-a)]:[D()];for(let e=u;e<=l;e++){let t=O(r,A(c,e/l));if(d.some(e=>Qt(n.alpha,o,O(t,e))))return t}return null}function xo(e,t,n,r){if(e.length<2)return;let i=t.documentScale(),a=e.filter(e=>e.sim.mode===`car`&&e.sim.car.explodedAt===null&&!e.isGhost).map(e=>{let r=n(e);return{entity:e,mask:r,shape:yo(e,t,r)}});for(let e=0;e<a.length;e++)for(let n=e+1;n<a.length;n++){let o=a[e],s=a[n],c=vo(o.shape,s.shape);if(!c||!_o(o,s))continue;let l=c.normal,u=D(l.x,-l.y),d=Yt(o.mask.alpha,o.shape,A(l,-1)),f=A(O(d,Yt(s.mask.alpha,s.shape,l)),.5),p=t.worldFromDocument(f),m=o.entity.sim.body,h=s.entity.sim.body,g=o.shape,_=s.shape,v=k(p,m.position),y=k(p,h.position),b=j(k(m.velocityAt(p),h.velocityAt(p)),u),x=1/m.mass,S=1/h.mass,C=x+S,w=(c.depth+.5)/i;if(m.position=O(m.position,A(u,w*x/C)),h.position=k(h.position,A(u,w*S/C)),o.shape={...o.shape,center:O(o.shape.center,A(l,(c.depth+.5)*x/C))},s.shape={...s.shape,center:k(s.shape.center,A(l,(c.depth+.5)*S/C))},b>=0)continue;let ee=zt(v,u),te=zt(y,u),ne=C+ee**2/m.inertia+te**2/h.inertia,re=-(1+(b<-.8?.24:0))*b/ne,ie=A(u,re);m.impulse(ie,p),h.impulse(A(ie,-1),p);let ae=D(-u.y,u.x),oe=k(m.velocityAt(p),h.velocityAt(p)),se=zt(v,ae),ce=zt(y,ae),le=C+se**2/m.inertia+ce**2/h.inertia,ue=A(ae,Math.max(-re*.38,Math.min(re*.38,-j(oe,ae)/le)));m.impulse(ue,p),h.impulse(A(ue,-1),p);let de=-b;de<=.8||(o.entity.sim.car.takeImpact(de,m.local(p)),s.entity.sim.car.takeImpact(de,h.local(p)),o.entity.damage.hit(f,l,g,de,i),s.entity.damage.hit(f,A(l,-1),_,de,i),r?.({speedMps:de,point:f,velocity:A(k(m.velocity,h.velocity),i),normal:l,carNormal:en(o.mask.alpha,g,d),pixelsPerMeter:i}))}}function So(e){if(e.kind===`impact`||e.kind===`scrape`){let{element:t,...n}=e.impact,{element:r,...i}=e;return{...E({...i,impact:n}),element:r,impact:{...E(n),element:t}}}let{element:t,...n}=e;return{...E(n),element:t}}var Co=class{onObserverError;pending=[];listeners=new Set;draining=!1;constructor(e=e=>console.error(`Joy Ride event observer failed.`,e)){this.onObserverError=e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}captureState(){return this.pending.map(So)}restoreState(e){this.pending=e.map(So)}emit(e){this.pending.push(e)}drain(e){if(this.draining||!this.pending.length)return;let t=this.pending;this.pending=[],this.draining=!0;try{for(let n of t){e(n);for(let e of[...this.listeners])if(this.listeners.has(e))try{e(n)}catch(e){try{this.onObserverError(e)}catch(e){console.error(`Joy Ride event observer error reporting failed.`,e)}}}}finally{this.draining=!1}}clear(){this.pending.length=0}},wo=[`vehicle`,`objects`,`weapons`,`controls`,`ai`,`settings`,`embed`,`documentation`],To={showHud:!1,showHealthBars:!0,showWeaponBar:!0,showLogo:!0,showGithub:!0,allowVehicleEditing:!0,vehicleTabs:wo,vehicleDestructible:!0,weaponsEnabled:!0,enabledTools:oo.map(e=>e.id)},Eo={...To,showHud:!1,showHealthBars:!1,showWeaponBar:!1,showLogo:!1,showGithub:!1,allowVehicleEditing:!1,vehicleTabs:[`vehicle`,`weapons`,`controls`],vehicleDestructible:!1,enabledTools:oo.filter(e=>e.sfw).map(e=>e.id),brandColor:`#000000`,brandName:`Vehicle settings`};function Do(e={}){let t={...e.workMode?.sfw?Eo:To};for(let n of[e.workMode,e])if(n)for(let e of Object.keys({...To,brandColor:void 0,brandName:void 0})){let r=n[e];r!==void 0&&Object.assign(t,{[e]:r})}return t.vehicleTabs=[...new Set(t.vehicleTabs)],t.enabledTools=[...new Set(t.enabledTools)],t}function Oo(e){let{ignitionSeconds:t,spreadSeconds:n,spreadRadiusPx:r,burnSeconds:i,smokePerSecond:a}=e;return{ignitionSeconds:t,spreadSeconds:n,spreadRadiusPx:r,burnSeconds:i,smokePerSecond:a}}function ko(e){let t=(...e)=>e.every(Number.isFinite);if(!e||!t(e.point?.x,e.point?.y,e.radiusPx)||e.radiusPx<0||e.spreadSeconds!==void 0&&(!t(e.spreadSeconds)||e.spreadSeconds<0)||e.mask&&(!e.bounds||!(e.mask.alpha instanceof Uint8Array)||!Number.isInteger(e.mask.pixelWidth)||!Number.isInteger(e.mask.pixelHeight)||e.mask.pixelWidth<=0||e.mask.pixelHeight<=0||e.mask.alpha.length!==e.mask.pixelWidth*e.mask.pixelHeight||!t(e.mask.origin?.x,e.mask.origin?.y)||e.mask.frontRadius!==1/0&&(!t(e.mask.frontRadius)||e.mask.frontRadius<0))||e.bounds&&(!t(e.bounds.x,e.bounds.y,e.bounds.width,e.bounds.height)||e.bounds.width<0||e.bounds.height<0))throw Error(`Invalid fire source: expected finite coordinates and nonnegative geometry`);return{...e,point:{...e.point},...e.bounds&&{bounds:{...e.bounds}},...e.profile&&{profile:{...e.profile}},...e.mask&&{mask:{...e.mask,alpha:e.mask.alpha.slice(),origin:{...e.mask.origin}}}}}function Ao(e,t){if(e.mask&&e.bounds)return Po({rect:e.bounds,alpha:e.mask.alpha,pixelWidth:e.mask.pixelWidth,pixelHeight:e.mask.pixelHeight},e.mask.origin,e.mask.frontRadius,t,e.radiusPx);if(e.bounds){let n=e.bounds;return Math.hypot(Math.max(t.x-n.x-n.width,n.x-t.x-t.width,0),Math.max(t.y-n.y-n.height,n.y-t.y-t.height,0))}return Math.hypot(Math.max(t.x-e.point.x,0,e.point.x-t.x-t.width),Math.max(t.y-e.point.y,0,e.point.y-t.y-t.height))}function jo(e,t,n,r){let i=Ao(t,n);return i>t.radiusPx?0:e/Math.max(.01,t.spreadSeconds??r)*(1.5-.5*i/Math.max(t.radiusPx,1))}function Mo(e,t,n=1024){let{x:r,y:i,width:a,height:o}=e,s=Math.max(1,Math.ceil(a/Math.max(1,t))),c=Math.max(1,Math.ceil(o/Math.max(1,t))),l=Math.min(1,Math.sqrt(n/(s*c))),u=Math.min(n,Math.max(1,Math.floor(s*l))),d=Math.min(n,Math.max(1,Math.floor(c*l)));u=Math.min(u,Math.max(1,Math.floor(n/d)));let f=[];for(let e=0;e<d;e++)for(let t=0;t<u;t++)f.push({x:r+(t+.5)*a/u,y:i+(e+.5)*o/d});return f}function No(e,t){if(!e.bounds)return[e.point];let n=e.bounds,r=e.radiusPx,i=t?{x:Math.max(n.x,t.x-r),y:Math.max(n.y,t.y-r),width:Math.min(n.x+n.width,t.x+t.width+r)-Math.max(n.x,t.x-r),height:Math.min(n.y+n.height,t.y+t.height+r)-Math.max(n.y,t.y-r)}:n;return i.width<=0||i.height<=0?[]:Mo(i,Math.max(1,e.radiusPx)).filter(t=>!e.mask||Ao({...e,radiusPx:0},{...t,width:0,height:0})===0)}function Po(e,t,n,r,i){let{rect:a,alpha:o,pixelWidth:s,pixelHeight:c}=e;if(a.width<=0||a.height<=0)return 1/0;let l=Math.max(0,Math.floor((r.x-i-a.x)/a.width*s)),u=Math.min(s-1,Math.floor((r.x+r.width+i-a.x)/a.width*s)),d=Math.max(0,Math.floor((r.y-i-a.y)/a.height*c)),f=Math.min(c-1,Math.floor((r.y+r.height+i-a.y)/a.height*c)),p=1/0;for(let e=d;e<=f;e++)for(let i=l;i<=u;i++){if(o[e*s+i]<=32)continue;let l={x:a.x+i*a.width/s,y:a.y+e*a.height/c,width:a.width/s,height:a.height/c};Math.hypot(l.x+l.width/2-t.x,l.y+l.height/2-t.y)>n||(p=Math.min(p,Math.hypot(Math.max(r.x-l.x-l.width,l.x-r.x-r.width,0),Math.max(r.y-l.y-l.height,l.y-r.y-r.height,0))))}return p}var Fo=new WeakMap;function Io(e,t){let{rect:n,alpha:r,pixelWidth:i,pixelHeight:a}=e,o=t.spreadRadiusPx,s=Fo.get(e);if(!s||s.alpha!==r||s.width!==n.width||s.height!==n.height||s.pixelWidth!==i||s.pixelHeight!==a||s.radius!==o){let t=Math.max(1,o*.75),c=Math.max(1,Math.ceil(n.width/t)),l=Math.max(1,Math.ceil(n.height/t)),u=Array(c*l),d=(e,r)=>{let i=Math.min(c-1,Math.floor(e/t)),a=Math.min(l-1,Math.floor(r/t)),o=a*c+i,s=(i+.5)*n.width/c,d=(a+.5)*n.height/l,f=(e-s)**2+(r-d)**2;(!u[o]||f<u[o].distance)&&(u[o]={x:e,y:r,distance:f})};for(let e=0;e<l;e++)for(let t=0;t<c;t++){let o=(t+.5)*n.width/c,s=(e+.5)*n.height/l,u=Math.min(i-1,Math.floor(o/n.width*i));r[Math.min(a-1,Math.floor(s/n.height*a))*i+u]>32&&d(o,s)}for(let e=0;e<a;e++)for(let t=0;t<i;t++)r[e*i+t]<=32||d((t+.5)*n.width/i,(e+.5)*n.height/a);s={alpha:r,width:n.width,height:n.height,pixelWidth:i,pixelHeight:a,radius:o,points:u.filter(e=>e!==void 0).map(({x:e,y:t})=>({x:e,y:t}))},Fo.set(e,s)}return s.points.map(e=>({point:{x:n.x+e.x,y:n.y+e.y},radiusPx:o,spreadSeconds:t.spreadSeconds,profile:t}))}var Lo=.15,Ro=class{renderer;id=`liquid`;sampleIntervalSeconds=Lo;receivesOwnSources=!1;elapsed=0;constructor(e){this.renderer=e}sources(){return this.renderer.burningLiquidSources?.()??[]}expose(e,t){e.length?(this.elapsed+=t,!(this.elapsed<Lo)&&(this.renderer.igniteLiquidsFromFire?.(e),this.elapsed%=Lo)):this.elapsed=0}captureState(){return this.elapsed}restoreState(e){if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw Error(`Invalid liquid heat checkpoint`);this.elapsed=e}reset(){this.elapsed=0}},zo=class{domains;conductiveDomains;heatClocks=new Map;constructor(e,t){this.domains=[{id:`scene`,sampleIntervalSeconds:1/15,canReceive:()=>e.hasFireTargets?.()??!0,receivesOwnSources:!0,sources:()=>e.burningFireSources?.()??[],expose:(t,n)=>e.exposeToFire?.(t,n)},new Ro(t)],this.conductiveDomains=[{id:`liquid`,conduct:(e,n)=>t.hasConductiveLiquidNear?.(e,n)===!1?null:t.conductLightning?.(e,n)??null,ignite:(e,n)=>t.igniteConductedLiquids?.(e,n)}]}registerHeatDomain(e){if(this.domains.some(t=>t.id===e.id))throw Error(`Heat domain already registered: ${e.id}`);if(!!e.captureState!=!!e.restoreState)throw Error(`Heat domain checkpoint methods must be paired: ${e.id}`);return this.domains.push(e),this.heatClocks.set(e.id,0),()=>{let t=this.domains.indexOf(e);t>=0&&this.domains.splice(t,1),this.heatClocks.delete(e.id)}}registerConductiveDomain(e){if(this.conductiveDomains.some(t=>t.id===e.id))throw Error(`Conductive domain already registered: ${e.id}`);if(!!e.captureState!=!!e.restoreState)throw Error(`Conductive domain checkpoint methods must be paired: ${e.id}`);return this.conductiveDomains.push(e),()=>{let t=this.conductiveDomains.indexOf(e);t>=0&&this.conductiveDomains.splice(t,1)}}captureState(){let e=e=>e.map(e=>({id:e.id,state:E(e.captureState?.())}));return{heat:e(this.domains),heatClocks:this.domains.map(e=>({id:e.id,elapsed:this.heatClocks.get(e.id)??0})),conductive:e(this.conductiveDomains)}}validateState(e){let t=(e,t)=>e.length===t.length&&e.every((e,n)=>e.id===t[n].id);if(!t(e.heat,this.domains)||!t(e.heatClocks,this.domains)||!t(e.conductive,this.conductiveDomains))throw Error(`Material domain registry changed since the checkpoint`)}restoreState(e){this.validateState(e),this.domains.forEach((t,n)=>t.restoreState?.(E(e.heat[n].state))),this.heatClocks.clear();for(let{id:t,elapsed:n}of e.heatClocks)this.heatClocks.set(t,n);this.conductiveDomains.forEach((t,n)=>t.restoreState?.(E(e.conductive[n].state)))}reset(){this.heatClocks.clear();for(let e of this.domains)e.reset?.();for(let e of this.conductiveDomains)e.reset?.()}conduct(e,t){let n=[],r=new Set(e.map(e=>`${e.x}:${e.y}`)),i=new Set,a=e.map(e=>({point:e,origin:null,owner:null}));for(let e=0;e<8&&a.length;e++){let e=[];for(let o of this.conductiveDomains){let s=a.filter(e=>e.origin!==o.id);if(!s.length)continue;let c=o.conduct(s.map(e=>e.point),t);if(!c?.points.length)continue;let l=s.filter(e=>c.contains(e.point,t)),u={path:c,bridges:(l.length?l:s).map(({point:e,owner:t})=>({point:e,owner:t}))},d=!1;for(let t of c.points){let n=`${t.x}:${t.y}`;r.has(n)||(r.add(n),e.push({point:t,origin:o.id,owner:u}),d=!0)}(d||!i.has(o.id))&&n.push(u),i.add(o.id)}a=e}return{points:n.flatMap(({path:e})=>e.points),contains:(e,t=0)=>n.some(({path:n})=>n.contains(e,t)),intersects:(e,t=0)=>n.some(({path:n})=>n.intersects(e,t)),pathTo:(t,r=0)=>{let i=n.map(e=>({entry:e,local:e.path.pathTo(t,r)})).filter(({local:e})=>e.length).sort((e,n)=>{let r=e.local[e.local.length-1],i=n.local[n.local.length-1];return Math.hypot(r.x-t.x,r.y-t.y)-Math.hypot(i.x-t.x,i.y-t.y)})[0];if(!i)return[];let a=[...i.local],o=i.entry;for(;;){let e=o.bridges.filter(e=>e.owner).sort((e,t)=>Math.hypot(e.point.x-a[0].x,e.point.y-a[0].y)-Math.hypot(t.point.x-a[0].x,t.point.y-a[0].y))[0];if(!e?.owner)break;let t=e.owner.path.pathTo(e.point,r);(!a.length||Math.hypot(a[0].x-e.point.x,a[0].y-e.point.y)>1e-6)&&a.unshift(e.point),a=[...t,...a],o=e.owner}let s=e.reduce((e,t)=>!e||Math.hypot(t.x-a[0].x,t.y-a[0].y)<Math.hypot(e.x-a[0].x,e.y-a[0].y)?t:e,null);return s&&Math.hypot(s.x-a[0].x,s.y-a[0].y)>1e-6&&a.unshift(s),a.filter((e,t)=>t===0||Math.hypot(e.x-a[t-1].x,e.y-a[t-1].y)>1e-6)}}}igniteConducted(e,t){for(let n of this.conductiveDomains)n.ignite?.(e,t)}stepFire(e){let t=[...this.domains],n=t.map(t=>{let n=(this.heatClocks.get(t.id)??0)+e,r=t.sampleIntervalSeconds??0;return r>0&&n+1e-9<r?(this.heatClocks.set(t.id,n),0):(this.heatClocks.set(t.id,r>0?n%r:0),n)}),r=n.map((e,n)=>e>0&&t[n].canReceive?.()!==!1);if(!r.some(Boolean))return;let i=t.map((e,n)=>r.some((e,r)=>e&&(r!==n||t[r].receivesOwnSources))?e.sources().map(ko):[]);t.forEach((e,t)=>{if(!r[t])return;let a=i.flatMap((n,r)=>t===r&&!e.receivesOwnSources?[]:n);e.expose(a,n[t])})}},Bo={throttle:0,steer:0,action:!1,boost:!1},Vo=class{world;state;version=3;disposed=!1;constructor(e,t){this.world=e,this.state=t}get available(){return!this.disposed}restore(){this.world.restoreState(this)}dispose(){this.disposed||(this.disposed=!0,this.state.renderer.dispose(),this.world.releaseCheckpoint(this))}},Ho=class{renderer;odometer;sound;overlay;rocketBlastStrength;stateParticipants=new Map;registerStateParticipant(e,t){if(this.stateParticipants.has(e))throw Error(`State participant already registered: ${e}`);return this.stateParticipants.set(e,t),()=>this.stateParticipants.delete(e)}slowMo=new r;events=new Co;vehicleRegistry=new Map;drivers=new Map;driveTasks=new Map;tourFactory=null;driverTargets=new Map;cameraVehicleId=null;collisions;materialInteractions;checkpoints=new Set;flameDamageThisStep=new Map;stepSeconds=1/120;destructionPoints=0;disposed=!1;constructor(e,t,n,r,i,a,o=new sn,s={}){this.renderer=t,this.odometer=n,this.sound=r,this.overlay=i,this.rocketBlastStrength=a;let c=Do(s);this.vehicleDestructible=c.vehicleDestructible,this.weaponsEnabled=c.weaponsEnabled,this.enabledTools=[...c.enabledTools],e&&this.spawnVehicle({id:`player`,sim:e,control:{kind:`player`}}),this.collisions=o,this.materialInteractions=new zo(o,t),o.setEvents(this.events),o.setAutoPaint?.(s.autoPaint??!1)}get playerVehicle(){return[...this.vehicleRegistry.values()].find(e=>!this.drivers.has(e.id))}get focusVehicle(){return this.playerVehicle??this.vehicleRegistry.values().next().value}get primaryVehicle(){let e=this.focusVehicle;if(!e)throw Error(`Game world has no vehicles`);return e}get sim(){return this.primaryVehicle.sim}get damage(){return this.primaryVehicle.damage}getVehicle(e){return this.vehicleRegistry.get(e)}get cameraVehicle(){return this.cameraVehicleId&&this.getVehicle(this.cameraVehicleId)||this.focusVehicle}watchVehicle(e,t=!0){return e!==null&&!this.vehicleRegistry.has(e)?!1:(this.cameraVehicleId=e,t&&(this.renderer.resumeFollow(),this.overlay&&this.cameraVehicle&&this.renderer.followDocument(this.cameraVehicle.sim)),!0)}get companionVehicles(){let e=this.focusVehicle;return[...this.vehicleRegistry.values()].filter(t=>t!==e)}get vehicles(){return[...this.vehicleRegistry.values()]}registerHeatDomain(e){return this.materialInteractions.registerHeatDomain(e)}registerConductiveDomain(e){return this.materialInteractions.registerConductiveDomain(e)}configureVehicle(e,t){let n=this.getVehicle(e);if(!n)return!1;if(t.appearance!==void 0&&![`auto`,`light`,`dark`].includes(t.appearance))throw TypeError(`Unknown vehicle appearance`);let r=t.slots===void 0?void 0:yn(t.slots);return t.control?.kind===`player`&&this.playerVehicle&&this.playerVehicle!==n?!1:(t.preset&&this.collisions.prepare(t.preset),t.control&&this.setVehicleControl(e,t.control),t.preset&&t.preset!==n.sim.car.preset&&n.setPreset(t.preset),t.appearance!==void 0&&(n.appearance=t.appearance),r!==void 0&&(n.slots=r),n===this.focusVehicle&&this.projectFocusVehicle(!!t.preset),!0)}projectedSound;projectedPreset;projectFocusVehicle(e=!1){let t=this.focusVehicle;if(!t)return;let n=this.sound(),r=t.sim.car.preset;(n!==this.projectedSound||r!==this.projectedPreset)&&(n.setPreset(r),this.collisions.prepare(r),this.projectedSound=n,this.projectedPreset=r),e&&this.renderer.resetVehicleDamage()}resetEffects(){this.renderer.reset(),this.materialInteractions.reset()}fadeEffects(){this.materialInteractions.reset(),this.renderer.fadeEffects()}resetScene(){this.destructionPoints=0,this.events.clear(),this.collisions.reset?.(),this.fadeEffects();for(let e of this.vehicleRegistry.values())e.restoreHealth()}deformationEnabled=!0;weaponCooldownEnabled=!0;vehicleDestructible=!0;weaponsEnabled=!0;enabledTools=oo.map(e=>e.id);setEnabledTools(e){this.enabledTools=[...new Set(e)];for(let e of this.vehicleRegistry.values())e.weapons.reset()}setVehicleDestructible(e){this.vehicleDestructible=e;for(let t of this.vehicleRegistry.values())t.sim.car.destructible=e,e||t.restoreHealth()}setWeaponsEnabled(e){if(this.weaponsEnabled=e,!e)for(let e of this.vehicleRegistry.values())e.weapons.reset()}setWeaponCooldownEnabled(e){this.weaponCooldownEnabled=e;for(let t of this.vehicleRegistry.values())e||t.weaponReserves.reset(),t.weaponReserves.enabled=e}setDeformationEnabled(e){this.deformationEnabled=e;for(let t of this.vehicleRegistry.values())t.damage.setEnabled(e)}spawnVehicle({id:e,sim:t,control:n,label:r=``}){if(this.vehicleRegistry.has(e))throw Error(`Vehicle ${e} already exists`);if(n.kind===`player`&&this.playerVehicle)throw Error(`Game world already has a player vehicle`);let i=new po(e,t);return t.car.destructible=this.vehicleDestructible,this.vehicleDestructible||i.restoreHealth(),i.weaponReserves.enabled=this.weaponCooldownEnabled,this.bindTourCommands(i),i.damage.setEnabled(this.deformationEnabled),i.label=r,i.controlSource=n.kind===`player`?`player`:`scripted`,this.vehicleRegistry.set(e,i),n.kind===`ai`&&(this.drivers.set(e,n.driver),n.targetId&&this.driverTargets.set(e,n.targetId)),this.focusVehicle===i&&this.renderer.bindVehicle(i),i}setVehicleControl(e,t){let n=this.vehicleRegistry.get(e);if(!n)return!1;if(t.kind===`player`){let t=this.playerVehicle;if(t&&t!==n)return!1;this.drivers.delete(e),this.driverTargets.delete(e)}else this.drivers.set(e,t.driver),t.targetId&&this.driverTargets.set(e,t.targetId);return n.controlSource=t.kind===`player`?`player`:`scripted`,this.focusVehicle===n&&this.renderer.bindVehicle(n),!0}removeVehicle(e){let t=this.vehicleRegistry.get(e);if(!t)return!1;this.stopVehicleTour(e),t.bindTourCommands(void 0),this.drivers.delete(e),this.driverTargets.delete(e),this.vehicleRegistry.delete(e),this.cameraVehicleId===e&&(this.cameraVehicleId=null),this.collisions.forgetVehicle(e),this.renderer.forgetVehicle(e),t.dispose();let n=this.focusVehicle;return n&&this.renderer.bindVehicle(n),!0}setVehicleTarget(e,t){return this.drivers.has(e)?(t?this.driverTargets.set(e,t):this.driverTargets.delete(e),!0):!1}getVehicleTarget(e){if(!this.drivers.has(e))return null;let t=this.driverTargets.get(e),n=t?this.vehicleRegistry.get(t)??null:this.vehicleRegistry.get(e)===this.focusVehicle?null:this.focusVehicle??null;return n?.id===e?null:n}bindTourCommands(e){e.bindTourCommands(this.tourFactory?{start:(t,n)=>this.startVehicleTour(e.id,t,n),stop:()=>this.stopVehicleTour(e.id)}:void 0)}setVehicleTourFactory(e){this.tourFactory=e;for(let e of this.vehicleRegistry.values())this.bindTourCommands(e)}startVehicleTour(e,t,n){let r=this.vehicleRegistry.get(e);if(!r||!this.tourFactory||!t.length)return!1;let i=this.tourFactory(r,t,n);return i?(this.stopVehicleTour(e),i.activate?.(),this.driveTasks.set(e,i),!0):!1}stopVehicleTour(e){let t=this.driveTasks.get(e);return t?(this.driveTasks.delete(e),t.cancel(),!0):!1}getVehicleTour(e){return this.driveTasks.get(e)??null}consumeEvent=e=>{let t=this.sound();switch(e.kind){case`impact`:t.playCrash(e.impact.speedMps),this.renderer.emitSparks(e.impact),this.renderer.emitCrashShake(e.impact.speedMps);break;case`scrape`:this.renderer.emitSparks(e.impact);break;case`crush`:t.playCrush(),this.awardPoints(e.point,e.points);break;case`combustionExplosion`:this.awardPoints(e.point,e.points),t.playCombustibleExplosion(this.overlay?Be(e.point,this.renderer.sceneScroll(),this.renderer.viewportSize()):1);break;case`destructibleDestroyed`:this.awardPoints(e.point,e.points)}};awardPoints(e,t){t<=0||(this.destructionPoints+=t,this.renderer.emitPoints(e,t))}get points(){return this.destructionPoints}get totalPoints(){return this.collisions.totalPoints}vehicleProjectileHit(e,t,n,r){let i=null;for(let a of this.vehicleRegistry.values()){if(a===e)continue;let o=bo(a,this.renderer,this.collisions.vehicleMask(a.sim.car.preset,a.damage),t,n,r);if(!o)continue;let s=M(k(o,t));(!i||s<i.distance)&&(i={vehicle:a,point:o,distance:s})}return i}nearestProjectileTarget(e,t,n,r){let i=this.vehicleProjectileHit(e,t,n,r),a=this.collisions.projectileHit(t,n,r);return i&&(!a||i.distance<M(k(a.point,t)))?{vehicle:i.vehicle,point:i.point,object:null}:a?{vehicle:null,point:a.point,object:a}:null}rocketCollision=(e,t,n,r)=>{this.collisions.setSourceVehicle?.(e.id);let i=this.rocketBlastStrength(),a=this.nearestProjectileTarget(e,t,n,r);if(!a)return null;let o=a.vehicle?a.point:this.collisions.rocketImpact(t,n,r,i,a.object??void 0);if(o){let r=In(i),s=r.radiusPx;a.vehicle&&this.collisions.applyAreaImpact?.(o,r),r.ignite&&this.renderer.igniteLiquidAt?.(o,this.renderer.documentScale()*2.2);for(let t of this.vehicleRegistry.values()){if(t===e||t.sim.car.explodedAt!==null||t.isGhost)continue;let n=M(k(this.renderer.documentPoint(t.sim.body.position),o)),i=t===a.vehicle;if(!i&&n>s)continue;let c=i?1:Math.max(.2,1-n/s*.7);t.sim.car.damage(It(`rocket`,e.sim.car.preset)*c*r.damage/100),t.synchronizeLifecycle()}this.renderer.emitRocketExplosionShake(i),this.renderer.emitRocketExplosion(o,k(n,t),i)}return o};bulletCollision=(e,t,n,r)=>{this.collisions.setSourceVehicle?.(e.id);let i=this.nearestProjectileTarget(e,t,n,r);return i?i.vehicle?(i.vehicle.sim.car.damage(It(`bullet`,e.sim.car.preset)),i.vehicle.synchronizeLifecycle(),i.point):this.collisions.bulletImpact(t,n,r,i.object??void 0):null};stepLightning(){let{renderer:e,collisions:t}=this,n=e.documentScale();for(let r of this.vehicleRegistry.values()){let i=r.weapons.lightning,a=i.takeDischarge();if(!i.charging&&!a||r.sim.mode!==`car`||r.isGhost||r.lifecycleState!==`drivable`)continue;let o=jn(r.sim.car.preset),s=e.documentPoint(r.sim.body.position),c=Mn(r.sim.car.preset,e.viewportSize?.().width,n)*n,l=[...this.vehicleRegistry.values()].filter(e=>e!==r&&e.sim.mode===`car`&&!e.isGhost&&e.lifecycleState===`drivable`),u=[...t.arcTargets?.(s,c)??[],...l.map(t=>({key:t,point:e.documentPoint(t.sim.body.position)}))].map(e=>({...e,distance:M(k(e.point,s)),score:Nn(s,e.point,r.sim.body.angle,o.forwardBias)})).filter(e=>e.distance<=c).sort((e,t)=>e.score-t.score||e.distance-t.distance)[0];if(i.target=u?{...u.point}:null,!a)continue;let d=o.impactRadiusM*n,f={radiusPx:d,coreRadiusPx:d*.35,damage:o.damage,impulse:o.impulse,ignite:o.ignite},p=new Set,m=[],h=[],g=(e,t)=>{if(e.length<2||h.length>=8)return;let n=Math.max(1,Math.ceil(e.length/24)),r=e.filter((e,t)=>t%n===0);t?r.push(t):r.push(e[e.length-1]),h.push(r)},_=(n,i=!0)=>{t.setSourceVehicle?.(r.id);let a=k(n,s),c=M(a);t.applyAreaImpact?.(n,{...f,impulseDirection:c>.001?{x:a.x/c,y:a.y/c}:{x:Math.cos(r.sim.body.angle),y:-Math.sin(r.sim.body.angle)}},p),o.ignite&&e.igniteLiquidAt?.(n,d),i&&m.push({...n})};u&&_(u.point);let v=this.materialInteractions.conduct(u?[s,u.point]:[s],n*.4);if(v?.points.length){o.ignite&&this.materialInteractions.igniteConducted(v.points,n*.7);let e=c;for(let t of v.points)e=Math.max(e,M(k(t,s))+n);for(let r of t.arcTargets?.(s,e)??[]){let e=r.bounds&&v.intersects?v.intersects(r.bounds,n*.7):v.contains(r.point,n*.7);if(p.has(r.key)||!e)continue;_(r.point,!1);let t=r.bounds;if(g(v.pathTo(t?{x:t.x+t.width/2,y:t.y+t.height/2}:r.point,t?Math.hypot(t.width,t.height)/2+n*.7:n*.7),r.point),p.size>=64)break}h.length||g(v.pathTo(v.points[v.points.length-1]))}for(let t of l){let r=e.documentPoint(t.sim.body.position);if(M(k(r,s))>c&&!v?.contains(r,n*(.7+t.sim.car.preset.geometry.widthM*.5)))continue;let i=t.sim.car.statusEffects;i.remaining(`electrified`)<=0&&(t.sim.body.velocity.x*=o.speedFactor,t.sim.body.velocity.y*=o.speedFactor),i.apply(`electrified`,{lifetime:{unit:`seconds`,amount:o.statusSeconds},modifiers:{speed:o.speedFactor,driveForce:o.speedFactor},intensity:`constant`}),M(k(r,s))<=c?m.push(r):v&&g(v.pathTo(r,n*(.7+t.sim.car.preset.geometry.widthM*.5)),r)}i.discharge(m,h),this.sound().playElectricBolt(r===this.focusVehicle?1:.55)}}flameContact=(e,t,n,r,i)=>{this.collisions.setSourceVehicle?.(e.id);let a=this.nearestProjectileTarget(e,t,n,r);if(a?.vehicle){let t=this.flameDamageThisStep.get(a.vehicle.id)??0,n=Math.min(It(`flame`,e.sim.car.preset,i),Math.max(0,Tt.damagePerSecond*this.stepSeconds-t));return a.vehicle.sim.car.damage(n),this.flameDamageThisStep.set(a.vehicle.id,t+n),a.vehicle.synchronizeLifecycle(),a.point}return this.collisions.flameContact(t,n,r,i,Qe(e.sim.car.preset))};gunshot=()=>this.sound().playGunshot();rocketLaunch=e=>this.sound().playRocketLaunch(this.overlay?ze(this.renderer.vehicleViewportPosition(e),this.renderer.viewportSize(),!1):1);rocketImpact=e=>this.sound().playRocketExplosion(this.overlay?ze(this.renderer.vehicleViewportPosition(e),this.renderer.viewportSize(),!1):1);bulletImpact=e=>this.sound().playBulletImpact(this.overlay?ze(this.renderer.vehicleViewportPosition(e),this.renderer.viewportSize(),!1):1);step(e={},t){let n=this.focusVehicle;if(!n)return;this.stepSeconds=t,this.flameDamageThisStep.clear(),performance.now();let{renderer:r,collisions:i}=this,a=n.sim,o=this.playerVehicle,s=this.drivers.size?r.worldFromDocument({x:0,y:0}):null,c=this.drivers.size?1/r.documentScale():0,l=this.drivers.size?{walls:i.wallRects().map(e=>{let t=s.x+e.x*c,n=s.y-e.y*c||0;return{left:t,right:t+e.width*c,bottom:n-e.height*c,top:n}}),vehicles:[...this.vehicleRegistry.values()].map(e=>({id:e.id,position:{...e.sim.body.position},velocity:{...e.sim.body.velocity},radiusM:Math.hypot(e.sim.car.preset.geometry.lengthM,e.sim.car.preset.geometry.widthM)/2}))}:void 0,u={...a.body.position},d=new Map,f={enabledTools:this.enabledTools,weaponsEnabled:this.weaponsEnabled};for(let n of this.vehicleRegistry.values()){d.set(n,{...n.sim.body.position}),n.synchronizeLifecycle(),n===o&&e.userDriven&&e.controls&&(e.controls.throttle!==0||e.controls.steer!==0||e.controls.brake||e.controls.action||e.controls.boost||e.controls.ghost)&&this.stopVehicleTour(n.id);let r=this.driveTasks.get(n.id),i=this.drivers.get(n.id);r?n.setControls(r.next(n,t),`scripted`,f):i?n.setControls(i(this.getVehicleTarget(n.id),n,t,l),`scripted`,f):n.setControls(e.controls??Bo,e.userDriven?`player`:`scripted`,f),n.step(t,n===o?this.sound().rpm:null,n===o&&e.manualMoved),r?.afterPhysics(n,t),r?.complete&&this.driveTasks.delete(n.id)}o&&e.userDriven&&a.mode===`car`&&this.odometer.add(M(k(a.body.position,u)),r.documentScale()),e.afterPhysics?.();let p=this.cameraVehicle?.sim??a,m=this.overlay&&(e.allowFollow?.()??!0)&&M(p.body.velocity)>.1&&r.followDocument(p);if(a.barrier&&!this.overlay){let e={...a.body.velocity};a.contain(r.bounds());let t=M(k(e,a.body.velocity));a.mode===`car`&&a.car.takeImpact(t),this.sound().playCrash(t),r.emitCrashShake(t)}performance.now(),i.beginStep(r,t),performance.now();for(let e of this.vehicleRegistry.values()){let n=e.advanceBurn(t);if(n){let a=r.emitVehicleBurn(e,n,i.vehicleMask(e.sim.car.preset,e.damage),t);a&&this.events.emit({kind:`combustionExplosion`,point:a,points:0})}let a=d.get(e)??e.sim.body.position,o=k({...e.sim.body.position},a),s=Math.max(.25,e.sim.car.preset.geometry.widthM*.35),c=Math.min(16,Math.max(1,Math.ceil(M(o)/s)));c>1&&(e.sim.body.position={...a});for(let t=1;t<=c;t++){let n={x:a.x+o.x*t/c,y:a.y+o.y*t/c};if(e.sim.body.position={...n},i.stepVehicle(e.sim,r,e===this.cameraVehicle&&e.sim.barrier&&m,e.damage,e.id,e.isGhost),M(k(e.sim.body.position,n))>.02)break}e.synchronizeLifecycle()}let h=a.mode===`car`&&a.car.explodedAt===null&&n.controls.attractor&&!n.isGhost?{center:r.documentPoint(a.body.position),velocity:{x:a.body.velocity.x*r.documentScale(),y:-a.body.velocity.y*r.documentScale()},radiusPx:7*r.documentScale()}:null;if(i.endStep(t,h),performance.now(),this.vehicleRegistry.size>1){xo(this.vehicles,r,e=>i.vehicleMask(e.sim.car.preset,e.damage),e=>this.events.emit({kind:`impact`,impact:e}));for(let e of this.vehicleRegistry.values())e.synchronizeLifecycle()}this.stepLightning(),this.events.drain(this.consumeEvent),performance.now(),i.stepElementLiquids?.(r,e.manualMoved?this.companionVehicles:[n,...this.companionVehicles],t),r.advanceEffects(n,t,{walls:i.wallRects(),carMask:i.vehicleMask(a.car.preset,n.damage),tirePaintSources:e=>i.tirePaintAt(e),driven:!e.manualMoved,rocketCollision:this.rocketCollision,bulletCollision:this.bulletCollision,onGunshot:this.gunshot,flameContact:this.flameContact,onRocketLaunch:this.rocketLaunch,onRocketImpact:this.rocketImpact,onBulletImpact:this.bulletImpact,maskFor:e=>i.vehicleMask(e.sim.car.preset,e.damage),companions:this.companionVehicles}),performance.now(),this.materialInteractions.stepFire(t);let g=r.rocketFlightPosition,_=this.sound();_.setRocketFlightProximity(g?this.overlay?ze(r.vehicleViewportPosition(g),r.viewportSize(),!1):1:0),_.setBurningFireProximity(Math.max(i.burningProximity(r.documentPoint(a.body.position)),a.mode===`car`&&a.car.explodedAt===null?Ft(a.car.health,a.car.maxHealth):0)),this.events.drain(this.consumeEvent)}advanceTime(e){let t=this.slowMo.advance(e);return this.renderer.setSlowMoZoom(this.slowMo.zoomFactor),this.sound().setTimeScale?.(this.slowMo.speedFactor),t}present(e,t,n,r,i,a,o){let s=this.focusVehicle;if(!s)return;let{renderer:c}=this,l=s.sim;this.projectFocusVehicle();let u=this.playerVehicle?{...n,boost:l.lastInput.boost}:{...s.controls,boost:l.lastInput.boost};if(!document.hidden){let e=this.sound(),n=l.paused?0:M(l.body.velocity),o=l.mode===`car`&&!l.paused&&!s.isGhost?Ie(l,l.lastInput.action):[];e.setActive(l.mode===`car`&&i),s.isGhost&&e.silenceTires(),e.setGhostMode(!l.paused&&s.isGhost),e.setAttractor(!l.paused&&!!s.controls.attractor&&!s.isGhost);let d=0;!l.paused&&!s.isGhost&&(s.weapons.lightning.charging?d=.3+s.weapons.lightning.charge*.7:l.car.statusEffects.remaining(`electrified`)>0&&(d=.35)),e.setElectricCharge(d),e.setFlamethrowerFiring(!l.paused&&c.flamethrowerFiring),e.setBoosting(!l.paused&&l.car.boostActive);let f=u.throttle!==0||u.steer!==0||u.action||r;e.setProximity(this.overlay?ze(c.vehicleViewportPosition(l.body.position),c.viewportSize(),f):1),e.setMasterVolume(Re(a)),performance.now(),e.update(t*this.slowMo.speedFactor,u,n,0,0,l.mode===`car`?l.car.boostCharge:0,o);let p=e.takeExhaustPops();!l.paused&&l.mode===`car`&&c.queueExhaustPops(p)}c.render(s,e,o,this.collisions,this.companionVehicles)}snapshot(){let{sim:e}=this;return{mode:e.mode,presetId:e.car.preset.id,position:{...e.body.position},speed:M(e.body.velocity),angle:e.body.angle,spin:e.body.spin,paused:e.paused,health:e.car.health,maxHealth:e.car.maxHealth,burnStage:e.car.stage,points:this.destructionPoints}}saveState(){if(this.disposed)throw Error(`Game world has been disposed`);let e=[...this.vehicleRegistry.values()].map(e=>e.captureState()),t=this.collisions.captureState(),n=this.odometer.captureState(),r=this.events.captureState(),i=this.renderer.captureState(),a;try{a=new Vo(this,{extensions:new Map([...this.stateParticipants].map(([e,t])=>[e,E(t.captureState())])),vehicles:e,drivers:new Map(this.drivers),driveTasks:new Map(this.driveTasks),driveTaskStates:new Map([...this.driveTasks].map(([e,t])=>[e,E(t.captureState())])),driverStates:new Map([...this.drivers].flatMap(([e,t])=>t.captureState?[[e,E(t.captureState())]]:[])),driverTargets:new Map(this.driverTargets),cameraVehicleId:this.cameraVehicleId,deformationEnabled:this.deformationEnabled,weaponCooldownEnabled:this.weaponCooldownEnabled,vehicleDestructible:this.vehicleDestructible,weaponsEnabled:this.weaponsEnabled,enabledTools:[...this.enabledTools],slowMo:this.slowMo.captureState(),collisions:t,odometer:n,events:r,points:this.destructionPoints,renderer:i,materialInteractions:this.materialInteractions.captureState()})}catch(e){throw i.dispose(),e}return this.checkpoints.add(a),a}restoreState(e){if(this.disposed||e.world!==this||!e.available)throw Error(`Checkpoint is unavailable for this game world`);let t=e.state;if(t.vehicles.length!==this.vehicleRegistry.size||t.vehicles.some(e=>!this.vehicleRegistry.has(e.id)))throw Error(`Checkpoint vehicle registry does not match`);this.materialInteractions.validateState(t.materialInteractions),this.drivers.clear(),this.driveTasks.clear(),this.driverTargets.clear(),this.deformationEnabled=t.deformationEnabled,this.weaponCooldownEnabled=t.weaponCooldownEnabled,this.vehicleDestructible=t.vehicleDestructible,this.weaponsEnabled=t.weaponsEnabled,this.enabledTools=[...t.enabledTools],this.slowMo.restoreState(t.slowMo),this.sound().setTimeScale?.(this.slowMo.speedFactor),this.destructionPoints=t.points,this.cameraVehicleId=t.cameraVehicleId;for(let[e,n]of t.drivers)this.drivers.set(e,n);for(let[e,n]of t.driveTasks)this.driveTasks.set(e,n);for(let[e,n]of t.driveTaskStates)this.driveTasks.get(e)?.restoreState(E(n));for(let[e,n]of t.driverStates)this.drivers.get(e)?.restoreState?.(E(n));for(let[e,n]of t.driverTargets)this.driverTargets.set(e,n);let n=this.focusVehicle;n&&this.renderer.bindVehicle(n),this.renderer.restoreState(t.renderer),this.materialInteractions.restoreState(t.materialInteractions);for(let e of t.vehicles){let t=this.vehicleRegistry.get(e.id);if(!t)throw Error(`Checkpoint vehicle is unavailable`);t.restoreState(e)}n&&this.collisions.prepare(n.sim.car.preset),this.collisions.restoreState(t.collisions),this.odometer.restoreState(t.odometer),this.events.restoreState(t.events);for(let[e,n]of t.extensions){let t=this.stateParticipants.get(e);if(!t)throw Error(`Checkpoint state participant is unavailable: ${e}`);t.restoreState(E(n))}}releaseCheckpoint(e){this.checkpoints.delete(e)}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.checkpoints])e.dispose();this.slowMo.reset(),this.sound().setTimeScale?.(1),this.events.clear(),this.collisions.destroy(),this.renderer.dispose();for(let e of this.vehicleRegistry.values())e.dispose();this.vehicleRegistry.clear(),this.drivers.clear(),this.driveTasks.clear(),this.stateParticipants.clear()}}},Uo=null,Wo=()=>{Uo&&(Uo=null,window.removeEventListener(`scroll`,Wo))};function Go(){if(Uo)return Uo;let e={x:window.scrollX,y:window.scrollY};return typeof window.addEventListener==`function`?(window.addEventListener(`scroll`,Wo,{passive:!0}),Uo=e):e}var Ko=Wo,qo=class{frameStart=null;lastFrame=null;frames=0;fps=0;sample(e){if(!Number.isFinite(e))return this.fps;if(this.frameStart===null||this.lastFrame===null||e-this.lastFrame>1e3||e<=this.lastFrame)return this.frameStart=e,this.lastFrame=e,this.frames=0,this.fps=0,this.fps;this.frames++,this.lastFrame=e;let t=e-this.frameStart;return t>=500&&(this.fps=this.frames*1e3/t,this.frameStart=e,this.frames=0),this.fps}reset(){this.frameStart=null,this.lastFrame=null,this.frames=0,this.fps=0}captureState(){return{frameStart:this.frameStart,lastFrame:this.lastFrame,frames:this.frames,fps:this.fps}}restoreState(e){this.frameStart=e.frameStart,this.lastFrame=e.lastFrame,this.frames=e.frames,this.fps=e.fps}},Jo=class extends Error{path;code=`JR_INVALID_CONFIGURATION`;constructor(e,t){super(`${e}: ${t}`),this.path=e,this.name=`PlaygroundConfigurationError`}},F=(e,t)=>{throw new Jo(e,t)},Yo=(e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))return F(t,`expected an option object`);let n=Object.getPrototypeOf(e),r=n&&Object.getOwnPropertyDescriptor(n,`constructor`)?.value;return n!==null&&(Object.getPrototypeOf(n)!==null||typeof r!=`function`||Function.prototype.toString.call(r)!==Function.prototype.toString.call(Object))?F(t,`expected an option object`):e},Xo=(e,t)=>Object.hasOwn(e,t)&&e[t]!==void 0,Zo=e=>e!==void 0&&e!==!1,Qo=(e,t,n)=>{for(let r of Object.keys(e))t.includes(r)||F(`${n}.${r}`,`unknown option`)},$o=(e,t)=>(typeof e==`string`&&e.trim()||F(t,`expected a non-empty string`),e),es=(e,t)=>{typeof e!=`boolean`&&F(t,`expected true or false`)},ts=(e,t,n=0,r=1/0,i=!1)=>{(typeof e!=`number`||!Number.isFinite(e)||(i?e<=n:e<n)||e>r)&&F(t,`expected a finite number ${i?`greater than`:`at least`} ${n}${r<1/0?` and at most ${r}`:``}`)},ns=(e,t,n)=>{typeof e==`string`&&t.includes(e)||F(n,`expected ${t.join(`, `)}`)},rs=(e,t,n=!1)=>{n&&e===`auto`||typeof e==`string`&&/^#[\da-f]{6}$/i.test(e)||Array.isArray(e)&&e.length===3&&e.every(e=>typeof e==`number`&&Number.isFinite(e)&&e>=0&&e<=255)||F(t,`expected a six-digit hex color or RGB tuple`)},is=(e,t,n)=>{Qo(e,Object.keys(t),n);for(let[r,i]of Object.entries(t))Xo(e,r)&&i(e[r],`${n}.${r}`)},as=(e,t)=>ts(e,t,0,1/0,!0),os=(e,t)=>ts(e,t,0,1),ss=(e,t)=>ts(e,t),cs=(e,t)=>ns(e,[`auto`,`light`,`dark`],t),ls=(e,t,n)=>{typeof e!=`boolean`&&is(Yo(e,t),n,t)};function us(e,t){let n=Math.imul(e^Math.imul(t+13,374761393),668265263);return n=Math.imul(n^n>>>13,1274126177),((n^n>>>16)>>>0)/4294967296}function ds(e,t,n,r){let i=Array.from({length:9},(i,a)=>{let o=a*2.399963+us(r,3)*6.28,s=Math.sqrt(a/9)*n*.45;return{x:e+Math.cos(o)*s,y:t+Math.sin(o)*s*.8,z:0,vx:0,vy:0,vz:0,radius:n*(.29+us(r,a+20)*.13),spread:1,angle:us(r,a+40)*6.28,mass:1/9,seed:r+a*7919|0}}),a=i.reduce((t,n)=>t+n.x-e,0)/i.length,o=i.reduce((e,n)=>e+n.y-t,0)/i.length;for(let e of i)e.x-=a,e.y-=o;return{parcels:i,radius:n}}function fs(e,t,n,r,i){let a=e.dust,o=!1;for(let e of a.parcels){let a=r(e.x,e.y),s=a.x,c=a.y,l=Math.hypot(s-e.vx,c-e.vy),u=e.z>.02||e.vz>0;if(!u&&l<18&&Math.hypot(e.vx,e.vy)<.02){e.vx=e.vy=0;continue}o=!0;let d=1-Math.exp(-e.z/9),f=us(31,73)*6.28,p=e.x/61+n*.35+f,m=e.y/53-n*.22+f,h=e.x/23+e.y/39+n*.8,g=d*Math.min(950,l*8+Math.hypot(e.vx,e.vy)*4);s+=(-Math.sin(p)*Math.sin(m)/53+Math.cos(h)*.3/39)*g,c-=(Math.cos(p)*Math.cos(m)/61+Math.cos(h)*.3/23)*g;let _=15+us(e.seed,5)*9,v=Math.max(0,l-20)*(.85+us(e.seed,7)*.4);(u||v>_)&&(e.vz+=(v/(1+e.z/80)-_-e.vz*1.6)*t),e.vz=Math.min(65,e.vz),e.z=Math.max(0,Math.min(80,e.z+e.vz*t)),e.z===0&&e.vz<0&&(e.vz=0),e.z===80&&(e.vz=Math.min(0,e.vz));let y=e.z>.02?1:Math.max(0,Math.min(.6,(l-18)/90)),b=1-Math.exp(-(2.2+us(e.seed,9)*2)*y*t);if(e.vx+=(s-e.vx)*b,e.vy+=(c-e.vy)*b,e.z<.02){let n=Math.exp(-9*t);e.vx*=n,e.vy*=n}let x=e.x,S=e.y;if(e.x+=e.vx*t,e.y+=e.vy*t,e.z<12)for(let t of i)e.x<t.x||e.x>t.x+t.width||e.y<t.y||e.y>t.y+t.height||((x<=t.x||x>=t.x+t.width)&&(e.x=x,e.vx=0),(S<=t.y||S>=t.y+t.height)&&(e.y=S,e.vy=0));e.spread=Math.min(2.2,e.spread+d*Math.hypot(e.vx,e.vy)*t*.0018),e.angle+=(e.vx-e.vy)*t*.006+d*Math.sin(p+m)*t*.7}if(!o)return;let s=a.parcels.length;for(let t of[`x`,`y`,`z`,`vx`,`vy`,`vz`])e[t]=a.parcels.reduce((e,n)=>e+n[t],0)/s;a.radius=Math.max(...a.parcels.map(t=>Math.hypot(t.x-e.x,t.y-e.y)+t.radius*t.spread*1.8))}var ps=Object.freeze([`paper`,`crumpled-paper`,`trash`,`leaf`,`dust`]),ms=Object.freeze([`center`,`top`,`top-right`,`right`,`bottom-right`,`bottom`,`bottom-left`,`left`,`top-left`,`fill`]),hs=(e,t)=>{let n=Math.imul(e+31,374761393)^Math.imul(t+17,668265263);return n=Math.imul(n^n>>>13,1274126177),((n^n>>>16)>>>0)/4294967296},gs=(e,t,n)=>e+(t-e)*n;function _s(e,t){let n=Math.floor(e),r=e-n;return gs(hs(n,t),hs(n+1,t),r*r*(3-2*r))*2-1}var vs={paper:{size:[15,24],response:3.8,threshold:28,lift:1.6,gravity:52,friction:4,colors:[`#f2efe4`,`#e4e5dc`,`#e8dfc8`,`#d8e2e2`]},"crumpled-paper":{size:[8,13],response:1.8,threshold:82,lift:.65,gravity:170,friction:2.8,colors:[`#b9b4a4`,`#d2cbbb`,`#9eaaad`]},trash:{size:[11,18],response:3,threshold:45,lift:1.15,gravity:92,friction:4,colors:[`#9aacae`,`#b2a681`,`#ab6960`,`#697f86`]},leaf:{size:[12,21],response:3.4,threshold:32,lift:1.4,gravity:65,friction:4.5,colors:[`#91824e`,`#927146`,`#707c4e`,`#9c7552`]},dust:{size:[28,46],response:5,threshold:24,lift:1.5,gravity:20,friction:6,colors:[`#a28a62`,`#978a76`,`#b09b79`]}};function ys(e={}){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Debris options must be an object`);for(let t of Object.keys(e))if(![`amount`,`kinds`,`anchor`,`spread`,`seed`,`wind`,`color`,`glint`].includes(t))throw RangeError(`Unknown debris option: ${t}`);let t=(t,n,r,i=!1)=>{let a=e[t];if(a!==void 0&&(!Number.isFinite(a)||a<n||a>r||i&&!Number.isInteger(a)))throw RangeError(`debris.${t} must be ${i?`an integer`:`a number`} between ${n} and ${r}`)};if(t(`amount`,0,600,!0),t(`spread`,0,2e3),t(`seed`,-2147483648,2147483647,!0),e.anchor!==void 0&&!ms.includes(e.anchor))throw RangeError(`Unknown debris anchor`);if(e.kinds!==void 0&&(!Array.isArray(e.kinds)||!e.kinds.length||e.kinds.some(e=>!ps.includes(e))))throw RangeError(`Choose at least one supported debris kind`);if(e.wind!==void 0&&(!e.wind||typeof e.wind!=`object`||!Number.isFinite(e.wind.x)||!Number.isFinite(e.wind.y)||Math.hypot(e.wind.x,e.wind.y)>500))throw RangeError(`Debris wind must be a finite vector up to 500 pixels/second`);if(e.glint!==void 0&&(!Number.isFinite(e.glint)||e.glint<0||e.glint>1))throw RangeError(`Debris glint must be between 0 and 1`);if(e.color!==void 0&&!/^#[\da-f]{3}(?:[\da-f]{3})?$/i.test(e.color))throw RangeError(`Debris color must be a 3 or 6 digit hex color`)}function bs(e,t){let n=t.anchor,r=n.includes(`left`)||n===`left`?0:n.includes(`right`)||n===`right`?1:.5,i=n.includes(`top`)||n===`top`?0:n.includes(`bottom`)||n===`bottom`?1:.5;return Array.from({length:t.amount},(a,o)=>{let s=Math.imul(t.seed,31)+o*977|0,c=t.kinds[o%t.kinds.length],l=vs[c],u=hs(s,7)*Math.PI*2,d=Math.sqrt(hs(s,11))*t.spread,f={kind:c,x:e.x+(n===`fill`?hs(s,13)*e.width:e.width*r+Math.cos(u)*d),y:e.y+(n===`fill`?hs(s,17)*e.height:e.height*i+Math.sin(u)*d),z:0,vx:0,vy:0,vz:0,angle:hs(s,19)*Math.PI*2,spin:0,tilt:0,fold:.05+hs(s,23)*.18,curlX:.35+hs(s,41)*.4,curlY:.1+hs(s,43)*.35,twist:(hs(s,47)-.5)*.4,curlVelocityX:0,curlVelocityY:0,twistVelocity:0,size:gs(l.size[0],l.size[1],hs(s,29)),seed:s,color:t.color||l.colors[Math.floor(hs(s,31)*l.colors.length)],age:0,opacity:c===`dust`?.65+hs(s,37)*.2:1,glint:t.glint};return c===`dust`&&(f.dust=ds(f.x,f.y,f.size,s)),f})}var xs=class{groups=new Map;vortices=[];serial=0;time=0;wakeClock=0;collection=[];get particles(){return this.collection}get count(){return this.collection.length}get managedBytes(){return this.count*216+this.collection.reduce((e,t)=>e+(t.dust?.parcels.length??0)*104,0)+this.vortices.length*64}collect(){this.collection=[...this.groups.values()].flatMap(e=>e.particles)}scatter(e,t={}){if(ys(t),[e.x,e.y,e.width,e.height].some(e=>!Number.isFinite(e))||e.width<0||e.height<0)throw RangeError(`Debris bounds must be finite and non-negative`);let n={amount:t.amount??30,anchor:t.anchor??`center`,kinds:[...new Set(t.kinds??ps)],seed:t.seed??31,spread:t.spread??Math.max(60,Math.min(200,Math.sqrt(e.width*e.height)*.4)),wind:{...t.wind??{x:7,y:-2}},color:t.color??``,glint:t.glint??.12};if(this.count+n.amount>3e3)throw RangeError(`Scene debris budget is 3000 particles`);let r=`debris-${++this.serial}`;return this.groups.set(r,{bounds:{...e},options:n,particles:bs(e,n),gust:{x:0,y:0},gustAge:0}),this.collect(),this.handle(r)}get(e){return this.groups.has(e)?this.handle(e):null}handle(e){return{id:e,reset:()=>{let t=this.groups.get(e);t&&(t.particles=bs(t.bounds,t.options),t.gust={x:0,y:0},this.collect())},gust:t=>{if(!Number.isFinite(t.x)||!Number.isFinite(t.y)||Math.hypot(t.x,t.y)>500)throw RangeError(`Gust velocity must be finite and at most 500 pixels/second`);let n=this.groups.get(e);n&&(n.gust={...t},n.gustAge=0)},dispose:()=>{this.groups.delete(e),this.collect()}}}reset(){this.vortices=[],this.time=0,this.wakeClock=0;for(let e of this.groups.values())e.particles=bs(e.bounds,e.options),e.gust={x:0,y:0},e.gustAge=0;this.collect()}clear(){this.groups.clear(),this.vortices=[],this.collection=[]}captureState(){return E({groups:this.groups,vortices:this.vortices,serial:this.serial,time:this.time,wakeClock:this.wakeClock})}restoreState(e){let t=E(e);this.groups=t.groups,this.vortices=t.vortices,this.serial=Math.max(this.serial,t.serial),this.time=t.time,this.wakeClock=t.wakeClock,this.collect()}step(e,t=[],n,r=[]){if(!this.count||e<=0)return;let i=Math.max(1,Math.ceil(Math.min(.1,e)*120));for(let a=0;a<i;a++)this.integrate(Math.min(.1,e)/i,t,n,r)}airAt(e,t,n,r,i){let a=1+_s(this.time*.27+e*7e-4,n.options.seed)*.55,o=n.options.wind.x*a+n.gust.x*r,s=n.options.wind.y*a+n.gust.y*r;o+=_s(this.time*.5+t*.002,n.options.seed+19)*5,s+=_s(this.time*.4+e*.002,n.options.seed+31)*5;for(let n of i){let r=e-n.x,i=t-n.y,a=Math.hypot(n.vx,n.vy);if(a<3||Math.abs(r)>n.length+100||Math.abs(i)>n.length+100)continue;let c=n.angle,l=Math.cos(c),u=Math.sin(c),d=r*l+i*u,f=-r*u+i*l,p=Math.max(0,1-Math.abs(d)/(n.length*.75+40))*Math.max(0,1-Math.abs(f)/(n.width*.7+55)),m=f>=0?1:-1;o+=(n.vx*.22-u*a*.36*m)*p,s+=(n.vy*.22+l*a*.36*m)*p}for(let n of this.vortices){let r=e-n.x,i=t-n.y,a=r*r+i*i;if(a>n.radius*n.radius)continue;let c=(1-a/(n.radius*n.radius))**2*Math.exp(-n.age*2),l=n.strength*c/Math.max(12,Math.sqrt(a));o+=-i*l+n.vx*c,s+=r*l+n.vy*c}return{x:o,y:s}}integrate(e,t,n,r=[]){this.time+=e,this.wakeClock+=e,this.vortices=this.vortices.filter(e=>e.age<1.6);for(let t of this.vortices)t.age+=e,t.x+=t.vx*e,t.y+=t.vy*e;if(this.wakeClock>=.1){this.wakeClock%=.1;for(let e of t){let t=Math.hypot(e.vx,e.vy);if(t<35)continue;let n=e.vx/t,r=e.vy/t;for(let i of[-1,1])this.vortices.push({x:e.x-n*e.length*.45-r*e.width*.6*i,y:e.y-r*e.length*.45+n*e.width*.6*i,vx:e.vx*.12,vy:e.vy*.12,strength:Math.min(200,t*.3)*i,radius:Math.min(130,e.width*1.6+t*.1),age:0})}this.vortices.length>32&&this.vortices.splice(0,this.vortices.length-32)}for(let i of this.groups.values()){i.gustAge+=e;let a=Math.exp(-i.gustAge*1.5);for(let o of i.particles){if(o.age+=e,n&&o.z<.05&&(!o.dust||o.dust.parcels.every(e=>e.z===0&&e.vz===0))&&Math.hypot(o.vx,o.vy)<2&&o.vz<=0&&(o.x<n.x-300-(o.dust?.radius??0)||o.x>n.x+n.width+300+(o.dust?.radius??0)||o.y<n.y-300-(o.dust?.radius??0)||o.y>n.y+n.height+300+(o.dust?.radius??0)))continue;let s=vs[o.kind];if(o.kind===`dust`){o.dust??=ds(o.x,o.y,o.size,o.seed),fs(o,e,this.time,(e,n)=>this.airAt(e,n,i,a,t),r);continue}let{x:c,y:l}=this.airAt(o.x,o.y,i,a,t),u=Math.hypot(c-o.vx,l-o.vy),d=o.z>.1||o.vz>0,f=Math.max(0,u-s.threshold)*s.lift;(d||f>s.gravity*.8)&&(o.vz+=(f-s.gravity-o.vz*1.8)*e,o.vz=Math.min(95,o.vz)),o.z+=o.vz*e,o.z<=0&&(o.z=0,o.vz=o.vz<-18&&o.kind===`crumpled-paper`?-o.vz*.13:0),o.z>70&&(o.z=70,o.vz=Math.min(0,o.vz));let p=o.z>.1?1:Math.max(0,Math.min(.7,(u-s.threshold*.5)/70));if(o.vx+=(c-o.vx)*(1-Math.exp(-s.response*p*e)),o.vy+=(l-o.vy)*(1-Math.exp(-s.response*p*e)),o.z<.1){let t=Math.exp(-s.friction*e);o.vx*=t,o.vy*=t}let m=o.x,h=o.y;if(o.x+=o.vx*e,o.y+=o.vy*e,o.z<12){for(let e of r)if(!(o.x<e.x||o.x>e.x+e.width||o.y<e.y||o.y>e.y+e.height)){o.x=m,o.y=h,o.vx*=-.15,o.vy*=-.15;break}}let g=_s(this.time*3.2+o.x*.01,o.seed),_=(c*Math.sin(o.angle)-l*Math.cos(o.angle))*.024;if(o.spin+=(_+g*u*.02-o.spin*(o.z>0?1.8:9))*e,o.angle+=o.spin*e,o.kind===`paper`){let t=Math.min(1,Math.max(0,(u-18)/100)),n=c-o.vx,r=l-o.vy,i=Math.max(1,Math.hypot(n,r)),a=(n*Math.cos(o.angle)+r*Math.sin(o.angle))/i,s=(-n*Math.sin(o.angle)+r*Math.cos(o.angle))/i,d=.35+hs(o.seed,41)*.4,f=.1+hs(o.seed,43)*.35,p=(hs(o.seed,47)-.5)*.4,m=d+t*(1.5+Math.abs(a)*1.1+g*.7),h=f+t*(.5+Math.abs(s)*.8-g*.3),_=p+t*(s*.9+g*.8);o.curlVelocityX+=((m-o.curlX)*55-o.curlVelocityX*9)*e,o.curlVelocityY+=((h-o.curlY)*38-o.curlVelocityY*7)*e,o.twistVelocity+=((_-o.twist)*42-o.twistVelocity*7.5)*e,o.curlX+=o.curlVelocityX*e,o.curlY+=o.curlVelocityY*e,o.twist+=o.twistVelocity*e}if(o.z>.5)o.tilt+=(Math.hypot(o.vx,o.vy)*.035+g*2.5)*e,o.fold+=(.18+Math.abs(g)*.5-o.fold)*Math.min(1,e*8);else{if(o.kind===`crumpled-paper`)o.tilt+=Math.hypot(o.vx,o.vy)/Math.max(2,o.size*.42)*e;else{let t=Math.round(o.tilt/Math.PI)*Math.PI;o.tilt+=(t-o.tilt)*(1-Math.exp(-e*10))}o.fold+=(.05+hs(o.seed,23)*.18-o.fold)*Math.min(1,e*4)}}}}},Ss={health:as},Cs={burnSeconds:as,ignitionSeconds:ss,spreadSeconds:ss},ws={health:as,burnSeconds:as,blastRadiusPx:as},Ts={scale:os,opacity:os,crushedClass:$o,crushedPaintColor:(e,t)=>rs(e,t)},Es={kind:$o,color:(e,t)=>rs(e,t,!0),distanceM:ss,opacity:os,deformation:(e,t)=>ts(e,t,0,4)},Ds=[`click`,`check`,`toggle`,`pickup`,`parking`],Os=(e,t)=>{typeof e!=`string`&&F(t,`expected a space-separated class string`)},ks={preset:(e,t)=>ns(e,Ds,t),when:(e,t)=>ns(e,[`enter`,`stop`],t),dwellSeconds:ss,maxSpeedMps:ss,action:(e,t)=>ns(e,[`event`,`click`,`check`,`uncheck`,`toggle`],t),event:$o,repeat:(e,t)=>ns(e,[`visit`,`vehicle`,`scene`],t),vehicles:(e,t)=>ns(e,[`player`,`all`,`ai`],t),target:$o,consume:es,exitMarginPx:ss,containment:(e,t)=>ns(e,[`overlap`,`center`,`full`],t),requireExit:es,suspended:es,reveal:(e,t)=>ns(e,[`departed`],t),enteredClass:Os,dwellingClass:Os,successClass:Os};function As(e,t){typeof e!=`boolean`&&(typeof e==`string`?ns(e,Ds,t):is(Yo(e,t),ks,t))}function js(e,t,n=!0){vn(e,t,n,F)}function Ms(e,t,n=new Set){if(e!==null&&typeof e!=`string`&&typeof e!=`boolean`){if(typeof e==`number`)ts(e,t,-1/0);else{if(typeof e!=`object`)return F(t,`metadata must be JSON-compatible`);if(n.has(e)&&F(t,`metadata cannot contain cycles`),n.add(e),Array.isArray(e))e.forEach((e,r)=>Ms(e,`${t}.${r}`,n));else for(let[r,i]of Object.entries(Yo(e,t)))Ms(i,`${t}.${r}`,n);n.delete(e)}}}function Ns(e,t,n=!0){if(e===!1)return;let r=Yo(e,t);is(r,{field:(e,t)=>ns(e,[`fps`,`speed`,`rpm`,`gear`,`health`,`points`],t),unit:(e,t)=>ns(e,[`mph`,`kmh`,`mps`],t),precision:(e,t)=>{ts(e,t,0,4),Number.isInteger(e)||F(t,`precision must be an integer`)}},t),n&&!Xo(r,`field`)&&F(`${t}.field`,`choose one HUD metric`),Xo(r,`unit`)&&Xo(r,`field`)&&r.field!==`speed`&&F(`${t}.unit`,`only speed has a unit`)}var Ps={id:$o,enabled:es,debris:e=>{typeof e!=`boolean`&&ys(e)},trigger:As,hud:Ns,meta:(e,t)=>{Yo(e,t),Ms(e,t)},object:$o,solid:es,pushable:es,points:ss,liquid:(e,t)=>{if(e===!1)return;let n=Yo(e,t);is(n,Es,t),Xo(n,`kind`)||F(`${t}.kind`,`choose a liquid`)},breakable:(e,t)=>ls(e,t,Ss),burnable:(e,t)=>ls(e,t,Cs),combustible:(e,t)=>ls(e,t,ws),crushable:(e,t)=>ls(e,t,Ts)},Fs={id:$o,vehicle:$o,driver:(e,t)=>ns(e,[`player`,`idle`,`follow`,`flee`,`pursue`],t),appearance:cs,slots:js};function Is(e){let t=Yo(e,`object`);return is(t,{...Ps,hud:(e,t)=>Ns(e,t,!1)},`object`),structuredClone(t)}function Ls(e){let t=Yo(e,`object`);return is(t,Ps,`object`),Zo(t.combustible)&&Zo(t.breakable)&&F(`object.combustible`,`combustible excludes breakable`),Zo(t.crushable)&&Zo(t.breakable)&&F(`object.crushable`,`crushable excludes breakable`),Zo(t.crushable)&&t.solid===!0&&F(`object.solid`,`crushable objects cannot be solid`),Zo(t.hud)&&(Zo(t.breakable)||Zo(t.burnable)||t.pushable===!0||Zo(t.liquid))&&F(`object.hud`,`HUD output cannot also own artwork or a liquid field`),structuredClone(t)}function Rs(e){let t=Yo(e,`vehicle`);is(t,{...Fs,slots:(e,t)=>js(e,t,!1)},`vehicle`);let n=t.slots;if(n)for(let[e,t]of Object.entries(n))t&&t.action!==void 0&&js({[e]:t},`vehicle.slots`);return structuredClone(t)}function zs(e){let t=Yo(e,`vehicle`);return is(t,Fs,`vehicle`),$o(t.vehicle,`vehicle.vehicle`),structuredClone(t)}function Bs(e){let t=Yo(e,`player`);return Qo(t,[`vehicle`,`appearance`,`slots`],`player`),zs(t)}function Vs(e,t){let n=Yo(e,t);is(n,{order:(e,t)=>ns(e,[`ordered`,`any`],t),progress:(e,t)=>ns(e,[`vehicle`,`scene`],t),event:$o,stops:(e,t)=>{Array.isArray(e)&&e.length||F(t,`expected at least one stop`);let n=new Set;for(let[r,i]of e.entries()){let e;if(typeof i==`string`)e=$o(i,`${t}.${r}`);else{let n=Yo(i,`${t}.${r}`);is(n,{target:$o,when:ks.when,dwellSeconds:ss,maxSpeedMps:ss},`${t}.${r}`),e=$o(n.target,`${t}.${r}.target`)}n.has(e)&&F(t,`duplicate stop ${e}`),n.add(e)}}},t),Xo(n,`stops`)||F(`${t}.stops`,`expected at least one stop`)}function Hs(e){return Vs(e,`route`),structuredClone(e)}function Us(e,t,n=[]){if(t===void 0||t===!0&&e&&typeof e==`object`&&!Array.isArray(e))return e;if(t&&typeof t==`object`&&!Array.isArray(t)){let r=Yo(t,`object`);n.length===2&&n[0]===`slots`&&r.action!==void 0&&e&&typeof e==`object`&&e.action!==r.action&&(e=void 0);let i={...e&&typeof e==`object`&&!Array.isArray(e)?e:{}};for(let[e,r]of Object.entries(t))[`__proto__`,`prototype`,`constructor`].includes(e)&&F(e,`reserved option name`),r!==void 0&&(i[e]=Us(i[e],r,[...n,e]));return i}return t}function Ws(...e){let t={};for(let n of e){if(n==null)continue;let e={...Yo(n,`object`)};for(let t of[`trigger`])typeof e[t]==`string`&&(e[t]={preset:e[t]});t=Us(t,e)}return structuredClone(t)}var Gs=e=>e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ks=e=>e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),qs=new Map,Js=(e,t,n)=>qs.set(`data-jr-${e}`,{path:t,kind:n});for(let e of[`solid`,`pushable`,`enabled`])Js(e,[e],`boolean`);for(let e of[`id`,`object`])Js(e,[e],`string`);for(let e of[`points`])Js(e,[e],`number`);var Ys=new Set([as,ss,os,Es.deformation]);function Xs(e,t,n){for(let[r,i]of Object.entries(n))Js(`${e}-${Ks(r)}`,[...t,r],i===es?`boolean`:Ys.has(i)?`number`:`string`)}for(let[e,t]of Object.entries({breakable:Ss,burnable:Cs,combustible:ws,crushable:Ts}))Js(e,[e],`root`),Xs(e,[e],t);Js(`crushed-class`,[`crushable`,`crushedClass`],`string`),Js(`crushed-paint-color`,[`crushable`,`crushedPaintColor`],`string`),Js(`liquid`,[`liquid`,`kind`],`string`);var{kind:Zs,...Qs}=Es;Xs(`liquid`,[`liquid`],Qs),Js(`debris`,[`debris`],`root`);for(let e of[`anchor`,`color`])Js(`debris-${e}`,[`debris`,e],`string`);for(let e of[`amount`,`spread`,`seed`,`glint`])Js(`debris-${e}`,[`debris`,e],`number`);Js(`debris-kinds`,[`debris`,`kinds`],`list`),Js(`debris-wind-x`,[`debris`,`wind`,`x`],`number`),Js(`debris-wind-y`,[`debris`,`wind`,`y`],`number`),Js(`trigger`,[`trigger`],`root`),Xs(`trigger`,[`trigger`],ks);var $s=[...[`fps`,`speed`,`rpm`,`gear`,`health`,`points`].map(e=>`data-jr-hud-${e}`),`data-jr-hud-unit`,`data-jr-hud-precision`],ec=Object.freeze([...qs.keys(),...$s]).map(e=>`[${e}]`).join(`,`);function tc(e,t){return e===``||e===`true`||e!==`false`&&F(t,`use an empty marker, true, or false`)}function nc(e,t,n,r){let i=e;for(let e=0;e<t.length-1;e++){let n=t[e],a=i[n];a===!1&&F(r,`options require an enabled capability`),a&&typeof a==`object`||(i[n]=typeof a==`string`?{preset:a}:{}),i=i[n]}i[t[t.length-1]]=n}function rc(e){let t={},n=!1,r={},i=!1,a=Array.from(e.attributes).sort((e,t)=>e.name.split(`-`).length-t.name.split(`-`).length);for(let{name:e,value:o}of a){if($s.includes(e)){n=!0;let t=e.slice(12);t===`unit`?r.unit=o:t===`precision`?(o.trim()&&Number.isFinite(Number(o))||F(e,`expected a finite number`),r.precision=Number(o)):tc(o,e)?(r.field&&F(e,`one element can display only one HUD metric`),r.field=t):i=!0;continue}if(e.startsWith(`data-jr-meta-`)){let r=Gs(e.slice(13));(!r||[`__proto__`,`prototype`,`constructor`].includes(r))&&F(e,`invalid metadata key`),t.meta??={},t.meta[r]=o,n=!0;continue}let a=qs.get(e);if(!a)continue;n=!0;let s=o;a.kind===`list`?s=o.split(/[\s,]+/).filter(Boolean):a.kind===`boolean`?s=tc(o,e):a.kind===`number`?(o.trim()||F(e,`expected a number`),s=Number(o),Number.isFinite(s)||F(e,`expected a finite number`)):a.kind===`root`&&(s=o===``||o===`true`||o===`false`?tc(o,e):e===`data-jr-debris`?{kinds:o.split(/[\s,]+/).filter(Boolean)}:o),nc(t,a.path,s,e)}return Object.keys(r).length?t.hud=r:i&&(t.hud=!1),n?t:null}function ic(e){return e&&typeof e==`object`&&(Object.values(e).forEach(ic),Object.freeze(e)),e}function ac(e){let t=Yo(e,`definitions`);Qo(t,[`liquids`,`vehicles`,`objects`,`routes`],`definitions`);for(let[e,n]of Object.entries(t)){if(n===void 0)continue;let t=Yo(n,`definitions.${e}`);for(let[n,r]of Object.entries(t)){let t=`definitions.${e}.${n}`;(!/^[a-z][a-z0-9-]{0,63}$/.test(n)||[`constructor`,`prototype`,`__proto__`].includes(n))&&F(t,`use a lowercase recipe name`);let i=Yo(r,t);if(e===`objects`)Ls(i);else if(e===`routes`)Vs(i,t);else if(e===`liquids`)is(i,{base:$o,color:rs,thickness:os,opacity:os,deformation:(e,t)=>ts(e,t,0,4),conductive:es,burnable:es,burnLifetime:as,fireSpreadMps:as,effect:(e,t)=>{let n=Yo(e,t);is(n,{lifetime:(e,t)=>{let n=Yo(e,t);is(n,{unit:(e,t)=>ns(e,[`seconds`,`distanceM`],t),amount:as},t),Xo(n,`unit`)&&Xo(n,`amount`)||F(t,`unit and amount are required`)},modifiers:(e,t)=>{for(let[n,r]of Object.entries(Yo(e,t)))ss(r,`${t}.${n}`)},additiveModifiers:(e,t)=>{for(let[n,r]of Object.entries(Yo(e,t)))ts(r,`${t}.${n}`,-1/0)},intensity:(e,t)=>ns(e,[`linear`,`pulse`,`constant`],t)},t),Xo(n,`lifetime`)&&Xo(n,`modifiers`)||F(t,`lifetime and modifiers are required`)}},t),$o(i.base,`${t}.base`);else{Qo(i,`base.name.description.make.model.year.massKg.health.frontWeightFraction.geometry.exhaust.lights.roofRocket.machineGuns.flamethrower.rockets.lightning.sound.visual.engineForceN.reversePowerRatio.maxReverseSpeedMps.rollingResistance.coastDecelerationMps2.handbrakeDecelerationMps2.serviceBrakeDecelerationMps2.lateralResistance.corneringAccelerationMps2.maxSteerAngleRad.handbrakeStrength.drift.launch.driveBoost.image.appearance.slots`.split(`.`),t),$o(i.base,`${t}.base`),Xo(i,`appearance`)&&cs(i.appearance,`${t}.appearance`),Xo(i,`slots`)&&js(i.slots,`${t}.slots`);for(let[e,n]of Object.entries(i))typeof n==`number`&&ts(n,`${t}.${e}`,-1/0);Ms(Us({},i),t)}}for(let n of Object.keys(t)){let r=new Set,i=n;for(;i&&Object.hasOwn(t,i);)r.has(i)&&F(`definitions.${e}.${n}.base`,`recipe inheritance contains a cycle`),r.add(i),i=t[i].base}}return ic(structuredClone(e))}function oc(e,t){let n=1/0,r={x:1,y:0};for(let i of[e,t])for(let a=0;a<i.length;a++){let o=i[a],s=i[(a+1)%i.length],c=Math.hypot(s.x-o.x,s.y-o.y);if(c<1e-9)continue;let l={x:-(s.y-o.y)/c,y:(s.x-o.x)/c},u=e.map(e=>e.x*l.x+e.y*l.y),d=t.map(e=>e.x*l.x+e.y*l.y),f=Math.min(...u),p=Math.max(...u),m=Math.min(...d),h=Math.max(...d);if(p<=m||h<=f)return null;let g=p-m,_=h-f,v=Math.min(g,_);v<n&&(n=v,r=g<_?{x:-l.x,y:-l.y}:l)}return Number.isFinite(n)?{normal:r,depth:n}:null}function sc(e,t,n,r){let i=r.reduce((e,t,n)=>{let i=r[(n+1)%r.length];return e+t.x*i.y-i.x*t.y},0),a=0,o=1;for(let s=0;s<r.length;s++){let c=r[s],l=r[(s+1)%r.length],u=Math.hypot(l.x-c.x,l.y-c.y);if(u<1e-9)continue;let d=(l.y-c.y)/u*Math.sign(i),f=-(l.x-c.x)/u*Math.sign(i),p=(e.x-c.x)*d+(e.y-c.y)*f-n,m=(t.x-e.x)*d+(t.y-e.y)*f;if(Math.abs(m)<1e-9){if(p>0)return null;continue}let h=-p/m;if(m<0?a=Math.max(a,h):o=Math.min(o,h),a>o)return null}return a<=1&&o>=0?a:null}function cc(e,t,n,r,i){if(!(r.speedMps>.8))return!1;let a=r.pixelsPerMeter,o=k(r.point,n.center);return e.car.takeImpact(r.speedMps,D(j(o,n.forward)/a,j(o,n.side)/a)),t?.hit(r.point,r.normal,n,r.speedMps,a),i(),!0}var lc=[`low`,`medium`,`high`],uc=1e3/60,dc=2e3,fc=8,pc=2e3,mc=1e4,hc=12e4,gc=5e3,_c=class{cap=lc.length-1;misses=[];lastTime=null;lastChange=-1/0;lastStepUp=-1/0;stepUpDelay=mc;get limit(){return lc[this.cap]}apply(e){return lc[Math.min(lc.indexOf(e),this.cap)]}sample(e,t,n,r){let i=this.lastTime;if(this.lastTime=e,i===null)return!1;let a=e-i;if(!(a>0)||a>250)return!1;for(a>uc*1.5&&t<uc*.8&&n&&this.misses.push(e);this.misses.length&&e-this.misses[0]>dc;)this.misses.shift();if(e-this.lastChange<pc)return!1;let o=lc.indexOf(r);return this.misses.length>=fc&&Math.min(this.cap,o)>0?(e-this.lastStepUp<gc&&(this.stepUpDelay=Math.min(hc,this.stepUpDelay*2)),this.cap=Math.min(this.cap,o)-1,this.changed(e),!0):n&&this.cap<o&&!this.misses.length&&e-this.lastChange>=this.stepUpDelay?(this.cap++,this.lastStepUp=e,this.changed(e),!0):!1}restoreLimit(e){this.cap=e?Math.max(0,lc.indexOf(e)):lc.length-1,this.misses=[],this.lastTime=null}reset(){this.cap=lc.length-1,this.misses=[],this.lastTime=null,this.lastChange=this.lastStepUp=-1/0,this.stepUpDelay=mc}changed(e){this.lastChange=e,this.misses=[]}};function vc(e,t){let n=t.x-e.point.x,r=t.y-e.point.y;if(Math.hypot(e.direction.x,e.direction.y)<.1)return Math.exp(-(n*n+r*r)/Math.max(1,e.radius*e.radius))*e.intensity;let i=n*e.direction.x+r*e.direction.y;if(i<0||i>e.range)return 0;let a=n*-e.direction.y+r*e.direction.x,o=e.radius+i*e.spread,s=i/Math.max(1,e.range),c=Math.max(0,Math.min(1,(1-s)/.36));return Math.exp(-(a*a)/Math.max(1,o*o))*c*c*(3-2*c)*(1-s*.42)*e.intensity}var yc=`
2
- uniform int vehicleLightCount;
3
- uniform vec4 vehicleLightPosition[12];
4
- uniform vec4 vehicleLightShape[12];
5
- uniform vec4 vehicleLightColor[12];
6
- vec3 scatterVehicleLight(vec3 baseColor, float density, vec2 canvasPoint, bool dark) {
7
- if (vehicleLightCount == 0) return baseColor;
8
- vec3 radiance = vec3(0.0);
9
- vec2 slope = vec2(dFdx(density), -dFdy(density));
10
- vec3 normal = normalize(vec3(-slope * 8.0, 0.7));
11
- for (int i = 0; i < 12; i++) {
12
- if (i >= vehicleLightCount) break;
13
- vec2 offset = canvasPoint - vehicleLightPosition[i].xy;
14
- vec2 direction = vehicleLightShape[i].xy;
15
- float radius = max(1.0, vehicleLightPosition[i].w);
16
- float strength;
17
- if (dot(direction, direction) < 0.1) {
18
- strength = exp(-dot(offset, offset) / (radius * radius));
19
- } else {
20
- float along = dot(offset, direction);
21
- float distance = along / max(1.0, vehicleLightPosition[i].z);
22
- float across = dot(offset, vec2(-direction.y, direction.x));
23
- float beamWidth = radius + max(0.0, along) * vehicleLightShape[i].z;
24
- strength = exp(-across * across / (beamWidth * beamWidth));
25
- strength *= step(0.0, along) * (1.0 - smoothstep(0.64, 1.0, distance));
26
- strength *= 1.0 - clamp(distance, 0.0, 1.0) * 0.42;
27
- }
28
- // Curling edges face the source differently as the smoke moves.
29
- vec2 towardLight = -offset / max(1.0, length(offset));
30
- float facing = max(0.0, dot(normal, normalize(vec3(towardLight * 0.65, 0.75))));
31
- float edge = clamp(length(slope) * 18.0, 0.0, 1.0);
32
- strength *= 0.72 + facing * 0.28 + edge * 0.32;
33
- radiance += vehicleLightColor[i].rgb * strength * vehicleLightColor[i].a;
34
- }
35
- float illumination = max(radiance.r, max(radiance.g, radiance.b));
36
- // Toggling a source must not change smoke outside its finite light field.
37
- vec3 ambient = baseColor;
38
- // Thin edges transmit light; dense centers retain their volume and texture.
39
- float transmission = 1.0 / (1.0 + max(0.0, density) * 0.11);
40
- vec3 lit = radiance / max(illumination, 0.0001);
41
- // White particles retain a neutral component under colored light. This
42
- // avoids turning the entire dense plume into a flat, saturated red decal.
43
- float chroma = max(lit.r, max(lit.g, lit.b)) - min(lit.r, min(lit.g, lit.b));
44
- lit = mix(lit, vec3(1.0), chroma * 0.24);
45
- float scattering = 1.0 - exp(-illumination * transmission * 1.28);
46
- return mix(ambient, lit, scattering * 0.65) + radiance * 0.045 * transmission;
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: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
- `||r===` `||r===` `)for(;L<t.length&&(t[L]===`
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
- `||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(`
52
- `).map((e,t)=>{let r=i.get(t);return`${t+1+n}: ${e}${r?`\n\n^^^ ${r}`:``}`}).join(`
53
- `)}var F_=/^[ \t]*\n/;function I_(e){let t=0;return F_.test(e)&&(t=1,e=e.replace(F_,``)),{lineOffset:t,shaderSource:e}}function L_(e,t,n,r){if(r||=qh,!e.getShaderParameter(n,Qh)){let i=e.getShaderInfoLog(n),{lineOffset:a,shaderSource:o}=I_(e.getShaderSource(n)),s=`${P_(o,i,a)}\nError compiling ${Rf(e,t)}: ${i}`;return r(s),s}return``}function R_(e,t,n){let r,i,a;if(typeof t==`function`&&(n=t,t=void 0),typeof e==`function`)n=e,e=void 0;else if(e&&!Array.isArray(e)){let t=e;n=t.errorCallback,e=t.attribLocations,r=t.transformFeedbackVaryings,i=t.transformFeedbackMode,a=t.callback}let o=n||qh,s=[],c={errorCallback(e,...t){s.push(e),o(e,...t)},transformFeedbackVaryings:r,transformFeedbackMode:i,callback:a,errors:s};{let n={};Array.isArray(e)?e.forEach(function(e,r){n[e]=t?t[r]:r}):n=e||{},c.attribLocations=n}return c}var z_=[`VERTEX_SHADER`,`FRAGMENT_SHADER`];function B_(e,t){if(t.indexOf(`frag`)>=0)return eg;if(t.indexOf(`vert`)>=0)return tg}function V_(e,t,n){let r=e.getAttachedShaders(t);for(let t of r)n.has(t)||e.deleteShader(t);e.deleteProgram(t)}var H_=(e=0)=>new Promise(t=>setTimeout(t,e));function U_(e,t,n){let r=e.createProgram(),{attribLocations:i,transformFeedbackVaryings:a,transformFeedbackMode:o}=R_(n);for(let n=0;n<t.length;++n){let i=t[n];if(typeof i==`string`){let t=Jh(i),r=t?t.text:i,a=e[z_[n]];t&&t.type&&(a=B_(e,t.type)||a),i=e.createShader(a),e.shaderSource(i,I_(r).shaderSource),e.compileShader(i)}e.attachShader(r,i)}Object.entries(i).forEach(([t,n])=>e.bindAttribLocation(r,n,t));{let t=a;t&&(t.attribs&&(t=t.attribs),Array.isArray(t)||(t=Object.keys(t)),e.transformFeedbackVaryings(r,t,o||ng))}return e.linkProgram(r),r}function W_(e,t,n,r,i){let a=R_(n,r,i),o=new Set(t),s=U_(e,t,a);function c(e,t){let n=K_(e,t,a.errorCallback);return n&&V_(e,t,o),n}if(a.callback)G_(e,s).then(()=>{let t=c(e,s);a.callback(t,t?void 0:s)});else return c(e,s)?void 0:s}async function G_(e,t){let n=e.getExtension(`KHR_parallel_shader_compile`),r=n?(e,t)=>e.getProgramParameter(t,n.COMPLETION_STATUS_KHR):()=>!0,i=0;do await H_(i),i=1e3/60;while(!r(e,t))}function K_(e,t,n){if(n||=qh,!e.getProgramParameter(t,$h)){let r=e.getProgramInfoLog(t);return n(`Error in program linking: ${r}`),`${r}\n${e.getAttachedShaders(t).map(t=>L_(e,e.getShaderParameter(t,e.SHADER_TYPE),t,n)).filter(e=>e).join(`
54
- `)}`}}function q_(e,t,n,r,i){return W_(e,t,n,r,i)}function J_(e){let t=e.name;return t.startsWith(`gl_`)||t.startsWith(`webgl_`)}var Y_=/(\.|\[|]|\w+)/g,X_=e=>e>=`0`&&e<=`9`;function Z_(e,t,n,r){let i=e.split(Y_).filter(e=>e!==``),a=0,o=``;for(;;){let e=i[a++];o+=e;let s=X_(e[0]),c=s?parseInt(e):e;if(s&&(o+=i[a++]),a===i.length){n[c]=t;break}{let e=i[a++],t=e===`[`,s=n[c]||(t?[]:{});n[c]=s,n=s,r[o]=r[o]||function(e){return function(t){tv(e,t)}}(s),o+=e}}}function Q_(e,t){let n=0;function r(t,r,i){let a=r.name.endsWith(`[0]`),o=r.type,s=B[o];if(!s)throw Error(`unknown type: 0x${o.toString(16)}`);let c;if(s.bindPoint){let t=n;n+=r.size,c=a?s.arraySetter(e,o,t,i,r.size):s.setter(e,o,t,i,r.size)}else c=s.arraySetter&&a?s.arraySetter(e,i):s.setter(e,i);return c.location=i,c}let i={},a={},o=e.getProgramParameter(t,rg);for(let n=0;n<o;++n){let o=e.getActiveUniform(t,n);if(J_(o))continue;let s=o.name;s.endsWith(`[0]`)&&(s=s.substr(0,s.length-3));let c=e.getUniformLocation(t,o.name);if(c){let e=r(t,o,c);i[s]=e,Z_(s,e,a,i)}}return i}function $_(e,t){let n={},r=e.getProgramParameter(t,ag);for(let i=0;i<r;++i){let r=e.getTransformFeedbackVarying(t,i);n[r.name]={index:i,type:r.type,size:r.size}}return n}function ev(e,t){let n=e.getProgramParameter(t,rg),r=[],i=[];for(let a=0;a<n;++a){i.push(a),r.push({});let n=e.getActiveUniform(t,a);r[a].name=n.name}[[`UNIFORM_TYPE`,`type`],[`UNIFORM_SIZE`,`size`],[`UNIFORM_BLOCK_INDEX`,`blockNdx`],[`UNIFORM_OFFSET`,`offset`]].forEach(function(n){let a=n[0],o=n[1];e.getActiveUniforms(t,i,e[a]).forEach(function(e,t){r[t][o]=e})});let a={},o=e.getProgramParameter(t,og);for(let n=0;n<o;++n){let r=e.getActiveUniformBlockName(t,n),i={index:e.getUniformBlockIndex(t,r),usedByVertexShader:e.getActiveUniformBlockParameter(t,n,sg),usedByFragmentShader:e.getActiveUniformBlockParameter(t,n,cg),size:e.getActiveUniformBlockParameter(t,n,lg),uniformIndices:e.getActiveUniformBlockParameter(t,n,ug)};i.used=i.usedByVertexShader||i.usedByFragmentShader,a[r]=i}return{blockSpecs:a,uniformData:r}}function tv(e,t){for(let n in t){let r=e[n];typeof r==`function`?r(t[n]):tv(e[n],t[n])}}function nv(e,...t){let n=e.uniformSetters||e,r=t.length;for(let e=0;e<r;++e){let r=t[e];if(Array.isArray(r)){let e=r.length;for(let t=0;t<e;++t)nv(n,r[t])}else for(let e in r){let t=n[e];t&&t(r[e])}}}function rv(e,t){let n={},r=e.getProgramParameter(t,ig);for(let i=0;i<r;++i){let r=e.getActiveAttrib(t,i);if(J_(r))continue;let a=e.getAttribLocation(t,r.name),o=M_[r.type],s=o.setter(e,a,o);s.location=a,n[r.name]=s}return n}function iv(e,t){for(let n in t){let r=e[n];r&&r(t[n])}}function av(e,t,n){n.vertexArrayObject?e.bindVertexArray(n.vertexArrayObject):(iv(t.attribSetters||t,n.attribs),n.indices&&e.bindBuffer(Zh,n.indices))}function ov(e,t){let n=Q_(e,t),r=rv(e,t),i={program:t,uniformSetters:n,attribSetters:r,uniformLocations:Object.fromEntries(Object.entries(n).map(([e,t])=>[e,t.location])),attribLocations:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,t.location]))};return Lf(e)&&(i.uniformBlockSpec=ev(e,t),i.transformFeedbackInfo=$_(e,t)),i}var sv=36160,cv=6402,lv=33190,uv=36012,dv=35056,fv=36013,pv=32854,mv=32855,hv=36194,gv=33189,_v=6401,vv=36168,yv=34041,bv=36096,xv=36128,Sv=33306,Cv={};Cv[yv]=Sv,Cv[_v]=xv,Cv[vv]=xv,Cv[cv]=bv,Cv[gv]=bv,Cv[lv]=bv,Cv[uv]=bv,Cv[dv]=Sv,Cv[fv]=Sv;var wv={};wv[pv]=!0,wv[mv]=!0,wv[hv]=!0,wv[yv]=!0,wv[gv]=!0,wv[_v]=!0,wv[vv]=!0;function Tv(e,t,n){n||=sv,t?(e.bindFramebuffer(n,t.framebuffer),e.viewport(0,0,t.width,t.height)):(e.bindFramebuffer(n,null),e.viewport(0,0,e.drawingBufferWidth,e.drawingBufferHeight))}var Ev=new WeakMap;function Dv(e,t,n,r){let i=[],a=q_(e,[t,n],{errorCallback:e=>i.push(e)});if(!a)throw Error(`${r} shader: ${i.join(`
55
- `)||`Unable to link program`}`);let o=e.getAttachedShaders(a)??[];try{return Ev.set(a,ov(e,a)),a}catch(t){throw e.deleteProgram(a),t}finally{for(let t of o)e.deleteShader(t)}}function Ov(e){let t=Ev.get(e);if(!t)throw Error(`GPU program is not initialized or has been disposed`);return t}function kv(e,t){return Ov(e).uniformLocations[t.replace(/\[0\]$/,``)]??null}function Av(e,t){return Ov(e).attribLocations[t]??-1}function jv(e,t){nv(Ov(e),t)}function Mv(e,t,n){av(e,Ov(t),{attribs:n,numElements:0})}function Nv(e,t,n=e.STATIC_DRAW){let r=If(e,t,e.ARRAY_BUFFER,n);if(!r)throw Error(`Unable to allocate GPU vertex buffer`);return r}function Pv(e,t){Ev.delete(t),e.deleteProgram(t)}function Fv(e,t,n,r,i,a,o){let s=e.createTexture(),c=e.createFramebuffer();if(!s||!c)throw e.deleteTexture(s),e.deleteFramebuffer(c),Error(`Unable to allocate ${o}`);try{if(Kh(e,s,{width:t,height:n,internalFormat:r,format:e.RGBA,type:i}),Gh(e,s,{minMag:a,wrap:e.CLAMP_TO_EDGE}),e.bindFramebuffer(e.FRAMEBUFFER,c),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE)throw Error(`${o} framebuffer is incomplete`);return{texture:s,framebuffer:c}}catch(t){throw e.deleteTexture(s),e.deleteFramebuffer(c),t}}function Iv(e,t,n,r){Tv(e,t?{framebuffer:t.framebuffer,attachments:[t.texture],width:n,height:r}:null)}var Lv=3.2;function Rv(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}function zv(e){return{dissipation:.55+2.3*Rv(1.35,2.65,e),opacity:1-Rv(2.25,Lv,e)}}var Bv=class{gl;width;height;texture;framebuffer;disposed=!1;constructor(e,t,n,r,i,a){this.gl=e,this.width=n,this.height=r;let o=e.createTexture(),s=e.createFramebuffer();if(!o||!s)throw o&&e.deleteTexture(o),s&&e.deleteFramebuffer(s),Error(`Unable to allocate GPU checkpoint`);this.texture=o,this.framebuffer=s;let c=e.getParameter(e.READ_FRAMEBUFFER_BINDING),l=e.getParameter(e.DRAW_FRAMEBUFFER_BINDING),u=e.getParameter(e.TEXTURE_BINDING_2D);try{if(e.bindTexture(e.TEXTURE_2D,o),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,i,n,r,0,e.RGBA,a,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,s),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,o,0),e.checkFramebufferStatus(e.DRAW_FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE)throw Error(`GPU checkpoint target is incomplete`);if(e.bindFramebuffer(e.READ_FRAMEBUFFER,t),e.blitFramebuffer(0,0,n,r,0,0,n,r,e.COLOR_BUFFER_BIT,e.NEAREST),e.getError()!==e.NO_ERROR)throw Error(`GPU checkpoint copy failed`)}catch(t){throw e.deleteFramebuffer(s),e.deleteTexture(o),t}finally{e.bindFramebuffer(e.READ_FRAMEBUFFER,c),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,l),e.bindTexture(e.TEXTURE_2D,u)}}restore(e,t=this.width,n=this.height){if(this.disposed)throw Error(`GPU checkpoint has been disposed`);let r=this.gl,i=r.getParameter(r.READ_FRAMEBUFFER_BINDING),a=r.getParameter(r.DRAW_FRAMEBUFFER_BINDING);try{if(r.bindFramebuffer(r.READ_FRAMEBUFFER,this.framebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,e),r.blitFramebuffer(0,0,this.width,this.height,0,0,t,n,r.COLOR_BUFFER_BIT,r.NEAREST),r.getError()!==r.NO_ERROR)throw Error(`GPU checkpoint restore failed`)}finally{r.bindFramebuffer(r.READ_FRAMEBUFFER,i),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,a)}}dispose(){this.disposed||(this.disposed=!0,this.gl.deleteFramebuffer(this.framebuffer),this.gl.deleteTexture(this.texture))}},Vv=[214,216,215].map(e=>e/255),Hv={low:{simulation:96,dye:512,iterations:8},medium:{simulation:160,dye:960,iterations:14},high:{simulation:320,dye:1536,iterations:22}},Uv=`#version 300 es
56
- in vec2 aPosition;
57
- out vec2 vUv;
58
- void main() { vUv = aPosition * 0.5 + 0.5; gl_Position = vec4(aPosition, 0.0, 1.0); }`,V=`#version 300 es
59
- precision highp float;
60
- in vec2 vUv;
61
- out vec4 color;
62
- `,Wv=`#version 300 es
63
- in vec4 aStamp;
64
- in float aStrength;
65
- uniform vec2 canvasSize, dyeSize;
66
- out float strength;
67
- out float progress;
68
- void main() {
69
- gl_Position = vec4(aStamp.xy / canvasSize * vec2(2.0, -2.0)
70
- + vec2(-1.0, 1.0), 0.0, 1.0);
71
- gl_PointSize = max(1.0, aStamp.z * 2.0 * dyeSize.x / canvasSize.x);
72
- strength = aStrength * (1.0 - aStamp.w * 0.32);
73
- progress = aStamp.w;
74
- }`,Gv=`#version 300 es
75
- precision highp float;
76
- in float strength;
77
- in float progress;
78
- uniform bool agePalette;
79
- out vec4 color;
80
- void main() {
81
- vec2 point = gl_PointCoord * 2.0 - 1.0;
82
- float angle = atan(point.y, point.x);
83
- float contour = 1.0 + 0.08 * sin(angle * 5.0 + progress * 19.0)
84
- + 0.045 * sin(angle * 11.0 - progress * 31.0);
85
- float radius = dot(point, point) / (contour * contour);
86
- float outer = 1.0 - smoothstep(0.48, 0.88, radius);
87
- float middle = 1.0 - smoothstep(0.18, 0.62, radius);
88
- float core = 1.0 - smoothstep(0.035, 0.34, radius);
89
- if (agePalette) {
90
- float fuel = outer * strength * 1.15;
91
- // The weapon advances each fuel parcel across its range in about 0.3 s.
92
- // Seed that travel age at the GPU stamp, then let the shared solver carry
93
- // and age it. Fresh emission stays blue at the nozzle, not at the far tip.
94
- color = vec4(fuel, fuel * progress * 0.3, fuel * progress, 0.0);
95
- } else {
96
- color = vec4(outer * strength * 0.65,
97
- middle * strength * 1.55,
98
- core * strength * 2.2, 0.0);
99
- }
100
- }`,Kv=`
101
- uniform sampler2D uWalls;
102
- uniform bool hasWalls;
103
- bool isWall(vec2 uv) {
104
- if (!hasWalls) return false;
105
- return texture(uWalls, clamp(uv, vec2(0.0), vec2(1.0))).r > 0.5;
106
- }`,qv={copy:`${V}
107
- uniform sampler2D uTexture;
108
- void main() { color = texture(uTexture, vUv); }`,addFlame:`${V}
109
- uniform sampler2D uTarget, uSource;
110
- void main() { color = texture(uTarget, vUv) + texture(uSource, vUv); }`,splat:`${V}
111
- uniform sampler2D uTarget;
112
- uniform vec2 point, size;
113
- uniform vec4 value;
114
- uniform float radius;
115
- void main() {
116
- vec2 p = (vUv - point) * size;
117
- color = texture(uTarget, vUv) + value * exp(-dot(p, p) / max(radius * radius, 1.0));
118
- }`,splatBatch:`${V}
119
- uniform sampler2D uTarget;
120
- uniform vec2 size;
121
- uniform int count;
122
- uniform vec4 stamps[16];
123
- uniform vec4 values[16];
124
- void main() {
125
- vec4 contribution = vec4(0.0);
126
- for (int i = 0; i < 16; i++) {
127
- if (i >= count) break;
128
- vec2 p = (vUv - stamps[i].xy) * size;
129
- contribution += values[i] * exp(-dot(p, p) / max(stamps[i].z * stamps[i].z, 1.0));
130
- }
131
- color = texture(uTarget, vUv) + contribution;
132
- }`,splatSegment:`${V}
133
- uniform sampler2D uTarget;
134
- uniform vec2 start, end, size, radii;
135
- uniform vec4 value;
136
- void main() {
137
- vec2 pixel = vUv * size;
138
- vec2 a = start * size, b = end * size;
139
- vec2 axis = b - a;
140
- float along = clamp(dot(pixel - a, axis) / max(dot(axis, axis), 1.0), 0.0, 1.0);
141
- float radius = mix(radii.x, radii.y, along);
142
- vec2 offset = pixel - mix(a, b, along);
143
- color = texture(uTarget, vUv) + value *
144
- exp(-dot(offset, offset) / max(radius * radius, 1.0));
145
- }`,inkFlame:`${V}
146
- uniform sampler2D uInk;
147
- uniform vec2 uCanvasSize, uInkOrigin, uInkSize, uIgnition;
148
- uniform float uTime, uDt;
149
- void main() {
150
- vec2 point = vec2(vUv.x, 1.0 - vUv.y) * uCanvasSize;
151
- vec2 uv = (point - uInkOrigin) / uInkSize;
152
- if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
153
- color = vec4(0.0); return;
154
- }
155
- // Uint8Array rows are uploaded top-first into texture row zero.
156
- float ink = texture(uInk, uv).r;
157
- vec2 local = point - uInkOrigin;
158
- float irregularity = sin(local.x * 0.105 + local.y * 0.21) * 0.095 +
159
- sin(local.x * 0.27 - local.y * 0.09) * 0.055;
160
- float arrival = max(0.0, max(0.0, local.x - uIgnition.x) / 88.0 + irregularity);
161
- float age = uTime - arrival;
162
- float burning = smoothstep(-0.06, 0.12, age) *
163
- (1.0 - smoothstep(0.35, 0.75, age));
164
- float smoking = smoothstep(0.15, 0.36, age) *
165
- (1.0 - smoothstep(0.85, 1.28, age));
166
- float variation = 0.90 + 0.10 * sin(point.y * 0.19 + uTime * 7.0);
167
- float above = texture(uInk, vec2(uv.x, uv.y - 2.5 / uInkSize.y)).r;
168
- float upperEdge = max(0.0, ink - above);
169
- float fire = (ink * 0.30 + upperEdge * 1.55) * burning * variation * uDt * 5.2;
170
- color = vec4(fire * 0.75, fire * 1.4, fire * 1.9,
171
- ink * smoking * uDt * 4.8);
172
- }`,inkFlow:`${V}
173
- uniform sampler2D uVelocity;
174
- uniform vec2 uCanvasSize, uCellSize, uInkOrigin, uInkSize;
175
- uniform float uTime, uDt, uIgnitionX;
176
- void main() {
177
- vec2 point = vec2(vUv.x, 1.0 - vUv.y) * uCanvasSize;
178
- vec2 local = point - uInkOrigin;
179
- float front = min(uInkSize.x, uIgnitionX + uTime * 88.0);
180
- float widthGate = smoothstep(-24.0, 10.0, local.x) *
181
- (1.0 - smoothstep(front - 12.0, front + 38.0, local.x));
182
- float heightGate = exp(-pow((local.y - uInkSize.y * 0.38) / 65.0, 2.0));
183
- float envelope = widthGate * heightGate;
184
- float curl = sin(local.x * 0.086 - uTime * 3.1) *
185
- cos(local.y * 0.092 + uTime * 2.4);
186
- vec2 flow = vec2(25.0 * curl + 12.0 * sin(local.y * 0.14 - uTime * 3.8),
187
- -94.0 - 24.0 * sin(local.x * 0.11 + uTime * 2.7));
188
- vec2 velocity = texture(uVelocity, vUv).xy +
189
- vec2(flow.x / uCellSize.x, -flow.y / uCellSize.y) * uDt * 0.52 * envelope;
190
- color = vec4(velocity, 0.0, 1.0);
191
- }`,sceneInkFlame:`${V}
192
- uniform sampler2D uInk;
193
- uniform vec2 uCanvasSize, uOrigin;
194
- uniform vec4 uRect;
195
- uniform float uAngle, uAge, uFarthest, uSpreadSeconds, uBurnSeconds;
196
- uniform float uDt, uSmokeRate, uTime, uIntensity, uFixedRadius, uSmokeOnly;
197
- uniform float uBlastAge, uBlastSeconds;
198
- uniform bool uAgePalette;
199
- void main() {
200
- vec2 point = vec2(vUv.x, 1.0 - vUv.y) * uCanvasSize;
201
- vec2 center = uRect.xy + uRect.zw * 0.5;
202
- vec2 offset = point - center;
203
- float c = cos(uAngle), s = sin(uAngle);
204
- vec2 local = vec2(offset.x * c + offset.y * s,
205
- -offset.x * s + offset.y * c) + uRect.zw * 0.5;
206
- vec2 uv = local / uRect.zw;
207
- if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
208
- color = vec4(0.0); return;
209
- }
210
- float ink = texture(uInk, uv).r;
211
- float arrival = uFixedRadius > 0.0
212
- ? step(uFixedRadius, distance(point, uOrigin)) * 999.0
213
- : distance(point, uOrigin) / max(uFarthest, 1.0) * uSpreadSeconds;
214
- float progress = (uAge - arrival) / max(uBurnSeconds, 0.01);
215
- float burning = smoothstep(0.0, 0.06, progress) *
216
- (1.0 - smoothstep(0.78, 1.02, progress));
217
- float smoking = smoothstep(0.12, 0.32, progress) *
218
- (1.0 - smoothstep(0.90, 1.08, progress));
219
- float above = texture(uInk, vec2(uv.x,
220
- uv.y - 2.5 / max(uRect.w, 1.0))).r;
221
- float upperEdge = max(0.0, ink - above);
222
- float variation = 0.90 + 0.10 * sin(point.y * 0.19 + uTime * 7.0);
223
- if (uBlastAge >= 0.0) {
224
- float envelope = 1.0 - smoothstep(uBlastSeconds * 0.28,
225
- uBlastSeconds, uBlastAge);
226
- float flash = 1.0 - smoothstep(0.04, 0.17, uBlastAge);
227
- float fire = (ink * 0.85 + upperEdge * 0.5) * envelope *
228
- (1.0 + flash * 0.55) * variation * uDt * 38.0;
229
- if (uAgePalette) {
230
- float fuel = fire * 2.0;
231
- float smoke = ink * envelope * uDt * 7.0 * 0.3;
232
- color = vec4(fuel, fuel * 0.23, fuel * 0.55, smoke);
233
- return;
234
- }
235
- color = vec4(fire * 0.85, fire * 1.5, fire * 2.15,
236
- ink * envelope * uDt * 7.0);
237
- return;
238
- }
239
- float fire = (ink * 0.30 + upperEdge * 1.55) * burning * variation * uDt * 5.2 * uIntensity * (1.0 - uSmokeOnly);
240
- if (uAgePalette) {
241
- // Keep smoke in alpha so it cannot age and desaturate nearby live fire.
242
- // All four channels still ride the same velocity field and solve.
243
- float fuel = (ink * 0.14 + upperEdge * 1.55) * burning * variation *
244
- uDt * 5.2 * uIntensity * 4.0 * (1.0 - uSmokeOnly);
245
- float smokePresence = mix(smoking, max(smoking, smoothstep(0.02, 0.12, progress)), uSmokeOnly);
246
- float smoke = ink * smokePresence * uDt * 4.8 * uSmokeRate * mix(0.08, 0.8, uSmokeOnly);
247
- color = vec4(fuel, fuel * 0.24, fuel * 0.55, smoke);
248
- return;
249
- }
250
- color = vec4(fire * 0.75, fire * 1.4, fire * 1.9,
251
- ink * smoking * uDt * 4.8 * uSmokeRate);
252
- }`,sceneFlow:`${V}
253
- uniform sampler2D uVelocity, uDye;
254
- uniform vec2 uCanvasSize, uCellSize;
255
- uniform float uTime, uDt;
256
- void main() {
257
- vec2 point = vec2(vUv.x, 1.0 - vUv.y) * uCanvasSize;
258
- vec4 dye = max(texture(uDye, vUv), vec4(0.0));
259
- float heat = dot(dye.rgb, vec3(0.28, 0.22, 0.18));
260
- float activity = 1.0 - exp(-(heat + dye.a * 1.4) * 3.0);
261
- float eddy = sin(point.x * 0.086 - uTime * 3.1) *
262
- cos(point.y * 0.092 + uTime * 2.4);
263
- vec2 flow = vec2(42.0 * eddy + 12.0 * sin(point.y * 0.14 - uTime * 3.8),
264
- -310.0 - 78.0 * clamp(heat, 0.0, 1.0));
265
- vec2 velocity = texture(uVelocity, vUv).xy +
266
- vec2(flow.x / uCellSize.x, -flow.y / uCellSize.y) * uDt * 0.85 * activity;
267
- color = vec4(velocity, 0.0, 1.0);
268
- }`,radialBlast:`${V}
269
- uniform sampler2D uVelocity;
270
- uniform vec2 uCanvasSize, uCellSize, uCenter;
271
- uniform float uRadius;
272
- void main() {
273
- vec2 point = vec2(vUv.x, 1.0 - vUv.y) * uCanvasSize;
274
- vec2 offset = point - uCenter;
275
- float distanceFromCenter = length(offset);
276
- float envelope = 1.0 - smoothstep(uRadius * 0.18, uRadius, distanceFromCenter);
277
- vec2 direction = offset / max(distanceFromCenter, 1.0);
278
- vec2 impulse = direction * min(uRadius, 180.0) * 2.4 * envelope;
279
- vec2 velocity = texture(uVelocity, vUv).xy +
280
- vec2(impulse.x / uCellSize.x, -impulse.y / uCellSize.y);
281
- color = vec4(velocity, 0.0, 1.0);
282
- }`,flameSource:`${V}
283
- uniform sampler2D uTarget;
284
- uniform vec2 start, end, size;
285
- uniform vec3 radii, strengths;
286
- uniform float time;
287
- void main() {
288
- vec2 pixel = vUv * size;
289
- vec2 a = start * size, b = end * size;
290
- vec2 axis = b - a;
291
- float along = clamp(dot(pixel - a, axis) / max(dot(axis, axis), 1.0), 0.0, 1.0);
292
- vec2 side = normalize(vec2(-axis.y, axis.x) + vec2(0.0001));
293
- float tip = along * along;
294
- float weave = tip * (4.0 * sin(along * 12.0 - time * 7.0)
295
- + 1.5 * sin(along * 27.0 + time * 5.0));
296
- vec2 offset = pixel - mix(a, b, along) - side * weave;
297
- float edge = mix(1.0, 1.0 + 0.23 * sin(along * 24.0 - time * 8.0)
298
- + 0.12 * sin(along * 39.0 + time * 6.0), tip);
299
- float fade = 1.0 - smoothstep(0.93, 1.0, along);
300
- vec3 radius = max(mix(vec3(7.0, 5.0, 3.0), radii, along) * edge,
301
- vec3(1.0));
302
- vec3 density = strengths * fade * exp(-dot(offset, offset) / (radius * radius));
303
- color = texture(uTarget, vUv) + vec4(density, 0.0);
304
- }`,flameEddies:`${V}
305
- uniform sampler2D uTarget;
306
- uniform vec2 start, end, size, cellSize;
307
- uniform float time, dt;
308
- void main() {
309
- vec2 pixel = vec2(vUv.x, 1.0 - vUv.y) * size;
310
- vec2 axis = end - start;
311
- vec2 side = normalize(vec2(-axis.y, axis.x) + vec2(0.0001));
312
- vec2 centerA = mix(start, end, 0.72) + side * sin(time * 5.2) * 7.0;
313
- vec2 centerB = mix(start, end, 0.92) - side * cos(time * 4.1) * 9.0;
314
- vec2 a = pixel - centerA, b = pixel - centerB;
315
- float falloffA = exp(-dot(a, a) / (34.0 * 34.0));
316
- float falloffB = exp(-dot(b, b) / (29.0 * 29.0));
317
- vec2 spin = vec2(-a.y, a.x) * falloffA * 0.14
318
- - vec2(-b.y, b.x) * falloffB * 0.17;
319
- vec2 velocity = texture(uTarget, vUv).xy
320
- + vec2(spin.x / cellSize.x, -spin.y / cellSize.y) * dt;
321
- color = vec4(velocity, 0.0, 0.0);
322
- }`,body:`${V}
323
- uniform sampler2D uVelocity;
324
- uniform vec2 size, texelSize, center, forward, halfSize, motion;
325
- uniform float spin, bodyInfluence;
326
- void main() {
327
- vec2 pixel = vec2(vUv.x, 1.0 - vUv.y) * size;
328
- vec2 offset = pixel - center;
329
- vec2 side = vec2(-forward.y, forward.x);
330
- float along = dot(offset, forward);
331
- float across = dot(offset, side);
332
- float longPart = along / max(halfSize.x, 1.0);
333
- float sidePart = across / max(halfSize.y, 1.0);
334
- // Rounded body envelope keeps smoke moving around the vehicle.
335
- float shape = sqrt(pow(abs(longPart), 4.0) + sidePart * sidePart);
336
- vec2 cellSize = size * texelSize;
337
- vec2 existing = texture(uVelocity, vUv).xy * cellSize;
338
- if (shape > 1.75) { color = vec4(existing / cellSize, 0.0, 1.0); return; }
339
- vec2 moving = motion + vec2(-offset.y, offset.x) * spin;
340
- if (shape < 1.0) {
341
- color = vec4(mix(existing, moving, bodyInfluence) / cellSize, 0.0, 1.0);
342
- return;
343
- }
344
- vec2 gradient = forward * (4.0 * longPart * abs(longPart) * abs(longPart) / max(halfSize.x, 1.0))
345
- + side * (2.0 * sidePart / max(halfSize.y, 1.0));
346
- vec2 normal = normalize(gradient + vec2(0.00001));
347
- float speed = length(motion) + abs(spin) * halfSize.y * 0.4;
348
- float frontPush = max(dot(moving, normal), 0.0) * 0.55;
349
- float sidePush = speed * 0.18;
350
- vec2 wake = along < 0.0 ? moving * 0.14 : vec2(0.0);
351
- vec2 target = moving * 0.24 + normal * (frontPush + sidePush) + wake;
352
- float influence = 1.0 - smoothstep(1.0, 1.75, shape);
353
- vec2 nextVelocity = mix(existing, target, influence * 0.78 * bodyInfluence);
354
- color = vec4(nextVelocity / cellSize, 0.0, 1.0);
355
- }`,align:`${V}
356
- uniform sampler2D uSource;
357
- uniform vec2 size, oldOrigin, nextOrigin, oldScale, nextScale;
358
- void main() {
359
- vec2 nextPixel = vec2(vUv.x, 1.0 - vUv.y) * size;
360
- vec2 physical = (nextPixel - nextOrigin) / nextScale;
361
- vec2 oldPixel = oldOrigin + physical * oldScale;
362
- vec2 uv = vec2(oldPixel.x / size.x, 1.0 - oldPixel.y / size.y);
363
- color = uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0
364
- ? vec4(0.0) : texture(uSource, uv);
365
- }`,clear:`${V}
366
- uniform sampler2D uTexture;
367
- uniform float value;
368
- void main() { color = texture(uTexture, vUv) * value; }`,curl:`${V}
369
- uniform sampler2D uVelocity;
370
- uniform vec2 texelSize;
371
- void main() {
372
- float l = texture(uVelocity, vUv - vec2(texelSize.x, 0.0)).y;
373
- float r = texture(uVelocity, vUv + vec2(texelSize.x, 0.0)).y;
374
- float t = texture(uVelocity, vUv + vec2(0.0, texelSize.y)).x;
375
- float b = texture(uVelocity, vUv - vec2(0.0, texelSize.y)).x;
376
- color = vec4(0.5 * (r - l - t + b), 0.0, 0.0, 1.0);
377
- }`,vorticity:`${V}
378
- uniform sampler2D uVelocity, uCurl;
379
- uniform vec2 texelSize;
380
- uniform float curl, dt;
381
- void main() {
382
- float l = texture(uCurl, vUv - vec2(texelSize.x, 0.0)).x;
383
- float r = texture(uCurl, vUv + vec2(texelSize.x, 0.0)).x;
384
- float t = texture(uCurl, vUv + vec2(0.0, texelSize.y)).x;
385
- float b = texture(uCurl, vUv - vec2(0.0, texelSize.y)).x;
386
- float c = texture(uCurl, vUv).x;
387
- vec2 force = 0.5 * vec2(abs(t) - abs(b), abs(r) - abs(l));
388
- force = force / (length(force) + 0.0001) * curl * c;
389
- force.y *= -1.0;
390
- vec2 velocity = clamp(texture(uVelocity, vUv).xy + force * dt, vec2(-1000.0), vec2(1000.0));
391
- color = vec4(velocity, 0.0, 1.0);
392
- }`,divergence:`${V}${Kv}
393
- uniform sampler2D uVelocity;
394
- uniform vec2 texelSize;
395
- void main() {
396
- if (isWall(vUv)) { color = vec4(0.0); return; }
397
- vec2 c = texture(uVelocity, vUv).xy;
398
- float l = texture(uVelocity, vUv - vec2(texelSize.x, 0.0)).x;
399
- float r = texture(uVelocity, vUv + vec2(texelSize.x, 0.0)).x;
400
- float t = texture(uVelocity, vUv + vec2(0.0, texelSize.y)).y;
401
- float b = texture(uVelocity, vUv - vec2(0.0, texelSize.y)).y;
402
- if (vUv.x < texelSize.x) l = -c.x;
403
- if (vUv.x > 1.0 - texelSize.x) r = -c.x;
404
- if (vUv.y > 1.0 - texelSize.y) t = -c.y;
405
- if (vUv.y < texelSize.y) b = -c.y;
406
- if (isWall(vUv - vec2(texelSize.x, 0.0))) l = -c.x;
407
- if (isWall(vUv + vec2(texelSize.x, 0.0))) r = -c.x;
408
- if (isWall(vUv + vec2(0.0, texelSize.y))) t = -c.y;
409
- if (isWall(vUv - vec2(0.0, texelSize.y))) b = -c.y;
410
- color = vec4(0.5 * (r - l + t - b), 0.0, 0.0, 1.0);
411
- }`,pressure:`${V}${Kv}
412
- uniform sampler2D uPressure, uDivergence;
413
- uniform vec2 texelSize;
414
- void main() {
415
- if (isWall(vUv)) { color = vec4(0.0); return; }
416
- float p = texture(uPressure, vUv).x;
417
- float l = texture(uPressure, vUv - vec2(texelSize.x, 0.0)).x;
418
- float r = texture(uPressure, vUv + vec2(texelSize.x, 0.0)).x;
419
- float t = texture(uPressure, vUv + vec2(0.0, texelSize.y)).x;
420
- float b = texture(uPressure, vUv - vec2(0.0, texelSize.y)).x;
421
- if (isWall(vUv - vec2(texelSize.x, 0.0))) l = p;
422
- if (isWall(vUv + vec2(texelSize.x, 0.0))) r = p;
423
- if (isWall(vUv + vec2(0.0, texelSize.y))) t = p;
424
- if (isWall(vUv - vec2(0.0, texelSize.y))) b = p;
425
- float divergence = texture(uDivergence, vUv).x;
426
- color = vec4((l + r + t + b - divergence) * 0.25, 0.0, 0.0, 1.0);
427
- }`,gradient:`${V}${Kv}
428
- uniform sampler2D uPressure, uVelocity;
429
- uniform vec2 texelSize;
430
- void main() {
431
- if (isWall(vUv)) { color = vec4(0.0); return; }
432
- float p = texture(uPressure, vUv).x;
433
- float l = texture(uPressure, vUv - vec2(texelSize.x, 0.0)).x;
434
- float r = texture(uPressure, vUv + vec2(texelSize.x, 0.0)).x;
435
- float t = texture(uPressure, vUv + vec2(0.0, texelSize.y)).x;
436
- float b = texture(uPressure, vUv - vec2(0.0, texelSize.y)).x;
437
- if (isWall(vUv - vec2(texelSize.x, 0.0))) l = p;
438
- if (isWall(vUv + vec2(texelSize.x, 0.0))) r = p;
439
- if (isWall(vUv + vec2(0.0, texelSize.y))) t = p;
440
- if (isWall(vUv - vec2(0.0, texelSize.y))) b = p;
441
- vec2 velocity = texture(uVelocity, vUv).xy - vec2(r - l, t - b);
442
- if (isWall(vUv - vec2(texelSize.x, 0.0))) velocity.x = max(velocity.x, 0.0);
443
- if (isWall(vUv + vec2(texelSize.x, 0.0))) velocity.x = min(velocity.x, 0.0);
444
- if (isWall(vUv + vec2(0.0, texelSize.y))) velocity.y = min(velocity.y, 0.0);
445
- if (isWall(vUv - vec2(0.0, texelSize.y))) velocity.y = max(velocity.y, 0.0);
446
- color = vec4(velocity, 0.0, 1.0);
447
- }`,advection:`${V}${Kv}
448
- uniform sampler2D uVelocity, uSource;
449
- uniform vec2 velocityTexel, sourceTexel;
450
- uniform vec4 dissipation;
451
- uniform float dt;
452
- uniform bool ageDye;
453
- vec4 bilerp(sampler2D image, vec2 uv, vec2 texel) {
454
- vec2 st = uv / texel - 0.5;
455
- vec2 base = floor(st), fraction = fract(st);
456
- vec4 a = texture(image, (base + vec2(0.5, 0.5)) * texel);
457
- vec4 b = texture(image, (base + vec2(1.5, 0.5)) * texel);
458
- vec4 c = texture(image, (base + vec2(0.5, 1.5)) * texel);
459
- vec4 d = texture(image, (base + vec2(1.5, 1.5)) * texel);
460
- return mix(mix(a, b, fraction.x), mix(c, d, fraction.x), fraction.y);
461
- }
462
- void main() {
463
- if (isWall(vUv)) { color = vec4(0.0); return; }
464
- vec2 velocity = bilerp(uVelocity, vUv, velocityTexel).xy;
465
- vec2 coord = vUv - dt * velocity * velocityTexel;
466
- if (isWall(coord) || isWall(mix(vUv, coord, 0.5))) coord = vUv;
467
- color = bilerp(uSource, coord, sourceTexel) / (vec4(1.0) + dissipation * dt);
468
- if (ageDye) {
469
- color.g += color.r * dt;
470
- float fuel = color.r;
471
- float age = color.g / max(fuel, 0.0001);
472
- float burned = fuel * smoothstep(0.5, 0.85, age) * min(dt * 3.2, 1.0);
473
- color.rgb *= (fuel - burned) / max(fuel, 0.0001);
474
- color.a += burned * 0.65;
475
- }
476
- }`,ghostDisplay:`${V}${Kv}
477
- uniform sampler2D uDye;
478
- uniform vec3 smokeColor;
479
- uniform bool darkBackground;
480
- uniform int ghostStyle;
481
- void main() {
482
- // The dye is a moving volume, not a gray sprite overlay. Reconstruct it at
483
- // display resolution so the silhouette stays smooth at every quality mode.
484
- vec2 dyeSize = vec2(textureSize(uDye, 0));
485
- vec2 pixel = vUv * dyeSize - 0.5;
486
- vec2 base = floor(pixel);
487
- vec2 fraction = fract(pixel);
488
- vec2 low = (base + 0.5) / dyeSize;
489
- vec2 high = (base + 1.5) / dyeSize;
490
- float density = mix(
491
- mix(texture(uDye, vec2(low.x, low.y)).r, texture(uDye, vec2(high.x, low.y)).r, fraction.x),
492
- mix(texture(uDye, vec2(low.x, high.y)).r, texture(uDye, vec2(high.x, high.y)).r, fraction.x),
493
- fraction.y);
494
- if (isWall(vUv)) density = 0.0;
495
- density = max(0.0, density);
496
-
497
- // Screen-space density gradients give the vapor a lit edge without an
498
- // additional render target or another fluid pass.
499
- vec2 slope = vec2(dFdx(density), dFdy(density));
500
- float edge = clamp(length(slope) * 15.0, 0.0, 1.0);
501
- vec3 normal = normalize(vec3(-slope * 8.0, 0.7));
502
- float facingLight = max(0.0, dot(normal, normalize(vec3(-0.55, -0.7, 0.8))));
503
- float rim = edge * pow(facingLight, 1.7) * (1.0 - smoothstep(0.9, 2.8, density));
504
- float shadedRim = edge * (1.0 - facingLight) *
505
- (1.0 - smoothstep(0.9, 2.8, density));
506
- float body = smoothstep(0.02, 0.36, density);
507
- float fringe = smoothstep(0.01, 0.13, density) *
508
- (1.0 - smoothstep(0.23, 0.7, density));
509
-
510
- // All three looks read the same fluid field. Only the final material changes.
511
- float specter = 1.0 - step(0.5, float(ghostStyle));
512
- float phantom = 1.0 - step(0.5, abs(float(ghostStyle) - 1.0));
513
- float wraith = 1.0 - specter - phantom;
514
- float tight = smoothstep(0.09, 0.5, density);
515
- float fineEdge = smoothstep(0.04, 0.23, density) *
516
- (1.0 - smoothstep(0.4, 0.95, density));
517
-
518
- // The tint also identifies the theme, so saved fields and older callers
519
- // remain correct even when they omit the background argument.
520
- bool pale = darkBackground || dot(smokeColor, vec3(0.2126, 0.7152, 0.0722)) > 0.5;
521
- if (pale) {
522
- vec3 shade = vec3(0.67, 0.70, 0.76);
523
- vec3 white = vec3(0.98, 0.985, 1.0);
524
- vec3 rgb = mix(shade, white, smoothstep(0.12, 0.95, density));
525
- rgb = mix(rgb, vec3(0.48, 0.52, 0.60), min(0.5, shadedRim * 0.5));
526
- rgb = mix(rgb, vec3(1.0), min(0.42, rim * 0.42));
527
- float alpha = min(0.63, body * 0.52 + fringe * 0.06 + rim * 0.06);
528
- // Specter is compact and luminous; Phantom preserves the sprite's edges;
529
- // Wraith is the more transparent, drifting interpretation.
530
- alpha = specter * min(0.8, tight * 0.73 + fineEdge * 0.08 + rim * 0.14)
531
- + phantom * min(0.58, tight * 0.37 + fineEdge * 0.13 + rim * 0.14)
532
- + wraith * alpha;
533
- rgb = mix(rgb, vec3(1.0), specter * min(0.55, rim * 0.55));
534
- color = vec4(rgb, alpha);
535
- } else {
536
- vec3 ink = vec3(0.012, 0.015, 0.021);
537
- vec3 glint = vec3(0.94, 0.96, 0.99);
538
- vec3 rgb = mix(ink, vec3(0.075, 0.09, 0.11), fringe * 0.42);
539
- rgb = mix(rgb, glint, min(0.94, rim * 1.12));
540
- float alpha = min(0.7, body * 0.62 + fringe * 0.06 + rim * 0.07);
541
- alpha = specter * min(0.96, tight * 0.93 + fineEdge * 0.05 + rim * 0.08)
542
- + phantom * min(0.58, tight * 0.4 + fineEdge * 0.13 + rim * 0.13)
543
- + wraith * alpha;
544
- rgb = mix(rgb, glint, specter * min(0.8, rim * 0.8));
545
- color = vec4(rgb, alpha);
546
- }
547
- }`,display:`${V}${Kv}
548
- uniform sampler2D uDye;
549
- uniform vec3 smokeColor;
550
- uniform bool flamePalette, darkBackground, agePalette;
551
- uniform vec2 flameOrigin, size;
552
- uniform float lifecycleOpacity;
553
- ${yc}
554
- void main() {
555
- vec2 dyeSize = vec2(textureSize(uDye, 0));
556
- vec2 pixel = vUv * dyeSize - 0.5;
557
- vec2 base = floor(pixel);
558
- vec2 fraction = fract(pixel);
559
- vec2 low = (base + 0.5) / dyeSize;
560
- vec2 high = (base + 1.5) / dyeSize;
561
- vec4 material = mix(
562
- mix(texture(uDye, vec2(low.x, low.y)), texture(uDye, vec2(high.x, low.y)), fraction.x),
563
- mix(texture(uDye, vec2(low.x, high.y)), texture(uDye, vec2(high.x, high.y)), fraction.x),
564
- fraction.y);
565
- material = isWall(vUv) ? vec4(0.0) : max(material, vec4(0.0));
566
- vec3 density = material.rgb;
567
- if (!flamePalette) {
568
- // Unlit tire smoke reads as grey volume at night; beams supply localized brightness.
569
- vec3 ambientSmoke = smokeColor * (darkBackground ? 0.52 : 1.0);
570
- vec3 litSmoke = scatterVehicleLight(ambientSmoke, density.r, vec2(vUv.x, 1.0 - vUv.y) * size, darkBackground);
571
- color = vec4(litSmoke, min(1.0 - exp(-density.r * 0.9), 0.82));
572
- return;
573
- }
574
- if (agePalette) {
575
- // R is fuel, G its weighted age, B its travel, and A is separate smoke.
576
- // Burning fuel remains colored even while smoke overlaps it.
577
- float age = clamp(material.g / max(material.r, 0.0001), 0.0, 1.5);
578
- float travel = clamp(material.b / max(material.r, 0.0001), 0.0, 1.0);
579
- float visible = smoothstep(0.045, 0.7, material.r);
580
- float hotCore = smoothstep(0.2, 1.0, material.r) *
581
- smoothstep(0.045, 0.12, age) * (1.0 - smoothstep(0.43, 0.7, age));
582
- vec3 blue = darkBackground ? vec3(0.17, 0.65, 1.0) : vec3(0.07, 0.38, 0.82);
583
- vec3 rim = darkBackground ? vec3(0.88, 0.20, 0.035) : vec3(0.77, 0.17, 0.025);
584
- vec3 orange = darkBackground ? vec3(1.0, 0.56, 0.065) : vec3(0.94, 0.42, 0.025);
585
- vec3 yellow = darkBackground ? vec3(1.0, 0.84, 0.28) : vec3(1.0, 0.72, 0.13);
586
- vec3 ash = darkBackground ? vec3(0.37, 0.30, 0.27) : vec3(0.30, 0.26, 0.24);
587
- ash = scatterVehicleLight(ash, material.a, vec2(vUv.x, 1.0 - vUv.y) * size, darkBackground);
588
- vec3 rgb = mix(rim, orange, smoothstep(0.06, 0.42, material.r));
589
- rgb = mix(rgb, yellow, hotCore * 0.88);
590
- rgb = mix(rgb, vec3(1.0, 0.96, 0.76), hotCore * hotCore * 0.52);
591
- float fresh = 1.0 - smoothstep(0.035, 0.20, travel);
592
- rgb = mix(rgb, blue, fresh);
593
- float ignition = smoothstep(0.012, 0.055, age);
594
- float cooling = 1.0 - smoothstep(0.7, 1.1, age);
595
- float nozzleAlpha = mix(0.22, 1.0, smoothstep(0.015, 0.12, travel));
596
- float bodyAlpha = min(0.95, visible * 1.15) * ignition * cooling * nozzleAlpha;
597
- bodyAlpha *= lifecycleOpacity;
598
- float smokeAlpha = min(0.42, 1.0 - exp(-material.a * 0.48)) * lifecycleOpacity;
599
-
600
- // A small halo comes from neighboring *burning* fluid. The same field
601
- // supplies it, with no blur target or extra simulation/render pass.
602
- vec2 nearX = vec2(11.0, 0.0) / size;
603
- vec2 nearY = vec2(0.0, 11.0) / size;
604
- vec2 farX = vec2(21.0, 0.0) / size;
605
- vec2 farY = vec2(0.0, 21.0) / size;
606
- vec4 nearFuel = (texture(uDye, vUv + nearX) + texture(uDye, vUv - nearX)
607
- + texture(uDye, vUv + nearY) + texture(uDye, vUv - nearY)) * 0.25;
608
- vec4 farFuel = (texture(uDye, vUv + farX) + texture(uDye, vUv - farX)
609
- + texture(uDye, vUv + farY) + texture(uDye, vUv - farY)) * 0.25;
610
- vec4 glowField = mix(nearFuel, farFuel, 0.4);
611
- float glowAge = glowField.g / max(glowField.r, 0.0001);
612
- float glowTravel = glowField.b / max(glowField.r, 0.0001);
613
- float burning = smoothstep(0.04, 0.11, glowAge) *
614
- (1.0 - smoothstep(0.52, 0.82, glowAge));
615
- float haloAlpha = (1.0 - exp(-glowField.r * 0.68)) * burning * 0.33;
616
- haloAlpha *= 1.0 - smoothstep(0.06, 0.48, material.r);
617
- haloAlpha *= lifecycleOpacity;
618
- vec3 haloRgb = mix(orange, blue,
619
- (1.0 - smoothstep(0.02, 0.25, glowTravel)) * 0.7);
620
- float litAlpha = bodyAlpha + haloAlpha * (1.0 - bodyAlpha);
621
- vec3 lit = (rgb * bodyAlpha + haloRgb * haloAlpha * (1.0 - bodyAlpha)) /
622
- max(litAlpha, 0.0001);
623
- float alpha = litAlpha + smokeAlpha * (1.0 - litAlpha);
624
- color = vec4((lit * litAlpha + ash * smokeAlpha * (1.0 - litAlpha)) /
625
- max(alpha, 0.0001), alpha);
626
- return;
627
- }
628
- vec3 rim = darkBackground ? vec3(0.92, 0.28, 0.025) : vec3(0.85, 0.25, 0.015);
629
- vec3 orange = darkBackground ? vec3(1.0, 0.55, 0.045) : vec3(0.98, 0.44, 0.015);
630
- vec3 hot = darkBackground ? vec3(1.0, 0.87, 0.35) : vec3(1.0, 0.77, 0.19);
631
- vec3 rgb = mix(rim, orange, smoothstep(0.04, 0.35, density.g));
632
- rgb = mix(rgb, hot, smoothstep(0.1, 0.62, density.b));
633
- rgb = mix(rgb, vec3(1.0, 0.97, 0.82),
634
- smoothstep(0.75, 1.65, density.b) * 0.72);
635
- float ignition = 1.0 - smoothstep(8.0, 32.0,
636
- length(vUv * size - flameOrigin));
637
- rgb = mix(rgb, vec3(0.28, 0.65, 1.0), ignition * 0.68);
638
- float heat = dot(density, vec3(0.8, 1.0, 1.25));
639
- float flameAlpha = smoothstep(0.1, 0.43, heat) *
640
- min(0.98, 0.7 + heat * 0.17);
641
- float smokeAlpha = min(1.0 - exp(-material.a * 0.82), 0.72) * (1.0 - flameAlpha);
642
- float alpha = flameAlpha + smokeAlpha;
643
- vec3 smoke = darkBackground ? vec3(0.57, 0.58, 0.57) : vec3(0.39, 0.40, 0.39);
644
- smoke = scatterVehicleLight(smoke, material.a, vec2(vUv.x, 1.0 - vUv.y) * size, darkBackground);
645
- color = vec4((rgb * flameAlpha + smoke * smokeAlpha) / max(alpha, 0.0001),
646
- alpha * lifecycleOpacity);
647
- }`},Jv=class{quality;tint;vorticity;flamePalette;flameSmokeTail;ghostPalette;agePalette;ghostStyle=`phantom`;batchStamps=new Float32Array(64);batchValues=new Float32Array(64);canvas=document.createElement(`canvas`);gl;programs={};quad;positions={};lightPositions=new Float32Array(48);lightShapes=new Float32Array(48);lightColors=new Float32Array(48);flameStampProgram=null;flameStampBuffer=null;flameSource=null;flameInk=null;sceneInk=new Map;flameStampData=new Float32Array(10240);simulation;dyeSize;velocity;dye;pressure;curl;divergence;wallTexture=null;wallPixels=new Uint8Array;wallNext=new Uint8Array;hasWalls=!1;allSurfaces=[];width=1;height=1;pixelRatio=1;presentationPixelRatio;view=null;active=!1;sceneFireActive=!1;radialBlasts=[];idle=0;lost=!1;flameOrigin={x:0,y:0};gpuTimer=null;beginGpu(e){}endGpu(){this.gpuTimer?.end()}captureState(){if(this.lost)throw Error(`Cannot checkpoint a lost fluid context`);let e=this.gl,t=this.active||this.sceneFireActive||this.radialBlasts.length>0,n=t?new Bv(e,this.velocity.read.framebuffer,this.velocity.read.width,this.velocity.read.height,e.RGBA16F,e.HALF_FLOAT):null,r=null;try{r=t?new Bv(e,this.dye.read.framebuffer,this.dye.read.width,this.dye.read.height,e.RGBA16F,e.HALF_FLOAT):null}catch(e){throw n?.dispose(),e}return{velocity:n,dye:r,width:this.width,height:this.height,quality:this.quality,view:E(this.view),active:this.active,sceneFireActive:this.sceneFireActive,idle:this.idle,radialBlasts:E(this.radialBlasts),flameOrigin:E(this.flameOrigin),dispose:()=>{n?.dispose(),r?.dispose()}}}restoreState(e){if(this.lost)throw Error(`Cannot restore a lost fluid context`);this.quality=e.quality,this.resize(e.width,e.height,!0),this.reset(),e.velocity?.restore(this.velocity.read.framebuffer,this.velocity.read.width,this.velocity.read.height),e.dye?.restore(this.dye.read.framebuffer,this.dye.read.width,this.dye.read.height),this.view=E(e.view),this.active=e.active,this.sceneFireActive=e.sceneFireActive,this.idle=e.idle,this.radialBlasts=E(e.radialBlasts),this.flameOrigin=E(e.flameOrigin)}constructor(e,t,n,r=`natural`,i=18,a=!1,o=!1,s=!1,c=!1){this.quality=n,this.tint=r,this.vorticity=i,this.flamePalette=a,this.flameSmokeTail=o,this.ghostPalette=s,this.agePalette=c;let l=this.canvas.getContext(`webgl2`,{alpha:!0,depth:!1,stencil:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!0});if(!l||!l.getExtension(`EXT_color_buffer_float`))throw Error(`Float WebGL2 render targets are unavailable`);this.gl=l,this.canvas.addEventListener(`webglcontextlost`,e=>{e.preventDefault(),this.lost=!0}),this.quad=Nv(l,new Float32Array([-1,-1,1,-1,-1,1,1,1]));for(let[e,t]of Object.entries(qv)){if((e===`inkFlame`||e===`inkFlow`||e===`sceneInkFlame`||e===`sceneFlow`)&&!this.flameSmokeTail||e===`ghostDisplay`&&!this.ghostPalette)continue;let n=Dv(l,Uv,t,`Fluid ${e}`);this.programs[e]=n,this.positions[e]=Av(n,`aPosition`)}for(let e of[`vehicleLightPosition[0]`,`vehicleLightShape[0]`,`vehicleLightColor[0]`])this.uniform(`display`,e);if(this.flamePalette){let e=Dv(l,Wv,Gv,`Flame stamps`),t=l.createBuffer();if(!t)throw Pv(l,e),Error(`Unable to allocate flame stamps`);this.flameStampProgram=e,this.flameStampBuffer=t}this.resize(e,t)}get resolution(){return{quality:this.quality,cols:this.simulation.width,rows:this.simulation.height,engine:`WebGL2`}}get available(){return!this.lost}dispose(){if(!this.lost){this.gpuTimer?.dispose();for(let e of this.allSurfaces)this.gl.deleteTexture(e.texture),this.gl.deleteFramebuffer(e.framebuffer);for(let e of Object.values(this.programs))Pv(this.gl,e);for(let e of this.sceneInk.values())this.gl.deleteTexture(e.texture);this.flameInk&&this.gl.deleteTexture(this.flameInk.texture),this.wallTexture&&this.gl.deleteTexture(this.wallTexture),this.flameStampProgram&&Pv(this.gl,this.flameStampProgram),this.flameStampBuffer&&this.gl.deleteBuffer(this.flameStampBuffer),this.gl.deleteBuffer(this.quad),this.gl.getExtension(`WEBGL_lose_context`)?.loseContext(),this.lost=!0}}get managedBytes(){return this.active&&!this.lost?this.allSurfaces.reduce((e,t)=>e+t.width*t.height*t.bytesPerPixel,0)+this.wallPixels.byteLength+this.wallNext.byteLength+[...this.sceneInk.values()].reduce((e,t)=>e+t.width*t.height,0):0}get hasSceneFire(){return this.sceneFireActive}activateBuoyancy(){this.sceneFireActive=!0}queueRadialBlast(e,t){this.radialBlasts.push({center:e,radius:t}),this.sceneFireActive=!0}setTint(e){this.tint=e}setGhostStyle(e){this.ghostStyle=e}get running(){return this.active&&!this.lost}setQuality(e){e!==this.quality&&(this.quality=e,this.lost||this.resize(this.width,this.height,!0))}use(e){let t=this.gl,n=this.programs[e];t.useProgram(n),t.bindBuffer(t.ARRAY_BUFFER,this.quad);let r=this.positions[e];t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0)}uniform(e,t){return kv(this.programs[e],t)}texture(e,t,n,r){let i=this.gl;i.activeTexture(i.TEXTURE0+r),i.bindTexture(i.TEXTURE_2D,n.texture),i.uniform1i(this.uniform(e,t),r)}bindWalls(e){let t=this.gl;t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.wallTexture),t.uniform1i(this.uniform(e,`uWalls`),2),t.uniform1i(this.uniform(e,`hasWalls`),Number(this.hasWalls))}vec2(e,t,n,r){this.gl.uniform2f(this.uniform(e,t),n,r)}draw(e){let t=this.gl;Iv(t,e,e?.width??this.canvas.width,e?.height??this.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),this.flamePalette}surface(e,t,n=!1){let r=this.gl,i={...Fv(r,e,t,n?r.RGBA8:r.RGBA16F,n?r.UNSIGNED_BYTE:r.HALF_FLOAT,r.NEAREST,`Fluid render target`),width:e,height:t,bytesPerPixel:n?4:8};return this.allSurfaces.push(i),r.viewport(0,0,e,t),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),i}pair(e,t){let n={read:this.surface(e,t),write:this.surface(e,t),swap:()=>{[n.read,n.write]=[n.write,n.read]}};return n}scaled(e){let t=this.presentationPixelRatio===void 0?this.width/this.height:this.canvas.width/this.canvas.height;return t>=1?{width:e,height:Math.max(1,Math.round(e/t))}:{width:Math.max(1,Math.round(e*t)),height:e}}resize(e,t,n=!1,r){if(this.lost)return;e=Math.max(1,Math.round(e)),t=Math.max(1,Math.round(t)),r!==void 0&&(this.presentationPixelRatio=Math.max(.1,Math.min(2,r)));let i=this.presentationPixelRatio??Math.min(2,window.devicePixelRatio||1);if(!n&&e===this.width&&t===this.height&&i===this.pixelRatio&&this.allSurfaces.length)return;let a=this.allSurfaces.length?{surfaces:this.allSurfaces,velocity:this.velocity,dye:this.dye,active:this.active,view:this.view,idle:this.idle}:null;if(a?.view){let n=e/this.width,r=t/this.height;a.view={origin:{x:a.view.origin.x*n,y:a.view.origin.y*r},scaleX:a.view.scaleX*n,scaleY:a.view.scaleY*r},this.flameOrigin={x:this.flameOrigin.x*n,y:this.flameOrigin.y*r}}this.width=e,this.height=t,this.pixelRatio=i;let o=Hv[this.quality],s=this.quality===`high`?Math.min(2304,Math.max(o.dye,Math.round(Math.max(e,t)*i))):o.dye,c=Math.min(i,Math.max(1,s*1.5/Math.max(e,t))),l=Math.round(e*c),u=Math.round(t*c);this.canvas.width!==l&&(this.canvas.width=l),this.canvas.height!==u&&(this.canvas.height=u);let d=this.scaled(o.simulation),f=this.scaled(s);if(!n&&a&&d.width===this.simulation.width&&d.height===this.simulation.height&&f.width===this.dyeSize.width&&f.height===this.dyeSize.height){this.view=a.view;return}let p=this.gl;if(this.allSurfaces=[],this.simulation=d,this.wallTexture&&p.deleteTexture(this.wallTexture),this.wallTexture=p.createTexture(),!this.wallTexture)throw Error(`Unable to allocate fluid wall mask`);p.bindTexture(p.TEXTURE_2D,this.wallTexture),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.pixelStorei(p.UNPACK_ALIGNMENT,1),this.wallPixels=new Uint8Array(this.simulation.width*this.simulation.height),this.wallNext=new Uint8Array(this.wallPixels.length),p.texImage2D(p.TEXTURE_2D,0,p.R8,this.simulation.width,this.simulation.height,0,p.RED,p.UNSIGNED_BYTE,this.wallPixels),this.hasWalls=!1,this.dyeSize=f,this.velocity=this.pair(this.simulation.width,this.simulation.height),this.dye=this.pair(this.dyeSize.width,this.dyeSize.height),this.flameSource=this.flamePalette?this.surface(this.dyeSize.width,this.dyeSize.height,!0):null,this.pressure=this.pair(this.simulation.width,this.simulation.height),this.curl=this.surface(this.simulation.width,this.simulation.height),this.divergence=this.surface(this.simulation.width,this.simulation.height),a?.active&&(this.use(`copy`),this.texture(`copy`,`uTexture`,a.velocity.read,0),this.draw(this.velocity.read),this.texture(`copy`,`uTexture`,a.dye.read,0),this.draw(this.dye.read));for(let e of a?.surfaces??[])p.deleteTexture(e.texture),p.deleteFramebuffer(e.framebuffer);this.view=a?.view??null,this.active=a?.active??!1,this.idle=a?.idle??0}reset(){if(this.lost)return;let e=this.gl;for(let t of this.sceneInk.values())e.deleteTexture(t.texture);this.sceneInk.clear(),e.clearColor(0,0,0,0);for(let t of this.allSurfaces)e.bindFramebuffer(e.FRAMEBUFFER,t.framebuffer),e.viewport(0,0,t.width,t.height),e.clear(e.COLOR_BUFFER_BIT);this.active=!1,this.sceneFireActive=!1,this.radialBlasts=[],this.idle=0,this.view=null}align(e){if(!this.view||!this.active){this.view=e;return}let t=this.view,n=Math.abs(e.origin.x-t.origin.x)+Math.abs(e.origin.y-t.origin.y),r=Math.abs(e.scaleX/t.scaleX-1)+Math.abs(e.scaleY/t.scaleY-1);if(n<.2&&r<.001)return;let i=this.gl;this.beginGpu(`fire.align`),this.use(`align`),this.vec2(`align`,`size`,this.width,this.height),this.vec2(`align`,`oldOrigin`,t.origin.x,t.origin.y),this.vec2(`align`,`nextOrigin`,e.origin.x,e.origin.y),this.vec2(`align`,`oldScale`,t.scaleX,t.scaleY),this.vec2(`align`,`nextScale`,e.scaleX,e.scaleY);for(let e of[this.velocity,this.dye])this.texture(`align`,`uSource`,e.read,0),this.draw(e.write),e.swap();this.endGpu(),this.flamePalette&&(this.flameOrigin={x:e.origin.x+(this.flameOrigin.x-t.origin.x)/t.scaleX*e.scaleX,y:e.origin.y+(this.flameOrigin.y-t.origin.y)/t.scaleY*e.scaleY}),this.view=e,i.bindFramebuffer(i.FRAMEBUFFER,null)}splat(e,t,n,r){if(t.x<-n*2||t.y<-n*2||t.x>this.width+n*2||t.y>this.height+n*2)return;let i=this.gl;this.use(`splat`),this.texture(`splat`,`uTarget`,e.read,0),this.vec2(`splat`,`point`,t.x/this.width,1-t.y/this.height),this.vec2(`splat`,`size`,this.width,this.height),i.uniform1f(this.uniform(`splat`,`radius`),Math.max(2,n)),i.uniform4f(this.uniform(`splat`,`value`),...r),this.draw(e.write),e.swap()}splatBatch(e,t){if(!t)return;let n=this.gl;this.use(`splatBatch`),this.texture(`splatBatch`,`uTarget`,e.read,0),this.vec2(`splatBatch`,`size`,this.width,this.height),n.uniform1i(this.uniform(`splatBatch`,`count`),t),n.uniform4fv(this.uniform(`splatBatch`,`stamps[0]`),this.batchStamps.subarray(0,t*4)),n.uniform4fv(this.uniform(`splatBatch`,`values[0]`),this.batchValues.subarray(0,t*4)),this.draw(e.write),e.swap()}splatSegment(e,t,n,r,i,a){let o=this.gl;this.use(`splatSegment`),this.texture(`splatSegment`,`uTarget`,e.read,0),this.vec2(`splatSegment`,`start`,t.x/this.width,1-t.y/this.height),this.vec2(`splatSegment`,`end`,n.x/this.width,1-n.y/this.height),this.vec2(`splatSegment`,`size`,this.width,this.height),this.vec2(`splatSegment`,`radii`,Math.max(2,r),Math.max(2,i)),o.uniform4f(this.uniform(`splatSegment`,`value`),...a),this.draw(e.write),e.swap()}splatFlame(e,t,n,r,i){let a=this.gl;this.use(`flameSource`),this.texture(`flameSource`,`uTarget`,this.dye.read,0),this.vec2(`flameSource`,`start`,e.x/this.width,1-e.y/this.height),this.vec2(`flameSource`,`end`,t.x/this.width,1-t.y/this.height),this.vec2(`flameSource`,`size`,this.width,this.height),a.uniform3f(this.uniform(`flameSource`,`radii`),...n),a.uniform3f(this.uniform(`flameSource`,`strengths`),...r),a.uniform1f(this.uniform(`flameSource`,`time`),i),this.draw(this.dye.write),this.dye.swap()}stirFlame(e,t,n,r,i,a){let o=this.gl;this.use(`flameEddies`),this.texture(`flameEddies`,`uTarget`,this.velocity.read,0),this.vec2(`flameEddies`,`start`,e.x,e.y),this.vec2(`flameEddies`,`end`,t.x,t.y),this.vec2(`flameEddies`,`size`,this.width,this.height),this.vec2(`flameEddies`,`cellSize`,i,a),o.uniform1f(this.uniform(`flameEddies`,`time`),n),o.uniform1f(this.uniform(`flameEddies`,`dt`),r),this.draw(this.velocity.write),this.velocity.swap()}applyBody(e){let t=this.gl;this.use(`body`),this.texture(`body`,`uVelocity`,this.velocity.read,0),this.vec2(`body`,`size`,this.width,this.height),this.vec2(`body`,`texelSize`,1/this.simulation.width,1/this.simulation.height),this.vec2(`body`,`center`,e.center.x,e.center.y),this.vec2(`body`,`forward`,e.forward.x,e.forward.y),this.vec2(`body`,`halfSize`,e.halfLength,e.halfWidth),this.vec2(`body`,`motion`,e.velocity.x,e.velocity.y),t.uniform1f(this.uniform(`body`,`spin`),e.spin),t.uniform1f(this.uniform(`body`,`bodyInfluence`),e.influence??(this.flamePalette?.35:1)),this.draw(this.velocity.write),this.velocity.swap()}updateWalls(e){let{width:t,height:n}=this.simulation;this.wallNext.fill(0);let r=!1;for(let i of e){if(i.width<=0||i.height<=0)continue;let e=Math.max(0,Math.floor(i.x/this.width*t)),a=Math.min(t-1,Math.ceil((i.x+i.width)/this.width*t)-1),o=Math.max(0,Math.floor(i.y/this.height*n)),s=Math.min(n-1,Math.ceil((i.y+i.height)/this.height*n)-1);for(let i=o;i<=s;i++)for(let o=e;o<=a;o++)this.wallNext[(n-1-i)*t+o]=255,r=!0}let i=r!==this.hasWalls;if(!i){for(let e=0;e<this.wallNext.length;e++)if(this.wallNext[e]!==this.wallPixels[e]){i=!0;break}}if(this.hasWalls=r,!i)return;[this.wallPixels,this.wallNext]=[this.wallNext,this.wallPixels];let a=this.gl;a.activeTexture(a.TEXTURE2),a.bindTexture(a.TEXTURE_2D,this.wallTexture),a.texSubImage2D(a.TEXTURE_2D,0,0,0,t,n,a.RED,a.UNSIGNED_BYTE,this.wallPixels)}inject(e,t,n,r,i){if(this.lost||t<=0)return;this.active=!0,this.idle=0;let a=this.width/this.simulation.width,o=this.height/this.simulation.height;this.splat(this.velocity,e,r*1.3,[n.x/a*t*.22,-n.y/o*t*.22,0,0]),i&&this.splat(this.velocity,{x:e.x+r*.5,y:e.y+r*.5},r,[-i/a*t*.08,i/o*t*.08,0,0]),this.splat(this.dye,e,r*1.2,[t*2.2,0,0,0])}injectBatch(e){if(this.lost||e.length===0)return;if(e.length===1){let t=e[0];this.inject(t.point,t.amount,t.flow,t.radiusPx,t.swirlPx);return}this.active=!0,this.idle=0;let t=this.width/this.simulation.width,n=this.height/this.simulation.height,r=0,i=(e,t,n,i)=>{if(e.x<-t*2||e.y<-t*2||e.x>this.width+t*2||e.y>this.height+t*2)return;let a=r*4;this.batchStamps[a]=e.x/this.width,this.batchStamps[a+1]=1-e.y/this.height,this.batchStamps[a+2]=Math.max(2,t),this.batchStamps[a+3]=0,this.batchValues[a]=n,this.batchValues[a+1]=i,this.batchValues[a+2]=0,this.batchValues[a+3]=0,r++,r===16&&(this.splatBatch(this.velocity,r),r=0)};for(let r of e){let{point:e,amount:a,flow:o,radiusPx:s,swirlPx:c}=r;a<=0||(i(e,s*1.3,o.x/t*a*.22,-o.y/n*a*.22),c&&i({x:e.x+s*.5,y:e.y+s*.5},s,-c/t*a*.08,c/n*a*.08))}this.splatBatch(this.velocity,r),r=0;for(let t of e){let{point:e,amount:n,radiusPx:i}=t;if(n<=0)continue;let a=i*1.2;if(e.x<-a*2||e.y<-a*2||e.x>this.width+a*2||e.y>this.height+a*2)continue;let o=r*4;this.batchStamps[o]=e.x/this.width,this.batchStamps[o+1]=1-e.y/this.height,this.batchStamps[o+2]=Math.max(2,a),this.batchStamps[o+3]=0,this.batchValues[o]=n*2.2,this.batchValues[o+1]=0,this.batchValues[o+2]=0,this.batchValues[o+3]=0,r++,r===16&&(this.splatBatch(this.dye,r),r=0)}this.splatBatch(this.dye,r)}disturb(e,t,n,r){if(!this.active||this.lost||r<=0)return;let i=this.width/this.simulation.width,a=this.height/this.simulation.height,o={x:e.x-t.x*r,y:e.y-t.y*r};this.splatSegment(this.velocity,o,e,n,n,[t.x/i*r*2.8,-t.y/a*r*2.8,0,0])}injectFlameSegment(e,t,n,r,i){if(this.lost||n<=0)return;this.active=!0,this.idle=0,this.flameOrigin=e;let a=this.width/this.simulation.width,o=this.height/this.simulation.height;this.splatSegment(this.velocity,e,t,8,21,[r.x/a*n*.26,-r.y/o*n*.26,0,0]);let s={x:e.x+(t.x-e.x)*.9,y:e.y+(t.y-e.y)*.9};this.stirFlame(e,s,i,n,a,o),this.splatFlame(e,t,[24,17,9],[n*.65,n*1.55,n*2.2],i)}injectFlameStamps(e,t,n){if(!e.length||this.lost||!this.flameSource||!this.flameStampProgram||!this.flameStampBuffer)return;this.beginGpu(`fire.stamps`);let r=this.gl,i=Math.min(e.length,this.flameStampData.length/5),a=null,o=null,s=0,c=0,l=0;for(let n=0;n<i;n++){let r=e[Math.floor(n*e.length/i)];!r.blast&&r.stir!==!1&&((!a||r.progress<a.progress)&&(a=r),(!o||r.progress>o.progress)&&(o=r),s+=r.flow.x,c+=r.flow.y,l++);let u=n*5;this.flameStampData[u]=r.point.x,this.flameStampData[u+1]=r.point.y,this.flameStampData[u+2]=Math.max(3,r.radius),this.flameStampData[u+3]=r.progress,this.flameStampData[u+4]=(r.blast?Math.min(.4,t*12):Math.min(.08,t*.65))*(r.strength??1)}this.active=!0,this.idle=0,this.flameOrigin=a?.point??{x:-1e3,y:-1e3},r.bindFramebuffer(r.FRAMEBUFFER,this.flameSource.framebuffer),r.viewport(0,0,this.flameSource.width,this.flameSource.height),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.useProgram(this.flameStampProgram),r.bindBuffer(r.ARRAY_BUFFER,this.flameStampBuffer),r.bufferData(r.ARRAY_BUFFER,this.flameStampData.subarray(0,i*5),r.DYNAMIC_DRAW);let u=Av(this.flameStampProgram,`aStamp`),d=Av(this.flameStampProgram,`aStrength`);if(r.enableVertexAttribArray(u),r.vertexAttribPointer(u,4,r.FLOAT,!1,20,0),r.enableVertexAttribArray(d),r.vertexAttribPointer(d,1,r.FLOAT,!1,20,16),r.uniform2f(kv(this.flameStampProgram,`canvasSize`),this.width,this.height),r.uniform2f(kv(this.flameStampProgram,`dyeSize`),this.flameSource.width,this.flameSource.height),r.uniform1i(kv(this.flameStampProgram,`agePalette`),Number(this.agePalette)),r.enable(r.BLEND),r.blendFunc(r.ONE,r.ONE),r.drawArrays(r.POINTS,0,i),r.disable(r.BLEND),this.use(`addFlame`),this.texture(`addFlame`,`uTarget`,this.dye.read,0),this.texture(`addFlame`,`uSource`,this.flameSource,1),this.draw(this.dye.write),this.dye.swap(),!a||!o||!l){this.endGpu();return}let f=this.width/this.simulation.width,p=this.height/this.simulation.height,m={x:s/l,y:c/l},h=[m.x/f*t*.18,-m.y/p*t*.18,0,0],g=Math.hypot(m.x,m.y);if(g>.001){let r=1/0,i=-1/0;for(let t of e){if(t.blast||t.stir===!1)continue;let e=(-t.point.x*m.y+t.point.y*m.x)/g;r=Math.min(r,e),i=Math.max(i,e)}if(i-r>10){let a=(r+i)*.5,o=null,s=null,c=null,l=null;for(let t of e)t.blast||t.stir===!1||((-t.point.x*m.y+t.point.y*m.x)/g<a?((!o||t.progress<o.progress)&&(o=t),(!s||t.progress>s.progress)&&(s=t)):((!c||t.progress<c.progress)&&(c=t),(!l||t.progress>l.progress)&&(l=t)));if(o&&s&&c&&l){this.splatSegment(this.velocity,o.point,s.point,7,19,h),this.splatSegment(this.velocity,c.point,l.point,7,19,h),this.stirFlame(o.point,s.point,n,t*.55,f,p),this.stirFlame(c.point,l.point,n,t*.55,f,p),this.endGpu();return}}}this.splatSegment(this.velocity,a.point,o.point,7,19,h),this.stirFlame(a.point,o.point,n,t*.55,f,p),this.endGpu()}setFlameInk(e){if(!this.flamePalette||!this.flameSmokeTail||this.lost)return;let t=this.gl;this.flameInk&&t.deleteTexture(this.flameInk.texture);let n=t.createTexture();if(!n)throw Error(`Unable to allocate flame ink texture`);t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.R8,e.pixelWidth,e.pixelHeight,0,t.RED,t.UNSIGNED_BYTE,e.alpha),this.flameInk={texture:n,x:e.x,y:e.y,width:e.width,height:e.height,ignitionX:e.origin.x-e.x}}injectFlameInk(e,t){let n=this.flameInk;if(!n||!this.flameSource||this.lost||e>(n.width-n.ignitionX)/88+1.28)return;let r=this.gl;this.active=!0,this.idle=0,this.flameOrigin={x:-1e3,y:-1e3},this.use(`inkFlame`),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,n.texture),r.uniform1i(this.uniform(`inkFlame`,`uInk`),0),this.vec2(`inkFlame`,`uCanvasSize`,this.width,this.height),this.vec2(`inkFlame`,`uInkOrigin`,n.x,n.y),this.vec2(`inkFlame`,`uInkSize`,n.width,n.height),this.vec2(`inkFlame`,`uIgnition`,n.ignitionX,0),r.uniform1f(this.uniform(`inkFlame`,`uTime`),e),r.uniform1f(this.uniform(`inkFlame`,`uDt`),Math.min(.05,t)),this.draw(this.flameSource),this.use(`addFlame`),this.texture(`addFlame`,`uTarget`,this.dye.read,0),this.texture(`addFlame`,`uSource`,this.flameSource,1),this.draw(this.dye.write),this.dye.swap(),this.use(`inkFlow`),this.texture(`inkFlow`,`uVelocity`,this.velocity.read,0),this.vec2(`inkFlow`,`uCanvasSize`,this.width,this.height),this.vec2(`inkFlow`,`uCellSize`,this.width/this.simulation.width,this.height/this.simulation.height),this.vec2(`inkFlow`,`uInkOrigin`,n.x,n.y),this.vec2(`inkFlow`,`uInkSize`,n.width,n.height),r.uniform1f(this.uniform(`inkFlow`,`uIgnitionX`),n.ignitionX),r.uniform1f(this.uniform(`inkFlow`,`uTime`),e),r.uniform1f(this.uniform(`inkFlow`,`uDt`),Math.min(.05,t)),this.draw(this.velocity.write),this.velocity.swap()}injectBurnMasks(e,t,n){if(!this.flameSmokeTail||!this.flameSource||this.lost)return;this.beginGpu(`fire.mask`);let r=this.gl,i=this.flameSource,a=new Set;r.bindFramebuffer(r.FRAMEBUFFER,i.framebuffer),r.viewport(0,0,i.width,i.height),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),this.use(`sceneInkFlame`),this.vec2(`sceneInkFlame`,`uCanvasSize`,this.width,this.height),r.uniform1f(this.uniform(`sceneInkFlame`,`uDt`),Math.min(.05,t)),r.uniform1f(this.uniform(`sceneInkFlame`,`uTime`),n),r.uniform1i(this.uniform(`sceneInkFlame`,`uAgePalette`),Number(this.agePalette)),r.enable(r.BLEND),r.blendFunc(r.ONE,r.ONE),r.enable(r.SCISSOR_TEST);let o=0;for(let t of e){if(t.width<=0||t.height<=0||t.pixelWidth<=0||t.pixelHeight<=0||t.alpha.length<t.pixelWidth*t.pixelHeight)continue;let e=t.x+t.width/2,n=t.y+t.height/2,s=Math.hypot(t.width,t.height)/2+5;if(e+s<0||e-s>this.width||n+s<0||n-s>this.height)continue;let c=Math.max(0,Math.floor((e-s)*i.width/this.width)),l=Math.min(i.width,Math.ceil((e+s)*i.width/this.width)),u=Math.max(0,Math.floor((this.height-n-s)*i.height/this.height)),d=Math.min(i.height,Math.ceil((this.height-n+s)*i.height/this.height));if(l<=c||d<=u)continue;a.add(t.key);let f=this.sceneInk.get(t.key);if(!f||f.width!==t.pixelWidth||f.height!==t.pixelHeight){f&&r.deleteTexture(f.texture);let e=r.createTexture();if(!e)continue;f={texture:e,width:t.pixelWidth,height:t.pixelHeight,alpha:t.alpha,revision:t.revision??0},this.sceneInk.set(t.key,f),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,e),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.R8,f.width,f.height,0,r.RED,r.UNSIGNED_BYTE,t.alpha)}else r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,f.texture),(f.alpha!==t.alpha||f.revision!==(t.revision??0))&&(r.texSubImage2D(r.TEXTURE_2D,0,0,0,f.width,f.height,r.RED,r.UNSIGNED_BYTE,t.alpha),f.alpha=t.alpha,f.revision=t.revision??0);r.uniform1i(this.uniform(`sceneInkFlame`,`uInk`),0),r.scissor(c,u,l-c,d-u),r.uniform4f(this.uniform(`sceneInkFlame`,`uRect`),t.x,t.y,t.width,t.height),this.vec2(`sceneInkFlame`,`uOrigin`,t.origin.x,t.origin.y),r.uniform1f(this.uniform(`sceneInkFlame`,`uAngle`),t.angle??0),r.uniform1f(this.uniform(`sceneInkFlame`,`uAge`),t.age),r.uniform1f(this.uniform(`sceneInkFlame`,`uFarthest`),t.farthest),r.uniform1f(this.uniform(`sceneInkFlame`,`uSpreadSeconds`),t.spreadSeconds),r.uniform1f(this.uniform(`sceneInkFlame`,`uBurnSeconds`),t.burnSeconds),r.uniform1f(this.uniform(`sceneInkFlame`,`uSmokeRate`),(t.smokeRate??13)/13),r.uniform1f(this.uniform(`sceneInkFlame`,`uIntensity`),t.intensity??1),r.uniform1f(this.uniform(`sceneInkFlame`,`uFixedRadius`),t.fixedRadius??0),r.uniform1f(this.uniform(`sceneInkFlame`,`uSmokeOnly`),+!!t.smokeOnly),r.uniform1f(this.uniform(`sceneInkFlame`,`uBlastAge`),t.blastAge??-1),r.uniform1f(this.uniform(`sceneInkFlame`,`uBlastSeconds`),t.blastSeconds??0),this.draw(i),o++}r.disable(r.SCISSOR_TEST),r.disable(r.BLEND);for(let[e,t]of this.sceneInk)a.has(e)||(r.deleteTexture(t.texture),this.sceneInk.delete(e));o&&(this.active=!0,this.sceneFireActive=!0,this.idle=0,this.flameOrigin={x:-1e3,y:-1e3},this.use(`addFlame`),this.texture(`addFlame`,`uTarget`,this.dye.read,0),this.texture(`addFlame`,`uSource`,i,1),this.draw(this.dye.write),this.dye.swap()),this.endGpu()}applySceneFlow(e,t){let n=this.gl;this.use(`sceneFlow`),this.texture(`sceneFlow`,`uVelocity`,this.velocity.read,0),this.texture(`sceneFlow`,`uDye`,this.dye.read,1),this.vec2(`sceneFlow`,`uCanvasSize`,this.width,this.height),this.vec2(`sceneFlow`,`uCellSize`,this.width/this.simulation.width,this.height/this.simulation.height),n.uniform1f(this.uniform(`sceneFlow`,`uTime`),t),n.uniform1f(this.uniform(`sceneFlow`,`uDt`),Math.min(.05,e)),this.draw(this.velocity.write),this.velocity.swap()}step(e,t,n=[]){if(!this.active||this.lost)return;let r=this.gl;if(e=Math.min(.05,e),this.idle+=e,this.idle>(this.ghostPalette?1.7:this.flamePalette?this.flameSmokeTail?3.2:1.35:10)){this.reset();return}this.beginGpu(`fire.curlAndWalls`),r.disable(r.BLEND),this.updateWalls(n);let i=1/this.simulation.width,a=1/this.simulation.height;t&&this.applyBody(t),this.use(`curl`),this.vec2(`curl`,`texelSize`,i,a),this.texture(`curl`,`uVelocity`,this.velocity.read,0),this.draw(this.curl),this.use(`vorticity`),this.vec2(`vorticity`,`texelSize`,i,a),this.texture(`vorticity`,`uVelocity`,this.velocity.read,0),this.texture(`vorticity`,`uCurl`,this.curl,1),r.uniform1f(this.uniform(`vorticity`,`curl`),this.vorticity),r.uniform1f(this.uniform(`vorticity`,`dt`),e),this.draw(this.velocity.write),this.velocity.swap(),this.use(`divergence`),this.bindWalls(`divergence`),this.vec2(`divergence`,`texelSize`,i,a),this.texture(`divergence`,`uVelocity`,this.velocity.read,0),this.draw(this.divergence),this.endGpu(),this.beginGpu(`fire.pressure`),this.use(`clear`),this.texture(`clear`,`uTexture`,this.pressure.read,0),r.uniform1f(this.uniform(`clear`,`value`),.8),this.draw(this.pressure.write),this.pressure.swap(),this.use(`pressure`),this.bindWalls(`pressure`),this.vec2(`pressure`,`texelSize`,i,a),this.texture(`pressure`,`uDivergence`,this.divergence,0);for(let e=0;e<Hv[this.quality].iterations;e++)this.texture(`pressure`,`uPressure`,this.pressure.read,1),this.draw(this.pressure.write),this.pressure.swap();this.use(`gradient`),this.bindWalls(`gradient`),this.vec2(`gradient`,`texelSize`,i,a),this.texture(`gradient`,`uPressure`,this.pressure.read,0),this.texture(`gradient`,`uVelocity`,this.velocity.read,1),this.draw(this.velocity.write),this.velocity.swap(),this.endGpu(),this.beginGpu(`fire.transport`),t&&this.applyBody(t),this.use(`advection`),this.bindWalls(`advection`),r.uniform1i(this.uniform(`advection`,`ageDye`),0),this.vec2(`advection`,`velocityTexel`,i,a),this.vec2(`advection`,`sourceTexel`,i,a),r.uniform1f(this.uniform(`advection`,`dt`),e),r.uniform4f(this.uniform(`advection`,`dissipation`),.2,.2,.2,.2),this.texture(`advection`,`uVelocity`,this.velocity.read,0),this.texture(`advection`,`uSource`,this.velocity.read,1),this.draw(this.velocity.write),this.velocity.swap(),this.sceneFireActive&&this.applySceneFlow(e,performance.now()*.001);for(let e of this.radialBlasts)this.use(`radialBlast`),this.texture(`radialBlast`,`uVelocity`,this.velocity.read,0),this.vec2(`radialBlast`,`uCanvasSize`,this.width,this.height),this.vec2(`radialBlast`,`uCellSize`,this.width/this.simulation.width,this.height/this.simulation.height),this.vec2(`radialBlast`,`uCenter`,e.center.x,e.center.y),r.uniform1f(this.uniform(`radialBlast`,`uRadius`),e.radius),this.draw(this.velocity.write),this.velocity.swap();this.radialBlasts=[],this.use(`advection`),this.bindWalls(`advection`),r.uniform1i(this.uniform(`advection`,`ageDye`),Number(this.agePalette)),this.vec2(`advection`,`velocityTexel`,i,a),r.uniform1f(this.uniform(`advection`,`dt`),e),this.vec2(`advection`,`sourceTexel`,1/this.dyeSize.width,1/this.dyeSize.height);let o=this.idle<.1,s=o?1:2.8;r.uniform4f(this.uniform(`advection`,`dissipation`),this.agePalette?s:this.flamePalette?o?.7:3:this.ghostPalette?2.1:.65,this.agePalette?s:this.flamePalette?o?.85:3.8:0,this.agePalette?s:this.flamePalette?o?1.05:4.8:0,this.flameSmokeTail?zv(this.idle).dissipation:0),this.texture(`advection`,`uVelocity`,this.velocity.read,0),this.texture(`advection`,`uSource`,this.dye.read,1),this.draw(this.dye.write),this.dye.swap(),this.endGpu()}drawTo(e,t,n=!1,r=[]){if(!this.active||this.lost)return;this.align(t),this.beginGpu(`fire.display`);let i=this.gl,a=this.ghostPalette?`ghostDisplay`:`display`;this.use(a),this.bindWalls(a),this.texture(a,`uDye`,this.dye.read,0);let o=typeof this.tint==`string`?this.tint===`cyan`?[.34,.83,.96]:this.tint===`magenta`?[.94,.38,.81]:Vv:this.tint;if(i.uniform3f(this.uniform(a,`smokeColor`),o[0],o[1],o[2]),i.uniform1i(this.uniform(a,`darkBackground`),Number(n)),this.ghostPalette&&i.uniform1i(this.uniform(a,`ghostStyle`),this.ghostStyle===`specter`?0:this.ghostStyle===`phantom`?1:2),!this.ghostPalette){let e=Math.min(r.length,12);i.uniform1i(this.uniform(`display`,`vehicleLightCount`),e);for(let t=0;t<e;t++){let e=r[t],n=t*4;this.lightPositions[n]=e.point.x,this.lightPositions[n+1]=e.point.y,this.lightPositions[n+2]=e.range,this.lightPositions[n+3]=e.radius,this.lightShapes[n]=e.direction.x,this.lightShapes[n+1]=e.direction.y,this.lightShapes[n+2]=e.spread,this.lightShapes[n+3]=0,this.lightColors[n]=e.color[0],this.lightColors[n+1]=e.color[1],this.lightColors[n+2]=e.color[2],this.lightColors[n+3]=e.intensity}e&&(i.uniform4fv(this.uniform(`display`,`vehicleLightPosition[0]`),this.lightPositions),i.uniform4fv(this.uniform(`display`,`vehicleLightShape[0]`),this.lightShapes),i.uniform4fv(this.uniform(`display`,`vehicleLightColor[0]`),this.lightColors)),i.uniform1i(this.uniform(`display`,`flamePalette`),Number(this.flamePalette)),i.uniform1i(this.uniform(`display`,`agePalette`),Number(this.agePalette)),i.uniform1f(this.uniform(`display`,`lifecycleOpacity`),this.flameSmokeTail?zv(this.idle).opacity:1),this.vec2(`display`,`flameOrigin`,this.flameOrigin.x,this.height-this.flameOrigin.y),this.vec2(`display`,`size`,this.width,this.height)}i.bindFramebuffer(i.FRAMEBUFFER,null),i.viewport(0,0,this.canvas.width,this.canvas.height),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT),this.draw(null),this.endGpu(),this.canvas.width*this.canvas.height/1e6,e.drawImage(this.canvas,0,0,this.width,this.height)}};function Yv(e,t,n,r=`fuel-age`){return new Jv(e,t,n,`natural`,12,!0,!0,!1,r===`fuel-age`)}var Xv=class{camera;quality;tireFire=new lf;fluid=null;fluidAttempted=!1;fluidClock=0;maskBatch=new cf;sceneMasks=new Map;hadSceneMasks=!1;stamps=[];blasts=[];vehicleAlpha=new WeakMap;previousFireTire=new Map;fireRefreshClock=0;constructor(e,t){this.camera=e,this.quality=t}get count(){return this.tireFire.count}get managedBytes(){return this.tireFire.managedBytes+(this.fluid?.managedBytes??0)}get resolution(){return this.fluid?.resolution}get available(){return this.fluid?.available??!1}prepare(){if(!this.fluidAttempted){this.fluidAttempted=!0,performance.now();try{this.fluid=Yv(this.camera.width,this.camera.height,this.quality)}catch(e){console.error(`Joy Ride fire requires WebGL2`,e)}}return this.fluid?.available?this.fluid:null}ensure(){return!!this.prepare()}get running(){return!!this.fluid?.running}setQuality(e){this.quality=e,this.fluid?.setQuality(e)}resize(e){this.fluid?.resize(this.camera.width,this.camera.height,!1,e)}alphaFor(e){let t=this.vehicleAlpha.get(e);return t||(t=e.map(e=>e?255:0),this.vehicleAlpha.set(e,t)),t}sceneMasksDue(e){return!this.sceneMasks.size||this.fluidClock+e>=this.solveInterval()}solveInterval(){return 1/(this.quality===`high`?45:this.quality===`medium`?30:24)}queueMask(e){this.prepare()&&this.sceneMasks.set(e.key,e)}queueBlast(e,t){this.blasts.push({point:e,radius:t})}queueStamp(e){this.prepare()&&this.stamps.push(e)}activateBuoyancy(){let e=this.prepare();return e?(e.activateBuoyancy(),!0):!1}emitJet(e,t,n,r,i,a){if(!this.prepare())return;let o=this.camera.particlePoint(e),s=k(this.camera.particlePoint(t),o),c=this.camera.particleScale(),l=Math.max(a===`rocket`?6:4,r*c*1.9),u=a===`exhaust`&&M(s)<.001?0:Math.min(10,Math.max(1,Math.ceil(M(s)/Math.max(4,l)))),d=this.camera.pixelSpace?D(n.x*this.camera.zoom,-n.y*this.camera.zoom):{...n};for(let e=0;e<=u;e++){let t=1-e/Math.max(1,u);this.stamps.push({point:O(O(o,A(s,e/Math.max(1,u))),a===`rocket`?A(d,t*.025):D()),radius:l*(a===`rocket`?.8+t*.65:1),progress:a===`rocket`?.08+t*.48:.95,flow:d,strength:a===`rocket`?i*5.2:4+i*8,source:a===`rocket`?`rocket`:void 0,stir:a===`rocket`})}}igniteTire(e,t,n,r,i){this.tireFire.ignite(e,t,n,r,i)}stepTire(e){this.tireFire.step(e)}emberSource(){return this.tireFire.emberSource()}clearTireHistory(){this.previousFireTire.clear(),this.fireRefreshClock=0}stepBoostFire(e,t,n){if(!e.car.boostActive){this.clearTireHistory();return}this.fireRefreshClock+=t;let r=this.fireRefreshClock>=1/15;r&&(this.fireRefreshClock%=1/15);let i=this.camera.particleScale();e.car.tires.forEach((t,a)=>{if(t.front)return;let o=this.camera.particlePoint(e.body.world(t.local));n(o);let s=this.previousFireTire.get(a)??o;!r&&M(k(o,s))<.24*i&&this.previousFireTire.has(a)||(this.igniteTire(s,o,e.car.preset.geometry.tireWidthM*i,e.car.preset.launch.fireLifetimeSeconds,.24*i),this.previousFireTire.set(a,o))})}particleScreen(e){return this.camera.pixelSpace?k(e,this.camera.sceneScroll()):this.camera.screen(e)}step(e,t,n,r,i,a,o){let s=this.fluid??(this.tireFire.count?this.prepare():null);if(!s?.available){this.stamps=[],this.blasts=[],this.sceneMasks.clear();return}if(!this.stamps.length&&!this.blasts.length&&!this.sceneMasks.size&&!this.tireFire.count&&s.managedBytes===0)return;this.fluidClock+=e;let c=this.solveInterval();if(this.fluidClock<c)return;let l=Math.min(.1,this.fluidClock);this.fluidClock=Math.max(0,this.fluidClock-c),s.align(a);let u=i?[]:this.tireFire.stamps();u.length&&s.activateBuoyancy();let d=[...this.stamps,...u].map(e=>({...e,point:this.particleScreen(e.point),radius:e.radius*(this.camera.pixelSpace?1:this.camera.zoom),flow:this.camera.pixelSpace?e.flow:D(e.flow.x*this.camera.zoom,-e.flow.y*this.camera.zoom)}));this.stamps=[];for(let e of this.blasts)s.queueRadialBlast(this.particleScreen(e.point),e.radius*(this.camera.pixelSpace?1:this.camera.zoom));this.blasts=[];let f=this.camera.pixelSpace?this.camera.sceneScroll():D(),p=[...this.sceneMasks.values()].map(e=>({...e,x:e.x-f.x,y:e.y-f.y,origin:k(e.origin,f)}));this.sceneMasks.clear();let m=Math.min(8,p.length);for(let e=0;e<m;e++){let t=p[Math.floor((e+.5)*p.length/m)];t.smokeOnly||o.emitFire(t,l)}performance.now();let h=this.maskBatch.combine(p,this.camera.width,this.camera.height);(h.length||this.hadSceneMasks||s.hasSceneFire)&&(performance.now(),s.injectBurnMasks(h,l,t),this.hadSceneMasks=h.length>0),performance.now();let g=d.filter(e=>e.source===`rocket`);s.injectFlameStamps(g.length?d.filter(e=>e.source!==`rocket`):d,l,t),g.length&&s.injectFlameStamps(g,l,t);let _=this.camera.pixelSpace?r.map(e=>({x:e.x-f.x,y:e.y-f.y,width:e.width,height:e.height})):[];performance.now(),s.step(l,n&&this.camera.pixelSpace?{...n,center:k(n.center,D(this.camera.smokeMargin,this.camera.smokeMargin))}:n,_)}draw(e,t,n,r){this.fluid?.drawTo(e,t,n,r)}captureState(){let e=this.tireFire.captureState();try{let t=this.fluid?.captureState()??null;return{tireFire:e,flame:t,fluidAttempted:this.fluidAttempted,fluidClock:this.fluidClock,hadSceneMasks:this.hadSceneMasks,stamps:this.stamps.map(e=>({...e,point:{...e.point},flow:{...e.flow}})),blasts:this.blasts.map(e=>({point:{...e.point},radius:e.radius})),previousFireTire:new Map([...this.previousFireTire].map(([e,t])=>[e,{...t}])),fireRefreshClock:this.fireRefreshClock,dispose:()=>{e.dispose(),t?.dispose()}}}catch(t){throw e.dispose(),t}}restoreState(e){if(this.reset(),this.tireFire.restoreState(e.tireFire),e.flame){this.fluid||(this.fluidAttempted=!1);let t=this.fluid??this.prepare();if(!t)throw Error(`Flame GPU context is unavailable`);t.restoreState(e.flame),this.fluidAttempted=e.fluidAttempted}else this.fluid?.dispose(),this.fluid=null,this.fluidAttempted=!1;this.fluidClock=e.fluidClock,this.hadSceneMasks=e.hadSceneMasks,this.stamps=e.stamps.map(e=>({...e,point:{...e.point},flow:{...e.flow}})),this.blasts=e.blasts.map(e=>({point:{...e.point},radius:e.radius}));for(let[t,n]of e.previousFireTire)this.previousFireTire.set(t,{...n});this.fireRefreshClock=e.fireRefreshClock}reset(){this.tireFire.reset(),this.fluid?.reset(),this.fluidClock=0,this.sceneMasks.clear(),this.hadSceneMasks=!1,this.stamps=[],this.blasts=[],this.clearTireHistory()}dispose(){this.fluid?.dispose(),this.tireFire.dispose()}},Zv=class{quality;gpu=null;constructor(e,t,n,r=`natural`){this.quality=n;try{this.gpu=new Jv(e,t,n,r)}catch(e){console.error(`Joy Ride smoke requires WebGL2`,e)}}get running(){return!!this.gpu?.running}get usesWebGL(){return!!this.gpu?.available}get managedBytes(){return this.usesWebGL?this.gpu.managedBytes:0}get resolution(){return this.usesWebGL?this.gpu.resolution:{quality:this.quality,cols:0,rows:0,engine:`WebGL2 required`}}captureState(){return this.usesWebGL?this.gpu.captureState():null}restoreState(e){if(e&&!this.usesWebGL)throw Error(`Smoke GPU context is unavailable`);e?this.gpu.restoreState(e):this.reset()}setQuality(e){this.quality=e,this.usesWebGL&&this.gpu.setQuality(e)}setTint(e){this.usesWebGL&&this.gpu.setTint(e)}resize(e,t,n){this.usesWebGL&&this.gpu.resize(e,t,!1,n)}reset(){this.usesWebGL&&this.gpu.reset()}dispose(){this.gpu?.dispose(),this.gpu=null}align(e){this.usesWebGL&&this.gpu.align(e)}inject(e,t,n,r,i){this.usesWebGL&&this.gpu.inject(e,t,n,r,i)}injectBatch(e){this.usesWebGL&&this.gpu.injectBatch(e)}disturb(e,t,n,r){this.usesWebGL&&this.gpu.disturb(e,t,n,r)}step(e,t,n=[]){this.usesWebGL&&this.gpu.step(e,t,n)}draw(e,t,n=[],r=!1){this.usesWebGL&&this.gpu.drawTo(e,t,r,n)}},Qv=class{camera;quality;smoke;sources=[];smokeClock=0;ghost=null;ghostAttempted=!1;ghostClock=0;ghostStyle=`phantom`;ghostWallCoverage=new Map;ghostEmergence=new Map;constructor(e,t){this.camera=e,this.quality=t,this.smoke=new Zv(1,1,t)}get smokeResolution(){return this.smoke.resolution}get smokeBytes(){return this.sources.length*64+this.smoke.managedBytes}get ghostBytes(){return this.ghost?.managedBytes??0}get ghostAvailable(){return this.ghost?.available??!1}get style(){return this.ghostStyle}get running(){return this.smoke.running||!!this.ghost?.running}setQuality(e){this.quality=e,this.smoke.setQuality(e),this.ghost?.setQuality(e)}setSmokeTint(e){this.smoke.setTint(e)}setGhostStyle(e){this.ghostStyle=e,this.ghost?.setGhostStyle(e)}resize(e){this.smoke.resize(this.camera.width+2*this.camera.smokeMargin,this.camera.height+2*this.camera.smokeMargin,e),this.ghost?.resize(this.camera.width,this.camera.height,!1,e)}emitSmoke(e){this.sources.push(e)}clearSmokeSources(){this.sources=[]}particleScreen(e){return this.camera.pixelSpace?k(e,this.camera.sceneScroll()):this.camera.screen(e)}stepSmoke(e,t,n,r){if(!this.smoke.usesWebGL){this.sources=[];return}this.smokeClock+=e;let i=1/(this.quality===`high`?45:this.quality===`medium`?30:24);if(this.smokeClock<i)return;let a=Math.min(.1,this.smokeClock);this.smokeClock=Math.max(0,this.smokeClock-i),this.smoke.align(r),this.smoke.injectBatch(this.sources.map(e=>({...e,point:O(this.particleScreen(e.point),D(this.camera.smokeMargin,this.camera.smokeMargin))}))),this.sources=[];let o=this.camera.sceneScroll(),s=this.camera.pixelSpace?n.map(e=>({x:e.x-o.x+this.camera.smokeMargin,y:e.y-o.y+this.camera.smokeMargin,width:e.width,height:e.height})):[];this.smoke.step(a,t,s)}drawSmoke(e,t,n,r){this.smoke.draw(e,t,n,r)}prepareGhost(){if(!this.ghostAttempted){this.ghostAttempted=!0;try{this.ghost=new Jv(this.camera.width,this.camera.height,this.quality,z.lightColor,z.vorticity,!1,!1,!0),this.ghost.setGhostStyle(this.ghostStyle)}catch(e){console.error(`Joy Ride ghost mode requires WebGL2`,e)}}return this.ghost?.available?this.ghost:null}stepGhost(e,t,n,r,i,a){let o=t.filter(e=>e.isGhost);if(!o.length)this.ghostWallCoverage.clear(),this.ghostEmergence.clear();else{let e=new Set(o.map(e=>e.id));for(let t of this.ghostWallCoverage.keys())e.has(t)||this.ghostWallCoverage.delete(t);for(let t of this.ghostEmergence.keys())e.has(t)||this.ghostEmergence.delete(t)}let s=o.length?this.prepareGhost():this.ghost;if(!s?.available||!o.length&&s.managedBytes===0)return;this.ghostClock+=e;let c=1/(this.quality===`high`?45:this.quality===`medium`?30:24);if(this.ghostClock<c)return;let l=Math.min(.1,this.ghostClock);this.ghostClock=Math.max(0,this.ghostClock-c),s.align(i);let u=this.camera.sceneScroll(),d=this.camera.pixelSpace?n.map(e=>({x:e.x-u.x,y:e.y-u.y,width:e.width,height:e.height})):[],f=null;if(r&&o.length){let e=z.styles[this.ghostStyle],n=[];for(let i of o){let{sim:o}=i,s=r(i),c=O(this.camera.screen(o.body.position),i===t[0]?a(i):D()),u=D(Math.cos(o.body.angle),-Math.sin(o.body.angle)),p=D(-u.y,u.x),m=s.lengthM*this.camera.zoom/2,h=s.widthM*this.camera.zoom/2,g=$d(c,u,m,h,d),_=this.ghostWallCoverage.get(i.id)??0,v=_+(g-_)*(1-Math.exp(-l*12));this.ghostWallCoverage.set(i.id,v);let y=Math.max(0,(this.ghostEmergence.get(i.id)??0)-l/z.emergenceFadeSeconds,(_-g)*1.8);this.ghostEmergence.set(i.id,y);let b=D(o.body.velocity.x*this.camera.zoom,-o.body.velocity.y*this.camera.zoom),x=A(b,Math.min(1,z.maxMotionSpeedPxPerSecond/Math.max(1,M(b)))),S=M(x),C=Math.min(1,S/z.wakeSpeedPxPerSecond),w=x.x*u.x+x.y*u.y,ee=Math.max(3,Math.min(14,h*e.radiusFactor));f||={center:c,forward:u,halfLength:m*.94,halfWidth:h*.78,velocity:x,spin:-o.body.spin,influence:e.bodyInfluence};let te=tf(s.alpha,this.quality),ne=tf(s.alpha,`low`).length/te.length;for(let t of te){let r=Math.max(0,w>=0?-t.x:t.x);n.push({point:O(c,O(A(u,t.x*m),A(p,t.y*h))),amount:l*e.emissionPerSecond*z.emissionFactor*ne*(1+C*r*z.wakeEmissionFactor)*(1+v*z.wallSmokeFactor+y*z.emergenceSmokeFactor),flow:O(A(x,.18-C*r*z.wakeFlowFactor),O(A(p,t.y*e.driftPixelsPerSecond),A(u,-e.driftPixelsPerSecond*.65))),radiusPx:ee,swirlPx:e.driftPixelsPerSecond*(t.y<0?-1:1)})}if(y>.05){let t=w>=0?-1:1,r=O(c,A(u,m*t*.72));for(let i of[-1,1])n.push({point:O(r,A(p,i*h*.45)),amount:l*e.emissionPerSecond*z.emissionFactor*y*1.35,flow:O(A(u,t*e.driftPixelsPerSecond*2),A(p,i*e.driftPixelsPerSecond*.7)),radiusPx:ee*1.55,swirlPx:i*e.driftPixelsPerSecond})}}s.injectBatch(n)}s.step(l,f,d)}drawGhost(e,t,n){this.ghost?.available&&(this.ghost.setTint(n?z.darkColor:z.lightColor),this.ghost.drawTo(e,t,n))}captureState(){let e=this.smoke.captureState();try{let t=this.ghost?.captureState()??null;return{smoke:e,ghost:t,sources:this.sources.map(e=>({...e,point:{...e.point},flow:{...e.flow}})),smokeClock:this.smokeClock,ghostAttempted:this.ghostAttempted,ghostClock:this.ghostClock,ghostStyle:this.ghostStyle,ghostWallCoverage:new Map(this.ghostWallCoverage),ghostEmergence:new Map(this.ghostEmergence),dispose:()=>{e?.dispose(),t?.dispose()}}}catch(t){throw e?.dispose(),t}}restoreState(e){if(this.reset(),this.smoke.restoreState(e.smoke),this.ghostStyle=e.ghostStyle,e.ghost){this.ghost||(this.ghostAttempted=!1);let t=this.ghost??this.prepareGhost();if(!t)throw Error(`Ghost GPU context is unavailable`);t.restoreState(e.ghost),t.setGhostStyle(this.ghostStyle),this.ghostAttempted=e.ghostAttempted}else this.ghost?.dispose(),this.ghost=null,this.ghostAttempted=!1;this.sources=e.sources.map(e=>({...e,point:{...e.point},flow:{...e.flow}})),this.smokeClock=e.smokeClock,this.ghostClock=e.ghostClock,this.ghostWallCoverage=new Map(e.ghostWallCoverage),this.ghostEmergence=new Map(e.ghostEmergence)}reset(){this.smoke.reset(),this.ghost?.reset(),this.sources=[],this.smokeClock=0,this.ghostClock=0,this.ghostWallCoverage.clear(),this.ghostEmergence.clear()}dispose(){this.smoke.dispose(),this.ghost?.dispose()}},$v={world:2147483643,foreground:2147483644,backdrop:2147483645,hud:2147483646,controls:2147483647};function ey(e){return`calc(var(--joy-ride-z-index, ${$v.world}) + ${$v[e]-$v.world})`}var ty=`[data-jr-foreground]`,ny=new WeakMap;function ry(e=ty){let t=new Map,n=!1,r=!1,i=(e,t)=>{if(--t.users>0)return;ny.delete(e);let n=e.style;n.zIndex===ey(`foreground`)&&(t.zIndex?n.setProperty(`z-index`,t.zIndex,t.zIndexPriority):n.removeProperty(`z-index`)),t.positioned&&n.position===`relative`&&!t.position?n.removeProperty(`position`):t.positioned&&n.position===`relative`&&t.position===`static`&&n.setProperty(`position`,t.position,t.positionPriority),e.getAttribute(`data-jr-ui`)===``&&(t.ui===null?e.removeAttribute(`data-jr-ui`):e.setAttribute(`data-jr-ui`,t.ui))},a=new MutationObserver(()=>{r||(r=!0,queueMicrotask(()=>{r=!1,n||o()}))}),o=()=>{if(n)return;let r=new Set(e?[...document.querySelectorAll(e)].filter(e=>e instanceof HTMLElement&&e!==document.body&&e!==document.documentElement):[]);a.disconnect();for(let[e,n]of t)r.has(e)||(i(e,n),t.delete(e));for(let e of r){let n=e.style;if(!t.has(e)){let r=ny.get(e);r?r.users++:(r={position:n.position,positionPriority:n.getPropertyPriority(`position`),zIndex:n.zIndex,zIndexPriority:n.getPropertyPriority(`z-index`),ui:e.getAttribute(`data-jr-ui`),positioned:!1,users:1},ny.set(e,r)),t.set(e,r)}getComputedStyle(e).position===`static`&&(n.setProperty(`position`,`relative`,`important`),t.get(e).positioned=!0),n.setProperty(`z-index`,ey(`foreground`),`important`),e.setAttribute(`data-jr-ui`,``)}a.observe(document.body,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[`class`,`id`,`data-jr-foreground`,...[...e.matchAll(/\[([\w-]+)/g)].map(e=>e[1])]})};return o(),{refresh:o,dispose(){n=!0,a.disconnect();for(let[e,n]of t)i(e,n);t.clear()}}}var iy={color:[.14,.64,1],corona:[.28,.13,1]},ay=11,oy=`#version 300 es
648
- precision highp float;
649
- in vec2 aStart, aEnd, aMotion;
650
- in vec4 aStyle;
651
- in float aSeed;
652
- uniform vec2 uViewport;
653
- uniform vec4 uDisturbance;
654
- uniform float uDisturbanceRadius;
655
- out vec2 vLocal;
656
- out float vLength, vCooling, vKind, vSeed, vSize;
657
-
658
- vec2 emberPosition(float t) {
659
- float s = aSeed * 6.2831853;
660
- // Two incommensurate eddies give some firebrands a short reverse turn.
661
- // Their amplitudes and periods differ per particle, like turbulent lofting.
662
- float slow = 3.0 + fract(aSeed * 73.19) * 3.1;
663
- float fast = 7.5 + fract(aSeed * 41.73) * 6.2;
664
- vec2 eddy = vec2(
665
- (sin(slow*t+s*2.3)-sin(s*2.3)) * (5.0+fract(aSeed*91.7)*13.0)
666
- + (sin(fast*t-s*3.1)-sin(-s*3.1))*3.5,
667
- (cos(slow*t+s*1.7)-cos(s*1.7))*4.0
668
- + (sin(fast*t+s*4.7)-sin(s*4.7))*2.5);
669
- vec2 travel = aMotion*t + vec2(0.0, -t*t*(24.0+fract(aSeed*19.3)*38.0));
670
- vec2 point = aStart + travel + eddy;
671
- vec2 fromGust = point-uDisturbance.xy;
672
- float nearGust = exp(-dot(fromGust,fromGust) /
673
- max(1.0,uDisturbanceRadius*uDisturbanceRadius));
674
- vec2 turn = vec2(-fromGust.y,fromGust.x) /
675
- max(length(fromGust),14.0);
676
- point += (uDisturbance.zw*0.17+turn*length(uDisturbance.zw)*0.055)
677
- * nearGust * t;
678
- return point;
679
- }
680
-
681
- void main() {
682
- float age = aStyle.x;
683
- vCooling = clamp(age/max(aStyle.y,0.001),0.0,1.0);
684
- vKind = aStyle.w;
685
- vSeed = aSeed;
686
- vSize = aStyle.z;
687
- vec2 start = aStart;
688
- vec2 end = aEnd;
689
- if (vKind > 1.5 && vKind < 2.5) {
690
- start = emberPosition(max(0.0,age-(0.018+fract(aSeed*17.2)*0.024)));
691
- end = emberPosition(age);
692
- } else if (vKind > 2.5 && vKind < 3.5) {
693
- vec2 axis = vec2(cos(aSeed*6.2831853),sin(aSeed*6.2831853));
694
- start = aStart-axis*aStyle.z*0.12;
695
- end = aStart+axis*aStyle.z*0.12;
696
- }
697
- vec2 delta = end-start;
698
- float lengthPx = max(length(delta),0.01);
699
- vec2 axis = lengthPx < 0.1 ? vec2(1.0,0.0) : delta/lengthPx;
700
- vec2 normal = vec2(-axis.y,axis.x);
701
- vec2 corner[6] = vec2[6](
702
- vec2(0.0,-1.0),vec2(0.0,1.0),vec2(1.0,-1.0),
703
- vec2(1.0,-1.0),vec2(0.0,1.0),vec2(1.0,1.0));
704
- vec2 uv = corner[gl_VertexID];
705
- float radius = vKind > 3.5 ? max(7.0,aStyle.z*5.0) :
706
- vKind > 2.5 ? max(12.0,aStyle.z*2.4) :
707
- vKind > 1.5 ? max(8.0,aStyle.z*4.5) : max(7.0,aStyle.z*3.0);
708
- float axial = mix(-radius,lengthPx+radius,uv.x);
709
- float across = uv.y*radius;
710
- vLocal = vec2(axial,across);
711
- vLength = lengthPx;
712
- vec2 position = start+axis*axial+normal*across;
713
- gl_Position = vec4(position/uViewport*vec2(2.0,-2.0)+vec2(-1.0,1.0),0.0,1.0);
714
- }`,sy=`#version 300 es
715
- precision highp float;
716
- in vec2 vLocal;
717
- in float vLength, vCooling, vKind, vSeed, vSize;
718
- uniform float uFade;
719
- uniform vec2 uViewport;
720
- uniform int uWallCount;
721
- uniform vec4 uWalls[32];
722
- uniform vec3 uElectricColor;
723
- uniform vec3 uElectricCorona;
724
- out vec4 color;
725
- void main() {
726
- vec2 pixel = vec2(gl_FragCoord.x,uViewport.y-gl_FragCoord.y);
727
- for (int index=0;index<32;index++) {
728
- if (index>=uWallCount) break;
729
- vec4 wall = uWalls[index];
730
- if (pixel.x>=wall.x && pixel.x<=wall.z &&
731
- pixel.y>=wall.y && pixel.y<=wall.w) discard;
732
- }
733
- float dist = length(vLocal-vec2(clamp(vLocal.x,0.0,vLength),0.0));
734
- float aa = max(0.7,fwidth(dist));
735
- bool ember = vKind>1.5 && vKind<2.5;
736
- bool flash = vKind>2.5 && vKind<3.5;
737
- bool electrical = vKind>3.5;
738
- if (electrical) {
739
- float heat = pow(1.0-vCooling,0.85+vSeed*0.25);
740
- float coreRadius = 0.3+vSize*0.2;
741
- float core = 1.0-smoothstep(max(0.0,coreRadius-aa*0.7),coreRadius+aa*0.7,dist);
742
- float sheath = exp(-dist*dist/max(0.6,vSize*vSize*2.5));
743
- float glow = exp(-dist*dist/max(4.0,vSize*vSize*15.0));
744
- float flicker = 0.88+0.12*sin(vSeed*157.0+vCooling*52.0);
745
- vec3 cool = mix(uElectricCorona,uElectricColor,sheath);
746
- cool = mix(cool,vec3(0.92,0.985,1.0),core*heat*0.93);
747
- float alpha = clamp(core+sheath*0.28+glow*0.13,0.0,1.0)*heat*flicker*uFade;
748
- color = vec4(cool,alpha);
749
- return;
750
- }
751
- float heat = pow(1.0-vCooling,
752
- ember?0.55:flash?1.8:0.55+vSeed*0.8);
753
- // Cold metal loses its white core before its amber afterglow.
754
- float coreRadius = flash?2.0:ember?0.32+vSize*0.26:0.38+vSize*0.13;
755
- float core = 1.0-smoothstep(coreRadius-aa,coreRadius+aa,dist);
756
- float rim = 1.0-smoothstep(coreRadius+0.55-aa,coreRadius+0.55+aa,dist);
757
- float haloRadius = flash?7.0:ember?2.8+vSize*0.9:2.6+vSize*0.45;
758
- float glow = exp(-dist*dist/(haloRadius*haloRadius));
759
- float flicker = ember ? 0.83+0.17*sin(vSeed*139.1+vCooling*31.0) : 1.0;
760
- float alpha = clamp(core+rim*0.3+glow*(ember?0.22:0.18),0.0,1.0);
761
- alpha *= heat*flicker*uFade;
762
- vec3 orange = mix(vec3(0.85,0.16,0.012),vec3(1.0,0.53,0.07),heat);
763
- vec3 hot = mix(orange,vec3(1.0,0.88,0.45),
764
- clamp(rim*heat*1.3,0.0,1.0));
765
- hot = mix(hot,vec3(1.0,0.99,0.87),core*heat*0.85);
766
- if (flash) {
767
- hot = mix(vec3(1.0,0.44,0.025),vec3(1.0,0.96,0.62),core);
768
- alpha = max(alpha,glow*0.5*heat*uFade);
769
- }
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),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
- precision highp float;
773
- out vec2 uv;
774
- void main() {
775
- vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
776
- uv = p;
777
- gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
778
- }`,`#version 300 es
779
- precision highp float;
780
- in vec2 uv;
781
- out vec4 color;
782
- uniform sampler2D mask;
783
- uniform vec2 pixel;
784
- uniform float progress;
785
- uniform bool dark;
786
- void main() {
787
- float shape = texture(mask, uv).a;
788
- float nearShape = max(max(texture(mask, uv + vec2(pixel.x * 3.0, 0.0)).a,
789
- texture(mask, uv - vec2(pixel.x * 3.0, 0.0)).a),
790
- max(texture(mask, uv + vec2(0.0, pixel.y * 3.0)).a,
791
- texture(mask, uv - vec2(0.0, pixel.y * 3.0)).a));
792
- float rim = max(0.0, nearShape - shape);
793
- float sweep = exp(-pow((fract((uv.x + uv.y * 0.28) * 4.0 - progress * 2.2) - 0.5) * 10.0, 2.0));
794
- float pulse = sin(3.14159265 * progress);
795
- float alpha = clamp((shape * (0.15 + sweep * 0.6) + rim * 0.75) * pulse, 0.0, 0.78);
796
- vec3 tint = dark ? vec3(1.0, 0.86, 0.55) : vec3(0.72, 0.38, 0.08);
797
- color = vec4(tint, alpha);
798
- }`,`Object glint`),this.texture=e.createTexture(),this.texture||(Pv(e,this.program),this.program=null))}trigger(e,t,n,r){let i=this.gl;if(!i||!this.program||!this.texture)return;this.canvas.width=this.mask.width=Math.ceil(e*n),this.canvas.height=this.mask.height=Math.ceil(t*n);let a=this.mask.getContext(`2d`);a&&(a.setTransform(n,0,0,n,0,0),a.clearRect(0,0,e,t),r(a),i.bindTexture(i.TEXTURE_2D,this.texture),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,!0),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,this.mask),this.startedAt=performance.now())}draw(e,t,n,r){let i=this.gl,a=(performance.now()-this.startedAt)/this.duration;!i||!this.program||!this.texture||a<0||a>=1||(i.viewport(0,0,this.canvas.width,this.canvas.height),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT),i.useProgram(this.program),i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,this.texture),i.uniform1i(kv(this.program,`mask`),0),jv(this.program,{pixel:[1/this.canvas.width,1/this.canvas.height],progress:a,dark:Number(r)}),i.drawArrays(i.TRIANGLES,0,3),this.canvas.width*this.canvas.height/1e6,e.drawImage(this.canvas,0,0,t,n))}dispose(){this.gl&&(this.texture&&this.gl.deleteTexture(this.texture),this.program&&Pv(this.gl,this.program),this.texture=null,this.program=null)}};function Cb(e,t,n=!1){if(!t)return{...e};let r=e.x*t.scaleX,i=e.y*t.scaleY,a=Math.cos(t.angle),o=Math.sin(t.angle);return{x:(n?0:t.x)+r*a-i*o,y:(n?0:t.y)+r*o+i*a}}function wb(e,t,n){if(!n)return;let r=Math.cos(n.angle),i=Math.sin(n.angle);for(let a of[0,2]){let o=e[t+a]*n.scaleX,s=e[t+a+1]*n.scaleY;e[t+a]=n.x+o*r-s*i,e[t+a+1]=n.y+o*i+s*r}e[t+4]*=n.width,e[t+8]*=n.scaleX,e[t+9]*=n.scaleX}var Tb=(e,t,n)=>Math.max(t,Math.min(n,e)),Eb=(e,t)=>Number.isFinite(e)?e:t,Db=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y);function Ob(e,t){let n=!1;for(let r=0,i=e.length-1;r<e.length;i=r++){let a=e[r],o=e[i];a.y>t.y!=o.y>t.y&&t.x<(o.x-a.x)*(t.y-a.y)/(o.y-a.y)+a.x&&(n=!n)}return n}function kb(e,t,n){let r=n.x-t.x,i=n.y-t.y,a=Tb(((e.x-t.x)*r+(e.y-t.y)*i)/Math.max(1e-9,r*r+i*i),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)}function Ab(e,t,n){let r=t.x-e.x,i=t.y-e.y;for(let t=0,a=n.length-1;t<n.length;a=t++){let o=n[a],s=n[t],c=s.x-o.x,l=s.y-o.y,u=r*l-i*c;if(Math.abs(u)<1e-9)continue;let d=((o.x-e.x)*l-(o.y-e.y)*c)/u,f=((o.x-e.x)*i-(o.y-e.y)*r)/u;if(d>0&&d<1&&f>=0&&f<=1)return!0}return!1}function jb(e,t,n){if(e.kind===`point`)return!0;if(e.kind===`surface`)return!Ab(t,n,e.points)&&!(e.holes??[]).some(e=>Ab(t,n,e));let r=Math.max(8,Math.ceil(Db(t,n)/.75));for(let i=1;i<r;i++)if(!Mb(e,{x:t.x+(n.x-t.x)*i/r,y:t.y+(n.y-t.y)*i/r}))return!1;return!0}function Mb(e,t){if(e.kind===`point`)return Db(t,e.center)<=e.radius;if(e.kind===`surface`)return Ob(e.points,t)&&!(e.holes??[]).some(e=>Ob(e,t));let n=e.points.length;for(let r=1;r<n;r++)if(kb(t,e.points[r-1],e.points[r])<=e.width/2)return!0;return!!e.closed&&n>1&&kb(t,e.points[n-1],e.points[0])<=e.width/2}function Nb(e){if(e.kind===`point`)return{x:e.center.x-e.radius,y:e.center.y-e.radius,width:e.radius*2,height:e.radius*2};let t=e.kind===`path`?e.width/2:0,n=1/0,r=1/0,i=-1/0,a=-1/0;for(let t of e.points)n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x),a=Math.max(a,t.y);return{x:n-t,y:r-t,width:i-n+t*2,height:a-r+t*2}}function Pb(e,t){if(e.kind===`point`)return Math.max(0,e.radius-Db(t,e.center));let n=1/0,r=(e,r)=>{for(let r=1;r<e.length;r++)n=Math.min(n,kb(t,e[r-1],e[r]));r&&e.length>1&&(n=Math.min(n,kb(t,e.at(-1),e[0])))};if(e.kind===`path`)return r(e.points,!!e.closed),Math.max(0,e.width/2-n);r(e.points,!0);for(let t of e.holes??[])r(t,!0);return n}var Fb=class{onDischarge;onEmission;emissionFrame;setEmissionFrame(e){this.emissionFrame=e?{...e}:void 0}nodes=[];ionization=new Float32Array;ionScratch=new Float32Array;sources=[];targets=[];strokes=[];sourceCursor=0;randomState;nextStrike=0;accumulator=0;elapsed=0;sparkBudget=0;disposed=!1;shape;options;_spacing=10;constructor(e,t={}){this.options={seed:1,spacing:9,maxNodes:1800,strikesPerSecond:5,branching:.6,intensity:1,corona:0,nearbyTargets:!1,...t},this.randomState=this.options.seed>>>0||1,this.shape=e.shape,this.setDomain(e)}random(){let e=this.randomState;return e^=e<<13,e^=e>>>17,e^=e<<5,this.randomState=e>>>0,this.randomState/4294967296}configure(e){Object.assign(this.options,e)}get stats(){return{nodes:this.nodes.length,segments:this.strokes.reduce((e,t)=>e+t.segments.length,0),strokes:this.strokes.length,spacing:this._spacing,growing:this.strokes.filter(e=>!e.connected).length,ionizedNodes:this.ionization.reduce((e,t)=>e+ +(t>.08),0)}}setDomain(e){if(this.disposed)return;this.shape=e.shape,this.nodes=[],this.strokes=[],this.sources=[],this.targets=[],this.nextStrike=0,this.accumulator=0,this.ionization=new Float32Array;let t=Nb(e.shape);if(!Number.isFinite(t.width)||!Number.isFinite(t.height)||t.width<=0||t.height<=0)return;let n=Tb(Math.floor(Eb(this.options.maxNodes,1800)),64,4096),r=Math.max(3,Eb(this.options.spacing,9),Math.sqrt(t.width*t.height/n)*1.1,t.width/512,t.height/512);this._spacing=r;let i=Math.ceil(t.width/r)+1,a=Math.ceil(t.height/r)+1,o=new Int32Array(i*a).fill(-1);for(let e=0;e<a;e++)for(let a=0;a<i;a++){let s={x:t.x+(a+.2+this.random()*.6)*r,y:t.y+(e+.2+this.random()*.6)*r};this.nodes.length>=n||!Mb(this.shape,s)||(o[e*i+a]=this.nodes.length,this.nodes.push({...s,links:[]}))}for(let e=0;e<a;e++)for(let t=0;t<i;t++){let n=o[e*i+t];if(n<0)continue;let r=this.nodes[n];for(let n=-1;n<=1;n++)for(let s=-1;s<=1;s++){let c=t+s,l=e+n;if(!s&&!n||c<0||l<0||c>=i||l>=a)continue;let u=o[l*i+c];u<0||jb(this.shape,r,this.nodes[u])&&r.links.push(u)}}this.ionization=new Float32Array(this.nodes.length),this.ionScratch=new Float32Array(this.nodes.length),this.setElectrodes(e.sources,e.targets)}setElectrodes(e,t){this.disposed||(this.sources=e.map(e=>this.closest(e)).filter(e=>e>=0),this.sourceCursor=0,t&&(this.targets=t.map(e=>this.closest(e)).filter(e=>e>=0)))}closest(e){let t=-1,n=1/0;for(let r=0;r<this.nodes.length;r++){let i=Db(this.nodes[r],e);i<n&&(t=r,n=i)}return t}relax(e,t){for(let n=0;n<t;n++){let t=e.potential,n=e.scratch;for(let r=0;r<this.nodes.length;r++){if(r===e.target){n[r]=1;continue}if(e.grounded[r]){n[r]=0;continue}let i=this.nodes[r].links,a=0;for(let e=0;e<i.length;e++)a+=t[i[e]];n[r]=i.length?a/i.length:0}e.potential=n,e.scratch=t}}strike(){if(this.strokes.length>=10||!this.nodes.length||!this.sources.length||!this.targets.length)return;let e=this.sources[this.sourceCursor];this.sourceCursor=(this.sourceCursor+1)%this.sources.length;let t=0;for(let n of this.targets)t=Math.max(t,Db(this.nodes[e],this.nodes[n]));let n=this.targets.filter(n=>{let r=Db(this.nodes[e],this.nodes[n]);return this.options.nearbyTargets?r>Math.max(this._spacing*3,t*.16)&&r<t*.65:r>=t*.6}),r=n.length?n:this.targets,i=r[Math.floor(this.random()*r.length)];if(i===e&&(i=this.targets.find(t=>t!==e)??e),i===e)return;let a=this.nodes.length,o=new Int32Array(a).fill(-1),s=new Int32Array(a);o[i]=0,s[0]=i;let c=0,l=1;for(;c<l;){let e=s[c++];for(let t of this.nodes[e].links)o[t]<0&&(o[t]=o[e]+1,s[l++]=t)}if(o[e]<0)return;let u=new Float32Array(a),d=new Uint8Array(a);d[e]=1;let f=Math.max(1,o[e]);for(let e=0;e<a;e++)u[e]=o[e]<0?0:Tb(1-o[e]/(f+2),.01,1);let p=this.vertex(this.nodes[e],-1,1,0,e,!1),m={frame:this.emissionFrame?{...this.emissionFrame}:void 0,segments:[],vertices:[p],fronts:[{at:e,vertex:0,distance:0,branch:!1,steps:0,limit:256,budget:0,energy:1,diffuse:!1}],potential:u,scratch:new Float32Array(a),grounded:d,hops:o,target:i,source:e,age:0,life:.75+this.random()*.35,seed:this.random(),connected:!1,noise:0,drive:.6,pulse:0,sparkTimer:.02};m.fronts[0].diffuse=this.random()<this.options.corona*.45,this.relax(m,12),this.strokes.push(m)}vertex(e,t,n,r,i,a){return{position:{x:e.x,y:e.y},rest:{x:e.x,y:e.y},velocity:{x:0,y:0},parent:t,children:[],base:n,charge:0,arc:r,node:i,diffuse:a,clearance:Pb(this.shape,e),motionRadius:3}}choose(e,t){let n=this.nodes[t.at].links,r=n=>{if(e.grounded[n]||e.hops[n]<0||!t.branch&&e.hops[n]>=e.hops[t.at])return 0;let r=e.hops[t.at]-e.hops[n];if(t.branch&&t.direction){if(n===e.target)return 0;let r=this.nodes[n].x-this.nodes[t.at].x,i=this.nodes[n].y-this.nodes[t.at].y,a=(r*t.direction.x+i*t.direction.y)/Math.max(.001,Math.hypot(r,i));return Math.max(.02,a+.25)**2*(.6+e.potential[n]*.4)}return Math.max(.015,e.potential[n])**1.7*(r>0?3.5:.25)*(1+this.ionization[n]*4)},i=0;for(let e of n)i+=r(e);if(!i)return-1;let a=this.random()*i;for(let e of n)if(a-=r(e),a<=0&&r(e)>0)return e;return-1}grow(e,t){for(let n=e.fronts.length-1;n>=0;n--){let r=e.fronts[n];r.budget+=t*(r.branch?1250:3200);let i=0;for(;r.budget>=this._spacing*.55&&i++<8;){let t=this.choose(e,r);if(t<0||r.steps>=r.limit||e.segments.length>=690){e.fronts.splice(n,1);break}let i=this.nodes[r.at],a=this.nodes[t],o=Db(i,a);if(r.budget<o)break;r.budget-=o;let s={x:-(a.y-i.y)/o,y:(a.x-i.x)/o},c=r.vertex,l=Math.max(2,Math.ceil(o/4)),u=(this.random()-.5)*Math.min(3,this._spacing*.3);for(let n=1;n<=l;n++){let d=n/l,f={x:i.x+(a.x-i.x)*d,y:i.y+(a.y-i.y)*d},p={x:f.x+s.x*Math.sin(d*Math.PI)*u,y:f.y+s.y*Math.sin(d*Math.PI)*u},m=e.vertices[c].position,h=Mb(this.shape,p)&&jb(this.shape,e.vertices[c].rest,p)&&jb(this.shape,m,p)&&jb(this.shape,p,a)?p:f,g=r.energy*(r.branch?Math.max(.08,1-r.steps/r.limit):1),_=this.vertex(h,c,g,r.distance+o*d,t,r.diffuse),v=e.vertices[c],y=Db(v.rest,_.rest),b={x:(v.rest.x+h.x)/2,y:(v.rest.y+h.y)/2},x=Math.max(0,Math.min(v.clearance,_.clearance,Pb(this.shape,b))-y/4)*.45;v.motionRadius=Math.min(v.motionRadius,x),_.motionRadius=Math.min(3,x);let S=e.vertices.length;e.vertices[c].children.push(S),e.vertices.push(_),e.segments.push({start:m,end:_.position,energy:g,distance:e.vertices[c].arc,length:Db(m,h),branch:r.branch}),c=S}if(r.vertex=c,r.distance+=o,r.at=t,r.steps++,e.grounded[t]=1,this.ionization[t]=Math.min(1,this.ionization[t]+.28),!r.branch&&r.steps%3==0&&this.relax(e,2),(!r.branch||this.options.branching>1&&r.energy>.2)&&r.steps>2&&e.fronts.length<9&&this.random()<this.options.branching*(r.branch?.08:.26)){let n=this.random()<.5?-1:1,l=this.options.branching>1?{x:s.x*n*.85+(a.x-i.x)/o*.35,y:s.y*n*.85+(a.y-i.y)/o*.35}:void 0;e.fronts.push({direction:l,at:t,vertex:c,distance:r.distance,branch:!0,steps:0,limit:2+Math.floor(this.random()*(7+Math.max(0,this.options.branching-1)*10)),budget:0,energy:r.energy*(.45+this.random()*.2),diffuse:this.random()<this.options.corona})}if(t===e.target){e.fronts.splice(n,1),!r.branch&&!e.connected&&(e.connected=!0,e.pulse=.2,this.onDischarge?.({source:Cb(this.nodes[e.source],e.frame),target:Cb(this.nodes[e.target],e.frame),segments:e.frame?e.segments.map(t=>({...t,start:Cb(t.start,e.frame),end:Cb(t.end,e.frame)})):e.segments}));break}}}}advance(e,t){e.age+=t,this.grow(e,t),e.noise+=-e.noise*8*t+(this.random()-.5)*Math.sqrt(t)*1.6,e.pulse*=Math.exp(-t*18);let n=.57+.15*Math.sin(this.elapsed*3.4+e.seed*17)+e.noise*.24+e.pulse;e.drive+=(Tb(n,.25,1)-e.drive)*(1-Math.exp(-t*12));let r=Math.exp(-t*11),i=1-Math.exp(-t*36);for(let n=0;n<e.vertices.length;n++){let a=e.vertices[n],o=.9+.1*Math.sin(this.elapsed*15-a.arc*.035+e.seed*9),s=a.parent<0?e.drive:e.vertices[a.parent].charge,c=(e.drive*.78+s*.22)*a.base*o;if(a.charge+=(c-a.charge)*i,this.options.corona>0&&(this.ionization[a.node]=Math.min(1,this.ionization[a.node]+t*a.charge*.8)),a.parent<0||a.node===e.target)continue;let l=a.position,u=a.rest,d=a.velocity,f=u.x*.031,p=u.y*.031,m=this.elapsed,h=Math.sin(f+m*.8)*Math.cos(p-m*1.1)+.4*Math.cos(f*2.7-p*1.9+m*2.6),g=-Math.cos(f+m*.8)*Math.sin(p-m*1.1)+.4*Math.sin(f*2.7-p*1.9+m*2.6);d.x=(d.x+((u.x-l.x)*65+h*130)*t)*r,d.y=(d.y+((u.y-l.y)*65+g*130)*t)*r;let _={x:l.x+d.x*t,y:l.y+d.y*t},v=_.x-u.x,y=_.y-u.y,b=Math.hypot(v,y);b>a.motionRadius&&b>0?(l.x=u.x+v/b*a.motionRadius,l.y=u.y+y/b*a.motionRadius,d.x*=.4,d.y*=.4):(l.x=_.x,l.y=_.y)}if(e.sparkTimer-=t,e.sparkTimer<=0&&this.sparkBudget>=1&&e.vertices.length>3&&e.age<e.life-.15){let t=e.vertices[Math.floor(this.random()*(e.vertices.length-1))+1];if(t.charge>.12){let n=e.vertices[t.parent].position,r=t.position.x-n.x,i=t.position.y-n.y,a=this.random()<.5?-1:1;this.onEmission?.({point:Cb(t.position,e.frame),direction:Cb({x:-i*a,y:r*a},e.frame,!0),strength:.2+t.charge*.35}),this.sparkBudget--}e.sparkTimer=.075+this.random()*.09}}step(e){if(this.disposed)return;this.accumulator+=Tb(Eb(e,0),0,.05);let t=1/120;for(;this.accumulator>=.008333332333333334;){if(this.accumulator-=t,this.elapsed+=t,this.sparkBudget=Math.min(3,this.sparkBudget+t*36),this.options.corona>0){for(let e=0;e<this.nodes.length;e++){let n=this.nodes[e].links,r=0;for(let e of n)r+=this.ionization[e];let i=this.ionization[e],a=n.length?r/n.length:i;this.ionScratch[e]=Math.max(0,i+(a-i)*t*18-i*t*1.4)}let e=this.ionization;this.ionization=this.ionScratch,this.ionScratch=e}else for(let e=0;e<this.ionization.length;e++)this.ionization[e]*=.99;for(let e=this.strokes.length-1;e>=0;e--){let n=this.strokes[e];this.advance(n,t),n.age>=n.life&&this.strokes.splice(e,1)}this.nextStrike-=t,this.nextStrike<=0&&this.options.strikesPerSecond>0&&(this.strike(),this.nextStrike=(.8+this.random()*.4)/Tb(this.options.strikesPerSecond,.1,30))}}discharge(e=1){if(!this.disposed){for(let t=0;t<Tb(Math.round(Eb(e,1)),1,4);t++)this.strike();this.nextStrike=(.8+this.random()*.4)/Tb(Eb(this.options.strikesPerSecond,1),.1,30)}}writeInstances(e,t=0){let n=Math.min(Math.floor(e.length/10),Math.max(0,Math.floor(Eb(t,0)))),r=n,i=Tb(Eb(this.options.intensity,1),0,3);for(let t=this.strokes.length-1;t>=0;t--){let a=this.strokes[t],o=Tb((a.life-a.age)/.24,0,1),s=o*o*(3-2*o);for(let t=0;t<a.segments.length;t++){if(r*10+10>e.length)return r-n;let o=a.segments[t],c=a.vertices[t+1],l=a.vertices[c.parent],u=(c.charge+l.charge)*.5*i*s;if(u<.008)continue;let d=r++*10;e[d]=o.start.x,e[d+1]=o.start.y,e[d+2]=o.end.x,e[d+3]=o.end.y,e[d+4]=o.branch?.65:1.05,e[d+5]=u,e[d+6]=a.seed,e[d+7]=c.diffuse?3:+!!o.branch,e[d+8]=o.distance,e[d+9]=o.distance+o.length,wb(e,d,a.frame)}for(let t=0;t<(a.connected?2:1)&&!(r*10+10>e.length);t++){let n=t===0?a.vertices[0].position:this.nodes[a.target],o=r++*10;e[o]=n.x,e[o+1]=n.y,e[o+2]=n.x+.1,e[o+3]=n.y,e[o+4]=1.25,e[o+5]=a.drive*i*s*.5,e[o+6]=a.seed,e[o+7]=2,e[o+8]=0,e[o+9]=1,wb(e,o,a.frame)}}if(this.options.corona>0&&!this.emissionFrame){let t=Math.max(1,Math.ceil(this.nodes.length/128));for(let n=0;n<this.nodes.length&&!(r*10+10>e.length);n+=t){let t=this.ionization[n]*this.options.corona*i*.7;if(t<.01)continue;let a=this.nodes[n],o=r++*10;e[o]=a.x,e[o+1]=a.y,e[o+2]=a.x+.1,e[o+3]=a.y,e[o+4]=.9,e[o+5]=t,e[o+6]=n/Math.max(1,this.nodes.length),e[o+7]=4,e[o+8]=0,e[o+9]=1}}return r-n}reset(){this.strokes=[],this.nextStrike=0,this.accumulator=0,this.ionization.fill(0)}dispose(){this.reset(),this.nodes=[],this.sources=[],this.targets=[],this.ionization=new Float32Array,this.ionScratch=new Float32Array,this.onDischarge=void 0,this.onEmission=void 0,this.disposed=!0}},Ib=`#version 300 es
799
- precision highp float;
800
- in vec2 aStart;
801
- in vec2 aEnd;
802
- in vec4 aStyle;
803
- in vec2 aDistance;
804
- uniform vec2 uViewport;
805
- out vec2 vLocal;
806
- out vec2 vScreen;
807
- out float vLength;
808
- out float vWidth;
809
- out float vEnergy;
810
- out float vSeed;
811
- out float vKind;
812
- out vec2 vDistance;
813
-
814
- void main() {
815
- vec2 delta = aEnd-aStart;
816
- float lengthPx = length(delta);
817
- vec2 axis = lengthPx>0.001 ? delta/lengthPx : vec2(1.0,0.0);
818
- vec2 normal = vec2(-axis.y,axis.x);
819
- vec2 corners[6] = vec2[6](
820
- vec2(0.0,-1.0),vec2(0.0,1.0),vec2(1.0,-1.0),
821
- vec2(1.0,-1.0),vec2(0.0,1.0),vec2(1.0,1.0));
822
- vec2 corner = corners[gl_VertexID];
823
- float width = max(0.12,aStyle.x);
824
- bool contact = aStyle.w>1.5 && aStyle.w<2.5;
825
- bool field = aStyle.w>2.5;
826
- // The broad halo is deliberately cheap and local: no fullscreen bloom or
827
- // oversized transparent quad. Contacts earn a larger soft pool of light.
828
- float radius = aStyle.w>4.5 ? width*1.25 : contact ? max(48.0,width*70.0) :
829
- field ? (aStyle.w<3.5 ? max(18.0,width*12.0) : max(28.0,width*76.0)) :
830
- aStyle.w<0.5 ? max(18.0,width*38.0) : max(12.0,width*26.0);
831
- vec2 local = vec2(mix(-radius,lengthPx+radius,corner.x),corner.y*radius);
832
- vec2 position = aStart+axis*local.x+normal*local.y;
833
- vLocal=local;
834
- vScreen=position;
835
- vLength=lengthPx;
836
- vWidth=width;
837
- vEnergy=max(0.0,aStyle.y);
838
- vSeed=aStyle.z;
839
- vKind=aStyle.w;
840
- vDistance=aDistance;
841
- gl_Position=vec4(position/uViewport*vec2(2.0,-2.0)+vec2(-1.0,1.0),0.0,1.0);
842
- }`,Lb=`#version 300 es
843
- precision highp float;
844
- in vec2 vLocal;
845
- in vec2 vScreen;
846
- in float vLength;
847
- in float vWidth;
848
- in float vEnergy;
849
- in float vSeed;
850
- in float vKind;
851
- in vec2 vDistance;
852
- uniform float uTime;
853
- uniform vec3 uColor;
854
- uniform vec3 uCorona;
855
- uniform float uExposure;
856
- uniform float uDark;
857
- uniform vec2 uNoiseOrigin;
858
- uniform float uNoiseScale;
859
- out vec4 color;
860
-
861
- float hash(float p) { return fract(sin(p*127.1+311.7)*43758.5453); }
862
- float airHash(vec2 p) {
863
- vec3 q=fract(vec3(p.xyx)*0.1031);
864
- q+=dot(q,q.yzx+33.33);
865
- return fract((q.x+q.y)*q.z);
866
- }
867
- float airNoise(vec2 p) {
868
- vec2 cell=floor(p), f=fract(p);
869
- f=f*f*(3.0-2.0*f);
870
- return mix(mix(airHash(cell),airHash(cell+vec2(1.0,0.0)),f.x),
871
- mix(airHash(cell+vec2(0.0,1.0)),airHash(cell+1.0),f.x),f.y);
872
- }
873
- // Neighboring collinear segments partition their halo at the joint instead of
874
- // adding bright beads. Short segments get a proportionate share of soft light.
875
- float finiteChannel(float reach) {
876
- return max(0.0,smoothstep(-reach,reach,vLocal.x)-
877
- smoothstep(vLength-reach,vLength+reach,vLocal.x));
878
- }
879
-
880
- void main() {
881
- float axisPosition=clamp(vLocal.x,0.0,vLength);
882
- vec2 fromChannel=vLocal-vec2(axisPosition,0.0);
883
- float distancePx=length(fromChannel);
884
- bool contact=vKind>1.5 && vKind<2.5;
885
- bool branch=vKind>0.5 && vKind<1.5;
886
- bool field=vKind>2.5;
887
- float energy=clamp(vEnergy,0.0,2.4);
888
- if (energy<0.002) discard;
889
- vec2 mediumPosition=vScreen*uNoiseScale+uNoiseOrigin;
890
- if (vKind>4.5) {
891
- // Excited air fills the influence disk. No ring edge or sprite-shaped mask.
892
- float r=length(vLocal)/max(1.0,vWidth);
893
- float envelope=exp(-r*r*2.4)*(1.0-smoothstep(0.75,1.22,r));
894
- vec2 flow=mediumPosition*0.018+vec2(uTime*0.045,-uTime*0.035);
895
- float coarse=airNoise(flow);
896
- if (vSeed>0.5) {
897
- // Two overlapping advection windows prevent an ever-increasing angular
898
- // frequency (radial streaks) or a visible reset as vapor travels inward.
899
- vec2 radial=normalize(vLocal+vec2(0.001));
900
- vec2 drift=radial*2.4+vec2(-radial.y,radial.x)*0.45;
901
- float phase=fract(uTime*0.16);
902
- float weight=1.0-abs(phase*2.0-1.0);
903
- vec2 base=mediumPosition*0.018;
904
- coarse=mix(airNoise(base+drift*fract(phase+0.5)),airNoise(base+drift*phase),weight);
905
- flow=base;
906
- }
907
- float detail=airNoise(flow*2.7+coarse*1.7+vec2(-uTime*0.065,uTime*0.025));
908
- float wisps=smoothstep(0.20,0.85,coarse*0.65+detail*0.35);
909
- vec3 tint=mix(uCorona,uColor,0.55+detail*0.3);
910
- float density=envelope*(0.055+wisps*0.24)*energy*uExposure;
911
- float alpha=density*mix(0.10,1.0,uDark);
912
- color=vec4(mix(vec3(0.36,0.38,0.42),tint,uDark)*alpha,alpha);
913
- return;
914
- }
915
- if (vKind>2.5 && vKind<3.5) {
916
- // Inward current reveals suspended vapor, with no hard electrical core.
917
- float along=mix(vDistance.x,vDistance.y,clamp(vLocal.x/max(vLength,0.001),0.0,1.0));
918
- float pulse=pow(0.5+0.5*cos(along*0.055-uTime*5.0+vSeed*6.283),7.0);
919
- float body=exp(-vLocal.y*vLocal.y/max(1.0,vWidth*vWidth*2.8));
920
- float mist=exp(-vLocal.y*vLocal.y/max(3.0,vWidth*vWidth*12.0));
921
- float grain=0.45+0.55*airNoise(mediumPosition*0.06+uTime*0.08);
922
- float alpha=energy*(body*0.8+mist*0.14)*(0.20+pulse)*grain*finiteChannel(7.0)*uExposure;
923
- alpha*=mix(0.35,1.0,uDark);
924
- vec3 tint=mix(vec3(0.25,0.28,0.33),vec3(0.65,0.79,0.9),uDark);
925
- color=vec4(tint*alpha,alpha);
926
- return;
927
- }
928
- if (vKind>3.5) {
929
- // Isotropic density from a simulated cloud cell, not an electrical line.
930
- // Shared advected texture connects overlapping cells into wisps; it only
931
- // reveals the density supplied by the simulation and never births clouds.
932
- float r2=dot(fromChannel,fromChannel);
933
- float inner=exp(-r2/max(48.0,vWidth*vWidth*150.0));
934
- float outer=exp(-r2/max(100.0,vWidth*vWidth*520.0));
935
- vec2 flow=mediumPosition*0.032+vec2(uTime*0.055,-uTime*0.035);
936
- float body=airNoise(flow);
937
- float detail=airNoise(mediumPosition*0.095+vec2(-uTime*0.08,uTime*0.06)+body*0.5);
938
- float wisp=smoothstep(0.20,0.84,body*0.68+detail*0.32);
939
- vec3 tint=mix(uCorona,uColor,0.35+detail*0.32);
940
- float density=energy*(inner*0.24+outer*0.20)*wisp;
941
- density*=mix(0.18,1.0,clamp(uDark,0.0,1.0))*max(0.0,uExposure);
942
- tint=mix(vec3(0.30,0.33,0.38),tint,uDark);
943
- vec3 emission=clamp(tint*density,0.0,1.0);
944
- float opacity=max(emission.r,max(emission.g,emission.b));
945
- if (opacity<0.0005) discard;
946
- color=vec4(emission,opacity);
947
- return;
948
- }
949
- float aa=max(0.55,fwidth(distancePx));
950
- float charge=sqrt(min(energy,1.0));
951
- // Fractional-pixel coverage retains fine capillaries as charge wanes, with
952
- // width controlled by simulated local current rather than per-segment waves.
953
- float radius=vWidth*(field?0.24:branch?0.42:0.53)*
954
- (branch?0.35+0.65*charge:0.60+0.40*charge);
955
- float core=clamp((radius+aa*0.5-distancePx)/aa,0.0,1.0);
956
- float sheath=exp(-distancePx*distancePx/max(0.35,radius*radius*6.0));
957
- float closeScale=max(2.0,vWidth*vWidth*(field?75.0:35.0));
958
- float closeHalo=contact ? exp(-distancePx*distancePx/closeScale) :
959
- exp(-vLocal.y*vLocal.y/closeScale)*finiteChannel(sqrt(closeScale)*1.4);
960
- // A little off-axis corona avoids a uniform Photoshop outer-glow silhouette.
961
- float drift=(hash(vSeed+4.7)-0.5)*vWidth*(field?12.0:branch?2.8:7.0);
962
- vec2 softOffset=fromChannel-vec2(0.0,drift);
963
- float broadScale=max(9.0,vWidth*vWidth*(field?600.0:branch?85.0:196.0));
964
- float broadHalo=contact ? exp(-dot(softOffset,softOffset)/broadScale) :
965
- exp(-pow(vLocal.y-drift,2.0)/broadScale)*finiteChannel(sqrt(broadScale)*1.4);
966
- // A shared drifting air field gives the low-density corona depth without
967
- // moving the actual channel. Brightness/motion stay rooted in the simulation.
968
- vec2 air=mediumPosition*0.034+vec2(uTime*0.085,-uTime*0.055);
969
- float along=mix(vDistance.x,vDistance.y,clamp(vLocal.x/max(vLength,0.001),0.0,1.0));
970
- float vapor=airNoise(air+vec2(0.0,along*0.0008));
971
- float atmosphere=0.30+0.70*vapor*vapor;
972
- float grain=0.82+0.18*airNoise(mediumPosition*0.18-vec2(uTime*0.13,uTime*0.08));
973
- float darkness=clamp(uDark,0.0,1.0);
974
- float glowScale=mix(0.22,1.0,darkness);
975
- vec3 dayColor=mix(uColor*vec3(0.18,0.40,0.72),vec3(0.035,0.22,0.72),0.35);
976
- vec3 whiteHot=mix(dayColor,
977
- mix(uColor,vec3(0.93,0.985,1.0),0.12+0.88*smoothstep(0.14,1.05,energy)),darkness);
978
- vec3 sheathColor=mix(dayColor,uColor,darkness);
979
- vec3 light=(field?sheathColor:whiteHot)*core*(field?0.18:0.92);
980
- light+=sheathColor*(sheath*(field?0.055:0.19)+closeHalo*(field?0.13:branch?0.075:0.10))*glowScale;
981
- light+=mix(uCorona,uColor,field?0.45:0.22)*broadHalo*(field?0.19:branch?0.025:0.115)*atmosphere*grain*glowScale;
982
- light*=energy/(0.72+0.28*min(energy,1.0));
983
- if (contact) {
984
- // Brief terminal attachment light, not a decorative six-point star.
985
- float pool=exp(-distancePx*distancePx/max(90.0,vWidth*vWidth*490.0));
986
- float attachment=exp(-distancePx*distancePx/max(12.0,vWidth*vWidth*55.0));
987
- float pin=exp(-distancePx*distancePx/max(0.2,vWidth*vWidth*0.55));
988
- light+=(mix(uCorona,sheathColor,0.7)*pool*0.21+
989
- sheathColor*attachment*0.19)*energy*glowScale+whiteHot*pin*energy*0.45;
990
- }
991
- if (uDark<0.5) {
992
- // Daylight plasma: a fine white-hot core, a neutral ionized sheath and very
993
- // little colored emission. Alpha compositing avoids blue marker-like lines.
994
- float edge=exp(-distancePx*distancePx/max(1.0,vWidth*vWidth*3.5));
995
- float neutralHalo=edge*0.08;
996
- float hot=core*(branch?0.42:0.95)*min(1.0,energy);
997
- float scatter=(closeHalo*0.08+broadHalo*atmosphere*0.035)*(branch?0.45:1.0);
998
- if (contact) scatter+=exp(-distancePx*distancePx/max(36.0,vWidth*vWidth*180.0))*0.22;
999
- float total=hot+neutralHalo+scatter;
1000
- float alpha=clamp(total*min(1.0,energy)*uExposure,0.0,0.96);
1001
- vec3 tint=(vec3(0.28,0.29,0.35)*neutralHalo+vec3(0.95,0.97,1.0)*hot+vec3(0.80,0.84,0.96)*scatter)/max(0.001,total);
1002
- color=vec4(tint*alpha,alpha);
1003
- return;
1004
- }
1005
- light=clamp(light*max(0.0,uExposure),0.0,1.0);
1006
- float alpha=max(light.r,max(light.g,light.b));
1007
- if (alpha<0.001) discard;
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.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
- * combustion-worklet.js — the engine's source, one combustion event at a time.
1011
- *
1012
- * Runs on the audio thread (AudioWorkletProcessor 'engine-combustion').
1013
- *
1014
- * The wavetable source (pulse.js) builds ONE 720° cycle per bank and repeats
1015
- * it forever: every cycle identical to the sample. A real engine never does
1016
- * that. Peak cylinder pressure varies cycle to cycle (COV of IMEP ≈ 1-3 % at
1017
- * full load, 5-15 % at idle and on a lumpy cam), ignition timing wanders by a
1018
- * degree or so, and a cylinder occasionally burns badly or not at all. That
1019
- * variation is not noise laid on top of the engine — it is energy spread into
1020
- * sidebands AROUND the engine's own harmonics, tied to its firing, and it is
1021
- * most of what makes a recording sound like a machine instead of an organ.
1022
- * The old graph faked it with slow LFO vibrato on the whole engine and with
1023
- * noise beds; this generates it where it happens.
1024
- *
1025
- * Per sample: the crank phase advances by f0 / sampleRate (f0 = one 720°
1026
- * cycle per second). When it passes a cylinder's firing angle (+ that
1027
- * cylinder's fixed trim + this event's jitter), a pressure pulse starts on that
1028
- * cylinder's bank output:
1029
- *
1030
- * p(t) = A · g(t) · (1 − e^(−a·t)) · e^(−b·t) t in cycles since firing
1031
- *
1032
- * with the same attack/decay law as pulse.js (load hardens it continuously
1033
- * instead of crossfading two tables), A carrying the cylinder's trim and this
1034
- * cycle's variation, and g(t) a ~60 µs Gaussian onset so the gradient has no
1035
- * step to alias. The output is the pressure GRADIENT (what an open pipe
1036
- * radiates), per unit of crank phase so it is rpm-independent, through a
1037
- * one-pole lowpass at RADIATION_KNEE half-orders — the time-domain version of
1038
- * pulse.js's radiation shelf — and scaled by a calibration gain computed on the
1039
- * main thread from the same shape (\`combustionGains\` in pulse.js).
1040
- *
1041
- * Outputs: one per exhaust bank, then the intake (all cylinders, 360° earlier).
1042
- *
1043
- * AudioParams (k-rate): f0, load, amp, rough (0..1 misfires + extra variation),
1044
- * ripple (crank-speed swing per firing, see pulse.js crankRipple) and low
1045
- * (1 at idle, 0 at redline).
1046
- *
1047
- * CRANK-SPEED RIPPLE. The crank does not turn evenly: every firing kicks it
1048
- * faster and the compression strokes in between brake it. \`v\` is that speed
1049
- * deviation: each firing adds \`ripple × its own strength\`, and it is drawn
1050
- * back down continuously at the average rate, so it is a sawtooth around
1051
- * zero. The crank phase advances at \`dph × (1 + v)\`, so every pulse — and the
1052
- * timing of the next firing — is frequency-modulated by the engine's own
1053
- * firings. A strong firing pulls the next one early, a weak one lets it come
1054
- * late: asymmetry and irregularity that come from the mechanism, and fade
1055
- * with ω² as it revs.
1056
- *
1057
- * LOW-RPM SCATTER. Combustion is least repeatable at low speed: the flame is
1058
- * slow, turbulence is low, and cylinder-to-cylinder air distribution is at its
1059
- * worst. So \`low\` widens the cycle-to-cycle variation, the timing jitter, and
1060
- * each cylinder's fixed imbalance.
1061
- */
1062
-
1063
- const KNEE_HALF_ORDERS = 48; // = RADIATION_KNEE_ORDER (24) × 2
1064
- const ONSET_S = 60e-6; // Gaussian onset time constant
1065
-
1066
- class CombustionProcessor extends AudioWorkletProcessor {
1067
- static get parameterDescriptors() {
1068
- return [
1069
- { name: 'f0', defaultValue: 10, minValue: 0, maxValue: 4000, automationRate: 'k-rate' },
1070
- { name: 'load', defaultValue: 0, minValue: 0, maxValue: 1, automationRate: 'k-rate' },
1071
- { name: 'amp', defaultValue: 0, minValue: 0, maxValue: 8, automationRate: 'k-rate' },
1072
- { name: 'rough', defaultValue: 0, minValue: 0, maxValue: 1, automationRate: 'k-rate' },
1073
- { name: 'ripple', defaultValue: 0, minValue: 0, maxValue: 0.2, automationRate: 'k-rate' },
1074
- { name: 'low', defaultValue: 0, minValue: 0, maxValue: 1, automationRate: 'k-rate' },
1075
- ];
1076
- }
1077
-
1078
- constructor(options) {
1079
- super();
1080
- const o = options.processorOptions;
1081
- // events: [{ out, angle (cycles 0..1), ampTrim, decayTrim }] sorted by angle
1082
- this.events = o.events;
1083
- this.nOut = o.outputs;
1084
- this.attack = o.attack;
1085
- this.decay = o.decay;
1086
- this.hardness = o.hardness; // normalised (1 = the 0.65 reference)
1087
- this.ccv = o.ccv; // cycle-to-cycle amplitude COV at full load
1088
- this.jitterCycles = o.jitterDeg / 720;
1089
- this.gains = o.gains; // [out][5] calibration over load 0..1
1090
- this.abs = 0; // crank position, in cycles, absolute
1091
- this.pulses = []; // active pulses
1092
- this.pool = [];
1093
- this.prevP = new Float64Array(this.nOut);
1094
- this.lp = new Float64Array(this.nOut);
1095
- // Each event's next firing, in absolute cycles: its cycle index + angle +
1096
- // this cycle's jitter. Advancing the index by exactly one per firing means
1097
- // jitter can never fire an event twice, or skip one.
1098
- this.cycleOf = new Float64Array(this.events.length);
1099
- this.nextAt = Float64Array.from(this.events, (e) => e.angle);
1100
- this.seed = (o.seed >>> 0) || 1;
1101
- this.v = 0; // crank-speed deviation, fraction
1102
- this.nFire = this.events.filter((e) => e.out < this.nOut - 1).length;
1103
- this.alive = true;
1104
- this.port.onmessage = (m) => { if (m.data === 'stop') this.alive = false; };
1105
- }
1106
-
1107
- rand() {
1108
- let s = this.seed;
1109
- s ^= s << 13; s >>>= 0; s ^= s >> 17; s ^= s << 5; s >>>= 0;
1110
- this.seed = s;
1111
- return s / 4294967296;
1112
- }
1113
-
1114
- gauss() {
1115
- // Irwin-Hall approximation: cheap, bounded (±3σ), good enough for COV.
1116
- return (this.rand() + this.rand() + this.rand() + this.rand() - 2) * 1.732;
1117
- }
1118
-
1119
- /** Schedule event k's next firing: one cycle on, with fresh jitter. */
1120
- _schedule(k, load, rough, low = 0) {
1121
- const e = this.events[k];
1122
- const spread = this.jitterCycles * (0.6 + 1.4 * (1 - load)) * (1 + 2 * rough) * (1 + 0.8 * low);
1123
- this.cycleOf[k] += 1;
1124
- this.nextAt[k] = this.cycleOf[k] + e.angle + Math.max(-0.02, Math.min(0.02, this.gauss() * spread));
1125
- }
1126
-
1127
- _fire(e, load, rough, low = 0, ripple = 0) {
1128
- // Cycle-to-cycle variation: larger at light load (poorer, slower burns)
1129
- // and with \`rough\`; occasional misfire — the cylinder still pumps air, so
1130
- // a faint pulse, not silence.
1131
- const cov = this.ccv * (0.7 + 2.3 * (1 - load) * (1 - load)) * (1 + 2.5 * rough) * (1 + low);
1132
- const trim = 1 + (e.ampTrim - 1) * (1 + 1.5 * low);
1133
- let A = trim * Math.max(0.15, 1 + this.gauss() * cov);
1134
- if (rough > 0 && this.rand() < 0.06 * rough * rough) A *= 0.12;
1135
- const h = this.hardness * load;
1136
- const a = this.attack * (0.55 + 0.85 * h);
1137
- const b = this.decay * (1.25 - 0.35 * h) * e.decayTrim * (1 + 0.5 * cov * this.gauss());
1138
- const p = this.pool.pop() || {};
1139
- p.out = e.out; p.A = A; p.a = a; p.b = b; p.t = 0; p.ts = 0;
1140
- this.pulses.push(p);
1141
- // The intake events mirror the firings; only a firing kicks the crank.
1142
- if (e.out < this.nOut - 1) this.v += ripple * A;
1143
- }
1144
-
1145
- process(inputs, outputs, params) {
1146
- const out = outputs;
1147
- const n = out[0][0].length;
1148
- const f0 = params.f0[0];
1149
- const load = Math.min(1, Math.max(0, params.load[0]));
1150
- const amp = params.amp[0];
1151
- const rough = params.rough[0];
1152
- const ripple = params.ripple ? params.ripple[0] : 0;
1153
- const low = params.low ? params.low[0] : 0;
1154
- const drag = ripple * this.nFire; // mean kick per cycle, drawn back
1155
- const sr = sampleRate;
1156
- const dph = f0 / sr; // crank cycles per sample
1157
- const dts = 1 / sr;
1158
- const ev = this.events, nEv = ev.length;
1159
- // Calibration gain per output at this load (linear between 5 points).
1160
- const gi = load * 4, g0 = Math.min(3, Math.floor(gi)), gf = gi - g0;
1161
- // One-pole lowpass at KNEE half-orders of f0 (the radiation knee).
1162
- const fc = Math.min(KNEE_HALF_ORDERS * f0, 0.45 * sr);
1163
- const lpk = 1 - Math.exp(-2 * Math.PI * fc / sr);
1164
-
1165
- for (let o = 0; o < this.nOut; o++) out[o][0].fill(0);
1166
- const acc = this._acc || (this._acc = new Float64Array(this.nOut));
1167
-
1168
- for (let i = 0; i < n; i++) {
1169
- // Advance the crank; fire every event whose (jittered) time has come.
1170
- const dphv = dph * (1 + this.v);
1171
- const invv = dphv > 1e-9 ? 1 / dphv : 0;
1172
- // Compression drag, plus a leak (~e^-6 per cycle) standing in for the
1173
- // load and idle-speed control that stop the speed wandering off.
1174
- this.v -= (drag + 6 * this.v) * dph;
1175
- if (this.v > 0.2) this.v = 0.2; else if (this.v < -0.2) this.v = -0.2;
1176
- this.abs += dphv;
1177
- const abs = this.abs;
1178
- for (let k = 0; k < nEv; k++) {
1179
- if (abs >= this.nextAt[k]) {
1180
- this._fire(ev[k], load, rough, low, ripple);
1181
- // Sub-sample start: how far past its firing this sample already is.
1182
- const past = Math.min(1, abs - this.nextAt[k]);
1183
- const last = this.pulses[this.pulses.length - 1];
1184
- last.t = past; last.ts = f0 > 0 ? past / f0 : 0;
1185
- this._schedule(k, load, rough, low);
1186
- // Far behind (e.g. f0 jumped from 0): catch the schedule up silently.
1187
- while (this.nextAt[k] < abs) this._schedule(k, load, rough, low);
1188
- }
1189
- }
1190
- // Sum the live pulses' pressure per output.
1191
- acc.fill(0);
1192
- for (let j = this.pulses.length - 1; j >= 0; j--) {
1193
- const p = this.pulses[j];
1194
- if (p.t > 1 || p.b * p.t > 9) { // spent (or past one cycle)
1195
- this.pulses[j] = this.pulses[this.pulses.length - 1];
1196
- this.pulses.pop();
1197
- this.pool.push(p);
1198
- continue;
1199
- }
1200
- const on = 1 - Math.exp(-(p.ts * p.ts) / (ONSET_S * ONSET_S));
1201
- acc[p.out] += p.A * on * (1 - Math.exp(-p.a * p.t)) * Math.exp(-p.b * p.t);
1202
- p.t += dphv; p.ts += dts;
1203
- }
1204
- for (let o = 0; o < this.nOut; o++) {
1205
- const grad = (acc[o] - this.prevP[o]) * invv; // dp / d(phase)
1206
- this.prevP[o] = acc[o];
1207
- this.lp[o] += lpk * (grad - this.lp[o]);
1208
- const G = this.gains[o];
1209
- const gain = G[g0] + (G[g0 + 1] - G[g0]) * gf;
1210
- out[o][0][i] = this.lp[o] * gain * amp;
1211
- }
1212
- }
1213
- return this.alive;
1214
- }
1215
- }
1216
-
1217
- registerProcessor('engine-combustion', CombustionProcessor);
1218
- `,Q=(e,t,n)=>e<t?t:e>n?n:e,mC={...rx.mix},hC=new WeakSet,gC=new WeakMap,_C=class e{static preload(e){if(hC.has(e))return Promise.resolve(!0);if(!e||!e.audioWorklet||typeof AudioWorkletNode>`u`)return Promise.resolve(!1);if(!gC.has(e)){let t=URL.createObjectURL(new Blob([pC],{type:`text/javascript`}));gC.set(e,e.audioWorklet.addModule(t).then(()=>(hC.add(e),!0)).catch(e=>(console.warn(`[engine-sim] combustion worklet unavailable, using wavetables`,e),!1)).finally(()=>URL.revokeObjectURL(t)))}return gC.get(e)}constructor(e=null,t={}){this.ctx=e||new(window.AudioContext||window.webkitAudioContext),this.timeScale=1,this.ownsContext=!e,this.opts=t,this.engineId=t.engine in Jb?t.engine:`v8cross`,this.vehicleId=t.vehicle in $b?t.vehicle:`sports`,this.profile=ux(this.engineId).engine,this.vehicle=$b[this.vehicleId],this.stockGearing=t.gearing===`stock`,this.geared=this._gearedVehicle(),this.mix={...mC,...t.mix||{}},this.turboCfg={...rx.turbo,enabled:+!!t.turbo},this._volume=t.volume??rx.volume,this.running=!1,this._destOpt=t.destination||null,this.presetId=this.engineId,this.presetLabel=ux(this.engineId).label,this._rumble=rx.tone.rumble,this._brightness=rx.tone.brightness,this._popDepth=rx.fx.popDepth,this._dynamics=rx.fx.dynamics,this._width=rx.fx.width,this._position=rx.position,this._punch=rx.tone.punch,this.inputs={...wS,...t.inputs||{}},this._ps={},this._misfireRng=625341585,this._misfireHold=0,this._bark=0,this._prevLoad=0,this.physics=new KS(this._machine(),this.geared,{...t}),this._buildGraph(),this._buildVoices(),this.setPerspective(t.perspective||`exterior`),this.setVolume(this._volume),t.preset&&this.loadPreset(t.preset)}_buildGraph(){let e=this.ctx;this.master=e.createGain(),this.master.gain.value=0,this.dynamics=new cC(e,{amount:1}),this.cabin=new Ux(e,this.profile),this.mixBus=e.createGain(),this.mixBus.gain.value=.95,this.rumbleShelf=e.createBiquadFilter(),this.rumbleShelf.type=`lowshelf`,this.rumbleShelf.frequency.value=145,this.rumbleShelf.gain.value=2,this.bodyBump=e.createBiquadFilter(),this.bodyBump.type=`peaking`,this.bodyBump.frequency.value=78,this.bodyBump.Q.value=1,this.bodyBump.gain.value=1.5,this.presence=e.createBiquadFilter(),this.presence.type=`peaking`,this.presence.frequency.value=3e3,this.presence.Q.value=.85,this.presence.gain.value=-1.5,this.airCut=e.createBiquadFilter(),this.airCut.type=`highshelf`,this.airCut.frequency.value=2900,this.airCut.gain.value=-2,this.infra=[0,1].map(()=>{let t=e.createBiquadFilter();return t.type=`highpass`,t.frequency.value=36,t.Q.value=-3.0103,t}),this.mixBus.connect(this.infra[0]),this.infra[0].connect(this.infra[1]),this.infra[1].connect(this.rumbleShelf),this.bass=new dC(e),this.infra[1].connect(this.bass.input),this.bass.output.connect(this.rumbleShelf),this.rumbleShelf.connect(this.bodyBump),this.bodyBump.connect(this.presence),this.presence.connect(this.airCut),this.airCut.connect(this.cabin.input),this.limiter=e.createDynamicsCompressor(),this.limiter.threshold.value=-1.5,this.limiter.knee.value=4,this.limiter.ratio.value=20,this.limiter.attack.value=.004,this.limiter.release.value=.16,this.limiterTrim=e.createGain(),this.limiterTrim.gain.value=10**(-lC(-1.5,20,4)/20),this.safety=new uC(e),this.eq=new aC(e),this.reverb=new oC(e,{size:.32,mix:.14}),this.stereo=new sC(e,{width:.35}),this.air=e.createBiquadFilter(),this.air.type=`lowpass`,this.air.frequency.value=18e3,this.air.Q.value=.5,this.distGain=e.createGain(),this.distGain.gain.value=1,this.space=new fC(e),this.cabin.output.connect(this.air),this.air.connect(this.distGain),this.distGain.connect(this.eq.input),this.eq.output.connect(this.space.input),this.space.output.connect(this.reverb.input),this.reverb.output.connect(this.stereo.input),this.stereo.output.connect(this.dynamics.input),this.dynamics.output.connect(this.limiter),this.limiter.connect(this.limiterTrim),this.limiterTrim.connect(this.master),this.master.connect(this.safety.input),this._destination=null,this.connect(this._destOpt||e.destination),this.busses={};for(let t of Object.keys(mC)){let n=e.createGain();n.gain.value=this.mix[t],n.connect(this.mixBus),this.busses[t]=n}}_machine(){return{...this.profile,turbo:this.turboCfg.enabled>=.5?this.turboCfg:null}}_buildVoices(){let e=this.ctx,t=this._machine();this.waves=Tx(e,t,Xb),this.exhaustTrem&&this.exhaustTrem.disconnect(),this.exhaust=new Wx(e,t),this.exhaustTrem=e.createGain(),this.exhaustTrem.gain.value=1,this.exhaust.output.connect(this.exhaustTrem),this.turbineShelf&&this.turbineShelf.disconnect(),this.turbineShelf=e.createBiquadFilter(),this.turbineShelf.type=`highshelf`,this.turbineShelf.frequency.value=700,this.turbineShelf.gain.value=0,this.exhaustTrem.connect(this.turbineShelf),this.turbineShelf.connect(this.busses.exhaust),this.intake=new Vx(e,t),this.intakeTrim&&this.intakeTrim.disconnect(),this.intakeTrim=e.createGain(),this.intake.output.connect(this.intakeTrim),this.intakeTrim.connect(this.busses.intake),this.transmission=new oS(e,t,this.geared),this.transmission.output.connect(this.busses.transmission),this.turbo=t.turbo?new cS(e,t):null,this.turbo&&this._wireTurbo(),this.transients=new mS(e,t),this.transients.output.connect(this.busses.transients),this.popSend=e.createGain(),this.popSend.gain.value=1.05,this.transients.combustionOutput.connect(this.popSend);for(let e of this.exhaust.inputs)this.popSend.connect(e);this.popDirect=e.createGain(),this.popDirect.gain.value=.75,this.transients.combustionOutput.connect(this.popDirect),this.popDirect.connect(this.busses.transients),this.exhaustNoise=new bS(e,t);for(let e of this.exhaust.inputs)this.exhaustNoise.output.connect(e);if(this.sub=new xS(e,t),this.sub.output.connect(this.busses.sub),this.character=new SS(e,t),this.character.tremolo.connect(this.exhaustTrem.gain),this.oscs=[],this.combustion)try{this.combustion.port.postMessage(`stop`),this.combustion.disconnect()}catch{}if(this.combustion=null,hC.has(e)&&!this.opts?.wavetables){let n=Dx(t,Xb);this.combustion=new AudioWorkletNode(e,`engine-combustion`,{numberOfInputs:0,numberOfOutputs:n.outputs,outputChannelCount:Array(n.outputs).fill(1),processorOptions:n})}if(this.gates)for(let e of this.gates)e.disconnect();this.gates=[],this.waves.banks.forEach((t,n)=>{let r=e.createGain();r.gain.value=1,r.connect(this.exhaust.inputs[n]),this.gates.push(r),this.combustion?this.combustion.connect(r,n):this.oscs.push(this._makeWavePair(t.soft,t.hard,r,`bank`+n))}),this.combustion?this.combustion.connect(this.intake.input,this.waves.banks.length):this.oscs.push(this._makeWavePair(this.waves.intake.soft,this.waves.intake.hard,this.intake.input,`intake`)),this.character&&this.character.setEventSource(!!this.combustion)}_makeWavePair(e,t,n,r){let i=this.ctx,a=(e,t)=>{let r=c(i.createOscillator());r.setPeriodicWave(e),r.detune.value=t,this.character&&this.character.detune.connect(r.detune);let a=i.createGain();return a.gain.value=0,r.connect(a),a.connect(n),{osc:r,gain:a}};return{label:r,soft:a(e,-3),hard:a(t,3)}}async start(){if(this.running)return;if(this.ctx.state===`suspended`&&await this.ctx.resume(),!this.opts?.wavetables&&!hC.has(this.ctx)&&this.ctx.audioWorklet&&typeof AudioWorkletNode<`u`&&await e.preload(this.ctx)&&(this._needsRebuild=!0),this._needsRebuild){for(let e of this._modules())e!==this.cabin&&e.dispose&&e.dispose();this._buildVoices(),this._needsRebuild=!1}this.running=!0;let t=this.ctx.currentTime+.02;for(let e of this.oscs)e.soft.osc.start(t),e.hard.osc.start(t);for(let e of this._modules())e.start&&e.start(t);let n=this.ctx.currentTime;this.master.gain.cancelScheduledValues(n),this.master.gain.setValueAtTime(1e-4,n),this.master.gain.linearRampToValueAtTime(this._volume,n+.3),this._writeParams(this.physics.step(0,this.ctx.currentTime),!0)}stop(){if(!this.running)return;let e=this.ctx.currentTime;this.master.gain.cancelScheduledValues(e),this.master.gain.setValueAtTime(Math.max(this.master.gain.value,1e-4),e),this.master.gain.linearRampToValueAtTime(1e-4,e+.25);let t=e+.3;for(let e of this.oscs){try{e.soft.osc.stop(t)}catch{}try{e.hard.osc.stop(t)}catch{}}if(this.combustion){let e=this.combustion;setTimeout(()=>{try{e.port.postMessage(`stop`),e.disconnect()}catch{}},320)}for(let e of this._modules())e.stop&&e.stop(t);this.running=!1,this._needsRebuild=!0}dispose(){this.stop();for(let e of this._modules())e.dispose&&e.dispose();for(let e of[this.eq,this.reverb,this.stereo,this.dynamics,this.bass,this.space,this.safety])e&&e.dispose&&e.dispose();this.ownsContext&&setTimeout(()=>this.ctx.close(),500)}_modules(){return[this.exhaust,this.intake,this.transmission,this.turbo,this.transients,this.exhaustNoise,this.sub,this.character,this.cabin].filter(Boolean)}setTurbo(e){return this.turboCfg.enabled=+!!e,this._syncTurbo(),!!e}_syncTurbo(){let e=this._machine();!!e.turbo==!!this.turbo?this.turbo&&this.turbo.setProfile(e):(this.physics.setEngine(e),this.turbo?(this.turbo.release(),this.turbo=null):(this.turbo=new cS(this.ctx,e),this._wireTurbo(),this.running&&this.turbo.start(this.ctx.currentTime+.02)))}_wireTurbo(){this.turbo.output.connect(this.busses.turbo);for(let e of this.exhaust.inputs)this.turbo.surgeSend.connect(e)}setEngineType(e){return!(e in Jb)||e===this.engineId?!1:(this.engineId=e,this._applyEngine(ux(e).engine),!0)}_applyEngine(e){let t=this.running;t&&this._hardStopVoices(),this.profile=e,this.physics.setEngine(this._machine()),this.geared=this._gearedVehicle(),this.physics.setVehicle(this.geared);for(let e of this._modules())e!==this.cabin&&e.dispose&&e.dispose();if(this._buildVoices(),this._needsRebuild=!1,t){let e=this.ctx.currentTime+.02;for(let t of this.oscs)t.soft.osc.start(e),t.hard.osc.start(e);for(let t of this._modules())t.start&&t.start(e)}}getPreset(){let e=this.reverb.getState();return fx({version:3,id:this.presetId,label:this.presetLabel,engine:this.profile,turbo:{...this.turboCfg},mix:{...this.mix},tone:{rumble:this._rumble??1,brightness:this._brightness??1,punch:this._punch??1},eq:this.eq.getGains(),fx:{reverbMix:e.mix,reverbSize:e.size,reverbDamping:e.damping,width:this.stereo.getWidth?this.stereo.getWidth():this._width,popDepth:this._popDepth,dynamics:this._dynamics},position:this._position,volume:this._volume})}loadPreset(e){let t=e;return typeof e==`string`&&(t=Jb[e]?ux(e):mx(e).preset),!t||typeof t!=`object`?!1:(t=fx(t),this.presetId=t.id,this.presetLabel=t.label,Jb[t.id]&&(this.engineId=t.id),Object.assign(this.turboCfg,t.turbo),JSON.stringify(t.engine)===JSON.stringify(this.profile)?this._syncTurbo():this._applyEngine(t.engine),this.setMix(t.mix),this.setTone(t.tone),this.setEQ(t.eq),this.setReverb({mix:t.fx.reverbMix,size:t.fx.reverbSize,damping:t.fx.reverbDamping}),this.setWidth(t.fx.width),this.setPopDepth(t.fx.popDepth),this.setDynamics(t.fx.dynamics),this.setPosition(t.position),this.setVolume(t.volume),!0)}exportPreset(){return px(this.getPreset())}setParam(e,t){let n=cx(e);if(!n)return null;let r=Q(Number(t),n.min,n.max);if((n.unit===`bool`||n.unit===`enum`)&&(r=Math.round(r)),!isFinite(r))return null;if(n.rebuild){let t=this.getPreset();return sx(t,e,r),this._applyEngine(fx(t).engine),r}let i=e.split(`.`);if(i[0]===`mix`)this.setMix({[i[1]]:r});else if(i[0]===`tone`)this.setTone({[i[1]]:r});else if(i[0]===`eq`)this.setEQBand(Number(i[1]),r);else if(e===`position`)this.setPosition(r);else if(e===`volume`)this.setVolume(r);else if(e===`turbo.enabled`)this.setTurbo(r);else if(i[0]===`turbo`)this.turboCfg[i[1]]=r,this._syncTurbo();else if(i[0]===`fx`)i[1]===`reverbMix`?this.setReverb({mix:r}):i[1]===`reverbSize`?this.setReverb({size:r}):i[1]===`reverbDamping`?this.setReverb({damping:r}):i[1]===`width`?this.setWidth(r):i[1]===`popDepth`?this.setPopDepth(r):i[1]===`dynamics`&&this.setDynamics(r);else if(i[0]===`engine`){sx(this.profile,i.slice(1).join(`.`),r);let e=this._machine();this.physics.setEngine(e);for(let t of this._modules())t.setProfile&&t.setProfile(e)}else return null;return r}getParam(e){let t=ox(this.getPreset(),e);return typeof t==`number`?t:null}static schema(){return ix}static groups(){return ax}static presets(){return dx()}_hardStopVoices(){let e=this.ctx.currentTime+.05;if(this.combustion){try{this.combustion.port.postMessage(`stop`),this.combustion.disconnect()}catch{}this.combustion=null}for(let t of this.oscs){try{t.soft.osc.stop(e)}catch{}try{t.hard.osc.stop(e)}catch{}}}setVehicle(e){return!(e in $b)||e===this.vehicleId?!1:(this.vehicleId=e,this.setVehicleProfile($b[e]),!0)}setVehicleProfile(e){return this.vehicle=e,this.geared=this._gearedVehicle(),this.physics.setVehicle&&this.physics.setVehicle(this.geared),this.transmission.setVehicle&&this.transmission.setVehicle(this.geared),this.geared}_gearedVehicle(){return this.stockGearing?this.vehicle:nC(this.profile,this.vehicle)}setInput(e,t){if(!(e in wS))return null;let n=Q(Number(t)||0,0,1);return this.inputs[e]=n,n}setInputs(e={}){for(let[t,n]of Object.entries(e))this.setInput(t,n);return this.getInputs()}getInputs(){return{...this.inputs}}static inputs(){return CS}setThrottle(e){this.physics.throttle=Q(Number(e)||0,0,1)}setBrake(e){this.physics.brake=Q(Number(e)||0,0,1)}setClutch(e){this.physics.clutchPedal=Q(Number(e)||0,0,1)}setClutchOverride(e){this.physics.burnoutClutchOverride=e==null?null:Q(Number(e)||0,0,1)}setAutoShift(e){this.physics.setAutoShift(e)}shiftUp(){return this.physics.shiftUp()}shiftDown(){return this.physics.shiftDown()}setGear(e){return this.physics.setGear(e)}setVolume(e){if(this._volume=Q(Number(e)||0,0,1),this.running){let e=this.ctx.currentTime;this.master.gain.cancelScheduledValues(e),this.master.gain.setValueAtTime(this.master.gain.value,e),this.master.gain.setTargetAtTime(this._volume,e,.05)}}setMix(e){Object.assign(this.mix,e);let t=this.ctx.currentTime;for(let[e,n]of Object.entries(this.busses))n.gain.setTargetAtTime(Q(this.mix[e]??1,0,2),t,.03)}setTone({rumble:e,brightness:t,punch:n}={}){let r=this.ctx.currentTime;return e!=null&&(this._rumble=Q(Number(e)||0,0,2),this.rumbleShelf.gain.setTargetAtTime(2*this._rumble,r,.05),this.bodyBump.gain.setTargetAtTime(1.5*this._rumble,r,.05)),t!=null&&(this._brightness=Q(Number(t)||0,0,2),this.airCut.gain.setTargetAtTime(-2*(2-this._brightness),r,.05)),n!=null&&(this._punch=Q(Number(n)||0,0,2),this.bass.setAmount(.15*this._punch)),{rumble:this._rumble??1,brightness:this._brightness??1,punch:this._punch??1}}setEQ(e){return this.eq.setGains(e),this.eq.getGains()}setEQBand(e,t){return this.eq.setBand(e,t),this.eq.getGains()}resetEQ(){return this.eq.reset(),this.eq.getGains()}setReverb({mix:e,size:t,damping:n}={}){return e!=null&&this.reverb.setMix(e),t!=null&&this.reverb.setSize(t),n!=null&&this.reverb.setDamping(n),this.reverb.getState()}setWidth(e){return this._width=this.stereo.setWidth(e)}setDynamics(e){return this._dynamics=this.dynamics.setAmount(e)}getReduction(){return this.dynamics.getReduction()}setPopDepth(e){let t=Q(Number(e)||0,0,2);return this._popDepth=t,this.popSend.gain.setTargetAtTime(t,this.ctx.currentTime,.03),t}setPerspective(e){this.cabin.setPerspective(e),this._perspective=e,this._position=+(e===`interior`)}setPosition(e){let t=Q(Number(e)||0,0,1);return this._position=t,this.cabin.setPosition(t),this._perspective=t>=.5?`interior`:`exterior`,t}update(e){let t=Number(e)||0;if(t<=0)return;t=Math.min(t,.1);let n=this.physics.step(t,this.ctx.currentTime);return this._evMisfire=0,this._writeParams(n,!1),this._lastParams=n,this}getState(){let e=this.physics.getState(),t=this._lastParams;return{...e,shiftPhase:e.phase||``,clutchSlip:t?t.clutchSlip:0,boost:t?t.boost:0,gearRatio:t?t.gearRatio:0,wheelRpm:t?t.wheelRpm:0,load:t?t.load:0,overrun:t?t.overrun:0,rpmNorm:t?t.rpmNorm:0,dRpm:t?t.dRpm:0,engine:this.engineId,engineLabel:this.presetLabel||this.profile.label,turbo:this.turboCfg.enabled>=.5,preset:this.presetId,vehicle:this.vehicleId,vehicleLabel:this.vehicle.label,gearbox:this.vehicle.gearbox,gearRatios:this.geared.gearRatios.slice(),auto:!this.physics.shift||this.physics.shift.autoShift,perspective:this._perspective,volume:this._volume,mix:{...this.mix},inputs:{...this.inputs}}}getEvents(){let e=this._lastParams;return e?{misfire:this._evMisfire||0,lash:e.evLash||0,pop:e.evPop||0,cut:e.evCut||0,engage:e.evEngage||0,bov:e.evBov||0,shiftDone:e.evShiftDone||0}:{misfire:0,lash:0,pop:0,cut:0,engage:0,bov:0,shiftDone:0}}takePops(){let e=this.transients;if(!e||!e.pops.length)return[];let t=e.pops;return e.pops=[],t}get output(){return this.safety.output}connect(e){if(!e)return this;if(this._destination)try{this.safety.output.disconnect(this._destination)}catch{}return this.safety.output.connect(e),this._destination=e,this}static engines(){return Object.entries(Jb).map(([e,t])=>({id:e,label:t.label,cylinders:t.cylinders,idleRpm:t.idleRpm,redlineRpm:t.redlineRpm,peakTorque:t.peakTorque,banks:t.banks.length}))}static vehicles(){return Object.entries($b).map(([e,t])=>({id:e,label:t.label,mass:t.mass,gears:t.gearRatios.length,gearbox:t.gearbox,finalDrive:t.finalDrive}))}_writeParams(e,t){if(!this.running&&!t)return;let n=t?.002:.02,r=e.now,i=this._applyInputs(e,r),a=Q(i.f0,.02,4e3);if(i.dt>0){let e=(i.load-this._prevLoad)/i.dt;this._bark=Math.max(this._bark*Math.exp(-i.dt/.16),Q(e/10,0,1))}this._prevLoad=i.load;let o=Q(i.load+.3*this._bark,0,1),s=(1+.35*this._bark)*(.32+.68*o**.7)*(.45+.55*Q(i.rpmNorm,0,1))*(1-.45*Q(i.overrun,0,1))*Q(Number(this.profile.voice)||1,.2,2),c=Math.cos(o*Math.PI/2)*s,l=Math.sin(o*Math.PI/2)*s;if(this.combustion){let e=this.combustion.parameters;e.get(`f0`).setTargetAtTime(a*this.timeScale,r,n),e.get(`load`).setTargetAtTime(o,r,n),e.get(`amp`).setTargetAtTime(s,r,n),e.get(`rough`).setTargetAtTime(Q(this.inputs.roughness||0,0,1),r,.05),e.get(`ripple`).setTargetAtTime(Ex(this.profile,i.rpm,o),r,n),e.get(`low`).setTargetAtTime(1-Q(i.rpmNorm,0,1),r,n)}for(let e of this.oscs)e.soft.osc.frequency.setTargetAtTime(a,r,n),e.hard.osc.frequency.setTargetAtTime(a,r,n),e.soft.gain.gain.setTargetAtTime(c,r,n),e.hard.gain.gain.setTargetAtTime(l,r,n);let u=this.turbo?.55+.45*Q(this.turbo.spool,0,1):0;this.turbineShelf.gain.setTargetAtTime(-7*u,r,.12),this.intakeTrim.gain.setTargetAtTime(1-.4*u,r,.12);for(let e of this._modules())e.update(i)}_applyInputs(e,t){let n=Object.assign(this._ps,e),r=this.inputs,i=r.strain,a=r.aggression,o=r.roughness;n.strain=i,n.valve=a,n.rough=o,i>0&&!(n.overrun>.5)&&(n.load=Q(n.load+(1-n.load)*.55*i*Math.max(.25,n.throttle||0),0,1)),vC(this.exhaustTrem.gain,1+.4*a,t,.08);let s=r.distance;if(vC(this.air.frequency,18e3*.09**s,t,.08),vC(this.distGain.gain,1/(1+2.6*s),t,.08),this.space.setEnvironment(r.environment),this.reverb.setExtra(.35*s+.32*r.environment),o>0&&this.gates&&this.running&&!this.combustion){let n=Math.max(1,(e.f0||0)*(this.profile.cylinders||4)),r=this._lastNow==null?0:Math.max(0,t-this._lastNow),i=1-(1-.06*o*o)**(n*r);this._misfireHold-=r;let a=this._misfireRng;if(a^=a<<13,a>>>=0,a^=a>>17,a^=a<<5,a>>>=0,this._misfireRng=a,this._misfireHold<=0&&a/4294967296<i&&!(e.overrun>.5)){let e=this.gates[a%this.gates.length].gain,r=this.gates.length/n;e.cancelScheduledValues(t),e.setTargetAtTime(.08,t+.004,.003),e.setTargetAtTime(1,t+.004+r,.01),this._misfireHold=.12+.4*(1-o),this._evMisfire=1}}return this._lastNow=t,this.character&&(this.character.roughness=o),n}};function vC(e,t,n,r){Number.isFinite(t)&&e.setTargetAtTime(t,n,r)}var yC={i3:3,i4:4,boxer4:4,i5:5,i6:6,v6:6,v6tt:6,flat6:6,v8cross:8,v8tt:8,v8flat:8,v10:10,v12:12},bC=class{context;output;noise;sources=new Set;disposed=!1;starters=null;ready;constructor(e,t=e.destination){this.context=e,this.output=e.createGain(),this.output.gain.value=Ae(ke.starter),this.output.connect(t),this.noise=e.createBuffer(1,Math.ceil(e.sampleRate),e.sampleRate);let n=this.noise.getChannelData(0);for(let e=0;e<n.length;e++)n[e]=Math.random()*2-1;this.ready=Promise.all([Ee(e).load(`starter-light`),Ee(e).load(`starter-heavy`)]).then(([e,t])=>{this.disposed||(this.starters=[e,t])})}run(e,t,n){this.sources.add(e),e.onended=()=>{e.disconnect(),this.sources.delete(e)},e.start(t),e.stop(t+n)}tone(e,t,n,r,i,a,o=`sawtooth`){let s=this.context,l=c(s.createOscillator());l.type=o,l.frequency.setValueAtTime(n,e),l.frequency.exponentialRampToValueAtTime(Math.max(20,r),e+t);let u=s.createBiquadFilter();u.type=`lowpass`,u.frequency.value=a;let d=s.createGain();d.gain.setValueAtTime(1e-4,e),d.gain.linearRampToValueAtTime(i,e+Math.min(.025,t*.3)),d.gain.exponentialRampToValueAtTime(1e-4,e+t),l.connect(u).connect(d).connect(this.output),l.addEventListener(`ended`,()=>{u.disconnect(),d.disconnect()},{once:!0}),this.run(l,e,t)}hiss(e,t,n,r){let i=this.context,a=c(i.createBufferSource());a.buffer=this.noise;let o=i.createBiquadFilter();o.type=`bandpass`,o.frequency.value=n,o.Q.value=.7;let s=i.createGain();s.gain.setValueAtTime(1e-4,e),s.gain.linearRampToValueAtTime(r,e+Math.min(.014,t*.25)),s.gain.exponentialRampToValueAtTime(1e-4,e+t),a.connect(o).connect(s).connect(this.output),a.addEventListener(`ended`,()=>{o.disconnect(),s.disconnect()},{once:!0}),this.run(a,e,t)}start(e){if(this.disposed)return 0;let t=e.sound.starter===`heavy`||e.sound.starter!==`light`&&(e.sound.vehicleId===`truck`||e.massKg>=1700),n=this.starters?.[+!!t];if(!n)return 0;let r=this.context.currentTime+.01,i=c(this.context.createBufferSource());return i.buffer=n,i.connect(this.output),this.run(i,r,n.duration),n.duration+.01}stop(e){if(this.disposed)return 0;this.cancel();let t=this.context.currentTime+.01,n=yC[e.sound.engineId]??6,r=Math.max(.8,Math.min(1.3,Math.sqrt(e.massKg/1400))),i=(75+n*3)/r;this.tone(t,.48,i,i*.38,.09,280,`triangle`);for(let e=0;e<4;e++){let n=t+e*(.095+e*.022);this.tone(n,.08,i*(.9-e*.16),i*(.72-e*.13),.055*(1-e*.18),240,`sawtooth`)}return this.hiss(t+.4,.1,360,.045),.55}dispose(){this.disposed||(this.disposed=!0,this.cancel(),this.output.disconnect())}cancel(){for(let e of this.sources)try{e.stop()}catch{}this.sources.clear()}},xC=(e,t,n)=>{let r=P((e-t)/Math.max(.1,n-t),0,1);return 1-r*r*(3-2*r)};function SC(e,t,n){let r=Math.max(0,e);return{warning:.105*(.62+.38*P(r/Math.max(.1,n.fadeStartMps),0,1))*xC(r,n.fadeStartMps,n.fadeEndMps),motor:(.025+.055*P(r/(12/3.6),0,1)+.015*P(Math.abs(t),0,1))*xC(r,n.motorFadeStartMps,n.motorFadeEndMps)}}var CC=class{context;range;output;tone;warning;motor;motorFundamental;motorHarmonic;motorHarmonicGain;choir;voices=[];formants=[];pitchLfo;pitchDepth;breathLfo;breathDepth;chorusLfo;chorusDepth;chorusDelay;chorusGain;air;airFilter;airGain;disposed=!1;constructor(e,t,n=e.destination){this.context=e,this.range=t,this.output=e.createGain(),this.output.gain.value=0,this.output.connect(n),this.warning=e.createGain(),this.warning.gain.value=0,this.warning.connect(this.output),this.tone=e.createGain(),this.tone.gain.value=.86,this.tone.connect(this.warning),this.motor=e.createGain(),this.motor.gain.value=0,this.motor.connect(this.output),this.motorFundamental=c(e.createOscillator()),this.motorFundamental.type=`sine`,this.motorFundamental.frequency.value=72,this.motorFundamental.connect(this.motor),this.motorFundamental.start(),this.motorHarmonic=c(e.createOscillator()),this.motorHarmonic.type=`triangle`,this.motorHarmonic.frequency.value=144,this.motorHarmonicGain=e.createGain(),this.motorHarmonicGain.gain.value=.24,this.motorHarmonic.connect(this.motorHarmonicGain).connect(this.motor),this.motorHarmonic.start(),this.chorusDelay=e.createDelay(.05),this.chorusDelay.delayTime.value=.021,this.chorusGain=e.createGain(),this.chorusGain.gain.value=.24,this.tone.connect(this.chorusDelay).connect(this.chorusGain).connect(this.warning),this.chorusLfo=c(e.createOscillator()),this.chorusLfo.frequency.value=.31,this.chorusDepth=e.createGain(),this.chorusDepth.gain.value=.0025,this.chorusLfo.connect(this.chorusDepth).connect(this.chorusDelay.delayTime),this.chorusLfo.start(),this.pitchLfo=c(e.createOscillator()),this.pitchLfo.frequency.value=.47,this.pitchDepth=e.createGain(),this.pitchDepth.gain.value=.7,this.pitchLfo.connect(this.pitchDepth),this.pitchLfo.start(),this.breathLfo=c(e.createOscillator()),this.breathLfo.frequency.value=.37,this.breathDepth=e.createGain(),this.breathDepth.gain.value=.09,this.breathLfo.connect(this.breathDepth).connect(this.tone.gain),this.breathLfo.start(),this.choir=e.createGain(),this.choir.gain.value=1;for(let[t,n]of[1,4/3,3/2,2,3,4].entries()){let r=c(e.createOscillator());r.type=`sine`,r.frequency.value=116*n;let i=e.createGain();if(i.gain.value=t===0?.29:t===3?.08:t===4?.045:t===5?.022:.19,r.connect(i).connect(this.tone),this.pitchDepth.connect(r.frequency),r.start(),this.voices.push({oscillator:r,ratio:n,gain:i}),t>=3)continue;let a=c(e.createOscillator());a.type=`sawtooth`,a.frequency.value=116*n,a.detune.value=t%2?4:-4;let o=e.createGain();o.gain.value=.12,a.connect(o).connect(this.choir),this.pitchDepth.connect(a.frequency),a.start(),this.voices.push({oscillator:a,ratio:n,gain:o})}for(let[t,n,r]of[[650,.85,.55],[1180,1.2,.35],[2250,1.6,.14]]){let i=e.createBiquadFilter();i.type=`bandpass`,i.frequency.value=t,i.Q.value=n;let a=e.createGain();a.gain.value=r,this.choir.connect(i).connect(a).connect(this.tone),this.formants.push({filter:i,gain:a})}let r=e.createBuffer(1,e.sampleRate,e.sampleRate),i=r.getChannelData(0);for(let e=0;e<i.length;e++)i[e]=Math.random()*2-1;this.air=c(e.createBufferSource()),this.air.buffer=r,this.air.loop=!0,this.airFilter=e.createBiquadFilter(),this.airFilter.type=`bandpass`,this.airFilter.frequency.value=1100,this.airFilter.Q.value=.65,this.airGain=e.createGain(),this.airGain.gain.value=.055,this.air.connect(this.airFilter).connect(this.airGain).connect(this.tone),this.air.start()}setRange(e){this.range=e}update(e,t,n){if(this.disposed)return;let r=this.context.currentTime,i=Math.max(0,e),a=SC(i,t,this.range);this.output.gain.setTargetAtTime(+!!n,r,.055),this.warning.gain.setTargetAtTime(a.warning,r,.08),this.motor.gain.setTargetAtTime(a.motor,r,.08);let o=116+Math.min(i,this.range.fadeEndMps)*4+Math.abs(t)*4;for(let e of this.voices)e.oscillator.frequency.setTargetAtTime(o*e.ratio,r,.08);let s=72+Math.min(i,this.range.motorFadeEndMps)*7+Math.abs(t)*12;this.motorFundamental.frequency.setTargetAtTime(s,r,.07),this.motorHarmonic.frequency.setTargetAtTime(s*2.01,r,.07),this.airFilter.frequency.setTargetAtTime(1e3+i*65,r,.1)}silence(){this.disposed||this.output.gain.setTargetAtTime(0,this.context.currentTime,.045)}dispose(){if(!this.disposed){this.disposed=!0;for(let{oscillator:e,gain:t}of this.voices)e.stop(),e.disconnect(),t.disconnect();this.pitchLfo.stop(),this.pitchLfo.disconnect(),this.pitchDepth.disconnect(),this.breathLfo.stop(),this.breathLfo.disconnect(),this.breathDepth.disconnect(),this.chorusLfo.stop(),this.chorusLfo.disconnect(),this.chorusDepth.disconnect(),this.chorusDelay.disconnect(),this.chorusGain.disconnect(),this.air.stop(),this.air.disconnect(),this.motorFundamental.stop(),this.motorFundamental.disconnect(),this.motorHarmonic.stop(),this.motorHarmonic.disconnect(),this.motorHarmonicGain.disconnect(),this.airFilter.disconnect(),this.airGain.disconnect();for(let{filter:e,gain:t}of this.formants)e.disconnect(),t.disconnect();this.choir.disconnect(),this.tone.disconnect(),this.warning.disconnect(),this.motor.disconnect(),this.output.disconnect()}}},wC=class{context;profile;destination;voice=null;disposed=!1;pressed=!1;constructor(e,t,n=e.destination){this.context=e,this.profile=t,this.destination=n}setProfile(e){this.profile=e,this.pressed&&(this.release(),this.start())}setPressed(e){this.disposed||this.pressed===e||(this.pressed=e,e?this.start():this.release())}start(){let e=this.context.currentTime,{lowHz:t,highHz:n,tone:r,level:i}=this.profile,a=this.context.createGain();a.gain.setValueAtTime(0,e),a.gain.linearRampToValueAtTime(Ae(ke.horn)*i,e+(r===`electronic`?.012:r===`trumpet`?.032:.022)),a.connect(this.destination);let o={envelope:a,oscillators:[],filters:[],gains:[]};for(let[i,s]of[t,n].entries()){let t=c(this.context.createOscillator());t.type=r===`electronic`?`triangle`:`sawtooth`,t.frequency.value=s,t.detune.value=i?2:-2;let n=this.context.createBiquadFilter();n.type=`lowpass`,n.frequency.value=r===`trumpet`?2300:r===`electronic`?1050:1600,n.Q.value=r===`trumpet`?.8:.55;let l=this.context.createGain();l.gain.value=i?.55:.7,t.connect(n).connect(l).connect(a),t.start(e),o.oscillators.push(t),o.filters.push(n),o.gains.push(l)}this.voice=o}release(){let e=this.voice;if(!e)return;this.voice=null;let t=this.context.currentTime;e.envelope.gain.cancelScheduledValues(t),e.envelope.gain.setTargetAtTime(0,t,.022);let n=e.oscillators.length;for(let r of e.oscillators)r.addEventListener(`ended`,()=>{r.disconnect(),--n===0&&(e.filters.forEach(e=>e.disconnect()),e.gains.forEach(e=>e.disconnect()),e.envelope.disconnect())},{once:!0}),r.stop(t+.16)}silence(){this.pressed=!1,this.release()}dispose(){this.disposed||=(this.silence(),!0)}},TC={low:`collision-soft`,mid:`collision-medium`,high:`collision-hard`};be[`collision-soft`].url,be[`collision-medium`].url,be[`collision-hard`].url;function EC(e){return e<4?`low`:e<10?`mid`:`high`}function DC(e,t){let n=Math.max(0,Math.min(18,e)),r=n/18;return{clip:EC(n),volume:Math.min(1,.1+.9*r**.8),rate:Math.max(.9,Math.min(1.06,.94+n*.004+(t-.5)*.06))}}var OC=class{context;output;clips={};voices=[];nextAt=0;disposed=!1;constructor(e,t=e.destination){this.context=e,this.output=e.createGain(),this.output.gain.value=Ae(ke.collision),this.output.connect(t),this.load()}async load(){await Promise.all(Object.entries(TC).map(async([e,t])=>{try{let n=await Ee(this.context).load(t);this.disposed||(this.clips[e]=n)}catch(t){this.disposed||console.warn(`Joy Ride ${e} crash sound could not load.`,t)}}))}play(e){if(this.disposed||!Number.isFinite(e)||e<.8)return;let t=this.context.currentTime;if(t<this.nextAt)return;let n=DC(e,Math.random()),r=this.clips[n.clip];if(!r)return;this.nextAt=t+.16;let i=c(this.context.createBufferSource()),a=this.context.createGain();i.buffer=r,i.playbackRate.value=n.rate,a.gain.value=n.volume,i.connect(a).connect(this.output);let o={source:i,gain:a};this.voices.push(o),i.onended=()=>{i.disconnect(),a.disconnect();let e=this.voices.indexOf(o);e>=0&&this.voices.splice(e,1)},i.start(t)}silence(){for(let e of this.voices)try{e.source.stop()}catch{}this.nextAt=0}dispose(){this.disposed||(this.disposed=!0,this.silence(),this.output.disconnect())}},kC=class{context;destination;noise=null;voice=null;pressed=!1;disposed=!1;constructor(e,t=e.destination){this.context=e,this.destination=t}setPressed(e){this.disposed||this.pressed===e||(this.pressed=e,e?this.start():this.release())}start(){let e=this.context;if(!this.noise){let t=e.sampleRate*2,n=e.createBuffer(1,t,e.sampleRate),r=n.getChannelData(0);for(let e=0;e<t;e++)r[e]=Math.random()*2-1;this.noise=n}let t=e.currentTime,n=c(e.createBufferSource());n.buffer=this.noise,n.loop=!0;let r=e.createGain();r.gain.setValueAtTime(1e-4,t),r.gain.exponentialRampToValueAtTime(Ae(ke.flamethrower),t+.065),r.connect(this.destination);let i={source:n,envelope:r,filters:[],gains:[]};for(let[t,a,o]of[[`lowpass`,330,.85],[`bandpass`,760,.2],[`highpass`,2600,.025]]){let s=e.createBiquadFilter();s.type=t,s.frequency.value=a,s.Q.value=.6;let c=e.createGain();c.gain.value=o,n.connect(s).connect(c).connect(r),i.filters.push(s),i.gains.push(c)}n.addEventListener(`ended`,()=>{n.disconnect(),i.filters.forEach(e=>e.disconnect()),i.gains.forEach(e=>e.disconnect()),r.disconnect()},{once:!0}),n.start(t),this.voice=i}release(){let e=this.voice;if(!e)return;this.voice=null;let t=this.context.currentTime;e.envelope.gain.cancelScheduledValues(t),e.envelope.gain.setTargetAtTime(1e-4,t,.035),e.source.stop(t+.18)}silence(){this.pressed=!1,this.release()}dispose(){this.disposed||(this.silence(),this.disposed=!0,this.noise=null)}},AC=class{context;destination;noiseBuffer=null;voice=null;boosting=!1;disposed=!1;constructor(e,t=e.destination){this.context=e,this.destination=t}setBoosting(e){this.disposed||this.boosting===e||(this.boosting=e,e?this.start():this.release())}start(){let e=this.context;if(!this.noiseBuffer){let t=e.sampleRate,n=e.createBuffer(1,t,e.sampleRate),r=n.getChannelData(0);for(let e=0;e<t;e++)r[e]=Math.random()*2-1;this.noiseBuffer=n}let t=e.currentTime,n=e.createGain();n.gain.setValueAtTime(1e-4,t),n.gain.exponentialRampToValueAtTime(Ae(ke.boost),t+.12),n.connect(this.destination);let r=c(e.createBufferSource());r.buffer=this.noiseBuffer,r.loop=!0;let i=e.createBiquadFilter();i.type=`highpass`,i.frequency.value=450;let a=e.createBiquadFilter();a.type=`lowpass`,a.frequency.setValueAtTime(950,t),a.frequency.exponentialRampToValueAtTime(2100,t+.42);let o=e.createGain();o.gain.value=.54,r.connect(i).connect(a).connect(o).connect(n);let s=c(e.createOscillator());s.type=`triangle`,s.frequency.setValueAtTime(145,t),s.frequency.exponentialRampToValueAtTime(350,t+.42);let l=e.createGain();l.gain.value=.2,s.connect(l).connect(n);let u={noise:r,tone:s,envelope:n,filters:[i,a],gains:[o,l]},d=2,f=()=>{--d||(r.disconnect(),s.disconnect(),u.filters.forEach(e=>e.disconnect()),u.gains.forEach(e=>e.disconnect()),n.disconnect())};r.addEventListener(`ended`,f,{once:!0}),s.addEventListener(`ended`,f,{once:!0}),r.start(t),s.start(t),this.voice=u}release(){let e=this.voice;if(!e)return;this.voice=null;let t=this.context.currentTime;e.envelope.gain.cancelScheduledValues(t),e.envelope.gain.setTargetAtTime(1e-4,t,.055),e.noise.stop(t+.27),e.tone.stop(t+.27)}silence(){this.boosting=!1,this.release()}dispose(){this.disposed||(this.silence(),this.disposed=!0,this.noiseBuffer=null)}},jC=class{context;volume;envelope;loadComplete;buffer=null;source=null;gain;disposed=!1;level=0;constructor(e,t,n,r=1,i={attackSeconds:.055,releaseSeconds:.055}){this.context=e,this.volume=r,this.envelope=i,this.gain=e.createGain(),this.gain.gain.value=0,this.gain.connect(t),this.loadComplete=Oe(e,n).then(e=>{this.disposed||(this.buffer=e,this.level>0&&(this.gain.gain.setValueAtTime(0,this.context.currentTime),this.start(),this.setGain(this.level,0)))}).catch(e=>{this.disposed||console.warn(`Joy Ride sound could not load.`,e)})}start(){if(this.source||!this.buffer)return;let e=c(this.context.createBufferSource());e.buffer=this.buffer,e.loop=!0,e.connect(this.gain),e.start(),this.source=e}setGain(e,t){let n=this.gain.gain,r=this.context.currentTime;if(this.envelope.followLevel){let t=n.value;n.cancelScheduledValues(r),n.setValueAtTime(t,r),n.linearRampToValueAtTime(e*this.volume,r+1/120)}else n.setTargetAtTime(e*this.volume,r,(e>t?this.envelope.attackSeconds:this.envelope.releaseSeconds)??.055)}setLevel(e){if(this.disposed)return;let t=Math.max(0,Math.min(1,e));if(t===this.level||!this.envelope.followLevel&&t!==0&&Math.abs(t-this.level)<.005)return;let n=this.level;this.level=t,this.level>0&&this.start(),this.setGain(t,n)}silence(){this.setLevel(0)}dispose(){this.disposed||(this.silence(),this.disposed=!0,this.source?.stop(),this.source?.disconnect(),this.source=null,this.buffer=null,this.gain.disconnect())}},MC=class{context;destination;volume;options;loadComplete;buffer=null;voices=new Set;disposed=!1;pending=null;constructor(e,t,n,r=1,i={}){this.context=e,this.destination=t,this.volume=r,this.options=i,this.loadComplete=Oe(e,n).then(e=>{if(this.disposed)return;this.buffer=e;let t=this.pending;this.pending=null,t&&Date.now()-t.queuedAt<2500&&this.play(t.level,t.playbackRate)}).catch(e=>{this.disposed||console.warn(`Joy Ride sound could not load.`,e)})}play(e=1,t=1){if(this.disposed||e<=0)return;if(!this.buffer){this.options.queueWhileLoading&&(this.pending={level:e,playbackRate:t,queuedAt:Date.now()});return}let n=c(this.context.createBufferSource()),r=this.context.createGain();n.buffer=this.buffer,n.playbackRate.value=t,r.gain.value=Math.min(1,e)*this.volume,n.connect(r).connect(this.destination),this.voices.add(n),n.onended=()=>{n.disconnect(),r.disconnect(),this.voices.delete(n)},n.start()}get duration(){return this.buffer?.duration??0}silence(){this.pending=null;for(let e of this.voices)e.stop();this.voices.clear()}dispose(){this.disposed=!0,this.silence(),this.buffer=null}},NC=class{context;output;launch;explosion;flight;flightGain;disposed=!1;ready;constructor(e,t=1){this.context=e,this.output=e.createGain(),this.output.gain.value=Re(t),this.output.connect(e.destination),this.launch=new MC(e,this.output,`rocket-launch`,Ae(ke.rocketLaunch)),this.explosion=new MC(e,this.output,`rocket-explosion`,Ae(ke.rocketExplosion)),this.ready=Promise.all([this.launch.loadComplete,this.explosion.loadComplete]).then(()=>{}),this.flightGain=e.createGain(),this.flightGain.gain.value=0,this.flightGain.connect(this.output),this.flight=new kC(e,this.flightGain)}setMasterVolume(e){this.output.gain.setTargetAtTime(Re(e),this.context.currentTime,.055)}playLaunch(e){this.disposed||this.launch.play(Re(e))}playExplosion(e){this.disposed||this.explosion.play(Re(e))}setFlightProximity(e){if(this.disposed)return;let t=Re(e);this.flight.setPressed(t>.015),this.flightGain.gain.setTargetAtTime(t*Ae(ke.rocketFlight),this.context.currentTime,.055)}silence(){this.launch.silence(),this.explosion.silence(),this.flight.silence(),this.flightGain.gain.setValueAtTime(0,this.context.currentTime)}dispose(){this.disposed||(this.disposed=!0,this.silence(),this.launch.dispose(),this.explosion.dispose(),this.flight.dispose(),this.flightGain.disconnect(),this.output.disconnect())}},PC={bulletRicochetChance:.22,bulletRicochetMinimumGapSeconds:.08},FC=class{preset;engine=null;tires=null;lifecycle=null;electric=null;horn=null;crashes=null;flamethrower=null;boost=null;rockets=null;gunshot=null;ricochets=[];lastRicochetAt=-1/0;crunch=null;combustibleExplosion=null;burningFire=null;electricCharge=null;electricBolt=null;ghostMode=null;attractor=null;fireOutput=null;hornPressed=!1;output=null;engineStartPromise=null;startGateTimer=null;stopTimer=null;disposed=!1;stopping=!1;starting=!1;ready=!1;active=!0;idleSound;driving=!1;engineAudible=null;masterVolume;proximity=1;appliedVolume=-1;baseLaunchFlareRpm=2400;timeScale=1;get playbackRate(){return this.timeScale}setTimeScale(e){let t=Number.isFinite(e)&&e>0?Math.min(1,e):1;(t!==this.timeScale||this.engine&&this.engine.timeScale!==t)&&(this.timeScale=t,this.engine&&(this.engine.timeScale=this.timeScale,o(this.engine.ctx,this.timeScale)))}constructor(e,t={}){this.preset=e,this.idleSound=t.idleSound??!0,this.masterVolume=Re(t.masterVolume??1)}get rpm(){return this.ready?this.engine?.physics.rpm??null:null}get gear(){return this.ready?this.engine?.physics.gear??null:null}takeExhaustPops(){if(!this.ready||!this.engine)return[];let e=this.engine.ctx.currentTime,t=this.engine.takePops();return this.preset.sound.electric||!this.active?[]:t.filter(t=>e-t.time<.25).map(e=>Math.max(0,Math.min(1,e.amp)))}get redlineRpm(){return this.engine?.physics.engine.redlineRpm??null}get outputVolume(){return this.masterVolume*this.proximity}silenceTires(){this.tires?.silence()}setMasterVolume(e){let t=Re(e);Math.abs(t-this.masterVolume)<.001||(this.masterVolume=t,this.syncOutputVolume(),this.rockets?.setMasterVolume(this.masterVolume),this.fireOutput?.gain.setTargetAtTime(this.masterVolume,this.fireOutput.context.currentTime,.055))}setProximity(e){this.proximity=Re(e),this.syncOutputVolume()}syncOutputVolume(){if(!this.output)return;let e=this.outputVolume;Math.abs(e-this.appliedVolume)<.001||(this.appliedVolume=e,this.output.gain.setTargetAtTime(e,this.output.context.currentTime,.055))}async start(){if(!(this.engine||this.disposed||this.stopping))try{let e=new _C(null,{engine:this.preset.sound.engineId,vehicle:this.preset.sound.vehicleId,turbo:this.preset.sound.turbo??!1,volume:0});this.engine=e,this.setTimeScale(this.timeScale),this.baseLaunchFlareRpm=e.physics.launchFlareRpm,this.output=e.ctx.createGain(),this.output.gain.value=this.outputVolume,this.appliedVolume=this.outputVolume,this.output.connect(e.ctx.destination),e.connect(this.output);let t=Ee(e.ctx).initialize();if(this.tires=new Le(e.ctx,this.output),this.horn=new wC(e.ctx,this.preset.sound.horn,this.output),this.crashes=new OC(e.ctx,this.output),this.flamethrower=new kC(e.ctx,this.output),this.boost=new AC(e.ctx,this.output),this.rockets=new NC(e.ctx,this.masterVolume),this.gunshot=new MC(e.ctx,this.output,`machine-gun`,Ae(ke.machineGun)),this.ricochets=[`bullet-ricochet-1`,`bullet-ricochet-2`,`bullet-ricochet-3`].map(t=>new MC(e.ctx,this.output,t,Ae(ke.ricochet))),this.crunch=new MC(e.ctx,this.output,`crush`,Ae(ke.crush)),this.combustibleExplosion=new MC(e.ctx,this.output,`combustible-explosion`,Ae(ke.combustibleExplosion),{queueWhileLoading:!0}),this.fireOutput=e.ctx.createGain(),this.fireOutput.gain.value=this.masterVolume,this.fireOutput.connect(e.ctx.destination),this.burningFire=new jC(e.ctx,this.fireOutput,`burning-fire`,Ae(ke.burningFire),{followLevel:!0}),this.horn.setPressed(this.hornPressed&&this.active),this.preset.sound.electric?this.electric=new CC(e.ctx,this.preset.sound.electric,this.output):this.lifecycle=new bC(e.ctx,this.output),e.ctx.state===`suspended`&&await e.ctx.resume(),this.disposed||this.stopping)return;if(this.lifecycle){if(this.starting=!0,await this.lifecycle.ready,this.disposed||this.stopping)return;let e=this.lifecycle.start(this.preset);this.startGateTimer=window.setTimeout(()=>{this.startGateTimer=null,this.starting=!1,this.syncEngineVolume()},e*1e3)}if(await t,this.disposed||this.stopping||(this.engineStartPromise=e.start(),await this.engineStartPromise,this.disposed))return;if(this.stopping){e.stop();return}this.ready=!0,this.applyPreset(),this.syncEngineVolume()}catch(e){if(this.disposed)return;this.startGateTimer!==null&&window.clearTimeout(this.startGateTimer),this.startGateTimer=null,this.starting=!1,this.lifecycle?.dispose(),this.lifecycle=null,this.electric?.dispose(),this.electric=null,this.tires?.dispose(),this.tires=null,this.horn?.dispose(),this.horn=null,this.crashes?.dispose(),this.crashes=null,this.flamethrower?.dispose(),this.flamethrower=null,this.boost?.dispose(),this.boost=null,this.rockets?.dispose(),this.rockets=null,this.gunshot?.dispose(),this.gunshot=null,this.ricochets.forEach(e=>e.dispose()),this.ricochets=[],this.crunch?.dispose(),this.crunch=null,this.combustibleExplosion?.dispose(),this.combustibleExplosion=null,this.burningFire?.dispose(),this.burningFire=null,this.electricCharge?.dispose(),this.electricCharge=null,this.electricBolt?.dispose(),this.electricBolt=null,this.ghostMode?.dispose(),this.ghostMode=null,this.attractor?.dispose(),this.attractor=null,this.fireOutput?.disconnect(),this.fireOutput=null,this.engine&&(s(this.engine.ctx),De(this.engine.ctx)),this.engine?.dispose(),this.engine=null,this.output?.disconnect(),this.output=null,this.appliedVolume=-1,this.engineStartPromise=null,this.ready=!1,this.stopping||console.warn(`Joy Ride engine audio could not start.`,e)}}setPreset(e){this.preset=e,this.horn?.setProfile(e.sound.horn),this.ready&&this.applyPreset()}setHorn(e){this.hornPressed=e,e&&!this.engine&&!this.disposed&&!this.stopping&&this.start(),this.horn?.setPressed(e&&this.active&&!this.stopping)}setFlamethrowerFiring(e){this.flamethrower?.setPressed(e&&this.active&&!this.stopping)}setBoosting(e){this.boost?.setBoosting(e&&this.active&&!this.stopping)}playRocketLaunch(e){this.active&&!this.stopping&&this.rockets?.playLaunch(e)}playRocketExplosion(e){this.active&&!this.stopping&&this.rockets?.playExplosion(e)}playCombustibleExplosion(e=1){this.active&&!this.stopping&&this.combustibleExplosion?.play(e)}setRocketFlightProximity(e){this.rockets?.setFlightProximity(this.active&&!this.stopping?e:0)}setBurningFireProximity(e){this.burningFire?.setLevel(this.active&&!this.stopping?e:0)}setElectricCharge(e){e>0&&this.active&&!this.stopping&&!this.electricCharge&&this.engine&&this.output&&(this.electricCharge=new jC(this.engine.ctx,this.output,`electric-charge`,Ae(ke.electricCharge))),this.electricCharge?.setLevel(this.active&&!this.stopping?e:0)}playElectricBolt(e=1){this.active&&!this.stopping&&this.engine&&this.output&&(this.electricBolt??=new MC(this.engine.ctx,this.output,`electric-bolt`,Ae(ke.electricBolt),{queueWhileLoading:!0}),this.electricBolt.play(e))}setGhostMode(e){e&&this.active&&!this.stopping&&!this.ghostMode&&this.engine&&this.output&&(this.ghostMode=new jC(this.engine.ctx,this.output,`ghost-mode`,Ae(ke.ghostMode))),this.ghostMode?.setLevel(this.active&&!this.stopping&&e?1:0)}setAttractor(e){e&&this.active&&!this.stopping&&!this.attractor&&this.engine&&this.output&&(this.attractor=new jC(this.engine.ctx,this.output,`attractor`,Ae(ke.attractor))),this.attractor?.setLevel(this.active&&!this.stopping&&e?1:0)}playCrush(){this.active&&!this.stopping&&this.crunch?.play()}playCrash(e){this.active&&!this.stopping&&this.crashes?.play(e)}playGunshot(){this.active&&!this.stopping&&!this.disposed&&this.gunshot?.play()}playBulletImpact(e=1){if(!this.active||this.stopping||this.disposed||!this.engine)return;let t=this.engine.ctx.currentTime;t-this.lastRicochetAt<PC.bulletRicochetMinimumGapSeconds||Math.random()>=PC.bulletRicochetChance||(this.lastRicochetAt=t,this.ricochets[Math.floor(Math.random()*this.ricochets.length)]?.play(e))}applyPreset(){this.engine&&!this.disposed&&(this.preset.sound.electric?(this.startGateTimer!==null&&window.clearTimeout(this.startGateTimer),this.startGateTimer=null,this.starting=!1,this.lifecycle?.dispose(),this.lifecycle=null,this.electric??=new CC(this.engine.ctx,this.preset.sound.electric,this.output??this.engine.ctx.destination),this.electric.setRange(this.preset.sound.electric)):(this.electric?.dispose(),this.electric=null,this.lifecycle??=new bC(this.engine.ctx,this.output??this.engine.ctx.destination),this.engine.setEngineType(this.preset.sound.engineId),this.engine.setVehicle(this.preset.sound.vehicleId),this.engine.setTurbo(this.preset.sound.turbo??!1)),this.engineAudible=null,this.syncEngineVolume())}setIdleSound(e){this.idleSound=e,this.syncEngineVolume()}syncEngineVolume(){if(!this.ready||!this.engine)return;let e=!this.preset.sound.electric&&this.active&&!this.starting&&!this.stopping&&(this.idleSound||this.driving);e!==this.engineAudible&&(this.engineAudible=e,this.engine.setVolume(e?Ae(ke.engine):0))}setActive(e){this.active!==e&&(this.active=e,this.syncEngineVolume(),e?this.horn?.setPressed(this.hornPressed&&!this.stopping):(this.tires?.silence(),this.electric?.silence(),this.horn?.silence(),this.crashes?.silence(),this.flamethrower?.silence(),this.boost?.silence(),this.rockets?.silence(),this.gunshot?.silence(),this.ricochets.forEach(e=>e.silence()),this.crunch?.silence(),this.combustibleExplosion?.silence(),this.burningFire?.silence(),this.electricCharge?.silence(),this.electricBolt?.silence(),this.ghostMode?.silence(),this.attractor?.silence()))}update(e,t,n,r=0,i=0,a=0,o){if(!this.engine||this.disposed||!this.ready)return;this.driving=Math.abs(t.throttle)>.01||n>.45,this.syncEngineVolume(),this.engine.physics.ww=Math.max(0,n)/Math.max(.01,this.engine.physics.r);let s=t.action&&t.throttle>.5&&t.boost,c=this.engine.physics,l=Math.min(c.engine.redlineRpm*.55,c.engine.idleRpm+1500+900*a),u=Math.max(.08,Math.min(.7,.4+(c.rpm-l)*3e-4));this.engine.setClutchOverride(s?u:null),this.engine.physics.launchFlareRpm=this.baseLaunchFlareRpm+(s?900*a:0),this.engine.setThrottle(Math.abs(t.throttle)),this.engine.setBrake(t.action?.85:0),this.engine.update(e),this.electric?.update(n,t.throttle,this.active&&!this.stopping&&(this.idleSound||this.driving)),this.tires?.update(e,this.active?o??[{skidding:r>0,slipMps:r,speedMps:n,wheelSpeedMps:n,loadN:this.preset.massKg*9.81,heat:i,grip:1}]:[],this.preset.massKg)}stop(){if(this.disposed||this.stopping)return;if(!this.engine){this.dispose();return}this.stopping=!0,this.ready=!1,this.starting=!1,this.startGateTimer!==null&&window.clearTimeout(this.startGateTimer),this.startGateTimer=null,this.tires?.silence(),this.electric?.silence(),this.hornPressed=!1,this.horn?.silence(),this.crashes?.silence(),this.flamethrower?.silence(),this.boost?.silence(),this.rockets?.silence(),this.gunshot?.silence(),this.ricochets.forEach(e=>e.silence()),this.crunch?.silence(),this.combustibleExplosion?.silence(),this.burningFire?.silence(),this.electricCharge?.silence(),this.electricBolt?.silence(),this.ghostMode?.silence(),this.attractor?.silence(),this.engine?.setThrottle(0),this.engine?.stop();let e=this.preset.sound.electric?0:this.lifecycle?.stop(this.preset)??0;this.stopTimer=window.setTimeout(()=>{this.stopTimer=null,this.engineStartPromise?this.engineStartPromise.then(()=>this.dispose(),()=>this.dispose()):this.dispose()},Math.max(650,e*1e3))}dispose(){if(this.disposed)return;this.disposed=!0,this.ready=!1,this.startGateTimer!==null&&window.clearTimeout(this.startGateTimer),this.stopTimer!==null&&window.clearTimeout(this.stopTimer),this.startGateTimer=null,this.stopTimer=null,this.lifecycle?.dispose(),this.lifecycle=null,this.electric?.dispose(),this.electric=null,this.tires?.dispose(),this.tires=null,this.horn?.dispose(),this.horn=null,this.crashes?.dispose(),this.crashes=null,this.flamethrower?.dispose(),this.flamethrower=null,this.boost?.dispose(),this.boost=null,this.rockets?.dispose(),this.rockets=null,this.gunshot?.dispose(),this.gunshot=null,this.ricochets.forEach(e=>e.dispose()),this.ricochets=[],this.crunch?.dispose(),this.crunch=null,this.combustibleExplosion?.dispose(),this.combustibleExplosion=null,this.burningFire?.dispose(),this.burningFire=null,this.electricCharge?.dispose(),this.electricCharge=null,this.electricBolt?.dispose(),this.electricBolt=null,this.ghostMode?.dispose(),this.ghostMode=null,this.attractor?.dispose(),this.attractor=null,this.fireOutput?.disconnect(),this.fireOutput=null,this.hornPressed=!1;let e=this.engine;e&&(this.engineStartPromise?this.engineStartPromise.then(()=>e.dispose(),()=>e.dispose()):e.dispose()),e&&(s(e.ctx),De(e.ctx)),this.engine=null,this.engineAudible=null,this.output?.disconnect(),this.output=null,this.appliedVolume=-1}},IC=`joy-ride-odometer-v1`,LC=`joy-ride-distance-dpi-v1`,RC=1609.344,zC={screen:96,print:300};zC.print;var BC=.0254;function VC(){try{return typeof window>`u`?null:window.localStorage}catch{return null}}var HC={pixels:0,kilometers:0,miles:0,dpi:zC.print,dpiMode:`print`};function UC(e){if(!e||typeof e!=`object`)return!1;let t=e;return Number.isFinite(t.pixels)&&(t.pixels??-1)>=0}var WC=class{store;total;dirty=!1;mode=`print`;constructor(e=VC()){this.store=e;let t=null;try{t=JSON.parse(this.store?.getItem(IC)??`null`)}catch{}this.total=UC(t)?{pixels:t.pixels}:{pixels:0};try{this.store?.getItem(LC)===`screen`&&(this.mode=`screen`)}catch{}}add(e,t){!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0||(this.total.pixels+=e*t,this.dirty=!0)}reset(){this.total.pixels=0,this.dirty=!0,this.flush()}get dpiMode(){return this.mode}captureState(){return{pixels:this.total.pixels,mode:this.mode}}restoreState(e){if(!Number.isFinite(e.pixels)||e.pixels<0||!(e.mode in zC))throw Error(`Invalid odometer checkpoint`);this.total.pixels=e.pixels,this.mode=e.mode,this.dirty=!0,this.flush();try{this.store?.setItem(LC,this.mode)}catch{}}get dpi(){return zC[this.mode]}cycleDpi(){this.mode=this.mode===`print`?`screen`:`print`;try{this.store?.setItem(LC,this.mode)}catch{}return this.readout}flush(){if(this.dirty)try{this.store?.setItem(IC,JSON.stringify(this.total)),this.dirty=!1}catch{}}get kilometers(){return this.total.pixels/this.dpi*BC/1e3}get miles(){return this.total.pixels/this.dpi*BC/RC}get readout(){return{pixels:this.total.pixels,kilometers:this.kilometers,miles:this.miles,dpi:this.dpi,dpiMode:this.mode}}},GC=un.map(e=>`Digit${e}`),KC=[{id:`accelerate`,label:`Accelerate`,keys:[`W`,`↑`],codes:[`KeyW`,`ArrowUp`]},{id:`reverse`,label:`Reverse`,keys:[`S`,`↓`],codes:[`KeyS`,`ArrowDown`]},{id:`left`,label:`Steer left`,keys:[`A`,`←`],codes:[`KeyA`,`ArrowLeft`]},{id:`right`,label:`Steer right`,keys:[`D`,`→`],codes:[`KeyD`,`ArrowRight`]},{id:`handbrake`,label:`Handbrake`,keys:[`Space`],codes:[`Space`]},{id:`boost`,label:`Hold boost / charge burnout launch`,keys:[`Shift`],codes:[`ShiftLeft`,`ShiftRight`]},...un.map(e=>({id:`slot${e}`,label:`Use assigned action in slot ${e}`,keys:[String(e)],codes:[`Digit${e}`]})),{id:`slowMo`,label:`Hold slow-mo`,keys:[`V`],codes:[`KeyV`]},{id:`underglow`,label:`Toggle underglow`,keys:[`U`],codes:[`KeyU`]},{id:`horn`,label:`Horn`,keys:[`H`],codes:[`KeyH`]},{id:`record`,label:`Record`,keys:[`R`],codes:[`KeyR`]},{id:`clean`,label:`Reset screen`,keys:[`C`],codes:[`KeyC`]},{id:`targets`,label:`Flash destroyable objects`,keys:[`F`],codes:[`KeyF`]},{id:`pause`,label:`Pause`,keys:[`P`],codes:[`KeyP`]},{id:`exit`,label:`Exit`,keys:[`Esc`],codes:[`Escape`]}],qC=new Set([`KeyW`,`KeyA`,`KeyS`,`KeyD`,`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Space`,`ShiftLeft`,`ShiftRight`,...GC]),JC=new Set([`KeyR`,`KeyU`,`KeyC`,`KeyF`,`KeyV`,`KeyP`,`KeyB`,`KeyG`,`KeyZ`,`KeyX`,`Escape`]);function YC(e){return(e instanceof Event?e.composedPath():[e]).some(e=>e instanceof Element&&!!e.closest(`input, textarea, select, [contenteditable="true"]`))}function XC(e){return{throttle:Number(e.has(`KeyW`)||e.has(`ArrowUp`))-Number(e.has(`KeyS`)||e.has(`ArrowDown`)),steer:Number(e.has(`KeyA`)||e.has(`ArrowLeft`))-Number(e.has(`KeyD`)||e.has(`ArrowRight`)),action:e.has(`Space`),boost:e.has(`ShiftLeft`)||e.has(`ShiftRight`),slots:un.filter(t=>e.has(`Digit${t}`))}}var ZC=`joy-ride:vehicles:v1`,QC=Object.values(rt);function $C(){try{if(typeof localStorage>`u`)return[];let e=JSON.parse(localStorage.getItem(ZC)??`[]`);return Array.isArray(e)?e.flatMap(e=>{try{return[aw(e)]}catch{return[]}}):[]}catch{return[]}}function ew(){let e=$C();return[...QC.map(t=>e.find(e=>e.id===t.id)??t),...e.filter(e=>nw(e.id))]}function tw(e){return ew().find(t=>t.id===e)}function nw(e){return e.startsWith(`custom-`)}function rw(e){return QC.some(t=>t.id===e)&&$C().some(t=>t.id===e)}function iw(e){let t=globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;return{...structuredClone(e),id:`custom-${t}`,name:`${e.name} Custom`}}function $(e,t,n){return typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n}function aw(e){if(!e||typeof e!=`object`)throw Error(`Invalid vehicle file.`);let t={...e},n=t.geometry;if(typeof t.id!=`string`||!(nw(t.id)||QC.some(e=>e.id===t.id))||t.id.length>100||typeof t.name!=`string`||!t.name.trim()||t.name.length>100||typeof t.description!=`string`||!n||!t.roofRocket||!t.sound||!t.sound.horn||!t.exhaust||!t.drift||!t.launch||!t.driveBoost||typeof t.sound.engineId!=`string`||!t.sound.engineId||typeof t.sound.vehicleId!=`string`||!t.sound.vehicleId||typeof t.sound.engineLabel!=`string`||![`left`,`right`,`center`,`left-right`].includes(t.exhaust.layout)||!$(t.massKg,50,1e4)||!$(n.lengthM,1,15)||!$(n.widthM,.5,6)||!$(n.wheelbaseM,.5,n.lengthM)||!$(n.trackWidthM,.3,n.widthM)||!$(n.tireLengthM,.1,2)||!$(n.tireWidthM,.05,1)||!$(t.engineForceN,100,1e5)||!$(t.rollingResistance,.1,1e4)||!$(t.maxSteerAngleRad,.05,1.4)||!$(t.roofRocket.xM,-n.lengthM/2,n.lengthM/2)||!$(t.roofRocket.yM,-n.widthM/2,n.widthM/2)||!$(t.roofRocket.sizeM,.1,n.widthM)||t.image&&(!/^(data:image\/(?:png|webp|jpeg);base64,|https?:\/\/|\/)/i.test(t.image.src)||t.image.src.length>3e6))throw Error(`Invalid vehicle geometry or settings.`);if([[t.reversePowerRatio,.05,2],[t.coastDecelerationMps2,0,30],[t.handbrakeDecelerationMps2,0,30],[t.lateralResistance,1,1e4],[t.corneringAccelerationMps2,1,100],[t.handbrakeStrength,0,2],[t.drift.entrySpeedMps,.2,30],[t.drift.slipAngleRad,.05,1.2],[t.launch.minRpm,0,12e3],[t.launch.boostMps,0,20],[t.launch.boostedBoostMps,0,30],[t.launch.assistDurationSeconds,.05,10],[t.launch.burnoutRampSeconds,.1,10],[t.launch.chargedSpinSeconds,0,20],[t.launch.fireLifetimeSeconds,0,30],[t.driveBoost.gainMps,0,30],[t.driveBoost.durationSeconds,.05,10],[t.driveBoost.cooldownSeconds,0,30],[t.sound.horn.lowHz,80,1200],[t.sound.horn.highHz,80,1600],[t.sound.horn.level,0,2]].some(([e,t,n])=>!$(e,t,n))||![`disc`,`trumpet`,`electronic`].includes(t.sound.horn.tone)||t.frontWeightFraction!==void 0&&!$(t.frontWeightFraction,.1,.9)||t.maxReverseSpeedMps!==void 0&&!$(t.maxReverseSpeedMps,1,30)||t.health!==void 0&&!$(t.health,1,1e4)||n.frontTrackWidthM!==void 0&&!$(n.frontTrackWidthM,.3,n.widthM)||n.rearTrackWidthM!==void 0&&!$(n.rearTrackWidthM,.3,n.widthM)||t.image?.scale!==void 0&&!$(t.image.scale,.5,1.5))throw Error(`Invalid vehicle tuning.`);let r=t.image?.crop;if(t.lightning!==void 0){if(!t.lightning||typeof t.lightning!=`object`||Array.isArray(t.lightning))throw Error(`Invalid lightning settings.`);let e={rangeM:[1,30],forwardBias:[0,4],chargeSeconds:[.1,10],statusSeconds:[.1,30],speedFactor:[.1,1],impactRadiusM:[.1,10],damage:[0,1e4],impulse:[0,4]};for(let[n,r]of Object.entries(t.lightning))if(n===`ignite`){if(typeof r!=`boolean`)throw Error(`Invalid lightning ignition.`)}else if(!e[n]||!$(r,...e[n]))throw Error(`Invalid lightning settings.`)}if(t.lights!==void 0){if(!t.lights||typeof t.lights!=`object`||Array.isArray(t.lights))throw Error(`Invalid vehicle light points.`);for(let e of[`headlights`,`taillights`]){let r=t.lights[e];if(r!==void 0&&(!r||!$(r.xM,-n.lengthM/2,n.lengthM/2)||!$(r.yM,0,n.widthM/2)))throw Error(`Invalid vehicle light points.`)}}if(r&&(!$(r.x,0,1)||!$(r.y,0,1)||!$(r.width,.01,1)||!$(r.height,.01,1)||r.x+r.width>1.001||r.y+r.height>1.001))throw Error(`Invalid vehicle image crop.`);if(n.frontAxleXM!==void 0&&!$(n.frontAxleXM,-n.lengthM/2,n.lengthM/2))throw Error(`Invalid front axle.`);if(n.rearAxleXM!==void 0&&!$(n.rearAxleXM,-n.lengthM/2,n.lengthM/2))throw Error(`Invalid rear axle.`);let i=e=>typeof e==`number`?Number.isFinite(e):e===null||typeof e==`boolean`||typeof e==`string`||typeof e==`object`&&Object.values(e).every(i);if(!i(t))throw Error(`Invalid vehicle settings.`);return t}function ow(e){let t=aw(e);if(typeof localStorage>`u`)throw Error(`Browser storage is unavailable.`);let n=$C().filter(e=>e.id!==t.id);return n.push(t),localStorage.setItem(ZC,JSON.stringify(n)),typeof window<`u`&&window.dispatchEvent(new Event(`joy-ride:vehicles-changed`)),t}function sw(e){(nw(e)||QC.some(t=>t.id===e))&&typeof localStorage<`u`&&(localStorage.setItem(ZC,JSON.stringify($C().filter(t=>t.id!==e))),typeof window<`u`&&window.dispatchEvent(new Event(`joy-ride:vehicles-changed`)))}function cw(){return ew().map(({id:e,name:t,make:n,model:r,year:i,image:a})=>({id:e,name:t,make:n,model:r,year:i,image:a?.src}))}function lw(e){if(e&&typeof e==`object`&&!(typeof Node<`u`&&e instanceof Node)){for(let t of Object.values(e))lw(t);Object.freeze(e)}return e}var uw={lighting:Ol(),masterVolume:1,idleSound:!0,quality:`high`,smokeTint:`natural`,surfaceTone:`auto`,debug:!1,sparks:!0,deform:!0,screenShake:!0,showHud:!1,showTotalPoints:!0,showHealthBars:!0,showVehicleMarkers:!0,showWeaponBar:!0,weaponCooldown:!0,autoPaint:!1,rocketBlastStrength:1,viewportWalls:!0,speedZoom:`auto`,vehicleDestructible:!0,weaponsEnabled:!0,enabledTools:oo.map(e=>e.id)},dw=lw(uw);function fw(e,t){return{...e,...Object.fromEntries(Object.entries(Do(t)).filter(([e])=>e in uw))}}var pw={audio:[`masterVolume`,`idleSound`],rendering:[`quality`,`smokeTint`,`sparks`,`deform`,`screenShake`,`surfaceTone`,`debug`],policy:[`weaponCooldown`,`vehicleDestructible`,`weaponsEnabled`,`enabledTools`,`rocketBlastStrength`],ui:[`showHud`,`showTotalPoints`,`showHealthBars`,`showVehicleMarkers`,`showWeaponBar`],camera:[`viewportWalls`,`speedZoom`]};function mw(e){let t={lighting:Ol(e.lighting),autoPaint:e.autoPaint??!1};for(let[n,r]of Object.entries(pw))t[n]=Object.fromEntries(r.map(t=>[t,e[t]]));return lw(structuredClone(t))}function hw(e,t){if(!t||typeof t!=`object`||Array.isArray(t))throw TypeError(`Runtime options must be an object`);let n=structuredClone(e),r=new Set([...Object.keys(pw),`lighting`,`autoPaint`]);for(let e of Object.keys(t))if(!r.has(e))throw TypeError(`Unknown runtime option: ${e}`);for(let[e,r]of Object.entries(pw)){let i=t[e];if(i!==void 0){if(!i||typeof i!=`object`||Array.isArray(i))throw TypeError(`options.${e} must be an object`);for(let[t,a]of Object.entries(i)){if(!r.includes(t))throw TypeError(`Unknown option: ${e}.${t}`);a!==void 0&&(n[t]=structuredClone(a))}}}if(t.lighting!==void 0){if(!t.lighting||typeof t.lighting!=`object`)throw TypeError(`Lighting options must be an object`);for(let[e,n]of Object.entries(t.lighting)){let t=Ol()[e];if(t===void 0||typeof n!=typeof t)throw TypeError(`Invalid lighting option: ${e}`);if(e===`underglowColor`&&!/^#[\da-f]{6}$/i.test(n))throw TypeError(`Underglow color must be six-digit hex`);if(e===`underglowOpacity`&&(!Number.isFinite(n)||n<0||n>1))throw RangeError(`Underglow opacity must be between 0 and 1`)}n.lighting=Ol({...n.lighting,...t.lighting})}t.autoPaint!==void 0&&(n.autoPaint=t.autoPaint);for(let[e,t]of Object.entries(n))if(typeof dw[e]==`boolean`&&typeof t!=`boolean`)throw TypeError(`${e} must be a boolean`);for(let[e,t]of Object.entries({quality:[`low`,`medium`,`high`],smokeTint:[`natural`,`cyan`,`magenta`],surfaceTone:[`auto`,`light`,`dark`]}))if(!t.includes(n[e]))throw TypeError(`Invalid ${e}`);if(n.speedZoom!==`auto`&&typeof n.speedZoom!=`boolean`)throw TypeError(`Invalid speedZoom`);for(let[e,t,r]of[[`masterVolume`,0,1],[`rocketBlastStrength`,0,10]])if(!Number.isFinite(n[e])||n[e]<t||n[e]>r)throw RangeError(`${e} must be between ${t} and ${r}`);if(!Array.isArray(n.enabledTools)||n.enabledTools.some(e=>!oo.some(t=>t.id===e)))throw TypeError(`Unknown enabled vehicle tool`);return n}var gw=class extends Error{code=`JR_NON_SERIALIZABLE_DEPENDENCY`;dependencies;constructor(e){super(`Configuration cannot be exported: ${e.map(({path:e,reason:t})=>`${e}: ${t}`).join(`; `)}`),this.name=`NonSerializableDependencyError`,this.dependencies=Object.freeze(e.map(e=>Object.freeze({...e})))}};function _w(e,t,n,r=new Set){if(e===null||typeof e==`string`||typeof e==`boolean`||e===void 0||typeof e==`number`&&Number.isFinite(e))return;if(typeof e!=`object`){n.push({path:t,reason:`only finite JSON values can be exported`});return}if(r.has(e)){n.push({path:t,reason:`cyclic references cannot be exported`});return}let i=Object.getPrototypeOf(e);if(!Array.isArray(e)&&i!==null&&Object.getPrototypeOf(i)!==null)n.push({path:t,reason:`DOM references and strategy instances are not serializable`});else{r.add(e);for(let[i,a]of Object.entries(e))_w(a,`${t}.${i}`,n,r);r.delete(e)}}function vw(e){return e&&typeof e==`object`&&(Object.values(e).forEach(vw),Object.freeze(e)),e}function yw(e){let t=[];if(_w(e,`configuration`,t),t.length)throw new gw(t);for(let t of Object.keys(e))if(![`root`,`definitions`,`player`,`bindings`,`routes`,`options`,`workMode`].includes(t))throw TypeError(`Unknown playground configuration field: ${t}`);if(e.root!==void 0&&(typeof e.root!=`string`||!e.root.trim()))throw TypeError(`Configuration root must be a selector string`);let n=ac(e.definitions??{}),r=e.player===void 0?void 0:Bs(e.player),i=e.bindings?.map((e,t)=>{if(typeof e.target!=`string`||!e.target.trim())throw new gw([{path:`bindings.${t}.target`,reason:`use a selector instead of an element reference`}]);return{target:e.target,spec:Is(e.spec)}}),a=e.routes&&Object.fromEntries(Object.entries(e.routes).map(([e,t])=>[e,Hs(t)])),o=e.options===void 0?void 0:mw(hw(fw(dw,{workMode:e.workMode}),e.options));if(e.workMode!==void 0){if(!e.workMode||typeof e.workMode!=`object`||Array.isArray(e.workMode))throw TypeError(`workMode must be an option object`);let t=Do();for(let[n,r]of Object.entries(e.workMode))if(r!==void 0){if(n===`sfw`){if(typeof r!=`boolean`)throw TypeError(`workMode.sfw must be boolean`)}else{if(!Object.hasOwn(t,n)&&![`brandColor`,`brandName`].includes(n))throw TypeError(`Unknown workMode option: ${n}`);if(typeof t[n]==`boolean`&&typeof r!=`boolean`)throw TypeError(`workMode.${n} must be boolean`);if([`brandColor`,`brandName`].includes(n)&&typeof r!=`string`)throw TypeError(`workMode.${n} must be a string`);if(n===`vehicleTabs`&&(!Array.isArray(r)||r.some(e=>!wo.includes(e))))throw TypeError(`Unknown workMode vehicle tab`);n===`enabledTools`&&hw(dw,{policy:{enabledTools:r}})}}}return vw(structuredClone({...e,definitions:n,player:r,bindings:i,routes:a,options:o,format:`joy-ride-playground`,version:1}))}function bw(e){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Expected a playground configuration`);let t=e;if(t.format!==`joy-ride-playground`||t.version!==1)throw TypeError(`Unsupported playground configuration format or version`);for(let e of Object.keys(t))if(![`format`,`version`,`root`,`definitions`,`player`,`bindings`,`routes`,`options`,`workMode`].includes(e))throw TypeError(`Unknown playground configuration field: ${e}`);let{format:n,version:r,...i}=t;return yw(i)}function xw(e){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Recording needs a portable vehicle configuration`);let t=e,n=[];if(_w(t,`vehicle`,n),n.length)throw new gw(n);for(let e of Object.keys(t))if(![`preset`,`appearance`,`slots`,`liquids`].includes(e))throw TypeError(`Unknown recorded vehicle field: ${e}`);if(t.appearance===void 0||t.slots===void 0||t.liquids===void 0)throw TypeError(`Recording needs appearance, slots, and material definitions`);let r=aw(t.preset),i=zs({vehicle:r.id,appearance:t.appearance,slots:t.slots}),a=ac({liquids:t.liquids});return vw({preset:r,appearance:i.appearance,slots:i.slots,liquids:a.liquids??{}})}function Sw(e,t){if(!(typeof HTMLElement<`u`&&e instanceof HTMLElement)){for(let e of[`trigger`,`crushable`,`combustible`,`pushable`])if(t[e])throw new Jo(`object.${e}`,`${e} requires an HTML element`);if(t.liquid&&!(typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement))throw new Jo(`object.liquid`,`liquid requires HTML or an SVG shape`);if(!(typeof SVGSVGElement<`u`&&e instanceof SVGSVGElement)&&(t.breakable||t.burnable))throw new Jo(`object`,`breakable and burnable artwork require HTML text/artwork or an SVG root`)}}var Cw=0;function ww(e){return e&&typeof e==`object`&&(Object.values(e).forEach(ww),Object.freeze(e)),e}var Tw=class{root;definitions;scope=++Cw;registrations=new Set;records=new Map;snapshot=Object.freeze([]);identities=new WeakMap;patches=new Map;listeners=new Set;diagnosticListeners=new Set;liquids=new Map;vehicles=new Map;importedVehicles=new Map;importedLiquids=new Map;recordingImports=new Map;importSerial=0;observer;dirty=!0;disposed=!1;nextId=0;nextRegistration=0;version=0;pageStateChanged=()=>this.invalidate();constructor(e=document,t={}){this.root=e,this.definitions=ac(t);try{for(let e of Object.keys(this.definitions.liquids??{}))this.resolveLiquid(e);for(let e of Object.keys(this.definitions.vehicles??{}))this.resolveVehicle(e);for(let e of Object.values(this.definitions.objects??{}))this.resolve(e);this.observe()}catch(e){throw this.dispose(),e}}observe(){this.observer?.disconnect(),this.observer??=new MutationObserver(e=>{e.some(e=>{if(e.type!==`attributes`){let t=e.target instanceof Element?e.target:e.target.parentElement;return!(t&&this.records.get(t)?.spec.hud)}if((e.target instanceof Element?e.target:null)?.closest(`[data-jr-embed],[data-jr-overlay],[data-jr-text-run]`))return!1;if([...this.registrations].some(e=>typeof e.target==`string`))return!0;let t=e.attributeName??``;return t!==`style`&&![`data-jr-trigger-state`,`data-jr-trigger-departed`,`data-jr-crushed`].includes(t)})&&this.invalidate()});for(let e of[`input`,`change`,`focusin`,`focusout`])this.root.addEventListener(e,this.pageStateChanged);this.observer.observe(this.root,{subtree:!0,childList:!0,attributes:!0,characterData:!0})}invalidate(){if(!(this.disposed||this.dirty)){this.dirty=!0;for(let e of this.listeners)e()}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onDiagnostic(e){return this.diagnosticListeners.add(e),()=>this.diagnosticListeners.delete(e)}report(e,t){let n={code:`configuration`,message:e instanceof Error?e.message:String(e),target:t};for(let e of this.diagnosticListeners)e(n);this.root.dispatchEvent(new CustomEvent(`joyride:diagnostic`,{bubbles:!0,detail:n}))}targets(e){if(typeof e==`string`){let t=[...this.root.querySelectorAll(e)];return this.root instanceof Element&&this.root.matches(e)&&t.unshift(this.root),t}if(e instanceof Element)return[e];if(!e||typeof e[Symbol.iterator]!=`function`)throw TypeError(`Expected a selector, element, or iterable of elements`);let t=[...e];if(t.some(e=>!(e instanceof Element)))throw TypeError(`Every binding target must be an Element`);return[...new Set(t)]}accepts(e){return e.isConnected&&!(this.root instanceof Element&&e!==this.root&&!this.root.contains(e))&&!e.closest(`[data-jr-embed],[data-jr-overlay]`)}compose(e,t=[...this.registrations],n=this.patches.get(e)){let r=t.filter(t=>typeof t.target==`string`&&e.matches(t.target)),i=t.filter(t=>typeof t.target!=`string`&&this.targets(t.target).includes(e)),a=this.resolve(Ws(...r.map(e=>e.spec),rc(e),...i.map(e=>e.spec),n));return Sw(e,a),a}validateChange(e,t,n,r){this.refresh();let i=new Set(e),a=new Set([...this.records.values()].filter(e=>!i.has(e.target)).map(e=>e.id));for(let i of e){if(!this.accepts(i))continue;let e=this.compose(i,t,i===n?r:this.patches.get(i)).id??this.identities.get(i);if(e&&a.has(e))throw Error(`Duplicate playground object ID: ${e}`);e&&a.add(e)}}bindAll(e){let t=[];try{for(let n of e)t.push(this.bind(n.target,n.spec));return t}catch(e){for(let e of t)e.dispose();throw e}}bind(e,t){if(this.disposed)throw Error(`Playground is disposed`);let n=this.targets(e),r={id:++this.nextRegistration,target:typeof e==`string`||e instanceof Element?e:n,spec:Is(t),disposed:!1};this.validateChange(n,[...this.registrations,r]),this.registrations.add(r),this.dirty=!1,this.invalidate();let i=()=>r.disposed||this.disposed?[]:(this.refresh(),this.targets(r.target).flatMap(e=>this.records.get(e)??[]));return{get objects(){return i()},update:e=>{if(r.disposed||this.disposed)throw Error(`Binding is disposed`);let t={...r,spec:Is(Ws(r.spec,e))};this.validateChange(this.targets(r.target),[...this.registrations].map(e=>e===r?t:e)),r.spec=t.spec,this.dirty=!1,this.invalidate()},replace:e=>{if(r.disposed||this.disposed)throw Error(`Binding is disposed`);let t={...r,spec:Is(e)};this.validateChange(this.targets(r.target),[...this.registrations].map(e=>e===r?t:e)),r.spec=t.spec,this.dirty=!1,this.invalidate()},refresh:()=>{if(r.disposed||this.disposed)throw Error(`Binding is disposed`);this.dirty=!1,this.invalidate(),this.refresh()},dispose:()=>{r.disposed||(r.disposed=!0,this.registrations.delete(r),this.dirty=!1,this.invalidate())}}}update(e,t){if(this.disposed)throw Error(`Playground is disposed`);if(this.refresh(),!this.records.has(e))throw Error(`Element is not registered`);let n=Is(Ws(this.patches.get(e),t));this.validateChange([e],[...this.registrations],e,n),this.patches.set(e,n),this.dirty=!1,this.invalidate()}get(e){return this.refresh(),this.records.get(e)}get objects(){return this.refresh(),this.snapshot}refresh(){if(!this.dirty||this.disposed)return;this.dirty=!1;let e=new Set(this.targets(ec));for(let t of this.registrations)for(let n of this.targets(t.target))e.add(n);let t=new Set,n=new Map([...this.records].filter(([t])=>e.has(t)&&this.accepts(t)).map(([e,t])=>[t.id,e])),r=!1;for(let i of e)if(this.accepts(i))try{let e=this.compose(i),a=e.id??this.identities.get(i);a??=`jr-${this.scope}-${++this.nextId}`;let o=n.get(a);if(o&&o!==i||t.has(a))throw Error(`Duplicate playground object ID: ${a}`);t.add(a),this.identities.set(i,a);let s=this.records.get(i);s&&JSON.stringify(s.spec)===JSON.stringify(e)||(this.records.set(i,Object.freeze({id:a,target:i,spec:ww(e),revision:++this.version})),r=!0)}catch(e){this.report(e,i)}for(let[t]of this.records)e.has(t)&&this.accepts(t)||(this.records.delete(t),this.patches.delete(t),r=!0);if(r){this.snapshot=Object.freeze([...this.records.values()]);for(let e of this.listeners)e()}}validateObject(e){return this.resolve(e)}exportBindings(){if(this.disposed)throw Error(`Playground is disposed`);let e=[...this.registrations].flatMap(e=>typeof e.target==`string`?[]:[{path:`bindings.${e.id}.target`,reason:`an exact element binding has no portable selector`}]);if(this.patches.size&&e.push({path:`objectOverrides`,reason:`runtime object overrides are tied to live element identities`}),e.length)throw new gw(e);return[...this.registrations].map(e=>({target:e.target,spec:structuredClone(e.spec)}))}exportDefinitions(){if(this.disposed)throw Error(`Playground is disposed`);return ac({...this.definitions,liquids:{...this.definitions.liquids,...Object.fromEntries(this.importedLiquids)},vehicles:{...this.definitions.vehicles,...Object.fromEntries(this.importedVehicles)}})}registerVehiclePreset(e,t){if(this.disposed)throw Error(`Playground is disposed`);if(this.definitions.vehicles?.[e]||this.importedVehicles.has(e)||Object.values(rt).some(t=>t.id===e))throw Error(`Vehicle recipe already exists: ${e}`);let{id:n,...r}=aw(t),i={...r,base:rt.porsche911997.id};return ac({vehicles:{[e]:i}}),this.importedVehicles.set(e,i),e}vehicleName(e){for(let[t,n]of this.vehicles)if(n.id===e)return t;if(Object.values(rt).some(t=>t.id===e))return e;throw new gw([{path:`player.vehicle`,reason:`vehicle ${e} has no authored recipe in this catalog`}])}captureVehicleConfiguration(e,t,n){let r=structuredClone(n),i=this.exportDefinitions().liquids??{},a={},o=e=>{if(a[e])return;let t=i[e];if(t)a[e]=t,o(t.base);else{if(e.startsWith(`custom:`))throw new gw([{path:`vehicle.liquids`,reason:`material ${e} has no portable authored definition`}]);ot(e)}};for(let e of Object.values(r))if(e&&e.action===`eject`){if(e.liquid=this.liquidName(e.liquid),e.liquid.startsWith(`custom:`))throw new gw([{path:`vehicle.slots`,reason:`material ${e.liquid} is not owned by this catalog`}]);o(e.liquid)}return xw({preset:e,appearance:t,slots:r,liquids:a})}importRecordedVehicle(e){if(this.disposed)throw Error(`Playground is disposed`);let t=xw(e),n=JSON.stringify(t),r=this.recordingImports.get(n);if(r)return structuredClone(r);let i;do i=`recorded-${++this.importSerial}`;while(this.importedVehicles.has(`${i}-vehicle`)||this.definitions.vehicles?.[`${i}-vehicle`]||Object.keys(t.liquids).some((e,t)=>this.importedLiquids.has(`${i}-liquid-${t}`)||this.definitions.liquids?.[`${i}-liquid-${t}`]));let a=new Map(Object.keys(t.liquids).map((e,t)=>[e,`${i}-liquid-${t}`]));for(let e of Object.values(t.liquids))if(!a.has(e.base)){if(e.base.startsWith(`custom:`))throw Error(`Recorded liquid bases must use portable authored names`);ot(e.base)}let o=structuredClone(t.slots);for(let e of Object.values(o))if(e&&e.action===`eject`){if(a.has(e.liquid))e.liquid=a.get(e.liquid);else{if(e.liquid.startsWith(`custom:`))throw Error(`Recorded emitters must use portable authored names`);ot(e.liquid)}}for(let[e,n]of Object.entries(t.liquids))this.importedLiquids.set(a.get(e),{...structuredClone(n),base:a.get(n.base)??n.base});let s={vehicle:this.registerVehiclePreset(`${i}-vehicle`,t.preset),appearance:t.appearance,slots:o};return this.recordingImports.set(n,s),structuredClone(s)}resolve(e,t=new Set){let n=Ws(e);if(typeof n.object==`string`){let e=n.object;if(t.has(e))throw Error(`Circular object definition: ${e}`);let r=this.definitions.objects?.[e];if(!r)throw Error(`Unknown object definition: ${e}`);t.add(e);let{object:i,...a}=n;n=Ws(this.resolve(r,t),a)}let r=n.liquid;return r&&typeof r==`object`&&typeof r.kind==`string`&&(r.kind=this.resolveLiquid(r.kind)),Ls(n)}resolveLiquid(e,t=new Set){let n=this.liquids.get(e);if(n)return n;let r=this.importedLiquids.get(e)??this.definitions.liquids?.[e];if(!r)return ot(e);if(t.has(e))throw Error(`Circular liquid definition: ${e}`);t.add(e);let i=this.resolveLiquid(r.base,t),a=`jr-${this.scope}-${this.liquids.size}-`,o=vt(`${a}${e.slice(0,64-a.length)}`,{...r,base:i});return this.liquids.set(e,o.kind),o.kind}liquidName(e){for(let[t,n]of this.liquids)if(n===e)return t;return e}resolveVehicle(e,t=new Set){let n=this.vehicles.get(e);if(n)return n;let r=this.importedVehicles.get(e)??this.definitions.vehicles?.[e];if(!r){let t=Object.values(rt).find(t=>t.id===e);if(!t)throw Error(`Unknown vehicle definition: ${e}`);return t}if(t.has(e))throw Error(`Circular vehicle definition: ${e}`);t.add(e);let{base:i,appearance:a,slots:o,...s}=r,c=aw(Ws(this.resolveVehicle(i,t),s,{id:`custom-jr-${this.scope}-${e}`}));return this.vehicles.set(e,c),c}vehicleOptions(e){let t=this.importedVehicles.get(e)??this.definitions.vehicles?.[e];return t?Ws(this.vehicleOptions(t.base),{appearance:t.appearance,slots:t.slots}):{appearance:`auto`,slots:pn}}captureState(){return E({patches:this.patches,registrations:new Map([...this.registrations].map(e=>[e.id,e.spec]))})}restoreState(e){let t=E(e);this.patches.clear();for(let[e,n]of t.patches)this.patches.set(e,n);for(let e of this.registrations){let n=t.registrations.get(e.id);n&&(e.spec=n)}this.dirty=!1,this.invalidate(),this.refresh()}reset(){this.patches.clear(),this.dirty=!1,this.invalidate()}dispose(){if(!this.disposed){this.disposed=!0,this.observer?.disconnect();for(let e of[`input`,`change`,`focusin`,`focusout`])this.root.removeEventListener(e,this.pageStateChanged);this.records.clear(),this.snapshot=Object.freeze([]),this.registrations.clear(),this.patches.clear(),this.listeners.clear(),this.diagnosticListeners.clear();for(let e of this.liquids.values())yt(e);this.liquids.clear(),this.vehicles.clear(),this.importedVehicles.clear(),this.importedLiquids.clear(),this.recordingImports.clear()}}};function Ew(e,t,n=0){let{halfX:r,halfY:i}=e,a=r.x*i.y-r.y*i.x;if(Math.abs(a)<1e-4)return!1;let o=t.x-e.center.x,s=t.y-e.center.y,c=(o*i.y-s*i.x)/a,l=(s*r.x-o*r.y)/a;return Math.abs(c)<=1+n/Math.max(1,Math.hypot(r.x,r.y))&&Math.abs(l)<=1+n/Math.max(1,Math.hypot(i.x,i.y))}var Dw=class{transforms=new WeakMap;transform(e){return this.transforms.has(e)||this.transforms.set(e,Ow(e)),this.transforms.get(e)}};function Ow(e){let t=getComputedStyle(e);if(t.visibility===`hidden`||t.display===`none`)return null;let n=new DOMMatrixReadOnly;if(t.rotate&&t.rotate!==`none`){let e=t.rotate.trim().split(/\s+/);if(e.length>1&&e.slice(0,-1).join(` `)!==`z`)return null;let r=e.at(-1),i=parseFloat(r),a=r.endsWith(`grad`)?i*.9:r.endsWith(`rad`)?i*180/Math.PI:r.endsWith(`turn`)?i*360:i;n=n.rotate(a)}if(t.scale&&t.scale!==`none`){let[e,r]=t.scale.split(/\s+/).map(Number);n=n.scale(e,r??e)}return t.transform&&t.transform!==`none`&&(n=n.multiply(new DOMMatrixReadOnly(t.transform))),n.is2D?n:null}function kw(e,t){let n=e.getBoundingClientRect();if(!n.width||!n.height)return null;let r=new DOMMatrixReadOnly;for(let n=e;n;n=n.parentElement){let e=t?t.transform(n):Ow(n);if(!e)return null;r=e.multiply(r)}return{center:{x:n.left+n.width/2,y:n.top+n.height/2},halfX:{x:r.a*e.offsetWidth/2,y:r.b*e.offsetWidth/2},halfY:{x:r.c*e.offsetHeight/2,y:r.d*e.offsetHeight/2}}}var Aw=(e=``)=>e.split(/\s+/u).filter(Boolean),jw=class{entries=new Map;apply(e,t,n){let r=this.entries.get(e),{enteredClass:i,dwellingClass:a,successClass:o}=t;if(!r&&!i&&!a&&!o||r?.phase===n&&r.entered===i&&r.dwelling===a&&r.success===o)return;let s=r?.tokens??new Map,c=new Set([...Aw(i),...Aw(a),...Aw(o)]),l=new Set(Aw(n===`entered`?i:n===`dwelling`?a:n===`success`?o:``));for(let[t,n]of s)c.has(t)||(this.restoreToken(e,t,n),s.delete(t));for(let t of c){let n=e.classList.contains(t),r=s.get(t)??{original:n,applied:n},i=l.has(t);n!==i&&e.classList.toggle(t,i),r.applied=i,s.set(t,r)}c.size?this.entries.set(e,{phase:n,entered:i,dwelling:a,success:o,tokens:s}):this.entries.delete(e)}restoreToken(e,t,n){let r=e.classList.contains(t);r===n.applied&&r!==n.original&&e.classList.toggle(t,n.original)}restore(e){for(let[t,n]of this.entries.get(e)?.tokens??[])this.restoreToken(e,t,n);this.entries.delete(e)}reset(){for(let e of this.entries.keys())this.restore(e)}captureState(){return E(this.entries)}restoreState(e){this.reset();for(let[t,n]of E(e)){this.entries.set(t,n);for(let[e,r]of n.tokens)t.classList.contains(e)!==r.applied&&t.classList.toggle(e,r.applied)}}},Mw=`input[type="checkbox"],[role="checkbox"],[role="switch"]`;function Nw(e){return e instanceof HTMLInputElement?{checked:e.checked,indeterminate:e.indeterminate}:{aria:e.getAttribute(`aria-checked`)}}function Pw(e,t){`checked`in t&&e instanceof HTMLInputElement?(e.checked=t.checked,e.indeterminate=t.indeterminate):`aria`in t&&(t.aria===null?e.removeAttribute(`aria-checked`):e.setAttribute(`aria-checked`,t.aria))}var Fw=class{initial=new Map;sync(e){for(let[t,n]of this.initial)e.has(t)||(Pw(t,n),this.initial.delete(t));for(let t of e)this.initial.has(t)||this.initial.set(t,Nw(t))}reset(){for(let[e,t]of this.initial)Pw(e,t)}resetTarget(e){let t=this.initial.get(e);t&&Pw(e,t)}captureState(){return E(new Map([...this.initial].map(([e,t])=>[e,{initial:t,current:Nw(e)}])))}restoreState(e){this.reset(),this.initial.clear();for(let[t,{initial:n,current:r}]of E(e))this.initial.set(t,n),Pw(t,r)}dispose(){this.reset(),this.initial.clear()}},Iw={click:{action:`click`},check:{action:`check`},toggle:{action:`toggle`},pickup:{repeat:`scene`,consume:!0},parking:{when:`stop`,dwellSeconds:.45,maxSpeedMps:.25,containment:`center`}};function Lw(e){let t=e.spec.trigger,n=typeof t==`string`?{preset:t}:typeof t==`object`?t:{};return{when:`enter`,action:`event`,repeat:`visit`,vehicles:`player`,...Iw[n.preset??``],...n}}var Rw=e=>e.spec.stops.map(e=>typeof e==`string`?e:e.target),zw=()=>({phase:`idle`,inside:!1,departed:!1,qualified:!1,dwell:0,routeDwell:new Map}),Bw=e=>[{x:e.center.x-e.halfX.x-e.halfY.x,y:e.center.y-e.halfX.y-e.halfY.y},{x:e.center.x+e.halfX.x-e.halfY.x,y:e.center.y+e.halfX.y-e.halfY.y},{x:e.center.x+e.halfX.x+e.halfY.x,y:e.center.y+e.halfX.y+e.halfY.y},{x:e.center.x-e.halfX.x+e.halfY.x,y:e.center.y-e.halfX.y+e.halfY.y}];function Vw(e){let t=Math.cos(e.angle),n=Math.sin(e.angle);return{center:e.position,halfX:{x:t*e.lengthPx/2,y:n*e.lengthPx/2},halfY:{x:-n*e.widthPx/2,y:t*e.widthPx/2}}}function Hw(e,t){let n=Math.hypot(e.halfX.x,e.halfX.y),r=Math.hypot(e.halfY.x,e.halfY.y);return{center:e.center,halfX:{x:e.halfX.x*(1+t/n),y:e.halfX.y*(1+t/n)},halfY:{x:e.halfY.x*(1+t/r),y:e.halfY.y*(1+t/r)}}}var Uw=(e,t,n,r,i)=>(!e.requireExit||r)&&(e.when===`stop`?t&&i>=(e.dwellSeconds??.45):n),Ww=(e,t,n,r,i)=>n&&Math.abs(r)<=(t.maxSpeedMps??.25)?e+i:0,Gw=class{registry;measure;publicPosition;localPosition;stateClasses=new jw;controls=new Fw;visits=new Map;credited=new Map;consumed=new Map;visuals=new Map;routes=new Map;declarations=new Map;definitionRoutes=new Set;listeners=new Set;missing=new Set;frameGeometry=null;defaultGeometryFrame;dirty=!0;disposed=!1;unsubscribe;constructor(e,t,n=e=>({...e}),r=e=>({...e})){this.registry=e,this.measure=t,this.publicPosition=n,this.localPosition=r,this.unsubscribe=e.subscribe(()=>{this.dirty=!0});for(let[t,n]of Object.entries(e.definitions.routes??{}))this.definitionRoutes.add(t),this.route(t,n)}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}beginFrame(){this.disposed||(this.frameGeometry??=new Map,this.frameGeometry.clear(),this.measure||(this.defaultGeometryFrame=new Dw))}relocateVehicle(e){for(let t of this.visits.values()){let n=t.get(e);n&&t.set(e,{...n,inside:!1,qualified:!1,position:void 0,dwell:0,routeDwell:new Map})}}geometry(e){let t=()=>this.measure?this.measure(e):e instanceof HTMLElement?kw(e,this.defaultGeometryFrame):null;return this.frameGeometry?(this.frameGeometry.has(e)||this.frameGeometry.set(e,t()),this.frameGeometry.get(e)):t()}exportRoutes(){if(this.disposed)throw Error(`Playground is disposed`);return Object.fromEntries([...this.routes].filter(([e,t])=>!t.target&&!this.definitionRoutes.has(e)).map(([e,t])=>[e,structuredClone(t.spec)]))}emit(e,t,n){let{object:r,...i}=t,a=lw({...E(i),...r?{object:r}:{},...`position`in t?{position:this.publicPosition(t.position)}:{}});(n??this.registry.root).dispatchEvent(new CustomEvent(`joyride:${e}`,{bubbles:!0,detail:a}));for(let t of this.listeners)try{t(e,a)}catch(e){this.registry.report(e,n)}}route(e,t,n){if(this.disposed)throw Error(`Playground is disposed`);if(!e.trim())throw Error(`Route needs an ID`);if(this.routes.has(e))throw Error(`Route already exists: ${e}`);let r=Hs(t),i={id:e,spec:r,target:n,visited:new Map,completed:new Set};this.routes.set(e,i);let a=!1;return{id:e,get state(){return[...i.visited].map(([e,t])=>Object.freeze({vehicleId:e,completed:t.size,total:r.stops.length,complete:t.size===r.stops.length}))},reset:()=>{a||this.resetRoute(i)},dispose:()=>{a||this.routes.delete(e),a=!0}}}sync(e){if(!this.dirty)return;this.dirty=!1;let t=[...this.registry.root.querySelectorAll(`[data-jr-route]`)];this.registry.root instanceof Element&&this.registry.root.matches(`[data-jr-route]`)&&t.unshift(this.registry.root);for(let[e,n]of this.declarations)t.includes(e)||(this.routes.delete(n.id),this.declarations.delete(e),this.missing.delete(n.id));for(let n of t)try{let t=n.getAttribute(`data-jr-route`)??``,r=this.declarations.get(n),i=e.filter(e=>n.contains(e.target)&&e.target.closest(`[data-jr-route]`)===n);if(!i.length)continue;let a=i.map(e=>e.id),o=n.getAttribute(`data-jr-route-order`)??`ordered`,s=n.getAttribute(`data-jr-route-progress`)??`vehicle`,c=n.getAttribute(`data-jr-route-event`)??void 0,l=r&&this.routes.get(r.id),u=Hs({order:o,progress:s,event:c,stops:l&&l.visited.size?Rw(l):a}),d=JSON.stringify({id:t,spec:u});if(r?.signature===d)continue;if(this.routes.has(t)&&r?.id!==t)throw Error(`Route already exists: ${t}`);if(r){let e=this.routes.get(r.id);e&&this.resetRoute(e),this.routes.delete(r.id)}this.route(t,u,n),this.declarations.set(n,{id:t,signature:d})}catch(e){this.registry.report(e,n)}let n=new Set(e.map(e=>e.target)),r=new Set;for(let t of e){let e=Lw(t);if(e.action!==`event`)try{let n=this.actionTarget(t.target,e),i=this.controlTarget(n);i&&r.add(i)}catch(e){this.registry.report(e,t.target)}}this.controls.sync(r);for(let e of this.visits.keys())n.has(e)||(this.visits.delete(e),this.credited.delete(e),this.restore(e))}eligible(e,t,n,r){let i=e.spec.progress===`scene`?`scene`:n.id,a=e.visited.get(i)??new Set,o=Rw(e);return o.includes(t.id)?o.some(e=>!r.some(t=>t.id===e))?(this.missing.has(e.id)||(this.missing.add(e.id),this.registry.report(Error(`Route ${e.id} is waiting for a missing or disabled stop`),e.target)),!1):(this.missing.delete(e.id),!a.has(t.id)&&(e.spec.order===`any`||o[a.size]===t.id)):!1}step(e,t,n=!0){if(this.disposed)return;let r=Number.isFinite(t)?Math.max(0,t):0,i=this.registry.objects.filter(e=>e.spec.trigger&&e.spec.enabled!==!1);this.sync(i);let a=new Set(e.map(e=>e.id)),o=[];for(let t of i){let r=Lw(t),i=t.target;if(!(i instanceof HTMLElement))continue;let s=this.visits.get(i);s||this.visits.set(i,s=new Map);for(let e of s.keys())a.has(e)||s.delete(e);let c=this.geometry(i);for(let a of e){let e=s.get(a.id)??zw(),l=r.vehicles===`all`||(r.vehicles===`ai`?!a.player:a.player);if(!n||!c||!l||r.suspended){let n={...e,phase:!l||r.suspended||!c?`idle`:e.phase===`dwelling`?`entered`:e.phase,inside:c?e.inside:!1,dwell:0,routeDwell:new Map,position:this.publicPosition(a.position)};s.set(a.id,n),(n.phase!==e.phase||n.inside!==e.inside)&&this.emit(`trigger:change`,{object:t,vehicle:{id:a.id},position:a.position,speedMps:a.speedMps,state:{inside:n.inside,departed:n.departed,stopped:n.qualified,phase:n.phase}},i);continue}let u=Vw(a),d=Bw(c),f=r.containment===`center`?Ew(c,a.position):r.containment===`full`?Bw(u).every(e=>Ew(c,e)):!!oc(Bw(u),d),p=r.containment===`center`?0:r.containment===`full`?-Math.hypot(a.lengthPx,a.widthPx)/2:a.widthPx/2,m=e.position&&this.localPosition(e.position),h=m&&Math.hypot(a.position.x-m.x,a.position.y-m.y)>.001?sc(m,a.position,p,d):null,g=!f&&!e.inside&&h!==null,_=!e.inside&&(f||g),v=r.containment===`center`?!Ew(c,a.position,r.exitMarginPx??20):!oc(Bw(u),Bw(Hw(c,r.exitMarginPx??20)));e.resetBlocked?v&&s.set(a.id,{...zw(),departed:!0,position:this.publicPosition(a.position)}):o.push({object:t,config:r,target:i,vehicle:a,visits:s,previous:e,inside:f,crossed:g,entered:_,outside:v,departed:e.departed||v,arrival:e.inside?0:h??1})}}o.sort((e,t)=>e.arrival-t.arrival);for(let e of o){let{object:t,config:n,target:a,vehicle:o,visits:s,previous:c,inside:l,crossed:u,entered:d,outside:f,departed:p}=e,m=[...this.routes.values()].filter(e=>Rw(e).includes(t.id)),h=Ww(c.dwell,n,l,o.speedMps,r),g={object:t,vehicle:{id:o.id},position:{...o.position},speedMps:o.speedMps,state:{inside:l,departed:p,stopped:c.qualified,phase:d?`entered`:c.phase}};d&&this.emit(`trigger:enter`,g,a);let _=m.filter(e=>this.eligible(e,t,o,i)),v=new Map(c.routeDwell),y=_.filter(e=>{let i=e.spec.stops.find(e=>(typeof e==`string`?e:e.target)===t.id),a=typeof i==`string`?n:{...n,...i},s=Ww(c.routeDwell.get(e.id)??0,a,l,o.speedMps,r);return v.set(e.id,s),Uw(a,l,d,p,s)});for(let e of v.keys())_.some(t=>t.id===e)||v.delete(e);let b=this.credited.get(a)??new Set;this.credited.set(a,b);let x=n.repeat===`scene`?`scene`:o.id,S=n.repeat===`visit`?!c.qualified:!b.has(x),C=!f&&c.qualified,w=!1,ee=(m.length?y.length>0:Uw(n,l,d,p,h))&&S;try{let e=!0;if(ee&&(e=this.action(a,n),e&&(w=!0,b.add(x),C=!f,g.state.stopped=C,g.state.phase=`success`,this.emit(`trigger:qualify`,g,a),(m.length?y.some(e=>{let r=e.spec.stops.find(e=>(typeof e==`string`?e:e.target)===t.id);return(typeof r==`string`?n.when:r.when??n.when)===`stop`}):n.when===`stop`)&&this.emit(`trigger:stop`,g,a),n.event&&this.emit(n.event,g,a),n.consume&&!this.consumed.has(a)&&(this.consumed.set(a,{value:a.style.getPropertyValue(`visibility`),priority:a.style.getPropertyPriority(`visibility`)}),a.style.setProperty(`visibility`,`hidden`)))),e)for(let e of y)this.credit(e,t,o,g)}catch(e){this.registry.report(e,a)}let te=m.some(e=>e.visited.get(e.spec.progress===`scene`?`scene`:o.id)?.has(t.id)),ne=S&&l&&(m.length?_.some(e=>{let r=e.spec.stops.find(e=>(typeof e==`string`?e:e.target)===t.id),i=typeof r==`string`?n:{...n,...r},a=v.get(e.id)??0;return i.when===`stop`&&a>0&&a<(i.dwellSeconds??.45)&&(!i.requireExit||p)}):n.when===`stop`&&h>0&&h<(n.dwellSeconds??.45)&&(!n.requireExit||p)),re=w||te||n.repeat!==`visit`&&b.has(x)||c.phase===`success`&&!d?`success`:ne?`dwelling`:l?`entered`:`idle`;g.state.phase=re,(!l&&c.inside||u)&&this.emit(`trigger:leave`,g,a),s.set(o.id,{phase:re,inside:l,departed:p,qualified:C,dwell:h,routeDwell:v,position:this.publicPosition(o.position)}),g.state.stopped=C,(l!==c.inside||p!==c.departed||C!==c.qualified||re!==c.phase)&&this.emit(`trigger:change`,g,a)}let s=new Set;for(let e of this.routes.values())for(let t of e.visited.values())for(let e of t)s.add(e);for(let e of i){let t=e.target;if(!(t instanceof HTMLElement))continue;let n=Lw(e),r=[...this.visits.get(t)?.values()??[]],i=s.has(e.id)||n.repeat!==`visit`&&this.credited.get(t)?.size||r.some(e=>e.phase===`success`)?`success`:r.some(e=>e.phase===`dwelling`)?`dwelling`:r.some(e=>e.phase===`entered`)?`entered`:`idle`;this.visual(t,`data-jr-trigger-state`,i),this.visual(t,`data-jr-trigger-departed`,String(r.some(e=>e.departed))),this.stateClasses.apply(t,n,i)}}credit(e,t,n,r){let i=e.spec.progress===`scene`?`scene`:n.id,a=e.visited.get(i)??new Set;a.add(t.id),e.visited.set(i,a);let o=a.size===e.spec.stops.length,s={...r,route:{id:e.id,completed:a.size,total:e.spec.stops.length,complete:o}};this.emit(`route:progress`,s,e.target),o&&!e.completed.has(i)&&(e.completed.add(i),this.emit(`route:complete`,s,e.target),e.spec.event&&this.emit(e.spec.event,s,e.target))}actionTarget(e,t){let n=e;if(t.target){let e=[...this.registry.root.querySelectorAll(t.target)];if(this.registry.root instanceof Element&&this.registry.root.matches(t.target)&&e.unshift(this.registry.root),e.length!==1)throw Error(`Trigger action target must resolve to exactly one element`);n=e[0]}if(!(n instanceof HTMLElement))throw Error(`Trigger action target must support native activation`);return n}controlTarget(e){let t=e.matches(`input[type="checkbox"],[role="checkbox"],[role="switch"]`)?e:e.querySelector(Mw);return t instanceof HTMLElement?t:null}action(e,t){if(t.action===`event`)return!0;let n=this.actionTarget(e,t);if(n.matches(`:disabled,[aria-disabled="true"]`))return!1;if(t.action===`click`)return n.click(),!0;let r=this.controlTarget(n);if(!(r instanceof HTMLElement))throw Error(`Checkbox action needs a checkbox or switch target`);if(r.matches(`:disabled,[aria-disabled="true"]`))return!1;let i=r instanceof HTMLInputElement?r.checked:r.getAttribute(`aria-checked`)===`true`;return(t.action===`toggle`||i!==(t.action===`check`))&&r.click(),!0}visual(e,t,n){let r=this.visuals.get(e);r||this.visuals.set(e,r=new Map);let i=r.get(t);i?.applied!==n&&(i?i.applied=n:r.set(t,{original:e.getAttribute(t),applied:n}),e.getAttribute(t)!==n&&e.setAttribute(t,n))}captureState(){return E({visits:this.visits,credited:this.credited,routes:[...this.routes].map(([e,t])=>({id:e,visited:t.visited,completed:t.completed})),consumed:this.consumed,visuals:this.visuals,classes:this.stateClasses.captureState(),controls:this.controls.captureState()})}restoreState(e){let t=E(e);this.reset(),this.visits.clear();for(let[e,n]of t.visits)this.visits.set(e,n);for(let[e,n]of t.credited)this.credited.set(e,n);for(let e of t.routes){let t=this.routes.get(e.id);t&&(t.visited=e.visited,t.completed=e.completed)}for(let[e,n]of t.consumed)this.consumed.set(e,n),e.style.setProperty(`visibility`,`hidden`);for(let[e,n]of t.visuals){this.visuals.set(e,n);for(let[t,r]of n)e.setAttribute(t,r.applied)}this.stateClasses.restoreState(t.classes),this.controls.restoreState(t.controls)}restore(e){if(!(e instanceof HTMLElement))return;this.stateClasses.restore(e);let t=this.consumed.get(e);t&&e.style.visibility===`hidden`&&(t.value?e.style.setProperty(`visibility`,t.value,t.priority):e.style.removeProperty(`visibility`)),this.consumed.delete(e);for(let[t,n]of this.visuals.get(e)??[])e.getAttribute(t)===n.applied&&(n.original===null?e.removeAttribute(t):e.setAttribute(t,n.original));this.visuals.delete(e)}resetRoute(e){e.visited.clear(),e.completed.clear(),this.missing.delete(e.id);for(let t of this.registry.objects)Rw(e).includes(t.id)&&(this.visits.delete(t.target),this.credited.delete(t.target),this.restore(t.target))}resetObject(e){let t=this.visits.get(e);this.restore(e),this.credited.delete(e);let n=new Map;for(let[e,r]of t??[])r.inside&&n.set(e,{...zw(),inside:!0,resetBlocked:!0});n.size?this.visits.set(e,n):this.visits.delete(e);let r=this.registry.get(e);if(r?.spec.trigger){let t=this.controlTarget(this.actionTarget(e,Lw(r)));t&&this.controls.resetTarget(t)}if(r){for(let e of this.routes.values())if(Rw(e).includes(r.id)){for(let t of e.visited.values())t.delete(r.id);e.completed.clear(),this.missing.delete(e.id)}}this.frameGeometry?.clear()}reset(){let e=new Map;for(let[t,n]of this.visits){let r=new Map;for(let[e,t]of n)t.inside&&r.set(e,{...zw(),inside:!0,resetBlocked:!0});r.size&&e.set(t,r)}this.stateClasses.reset(),this.controls.reset(),this.frameGeometry?.clear(),this.defaultGeometryFrame&&=new Dw;for(let e of new Set([...this.visits.keys(),...this.consumed.keys(),...this.visuals.keys()]))this.restore(e);this.visits.clear();for(let[t,n]of e)this.visits.set(t,n);this.credited.clear(),this.missing.clear();for(let e of this.routes.values())e.visited.clear(),e.completed.clear()}dispose(){this.disposed||(this.reset(),this.controls.dispose(),this.visits.clear(),this.disposed=!0,this.unsubscribe(),this.routes.clear(),this.declarations.clear(),this.definitionRoutes.clear(),this.listeners.clear(),this.frameGeometry=null,this.defaultGeometryFrame=void 0)}};function Kw(e,t,n,r){let{sim:i,weaponReserves:a}=e,o=i.car,s=a.indicator(),c=t?.redlineRpm??8e3,l=t?.gear;return{speed:(i.paused?0:M(i.body.velocity))*2.2369362921,rpm:t?.rpm??0,gear:l==null||l===0?`N`:l,maxRpm:Math.ceil(c/1e3)*1e3,redlineRpm:c,hp:o.health,maxHp:o.maxHealth,ammo:a.enabled?s?.fraction??1:void 0,maxAmmo:1,ammoState:(s?.fraction??1)<=0?`empty`:s?.recharging||s?.depleted?`refilling`:`ready`,points:n,totalPoints:r,maxPoints:r??999999,effects:[]}}var qw=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function Jw(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>Jw(e,t[n]));if(!qw(e)||!qw(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Jw(e[n],t[n]))}var Yw=e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==`id`&&e!==`base`));function Xw(e,t){if(Jw(e,t))return;if(!qw(e)||!qw(t))return e;let n=Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Xw(n,t[e])]).filter(([,e])=>e!==void 0));return Object.keys(n).length?n:void 0}function Zw(e){let t=Object.values(rt),n=t.find(t=>t.id===e.base);if(!n)return e;let r=Ws(n,e),i=e;for(let e of t){let t=Object.fromEntries(Object.entries(r).filter(([t,n])=>t!==`id`&&t!==`base`&&!Jw(n,e[t]))),n={base:e.id,...t};Jw(Yw(Ws(e,n)),Yw(r))&&JSON.stringify(n).length<JSON.stringify(i).length&&(i=n)}return i}function Qw(e,t){let n=[],r=new Set,i=e;for(;t?.vehicles?.[i]&&!r.has(i);){r.add(i);let e=t.vehicles[i];n.unshift(e),i=e.base}return Ws({slots:pn},...n.map(e=>({slots:e.slots}))).slots}function $w(e){let t=Do({workMode:{sfw:e.workMode?.sfw===!0}}),n=Object.fromEntries(Object.entries(e.workMode??{}).filter(([e,n])=>e===`sfw`?n===!0:!Jw(n,t[e]))),r=mw(fw(dw,{workMode:n})),i=e.options?Xw(e.options,r):void 0,a=e.definitions?{...Object.fromEntries(Object.entries(e.definitions).filter(([,e])=>Object.keys(e??{}).length)),...e.definitions.vehicles?{vehicles:Object.fromEntries(Object.entries(e.definitions.vehicles).map(([e,t])=>[e,Zw(t)]))}:{}}:void 0,o=e.player?Qw(e.player.vehicle,a):void 0,s=e.player?{vehicle:e.player.vehicle,...e.player.appearance&&e.player.appearance!==`auto`?{appearance:e.player.appearance}:{},...e.player.slots?{slots:Object.fromEntries(Object.entries(e.player.slots).filter(([e,t])=>!Jw(t,o?.[e])))}:{}}:void 0;return s?.slots&&!Object.keys(s.slots).length&&delete s.slots,{...e.root?{root:e.root}:{},...a&&Object.values(a).some(e=>Object.keys(e??{}).length)?{definitions:a}:{},...s?{player:s}:{},...e.bindings?.length?{bindings:e.bindings}:{},...e.routes&&Object.keys(e.routes).length?{routes:e.routes}:{},...i?{options:i}:{},...Object.keys(n).length?{workMode:n}:{}}}var eT=`https://unpkg.com/@joy-ride/joy-ride@latest/npm/embed.js`,tT=`https://unpkg.com/@joy-ride/joy-ride@latest/npm/index.js`;function nT(e){let t=$w(e),n=t.definitions?.vehicles;if(!n)return t;let r=typeof document<`u`&&document.baseURI||eT;return{...t,definitions:{...t.definitions,vehicles:Object.fromEntries(Object.entries(n).map(([e,t])=>[e,{...t,...t.image?.src?{image:{...t.image,src:new URL(t.image.src,r).href}}:{}}]))}}}function rT(e){return`javascript:(()=>{const u=${JSON.stringify(eT)},o=${JSON.stringify(nT(e))},d=window.JoyRide;if(d){d.active?d.active.dispose():d.mount(o);return}const s=document.createElement('script');s.type='module';s.src=u;s.async=true;s.charset='utf-8';s.onload=()=>window.JoyRide.mount(o);document.head.append(s)})()`}function iT(e){return JSON.stringify(nT(e),null,2).replace(/</g,`\\u003c`).replace(/\n/g,`
1219
- `)}function aT(e){let t=e.workMode;return`<button type="button" id="joy-ride-toggle">${(t?.brandName??(t?.sfw?`Drive`:`Joy Ride`)).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}</button>
1220
- <script type="module">
1221
- const joyRideOptions = ${iT(e)};
1222
- document.querySelector('#joy-ride-toggle').addEventListener('click', async () => {
1223
- const { default: JoyRide } = await import(${JSON.stringify(tT)});
1224
- if (JoyRide.active) JoyRide.active.dispose();
1225
- else JoyRide.mount(joyRideOptions);
1226
- });
1227
- <\/script>`}function oT(e){return`const joyRideOptions = ${iT(e)};
1228
- const joyRideUrl = ${JSON.stringify(tT)};
1229
- const { default: JoyRide } = await import(
1230
- /* @vite-ignore */ /* webpackIgnore: true */ joyRideUrl
1231
- );
1232
- const ride = JoyRide.mount(joyRideOptions);
1233
- // Call ride.dispose() when the host view is removed.`}function sT(e){return`import JoyRide from '@joy-ride/joy-ride';
1234
-
1235
- const joyRideOptions = ${iT(e)};
1236
- const ride = JoyRide.mount(joyRideOptions);
1237
- // Call ride.dispose() when the host view is removed.`}export{Ho as $,mt as $t,XC as A,P as At,Yd as B,Ot as Bt,cw as C,Jt as Ct,YC as D,en as Dt,ow as E,Yt as Et,Kb as F,k as Ft,ac as G,Nt as Gt,Ol as H,Lt as Ht,yb as I,O as It,zs as J,Dt as Jt,Ws as K,Pt as Kt,ry as L,N as Lt,WC as M,Vt as Mt,HC as N,j as Nt,KC as O,qt as Ot,FC as P,M as Pt,Ko as Q,ot as Qt,$v as R,A as Rt,rw as S,Zt as St,aw as T,nn as Tt,ul as U,Tt as Ut,Jd as V,Ft as Vt,cc as W,It as Wt,ys as X,at as Xt,Rs as Y,E as Yt,qo as Z,T as Zt,hw as _,yn as _t,Kw as a,rt as an,So as at,tw as b,rn as bt,kw as c,so as ct,yw as d,In as dt,Ze as en,Io as et,bw as f,kn as ft,mw as g,xn as gt,fw as h,bn as ht,sT as i,tt as in,wo as it,JC as j,zt as jt,qC as k,Gt as kt,Tw as l,oo as lt,dw as m,Sn as mt,rT as n,it as nn,jo as nt,Gw as o,mo as ot,xw as p,On as pt,Bs as q,At as qt,aT as r,nt as rn,Do as rt,Dw as s,po as st,oT as t,Xe as tn,Oo as tt,gw as u,xa as ut,iw as v,ln as vt,ew as w,tn as wt,nw as x,$t as xt,sw as y,cn as yt,ey as z,D as zt};