@joy-ride/game 0.27.1 → 0.28.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.
Files changed (85) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.md +3 -3
  3. package/bookmarklet.d.ts +1 -1
  4. package/bookmarklet.js +1 -1
  5. package/embed-assets/subaru-wrx-top-DszueAbm.webp +0 -0
  6. package/embed-assets/toyota-gr-corolla-top-dNitaLHl.webp +0 -0
  7. package/embed-chunks/{CodeBlock-CJRe6lHv.js → CodeBlock-ZJVQKkJK.js} +1 -1
  8. package/embed-chunks/{Documentation-DULnk8tf.js → Documentation-C1avN9ar.js} +3 -3
  9. package/embed-chunks/EmbedPanel-G7q47IIF.js +1 -0
  10. package/embed-chunks/JoyRideView-iI9D7qYG.js +1 -0
  11. package/embed-chunks/X.es-BZV6GJho.js +1 -0
  12. package/embed-chunks/{configuration~index~embed-ynFxJP_I.js → configuration~index~embed-yIM-mirE.js} +1 -1
  13. package/embed-chunks/configuration~index~embed~bookmarklet-D5yd-nGZ.js +1 -0
  14. package/embed-chunks/configuration~index~embed~bookmarklet~vehicle-popover~EmbedPanel~Documentation~JoyRideView~~n76yhyet-CxkUNnei.js +1 -0
  15. package/embed-chunks/{configuration~index~embed~bookmarklet~vehicle-popover~EmbedPanel~JoyRideView~browser-sessio~iaaa3ndj-DLfKTakR.js → configuration~index~embed~bookmarklet~vehicle-popover~EmbedPanel~JoyRideView~browser-sessio~iaaa3ndj-DuwqBPZc.js} +1 -1
  16. package/embed-chunks/controls~index~embed-x6xN6BFw.js +1 -0
  17. package/embed-chunks/controls~index~embed~vehicle-popover~JoyRideView~browser-session-core~renderer-Cnf30Q_A.js +1 -0
  18. package/embed-chunks/react-vendor~index~embed-Blb-qyUP.js +9 -0
  19. package/embed-chunks/react-vendor~index~embed~vehicle-popover~EmbedPanel~Documentation~JoyRideView-DSe2UFlv.js +1 -0
  20. package/embed-chunks/{runtime~JoyRideView~browser-session-core-D5ZWMVDY.js → runtime~JoyRideView~browser-session-core-D0evk3rV.js} +1 -1
  21. package/embed-chunks/runtime~browser-session-core-Coi2m2K_.js +1 -0
  22. package/embed-chunks/runtime~index~embed-DRvLAw-Q.js +210 -0
  23. package/embed-chunks/runtime~index~embed~vehicle-popover~browser-session-core~renderer-7QR7zJ4G.js +1 -0
  24. package/embed-chunks/{runtime~vehicle-popover-DRMddEZO.js → runtime~vehicle-popover-B9yI0IDm.js} +1 -1
  25. package/embed-chunks/{runtime~vehicle-popover~browser-session-core-Duk0oqZL.js → runtime~vehicle-popover~browser-session-core-CG3br9PK.js} +1 -1
  26. package/embed-chunks/{runtime~vehicle-popover~browser-session-core~renderer-Cf4rBrLo.js → runtime~vehicle-popover~browser-session-core~renderer-D9Tkkuld.js} +1 -1
  27. package/embed-chunks/runtime~vehicle-popover~renderer-CucvcM5-.js +849 -0
  28. package/embed-chunks/{src-Dz21SH_d.js → src-DpO0cT8m.js} +2 -2
  29. package/embed-chunks/{vehicle-catalog~index~embed-Dpqr1rYZ.js → vehicle-catalog~index~embed-CP-EevYT.js} +1 -1
  30. package/embed-chunks/vehicle-popover-Dn9KYK8F.js +1 -0
  31. package/embed.js +1 -1
  32. package/{index-At4NsLPU.d.ts → index-CTJwxnBj.d.ts} +11 -10
  33. package/index.d.ts +2 -2
  34. package/index.js +1 -1
  35. package/npm-chunks/{Documentation-B_Eb81Ol.js → Documentation-C0eIjv6u.js} +3 -3
  36. package/npm-chunks/{EmbedPanel-Cu4-LaxN.js → EmbedPanel-f5UGGrmb.js} +1 -1
  37. package/npm-chunks/JoyRideView-D5KwW5-l.js +1 -0
  38. package/npm-chunks/VehicleHint-YUZ0kRNw.js +1 -0
  39. package/npm-chunks/{configuration~react-CPx5MlF4.js → configuration~react-DUPESsWt.js} +1 -1
  40. package/npm-chunks/configuration~react~vehicle-popover~EmbedPanel~Documentation~JoyRideView~browser-session-co~fvauaeow-CxkUNnei.js +1 -0
  41. package/npm-chunks/{configuration~react~vehicle-popover~EmbedPanel~JoyRideView~browser-session-core-rFMaxKZs.js → configuration~react~vehicle-popover~EmbedPanel~JoyRideView~browser-session-core-PAwcrwen.js} +1 -1
  42. package/npm-chunks/{configuration~react~vehicle-popover~EmbedPanel~JoyRideView~browser-session-core~renderer-Bo9KSudc.js → configuration~react~vehicle-popover~EmbedPanel~JoyRideView~browser-session-core~renderer-DjaRQi9I.js} +1 -1
  43. package/npm-chunks/configuration~react~vehicle-popover~JoyRideView~browser-session-core~renderer-BwD100vD.js +1 -0
  44. package/npm-chunks/controls~react~vehicle-popover~Documentation~JoyRideView~browser-session-core-QxIfuAPb.js +1 -0
  45. package/npm-chunks/{runtime~JoyRideView~browser-session-core-DkTKYWMV.js → runtime~JoyRideView~browser-session-core-CqexK4_9.js} +1 -1
  46. package/npm-chunks/runtime~browser-session-core-CnigdG4N.js +1 -0
  47. package/npm-chunks/{runtime~react-C9tzIsBm.js → runtime~react-BiRrgv8z.js} +1 -1
  48. package/npm-chunks/{runtime~react~browser-session-core-B9a1rLNB.js → runtime~react~browser-session-core-BwCcJzcZ.js} +1 -1
  49. package/npm-chunks/{runtime~react~vehicle-popover~browser-session-core-CdrNmP2l.js → runtime~react~vehicle-popover~browser-session-core-2aPQOOXj.js} +2 -2
  50. package/npm-chunks/runtime~react~vehicle-popover~browser-session-core~renderer-DKpExYhH.js +1 -0
  51. package/npm-chunks/{runtime~vehicle-popover-VyqXHkfB.js → runtime~vehicle-popover-QsSxwpN_.js} +1 -1
  52. package/npm-chunks/{runtime~vehicle-popover~browser-session-core-D0thHU3T.js → runtime~vehicle-popover~browser-session-core-CrZME-1Y.js} +1 -1
  53. package/npm-chunks/{runtime~vehicle-popover~browser-session-core~renderer-EswVyRVp.js → runtime~vehicle-popover~browser-session-core~renderer-L2_7uaz1.js} +1 -1
  54. package/npm-chunks/{runtime~vehicle-popover~renderer-4RpQDOHk.js → runtime~vehicle-popover~renderer-4k-iW9CG.js} +1 -1
  55. package/npm-chunks/{sync-shadow-theme-DieEPOi7.js → sync-shadow-theme-BfMjtxaN.js} +1 -1
  56. package/npm-chunks/{theme-CjrpDpKE.js → theme-DdVUqUf4.js} +1 -1
  57. package/npm-chunks/{vehicle-catalog~react~browser-session-core-D5_CJzRM.js → vehicle-catalog~react~browser-session-core-Ck9lXSBn.js} +1 -1
  58. package/npm-chunks/vehicle-catalog~react~vehicle-popover~browser-session-core-Dz1vucc8.js +1 -0
  59. package/npm-chunks/vehicle-popover-CVncA-Cd.js +1 -0
  60. package/package.json +1 -1
  61. package/{playground-BcoLBJrj.d.ts → playground-CSIrDKFk.d.ts} +11 -0
  62. package/react.d.ts +5 -3
  63. package/react.js +5 -5
  64. package/embed-assets/subaru-wrx-top-dLvMFYDs.webp +0 -0
  65. package/embed-assets/toyota-gr-corolla-top-B0NnJP3L.webp +0 -0
  66. package/embed-chunks/EmbedPanel-D6NV8mze.js +0 -1
  67. package/embed-chunks/JoyRideView-Ob58zdVp.js +0 -1
  68. package/embed-chunks/X.es-d7B7rOGv.js +0 -1
  69. package/embed-chunks/configuration~index~embed~bookmarklet-BGiS_NuJ.js +0 -1
  70. package/embed-chunks/configuration~index~embed~bookmarklet~vehicle-popover~EmbedPanel~Documentation~JoyRideView~~n76yhyet-mgPW9A8j.js +0 -1
  71. package/embed-chunks/controls~index~embed-CFqR-DAK.js +0 -1
  72. package/embed-chunks/react-vendor~index~embed-BNCMh3YF.js +0 -9
  73. package/embed-chunks/runtime~browser-session-core-BAKqCyId.js +0 -1
  74. package/embed-chunks/runtime~index~embed-OYVxs2-3.js +0 -210
  75. package/embed-chunks/runtime~index~embed~vehicle-popover~browser-session-core~renderer-ZRVlax1L.js +0 -1
  76. package/embed-chunks/runtime~vehicle-popover~renderer-JCHjG7Oa.js +0 -849
  77. package/embed-chunks/vehicle-popover-uy2DwcVy.js +0 -1
  78. package/npm-chunks/JoyRideView-DHvlq6T7.js +0 -1
  79. package/npm-chunks/configuration~react~vehicle-popover~EmbedPanel~Documentation~JoyRideView~browser-session-co~fvauaeow-mgPW9A8j.js +0 -1
  80. package/npm-chunks/configuration~react~vehicle-popover~JoyRideView~browser-session-core~renderer-CPZkP_Db.js +0 -1
  81. package/npm-chunks/controls~react~vehicle-popover~Documentation~JoyRideView~browser-session-core-CoAcght5.js +0 -1
  82. package/npm-chunks/runtime~browser-session-core-AEIWcEJB.js +0 -1
  83. package/npm-chunks/runtime~react~vehicle-popover~browser-session-core~renderer-Dmgs7E8f.js +0 -1
  84. package/npm-chunks/vehicle-catalog~react~vehicle-popover~browser-session-core-B042f61I.js +0 -1
  85. package/npm-chunks/vehicle-popover-DErhsXB9.js +0 -1
@@ -1,210 +0,0 @@
1
- import{c as e,n as t,t as n}from"./definitions~index~embed~bookmarklet~vehicle-popover~Documentation~JoyRideView~browser-sessi~fklztn3g-BG7sJuWo.js";import{b as r,r as i,t as a}from"./definitions~index~embed~bookmarklet-CfH2mYuH.js";import{t as o}from"./controls~index~embed-CFqR-DAK.js";import{r as s}from"./definitions~index~embed~vehicle-popover~browser-session-core~renderer-RDNEXk_b.js";import{a as c,i as l,n as u,o as d,r as f,t as p}from"./definitions~index~embed-CnmHo4Z4.js";import{a as m,o as h}from"./configuration~index~embed-ynFxJP_I.js";import{S as g,a as _,n as v,u as y}from"./runtime~index~embed~vehicle-popover~browser-session-core~renderer-ZRVlax1L.js";import{d as b,h as x,p as ee,s as te,u as ne}from"./configuration~index~embed~bookmarklet-BGiS_NuJ.js";import{u as re}from"./vehicle-catalog~index~embed-Dpqr1rYZ.js";var S=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 C(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`${t} must be an object`);return e}function ie(e,t,n){for(let r of Object.keys(e))if(!n.includes(r))throw TypeError(`Unknown ${t} field: ${r}`)}function w(e,t,n,r=()=>!0){if(e[t]!==void 0&&(typeof e[t]!=`number`||!Number.isFinite(e[t])||!r(e[t])))throw TypeError(`${n}.${t} must be a valid number`)}function ae(e){let t=C(e,`entry`);ie(t,`entry`,[`target`,`delayMs`,`stopAt`,`approach`,`handbrake`]);let n=t.target;if(typeof n==`string`){if(!n.trim())throw TypeError(`entry.target must be a nonempty CSS selector`)}else{let e=C(n,`entry.target`);if(ie(e,`entry.target`,[`xPx`,`yPx`]),w(e,`xPx`,`entry.target`),w(e,`yPx`,`entry.target`),e.xPx===void 0||e.yPx===void 0)throw TypeError(`entry.target requires xPx and yPx`)}if(w(t,`delayMs`,`entry`,e=>e>=0),t.stopAt!==void 0){let e=C(t.stopAt,`entry.stopAt`);ie(e,`entry.stopAt`,[`x`,`y`,`offsetXPx`,`offsetYPx`]);for(let t of[`x`,`y`,`offsetXPx`,`offsetYPx`])w(e,t,`entry.stopAt`)}if(t.approach!==void 0){let e=C(t.approach,`entry.approach`);ie(e,`entry.approach`,[`angleRad`,`distancePx`,`initialSpeedMps`,`fadeFraction`]),w(e,`angleRad`,`entry.approach`),w(e,`distancePx`,`entry.approach`,e=>e>0),w(e,`initialSpeedMps`,`entry.approach`,e=>e>0),w(e,`fadeFraction`,`entry.approach`,e=>e>=0&&e<=1)}if(t.handbrake!==void 0){let e=C(t.handbrake,`entry.handbrake`);ie(e,`entry.handbrake`,[`steer`]),w(e,`steer`,`entry.handbrake`,e=>Math.abs(e)<=1)}return e}function oe(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))oe(a,`${t}.${i}`,n,r);r.delete(e)}}function se(e){return e&&typeof e==`object`&&(Object.values(e).forEach(se),Object.freeze(e)),e}function ce(e){let t=[];if(oe(e,`configuration`,t),t.length)throw new S(t);for(let t of Object.keys(e))if(![`audioSet`,`persist`,`definitions`,`player`,`bindings`,`routes`,`objectives`,`game`,`dialog`,`entry`].includes(t))throw TypeError(`Unknown playground configuration field: ${t}`);if(e.audioSet!==void 0&&!/^[a-z0-9][a-z0-9_-]*$/.test(e.audioSet))throw TypeError(`Audio set must be a folder name`);if(e.persist!==void 0){if(!e.persist||typeof e.persist!=`object`||Array.isArray(e.persist))throw TypeError(`persist must be an object`);for(let[t,n]of Object.entries(e.persist)){if(t!==`vehicle`&&t!==`audio`)throw TypeError(`Unknown persist field: ${t}`);if(typeof n!=`boolean`)throw TypeError(`persist.${t} must be boolean`)}}e.entry!==void 0&&ae(e.entry);let n=p(e.definitions??{}),r=e.player===void 0?void 0:c(e.player),i=e.bindings?.map((e,t)=>{if(typeof e.target!=`string`||!e.target.trim())throw new S([{path:`bindings.${t}.target`,reason:`use a selector instead of an element reference`}]);return{target:e.target,spec:f(e.spec)}}),a=e.routes&&Object.fromEntries(Object.entries(e.routes).map(([e,t])=>[e,d(t)])),o=e.objectives&&Object.fromEntries(Object.entries(e.objectives).map(([e,t])=>[e,u(t)])),s=ee(x(b,{game:e.game,dialog:e.dialog}));return se(structuredClone({...e,definitions:n,player:r,bindings:i,routes:a,objectives:o,...s,format:`joy-ride-playground`,version:3}))}function le(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!==3)throw TypeError(`Unsupported playground configuration format or version`);for(let e of Object.keys(t))if(![`format`,`version`,`audioSet`,`persist`,`definitions`,`player`,`bindings`,`routes`,`objectives`,`game`,`dialog`,`entry`].includes(e))throw TypeError(`Unknown playground configuration field: ${e}`);let{format:n,version:r,...i}=t;return ce(i)}function ue(e,t){if(!(typeof HTMLElement<`u`&&e instanceof HTMLElement)){for(let e of[`trigger`,`crushable`,`combustible`,`pushable`])if(t[e])throw new i(`object.${e}`,`${e} requires an HTML element`);if(t.liquid&&!(typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement))throw new i(`object.liquid`,`liquid requires HTML or an SVG shape`);if(!(typeof SVGSVGElement<`u`&&e instanceof SVGSVGElement)&&(t.breakable||t.burnable))throw new i(`object`,`breakable and burnable artwork require HTML text/artwork or an SVG root`)}}var de=0;function fe(e){return e&&typeof e==`object`&&(Object.values(e).forEach(fe),Object.freeze(e)),e}var pe=class{root;definitions;scope=++de;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;observer;dirty=!0;disposed=!1;nextId=0;nextRegistration=0;version=0;pageStateChanged=()=>this.invalidate();constructor(e=document,t={}){this.root=e,this.definitions=p(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.register(h,{},!0),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=>!e.internal&&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,g(`registry invalidations`);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=>!t.internal&&typeof t.target==`string`&&e.matches(t.target)),i=t.filter(t=>typeof t.target!=`string`&&this.targets(t.target).includes(e)),o=this.resolve(a(...r.map(e=>e.spec),m(e),...i.map(e=>e.spec),n));return ue(e,o),o}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){return this.register(e,t,!1)}register(e,t,n){if(this.disposed)throw Error(`Playground is disposed`);let r=n?[]:this.targets(e),i={id:++this.nextRegistration,target:typeof e==`string`||e instanceof Element?e:r,spec:f(t),disposed:!1,internal:n};n||this.validateChange(r,[...this.registrations,i]),this.registrations.add(i),this.dirty=!1,this.invalidate();let o=()=>i.disposed||this.disposed?[]:(this.refresh(),this.targets(i.target).flatMap(e=>this.records.get(e)??[]));return{get objects(){return o()},update:e=>{if(i.disposed||this.disposed)throw Error(`Binding is disposed`);let t={...i,spec:f(a(i.spec,e))};this.validateChange(this.targets(i.target),[...this.registrations].map(e=>e===i?t:e)),i.spec=t.spec,this.dirty=!1,this.invalidate()},replace:e=>{if(i.disposed||this.disposed)throw Error(`Binding is disposed`);let t={...i,spec:f(e)};this.validateChange(this.targets(i.target),[...this.registrations].map(e=>e===i?t:e)),i.spec=t.spec,this.dirty=!1,this.invalidate()},refresh:()=>{if(i.disposed||this.disposed)throw Error(`Binding is disposed`);this.dirty=!1,this.invalidate(),this.refresh()},dispose:()=>{i.disposed||(i.disposed=!0,this.registrations.delete(i),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=f(a(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;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:fe(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].filter(e=>!e.internal),t=e.flatMap(e=>typeof e.target==`string`?[]:[{path:`bindings.${e.id}.target`,reason:`an exact element binding has no portable selector`}]);if(this.patches.size&&t.push({path:`objectOverrides`,reason:`runtime object overrides are tied to live element identities`}),t.length)throw new S(t);return e.map(e=>({target:e.target,spec:structuredClone(e.spec)}))}exportDefinitions(){if(this.disposed)throw Error(`Playground is disposed`);return p({...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(ne).some(t=>t.id===e))throw Error(`Vehicle recipe already exists: ${e}`);let{id:n,...r}=re(t),i={...r,base:ne.porsche911997.id};return p({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(ne).some(t=>t.id===e))return e;throw new S([{path:`player.vehicle`,reason:`vehicle ${e} has no authored recipe in this catalog`}])}resolve(e,t=new Set){let n=a(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,...o}=n;n=a(this.resolve(r,t),o)}let r=n.liquid;return r&&typeof r==`object`&&typeof r.kind==`string`&&(r.kind=this.resolveLiquid(r.kind)),l(n)}resolveLiquid(t,r=new Set){let i=this.liquids.get(t);if(i)return i;let a=this.importedLiquids.get(t)??this.definitions.liquids?.[t];if(!a)return e(t);if(r.has(t))throw Error(`Circular liquid definition: ${t}`);r.add(t);let o=this.resolveLiquid(a.base,r),s=`jr-${this.scope}-${this.liquids.size}-`,c=n(`${s}${t.slice(0,64-s.length)}`,{...a,base:o});return this.liquids.set(t,c.kind),c.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(ne).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:o,slots:s,...c}=r,l=re(a(this.resolveVehicle(i,t),c,{id:`custom-jr-${this.scope}-${e}`}));return this.vehicles.set(e,l),l}vehicleOptions(e){let t=this.importedVehicles.get(e)??this.definitions.vehicles?.[e];return t?a(this.vehicleOptions(t.base),{appearance:t.appearance,slots:t.slots}):{appearance:`auto`,slots:r}}captureState(){return s({patches:this.patches,registrations:new Map([...this.registrations].filter(e=>!e.internal).map(e=>[e.id,e.spec]))})}restoreState(e){let t=s(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())t(e);this.liquids.clear(),this.vehicles.clear(),this.importedVehicles.clear(),this.importedLiquids.clear()}}},me=(function(){let e=typeof document<`u`&&document.createElement(`link`).relList;return e&&e.supports&&e.supports(`modulepreload`)?`modulepreload`:`preload`})(),he=function(e,t){return new URL(e,t).href},ge={},_e=function(e){return e.pathname.endsWith(`.css`)},ve=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},ye=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=he(t,n);let r=s(t),i=_e(r);return ve(ge,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:me,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},be=()=>ye(()=>import(`./runtime~vehicle-popover~renderer-JCHjG7Oa.js`).then(e=>e.n),[],import.meta.url),xe=class{releases=[];disposed=!1;own(e){if(this.disposed)try{e()}catch(e){console.error(`JoyRide cleanup failed`,e)}else this.releases.push(e)}disown(e){let t=this.releases.lastIndexOf(e);t>=0&&this.releases.splice(t,1)}listen(e,t,n,r){e.addEventListener(t,n,r),this.own(()=>e.removeEventListener(t,n,r))}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.releases.splice(0).reverse())try{e()}catch(e){console.error(`JoyRide cleanup failed`,e)}}}},Se=new WeakMap;function Ce(e){let t=Se.get(e);return!t&&typeof e.createConstantSource==`function`&&(t=e.createConstantSource(),t.offset.value=0,t.start(),Se.set(e,t)),t}function we(e,t){let n=Ce(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 Te(e){let t=Se.get(e);t&&(t.stop(),t.disconnect(),Se.delete(e))}function T(e){if(!e.detune||!e.context)return e;let t=Ce(e.context);return t&&(t.connect(e.detune),e.addEventListener(`ended`,()=>{try{t.disconnect(e.detune)}catch{}},{once:!0})),e}var Ee={"../assets/audio/cleared/boost.opus":new URL(`../embed-assets/boost-2QB6phrp.opus`,import.meta.url).href,"../assets/audio/cleared/collision.opus":new URL(`../embed-assets/collision-r7KCgXfr.opus`,import.meta.url).href,"../assets/audio/cleared/crush.opus":new URL(`../embed-assets/crush-CN-lxC7x.opus`,import.meta.url).href,"../assets/audio/cleared/explosion.opus":new URL(`../embed-assets/explosion-DyvbNXFI.opus`,import.meta.url).href,"../assets/audio/cleared/fire.opus":new URL(`../embed-assets/fire-BYgTEP5X.opus`,import.meta.url).href,"../assets/audio/cleared/gunfire.opus":new URL(`../embed-assets/gunfire-DUWyQGGm.opus`,import.meta.url).href,"../assets/audio/cleared/ricochet.opus":new URL(`../embed-assets/ricochet-BTW-Iqeu.opus`,import.meta.url).href,"../assets/audio/cleared/tires.opus":new URL(`../embed-assets/tires-B_97_Y5P.opus`,import.meta.url).href},De=[`collision`,`crush`,`fire`,`tires`,`gunfire`,`ricochet`,`explosion`,`boost`];[...new Set(Object.keys(Ee).map(e=>e.split(`/`).at(-2)).filter(e=>e!=="default"))];var Oe=(e,t)=>`../assets/audio/${e}/${t}.opus`,ke=Object.fromEntries(De.map(e=>[e,Ee[Oe(`cleared`,e)]]));for(let e of De)if(!ke[e])throw Error(`Missing default audio file: ${e}`);var Ae=Object.fromEntries(De.map(e=>[e,{kind:`recording`,url:ke[e]}]));function je(e,t=`default`){if(!/^[a-z0-9][a-z0-9_-]*$/.test(t))throw TypeError(`Invalid audio set name: ${t}`);return Ee[Oe(t,e)]??ke[e]}async function Me(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 Ne=class{context;audioSet;buffers=new Map;abort=new AbortController;disposed=!1;constructor(e,t=`default`){if(this.context=e,this.audioSet=t,!/^[a-z0-9][a-z0-9_-]*$/.test(t))throw TypeError(`Invalid audio set name: ${t}`)}async initialize(){return Promise.allSettled(De.map(e=>this.load(e)))}load(e){return this.prepare(e,()=>this.decode(je(e,this.audioSet)))}loadUri(e){return this.prepare(e,()=>this.decode(e))}async decode(e){let t=await Me(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()}},Pe=new WeakMap;function Fe(e,t){let n=Pe.get(e);if(!n)n=new Ne(e,t),Pe.set(e,n);else if(t!==void 0&&n.audioSet!==t)throw Error(`Audio context already uses set ${n.audioSet}; requested ${t}`);return n}function Ie(e){Pe.get(e)?.dispose(),Pe.delete(e)}function Le(e,t){let n=Fe(e);return Object.hasOwn(Ae,t)?n.load(t):n.loadUri(t)}var E={engine:-9.9,engineShutdown:-8.4,tire:-12,horn:-26,boost:-16,flamethrower:-20,rocketFlight:-3,collision:-17,crush:-18,machineGun:-22,ricochet:-21,rocketLaunch:-19,rocketExplosion:-18,combustibleExplosion:-18,burningFire:-20,ghostMode:-22},D=e=>10**(e/20),Re={pitchShiftSemitones:-3,pitchDynamics:1.8},ze=(e,t=0,n=1)=>Math.max(t,Math.min(n,e)),Be=e=>{let t=ze(e);return t*t*(3-2*t)};function Ve({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 He=class{context;ready;output;highpass;voices=new Set;config;clip=null;disposed=!1;constructor(e,t=e.destination,n={}){this.context=e,this.config={...Re,...n},this.output=e.createGain(),this.output.gain.value=D(E.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 Fe(this.context).load(`tires`);this.disposed||(this.clip=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=T(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=ze(e,0,.1),a=ze((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=ze(n?.heat??0),p=Math.sqrt(ze((n?.loadN??0)/2943,0,2.5)),m=Math.sqrt(ze(n?.grip??1,0,1.3)),h=n?.skidding?.38*Be((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 O(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):1}function Ue(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 O(1-Math.hypot(r,i))}function We(e,t,n){return Ue({x:e.x-t.x,y:e.y-t.y},n,!1)}function Ge(e,t,...n){try{return t?.(...n)}catch(t){try{e(t)}catch(e){console.error(`Joy Ride host callback error reporting failed.`,e)}return}}var Ke=343,k={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 turbo 1.6`,cylinders:3,firingOrder:[1,2,3],banks:[[1,2,3]],idleRpm:850,redlineRpm:7e3,peakTorque:400,peakTorqueRpm:3250,gears:6,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:8e3,peakTorque:314,peakTorqueRpm:5e3,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:7500,peakTorque:205,peakTorqueRpm:4e3,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},i6tt:{label:`Inline-6 twin-turbo 3.0`,cylinders:6,firingOrder:[1,5,3,6,2,4],banks:[[1,2,3,4,5,6]],idleRpm:750,redlineRpm:6800,peakTorque:431,peakTorqueRpm:4e3,gears:6,engineInertia:.29,gasTempFactor:1.22,pulse:{attack:29,decay:5,hardness:.59,jitter:.7},exhaust:{bank:1.48,collector:1.32,reflection:.52,damping:.5,muffler:[.34,.22,.15]},intake:{helmholtz:100,q:5.9,level:.32},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:1458,peakTorqueRpm:1800,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:588,peakTorqueRpm:3600,gears:6,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:7500,peakTorque:770,peakTorqueRpm:5500,gears:7,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 5.5`,cylinders:8,firingOrder:[1,5,3,7,4,8,2,6],banks:[[1,2,3,4],[5,6,7,8]],idleRpm:900,redlineRpm:8600,peakTorque:623,peakTorqueRpm:6300,gears:8,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:718,peakTorqueRpm:7e3,gears:7,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 qe(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 Je(e,t){let n=qe(e);return e.banks[t].map(e=>n.get(e)).sort((e,t)=>e-t)}function Ye(e,t=1){return Ke*t/(4*Math.max(.05,e))}function Xe(e,t=1){return 2*Math.max(.05,e)/(Ke*t)}var Ze={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]}},Qe={stiffness:5200,dampingRatio:.22,damping:13,backlash:.035,clutchTorqueCapacity:900,clutchStiffness:3.2},A=(e,t,n)=>e<t?t:e>n?n:e,$e=(e,t)=>typeof e==`number`&&isFinite(e)?e:t,j=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}),et=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}]),tt=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 nt(e,t){let n=e;for(let e of t.split(`.`)){if(n==null)return;n=n[e]}return n}function rt(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 it(e){return et.find(t=>t.path===e)}function M(e){if(Array.isArray(e))return e.map(M);if(e&&typeof e==`object`){let t={};for(let n of Object.keys(e))t[n]=M(e[n]);return t}return e}function at(e){let t=k[e];return t?N({version:3,id:e,label:t.label,engine:M(t),...M(j)}):null}function ot(){let e={};for(let t of Object.keys(k))e[t]=at(t);return e}function N(e){let t=e&&typeof e==`object`?e:{},n=k[t.id]||k.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=A(Math.round($e(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?M(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?M(c):n.cylinders===a?M(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]=A($e(n,0),-360,360))}Object.keys(e).length&&(r.engine.pinOffsets=e)}let d=$e(i.exhaust&&i.exhaust.bankB,NaN);r.engine.exhaust={},isFinite(d)&&r.engine.banks.length>1&&(r.engine.exhaust.bankB=A(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,...j};for(let e of et){let t=nt(p,e.path);isFinite(Number(t))||(t=nt(m,e.path)),isFinite(Number(t))||(t=e.min);let n=A(Number(t),e.min,e.max);rt(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=>A($e(h&&h[e],.2),0,.8)),r.eq=[0,1,2,3,4].map(e=>A($e(r.eq[e],0),-18,18)),r}function st(e){return JSON.stringify(N(e),null,2).replace(/\[\s+((?:-?[\d.]+,?\s+)+)\]/g,(e,t)=>`[`+t.trim().replace(/,\s+/g,`, `)+`]`)}function ct(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:N(t),error:null}}var lt=8192,ut=1024;function dt(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 ft(e){let t=e>>>0||1;return()=>(t^=t<<13,t>>>=0,t^=t>>17,t^=t<<5,t>>>=0,t/4294967296)}function pt(e,t,n){return e<0||e>1?0:(1-Math.exp(-t*e))*Math.exp(-n*e)}function mt(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(lt),l=ft(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<lt;e++){let n=e/lt-a;n<0&&(n+=1),c[e]+=t*pt(n,o,s*i)}}return c}function ht(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 gt=24;function _t(e,t=ut,n=gt){let r=e.length,i=new Float64Array(r),a=new Float64Array(r);i.set(e),dt(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 vt(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 yt(e,t,n){let r={disableNormalization:!0},i=(n,i,a)=>{let o=vt(_t(ht(mt(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 bt(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 xt(e,t){let n=e.pulse,r=(n.jitter||0)/100,i=ft(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=lt,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*pt(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 St=1.02,P=10,Ct=2e4,wt=.92,F=.02,Tt=.09,I=(e,t,n)=>e<t?t:e>n?n:e;function L(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function R(e,t,n,r=F){let i=L(t,0),a=L(n,0);e.setTargetAtTime(i,a<0?0:a,r>0?r:F)}function Et(e,t,n,r){let i=2*Math.PI*I(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*I(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*_),ee=Math.atan2(y,v)-Math.atan2(x,b);return Number.isFinite(ee)?ee:0}function Dt(e,t,n,r){let i=2*Math.PI*e;if(!(i>0))return 0;let a=Et(e,t,n,r),o=(Math.PI+a)/i;return o>0&&Number.isFinite(o)?o:1/(2*e)}var Ot=new Map;function kt(e,t,n=4096,r=At()){let i=e+`:`+t+`:`+n+`:`+r,a=Ot.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 Ot.set(i,c),c}var At=()=>6,jt=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1;let r=t&&t.exhaust||{};this.length=I(L(n.length,L(r.bank,1)),.05,12),this.gasTemp=I(L(n.gasTempFactor,L(t&&t.gasTempFactor,1)),.5,2.5),this.reflection=I(L(n.reflection,L(r.reflection,.5)),0,wt),this.damping=I(L(n.damping,L(r.damping,.4)),.05,2),this.thermalSpan=I(L(n.thermalSpan,.05),0,.25),this.thermalBias=.35,this.sampleRate=L(e&&e.sampleRate,48e3),this.minLoopDelay=128/this.sampleRate,this.nominalDelay=Xe(this.length,this.gasTemp),this.frequency=Ye(this.length,this.gasTemp),this.lpBase=I(this.frequency*(1.8/this.damping),150,12e3),this.loopQ=.5;let i=.49*this.sampleRate;if(this.fMax=Math.min(Ct,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*St?`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=I(L(n.dry,.3),0,4),this.inGain.connect(this.dryGain),this.dryGain.connect(this.out),this.wetGain=e.createGain(),this.wetGain.gain.value=I(L(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=I(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=I(Math.PI/(2*Math.max(.02,1-t)),.7,24);let r=I(Math.round(L(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 I(L(e,P),P,this.fMax)}_tunedDelay(e,t){return Dt(I(L(e,P),P,this.fMax),I(L(t,150),20,.49*this.sampleRate),this.loopQ,this.sampleRate)}_fbMag(e){return I(this.reflection*(.92+.08*I(e,0,1)),0,wt)}_heatScale(e){let t=I(L(e&&e.load,0),0,1),n=I(L(e&&e.rpmNorm,0),0,1),r=I(.6*t+.4*n,0,1);return 1+this.thermalSpan*(r-this.thermalBias)}update(e){if(this.disposed)return;let t=L(e&&e.now,L(this.ctx.currentTime,0)),n=I(L(e&&e.load,0),0,1),r=this._heatScale(e);if(this.mode===`delay`){let e=I(this.nominalDelay/r,this.minLoopDelay,this.maxDelayTime);R(this.delay.delayTime,e,t,Tt),R(this.loopLP.frequency,this._f(this.lpBase*r*(1+.35*n)),t,F),R(this.fb.gain,-this._fbMag(n),t,F)}else for(let e=0;e<this.modes.length;e++){let n=this.modes[e];R(n.bp.frequency,this._f(this.frequency*n.order*r),t,Tt)}}_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()}},Mt=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=>I(L(e,.2),.02,3)),this.gasTemp=I(L(r.gasTempFactor,L(n&&n.gasTempFactor,1)),.5,2.5),this.sampleRate=L(t&&t.sampleRate,48e3),this.fMax=Math.min(Ct,.49*this.sampleRate),this.thermalSpan=I(L(r.thermalSpan,.025),0,.2),this.thermalBias=.35;let o=this.chambers.map(e=>Xe(e,this.gasTemp));this.spread=I(L(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=I(L(i.reflection,.5),0,1);this.branchGain=I(L(r.branchGain,.55+.3*u),.05,.9);let d=I(L(r.packingOctaves,7),1,40);this.packingBase=I(Ye(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=I(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=I(this.packingBase,P,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=L(e&&e.now,L(this.ctx.currentTime,0)),n=I(L(e&&e.load,0),0,1),r=I(L(e&&e.rpmNorm,0),0,1),i=I(.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];R(i.delay.delayTime,I(i.T/a,0,i.maxT),t,Tt);let o=I(L(e&&e.valve,0),0,1);R(i.branch.gain,I(this.branchGain*i.taper*(1-.12*n)*(1-.65*o),0,.95),t,F)}let o=I(L(e&&e.valve,0),0,1);R(this.packing.frequency,I(this.packingBase*(1+.3*n)*(1+1.1*o)*a,P,this.fMax),t,F)}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()}},Nt=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1;let r=t&&t.intake||{};this.f0=I(L(n.helmholtz,L(r.helmholtz,110)),P,2e3),this.q0=I(L(n.q,L(r.q,6)),.3,30),this.level=I(L(n.level,L(r.level,.33)),0,4),this.sampleRate=L(e&&e.sampleRate,48e3),this.fMax=Math.min(Ct,.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=T(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 I(L(e,P),P,this.fMax)}_makeNoise(e,t){let n=Math.max(1,Math.floor(L(e&&e.sampleRate,48e3)*t)),r=e.createBuffer(1,n,L(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]=I((o+s+t*.1848)*.32,-1,1)}return r}start(e){if(!(this.started||this.disposed)){this.started=!0;try{this.noiseSrc.start(L(e,0))}catch{}}}update(e){if(this.disposed)return;this.started||this.start(L(e&&e.now,0));let t=L(e&&e.now,L(this.ctx.currentTime,0)),n=I(L(e&&e.load,0),0,1),r=I(L(e&&e.throttle,0),0,1),i=I(L(e&&e.rpmNorm,0),0,1),a=I(L(e&&e.overrun,0),0,1),o=Math.max(n,.001)**.7,s=I(r*(.25+.75*i),0,1),c=I(a*(.15+.85*i),0,1);R(this.helm.Q,I(this.q0*(.55+.45*r),.3,30),t,.05),R(this.helm.frequency,this._f(this.f0),t,.1),R(this.helmGain.gain,I((.12+.88*o)*(.35+.65*i),0,4),t,F),R(this.directGain.gain,I(.3*(.2+.8*o),0,4),t,F),R(this.noiseBP.frequency,this._f(this.f0*(3+9*s)*(1+.6*c)),t,F),R(this.noiseBP.Q,I(.9+.7*s,.3,6),t,.05),R(this.noiseGain.gain,I(.42*s**1.2+.16*c,0,4),t,F),R(this.noiseToHelm.gain,I(.2*s+.05*c,0,2),t,F),R(this.out.gain,I(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()}},Pt=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1,this.maxDrive=I(L(n.maxDrive,4.5),1,40),this.idleDrive=I(L(n.idleDrive,1),.1,10);let r=I(L(n.kp,3.2),.5,12),i=I(L(n.kn,2),.5,12);this.sampleRate=L(e&&e.sampleRate,48e3),this.fMax=Math.min(Ct,.49*this.sampleRate),this.drive=e.createGain(),this.drive.gain.value=this.idleDrive,this.shaper=e.createWaveShaper(),this.shaper.curve=kt(r,i,4096),this.shaper.oversample=`4x`,this.span=e.createGain(),this.span.gain.value=1/At(),this.dcBlock=e.createBiquadFilter(),this.dcBlock.type=`highpass`,this.dcBlock.frequency.value=I(22,P,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 I(1/Math.max(.05,e)**.7,.05,4)}update(e){if(this.disposed)return;let t=L(e&&e.now,L(this.ctx.currentTime,0)),n=I(L(e&&e.load,0),0,1),r=I(L(e&&e.rpmNorm,0),0,1),i=I(L(e&&e.boost,0),0,1),a=I(L(e&&e.overrun,0),0,1),o=I(n**1.5*(.55+.45*r)+.55*i*n,0,1.4),s=.25*a*(.3+.7*r)+.22*I(L(e&&e.valve,0),0,1)*(.4+.6*n),c=I(this.idleDrive+(this.maxDrive-this.idleDrive)*I(o+s,0,1),.1,this.maxDrive);R(this.drive.gain,c,t,F),R(this.makeup.gain,this._makeupFor(c),t,F)}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()}}},Ft=class{constructor(e,t,n={}){this.ctx=e,this.profile=t,this.disposed=!1,this.sampleRate=L(e&&e.sampleRate,48e3),this.fMax=Math.min(Ct,.49*this.sampleRate),this.boomHz=I(L(n.boomHz,62),20,300),this.panelHz=I(L(n.panelHz,155),40,800),this.extLP=I(L(n.exteriorLP,17e3),1e3,this.fMax),this.intLP=I(L(n.interiorLP,1050),120,8e3),this.intBoomDb=I(L(n.boomDb,6.5),0,18),this.intPanelDb=I(L(n.panelDb,3.5),0,18),this.intShelfDb=I(L(n.shelfDb,-11),-40,0),this.shelfHz=I(L(n.shelfHz,3200),500,this.fMax),this.position=I(L(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=I(this.boomHz,P,this.fMax),this.boom.Q.value=I(L(n.boomQ,3.2),.3,20),this.boom.gain.value=0,this.panel=e.createBiquadFilter(),this.panel.type=`peaking`,this.panel.frequency.value=I(this.panelHz,P,this.fMax),this.panel.Q.value=I(L(n.panelQ,2.4),.3,20),this.panel.gain.value=0,this.lp=e.createBiquadFilter(),this.lp.type=`lowpass`,this.lp.frequency.value=I(this.extLP,P,this.fMax),this.lp.Q.value=.6,this.shelf=e.createBiquadFilter(),this.shelf.type=`highshelf`,this.shelf.frequency.value=I(this.shelfHz,P,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(L(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=I(L(e,0),0,1),this.disposed||this._write(L(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;R(this.lp.frequency,I(r,P,this.fMax),e,t),R(this.boom.gain,this.intBoomDb*n,e,t),R(this.panel.gain,this.intPanelDb*n,e,t),R(this.shelf.gain,this.intShelfDb*n,e,t),R(this.trim.gain,I(10**(-4.5*n/20),.05,1),e,t)}update(e){if(this.disposed)return;let t=L(e&&e.now,L(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()}}},It=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=L(e&&e.sampleRate,48e3),this.bankLengths=i.map((e,t)=>t===1&&Number.isFinite(r.bankB)?r.bankB:L(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 jt(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=I(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 jt(e,t,Object.assign({length:L(r.collector,1),reflection:I(L(r.reflection,.5)*.7,0,wt),damping:I(L(r.damping,.4)*1.5,.05,2)},n.collectorOpts)),this.collectorNode.connect(this.collector.input),this.muffler=new Mt(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 Pt(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=L(e&&e.now,L(this.ctx.currentTime,0)),n=I(L(e&&e.load,0),0,1),r=I(L(e&&e.rpmNorm,0),0,1),i=I(.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&&R(r.d.delayTime,I(r.t/a,0,r.maxT),t,Tt)}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()}}},Lt=3800,Rt=-5.5,zt=1150,z=.02,Bt=10,Vt=2e4,Ht=.004;function B(e,t,n){return e<t?t:e>n?n:e}function V(e,t){return typeof e==`number`&&isFinite(e)?e:t}function Ut(e,t){return B(V(e,t),Bt,Vt)}function H(e,t,n,r){e.setTargetAtTime(V(t,0),V(n,0),r>0?r:z)}function U(e,t,n,r,i){e.setTargetAtTime(Ut(t,i===void 0?Bt:i),V(n,0),r>0?r:z)}function Wt(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 Gt=new WeakMap;function Kt(e,t){let n=Gt.get(e);if(n||(n={},Gt.set(e,n)),n[t])return n[t];let r=V(e.sampleRate,48e3),i=Math.max(1024,Math.floor(r*2)),a=e.createBuffer(1,i,r),o=a.getChannelData(0),s=Wt(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 W(e,t,n){let r=T(e.createBufferSource());r.buffer=Kt(e,t),r.loop=!0;try{r.start(0,V(n,0)),r.__started=!0}catch{}return r}function qt(e,t,n,r){let i=e.createGain();return i.gain.value=n,t.connect(i),i.connect(r),i}function Jt(e,t){let n=V(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 Yt(e,t){for(let n=0;n<e.length;n++){try{e[n].stop(V(t,0))}catch{}try{e[n].disconnect()}catch{}}}function Xt(e){for(let t=0;t<e.length;t++)try{e[t].disconnect()}catch{}}var Zt=class{constructor(e,t,n){this.ctx=e,this.profile=t;let r=n||{};this.level=V(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=W(e,`white`,.71),o=W(e,`pink`,1.31);this._srcs.push(a,o),this.meshOsc1=T(e.createOscillator()),this.meshOsc1.type=`sine`,this.meshOsc1.frequency.value=500,this.meshOsc2=T(e.createOscillator()),this.meshOsc2.type=`sine`,this.meshOsc2.frequency.value=1e3,this.runoutOsc=T(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(qt(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=T(e.createOscillator()),this.torsOsc.type=`sawtooth`,this.torsOsc.frequency.value=60,this._srcs.push(this.torsOsc),i(qt(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=B(V(n,V(r&&r.finalDrive,3.9)),1,12),this._scale=0}setProfile(e){this.profile=e,this.cyl=B(V(e&&e.cylinders,4),1,16),this.idleRpm=V(e&&e.idleRpm,800)}_shaftRpm(e){let t=Math.abs(V(e.wheelRpm,0));if(this.driveshaftScale!==`auto`)return t*this.driveshaftScale;if(this._scale===0){let n=V(e.gearRatio,0),r=V(e.rpm,0);if(n>.05&&t>50&&r>200&&V(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(V(e,0))-1;return n<0||n>=this.teeth.length?0:Math.abs(V(t,0))/60*V(this.teeth[n],0)}update(e){let t=V(e.now,0),n=Math.round(V(e.gear,0)),r=B(V(e.load,0),0,1),i=Math.max(0,V(e.rpm,0)),a=V(e.f0,i/120),o=B(V(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=B((l-30)/40,0,1)*e}let d=V(e.torqueSign,1)>=0?.22+.85*r:.34,f=+(n>0&&Math.abs(V(e.gearRatio,0))>.001),p=s===`open`||s===`sync`||s===`cut`?.05:1,m=.45+.55*B(c/2500,0,1),h=.065*(this.gearCut===`straight`?1:.42)*f*o*p*d*u*m;U(this.meshOsc1.frequency,l,t,z,500),U(this.meshOsc2.frequency,l*2,t,z,1e3);let g=this.gearCut===`straight`?.55:.2;H(this.meshH2.gain,g/(1+(l*2/2600)**2.4),t,z),U(this.meshBP.frequency,l,t,z,500),U(this.runoutOsc.frequency,c/60*2,t,z,Bt),H(this.meshGain.gain,h,t,z);let _=B(Math.abs(V(e.dRpm,0))/4e3,0,1),v=B(Math.abs(V(e.clutchSlip,0))/800,0,1),y=o*B(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=B(.5*y+.75*_+.7*v,0,1)*b;U(this.torsOsc.frequency,this.cyl*a,t,z,Bt),H(this.ratGain.gain,.09*x*B(i/Math.max(1,this.idleRpm*.6),0,1),t,z)}start(e){Jt(this._srcs,e)}dispose(){let e=V(this.ctx.currentTime,0);Yt(this._srcs,e),Xt(this._nodes),this._srcs.length=0}},Qt=e=>e<.1,$t=class e{static supports(e){return!!(e&&e.turbo)}constructor(t,n,r){this.ctx=t;let i=r||{};this.level=V(i.level,1),this.maxTurboRpm=V(i.maxTurboRpm,15e4),this.flutterMode=i.flutter!==!1,this.surgeLevel=B(V(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=Wt(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=Lt,this.airLP.Q.value=-3.01,this.airShelf=a(t.createBiquadFilter()),this.airShelf.type=`highshelf`,this.airShelf.frequency.value=2600,this.airShelf.gain.value=Rt,this.bus.connect(this.airLP),this.airLP.connect(this.airShelf),this.airShelf.connect(this.out);let o=W(t,`white`,1.07);this._srcs.push(o),this.whineOsc=T(t.createOscillator()),this.whineOsc.setPeriodicWave(tn(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=nn(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=W(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=T(t.createOscillator()),this.wander1.type=`sine`,this.wander1.frequency.value=.31,this.wander2=T(t.createOscillator()),this.wander2.type=`sine`,this.wander2.frequency.value=2.17,this._srcs.push(this.wander1,this.wander2),this.wanderDepth1=a(qt(t,this.wander1,0,this.whineOsc.detune)),this.wanderDepth2=a(qt(t,this.wander2,0,this.whineOsc.detune)),this.shaftOsc=T(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 c=W(t,`pink`,1.31);this._srcs.push(c),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,c.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=T(t.createOscillator()),this.wgOsc.type=`sawtooth`,this.wgOsc.frequency.value=24,this._srcs.push(this.wgOsc),this.wgShaper=a(t.createWaveShaper()),this.wgShaper.curve=rn(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=T(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(qt(t,this.wander2,0,this.hiOsc.detune)),this.buzzOsc=T(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=T(t.createOscillator()),this.surgeOsc.type=`sawtooth`,this.surgeOsc.frequency.value=16,this._srcs.push(this.surgeOsc),this.surgeShaper=a(t.createWaveShaper()),this.surgeShaper.curve=rn(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=T(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=B(V(t&&t.inertia,.4),.05,3),this.maxBoost=B(V(t&&t.maxBoost,1),0,5),this.bovLevel=B(V(t&&t.bov,.5),0,2),this.surgeTrim=B(V(t&&t.surge,1),0,3),this.valve=Math.round(B(V(t&&t.valve,1),0,2)),this.flutterHz=B(V(t&&t.flutterHz,13),3,30),this.screamer=V(t&&t.screamer,0)>=.5,this.antiLag=V(t&&t.antiLag,0)>=.5;let n=V(e&&e.redlineRpm,7e3);this.boostRpm=Math.min(B(V(t&&t.boostRpm,3500),800,9e3),.65*n);let r=.5*V(t&&t.whineOrder,70);this.whineRef=B(n/120*r,200,zt)}update(e){if(!this.enabled)return;let t=V(e.now,0),n=B(V(e.dt,1/60),0,.25),r=B(V(e.load,0),0,1),i=B(V(e.throttle,0),0,1),a=B(V(e.rpmNorm,0),0,1),o=!!e.shifting;this._als=this.antiLag&&i<.12&&a>.15;let s=V(e.rpm,0),c=Math.max(.6*V(this.profile&&this.profile.redlineRpm,7e3),this.boostRpm+1500),l=B((s-this.boostRpm)/(c-this.boostRpm),0,1),u=e.limiter?Math.max(r,.95*i):r,d=this._als?.7*(.3+.7*a):B(u*(.08+.92*l),0,1),f=i<.12,p=B((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=B(V(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=B(_*(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);U(this.whineOsc.frequency,v,t,z,1e3),U(this.whineBP.frequency,v*1.25,t,z,1600),U(this.whineNoiseBP.frequency,v,t,z,800);let y=this.spool**2,b=B(Math.max(r,i*.7),0,1),x=.085*y*(.62+.38*b);H(this.whineGain.gain,x,t,z),H(this.whineNoiseGain.gain,.3*y*(.5+.5*b),t,z),H(this.airflowGain.gain,.2*(.15+.85*this.spool)*this.spool*(.25+.75*b),t,.05),U(this.airflowLP.frequency,900+1300*this.spool,t,z,1400);let ee=26*(1-.75*this.spool);H(this.wanderDepth1.gain,ee,t,.08),H(this.wanderDepth2.gain,ee*.4,t,.08);let te=.55-.3*this.spool;H(this.grainDepth.gain,x*te,t,.05),H(this.whineDrive.gain,.8+.9*this.spool,t,z),U(this.grainBP.frequency,28+120*this.spool,t,z,55),U(this.shaftOsc.frequency,B(v/11,4,400),t,z,180),H(this.shaftDepth.gain,x*(.52-.28*this.spool),t,z);let ne=B((this.spool-.4)/.3,0,1)*B((a-.4)/.3,0,1),re=ne*i*(this.screamer?1.3:.7);U(this.wgOsc.frequency,18+12*ne+8*a,t,.05,24),U(this.wgBP.frequency,(this.screamer?900:1400)+1300*this.spool,t,z,1500),H(this.wgLevel.gain,re,t,.05),H(this.wgGrain.gain,re*.5,t,.05);let S=.1*y*(.45+.55*b);H(this.hissGain.gain,S,t,z),H(this.hissGrain.gain,S*.65,t,.05),U(this.hissBP.frequency,B(v*2.2,900,4200),t,z,2e3);let C=.18*(B((this.boost-.12)/.45,0,1)*i*(1-.75*a)+.6*this._climb*Math.sqrt(this.spool));H(this.whooshGain.gain,C,t,.04),H(this.whooshGrain.gain,C*.6,t,.05),U(this.whooshBP.frequency,B(4e3+3500*this.spool,3e3,8e3),t,z,5e3);let ie=.08*B((this.spool-.62)/.25,0,1)*b;U(this.buzzOsc.frequency,B(v/11,20,400),t,z,60),U(this.buzzBP.frequency,B(v*1.5,400,6e3),t,z,1500),H(this.buzzGain.gain,ie,t,z),U(this.hiOsc.frequency,B(5e3+8e3*this.spool**1.4,3e3,15e3),t,z,6e3);let w=.022*y*(.55+.45*b);H(this.hiGain.gain,w,t,z),H(this.hiGrain.gain,w*.4,t,.05),H(this.hiWander.gain,12*(1-.6*this.spool),t,.08);let ae=B(V(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=Qt(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=B((this.spool-.12)/.28,0,1)*(this.valve===0?1:B(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=B(this._surge,0,1),g=this._liftRate*(.7+.45*h);U(this.surgeOsc.frequency,g,e,.03,16),U(this.surgeBody.frequency,(2400+700*h+500*r)*this._liftPitch,e,.04,3e3),U(this.surgeEdge.frequency,(4600+600*h+600*r)*this._liftPitch,e,.04,5200),H(this.surgeChirp.gain,600*h,e,.04),H(this.surgeJitter.gain,18*h,e,.04);let _=B(V(a.overrun,0),0,1),v=(.6+.4*r)*(.8+.3*_),y=this.surgeLevel*this.surgeTrim;H(this.surgeBodyLvl.gain,6.5*y*h*v,e,.03),H(this.surgeEdgeLvl.gain,.25*y*h*h*v,e,.03);let b=B(5500+3500*this.spool,4500,9500);U(this.fwOsc.frequency,b,e,.03,7e3),U(this.fwBP.frequency,b,e,.03,7e3),H(this.hiSurgeLvl.gain,1.6*y*h*v,e,.03),H(this.hiChirp.gain,900*h,e,.04),H(this.hiChirpN.gain,900*h,e,.04)}release(){let e=V(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=B(this.boost,0,1),i=B(this.bovLevel*1.35*t*(.15+.85*r)*(n?.3:1),5e-4,2.5),a=B(.11+.26*r,.05,.5),o=V(e,0)+Ht,s=this.bovBP.frequency;s.cancelScheduledValues(o),s.setValueAtTime(Ut((n?1300:2600)+1800*r,2800),o),s.exponentialRampToValueAtTime(Ut((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=B(this.bovLevel,.15,1),this.spool*=.97,this._lastBov=V(e,0)}start(e){Jt(this._srcs,e)}dispose(){let e=V(this.ctx.currentTime,0);Yt(this._srcs,e),Xt(this._nodes),this._srcs.length=0,this.enabled=!1}},en=new WeakMap;function tn(e){let t=en.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 en.set(e,i),i}function nn(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 rn(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 an=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})}),on=class{constructor(e,t,n){this.ctx=e;let r=n||{};this.level=V(r.level,1),this.lookahead=B(V(r.lookahead,Ht),0,.05),this.overrunCrackle=r.overrunCrackle!==!1,this.maxPerFrame=B(Math.round(V(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=Wt(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=B(V(r.makeup,9),1,40),this.out.gain.value=this.level*this.makeup,this.combOut.gain.value=this.level*this.makeup;let a=B(Math.round(V(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=W(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=B(V(e&&e.cylinders,6),1,16);this.cyl=t,this.idleRpm=V(e&&e.idleRpm,800),this.sizeF=(6/t)**.35,this.sizeA=(t/6)**.3,this.burstCount=B(1+Math.round(t/5),1,3)}trigger(e,t,n,r,i){let a=an[e]||an.click,o=V(this.ctx.currentTime,0),s=Math.max(V(t,o),o+this.lookahead),c=B(V(n,0)*a.lvl,8e-4,4),l=B(V(r,1),.2,5),u=B(a.dec*B(V(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(Ut(a.fA*l,1e3),s),g.bpA.Q.setValueAtTime(V(a.qA,4),s),g.bpB.frequency.cancelScheduledValues(s),g.bpB.frequency.setValueAtTime(Ut(a.fB*l,3e3),s),g.bpB.Q.setValueAtTime(V(a.qB,6),s),g.mixB.gain.cancelScheduledValues(s),g.mixB.gain.setValueAtTime(V(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:B(V(n,0),0,1)}),h}update(e){let t=V(e.now,0),n=Math.max(0,V(e.rpm,0)),r=B(V(e.rpmNorm,0),0,1),i=this._rnd,a=this.maxPerFrame,o=B(V(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=B(.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=B(V(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=B(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=B(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=B(V(e.evLash,0),0,1);if(c>0&&a>0){let e=t+this.lookahead;this.trigger(`clunk`,e,B(.5*c,.001,1),.9+.25*i(),.8+.5*c),a--,c>.35&&a>0&&(this.trigger(`clunk`,e+.018+i()*.012,B(.16*c,.001,1),1.3,.5),a--)}let l=B(V(e.evEngage,0),0,1);l>0&&a>0&&(this.trigger(`thump`,t+this.lookahead,B(.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>=V(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=B(V(e.overrun,0),0,1),f=e.popIntensity==null?d*.55:B(V(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=B(.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){Jt(this._srcs,e)}dispose(){let e=V(this.ctx.currentTime,0);Yt(this._srcs,e),Xt(this._nodes),this._srcs.length=0,this.voices.length=0}},G=(e,t,n)=>e<t?t:e>n?n:e,K=(e,t=0)=>typeof e==`number`&&isFinite(e)?e:t,sn=.02;function q(e,t,n,r=sn){if(!e)return;let i=K(t,0);e.setTargetAtTime(i,Math.max(0,K(n,0)),r>0?r:sn)}function cn(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 ln=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=T(e.createBufferSource()),this.src.buffer=cn(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=T(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=G(K(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=K(e.now,0),n=G(K(e.rpmNorm,0),0,1),r=G(K(e.load,0),0,1),i=G(K(e.overrun,0),0,1),a=G(G(K(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);q(this.level.gain,s,t),q(this.pulse.frequency,a,t),q(this.pulseDepth.gain,Math.min(s*.85,s*(1.1-.7*n)),t),q(this.peak.frequency,G(a,30,2e3),t),q(this.body.frequency,G(450+2600*r+1800*n,120,9e3),t),q(this.hp.frequency,G(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()}},un=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=T(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=G(K(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=K(e.now,0),n=G(K(e.f0,10),.05,4e3),r=G(K(e.load,0),0,1),i=G(K(e.rpmNorm,0),0,1),a=G(K(e.overrun,0),0,1);q(this.osc.frequency,G(n*this.order,12,400),t);let o=.34*(.18+.82*r**.75)*(1-.45*i)*(1-.6*a);q(this.level.gain,o,t),q(this.tone.frequency,G(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()}},dn=class{constructor(e,t,n={}){this.ctx=e,this.depthCents=G(K(n.detuneCents,7),0,60),this.depthGain=G(K(n.tremolo,.1),0,.6);let r=[.237,1.703,5.317];this.lfos=r.map(t=>{let n=T(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=T(e.createBufferSource()),this.rough.buffer=cn(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=K(e.now,0),n=G(K(e.rpmNorm,0),0,1),r=G(K(e.load,0),0,1),i=(1-n)*(1-.55*r),a=G(K(e.rough,0),0,1),o=+!this._event;q(this.detune.gain,o*this.depthCents*(.25+.75*i)*(1+2.5*a),t,.08),q(this.tremolo.gain,(this._event?.2:1)*this.depthGain*(.2+.8*i)*(1+1.5*a),t,.08),q(this.roughLP.frequency,G(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()}},fn=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.`}]),pn=Object.freeze(Object.fromEntries(fn.map(e=>[e.id,e.default]))),J=(e,t,n)=>e<t?t:e>n?n:e,mn=60/(2*Math.PI),hn={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}},gn=class{constructor(e={}){this.type=e.type in hn?e.type:`manual`,this.k=hn[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?J(e.gearedRpm(t),this.idleRpm,this.redlineRpm*.97)/mn:0,this.phase=`cut`,this.t=0;let a=J(((typeof e.egt==`number`?e.egt:1)-.45)/.35,0,1),o=r.cutBang*(.25+.75*e.throttle)*r.cutDepth*a,s=J((.12+.55*a)*r.cutBang,0,.9);return o>.04&&Math.random()<s&&e.fireEvent(`cut`,J(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)*J(e,0,1);return Math.max(this.idleRpm*1.6,this.redlineRpm*t)}downshiftRpm(e){let t=this.downFracLow+(this.downFracHigh-this.downFracLow)*J(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/mn;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=J(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)*mn;t.fireEvent(`engage`,J(.15+e/1800,0,1)),t.lashContactedSince=!1,this.contactSeen=!1}e===`lash`&&t.fireEvent(`shiftDone`,1)}},Y=60/(2*Math.PI),_n=2*Math.PI/60,vn=1.225,yn=9.81,X=(e,t,n)=>e<t?t:e>n?n:e,bn=2e3,xn=240,Sn=.03,Cn=.02,wn=52,Tn=.2,En=15,Dn=1.5,On=.055,kn=.55,An=2.4,jn=.85,Mn=.45,Nn=class{constructor(e,t,n={}){this.engine=e,this.vehicle=t,this.dl=Object.assign({},Qe,n.driveline),this.eff=n.driveEfficiency==null?.92:n.driveEfficiency,this.Je=Math.max(.02,e.engineInertia),this.Jin=n.inputInertia==null?Sn:n.inputInertia,this.Jout=n.outputInertia==null?Cn: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+wn*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 gn({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*_n,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*Y,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=X(Number(e)||0,0,1)}setBrake(e){this.brake=X(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=X(this.we*Y,e.idleRpm,e.redlineRpm);this.we=t*_n,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+wn*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=X(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*Y}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]*Y}launchRateFor(e){if(this.launchRateOverride!=null)return this.launchRateOverride;let t=X(Math.round(e),1,this.gearCount)-1,n=Math.abs(this.ratios[t]*this.fd)||1;return X(this.engine.peakTorque*n*this.eff/this.r/Math.max(1,this.vehicle.mass)/this.r*n*Y*.55,400,12e3)}inputShaftTargetW(e){return e<=0||e>this.gearCount?0:this.ww*this.fd*this.ratios[e-1]}selectGear(e){this.gear=X(Math.round(e),0,this.gearCount)}fireEvent(e,t){t>this.ev[e]&&(e===`pop`&&this.we*Y<bn||(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 X(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 X(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(xn,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-X(this.fuelCut,0,1),this.limiterActive&&(a=0),this.thrEff=a,this._stepTurbo(e,a),this._stepExhaustThermal(e,a);let o=this.we*Y,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+=X(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*_n,x=t.redlineRpm*1.015*_n;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=X(this.twist||0,-3,3)),this.lash=X(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*_n;return X((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+=(X(r,0,1)-this.clutch)*Math.min(1,e*i),this.clutch=X(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=X(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),X(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-X(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/Mn):c/Mn;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*_n,m=f>1?X(p/f,0,1):0,h=(this.rpm-d)/d;this.launchI=X(this.launchI*(1-Math.min(1,e/.6))+8*h*e,-.4,.5);let g=X(m+this.launchI+1.5*h,0,1),_=X((this.launchT-.9)/1.2,0,1);return Math.max(g,Math.min(_,m))}_converter(e,t){if(e>t+.5){let n=X(t/Math.max(e,.001),0,1),r=X(.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=X(e/Math.max(t,.001),0,1),r=X(.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*vn*n.dragArea*r*r,o=r>0?a*this.r:0,s=(n.rollingResistance*n.mass*yn+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/kn);let n=this.twist>t?1:this.twist<-t?-1:0;if(n===0){Math.abs(this.twist)<t*jn&&(this.contact=0);return}if(n===this.contact)return;let r=Math.abs(this.dtwist);if(this.contact=n,r<Tn||this.lashTimer<On)return;this.lashTimer=0,this.lashContactedSince=!0;let i=1/(1+An*this.lashHeat);this.lashHeat=Math.min(3,this.lashHeat+1);let a=X((r/En)**+Dn*i,.001,1);a<.05||this.fireEvent(`lash`,a)}_stepExhaustThermal(e,t){let n=this.we*Y,r=X((n-this.engine.idleRpm)/Math.max(1,this.engine.redlineRpm-this.engine.idleRpm),0,1),i=X(.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`,X(.16+.14*Math.random(),0,1))),this.prevLimiter=this.limiterActive,this.dfco!==this.prevDfco){if(this.dfcoEdge=1,this.dfco){let e=X(this.thrPeak,0,1),t=r**1.7;this.cutRpmN=r;let n=.55+Math.random()*.95;this.popCharge=X(this.popCharge+(.5+2.1*t)*(.4+.6*e)*n,0,3.4);let i=X((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`,X((this.egt-.35)*1.25*(.1+1.3*t)*(.35+.65*e)*n,0,1)))}else this.popCharge=X(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=X(this.popCharge+1.1+.5*r,0,2.6);let e=X((this.egt-.32)/.3,0,1)*(.35+.65*r);this.egt>.32&&this.popRefractory<=0&&Math.random()<e&&(this.popRefractory=.45,this.fireEvent(`pop`,X((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*Y,i=Math.min(X(Number(n.boostRpm)||3500,800,9e3),.65*this.engine.redlineRpm),a=Math.max(.6*this.engine.redlineRpm,i+1500),o=X((r-i)/(a-i),0,1),s=n.antiLag>=.5&&t<.12&&r>.3*this.engine.redlineRpm,c=s?.7*o:X(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=X(this.boost,0,1),this.boostDump>0&&(this.boostDump-=e);let u=r>900?.12+.2*o:0,d=X(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=X(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`,X(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*Y;n.now=t,n.dt=e,n.rpm=i,n.f0=i/120,n.rpmNorm=X((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=X(this.thrEff||0,0,1),o=e>0?X(e*12,0,1):1;this.load+=(a-this.load)*o,n.load=X(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?X(e*8,0,1):1),n.overrun=X(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*Y,n.clutchSlip=(this.we-this.wg)*Y,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=X(Math.max(0,this.egt-.45)/.55*X(this.popCharge,0,1)*(.12+.88*this.dfcoEdge)*(.45+.55*this.cutRpmN),0,1)*+(i>=bn),n}},Pn=1.225,Fn=9.81,In=60/(2*Math.PI),Ln=.8,Rn=(e,t,n)=>e<t?t:e>n?n:e;function zn(e,t,n=1){let r=(t-e.peakTorqueRpm)/(e.redlineRpm*.75),i=Rn(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 Bn(e){let t={rpm:e.redlineRpm,power:0,torque:0};for(let n=e.idleRpm;n<=e.redlineRpm;n+=25){let r=zn(e,n),i=r*n/In;i>t.power&&(t.power=i,t.rpm=n),r>t.torque&&(t.torque=r)}return t}function Vn(e){return[2.6+.4*(e-4),3.8+.8*(e-4)]}function Hn(e,t,n={}){let r=Math.round(Rn(n.gears||e.gears||t.gearRatios&&t.gearRatios.length||6,3,10)),i=t.gravity||Fn,a=n.efficiency||.92,o=t.wheelRadius,s=t.finalDrive,c=t.mass,l=e=>.5*Pn*t.dragArea*e*e+t.rollingResistance*c*i,u=Bn(e),d=Math.min(u.rpm*1.04,e.redlineRpm*.9),f=a*zn(e,d)*d/In,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/In*o/Math.max(h,1),_=.6*c*i*o/(Math.max(1,u.torque)*a),[v,y]=Vn(r),b=Rn(_/g,v,y),x=[];for(let e=1;e<=r;e++){let t=((r-e)/(r-1))**1.15;x.push(+(Ln*g*b**+t/s).toFixed(3))}return{gearRatios:x,gearTeeth:x.map(e=>Math.round(Rn(16+6.5*e,17,46))),topSpeed:h}}function Un(e,t,n){let r=Hn(e,t,n);return{...t,gearRatios:r.gearRatios,gearTeeth:r.gearTeeth}}var Z=(e,t,n)=>e<t?t:e>n?n:e,Q=(e,t=0)=>typeof e==`number`&&isFinite(e)?e:t,Wn=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(Z(Q(e[n],0),-18,18),t,.03)}setBand(e,t){e<0||e>=this.bands.length||this.bands[e].gain.setTargetAtTime(Z(Q(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()}},Gn=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=Z(Q(t.size,.35),.05,1),this._mix=Z(Q(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*Z(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=Z(Q(e,.35),.05,1),this.conv.buffer=this._buildIR(this._size),this._size}setMix(e){return this._mix=Z(Q(e,0),0,1),this._writeMix(.03),this._mix}setExtra(e){let t=Z(Q(e,0),0,1);Math.abs(t-(this._extra||0))<.001||(this._extra=t,this._writeMix(.08))}_writeMix(e){let t=Z(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(Z(Q(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()}},Kn=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(Q(t.width,.35))}get input(){return this.inGain}get output(){return this.out}setWidth(e){this._width=Z(Q(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()}},qn=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=Z(Q(n.amount,1),0,1),this.inGain=t.createGain(),this.out=t.createGain(),this.out.gain.value=Z(Q(n.makeup,1),0,4);let r=(e,n)=>{let r=t.createBiquadFilter();return r.type=e,r.frequency.value=Z(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=Z(Q(e,1),0,1);let t=Q(this.ctx.currentTime,0);for(let e of this.bands){let n=Z(e.spec.threshold*this._amount,-100,0);e.comp.threshold.setTargetAtTime(n,t,.05);let r=1+(e.spec.makeup-1)*this._amount,i=Jn(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]=Q(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 Jn(e,t,n=0){let r=Math.min(0,Q(e,0))+Math.max(0,Q(n,0))/2,i=Math.max(1,Q(t,1));return Math.max(0,-.6*Math.min(0,r)*(1-1/i))}var Yn=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()}},Xn=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=Z(Q(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(Z(Q(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()}},Zn=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=Z(Q(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()}},Qn=`/**
2
- * combustion-worklet.js — the engine's source, one combustion event at a time.
3
- *
4
- * Runs on the audio thread (AudioWorkletProcessor 'engine-combustion').
5
- *
6
- * The wavetable source (pulse.js) builds ONE 720° cycle per bank and repeats
7
- * it forever: every cycle identical to the sample. A real engine never does
8
- * that. Peak cylinder pressure varies cycle to cycle (COV of IMEP ≈ 1-3 % at
9
- * full load, 5-15 % at idle and on a lumpy cam), ignition timing wanders by a
10
- * degree or so, and a cylinder occasionally burns badly or not at all. That
11
- * variation is not noise laid on top of the engine — it is energy spread into
12
- * sidebands AROUND the engine's own harmonics, tied to its firing, and it is
13
- * most of what makes a recording sound like a machine instead of an organ.
14
- * The old graph faked it with slow LFO vibrato on the whole engine and with
15
- * noise beds; this generates it where it happens.
16
- *
17
- * Per sample: the crank phase advances by f0 / sampleRate (f0 = one 720°
18
- * cycle per second). When it passes a cylinder's firing angle (+ that
19
- * cylinder's fixed trim + this event's jitter), a pressure pulse starts on that
20
- * cylinder's bank output:
21
- *
22
- * p(t) = A · g(t) · (1 − e^(−a·t)) · e^(−b·t) t in cycles since firing
23
- *
24
- * with the same attack/decay law as pulse.js (load hardens it continuously
25
- * instead of crossfading two tables), A carrying the cylinder's trim and this
26
- * cycle's variation, and g(t) a ~60 µs Gaussian onset so the gradient has no
27
- * step to alias. The output is the pressure GRADIENT (what an open pipe
28
- * radiates), per unit of crank phase so it is rpm-independent, through a
29
- * one-pole lowpass at RADIATION_KNEE half-orders — the time-domain version of
30
- * pulse.js's radiation shelf — and scaled by a calibration gain computed on the
31
- * main thread from the same shape (\`combustionGains\` in pulse.js).
32
- *
33
- * Outputs: one per exhaust bank, then the intake (all cylinders, 360° earlier).
34
- *
35
- * AudioParams (k-rate): f0, load, amp, rough (0..1 misfires + extra variation),
36
- * ripple (crank-speed swing per firing, see pulse.js crankRipple) and low
37
- * (1 at idle, 0 at redline).
38
- *
39
- * CRANK-SPEED RIPPLE. The crank does not turn evenly: every firing kicks it
40
- * faster and the compression strokes in between brake it. \`v\` is that speed
41
- * deviation: each firing adds \`ripple × its own strength\`, and it is drawn
42
- * back down continuously at the average rate, so it is a sawtooth around
43
- * zero. The crank phase advances at \`dph × (1 + v)\`, so every pulse — and the
44
- * timing of the next firing — is frequency-modulated by the engine's own
45
- * firings. A strong firing pulls the next one early, a weak one lets it come
46
- * late: asymmetry and irregularity that come from the mechanism, and fade
47
- * with ω² as it revs.
48
- *
49
- * LOW-RPM SCATTER. Combustion is least repeatable at low speed: the flame is
50
- * slow, turbulence is low, and cylinder-to-cylinder air distribution is at its
51
- * worst. So \`low\` widens the cycle-to-cycle variation, the timing jitter, and
52
- * each cylinder's fixed imbalance.
53
- */
54
-
55
- const KNEE_HALF_ORDERS = 48; // = RADIATION_KNEE_ORDER (24) × 2
56
- const ONSET_S = 60e-6; // Gaussian onset time constant
57
-
58
- class CombustionProcessor extends AudioWorkletProcessor {
59
- static get parameterDescriptors() {
60
- return [
61
- { name: 'f0', defaultValue: 10, minValue: 0, maxValue: 4000, automationRate: 'k-rate' },
62
- { name: 'load', defaultValue: 0, minValue: 0, maxValue: 1, automationRate: 'k-rate' },
63
- { name: 'amp', defaultValue: 0, minValue: 0, maxValue: 8, automationRate: 'k-rate' },
64
- { name: 'rough', defaultValue: 0, minValue: 0, maxValue: 1, automationRate: 'k-rate' },
65
- { name: 'ripple', defaultValue: 0, minValue: 0, maxValue: 0.2, automationRate: 'k-rate' },
66
- { name: 'low', defaultValue: 0, minValue: 0, maxValue: 1, automationRate: 'k-rate' },
67
- ];
68
- }
69
-
70
- constructor(options) {
71
- super();
72
- const o = options.processorOptions;
73
- // events: [{ out, angle (cycles 0..1), ampTrim, decayTrim }] sorted by angle
74
- this.events = o.events;
75
- this.nOut = o.outputs;
76
- this.attack = o.attack;
77
- this.decay = o.decay;
78
- this.hardness = o.hardness; // normalised (1 = the 0.65 reference)
79
- this.ccv = o.ccv; // cycle-to-cycle amplitude COV at full load
80
- this.jitterCycles = o.jitterDeg / 720;
81
- this.gains = o.gains; // [out][5] calibration over load 0..1
82
- this.abs = 0; // crank position, in cycles, absolute
83
- this.pulses = []; // active pulses
84
- this.pool = [];
85
- this.prevP = new Float64Array(this.nOut);
86
- this.lp = new Float64Array(this.nOut);
87
- // Each event's next firing, in absolute cycles: its cycle index + angle +
88
- // this cycle's jitter. Advancing the index by exactly one per firing means
89
- // jitter can never fire an event twice, or skip one.
90
- this.cycleOf = new Float64Array(this.events.length);
91
- this.nextAt = Float64Array.from(this.events, (e) => e.angle);
92
- this.seed = (o.seed >>> 0) || 1;
93
- this.v = 0; // crank-speed deviation, fraction
94
- this.nFire = this.events.filter((e) => e.out < this.nOut - 1).length;
95
- this.alive = true;
96
- this.port.onmessage = (m) => { if (m.data === 'stop') this.alive = false; };
97
- }
98
-
99
- rand() {
100
- let s = this.seed;
101
- s ^= s << 13; s >>>= 0; s ^= s >> 17; s ^= s << 5; s >>>= 0;
102
- this.seed = s;
103
- return s / 4294967296;
104
- }
105
-
106
- gauss() {
107
- // Irwin-Hall approximation: cheap, bounded (±3σ), good enough for COV.
108
- return (this.rand() + this.rand() + this.rand() + this.rand() - 2) * 1.732;
109
- }
110
-
111
- /** Schedule event k's next firing: one cycle on, with fresh jitter. */
112
- _schedule(k, load, rough, low = 0) {
113
- const e = this.events[k];
114
- const spread = this.jitterCycles * (0.6 + 1.4 * (1 - load)) * (1 + 2 * rough) * (1 + 0.8 * low);
115
- this.cycleOf[k] += 1;
116
- this.nextAt[k] = this.cycleOf[k] + e.angle + Math.max(-0.02, Math.min(0.02, this.gauss() * spread));
117
- }
118
-
119
- _fire(e, load, rough, low = 0, ripple = 0) {
120
- // Cycle-to-cycle variation: larger at light load (poorer, slower burns)
121
- // and with \`rough\`; occasional misfire — the cylinder still pumps air, so
122
- // a faint pulse, not silence.
123
- const cov = this.ccv * (0.7 + 2.3 * (1 - load) * (1 - load)) * (1 + 2.5 * rough) * (1 + low);
124
- const trim = 1 + (e.ampTrim - 1) * (1 + 1.5 * low);
125
- let A = trim * Math.max(0.15, 1 + this.gauss() * cov);
126
- if (rough > 0 && this.rand() < 0.06 * rough * rough) A *= 0.12;
127
- const h = this.hardness * load;
128
- const a = this.attack * (0.55 + 0.85 * h);
129
- const b = this.decay * (1.25 - 0.35 * h) * e.decayTrim * (1 + 0.5 * cov * this.gauss());
130
- const p = this.pool.pop() || {};
131
- p.out = e.out; p.A = A; p.a = a; p.b = b; p.t = 0; p.ts = 0;
132
- this.pulses.push(p);
133
- // The intake events mirror the firings; only a firing kicks the crank.
134
- if (e.out < this.nOut - 1) this.v += ripple * A;
135
- }
136
-
137
- process(inputs, outputs, params) {
138
- const out = outputs;
139
- const n = out[0][0].length;
140
- const f0 = params.f0[0];
141
- const load = Math.min(1, Math.max(0, params.load[0]));
142
- const amp = params.amp[0];
143
- const rough = params.rough[0];
144
- const ripple = params.ripple ? params.ripple[0] : 0;
145
- const low = params.low ? params.low[0] : 0;
146
- const drag = ripple * this.nFire; // mean kick per cycle, drawn back
147
- const sr = sampleRate;
148
- const dph = f0 / sr; // crank cycles per sample
149
- const dts = 1 / sr;
150
- const ev = this.events, nEv = ev.length;
151
- // Calibration gain per output at this load (linear between 5 points).
152
- const gi = load * 4, g0 = Math.min(3, Math.floor(gi)), gf = gi - g0;
153
- // One-pole lowpass at KNEE half-orders of f0 (the radiation knee).
154
- const fc = Math.min(KNEE_HALF_ORDERS * f0, 0.45 * sr);
155
- const lpk = 1 - Math.exp(-2 * Math.PI * fc / sr);
156
-
157
- for (let o = 0; o < this.nOut; o++) out[o][0].fill(0);
158
- const acc = this._acc || (this._acc = new Float64Array(this.nOut));
159
-
160
- for (let i = 0; i < n; i++) {
161
- // Advance the crank; fire every event whose (jittered) time has come.
162
- const dphv = dph * (1 + this.v);
163
- const invv = dphv > 1e-9 ? 1 / dphv : 0;
164
- // Compression drag, plus a leak (~e^-6 per cycle) standing in for the
165
- // load and idle-speed control that stop the speed wandering off.
166
- this.v -= (drag + 6 * this.v) * dph;
167
- if (this.v > 0.2) this.v = 0.2; else if (this.v < -0.2) this.v = -0.2;
168
- this.abs += dphv;
169
- const abs = this.abs;
170
- for (let k = 0; k < nEv; k++) {
171
- if (abs >= this.nextAt[k]) {
172
- this._fire(ev[k], load, rough, low, ripple);
173
- // Sub-sample start: how far past its firing this sample already is.
174
- const past = Math.min(1, abs - this.nextAt[k]);
175
- const last = this.pulses[this.pulses.length - 1];
176
- last.t = past; last.ts = f0 > 0 ? past / f0 : 0;
177
- this._schedule(k, load, rough, low);
178
- // Far behind (e.g. f0 jumped from 0): catch the schedule up silently.
179
- while (this.nextAt[k] < abs) this._schedule(k, load, rough, low);
180
- }
181
- }
182
- // Sum the live pulses' pressure per output.
183
- acc.fill(0);
184
- for (let j = this.pulses.length - 1; j >= 0; j--) {
185
- const p = this.pulses[j];
186
- if (p.t > 1 || p.b * p.t > 9) { // spent (or past one cycle)
187
- this.pulses[j] = this.pulses[this.pulses.length - 1];
188
- this.pulses.pop();
189
- this.pool.push(p);
190
- continue;
191
- }
192
- const on = 1 - Math.exp(-(p.ts * p.ts) / (ONSET_S * ONSET_S));
193
- acc[p.out] += p.A * on * (1 - Math.exp(-p.a * p.t)) * Math.exp(-p.b * p.t);
194
- p.t += dphv; p.ts += dts;
195
- }
196
- for (let o = 0; o < this.nOut; o++) {
197
- const grad = (acc[o] - this.prevP[o]) * invv; // dp / d(phase)
198
- this.prevP[o] = acc[o];
199
- this.lp[o] += lpk * (grad - this.lp[o]);
200
- const G = this.gains[o];
201
- const gain = G[g0] + (G[g0 + 1] - G[g0]) * gf;
202
- out[o][0][i] = this.lp[o] * gain * amp;
203
- }
204
- }
205
- return this.alive;
206
- }
207
- }
208
-
209
- registerProcessor('engine-combustion', CombustionProcessor);
210
- `,$=(e,t,n)=>e<t?t:e>n?n:e,$n={...j.mix},er=new WeakSet,tr=new WeakMap,nr=class e{static preload(e){if(er.has(e))return Promise.resolve(!0);if(!e||!e.audioWorklet||typeof AudioWorkletNode>`u`)return Promise.resolve(!1);if(!tr.has(e)){let t=URL.createObjectURL(new Blob([Qn],{type:`text/javascript`}));tr.set(e,e.audioWorklet.addModule(t).then(()=>(er.add(e),!0)).catch(e=>(console.warn(`[engine-sim] combustion worklet unavailable, using wavetables`,e),!1)).finally(()=>URL.revokeObjectURL(t)))}return tr.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 k?t.engine:`v8cross`,this.vehicleId=t.vehicle in Ze?t.vehicle:`sports`,this.profile=at(this.engineId).engine,this.vehicle=Ze[this.vehicleId],this.stockGearing=t.gearing===`stock`,this.geared=this._gearedVehicle(),this.mix={...$n,...t.mix||{}},this.turboCfg={...j.turbo,enabled:+!!t.turbo},this._volume=t.volume??j.volume,this.running=!1,this._destOpt=t.destination||null,this.presetId=this.engineId,this.presetLabel=at(this.engineId).label,this._rumble=j.tone.rumble,this._brightness=j.tone.brightness,this._popDepth=j.fx.popDepth,this._dynamics=j.fx.dynamics,this._width=j.fx.width,this._position=j.position,this._punch=j.tone.punch,this.inputs={...pn,...t.inputs||{}},this._ps={},this._misfireRng=625341585,this._misfireHold=0,this._bark=0,this._prevLoad=0,this.physics=new Nn(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 qn(e,{amount:1}),this.cabin=new Ft(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 Xn(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**(-Jn(-1.5,20,4)/20),this.safety=new Yn(e),this.eq=new Wn(e),this.reverb=new Gn(e,{size:.32,mix:.14}),this.stereo=new Kn(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 Zn(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($n)){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=yt(e,t,Je),this.exhaustTrem&&this.exhaustTrem.disconnect(),this.exhaust=new It(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 Nt(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 Zt(e,t,this.geared),this.transmission.output.connect(this.busses.transmission),this.turbo=t.turbo?new $t(e,t):null,this.turbo&&this._wireTurbo(),this.transients=new on(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 ln(e,t);for(let e of this.exhaust.inputs)this.exhaustNoise.output.connect(e);if(this.sub=new un(e,t),this.sub.output.connect(this.busses.sub),this.character=new dn(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,er.has(e)&&!this.opts?.wavetables){let n=xt(t,Je);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=T(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&&!er.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 $t(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 k)||e===this.engineId?!1:(this.engineId=e,this._applyEngine(at(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 N({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=k[e]?at(e):ct(e).preset),!t||typeof t!=`object`?!1:(t=N(t),this.presetId=t.id,this.presetLabel=t.label,k[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 st(this.getPreset())}setParam(e,t){let n=it(e);if(!n)return null;let r=$(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 rt(t,e,r),this._applyEngine(N(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`){rt(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=nt(this.getPreset(),e);return typeof t==`number`?t:null}static schema(){return et}static groups(){return tt}static presets(){return ot()}_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 Ze)||e===this.vehicleId?!1:(this.vehicleId=e,this.setVehicleProfile(Ze[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:Un(this.profile,this.vehicle)}setInput(e,t){if(!(e in pn))return null;let n=$(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 fn}setThrottle(e){this.physics.throttle=$(Number(e)||0,0,1)}setBrake(e){this.physics.brake=$(Number(e)||0,0,1)}setClutch(e){this.physics.clutchPedal=$(Number(e)||0,0,1)}setClutchOverride(e){this.physics.burnoutClutchOverride=e==null?null:$(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,t=.05){if(this._volume=$(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),t>.05?this.master.gain.linearRampToValueAtTime(this._volume,e+t):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($(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=$(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=$(Number(t)||0,0,2),this.airCut.gain.setTargetAtTime(-2*(2-this._brightness),r,.05)),n!=null&&(this._punch=$(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=$(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=$(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(k).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(Ze).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=$(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),$(e/10,0,1))}this._prevLoad=i.load;let o=$(i.load+.3*this._bark,0,1),s=(1+.35*this._bark)*(.32+.68*o**.7)*(.45+.55*$(i.rpmNorm,0,1))*(1-.45*$(i.overrun,0,1))*$(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($(this.inputs.roughness||0,0,1),r,.05),e.get(`ripple`).setTargetAtTime(bt(this.profile,i.rpm,o),r,n),e.get(`low`).setTargetAtTime(1-$(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*$(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=$(n.load+(1-n.load)*.55*i*Math.max(.25,n.throttle||0),0,1)),rr(this.exhaustTrem.gain,1+.4*a,t,.08);let s=r.distance;if(rr(this.air.frequency,18e3*.09**s,t,.08),rr(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 rr(e,t,n,r){Number.isFinite(t)&&e.setTargetAtTime(t,n,r)}var ir={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},ar=class{context;output;noise;sources=new Set;disposed=!1;constructor(e,t=e.destination){this.context=e,this.output=e.createGain(),this.output.gain.value=D(E.engineShutdown),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}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,c=T(s.createOscillator());c.type=o,c.frequency.setValueAtTime(n,e),c.frequency.exponentialRampToValueAtTime(Math.max(20,r),e+t);let l=s.createBiquadFilter();l.type=`lowpass`,l.frequency.value=a;let u=s.createGain();u.gain.setValueAtTime(1e-4,e),u.gain.linearRampToValueAtTime(i,e+Math.min(.025,t*.3)),u.gain.exponentialRampToValueAtTime(1e-4,e+t),c.connect(l).connect(u).connect(this.output),c.addEventListener(`ended`,()=>{l.disconnect(),u.disconnect()},{once:!0}),this.run(c,e,t)}hiss(e,t,n,r){let i=this.context,a=T(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)}stop(e){if(this.disposed)return 0;this.cancel();let t=this.context.currentTime+.01,n=ir[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()}},or=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(D(E.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=T(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 c=this.context.createGain();c.gain.value=i?.55:.7,t.connect(n).connect(c).connect(a),t.start(e),o.oscillators.push(t),o.filters.push(n),o.gains.push(c)}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)}};function sr(e){let t=Math.max(0,Math.min(18,e))/18;return{volume:Math.min(1,.1+.9*t**.8),rate:2**((t-.5)/12)}}var cr=class{context;output;loadComplete;clip=null;voices=[];nextAt=0;disposed=!1;constructor(e,t=e.destination){this.context=e,this.output=e.createGain(),this.output.gain.value=D(E.collision),this.output.connect(t),this.loadComplete=Fe(e).load(`collision`).then(e=>{this.disposed||(this.clip=e)}).catch(e=>{this.disposed||console.warn(`Joy Ride collision sound could not load.`,e)})}play(e){if(this.disposed||!Number.isFinite(e)||e<.8)return;let t=this.context.currentTime;if(t<this.nextAt)return;let n=sr(e),r=this.clip;if(!r)return;this.nextAt=t+.16;let i=T(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.clip=null,this.output.disconnect())}},lr=new WeakMap;function ur(e){let t=lr.get(e);if(t)return t;t=e.createBuffer(1,Math.ceil(e.sampleRate*2),e.sampleRate);let n=t.getChannelData(0),r=0;for(let e=0;e<n.length;e++){let t=Math.random()*2-1;r+=.025*(t-r),n[e]=t*.25+r*2.3}let i=n[n.length-1]-n[0];for(let e=0;e<n.length;e++)n[e]-=i*(e/(n.length-1));return lr.set(e,t),t}var dr=class{context;volume;highpass;lowpass;voices=new Set;current=null;disposed=!1;level=0;constructor(e,t,n,r){this.context=e,this.volume=r,this.highpass=e.createBiquadFilter(),this.highpass.type=`highpass`,this.highpass.frequency.value=n===`flame`?70:220,this.highpass.Q.value=.55,this.lowpass=e.createBiquadFilter(),this.lowpass.type=`lowpass`,this.lowpass.frequency.value=n===`flame`?1800:950,this.lowpass.Q.value=.65,this.highpass.connect(this.lowpass).connect(t)}setLevel(e){if(this.disposed)return;let t=Number.isFinite(e)?Math.max(0,Math.min(1,e)):0;if(t===this.level)return;this.level=t;let n=this.context.currentTime;if(t<=0){let e=this.current;if(!e)return;this.current=null,e.gain.gain.setTargetAtTime(0,n,.035),e.source.stop(n+.18)}else{if(!this.current){let e=T(this.context.createBufferSource()),t=this.context.createGain();e.buffer=ur(this.context),e.loop=!0,t.gain.value=0,e.connect(t).connect(this.highpass);let n={source:e,gain:t};this.voices.add(n),this.current=n,e.onended=()=>{e.disconnect(),t.disconnect(),this.voices.delete(n),this.current===n&&(this.current=null)},e.start()}this.current.gain.gain.setTargetAtTime(t*this.volume,n,.065)}}silence(){this.setLevel(0)}dispose(){if(!this.disposed){this.disposed=!0,this.current=null,this.level=0;for(let e of this.voices)e.source.stop(),e.source.disconnect(),e.gain.disconnect();this.voices.clear(),this.highpass.disconnect(),this.lowpass.disconnect()}}},fr=class{loop;constructor(e,t=e.destination){this.loop=new dr(e,t,`flame`,D(E.flamethrower))}setPressed(e){this.loop.setLevel(+!!e)}silence(){this.loop.silence()}dispose(){this.loop.dispose()}},pr=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=Le(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=T(this.context.createBufferSource());e.buffer=this.buffer,e.loop=!0,this.envelope.loopStartSeconds!==void 0&&(e.loopStart=Math.min(this.envelope.loopStartSeconds,this.buffer.duration)),e.connect(this.gain),e.onended=()=>{e.disconnect(),this.source===e&&(this.source=null)},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),t===0&&this.envelope.stopWhenSilent&&this.source&&(this.source.stop(this.context.currentTime+.18),this.source=null)}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())}},mr=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=Le(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=T(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}},hr=class{loop;constructor(e,t=e.destination){this.loop=new pr(e,t,`boost`,D(E.boost),{attackSeconds:.12,releaseSeconds:.055,loopStartSeconds:.75,stopWhenSilent:!0})}setBoosting(e){this.loop.setLevel(+!!e)}silence(){this.loop.silence()}dispose(){this.loop.dispose()}},gr=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=O(t),this.output.connect(e.destination),this.launch=new mr(e,this.output,`explosion`,D(E.rocketLaunch)),this.explosion=new mr(e,this.output,`explosion`,D(E.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 fr(e,this.flightGain)}setMasterVolume(e){this.output.gain.setTargetAtTime(O(e),this.context.currentTime,.055)}playLaunch(e){this.disposed||this.launch.play(O(e),2**(7/12))}playExplosion(e){this.disposed||this.explosion.play(O(e))}setFlightProximity(e){if(this.disposed)return;let t=O(e);this.flight.setPressed(t>.015),this.flightGain.gain.setTargetAtTime(t*D(E.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())}},_r={bulletRicochetChance:.22,bulletRicochetMinimumGapSeconds:.08,bulletRicochetPitchSemitones:2},vr=class{preset;engine=null;tires=null;shutdown=null;horn=null;crashes=null;flamethrower=null;boost=null;rockets=null;gunshot=null;ricochet=null;lastRicochetAt=-1/0;crunch=null;combustibleExplosion=null;burningFire=null;ghostMode=null;fireOutput=null;hornPressed=!1;output=null;engineStartPromise=null;stopTimer=null;disposed=!1;stopping=!1;ready=!1;active=!0;idleSound;driving=!1;engineAudible=null;masterVolume;audioSet;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,we(this.engine.ctx,this.timeScale)))}constructor(e,t={}){this.preset=e,this.idleSound=t.idleSound??!0,this.masterVolume=O(t.masterVolume??1),this.audioSet=t.audioSet??`default`}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.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=O(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=O(e),this.syncOutputVolume()}syncOutputVolume(){if(!this.output)return;let e=this.outputVolume;if(Math.abs(e-this.appliedVolume)<.001)return;let t=this.appliedVolume<=0&&e>0;this.appliedVolume=e;let n=this.output.context.currentTime;t?(this.output.gain.cancelScheduledValues(n),this.output.gain.setValueAtTime(this.output.gain.value,n),this.output.gain.linearRampToValueAtTime(e,n+.3)):this.output.gain.setTargetAtTime(e,n,.055)}async start(){if(!(this.engine||this.disposed||this.stopping))try{let e=this.active&&this.idleSound,t=new nr(null,{engine:this.preset.sound.engineId,vehicle:this.preset.sound.vehicleId,turbo:this.preset.sound.turbo??!1,volume:e?D(E.engine):0});if(this.engine=t,this.engineAudible=e,this.setTimeScale(this.timeScale),this.baseLaunchFlareRpm=t.physics.launchFlareRpm,this.output=t.ctx.createGain(),this.output.gain.value=this.outputVolume,this.appliedVolume=this.outputVolume,this.output.connect(t.ctx.destination),t.connect(this.output),Fe(t.ctx,this.audioSet).initialize(),this.tires=new He(t.ctx,this.output),this.horn=new or(t.ctx,this.preset.sound.horn,this.output),this.crashes=new cr(t.ctx,this.output),this.flamethrower=new fr(t.ctx,this.output),this.boost=new hr(t.ctx,this.output),this.rockets=new gr(t.ctx,this.masterVolume),this.gunshot=new mr(t.ctx,this.output,`gunfire`,D(E.machineGun)),this.ricochet=new mr(t.ctx,this.output,`ricochet`,D(E.ricochet)),this.crunch=new mr(t.ctx,this.output,`crush`,D(E.crush)),this.combustibleExplosion=new mr(t.ctx,this.output,`explosion`,D(E.combustibleExplosion),{queueWhileLoading:!0}),this.fireOutput=t.ctx.createGain(),this.fireOutput.gain.value=this.masterVolume,this.fireOutput.connect(t.ctx.destination),this.burningFire=new pr(t.ctx,this.fireOutput,`fire`,D(E.burningFire),{followLevel:!0}),this.horn.setPressed(this.hornPressed&&this.active),this.shutdown=new ar(t.ctx,this.output),t.ctx.state===`suspended`&&await t.ctx.resume(),this.disposed||this.stopping||(this.engineStartPromise=t.start(),await this.engineStartPromise,this.disposed))return;if(this.stopping){t.stop();return}this.ready=!0,this.applyPreset(!0),this.syncEngineVolume()}catch(e){if(this.disposed)return;this.shutdown?.dispose(),this.shutdown=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.ricochet?.dispose(),this.ricochet=null,this.crunch?.dispose(),this.crunch=null,this.combustibleExplosion?.dispose(),this.combustibleExplosion=null,this.burningFire?.dispose(),this.burningFire=null,this.ghostMode?.dispose(),this.ghostMode=null,this.fireOutput?.disconnect(),this.fireOutput=null,this.engine&&(Te(this.engine.ctx),Ie(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)}setGhostMode(e){e&&this.active&&!this.stopping&&!this.ghostMode&&this.engine&&this.output&&(this.ghostMode=new dr(this.engine.ctx,this.output,`ghost`,D(E.ghostMode))),this.ghostMode?.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;if(t-this.lastRicochetAt<_r.bulletRicochetMinimumGapSeconds||Math.random()>=_r.bulletRicochetChance)return;this.lastRicochetAt=t;let n=(Math.random()*2-1)*_r.bulletRicochetPitchSemitones;this.ricochet?.play(e,2**(n/12))}applyPreset(e=!1){this.engine&&!this.disposed&&(this.shutdown??=new ar(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),e||(this.engineAudible=null),this.syncEngineVolume())}setIdleSound(e){this.idleSound=e,this.syncEngineVolume()}syncEngineVolume(){if(!this.ready||!this.engine)return;let e=this.active&&!this.stopping&&(this.idleSound||this.driving);if(e===this.engineAudible)return;let t=e&&this.engineAudible!==!0;this.engineAudible=e,this.engine.setVolume(e?D(E.engine):0,t?.3:.05)}setActive(e){this.active!==e&&(this.active=e,this.syncEngineVolume(),e?this.horn?.setPressed(this.hornPressed&&!this.stopping):(this.tires?.silence(),this.horn?.silence(),this.crashes?.silence(),this.flamethrower?.silence(),this.boost?.silence(),this.rockets?.silence(),this.gunshot?.silence(),this.ricochet?.silence(),this.crunch?.silence(),this.combustibleExplosion?.silence(),this.burningFire?.silence(),this.ghostMode?.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.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.tires?.silence(),this.hornPressed=!1,this.horn?.silence(),this.crashes?.silence(),this.flamethrower?.silence(),this.boost?.silence(),this.rockets?.silence(),this.gunshot?.silence(),this.ricochet?.silence(),this.crunch?.silence(),this.combustibleExplosion?.silence(),this.burningFire?.silence(),this.ghostMode?.silence(),this.engine?.setThrottle(0),this.engine?.stop();let e=this.shutdown?.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.stopTimer!==null&&window.clearTimeout(this.stopTimer),this.stopTimer=null,this.shutdown?.dispose(),this.shutdown=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.ricochet?.dispose(),this.ricochet=null,this.crunch?.dispose(),this.crunch=null,this.combustibleExplosion?.dispose(),this.combustibleExplosion=null,this.burningFire?.dispose(),this.burningFire=null,this.ghostMode?.dispose(),this.ghostMode=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&&(Te(e.ctx),Ie(e.ctx)),this.engine=null,this.engineAudible=null,this.output?.disconnect(),this.output=null,this.appliedVolume=-1}};function yr(e,t,n,r=()=>!0){let i=e.getAttribute(t);if(i===null)return n;let a=Number(i);if(!i.trim()||!Number.isFinite(a)||!r(a))throw TypeError(`${t} must be a valid number`);return a}function br(e){let t=yr(e,`data-jr-entry-angle-rad`,0),n=yr(e,`data-jr-entry-distance-px`,185,e=>e>0),r=yr(e,`data-jr-entry-fade-fraction`,.5,e=>e>=0&&e<=1),i=yr(e,`data-jr-entry-steer`,.04,e=>Math.abs(e)<=1),a=yr(e,`data-jr-entry-delay-ms`,0,e=>e>=0),o=e.getAttribute(`data-jr-entry-speed-mps`)===null?void 0:yr(e,`data-jr-entry-speed-mps`,0,e=>e>0);return{target:e,delayMs:a,approach:{angleRad:t,distancePx:n,fadeFraction:r,...o?{initialSpeedMps:o}:{}},handbrake:{steer:i}}}function xr(e){let t=e.querySelector(`[data-jr-entry]`);return t?br(t):null}function Sr(e,t){let n=e.getBoundingClientRect(),r=n.left+window.scrollX+n.width/2,i=n.top+window.scrollY+n.height/2,a=r-(t?.xPx??r-185),o=i-(t?.yPx??i);return{target:e,approach:{angleRad:Math.hypot(a,o)>1?Math.atan2(o,a):-(t?.angleRad??0),distancePx:185,fadeFraction:.5},handbrake:{steer:.04}}}function Cr(e){let t=e.car;return t.rollingResistance*(4+2*t.handbrakeStrength*7)/e.body.mass}function wr(e,t){let n=e.car;return n.preset.handbrakeDecelerationMps2+n.preset.coastDecelerationMps2+Cr(e)*t*.75}function Tr(e,t,n){return t*t*n/(2*wr(e,t))}function Er(e,t,n){let r=0,i=60;for(let a=0;a<14;a++){let a=(r+i)/2;Tr(e,a,n)<t?r=a:i=a}return(r+i)/2}function Dr(e,t,n){let{handbrake:r,stopAt:i}=e,a={angleRad:e.approach?.angleRad??0,distancePx:e.approach?.distancePx??185,initialSpeedMps:e.approach?.initialSpeedMps,fadeFraction:e.approach?.fadeFraction??.5};if(![a.angleRad,a.distancePx,a.initialSpeedMps??1,a.fadeFraction,r?.steer??0,i?.x??.5,i?.y??.5,i?.offsetXPx??0,i?.offsetYPx??0,n].every(Number.isFinite)||a.distancePx<=0||a.initialSpeedMps!==void 0&&a.initialSpeedMps<=0||a.fadeFraction<0||a.fadeFraction>1||Math.abs(r?.steer??0)>1||n<=0)return null;let o;try{o=typeof e.target==`string`?document.querySelector(e.target):e.target}catch(e){if(e instanceof DOMException&&e.name===`SyntaxError`)return null;throw e}if(!o)return null;let s=`xPx`in o?y(o.xPx,o.yPx):(()=>{if(!o.isConnected)return null;let e=o.getBoundingClientRect();return y(e.left+window.scrollX+e.width*(i?.x??.5),e.top+window.scrollY+e.height*(i?.y??.5))})();if(!s||!Number.isFinite(s.x)||!Number.isFinite(s.y))return null;s.x+=i?.offsetXPx??0,s.y+=i?.offsetYPx??0;let c=y(Math.cos(a.angleRad),Math.sin(a.angleRad)),l=a.initialSpeedMps??Er(t,a.distancePx,n),u=l*l*n/(2*a.distancePx),d=v((u-wr(t,l))/te(t.car.preset),0,1),f=Cr(t),p=Math.max(.01,t.car.preset.handbrakeDecelerationMps2+t.car.preset.coastDecelerationMps2+d*te(t.car.preset)),m=f>0?Math.log1p(f*l/p)/f:l/p;return{destination:s,start:y(s.x-c.x*a.distancePx,s.y-c.y*a.distancePx),headingRad:-a.angleRad,velocity:y(c.x*l,-c.y*l),fadeDurationSeconds:m*a.fadeFraction,steer:r?.steer??0,serviceBrake:d}}var Or=class{fadeDurationSeconds;steer;serviceBrake;elapsedSeconds=0;done=!1;constructor(e,t,n=0){this.fadeDurationSeconds=e,this.steer=t,this.serviceBrake=n}get opacity(){return this.fadeDurationSeconds===0?1:v(this.elapsedSeconds/this.fadeDurationSeconds,0,1)}get complete(){return this.done}drive(e,t,n,r,i){return this.elapsedSeconds+=r,_(e.body.velocity)<.45||this.elapsedSeconds>3?(this.done=!0,{throttle:0,steer:0,action:!1,boost:!1}):{throttle:0,steer:this.steer,action:!0,brake:this.serviceBrake,boost:!1}}},kr=async()=>{let[{BrowserSessionCore:e},{Renderer:t}]=await Promise.all([ye(()=>import(`./runtime~browser-session-core-BAKqCyId.js`).then(e=>e.t),[],import.meta.url),be()]);return(...n)=>new e(n[0],n[1]??{},n[2]??{},{Renderer:t,installPageLayers:o})},Ar=`joy-ride:preferences:v1`;function jr(e){if(e!==void 0&&(!e||typeof e!=`object`||Array.isArray(e)))throw TypeError(`persist must be an object`);for(let[t,n]of Object.entries(e??{})){if(t!==`vehicle`&&t!==`audio`)throw TypeError(`Unknown persist field: ${t}`);if(typeof n!=`boolean`)throw TypeError(`persist.${t} must be boolean`)}return{vehicle:e?.vehicle??!0,audio:e?.audio??!0}}function Mr(){try{return globalThis.localStorage}catch{return}}function Nr(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0&&e<=1}function Pr(e=Mr()){try{let t=e?.getItem(Ar);if(!t)return{};let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))return{};let r=n,i=r.audio;return{...typeof r.vehicle==`string`&&r.vehicle.length?{vehicle:r.vehicle}:{},...i&&typeof i==`object`&&!Array.isArray(i)&&Nr(i.masterVolume)&&Nr(i.lastAudibleVolume)&&i.lastAudibleVolume>0?{audio:{masterVolume:i.masterVolume,lastAudibleVolume:i.lastAudibleVolume}}:{}}}catch{return{}}}function Fr(e,t=Mr()){try{t?.setItem(Ar,JSON.stringify({...Pr(t),...e}))}catch{}}function Ir(e,t){e&&Fr({vehicle:e},t)}function Lr(e,t){Nr(e.masterVolume)&&Nr(e.lastAudibleVolume)&&e.lastAudibleVolume>0&&Fr({audio:e},t)}export{ae as S,ye as _,kr as a,ce as b,Dr as c,Ge as d,O as f,xe as g,Ve as h,Ir as i,xr as l,Ue as m,jr as n,Or as o,We as p,Lr as r,Sr as s,Pr as t,vr as u,pe as v,le as x,S as y};