Death242 commited on
Commit
b06bcb0
·
verified ·
1 Parent(s): a2b07e0

Static site

Browse files
Files changed (8) hide show
  1. index.html +17 -16
  2. static/extras.js +174 -0
  3. static/goals.js +46 -44
  4. static/main.js +500 -492
  5. static/npc.js +3 -3
  6. static/race.js +1 -0
  7. static/style.css +13 -0
  8. static/world.js +6 -4
index.html CHANGED
@@ -8,7 +8,7 @@
8
  <meta name="theme-color" content="#10131b">
9
  <link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
  <link href="https://fonts.googleapis.com/css2?family=Unbounded:wght@500;800;900&family=Inter:wght@400;500;600;700&family=Noto+Kufi+Arabic:wght@700&display=swap" rel="stylesheet">
11
- <link rel="stylesheet" href="/static/style.css?v=1792865033">
12
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect width=%2764%27 height=%2764%27 rx=%2714%27 fill=%27%23050506%27/%3E%3Ccircle cx=%2732%27 cy=%2732%27 r=%2716%27 fill=%27none%27 stroke=%27%23fff%27 stroke-width=%275%27/%3E%3C/svg%3E">
13
  <script type="importmap">
14
  { "imports": {
@@ -107,12 +107,13 @@
107
  <div class="hud-tr">
108
  <canvas class="g-map" id="gMap" width="180" height="180" aria-label="Minimap (tap for GPS)"></canvas>
109
  <div class="g-btns"><button class="pill solid" id="gFly">Fly</button><button class="pill" id="gMenuBtn" aria-haspopup="dialog">☰ Menu</button></div>
110
- <div class="chips" id="gChips"></div>
111
  <div class="g-players" id="gPlayers"></div>
112
  </div>
113
  <div class="g-trophy" id="gTrophy" aria-live="polite"></div>
114
  <div class="hud-top">
115
  <div class="g-race" id="gRace" hidden></div>
 
116
  <div class="g-gps" id="gGps"></div>
117
  <div class="g-hint" id="gHint"></div>
118
  <div class="g-target"><i id="gArrow">&#11014;</i><span id="gTgt"></span></div>
@@ -142,13 +143,14 @@
142
  <section><h4>Vehicle</h4><div class="tiles">
143
  <button class="tile" data-veh="car"><b>🚗</b>Car</button><button class="tile" data-veh="plane"><b>✈️</b>Plane</button><button class="tile" data-veh="heli"><b>🚁</b>Helicopter</button><button class="tile" data-veh="boat"><b>🚤</b>Boat</button><button class="tile" id="gGarage"><b>🔧</b>Garage</button></div></section>
144
  <section><h4>Go somewhere</h4><div class="tiles">
145
- <button class="tile" id="gGpsBtn"><b>🧭</b>GPS</button><button class="tile" id="gAuto"><b>🤖</b>Autopilot</button><button class="tile" id="gFuelNav"><b>⛽</b>Nearest fuel</button><button class="tile" id="gNetBtn"><b>🌐</b>Online</button></div></section>
146
  <section><h4>World</h4><div class="tiles">
147
  <button class="tile" id="gTime"><b>🌗</b>Time of day</button><button class="tile" id="gView"><b>🎥</b>Front seat</button><button class="tile" id="gPhoto"><b>📷</b>Photo mode</button><button class="tile" id="gHorn"><b>📯</b>Horn</button><button class="tile" id="gWeather"><b>☀️</b>Weather</button><button class="tile" id="gRadio"><b>🎵</b>Radio</button></div></section>
148
  <section><h4>Settings</h4>
149
  <label class="set">Graphics<span class="seg" data-set="q"><button data-v="low">Low</button><button data-v="medium">Medium</button><button data-v="high">High</button><button data-v="ultra">Ultra</button></span></label>
150
  <label class="set">Look speed<input type="range" id="gSens" min="0.4" max="2.5" step="0.1"></label>
151
  <label class="set">Auto gas<span class="seg" data-set="autogas"><button data-v="off">Off</button><button data-v="on">On</button></span></label>
 
152
  <label class="set">Touch steering<span class="seg" data-set="steer"><button data-v="stick">Joystick</button><button data-v="buttons">Buttons</button></span></label>
153
  </section>
154
  <section class="wide"><h4>Challenges</h4><div class="goals" id="gGoals"></div></section>
@@ -161,18 +163,17 @@
161
  <div class="pad-l"><button data-pad="left" aria-label="Left">&#9664;</button><button data-pad="right" aria-label="Right">&#9654;</button></div>
162
  <div class="pad-r"><button data-pad="nitro" class="nos">Nitro</button><button data-pad="drift" class="ground">Drift</button><button data-pad="brake">Brake</button><button data-pad="gas" class="big">Gas</button><button data-pad="down" class="air">Down</button><button data-pad="up" class="big air">Up</button></div>
163
  </div>
164
- <div class="g-card" id="gReady">
165
- <h2>Welcome to VOID City</h2>
166
- <ol>
167
- <li><b>Drive:</b> <kbd>W</kbd> <kbd>A</kbd> <kbd>S</kbd> <kbd>D</kbd> or the arrows. <kbd>Space</kbd> handbrake to drift, <kbd>Shift</kbd> nitro. Thousands of cars, cabs, buses and people.</li>
168
- <li><b>Smash:</b> hit traffic faster than it is going and it breaks apart. Anything faster or heavier than you does the damage. Hit a wall hard and you get hurt too.</li>
169
- <li><b>Fly:</b> <kbd>F</kbd>. Slow, the thrusters hover (<kbd>Space</kbd> up, <kbd>Q</kbd> down). Fast, the wings fly for real: <kbd>A</kbd>/<kbd>D</kbd> bank to turn, <kbd>Space</kbd>/<kbd>Q</kbd> pitch, too slow and it stalls.</li>
170
- <li><b>Stunts &amp; missions:</b> the loop and ramps, gold rings in the sky, near misses, drifts, and green pads on the park lawn and skyscraper rooftops.</li>
171
- </ol>
172
- <ol start="5"><li><b>Police, races, online:</b> smash cars and the police come for you (lose them or get busted). Drive into a 🏁 marker and press <kbd>Enter</kbd> to race. Online plays with real people, with voice chat.</li>
173
- <li><b>GPS &amp; autopilot:</b> <kbd>M</kbd> or tap the map to pick a place, <kbd>O</kbd> autopilot drives (or flies) you there. <kbd>L</kbd> lands on a glide slope.</li></ol>
174
- <p class="small"><kbd>C</kbd> camera · move the mouse (or drag on a phone) to look around · <kbd>G</kbd> garage · <kbd>T</kbd> day/night · <kbd>H</kbd> horn · <kbd>P</kbd> photo mode · <kbd>R</kbd> reset · drag to look around · gamepads work too.</p>
175
- <button class="pill solid" id="gGo">Start</button>
176
  <div class="small" id="gBest"></div>
177
  </div>
178
  <div class="g-card" id="gOver" hidden>
@@ -200,6 +201,6 @@
200
  <div id="toast" role="status"></div>
201
  <noscript><p style="position:fixed;inset:auto 0 0;padding:16px;background:#111;color:#fff;text-align:center">VOID needs JavaScript for the 3D car.</p></noscript>
202
  <script src="/static/hub.js" data-app="void" defer></script>
203
- <script type="module" src="/static/main.js?v=1792865033"></script>
204
  </body>
205
  </html>
 
8
  <meta name="theme-color" content="#10131b">
9
  <link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
  <link href="https://fonts.googleapis.com/css2?family=Unbounded:wght@500;800;900&family=Inter:wght@400;500;600;700&family=Noto+Kufi+Arabic:wght@700&display=swap" rel="stylesheet">
11
+ <link rel="stylesheet" href="/static/style.css?v=1792906818">
12
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 64 64%27%3E%3Crect width=%2764%27 height=%2764%27 rx=%2714%27 fill=%27%23050506%27/%3E%3Ccircle cx=%2732%27 cy=%2732%27 r=%2716%27 fill=%27none%27 stroke=%27%23fff%27 stroke-width=%275%27/%3E%3C/svg%3E">
13
  <script type="importmap">
14
  { "imports": {
 
107
  <div class="hud-tr">
108
  <canvas class="g-map" id="gMap" width="180" height="180" aria-label="Minimap (tap for GPS)"></canvas>
109
  <div class="g-btns"><button class="pill solid" id="gFly">Fly</button><button class="pill" id="gMenuBtn" aria-haspopup="dialog">☰ Menu</button></div>
110
+ <div class="chips" id="gChips"></div><div class="chips"><span id="gCoins">🪙 0/40</span></div>
111
  <div class="g-players" id="gPlayers"></div>
112
  </div>
113
  <div class="g-trophy" id="gTrophy" aria-live="polite"></div>
114
  <div class="hud-top">
115
  <div class="g-race" id="gRace" hidden></div>
116
+ <div class="g-job" id="gJob" hidden></div>
117
  <div class="g-gps" id="gGps"></div>
118
  <div class="g-hint" id="gHint"></div>
119
  <div class="g-target"><i id="gArrow">&#11014;</i><span id="gTgt"></span></div>
 
143
  <section><h4>Vehicle</h4><div class="tiles">
144
  <button class="tile" data-veh="car"><b>🚗</b>Car</button><button class="tile" data-veh="plane"><b>✈️</b>Plane</button><button class="tile" data-veh="heli"><b>🚁</b>Helicopter</button><button class="tile" data-veh="boat"><b>🚤</b>Boat</button><button class="tile" id="gGarage"><b>🔧</b>Garage</button></div></section>
145
  <section><h4>Go somewhere</h4><div class="tiles">
146
+ <button class="tile" id="gGpsBtn"><b>🧭</b>GPS</button><button class="tile" id="gAuto"><b>🤖</b>Autopilot</button><button class="tile" id="gFuelNav"><b>⛽</b>Nearest fuel</button><button class="tile" id="gTaxi"><b>🚕</b>Taxi job</button><button class="tile" id="gNetBtn"><b>🌐</b>Online</button></div></section>
147
  <section><h4>World</h4><div class="tiles">
148
  <button class="tile" id="gTime"><b>🌗</b>Time of day</button><button class="tile" id="gView"><b>🎥</b>Front seat</button><button class="tile" id="gPhoto"><b>📷</b>Photo mode</button><button class="tile" id="gHorn"><b>📯</b>Horn</button><button class="tile" id="gWeather"><b>☀️</b>Weather</button><button class="tile" id="gRadio"><b>🎵</b>Radio</button></div></section>
149
  <section><h4>Settings</h4>
150
  <label class="set">Graphics<span class="seg" data-set="q"><button data-v="low">Low</button><button data-v="medium">Medium</button><button data-v="high">High</button><button data-v="ultra">Ultra</button></span></label>
151
  <label class="set">Look speed<input type="range" id="gSens" min="0.4" max="2.5" step="0.1"></label>
152
  <label class="set">Auto gas<span class="seg" data-set="autogas"><button data-v="off">Off</button><button data-v="on">On</button></span></label>
153
+ <label class="set">Living city (day/night + weather change)<span class="seg" data-set="cycle"><button data-v="off">Off</button><button data-v="on">On</button></span></label>
154
  <label class="set">Touch steering<span class="seg" data-set="steer"><button data-v="stick">Joystick</button><button data-v="buttons">Buttons</button></span></label>
155
  </section>
156
  <section class="wide"><h4>Challenges</h4><div class="goals" id="gGoals"></div></section>
 
163
  <div class="pad-l"><button data-pad="left" aria-label="Left">&#9664;</button><button data-pad="right" aria-label="Right">&#9654;</button></div>
164
  <div class="pad-r"><button data-pad="nitro" class="nos">Nitro</button><button data-pad="drift" class="ground">Drift</button><button data-pad="brake">Brake</button><button data-pad="gas" class="big">Gas</button><button data-pad="down" class="air">Down</button><button data-pad="up" class="big air">Up</button></div>
165
  </div>
166
+ <div class="g-card g-welcome" id="gReady">
167
+ <h2>VOID City</h2>
168
+ <p class="sub">Drive, fly, smash, race. Everything else is in the ☰ Menu.</p>
169
+ <div class="tips">
170
+ <div><b>🚗</b><span><kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> drive · <kbd>Space</kbd> drift · <kbd>Shift</kbd> nitro</span></div>
171
+ <div><b>✈️</b><span><kbd>F</kbd> fly · <kbd>Space</kbd>/<kbd>Q</kbd> up/down · <kbd>L</kbd> land</span></div>
172
+ <div><b>🚕</b><span><kbd>J</kbd> taxi jobs · <kbd>Enter</kbd> at a 🏁 to race</span></div>
173
+ <div><b>🪙</b><span>40 hidden coins, 14 challenges, police, online</span></div>
174
+ </div>
175
+ <p class="small touch-only">On a phone: joystick left, pedals right, drag anywhere to look.</p>
176
+ <button class="pill solid big-go" id="gGo">Start driving</button>
 
177
  <div class="small" id="gBest"></div>
178
  </div>
179
  <div class="g-card" id="gOver" hidden>
 
201
  <div id="toast" role="status"></div>
202
  <noscript><p style="position:fixed;inset:auto 0 0;padding:16px;background:#111;color:#fff;text-align:center">VOID needs JavaScript for the 3D car.</p></noscript>
203
  <script src="/static/hub.js" data-app="void" defer></script>
204
+ <script type="module" src="/static/main.js?v=1792906818"></script>
205
  </body>
206
  </html>
static/extras.js ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Taxi jobs and hidden coins.
2
+ // Taxi: press J (or Menu → Taxi job). Passengers wave from the kerb near you; stop next to one and they hop in,
3
+ // the GPS shows where they're going, and the fare drops the longer you take. Back-to-back fares build a streak.
4
+ // Coins: 40 spinning VOID coins hidden on rooftops, piers, the bridge towers and round the park; found ones stay found.
5
+ import * as THREE from "three";
6
+ import { GRID } from "./city.js";
7
+
8
+ const store = { get(k) { try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } }, set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch { } } };
9
+ const fmt = t => `${Math.floor(t / 60)}:${String(Math.floor(t % 60)).padStart(2, "0")}`;
10
+ const ord = n => n + (n % 100 > 10 && n % 100 < 14 ? "th" : ["th", "st", "nd", "rd"][n % 10] || "th");
11
+
12
+ export function createExtras(W, api, nav, sound) {
13
+ const { scene } = W, $ = id => document.getElementById(id);
14
+ let sd = 77; const rnd = () => (sd = (sd * 16807) % 2147483647) / 2147483647;
15
+
16
+ // ---- passengers: a little figure with a yellow beacon ----
17
+ const personMat = new THREE.MeshStandardMaterial({ color: 0x3060c0, roughness: .7 }), skin = new THREE.MeshStandardMaterial({ color: 0xd9a07a, roughness: .7 });
18
+ const beaconMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(0xffd23d).multiplyScalar(1.8), transparent: true, opacity: .35, depthWrite: false, toneMapped: false, side: THREE.DoubleSide });
19
+ const fig = () => { const g = new THREE.Group(); const b = new THREE.Mesh(new THREE.CylinderGeometry(.25, .3, 1.2, 10).translate(0, .9, 0), personMat); const h = new THREE.Mesh(new THREE.SphereGeometry(.17, 12, 8).translate(0, 1.7, 0), skin); const arm = new THREE.Mesh(new THREE.BoxGeometry(.1, .6, .1).translate(0, .3, 0), personMat); arm.position.set(0, 1.35, .3); arm.rotation.x = -2.6; g.add(b, h, arm); const beam = new THREE.Mesh(new THREE.CylinderGeometry(1.4, 1.4, 30, 16, 1, true).translate(0, 15, 0), beaconMat); g.add(beam); g.userData.arm = arm; scene.add(g); return g; };
20
+ const waiting = [fig(), fig(), fig()], dropMark = new THREE.Mesh(new THREE.CylinderGeometry(5, 5, 40, 24, 1, true).translate(0, 20, 0), new THREE.MeshBasicMaterial({ color: new THREE.Color(0x3dff8a).multiplyScalar(1.6), transparent: true, opacity: .22, depthWrite: false, toneMapped: false, side: THREE.DoubleSide }));
21
+ scene.add(dropMark); dropMark.visible = false; waiting.forEach(w => w.visible = false);
22
+ const kerb = (x0, z0, rMin, rMax) => { // a sidewalk spot rMin..rMax metres away
23
+ for (let t = 0; t < 40; t++) {
24
+ const a = rnd() * 6.28, r = rMin + rnd() * (rMax - rMin); let x = x0 + Math.cos(a) * r, z = z0 + Math.sin(a) * r;
25
+ const i = Math.round((x - GRID.X0) / GRID.AV), j = Math.round((z - GRID.Z0) / GRID.ST);
26
+ if (i < 0 || i >= GRID.NX || j < 0 || j >= GRID.NZ) continue;
27
+ if (rnd() < .5) x = GRID.ax(i) + (GRID.avW(i) / 2 + 2) * (rnd() < .5 ? 1 : -1); else z = GRID.sz(j) + (GRID.stW(j) / 2 + 2) * (rnd() < .5 ? 1 : -1);
28
+ if (api.hitBox(x, z, .5, 1.2) || api.isWater(x, z)) continue;
29
+ return [x, z];
30
+ }
31
+ return null;
32
+ };
33
+ const J = { on: false, fare: null, streak: 0, t: 0, earned: 0 };
34
+ function placeWaiting(p) { for (const w of waiting) { const s = kerb(p.x, p.z, 60, 260); if (s) { w.position.set(s[0], 0, s[1]); w.visible = true; } } }
35
+ function toggle(on = !J.on) {
36
+ const p = api.state; if (!p) return;
37
+ J.on = on; J.fare = null; dropMark.visible = false;
38
+ if (on) { placeWaiting(p); api.say("🚕 Taxi: pick up a passenger (yellow beams). J to stop", 4); }
39
+ else { waiting.forEach(w => w.visible = false); if (nav.dest && nav.dest.taxi) nav.setDest(null); api.say(J.earned ? `🚕 Shift over: $${J.earned} earned` : "🚕 Taxi off", 3); J.earned = 0; J.streak = 0; }
40
+ $("gJob").hidden = !on;
41
+ }
42
+ addEventListener("keydown", e => { if (e.code === "KeyJ" && api.active() && !e.repeat) toggle(); });
43
+
44
+ // ---- coins ----
45
+ const COINS = [], got = new Set(store.get("void.coins") || []);
46
+ {
47
+ const spots = [];
48
+ for (const h of W.city.helipads.slice(0, 8)) spots.push([h.x + 4, h.y + 1.5, h.z]);
49
+ const roofs = W.buildings.filter(b => b.h > 12 && b.h < 60 && b.hw > 4).sort(() => rnd() - .5).slice(0, 14);
50
+ for (const b of roofs) spots.push([b.x, b.h + 1.5, b.z]);
51
+ for (const [x, y, z] of [[1210, 112, 15], [1570, 112, -15], [-1080, 1.5, -700 + 140 * 2], [-1080, 1.5, -700 + 140 * 7], [W.city.lake.x, 1.5, W.city.lake.z + W.city.lake.rz + 8], [W.city.lawn.x, 1.5, W.city.lawn.z], [-2600, 1.5, 0], [1900, 1.5, 0], [134, 6, 4.2], [16, 18.5, 2]]) spots.push([x, y, z]);
52
+ while (spots.length < 40) { const s = kerb(rnd() * 1800 - 900, rnd() * 1300 - 650, 0, 40); if (s) spots.push([s[0], 1.5, s[1]]); }
53
+ const gold = new THREE.MeshStandardMaterial({ color: 0xffc23d, metalness: 1, roughness: .2, emissive: 0x6a4a00, emissiveIntensity: .6 });
54
+ const geo = new THREE.CylinderGeometry(.8, .8, .14, 28).rotateX(Math.PI / 2);
55
+ const vTex = (() => { const c = document.createElement("canvas"); c.width = c.height = 64; const g = c.getContext("2d"); g.fillStyle = "#ffc23d"; g.fillRect(0, 0, 64, 64); g.fillStyle = "#7a5200"; g.font = "900 44px sans-serif"; g.textAlign = "center"; g.fillText("V", 32, 48); const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t; })();
56
+ const face = new THREE.MeshStandardMaterial({ map: vTex, metalness: .8, roughness: .3, emissive: 0x6a4a00, emissiveIntensity: .5 });
57
+ spots.slice(0, 40).forEach(([x, y, z], k) => {
58
+ const m = new THREE.Mesh(geo, [gold, face, face]); m.position.set(x, y, z); scene.add(m);
59
+ const glow = new THREE.Mesh(new THREE.SphereGeometry(1.6, 12, 8), new THREE.MeshBasicMaterial({ color: new THREE.Color(0xffc23d).multiplyScalar(1.4), transparent: true, opacity: .12, depthWrite: false, toneMapped: false })); m.add(glow);
60
+ COINS.push({ id: k, m, x, y, z }); if (got.has(k)) m.visible = false;
61
+ });
62
+ }
63
+
64
+ // ---- boost pads: glowing chevrons on the avenues that kick you forward ----
65
+ const PADS = [];
66
+ {
67
+ const tex = (() => { const c = document.createElement("canvas"); c.width = 64; c.height = 128; const g = c.getContext("2d"); g.clearRect(0, 0, 64, 128); g.strokeStyle = "#3df5ff"; g.lineWidth = 9; g.lineCap = "round"; for (const y of [30, 70, 110]) { g.beginPath(); g.moveTo(10, y); g.lineTo(32, y - 22); g.lineTo(54, y); g.stroke(); } const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t; })();
68
+ const mat = new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false, toneMapped: false, color: new THREE.Color(1.8, 1.8, 1.8), polygonOffset: true, polygonOffsetFactor: -4 });
69
+ for (let k = 0; k < 14; k++) {
70
+ const axis = rnd() < .5, i = 1 + Math.floor(rnd() * (GRID.NX - 2)), j = 1 + Math.floor(rnd() * (GRID.NZ - 2));
71
+ const x = axis ? GRID.ax(i) + 4.5 : GRID.ax(i) + 60 + rnd() * 40, z = axis ? GRID.sz(j) + 25 + rnd() * 20 : GRID.sz(j) + 3, yaw = axis ? (rnd() < .5 ? Math.PI / 2 : -Math.PI / 2) : (rnd() < .5 ? 0 : Math.PI);
72
+ if (api.isWater(x, z) || api.hitBox(x, z, .5, 2)) continue;
73
+ const m = new THREE.Mesh(new THREE.PlaneGeometry(4, 8).rotateX(-Math.PI / 2), mat); m.position.set(x, .07, z); m.rotation.y = -yaw + Math.PI / 2; scene.add(m);
74
+ PADS.push({ x, z, yaw, t: 0 });
75
+ }
76
+ }
77
+ // ---- speed cameras: drive past and your speed is recorded; beat your best for points ----
78
+ const TRAPS = [], best = store.get("void.traps") || {};
79
+ {
80
+ const flashM = new THREE.MeshBasicMaterial({ color: new THREE.Color(1, 1, 1).multiplyScalar(4), toneMapped: false, transparent: true, opacity: 0 }), pole = new THREE.MeshStandardMaterial({ color: 0x2a2b30, metalness: .5, roughness: .4 }), boxM = new THREE.MeshStandardMaterial({ color: 0xf7c414, roughness: .5 });
81
+ const spots = [[GRID.ax(9), GRID.sz(3), "Midtown"], [GRID.ax(3), GRID.sz(15), "Park Ave"], [GRID.ax(11), GRID.sz(17), "Downtown"], [600, 0, "Broadway"], [GRID.ax(1), GRID.sz(6), "West Side"], [1400, 18, "Bridge"]];
82
+ spots.forEach(([x, z, name]) => {
83
+ const g = new THREE.Group(); g.position.set(x + 11, 0, z + 9); scene.add(g);
84
+ g.add(new THREE.Mesh(new THREE.CylinderGeometry(.12, .15, 5, 8).translate(0, 2.5, 0), pole)); const b = new THREE.Mesh(new THREE.BoxGeometry(.8, .5, .5), boxM); b.position.y = 5; g.add(b);
85
+ const f = new THREE.Mesh(new THREE.SphereGeometry(.18, 8, 6), flashM.clone()); f.position.set(-.45, 5, 0); g.add(f);
86
+ TRAPS.push({ x, z, name, f, cool: 0 });
87
+ });
88
+ }
89
+ // ---- sky traffic: an airliner crossing high up, a slow blimp with a glowing VOID sign ----
90
+ const plane = new THREE.Group(), blimp = new THREE.Group();
91
+ {
92
+ const w = new THREE.MeshStandardMaterial({ color: 0xe8e8ea, roughness: .4, metalness: .3 });
93
+ const body = new THREE.Mesh(new THREE.CylinderGeometry(1.6, 1.4, 34, 14).rotateZ(Math.PI / 2), w); plane.add(body);
94
+ const wing = new THREE.Mesh(new THREE.BoxGeometry(6, .3, 36), w); wing.position.x = 1; plane.add(wing);
95
+ const tail = new THREE.Mesh(new THREE.BoxGeometry(4, 6, .3), w); tail.position.set(-15, 3, 0); plane.add(tail);
96
+ for (const [z, c] of [[18, 0x22ff66], [-18, 0xff2233]]) { const l = new THREE.Mesh(new THREE.SphereGeometry(.4, 8, 6), new THREE.MeshBasicMaterial({ color: new THREE.Color(c).multiplyScalar(3), toneMapped: false })); l.position.set(1, 0, z); plane.add(l); }
97
+ scene.add(plane);
98
+ const env = new THREE.Mesh(new THREE.SphereGeometry(8, 24, 16), new THREE.MeshStandardMaterial({ color: 0x1a1a20, roughness: .5, metalness: .2 })); env.scale.set(3.4, 1, 1); blimp.add(env);
99
+ const signT = (() => { const c = document.createElement("canvas"); c.width = 512; c.height = 128; const g = c.getContext("2d"); g.fillStyle = "#000"; g.fillRect(0, 0, 512, 128); g.fillStyle = "#ff2a3a"; g.shadowColor = "#ff2a3a"; g.shadowBlur = 20; g.font = "900 86px Unbounded, Impact, sans-serif"; g.textAlign = "center"; g.fillText("VOID", 256, 100); const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t; })();
100
+ for (const s of [-1, 1]) { const p = new THREE.Mesh(new THREE.PlaneGeometry(30, 7.5), new THREE.MeshBasicMaterial({ map: signT, toneMapped: false, color: new THREE.Color(1.6, 1.6, 1.6) })); p.position.z = s * 8.1; p.rotation.y = s > 0 ? 0 : Math.PI; blimp.add(p); }
101
+ const gond = new THREE.Mesh(new THREE.BoxGeometry(8, 2.4, 3), new THREE.MeshStandardMaterial({ color: 0x3a3b40 })); gond.position.y = -8.5; blimp.add(gond);
102
+ scene.add(blimp);
103
+ }
104
+ let skyT = 0;
105
+
106
+ return {
107
+ toggle, pads: PADS, get job() { return J; }, coins: () => ({ got: got.size, total: COINS.length }),
108
+ sky(dt, time) {
109
+ skyT += dt;
110
+ const a = (skyT * .012) % (Math.PI * 2); plane.position.set(Math.cos(a) * 2600, 620, Math.sin(a) * 1600); plane.rotation.y = -Math.atan2(Math.cos(a) * 1600, -Math.sin(a) * 2600);
111
+ const b = (skyT * .004) % (Math.PI * 2); blimp.position.set(-200 + Math.cos(b) * 700, 230, -300 + Math.sin(b) * 500); blimp.rotation.y = -Math.atan2(Math.cos(b) * 500, -Math.sin(b) * 700);
112
+ },
113
+ boosts(dt) {
114
+ const p = api.state; if (!p || p.mode !== "drive" || p.y > 1) return;
115
+ for (const b of PADS) {
116
+ if (b.t > 0) { b.t -= dt; continue; }
117
+ if (Math.abs(p.x - b.x) < 2.6 && Math.abs(p.z - b.z) < 4.6) {
118
+ b.t = 1.5; const sp = Math.hypot(p.vel.x, p.vel.z) + 18; p.vel.set(Math.cos(p.yaw) * sp, 0, Math.sin(p.yaw) * sp); api.say("⚡ BOOST", 1.2); sound.whoosh && sound.whoosh();
119
+ }
120
+ }
121
+ for (const t of TRAPS) {
122
+ t.f.material.opacity = Math.max(0, t.f.material.opacity - dt * 3);
123
+ if (t.cool > 0) { t.cool -= dt; continue; }
124
+ if (Math.hypot(p.x - t.x, p.z - t.z) < 14) {
125
+ const kmh = Math.round(Math.hypot(p.vel.x, p.vel.z) * 3.6); if (kmh < 60) continue;
126
+ t.cool = 4; t.f.material.opacity = 1;
127
+ if (kmh > (best[t.name] || 0)) { best[t.name] = kmh; store.set("void.traps", best); api.addScore(Math.round(kmh * 2), `📸 ${t.name} speed camera: ${kmh} km/h (new best)`); }
128
+ else api.say(`📸 ${t.name}: ${kmh} km/h (best ${best[t.name]})`, 2.5);
129
+ }
130
+ }
131
+ },
132
+ update(dt, time) {
133
+ const p = api.state; if (!p || !p.started) return;
134
+ this.boosts(dt);
135
+ // coins
136
+ for (const c of COINS) {
137
+ if (!c.m.visible) continue;
138
+ c.m.rotation.y += dt * 2.4; c.m.position.y = c.y + Math.sin(time * 2 + c.id) * .2;
139
+ if (Math.abs(p.x - c.x) < 3 && Math.abs(p.z - c.z) < 3 && Math.abs(p.y + .6 - c.y) < 3.5) {
140
+ c.m.visible = false; got.add(c.id); store.set("void.coins", [...got]); api.addScore(250, `🪙 Coin ${got.size}/${COINS.length}`); sound.win();
141
+ }
142
+ }
143
+ $("gCoins").textContent = `🪙 ${got.size}/${COINS.length}`;
144
+ if (!J.on) return;
145
+ const sp = Math.hypot(p.vel.x, p.vel.z);
146
+ // waving passengers; the nearest one gets in when you stop beside it
147
+ for (const w of waiting) {
148
+ if (!w.visible) continue;
149
+ w.userData.arm.rotation.z = Math.sin(time * 6) * .4;
150
+ if (!J.fare && Math.hypot(p.x - w.position.x, p.z - w.position.z) < 9 && sp < 4 && p.mode === "drive") {
151
+ const d = kerb(w.position.x, w.position.z, 350, 1100); if (!d) continue;
152
+ const dist = Math.hypot(d[0] - w.position.x, d[1] - w.position.z);
153
+ const j = Math.round((d[1] - GRID.Z0) / GRID.ST), street = j === 10 ? "Broadway" : `${ord(Math.abs(j - 10) * 7 + 14)} St`;
154
+ J.fare = { x: d[0], z: d[1], t: dist / 11 + 25, max: 300 + Math.round(dist * .6), street };
155
+ waiting.forEach(o => o.visible = false); dropMark.position.set(d[0], 0, d[1]); dropMark.visible = true;
156
+ nav.setDest({ name: `🚕 ${street}`, x: d[0], z: d[1], taxi: true });
157
+ api.say(`🚕 "Take me to ${street}, quick!"`, 3); sound.pop();
158
+ }
159
+ }
160
+ if (J.fare) {
161
+ const f = J.fare; f.t -= dt;
162
+ const pay = Math.max(50, Math.round(f.max * Math.min(1, .35 + f.t / 40)));
163
+ $("gJob").textContent = `🚕 To ${f.street} · ${fmt(Math.max(0, f.t))} · $${pay}${J.streak > 1 ? ` · streak ×${J.streak}` : ""}`;
164
+ if (Math.hypot(p.x - f.x, p.z - f.z) < 12 && sp < 4) {
165
+ J.streak = f.t > 0 ? J.streak + 1 : 0; const total = pay + (J.streak > 1 ? J.streak * 100 : 0); J.earned += total;
166
+ api.addScore(total, `🚕 Fare $${total}${J.streak > 1 ? ` (streak ×${J.streak})` : ""}`); J.fare = null; dropMark.visible = false; if (nav.dest && nav.dest.taxi) nav.setDest(null); placeWaiting(p);
167
+ } else if (f.t < -20) { api.say("🚕 The passenger gave up and got out", 3); J.fare = null; J.streak = 0; dropMark.visible = false; if (nav.dest && nav.dest.taxi) nav.setDest(null); placeWaiting(p); }
168
+ } else {
169
+ $("gJob").textContent = `🚕 Find a passenger (yellow beams)${J.earned ? ` · $${J.earned} so far` : ""}`;
170
+ if (waiting.every(w => !w.visible || Math.hypot(p.x - w.position.x, p.z - w.position.z) > 600)) placeWaiting(p);
171
+ }
172
+ },
173
+ };
174
+ }
static/goals.js CHANGED
@@ -1,44 +1,46 @@
1
- // Challenges: twelve goals tracked from what you do (kept on this device), each worth a trophy and 1000 points.
2
- const store = { get(k) { try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } }, set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch { } } };
3
- export const GOALS = [
4
- { id: "speed", icon: "🏎️", name: "Speed demon", text: "Hit 300 km/h", stat: "top", need: 300 },
5
- { id: "smash", icon: "💥", name: "Wrecking ball", text: "Smash 25 cars", stat: "smashed", need: 25 },
6
- { id: "drift", icon: "🌀", name: "Drift king", text: "One drift worth 1500", stat: "drift", need: 1500 },
7
- { id: "air", icon: "✈️", name: "Frequent flyer", text: "Spend 5 minutes in the air", stat: "air", need: 300 },
8
- { id: "pads", icon: "🛬", name: "Rooftop lander", text: "Land on 3 helipads", stat: "pads", need: 3 },
9
- { id: "butter", icon: "🧈", name: "Butter", text: "Make a butter-smooth landing", stat: "butter", need: 1 },
10
- { id: "race", icon: "🏁", name: "Champion", text: "Win a race", stat: "wins", need: 1 },
11
- { id: "cops", icon: "🚓", name: "Getaway", text: "Escape the police", stat: "escapes", need: 1 },
12
- { id: "rings", icon: "💍", name: "Ring master", text: "Fly through 10 rings", stat: "rings", need: 10 },
13
- { id: "road", icon: "🛣️", name: "Road trip", text: "Travel 25 km", stat: "km", need: 25 },
14
- { id: "fuel", icon: "⛽", name: "Pit stop", text: "Fill up at a station", stat: "refuels", need: 1 },
15
- { id: "brooklyn", icon: "🌉", name: "Bridge and tunnel", text: "Cross the bridge to Brooklyn", stat: "brooklyn", need: 1 },
16
- ];
17
- export function createGoals(onDone) {
18
- const S = Object.assign({ top: 0, smashed: 0, drift: 0, air: 0, pads: 0, butter: 0, wins: 0, escapes: 0, rings: 0, km: 0, refuels: 0, brooklyn: 0, best: 0 }, store.get("void.stats") || {});
19
- const done = new Set(store.get("void.goals") || []);
20
- let saveT = 0, lastSmash = null, lastRings = null, lastFuel = null, pads = new Set();
21
- function check() { for (const g of GOALS) if (!done.has(g.id) && S[g.stat] >= g.need) { done.add(g.id); store.set("void.goals", [...done]); onDone(g); } }
22
- return {
23
- stats: S, done, GOALS,
24
- // words from the score feed tell us about races, escapes and landings
25
- note(why) {
26
- if (/1st/.test(why)) S.wins++; if (/got away/i.test(why)) S.escapes++; if (/Butter/.test(why)) S.butter++;
27
- if (/^Landed at (?!PARK)/.test(why)) S.pads++; if (/^Drift/.test(why)) { const n = +(why.match(/\d+/) || [0])[0]; }
28
- check();
29
- },
30
- drift(points) { S.drift = Math.max(S.drift, points); check(); },
31
- update(dt, st, speedKmh) {
32
- if (!st || !st.started) return;
33
- S.top = Math.max(S.top, speedKmh); S.km += speedKmh / 3600 * dt;
34
- if (st.mode === "air") S.air += dt;
35
- if (lastSmash != null && st.smashed > lastSmash) S.smashed += st.smashed - lastSmash; lastSmash = st.smashed;
36
- if (lastRings != null && st.rings > lastRings) S.rings += st.rings - lastRings; lastRings = st.rings;
37
- if (lastFuel != null && st.fuel - lastFuel > .02 && Math.hypot(st.vel.x, st.vel.z) < 4) { if (!st._fueling) { S.refuels++; st._fueling = true; } } else if (st.fuel < lastFuel) st._fueling = false;
38
- lastFuel = st.fuel;
39
- if (st.x > 1760 && Math.abs(st.z) < 900) S.brooklyn = 1;
40
- S.best = Math.max(S.best, st.score || 0);
41
- if ((saveT += dt) > 3) { saveT = 0; store.set("void.stats", S); check(); }
42
- },
43
- };
44
- }
 
 
 
1
+ // Challenges: twelve goals tracked from what you do (kept on this device), each worth a trophy and 1000 points.
2
+ const store = { get(k) { try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } }, set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch { } } };
3
+ export const GOALS = [
4
+ { id: "speed", icon: "🏎️", name: "Speed demon", text: "Hit 300 km/h", stat: "top", need: 300 },
5
+ { id: "smash", icon: "💥", name: "Wrecking ball", text: "Smash 25 cars", stat: "smashed", need: 25 },
6
+ { id: "drift", icon: "🌀", name: "Drift king", text: "One drift worth 1500", stat: "drift", need: 1500 },
7
+ { id: "air", icon: "✈️", name: "Frequent flyer", text: "Spend 5 minutes in the air", stat: "air", need: 300 },
8
+ { id: "pads", icon: "🛬", name: "Rooftop lander", text: "Land on 3 helipads", stat: "pads", need: 3 },
9
+ { id: "butter", icon: "🧈", name: "Butter", text: "Make a butter-smooth landing", stat: "butter", need: 1 },
10
+ { id: "race", icon: "🏁", name: "Champion", text: "Win a race", stat: "wins", need: 1 },
11
+ { id: "cops", icon: "🚓", name: "Getaway", text: "Escape the police", stat: "escapes", need: 1 },
12
+ { id: "rings", icon: "💍", name: "Ring master", text: "Fly through 10 rings", stat: "rings", need: 10 },
13
+ { id: "road", icon: "🛣️", name: "Road trip", text: "Travel 25 km", stat: "km", need: 25 },
14
+ { id: "fuel", icon: "⛽", name: "Pit stop", text: "Fill up at a station", stat: "refuels", need: 1 },
15
+ { id: "coins", icon: "🪙", name: "Collector", text: "Find 20 hidden coins", stat: "coins", need: 20 },
16
+ { id: "taxi", icon: "🚕", name: "Cabbie", text: "Complete 5 taxi fares", stat: "fares", need: 5 },
17
+ { id: "brooklyn", icon: "🌉", name: "Bridge and tunnel", text: "Cross the bridge to Brooklyn", stat: "brooklyn", need: 1 },
18
+ ];
19
+ export function createGoals(onDone) {
20
+ const S = Object.assign({ top: 0, smashed: 0, drift: 0, air: 0, pads: 0, butter: 0, wins: 0, escapes: 0, rings: 0, km: 0, refuels: 0, brooklyn: 0, best: 0, coins: 0, fares: 0 }, store.get("void.stats") || {});
21
+ const done = new Set(store.get("void.goals") || []);
22
+ let saveT = 0, lastSmash = null, lastRings = null, lastFuel = null, pads = new Set();
23
+ function check() { for (const g of GOALS) if (!done.has(g.id) && S[g.stat] >= g.need) { done.add(g.id); store.set("void.goals", [...done]); onDone(g); } }
24
+ return {
25
+ stats: S, done, GOALS,
26
+ // words from the score feed tell us about races, escapes and landings
27
+ note(why) {
28
+ if (/1st/.test(why)) S.wins++; if (/Fare \$/.test(why)) S.fares++; if (/got away/i.test(why)) S.escapes++; if (/Butter/.test(why)) S.butter++;
29
+ if (/^Landed at (?!PARK)/.test(why)) S.pads++; if (/^Drift/.test(why)) { const n = +(why.match(/\d+/) || [0])[0]; }
30
+ check();
31
+ },
32
+ drift(points) { S.drift = Math.max(S.drift, points); check(); },
33
+ update(dt, st, speedKmh) {
34
+ if (!st || !st.started) return;
35
+ S.top = Math.max(S.top, speedKmh); S.km += speedKmh / 3600 * dt;
36
+ if (st.mode === "air") S.air += dt;
37
+ if (lastSmash != null && st.smashed > lastSmash) S.smashed += st.smashed - lastSmash; lastSmash = st.smashed;
38
+ if (lastRings != null && st.rings > lastRings) S.rings += st.rings - lastRings; lastRings = st.rings;
39
+ if (lastFuel != null && st.fuel - lastFuel > .02 && Math.hypot(st.vel.x, st.vel.z) < 4) { if (!st._fueling) { S.refuels++; st._fueling = true; } } else if (st.fuel < lastFuel) st._fueling = false;
40
+ lastFuel = st.fuel;
41
+ if (st.x > 1760 && Math.abs(st.z) < 900) S.brooklyn = 1;
42
+ S.best = Math.max(S.best, st.score || 0);
43
+ if ((saveT += dt) > 3) { saveT = 0; store.set("void.stats", S); check(); }
44
+ },
45
+ };
46
+ }
static/main.js CHANGED
@@ -1,492 +1,500 @@
1
- // VOID: one WebGL canvas, three modes on top of a showroom home screen.
2
- // Watch: a 48 s film whose clock is the music. Play: drive it, fly it, land it. Build: paint it.
3
- import * as THREE from "three";
4
-
5
- const V = new URL(import.meta.url).search;
6
- const $ = id => document.getElementById(id);
7
- const setLoad = p => { $("ldbar").style.width = p + "%"; $("ldpct").textContent = Math.round(p); };
8
- setLoad(15);
9
- const [{ createWorld, clamp, lerp, smooth, frame, PAD_R, ZONES }, { buildCar, MODELS }, { addInterior, HEAD }, { Sound, BAR }, { createWatch, TOTAL, CHAPTERS }, { createGame }, { createLife }] = await Promise.all(
10
- ["world", "car", "interior", "sound", "watch", "game", "npc"].map(n => import(`./${n}.js${V}`)));
11
- const [{ createPolice }, { createRaces }, { createNet, EMOTES }, { createNav }, { createVehicles }, { createAtmos, WEATHERS }, { createGoals, GOALS }] = await Promise.all(["police", "race", "net", "nav", "vehicles", "atmos", "goals"].map(n => import(`./${n}.js${V}`)));
12
- setLoad(40);
13
-
14
- const COARSE = matchMedia("(pointer: coarse)").matches, REDUCED = matchMedia("(prefers-reduced-motion: reduce)").matches;
15
- const store = { get(k) { try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } }, set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch { } } };
16
- const W = await createWorld($("gl"), COARSE), { renderer, scene, camera, composer, bloom, camLight, fx } = W;
17
- setLoad(55);
18
-
19
- // the car you drive: a fixed root the game and the film move around, with the chosen model swapped inside it
20
- const carRoot = new THREE.Group(); scene.add(carRoot);
21
- const car = { group: carRoot, wheels: [] };
22
- const carMats = new Set();
23
- let inner = null;
24
- function useModel(id, force) {
25
- if (inner && inner.model === id && !force) return;
26
- if (inner) carRoot.remove(inner.group);
27
- inner = buildCar(id); carRoot.add(inner.group);
28
- for (const k of Object.keys(inner)) if (typeof inner[k] === "function") car[k] = inner[k];
29
- Object.assign(car, { wheels: inner.wheels, clip: car.clip || inner.clip, materials: inner.materials, model: id, name: inner.name });
30
- carMats.clear();
31
- inner.group.traverse(o => { if (o.isMesh) { o.castShadow = true; if (o.material && o.material.isMeshStandardMaterial) carMats.add(o.material); } });
32
- for (const m of carMats) { m.envMap = null; m.needsUpdate = true; } // the paint reflects the city capture (scene.environment) // phones skip the live cube and use the city reflection
33
- }
34
- // live reflections on the paint: a small cube camera that rides with the car
35
- const carEnv = new THREE.WebGLCubeRenderTarget(COARSE ? 64 : 128, { type: THREE.HalfFloatType, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter });
36
- const carCube = new THREE.CubeCamera(.5, 320, carEnv);
37
- for (const c of carCube.children) c.layers.set(0);
38
- camera.layers.enable(1); // layer 1: the crowds, seen by the main camera only
39
- let cubeN = 0;
40
- useModel((store.get("void.build3") || {}).model != null ? Object.keys(MODELS)[(store.get("void.build3") || {}).model] || "hydra" : "hydra");
41
- setLoad(80);
42
- const interior = addInterior(car, renderer);
43
- const sound = new Sound();
44
- const watch = createWatch(W, car, interior);
45
- const life = createLife(scene, W.roads, W.walkways, COARSE);
46
- const TIMES = ["night", "sunset", "day"];
47
- function cycleTime() { const k = TIMES[(TIMES.indexOf(W.timeOfDay) + 1) % 3]; W.setTime(k); store.set("void.time", k); toast({ night: "Night in the city", sunset: "Golden hour", day: "Daytime" }[k]); cubeN = 0; }
48
- let police, races, nav;
49
- const net = createNet();
50
- setInterval(() => { if (document.hidden) net.tick(.5, null); }, 500); // a hosting tab in the background still relays everyone
51
- // settings: graphics quality, look speed, auto gas, touch steering (kept on this device)
52
- const SET = Object.assign({ q: COARSE ? "medium" : "high", sens: 1, autogas: "off", steer: "stick", weather: "clear", radio: "score" }, store.get("void.settings") || {});
53
- const gameOpts = {
54
- garage: () => openGarage(true), cycleTime, hornType: () => build.horn, autoGas: () => SET.autogas === "on", onRepair: () => car.repair && car.repair(),
55
- onScore: (n, why) => { if (why === "Drift") goals.drift(n); goals.note(why); },
56
- onSmash: kind => police && police.event("smash", kind), policeClear: () => police && police.clear(),
57
- autopilot: (g, dt, over) => nav ? nav.controls(g, dt, over) : null, openGps: () => document.getElementById("gGpsBtn").click(),
58
- mapExtra(mx, g, MM) {
59
- const P = (x, z) => [(x - g.x) / MM, (z - g.z) / MM];
60
- if (nav && nav.pts.length > 1) { mx.strokeStyle = "#3dfcff"; mx.lineWidth = 3; mx.beginPath(); nav.pts.forEach(([x, z], k) => { const [a, b] = P(x, z); k ? mx.lineTo(a, b) : mx.moveTo(a, b); }); mx.stroke(); }
61
- if (police) for (const c of police.cops) if (c.on) { const [a, b] = P(c.x, c.z); mx.fillStyle = Math.sin(performance.now() / 90) > 0 ? "#ff3040" : "#3060ff"; mx.beginPath(); mx.arc(a, b, 4, 0, 7); mx.fill(); }
62
- if (races && races.race && races.race.next) { const [a, b] = P(races.race.next[0], races.race.next[2]); mx.strokeStyle = "#ffd23d"; mx.lineWidth = 3; mx.beginPath(); mx.arc(a, b, 7, 0, 7); mx.stroke(); }
63
- for (const r of remotes.values()) if (r.at) { const [a, b] = P(r.at.x, r.at.z); mx.fillStyle = "#c07dff"; mx.beginPath(); mx.arc(a, b, 4.5, 0, 7); mx.fill(); }
64
- mx.font = "bold 12px sans-serif"; mx.textAlign = "center"; for (const st of W.city.stations) { const [a, b] = P(st.x, st.z); if (Math.abs(a) < 90 && Math.abs(b) < 90) { mx.save(); mx.translate(a, b); mx.rotate(g.yaw + Math.PI / 2); mx.fillText("⛽", 0, 4); mx.restore(); } }
65
- },
66
- };
67
- const game = createGame(W, car, sound, life, gameOpts);
68
- const vehicles = createVehicles(scene, game.api, W); gameOpts.vehicles = vehicles;
69
- const atmos = createAtmos(W, sound, COARSE);
70
- // trophies: a banner slides in at the top when a challenge is done
71
- const goals = createGoals(gl => { const t = document.getElementById("gTrophy"); t.innerHTML = `<b>${gl.icon}</b><div><span>Challenge complete</span>${gl.name}<em>+1000</em></div>`; t.classList.remove("on"); void t.offsetWidth; t.classList.add("on"); if (game.state) { game.state.score += 1000; } sound.win(); renderGoals(); });
72
- function renderGoals() {
73
- const S = goals.stats;
74
- document.getElementById("gGoals").innerHTML = GOALS.map(g => { const v = Math.min(1, (S[g.stat] || 0) / g.need), ok = goals.done.has(g.id); return `<div class="goal${ok ? " ok" : ""}"><b>${g.icon}</b><div><span>${g.name}</span><small>${g.text}</small><i style="--v:${v}"></i></div>${ok ? "🏆" : `<em>${Math.floor(v * 100)}%</em>`}</div>`; }).join("");
75
- document.getElementById("gStatsRow").innerHTML = `<div><b>${(S.best || 0).toLocaleString()}</b><span>Best score</span></div><div><b>${Math.round(S.top)}</b><span>Top km/h</span></div><div><b>${S.km.toFixed(1)}</b><span>km travelled</span></div><div><b>${goals.done.size}/${GOALS.length}</b><span>Trophies</span></div>`;
76
- }
77
- const WX_ICON = { clear: "☀️ Clear", rain: "🌧 Rain", storm: "⛈ Storm", fog: "🌫 Fog", snow: "❄️ Snow" }, RADIO = { score: "🎵 VOID Score", voidfm: "📻 VOID FM", off: "🔇 Radio off" };
78
- function chips() { document.getElementById("gChips").innerHTML = `<span>${{ night: "🌙", sunset: "🌇", day: "☀️" }[W.timeOfDay]} ${W.timeOfDay}</span><span>${WX_ICON[atmos.weather]}</span>`; document.getElementById("gWeather").innerHTML = `<b>${WX_ICON[SET.weather].split(" ")[0]}</b>${WX_ICON[SET.weather].split(" ").slice(1).join(" ")}`; document.getElementById("gRadio").innerHTML = `<b>${RADIO[SET.radio].split(" ")[0]}</b>${RADIO[SET.radio].split(" ").slice(1).join(" ")}`; }
79
- document.getElementById("gWeather").onclick = () => { SET.weather = WEATHERS[(WEATHERS.indexOf(SET.weather) + 1) % WEATHERS.length]; atmos.setWeather(SET.weather); store.set("void.settings", SET); chips(); toast(WX_ICON[SET.weather]); };
80
- document.getElementById("gRadio").onclick = () => { const k = Object.keys(RADIO); SET.radio = k[(k.indexOf(SET.radio) + 1) % k.length]; if (!sound.on) setSound(true); sound.setRadio(SET.radio); store.set("void.settings", SET); chips(); toast(RADIO[SET.radio]); };
81
- // ---------- the menu (☰ or Esc): everything that isn't driving lives here ----------
82
- const menuEl = document.getElementById("gMenu");
83
- function menu(open) {
84
- if (open == null) open = menuEl.hidden;
85
- menuEl.hidden = !open; document.body.classList.toggle("g-menu-open", open); if (open) { renderGoals(); chips(); }
86
- if (open && document.pointerLockElement) document.exitPointerLock();
87
- if (!net.online()) game.pause(open);
88
- }
89
- document.getElementById("gMenuBtn").onclick = () => menu(true);
90
- document.getElementById("gMenuClose").onclick = () => menu(false);
91
- document.getElementById("gExit").onclick = () => { menu(false); go("home"); };
92
- menuEl.addEventListener("click", e => { const t = e.target.closest(".tile"); if (t && !t.closest(".set")) setTimeout(() => menu(false), 60); if (e.target === menuEl) menu(false); });
93
- menuEl.querySelectorAll("[data-veh]").forEach(b => b.onclick = () => game.api.setVehicle(b.dataset.veh));
94
- document.getElementById("gFuelNav").onclick = () => { const st = game.state; if (!st) return; const best = W.city.stations.slice().sort((a, b) => Math.hypot(a.x - st.x, a.z - st.z) - Math.hypot(b.x - st.x, b.z - st.z))[0]; nav.setDest({ name: "⛽ Fuel station", x: best.x, z: best.z }); };
95
- function applySettings(save = true) {
96
- for (const seg of menuEl.querySelectorAll(".seg[data-set]")) for (const b of seg.children) b.classList.toggle("on", SET[seg.dataset.set] === b.dataset.v);
97
- document.getElementById("gSens").value = SET.sens; game.api.sens = +SET.sens;
98
- document.body.classList.toggle("steer-buttons", SET.steer === "buttons");
99
- const cap = W.setQuality(SET.q); perf.max = cap; perf.pr = Math.min(perf.pr, cap); if (renderer.getPixelRatio() > cap) { renderer.setPixelRatio(cap); composer.setPixelRatio(cap); lastW = 0; resize(); }
100
- if (save) store.set("void.settings", SET);
101
- }
102
- menuEl.querySelectorAll(".seg[data-set]").forEach(seg => seg.addEventListener("click", e => { const b = e.target.closest("button"); if (!b) return; e.preventDefault(); SET[seg.dataset.set] = b.dataset.v; if (seg.dataset.set === "q") { perf.pr = W.QUALITY[b.dataset.v].pr; perf.down = 0; } applySettings();
103
- atmos.setWeather(SET.weather); }));
104
- document.getElementById("gSens").addEventListener("input", e => { SET.sens = +e.target.value; applySettings(); });
105
- // the touch joystick: drag the knob; left/right steers, up/down pitches when flying
106
- {
107
- const st = document.getElementById("gStick"), knob = st.querySelector("i"); let id = null, cx = 0, cy = 0;
108
- const set = (x, y) => { const r = st.clientWidth / 2 - 10, l = Math.min(1, Math.hypot(x, y) / r), a = Math.atan2(y, x), kx = Math.cos(a) * l * r, ky = Math.sin(a) * l * r; knob.style.transform = `translate(${kx}px, ${ky}px)`; game.api.setStick(kx / r, ky / r); };
109
- st.addEventListener("pointerdown", e => { id = e.pointerId; const b = st.getBoundingClientRect(); cx = b.left + b.width / 2; cy = b.top + b.height / 2; try { st.setPointerCapture(id); } catch { } set(e.clientX - cx, e.clientY - cy); e.preventDefault(); });
110
- st.addEventListener("pointermove", e => { if (e.pointerId === id) set(e.clientX - cx, e.clientY - cy); });
111
- const end = e => { if (e.pointerId !== id) return; id = null; knob.style.transform = ""; game.api.setStick(0, 0); };
112
- st.addEventListener("pointerup", end); st.addEventListener("pointercancel", end);
113
- }
114
- // headlights that light the road at night
115
- const heads = new THREE.SpotLight(0xfff1d6, 0, 70, .55, .6, 1.2); heads.position.set(2.2, .7, 0); heads.target.position.set(18, -1.5, 0); carRoot.add(heads, heads.target);
116
- police = createPolice(scene, game.api, sound, life);
117
- races = createRaces(scene, game.api, sound, W.canvasTex, net);
118
- nav = createNav(scene, game.api, W, ZONES, races.starts);
119
-
120
- // ---------- online: other real players' cars, name tags, emotes, proximity voice ----------
121
- const remotes = new Map();
122
- const tagTex = (text, col = "#ffffff") => W.canvasTex(512, 96, (g, w, h) => { g.fillStyle = "rgba(0,0,0,.55)"; g.fillRect(0, 0, w, h); g.fillStyle = col; g.font = "800 50px Inter, sans-serif"; g.textAlign = "center"; g.fillText(text, w / 2, 66); });
123
- function remoteFor(p) {
124
- let r = remotes.get(p.id);
125
- const model = Object.keys(MODELS)[p.model | 0] || "hydra";
126
- if (r && r.model !== model) { scene.remove(r.root); remotes.delete(p.id); r = null; }
127
- if (!r) {
128
- const c = buildCar(model), root = new THREE.Group(); root.add(c.group); c.setReveal(1); c.setThrust(0, 0, 0, 0); c.setWings(0, 0);
129
- c.group.traverse(o => { if (o.isMesh) o.castShadow = true; });
130
- const tag = new THREE.Sprite(new THREE.SpriteMaterial({ map: tagTex(p.name), depthTest: false, toneMapped: false })); tag.scale.set(5, .95, 1); tag.position.y = 2.6; root.add(tag);
131
- const emo = new THREE.Sprite(new THREE.SpriteMaterial({ map: tagTex(""), depthTest: false, toneMapped: false })); emo.scale.set(6, 1.15, 1); emo.position.y = 3.8; emo.visible = false; root.add(emo);
132
- scene.add(root); r = { root, car: c, tag, emo, model, name: p.name, paint: null, emoT: 0 }; remotes.set(p.id, r);
133
- }
134
- if (r.name !== p.name) { r.name = p.name; r.tag.material.map = tagTex(p.name); }
135
- if (p.paint && r.paint !== p.paint) { r.paint = p.paint; r.car.setPaint(p.paint); }
136
- return r;
137
- }
138
- net.on("change", () => { for (const id of [...remotes.keys()]) if (!net.players().some(p => p.id === id)) { scene.remove(remotes.get(id).root); remotes.delete(id); } renderPlayers(); });
139
- net.on("status", t => { document.getElementById("gNetStatus").textContent = t; document.getElementById("gNetBtn").classList.toggle("on", net.online()); });
140
- net.on("mic", on => { const b = document.getElementById("gMic"); b.classList.toggle("on", on); b.textContent = on ? "🎙 Mic on" : "🎙 Voice chat"; });
141
- net.on("emote", (m, from) => { const r = remotes.get(from), e = EMOTES[m.e | 0]; if (r) { r.emo.material.map = tagTex(e, "#ffd23d"); r.emo.visible = true; r.emoT = 4; } feed(`${net.nameOf(from)}: ${e}`); });
142
- function feed(t) { const f = document.getElementById("gFeed"); const d = document.createElement("div"); d.textContent = t; f.prepend(d); setTimeout(() => d.remove(), 7000); while (f.children.length > 5) f.lastChild.remove(); }
143
- function renderPlayers() { document.getElementById("gPlayers").innerHTML = net.online() ? [`<b>${net.name} (you)</b>`, ...net.players().map(p => `<span>${p.vc ? "🎙 " : ""}${p.name}</span>`)].join("") : ""; }
144
- {
145
- const $ = id => document.getElementById(id), panel = $("gNetPanel");
146
- $("gNetName").value = store.get("void.name") || "";
147
- $("gNetBtn").onclick = () => { panel.hidden = !panel.hidden; };
148
- $("gNetClose").onclick = () => panel.hidden = true;
149
- const go = room => { const nm = $("gNetName").value; store.set("void.name", nm); net.join(room, nm); panel.hidden = true; };
150
- $("gNetPublic").onclick = () => go("public-1");
151
- $("gNetCreate").onclick = () => { const code = Math.random().toString(36).slice(2, 7); $("gNetCode").value = code; go("room-" + code); toast(`Room code: ${code}. Tell your friends!`); };
152
- $("gNetJoin").onclick = () => { const code = $("gNetCode").value.trim().toLowerCase(); if (code) go("room-" + code); };
153
- $("gNetLeave").onclick = () => { net.leave(); panel.hidden = true; };
154
- $("gMic").onclick = () => net.setMic(!net.mic);
155
- $("gEmotes").innerHTML = EMOTES.map((e, k) => `<button class="pill" data-e="${k}">${e}</button>`).join("");
156
- $("gEmotes").onclick = ev => { const b = ev.target.closest("[data-e]"); if (!b || !net.online()) return; net.send({ t: "emote", e: +b.dataset.e }); feed(`You: ${EMOTES[+b.dataset.e]}`); };
157
- }
158
- W.setTime(store.get("void.time") || "night");
159
- // fill the car's reflection cube once before the first frame, so the paint never samples an empty one
160
-
161
- $("osmCredit").textContent = W.credit;
162
- // the garage: the Build panel over the game, the game paused underneath
163
- function openGarage(on) { document.body.classList.toggle("garage", on); game.pause(on); if (on && car.repair) { car.repair(); applyBuild(); if (game.state) game.state.hp = 100; } }
164
- $("gGarageClose").onclick = () => openGarage(false);
165
- const nozzles = (car.nozzles || [[.9, .3, 1], [.9, .3, -1], [-.95, .38, 1], [-.95, .38, -1]]).map(([x, y, s]) => new THREE.Vector3(x, y - .5, s));
166
-
167
- // ---------- configurator ----------
168
- const OPTS = {
169
- paint: { label: "Paint", items: [["Void Black", "#0a0a0c"], ["Stealth Grey", "#2b2d32"], ["Liquid Silver", "#9fa3aa"], ["Ghost White", "#e9e9ea"], ["Blood Red", "#6f0a12"], ["Ember Orange", "#c9480c"], ["Ion Blue", "#123a8c"], ["Venom Green", "#2d6a1e"]] },
170
- finish: { label: "Finish", seg: true, items: [["Gloss", "gloss"], ["Satin", "satin"], ["Matte", "matte"]] },
171
- rim: { label: "Wheels", items: [["Black", "#121215"], ["Gunmetal", "#3a3d44"], ["Silver", "#b8bcc4"], ["Bronze", "#7a5a32"]] },
172
- cal: { label: "Calipers", items: [["Red", "#c1121f"], ["Black", "#2a2a30"], ["Yellow", "#e0b000"], ["White", "#e8e8e8"], ["Ion", "#3df5ff"]] },
173
- trim: { label: "Accents", items: [["Red", "#c1121f"], ["Black", "#16161a"], ["White", "#e8e8e8"], ["Gold", "#b8912e"], ["Ion", "#3df5ff"]] },
174
- light: { label: "Lights", items: [["Ice", "#e8fbff"], ["Amber", "#ffb347"], ["Ion", "#6ad8ff"], ["Violet", "#b38cff"]] },
175
- glow: { label: "Underglow", items: [["Off", ""], ["White", "#ffffff"], ["Red", "#ff2233"], ["Ion", "#3df5ff"], ["Violet", "#9b5cff"]] },
176
- spoiler: { label: "Spoiler", seg: true, items: [["Stock", "none"], ["Ducktail", "ducktail"], ["GT wing", "gt"], ["Swan neck", "swan"], ["Rally", "rally"]] },
177
- livery: { label: "Livery", seg: true, items: [["Clean", "none"], ["Twin stripes", "stripes"], ["Centre stripe", "center"], ["Side stripe", "side"], ["Race #42", "race"]] },
178
- livc: { label: "Livery colour", items: [["White", "#f2f2f2"], ["Red", "#c1121f"], ["Black", "#101012"], ["Gold", "#c9a227"], ["Ion", "#3df5ff"], ["Orange", "#ff6a00"]] },
179
- tint: { label: "Windows", seg: true, items: [["Light", "light"], ["Dark", "dark"], ["Limo", "limo"], ["Mirror", "mirror"]] },
180
- flame: { label: "Nitro flames", items: [["Blue", "#4fa8ff"], ["Orange", "#ff7a1a"], ["Green", "#3dff6a"], ["Purple", "#b05cff"], ["Pink", "#ff4fd8"]] },
181
- horn: { label: "Horn", seg: true, items: [["Classic", 0], ["Air horn", 1], ["Tune", 2]] },
182
- };
183
- OPTS.model = { label: "Car", seg: true, items: Object.entries(MODELS).map(([k, m]) => [m.name, k]) };
184
- const DEFAULT = { model: 0, paint: 0, finish: 0, rim: 0, cal: 0, trim: 0, light: 0, glow: 0, spoiler: 0, livery: 0, livc: 0, tint: 1, flame: 0, horn: 0 };
185
- let build = { ...DEFAULT, ...(store.get("void.build2") || {}), ...(store.get("void.build3") || {}) };
186
- try { const h = new URLSearchParams(location.hash.slice(1)).get("b"); if (h) { const v = h.split(".").map(Number); Object.keys(DEFAULT).forEach((k, i) => { if (OPTS[k].items[v[i]]) build[k] = v[i]; }); } } catch { }
187
- function applyBuild() {
188
- useModel(OPTS.model.items[build.model][1]);
189
- car.setSpoiler(OPTS.spoiler.items[build.spoiler][1]); car.setLivery(OPTS.livery.items[build.livery][1], OPTS.livc.items[build.livc][1]);
190
- car.setTint(OPTS.tint.items[build.tint][1]); car.setFlameColor(OPTS.flame.items[build.flame][1]);
191
- car.setPaint(OPTS.paint.items[build.paint][1]); car.setFinish(OPTS.finish.items[build.finish][1]);
192
- car.setRim(OPTS.rim.items[build.rim][1]); car.setAccent(OPTS.cal.items[build.cal][1]); car.setTrim(OPTS.trim.items[build.trim][1]); car.setLight(OPTS.light.items[build.light][1]);
193
- const gl = OPTS.glow.items[build.glow][1]; if (gl) fx.glow.material.color.set(gl).multiplyScalar(1.4);
194
- store.set("void.build3", build);
195
- $("sum").innerHTML = `<b>${car.name.toUpperCase()} &middot; ${OPTS.paint.items[build.paint][0]}</b>${OPTS.spoiler.items[build.spoiler][0]} spoiler, ${OPTS.livery.items[build.livery][0].toLowerCase()} livery, ${OPTS.finish.items[build.finish][0]} paint, ${OPTS.rim.items[build.rim][0].toLowerCase()} wheels, ${OPTS.cal.items[build.cal][0].toLowerCase()} calipers, ${OPTS.trim.items[build.trim][0].toLowerCase()} accents, ${OPTS.light.items[build.light][0].toLowerCase()} lights${gl ? ", " + OPTS.glow.items[build.glow][0].toLowerCase() + " underglow" : ""}`;
196
- for (const b of document.querySelectorAll("#cfgBody button")) b.setAttribute("aria-pressed", String(build[b.dataset.k] === +b.dataset.i));
197
- for (const k in OPTS) { const n = document.querySelector(`[data-name="${k}"]`); if (n) n.textContent = OPTS[k].items[build[k]][0]; }
198
- }
199
- const ORDER = ["model", "paint", "finish", "livery", "livc", "spoiler", "rim", "cal", "trim", "tint", "light", "glow", "flame", "horn"];
200
- $("cfgBody").innerHTML = ORDER.map(k => [k, OPTS[k]]).map(([k, o]) => `<div class="grp"><div class="grp-h">${o.label}<b data-name="${k}"></b></div><div class="${o.seg ? "seg" : "sw"}">${o.items.map(([n, c], i) => o.seg
201
- ? `<button data-k="${k}" data-i="${i}">${n}</button>`
202
- : `<button data-k="${k}" data-i="${i}" title="${n}" aria-label="${o.label}: ${n}" style="background:${c || "repeating-linear-gradient(45deg,#222 0 4px,#111 4px 8px)"}"></button>`).join("")}</div></div>`).join("");
203
- $("cfgBody").addEventListener("click", e => { const b = e.target.closest("button"); if (!b) return; build[b.dataset.k] = +b.dataset.i; applyBuild(); });
204
- $("reset").onclick = () => { build = { ...DEFAULT, model: build.model }; applyBuild(); toast("Back to black and red"); };
205
- $("share").onclick = async () => {
206
- const url = location.origin + location.pathname + "#b=" + Object.keys(DEFAULT).map(k => build[k]).join(".");
207
- try { await navigator.clipboard.writeText(url); toast("Link to your build copied"); } catch { prompt("Copy your build link", url); }
208
- };
209
- applyBuild();
210
- let toastT;
211
- function toast(t) { const el = $("toast"); el.textContent = t; el.classList.add("on"); clearTimeout(toastT); toastT = setTimeout(() => el.classList.remove("on"), 2200); }
212
-
213
- // ---------- sound ----------
214
- function setSound(on) { sound.setOn(on); $("snd").setAttribute("aria-pressed", String(on)); $("snd").textContent = on ? "Sound on" : "Sound off"; if (on && mode === "watch" && w.playing) sound.startSong(w.t); }
215
- $("snd").onclick = () => setSound(!sound.on);
216
- $("rev").onclick = () => { if (!sound.on) setSound(true); sound.rev(); };
217
-
218
- // ---------- modes ----------
219
- let mode = "home";
220
- const w = { t: 0, playing: false, dragging: false };
221
- function go(next) {
222
- if (next === mode) return;
223
- $("fade").classList.add("on");
224
- setTimeout(() => {
225
- if (mode === "play") { game.exit(); openGarage(false); }
226
- if (mode === "watch") { sound.stopSong(); w.playing = false; }
227
- mode = next; document.body.dataset.mode = next;
228
- if (next === "home") scrollTo(0, 0);
229
- if (next === "watch") { if (!sound.on) setSound(true); playFrom(0); }
230
- if (next === "play") { game.enter(); if (SET.radio !== "score") sound.setRadio(SET.radio); }
231
- if (mode !== "play" && sound.radio && sound.radio !== "score") sound.setRadio("score");
232
- $("fade").classList.remove("on");
233
- }, 320);
234
- }
235
- document.addEventListener("click", e => { const b = e.target.closest("[data-go]"); if (b) { e.preventDefault(); go(b.dataset.go); } });
236
- $("exit").onclick = () => go("home");
237
- addEventListener("keydown", e => {
238
- if (e.code === "Escape" && mode === "play" && !document.body.classList.contains("garage")) { menu(); return; }
239
- if (e.code === "Escape" && mode !== "home") go("home");
240
- if (mode === "watch") {
241
- if (e.code === "Space") { e.preventDefault(); togglePlay(); }
242
- if (e.code === "ArrowRight") seek(w.t + 4); if (e.code === "ArrowLeft") seek(w.t - 4);
243
- }
244
- });
245
-
246
- // watch player
247
- function playFrom(t) { w.t = clamp(t, 0, TOTAL); w.playing = true; $("wEnd").classList.remove("on"); if (sound.on) sound.startSong(w.t); setPlayIcon(); }
248
- function pause() { w.playing = false; sound.stopSong(); setPlayIcon(); }
249
- function togglePlay() { if (w.playing) pause(); else playFrom(w.t >= TOTAL - .05 ? 0 : w.t); }
250
- function seek(t) { w.t = clamp(t, 0, TOTAL); if (w.playing) playFrom(w.t); }
251
- function setPlayIcon() { $("wPlay").innerHTML = w.playing ? "&#10074;&#10074;" : "&#9654;"; $("wPlay").setAttribute("aria-label", w.playing ? "Pause" : "Play"); }
252
- $("wPlay").onclick = togglePlay;
253
- $("wAgain").onclick = () => playFrom(0);
254
- const scrub = $("wScrub"); scrub.max = TOTAL;
255
- scrub.addEventListener("input", () => { w.dragging = true; w.t = +scrub.value; if (w.playing) { sound.stopSong(); } });
256
- scrub.addEventListener("change", () => { w.dragging = false; if (w.playing) playFrom(+scrub.value); });
257
- $("wTicks").innerHTML = CHAPTERS.filter(c => c[1]).map(c => `<button style="left:${c[0] * BAR / TOTAL * 100}%" data-t="${c[0] * BAR}">${c[1]}</button>`).join("");
258
- $("wTicks").addEventListener("click", e => { const b = e.target.closest("button"); if (b) { seek(+b.dataset.t); if (!w.playing) playFrom(+b.dataset.t); } });
259
- const fmt = s => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;
260
-
261
- // drag to turn the car on the home and build screens
262
- const orbit = { a: .7, v: 0, drag: false, x: 0 };
263
- addEventListener("pointerdown", e => { if ((mode !== "build" && mode !== "home") || e.target !== $("gl") && !e.target.closest(".drag-hint, #buildUI") || e.target.closest(".cfg, button")) return; orbit.drag = true; orbit.x = e.clientX; });
264
- addEventListener("pointermove", e => { if (!orbit.drag) return; orbit.v = (e.clientX - orbit.x) * -.006; orbit.a += orbit.v; orbit.x = e.clientX; });
265
- addEventListener("pointerup", () => { orbit.drag = false; });
266
-
267
- // ---------- resize: ignore the phone address bar sliding, follow rotation and folding ----------
268
- let lastW = 0, lastH = 0;
269
- function resize() {
270
- const ww = innerWidth, hh = Math.max(innerHeight, document.documentElement.clientHeight);
271
- if (!ww || !hh) return;
272
- if (ww === lastW && Math.abs(hh - lastH) < 140 && lastW) return;
273
- lastW = ww; lastH = hh; renderer.setSize(ww, hh, false); composer.setSize(ww, hh);
274
- bloom.resolution.set(Math.max(1, ww * (COARSE ? .35 : .5)), Math.max(1, hh * (COARSE ? .35 : .5))); camera.aspect = ww / hh;
275
- }
276
- addEventListener("resize", resize); addEventListener("orientationchange", () => setTimeout(resize, 200));
277
- if (window.visualViewport) visualViewport.addEventListener("resize", resize);
278
- resize();
279
- const fovFor = f => { const a = camera.aspect; if (a >= 1.5) return f; const h = 2 * Math.atan(Math.tan(f * Math.PI / 360) * 1.5); return Math.min(88, 2 * Math.atan(Math.tan(h / 2) / a) * 180 / Math.PI); };
280
-
281
- // ---------- the showroom pose (home and build) ----------
282
- const showFr = frame(); W.track.sample(W.track.D[W.track.idxX(0)], showFr);
283
- const intro = { t: -1 }; // the car drives in once the loader lifts
284
- function showroom(dt, time) {
285
- let introX = 0, introV = 0;
286
- if (intro.t >= 0 && intro.t < 3.2) { intro.t += dt; const u = Math.min(1, intro.t / 3.2); introX = -46 * Math.pow(1 - u, 3); introV = 46 * 3 * Math.pow(1 - u, 2) / 3.2; }
287
- else if (intro.t < 0) introX = -46;
288
- if (!orbit.drag) { orbit.v *= .94; orbit.a += orbit.v + (REDUCED ? 0 : dt * (mode === "home" ? .16 : .1)); }
289
- const hf = 2 * Math.atan(Math.tan(fovFor(38) * Math.PI / 360) * camera.aspect), fit = 3.1 / Math.tan(hf / 2); // fit the whole car across the screen
290
- const scrolled = mode === "home" ? clamp(scrollY / innerHeight) : 0, dist = Math.max(mode === "build" ? 8.8 : 8.2, fit) + scrolled * 2;
291
- const cam = { pos: new THREE.Vector3(Math.cos(orbit.a) * dist, 1.5 + scrolled * 4, Math.sin(orbit.a) * dist), look: new THREE.Vector3(0, .5 - scrolled * .4, 0), fov: 38 };
292
- if (camera.aspect < 1) cam.look.y = mode === "build" ? -1.1 : -.2;
293
- else if (mode === "build") { const right = new THREE.Vector3().subVectors(cam.look, cam.pos).cross(new THREE.Vector3(0, 1, 0)).normalize(); cam.look.addScaledVector(right, 1.7); }
294
- const pos = showFr.p.clone(); pos.x += introX; const fr = { ...showFr, p: pos };
295
- if (introX < -.01) cam.look.x = Math.max(introX * .35, -8);
296
- return { pos, quat: new THREE.Quaternion(), fr, speed: introV * 3.6, g: 1, alt: 0, vs: 0, thrust: { power: 0, angle: 0, deploy: 0 }, wings: 0, air: false, cam, inside: false, screenOn: false, reveal: 1, rpm: 900, gear: 1, load: .1, engine: .6, mode: "PARK", zones: [] };
297
- }
298
-
299
- // ---------- per frame ----------
300
- const clock = new THREE.Clock();
301
- let lastGauge = 0, lastChips = 0;
302
- // the speedometer: a dial with a glowing arc, the speed, the gear (or altitude when flying) and what you're in
303
- const gauge = document.getElementById("gGauge"), gx = gauge.getContext("2d");
304
- function drawGauge(S) {
305
- const W2 = gauge.width, c = W2 / 2, r = c - 22, a0 = Math.PI * .75, a1 = Math.PI * 2.25, max = S.veh === "plane" ? 600 : S.veh === "boat" ? 140 : 360, f = Math.min(1, S.speed / max);
306
- gx.clearRect(0, 0, W2, W2);
307
- gx.beginPath(); gx.arc(c, c, r + 14, 0, 7); gx.fillStyle = "rgba(6,8,14,.62)"; gx.fill();
308
- gx.lineCap = "round"; gx.lineWidth = 14; gx.beginPath(); gx.arc(c, c, r, a0, a1); gx.strokeStyle = "rgba(255,255,255,.12)"; gx.stroke();
309
- const grd = gx.createLinearGradient(0, W2, W2, 0); grd.addColorStop(0, "#3df5ff"); grd.addColorStop(.6, "#ffffff"); grd.addColorStop(1, "#ff2a3a");
310
- gx.beginPath(); gx.arc(c, c, r, a0, a0 + (a1 - a0) * f); gx.strokeStyle = grd; gx.shadowColor = "#3df5ff"; gx.shadowBlur = 16; gx.stroke(); gx.shadowBlur = 0;
311
- gx.lineWidth = 2; gx.strokeStyle = "rgba(255,255,255,.5)"; for (let k = 0; k <= 12; k++) { const a = a0 + (a1 - a0) * k / 12, i = r - 18, o = r - (k % 3 ? 24 : 30); gx.beginPath(); gx.moveTo(c + Math.cos(a) * i, c + Math.sin(a) * i); gx.lineTo(c + Math.cos(a) * o, c + Math.sin(a) * o); gx.stroke(); }
312
- gx.fillStyle = "#fff"; gx.textAlign = "center"; gx.font = `900 ${W2 * .22}px Unbounded, Inter, sans-serif`; gx.fillText(Math.round(S.speed), c, c + W2 * .06);
313
- gx.font = `700 ${W2 * .055}px Inter, sans-serif`; gx.fillStyle = "rgba(255,255,255,.6)"; gx.fillText("KM/H", c, c + W2 * .14);
314
- gx.font = `800 ${W2 * .07}px Unbounded, Inter, sans-serif`; gx.fillStyle = S.air ? "#3df5ff" : "#ffd23d";
315
- gx.fillText(S.air || S.veh === "plane" || S.veh === "heli" ? `${Math.round(S.alt)} m` : S.veh === "boat" ? "BOAT" : `GEAR ${S.gear}`, c, c + W2 * .3);
316
- if (S.nitro > .1) { gx.font = `800 ${W2 * .05}px Inter, sans-serif`; gx.fillStyle = "#3df5ff"; gx.fillText("NITRO", c, c - W2 * .16); }
317
- }
318
- let wasWrecked = false, wreckPose = null; const wrecks = [];
319
- const perf = { t: 0, n: 0, pr: renderer.getPixelRatio(), max: renderer.getPixelRatio(), down: 0 };
320
- applySettings();
321
- let lastHud = 0, prevGear = 1, feedFlip = 0;
322
- function frameLoop(fixed) {
323
- const raw = fixed ? 0 : clock.getDelta(), dt = fixed || Math.min(.05, raw), time = clock.elapsedTime;
324
- // adaptive resolution: drop the pixel count when frames run slow, bring it back when there is headroom
325
- if (!fixed && raw < .5) {
326
- perf.t += raw; perf.n++;
327
- if (perf.t > 1.5) {
328
- const avg = perf.t / perf.n, was = perf.pr;
329
- if (avg > 1 / 45 && perf.pr > .6) perf.pr = Math.max(.6, perf.pr - (avg > 1 / 25 ? .25 : .12));
330
- else if (avg > 1 / 40 && mode === "play" && ++perf.down >= 3 && SET.q !== "low") { // still slow at the lowest resolution: drop a quality level
331
- perf.down = 0; SET.q = { ultra: "high", high: "medium", medium: "low" }[SET.q]; perf.pr = W.QUALITY[SET.q].pr; applySettings(false); toast(`Graphics set to ${SET.q} to keep it smooth`);
332
- }
333
- else if (avg < 1 / 58 && perf.pr < perf.max) perf.pr = Math.min(perf.max, perf.pr + .08);
334
- if (perf.pr !== was) { renderer.setPixelRatio(perf.pr); composer.setPixelRatio(perf.pr); lastW = 0; resize(); }
335
- perf.t = perf.n = 0;
336
- }
337
- }
338
- let S;
339
- if (mode === "watch") {
340
- if (w.playing && !w.dragging) {
341
- const st = sound.on ? sound.songTime() : null;
342
- w.t = st != null ? st : w.t + dt;
343
- if (w.t >= TOTAL) { w.t = TOTAL; pause(); $("wEnd").classList.add("on"); }
344
- }
345
- S = watch.at(w.t, time, camera.aspect, fovFor);
346
- if (!w.dragging) scrub.value = w.t;
347
- scrub.style.setProperty("--p", (w.t / TOTAL * 100) + "%");
348
- $("wTime").textContent = `${fmt(w.t)} / ${fmt(TOTAL)}`;
349
- const ch = S.chapter, cap = $("wCap");
350
- if (cap.dataset.ch !== ch[1]) { cap.dataset.ch = ch[1]; cap.classList.add("hide"); setTimeout(() => { $("wNum").textContent = ch[1] ? String(CHAPTERS.indexOf(ch) + 1).padStart(2, "0") : ""; $("wTitle").textContent = ch[1]; $("wSub").textContent = ch[2]; cap.classList.toggle("hide", !ch[1]); }, 250); }
351
- $("telem").style.opacity = S.bar > 2 && !S.inside && S.bar < 17.5 ? 1 : 0;
352
- $("tSpd").textContent = Math.round(S.speed); $("tG").textContent = S.g.toFixed(1); $("tAlt").textContent = Math.round(S.alt);
353
- $("dream").style.opacity = S.dream; $("fade").style.opacity = S.fade;
354
- } else if (mode === "play") S = game.update(dt, time, camera.aspect);
355
- else S = showroom(dt, time);
356
- life.update(dt, time, mode === "play" ? S.player : null, camera.position);
357
- if (mode === "play") {
358
- police.update(dt, time); races.update(dt, time); nav.update();
359
- const st = game.state, stars = police.stars;
360
- document.getElementById("gStars").textContent = stars ? "★".repeat(stars) + "☆".repeat(5 - stars) : "";
361
- document.getElementById("gStars").classList.toggle("bust", police.bust > .5);
362
- const pr = races.progress();
363
- net.tick(dt, { p: [st.x, st.y, st.z, st.yaw, st.pitch, st.roll].map(v => Math.round(v * 100) / 100), m: Object.keys(MODELS).indexOf(car.model), c: OPTS.paint.items[build.paint][1], v: Math.round(S.speed), a: S.air ? 1 : 0, r: pr ? pr.race : 0, rp: pr ? pr.rp : 0, rf: pr ? pr.rf : 0, w: stars });
364
- for (const p of net.players()) {
365
- const at = net.sample(p); const r = remoteFor(p); r.at = at;
366
- if (!at || at.stale) { r.root.visible = false; continue; }
367
- r.root.visible = true; r.root.position.set(at.x, at.y, at.z); r.root.rotation.set(0, -at.yaw, 0); r.car.group.rotation.set(at.roll, 0, at.pitch, "XYZ");
368
- r.car.setThrust(at.air ? .6 : 0, at.air && at.v > 90 ? 1 : 0, at.air ? 1 : 0, time); r.car.setWings(at.air && at.v > 100 ? 1 : 0, time);
369
- for (const wh of r.car.wheels) wh.rotation.z -= at.v / 3.6 * dt / .37;
370
- if (r.emoT > 0 && (r.emoT -= dt) <= 0) r.emo.visible = false;
371
- const dx = st.x - at.x, dz = st.z - at.z, d = Math.hypot(dx, dz);
372
- net.setVolume(p.id, 1 - d / 260);
373
- if (d < 3.4 && d > .01 && Math.abs(st.y - at.y) < 2) { st.x += dx / d * (3.4 - d) * .5; st.z += dz / d * (3.4 - d) * .5; st.vel.multiplyScalar(.9); }
374
- }
375
- } else { for (const r of remotes.values()) r.root.visible = false; net.tick(dt, null); } // the host keeps relaying from the menus
376
- W.city.update(time, camera.position);
377
- W.follow(S.pos);
378
- if (mode !== "watch") $("fade").style.opacity = "";
379
-
380
- // the car, or the plane / helicopter / boat
381
- const veh = mode === "play" ? S.veh || "car" : "car";
382
- carRoot.visible = veh === "car";
383
- vehicles.show(veh === "car" ? null : veh, S.pos, S.quat, S, time, dt);
384
- if (S.splash) for (let k = 0; k < 6; k++) { const pf = fx.puffs[fx.puffI++ % fx.puffs.length]; pf.s.position.copy(S.pos).add(new THREE.Vector3((Math.random() - .5) * 3, .3, (Math.random() - .5) * 3)); pf.life = 1; pf.s.visible = true; pf.grow = .8; pf.s.scale.setScalar(.8); pf.s.material.color.set(0xeaf6ff); pf.v.set((Math.random() - .5) * 6, 4 + Math.random() * 4, (Math.random() - .5) * 6); }
385
- if (veh === "boat" && S.speed > 12 && Math.random() < .6) { const back = new THREE.Vector3(-3.6, .1, (Math.random() - .5) * 2).applyQuaternion(S.quat).add(S.pos); const pf = fx.puffs[fx.puffI++ % fx.puffs.length]; pf.s.position.copy(back); pf.life = 1; pf.s.visible = true; pf.grow = .5; pf.s.scale.setScalar(.5); pf.s.material.color.set(0xf4fbff); pf.v.set((Math.random() - .5) * 2, .6, (Math.random() - .5) * 2); }
386
- const night = W.timeOfDay !== "day";
387
- heads.intensity = night && veh === "car" ? (W.timeOfDay === "night" ? 260 : 120) : 0;
388
- W.sky.position.copy(camera.position); W.grade.uniforms.time.value = time % 100;
389
- W.grade.uniforms.blur.value = mode === "play" ? Math.max(0, Math.min(1, (S.speed - 160) / 220)) * .9 + (S.nitro || 0) * .5 : 0;
390
- atmos.update(dt, time, S, mode === "play" ? game.state : null);
391
- W.city.poolMat.opacity = W.timeOfDay === "night" ? 1 : W.timeOfDay === "sunset" ? .45 : 0; W.city.poolMat.visible = W.timeOfDay !== "day";
392
- if (mode === "play") { goals.update(dt, game.state, S.speed); if (time - lastChips > 2) { lastChips = time; chips(); } }
393
- if (mode === "play" && time - lastGauge > .05) { lastGauge = time; drawGauge(S); const fu = document.getElementById("gFuel"); if (fu && S.fuel != null) { fu.style.setProperty("--v", S.fuel); fu.classList.toggle("low", S.fuel < .2); } }
394
- car.group.position.copy(S.pos); car.group.quaternion.copy(S.quat);
395
- car.setReveal(S.reveal);
396
- car.setThrust(S.thrust.power, S.thrust.angle, S.thrust.deploy, time);
397
- car.setFlame(S.nitro || 0, time);
398
- // damage: dent the model where it was hit; a destroyed car is left where it crashed and a fresh one is built for you
399
- const gs = mode === "play" ? game.state : null;
400
- if (gs && gs.impacts && gs.impacts.length && car.damage) { carRoot.updateMatrixWorld(true); for (const im of gs.impacts.splice(0)) car.damage(carRoot.worldToLocal(new THREE.Vector3(im.x, im.y, im.z)), im.p); }
401
- if (S.wrecked && !wasWrecked) { car.wreck && car.wreck(); wreckPose = { p: carRoot.position.clone(), q: carRoot.quaternion.clone() }; }
402
- if (!S.wrecked && wasWrecked && wreckPose && inner) {
403
- const wg = inner.group; carRoot.remove(wg); wg.position.copy(wreckPose.p); wg.quaternion.copy(wreckPose.q); scene.add(wg);
404
- wrecks.push({ g: wg, t: 30 }); if (wrecks.length > 4) { const o = wrecks.shift(); scene.remove(o.g); }
405
- useModel(car.model, true); applyBuild(); wreckPose = null;
406
- }
407
- wasWrecked = !!S.wrecked;
408
- for (const w of wrecks) { w.t -= dt; if (Math.random() < .25 && w.t > 10) { const pf = fx.puffs[fx.puffI++ % fx.puffs.length]; pf.s.position.copy(w.g.position).add(new THREE.Vector3((Math.random() - .5) * 2, 1, (Math.random() - .5) * 2)); pf.life = 1; pf.s.visible = true; pf.grow = .6; pf.s.scale.setScalar(.6); pf.s.material.color.set(0x2a2a2a); pf.v.set(0, 2, 0); } }
409
- for (let k = wrecks.length - 1; k >= 0; k--) if (wrecks[k].t <= 0) { scene.remove(wrecks[k].g); wrecks.splice(k, 1); }
410
- car.setWings(S.wings, time);
411
- const roll = S.speed / 3.6 * dt / .37;
412
- for (const wh of car.wheels) wh.rotation.z -= S.air ? roll * .15 : roll;
413
- car.group.updateMatrixWorld(true);
414
-
415
- // shadow, underglow, exhaust, speed lines
416
- const fr = S.fr, ground = clamp(1 - S.pos.y / 3) * (fr.u.y > .8 ? 1 : 0);
417
- fx.shadow.position.set(S.pos.x, S.pos.y > .5 ? .07 : S.pos.y + .07, S.pos.z); fx.shadow.material.opacity = veh === "car" ? ground : 0; fx.shadow.rotation.z = Math.atan2(-fr.f.z, fr.f.x);
418
- const glowOn = !!OPTS.glow.items[build.glow][1];
419
- fx.glow.position.copy(fx.shadow.position).y += .01; fx.glow.rotation.z = fx.shadow.rotation.z; fx.glow.material.opacity = glowOn ? ground * .85 : 0;
420
- if (S.thrust.power > .3) for (const n of nozzles) if (Math.random() < .18) {
421
- const pf = fx.puffs[fx.puffI++ % fx.puffs.length], wp = n.clone().applyMatrix4(car.group.matrixWorld);
422
- pf.s.position.copy(wp); pf.life = 1; pf.s.visible = true; pf.s.scale.setScalar(.4); pf.grow = .4; pf.s.material.color.set(0xc8d2e1);
423
- pf.v.copy(fr.u).multiplyScalar(-(1 - S.thrust.angle) * 7).addScaledVector(fr.f, -S.thrust.angle * 9 - S.speed / 3.6 * .2).add(new THREE.Vector3(Math.random() - .5, Math.random() - .5, Math.random() - .5).multiplyScalar(1.5));
424
- }
425
- const emit = (p, v, col, size, life = 1) => { const pf = fx.puffs[fx.puffI++ % fx.puffs.length]; pf.s.position.copy(p); pf.life = life; pf.s.visible = true; pf.s.scale.setScalar(size); pf.s.material.color.set(col); pf.v.copy(v); pf.grow = size; };
426
- if (mode === "play" && S.hp != null) {
427
- const eng = new THREE.Vector3(-1.2, .9, 0).applyMatrix4(car.group.matrixWorld);
428
- if (S.hp < 55 && !S.wrecked && Math.random() < (S.hp < 25 ? .5 : .2)) emit(eng, new THREE.Vector3((Math.random() - .5), 1.5 + Math.random(), (Math.random() - .5)), S.hp < 25 ? 0x222222 : 0x9a9a9a, .5);
429
- if (S.hp < 20 && !S.wrecked && Math.random() < .35) emit(eng, new THREE.Vector3(0, 2.5, 0), 0xff7a1a, .35, .5);
430
- if (S.sparks > .5) for (let k = 0; k < 4; k++) emit(S.pos.clone().add(new THREE.Vector3(0, .5, 0)), new THREE.Vector3((Math.random() - .5) * 12, Math.random() * 6, (Math.random() - .5) * 12), 0xffd27a, .12, .35);
431
- if (S.boom > .95) for (let k = 0; k < 40; k++) emit(S.pos.clone().add(new THREE.Vector3(0, 1, 0)), new THREE.Vector3((Math.random() - .5) * 18, Math.random() * 14, (Math.random() - .5) * 18), k % 3 ? 0xff7a1a : 0x333333, 1.2, 1.4);
432
- }
433
- for (const pf of fx.puffs) if (pf.life > 0) {
434
- pf.life -= dt * .9; pf.s.position.addScaledVector(pf.v, dt); pf.v.multiplyScalar(.97);
435
- pf.s.scale.setScalar((pf.grow || .4) + (1 - pf.life) * 4.5); pf.s.material.opacity = Math.max(0, pf.life) * .5; if (pf.life <= 0) pf.s.visible = false;
436
- }
437
- const lineA = smooth(240, 320, S.speed) * (S.inside ? 0 : 1);
438
- fx.lines.material.opacity = lineA * .08;
439
- if (lineA > .01) {
440
- const d = new THREE.Object3D();
441
- for (let i = 0; i < fx.LINES; i++) {
442
- const sd = fx.lineSeed[i]; sd[0] -= S.speed / 3.6 * dt * 1.6; if (sd[0] < -40) sd[0] += 80;
443
- d.position.copy(fr.p).addScaledVector(fr.f, sd[0]).addScaledVector(fr.u, sd[1]).addScaledVector(fr.s, sd[2]); d.quaternion.copy(S.quat); d.scale.set(1.5 + S.speed * .018, 1, 1);
444
- d.updateMatrix(); fx.lines.setMatrixAt(i, d.matrix);
445
- }
446
- fx.lines.instanceMatrix.needsUpdate = true;
447
- }
448
-
449
- // the front seat and its screens
450
- if (S.screenOn) {
451
- if (!COARSE || (feedFlip++ & 1)) interior.renderFeed(scene);
452
- if (time - lastHud > .1) {
453
- lastHud = time;
454
- const hud = { time, speed: S.speed, alt: S.alt, vs: S.vs, mode: S.mode, zones: S.zones, gear: S.gear, rpm: S.rpm };
455
- interior.drawHud(hud); interior.drawCluster(hud);
456
- }
457
- }
458
- interior.wheel.rotation.x = 0;
459
-
460
- // camera
461
- const c = S.cam, shake = REDUCED ? 0 : (Math.max(0, S.g - 2) * .004 + S.thrust.power * .01 + (S.shake || 0) * .25 + (S.nitro || 0) * .02) * (S.inside ? .25 : 1);
462
- camera.position.copy(c.pos).add(new THREE.Vector3(Math.sin(time * 53) * shake, Math.sin(time * 61 + 1) * shake, Math.sin(time * 47 + 2) * shake));
463
- camera.up.copy(c.up || new THREE.Vector3(0, 1, 0)); camera.lookAt(c.look);
464
- camera.fov = fovFor(c.fov); camera.near = S.inside || S.screenOn ? .02 : .05; camera.updateProjectionMatrix();
465
- camLight.position.copy(camera.position).add(new THREE.Vector3(0, 3, 0)); camLight.target.position.copy(S.pos);
466
- scene.fog.far = lerp(950, 2600, smooth(20, 160, S.alt)) * W.weatherFog; scene.fog.near = lerp(120, 400, smooth(20, 160, S.alt)) * W.weatherFog;
467
- camera.far = scene.fog.far * 1.1 + 150; camera.updateProjectionMatrix(); // nothing past the fog gets drawn
468
- // refresh the car's reflections every few frames (the car hides from its own camera)
469
- // (no shadows, no crowds, a short view: it only has to look right in the paint)
470
-
471
-
472
- // the car's own sound
473
- if (S.gear > prevGear && !S.air && S.speed > 20) sound.pop();
474
- prevGear = S.gear;
475
- sound.car({ rpm: S.rpm, load: S.load, engine: mode === "build" || mode === "home" ? .4 : S.engine, thrust: S.thrust.power, speed: S.speed, inside: S.inside });
476
-
477
- composer.render();
478
- }
479
-
480
- setLoad(95);
481
- renderer.compile(scene, camera);
482
- let raf;
483
- let frameErr = 0;
484
- const loop = () => { raf = requestAnimationFrame(loop); try { frameLoop(); } catch (e) { if (frameErr++ < 3) console.error(e); } }; // one bad frame never stops the game
485
- loop();
486
- setLoad(100);
487
- setTimeout(() => { $("loader").classList.add("done"); setTimeout(() => { intro.t = 0; if (sound.on) sound.rev(); }, 450); }, 900);
488
- document.addEventListener("visibilitychange", () => {
489
- if (document.hidden) { cancelAnimationFrame(raf); if (mode === "watch" && w.playing) pause(); if (sound.ctx) sound.ctx.suspend(); }
490
- else { clock.getDelta(); loop(); if (sound.on && sound.ctx) sound.ctx.resume(); }
491
- });
492
- window.VOID = { step: (n = 1, dt = 1 / 30) => { for (let i = 0; i < n; i++) frameLoop(dt); }, W, car, life, carCube, carEnv, get police() { return police; }, get races() { return races; }, get nav() { return nav; }, net, orbit, go, seek: t => { w.t = t; if (w.playing) playFrom(t); }, pause, get w() { return w; }, game }; // handy for testing in the console
 
 
 
 
 
 
 
 
 
1
+ // VOID: one WebGL canvas, three modes on top of a showroom home screen.
2
+ // Watch: a 48 s film whose clock is the music. Play: drive it, fly it, land it. Build: paint it.
3
+ import * as THREE from "three";
4
+
5
+ const V = new URL(import.meta.url).search;
6
+ const $ = id => document.getElementById(id);
7
+ const setLoad = p => { $("ldbar").style.width = p + "%"; $("ldpct").textContent = Math.round(p); };
8
+ setLoad(15);
9
+ const [{ createWorld, clamp, lerp, smooth, frame, PAD_R, ZONES }, { buildCar, MODELS }, { addInterior, HEAD }, { Sound, BAR }, { createWatch, TOTAL, CHAPTERS }, { createGame }, { createLife }] = await Promise.all(
10
+ ["world", "car", "interior", "sound", "watch", "game", "npc"].map(n => import(`./${n}.js${V}`)));
11
+ const [{ createPolice }, { createRaces }, { createNet, EMOTES }, { createNav }, { createVehicles }, { createAtmos, WEATHERS }, { createGoals, GOALS }, { createExtras }] = await Promise.all(["police", "race", "net", "nav", "vehicles", "atmos", "goals", "extras"].map(n => import(`./${n}.js${V}`)));
12
+ setLoad(40);
13
+
14
+ const COARSE = matchMedia("(pointer: coarse)").matches, REDUCED = matchMedia("(prefers-reduced-motion: reduce)").matches;
15
+ const store = { get(k) { try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } }, set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch { } } };
16
+ const W = await createWorld($("gl"), COARSE), { renderer, scene, camera, composer, bloom, camLight, fx } = W;
17
+ setLoad(55);
18
+
19
+ // the car you drive: a fixed root the game and the film move around, with the chosen model swapped inside it
20
+ const carRoot = new THREE.Group(); scene.add(carRoot);
21
+ const car = { group: carRoot, wheels: [] };
22
+ const carMats = new Set();
23
+ let inner = null;
24
+ function useModel(id, force) {
25
+ if (inner && inner.model === id && !force) return;
26
+ if (inner) carRoot.remove(inner.group);
27
+ inner = buildCar(id); carRoot.add(inner.group);
28
+ for (const k of Object.keys(inner)) if (typeof inner[k] === "function") car[k] = inner[k];
29
+ Object.assign(car, { wheels: inner.wheels, clip: car.clip || inner.clip, materials: inner.materials, model: id, name: inner.name });
30
+ carMats.clear();
31
+ inner.group.traverse(o => { if (o.isMesh) { o.castShadow = true; if (o.material && o.material.isMeshStandardMaterial) carMats.add(o.material); } });
32
+ for (const m of carMats) { m.envMap = null; m.needsUpdate = true; } // the paint reflects the city capture (scene.environment) // phones skip the live cube and use the city reflection
33
+ }
34
+ // live reflections on the paint: a small cube camera that rides with the car
35
+ const carEnv = new THREE.WebGLCubeRenderTarget(COARSE ? 64 : 128, { type: THREE.HalfFloatType, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter });
36
+ const carCube = new THREE.CubeCamera(.5, 320, carEnv);
37
+ for (const c of carCube.children) c.layers.set(0);
38
+ camera.layers.enable(1); // layer 1: the crowds, seen by the main camera only
39
+ let cubeN = 0;
40
+ useModel((store.get("void.build3") || {}).model != null ? Object.keys(MODELS)[(store.get("void.build3") || {}).model] || "hydra" : "hydra");
41
+ setLoad(80);
42
+ const interior = addInterior(car, renderer);
43
+ const sound = new Sound();
44
+ const watch = createWatch(W, car, interior);
45
+ const life = createLife(scene, W.roads, W.walkways, COARSE);
46
+ const TIMES = ["night", "sunset", "day"];
47
+ function cycleTime() { const k = TIMES[(TIMES.indexOf(W.timeOfDay) + 1) % 3]; W.setTime(k); store.set("void.time", k); toast({ night: "Night in the city", sunset: "Golden hour", day: "Daytime" }[k]); cubeN = 0; }
48
+ let police, races, nav;
49
+ const net = createNet();
50
+ setInterval(() => { if (document.hidden) net.tick(.5, null); }, 500); // a hosting tab in the background still relays everyone
51
+ // settings: graphics quality, look speed, auto gas, touch steering (kept on this device)
52
+ // a strong graphics card starts on High; everything else starts on Medium (it can be raised in the Menu)
53
+ const GPU = (() => { try { const c = renderer.getContext(), e = c.getExtension("WEBGL_debug_renderer_info"); return e ? c.getParameter(e.UNMASKED_RENDERER_WEBGL) : ""; } catch { return ""; } })();
54
+ const STRONG = /RTX|GTX 1[06-9]|GTX 9[78]|Radeon RX|Radeon Pro|Apple M[1-9]/i.test(GPU) && !COARSE;
55
+ const SET = Object.assign({ q: STRONG ? "high" : COARSE ? "low" : "medium", sens: 1, autogas: "off", steer: "stick", weather: "clear", radio: "score", cycle: "off" }, store.get("void.settings") || {});
56
+ const gameOpts = {
57
+ garage: () => openGarage(true), cycleTime, hornType: () => build.horn, autoGas: () => SET.autogas === "on", onRepair: () => car.repair && car.repair(),
58
+ onScore: (n, why) => { if (why === "Drift") goals.drift(n); goals.note(why); },
59
+ onSmash: kind => police && police.event("smash", kind), policeClear: () => police && police.clear(),
60
+ autopilot: (g, dt, over) => nav ? nav.controls(g, dt, over) : null, openGps: () => document.getElementById("gGpsBtn").click(),
61
+ mapExtra(mx, g, MM) {
62
+ const P = (x, z) => [(x - g.x) / MM, (z - g.z) / MM];
63
+ if (nav && nav.pts.length > 1) { mx.strokeStyle = "#3dfcff"; mx.lineWidth = 3; mx.beginPath(); nav.pts.forEach(([x, z], k) => { const [a, b] = P(x, z); k ? mx.lineTo(a, b) : mx.moveTo(a, b); }); mx.stroke(); }
64
+ if (police) for (const c of police.cops) if (c.on) { const [a, b] = P(c.x, c.z); mx.fillStyle = Math.sin(performance.now() / 90) > 0 ? "#ff3040" : "#3060ff"; mx.beginPath(); mx.arc(a, b, 4, 0, 7); mx.fill(); }
65
+ if (races && races.race && races.race.next) { const [a, b] = P(races.race.next[0], races.race.next[2]); mx.strokeStyle = "#ffd23d"; mx.lineWidth = 3; mx.beginPath(); mx.arc(a, b, 7, 0, 7); mx.stroke(); }
66
+ for (const r of remotes.values()) if (r.at) { const [a, b] = P(r.at.x, r.at.z); mx.fillStyle = "#c07dff"; mx.beginPath(); mx.arc(a, b, 4.5, 0, 7); mx.fill(); }
67
+ mx.font = "bold 12px sans-serif"; mx.textAlign = "center"; for (const st of W.city.stations) { const [a, b] = P(st.x, st.z); if (Math.abs(a) < 90 && Math.abs(b) < 90) { mx.save(); mx.translate(a, b); mx.rotate(g.yaw + Math.PI / 2); mx.fillText("⛽", 0, 4); mx.restore(); } }
68
+ },
69
+ };
70
+ const game = createGame(W, car, sound, life, gameOpts);
71
+ const vehicles = createVehicles(scene, game.api, W); gameOpts.vehicles = vehicles;
72
+ const atmos = createAtmos(W, sound, COARSE);
73
+ // trophies: a banner slides in at the top when a challenge is done
74
+ const goals = createGoals(gl => { const t = document.getElementById("gTrophy"); t.innerHTML = `<b>${gl.icon}</b><div><span>Challenge complete</span>${gl.name}<em>+1000</em></div>`; t.classList.remove("on"); void t.offsetWidth; t.classList.add("on"); if (game.state) { game.state.score += 1000; } sound.win(); renderGoals(); });
75
+ function renderGoals() {
76
+ const S = goals.stats;
77
+ document.getElementById("gGoals").innerHTML = GOALS.map(g => { const v = Math.min(1, (S[g.stat] || 0) / g.need), ok = goals.done.has(g.id); return `<div class="goal${ok ? " ok" : ""}"><b>${g.icon}</b><div><span>${g.name}</span><small>${g.text}</small><i style="--v:${v}"></i></div>${ok ? "🏆" : `<em>${Math.floor(v * 100)}%</em>`}</div>`; }).join("");
78
+ document.getElementById("gStatsRow").innerHTML = `<div><b>${(S.best || 0).toLocaleString()}</b><span>Best score</span></div><div><b>${Math.round(S.top)}</b><span>Top km/h</span></div><div><b>${S.km.toFixed(1)}</b><span>km travelled</span></div><div><b>${goals.done.size}/${GOALS.length}</b><span>Trophies</span></div>`;
79
+ }
80
+ const WX_ICON = { clear: "☀️ Clear", rain: "🌧 Rain", storm: "⛈ Storm", fog: "🌫 Fog", snow: "❄️ Snow" }, RADIO = { score: "🎵 VOID Score", voidfm: "📻 VOID FM", off: "🔇 Radio off" };
81
+ function chips() { document.getElementById("gChips").innerHTML = `<span>${{ night: "🌙", sunset: "🌇", day: "☀️" }[W.timeOfDay]} ${W.timeOfDay}</span><span>${WX_ICON[atmos.weather]}</span>`; document.getElementById("gWeather").innerHTML = `<b>${WX_ICON[SET.weather].split(" ")[0]}</b>${WX_ICON[SET.weather].split(" ").slice(1).join(" ")}`; document.getElementById("gRadio").innerHTML = `<b>${RADIO[SET.radio].split(" ")[0]}</b>${RADIO[SET.radio].split(" ").slice(1).join(" ")}`; }
82
+ document.getElementById("gWeather").onclick = () => { SET.weather = WEATHERS[(WEATHERS.indexOf(SET.weather) + 1) % WEATHERS.length]; atmos.setWeather(SET.weather); store.set("void.settings", SET); chips(); toast(WX_ICON[SET.weather]); };
83
+ document.getElementById("gRadio").onclick = () => { const k = Object.keys(RADIO); SET.radio = k[(k.indexOf(SET.radio) + 1) % k.length]; if (!sound.on) setSound(true); sound.setRadio(SET.radio); store.set("void.settings", SET); chips(); toast(RADIO[SET.radio]); };
84
+ // ---------- the menu (☰ or Esc): everything that isn't driving lives here ----------
85
+ const menuEl = document.getElementById("gMenu");
86
+ function menu(open) {
87
+ if (open == null) open = menuEl.hidden;
88
+ menuEl.hidden = !open; document.body.classList.toggle("g-menu-open", open); if (open) { renderGoals(); chips(); }
89
+ if (open && document.pointerLockElement) document.exitPointerLock();
90
+ if (!net.online()) game.pause(open);
91
+ }
92
+ document.getElementById("gMenuBtn").onclick = () => menu(true);
93
+ document.getElementById("gMenuClose").onclick = () => menu(false);
94
+ document.getElementById("gExit").onclick = () => { menu(false); go("home"); };
95
+ menuEl.addEventListener("click", e => { const t = e.target.closest(".tile"); if (t && !t.closest(".set")) setTimeout(() => menu(false), 60); if (e.target === menuEl) menu(false); });
96
+ menuEl.querySelectorAll("[data-veh]").forEach(b => b.onclick = () => game.api.setVehicle(b.dataset.veh));
97
+ document.getElementById("gFuelNav").onclick = () => { const st = game.state; if (!st) return; const best = W.city.stations.slice().sort((a, b) => Math.hypot(a.x - st.x, a.z - st.z) - Math.hypot(b.x - st.x, b.z - st.z))[0]; nav.setDest({ name: "⛽ Fuel station", x: best.x, z: best.z }); };
98
+ function applySettings(save = true) {
99
+ for (const seg of menuEl.querySelectorAll(".seg[data-set]")) for (const b of seg.children) b.classList.toggle("on", SET[seg.dataset.set] === b.dataset.v);
100
+ document.getElementById("gSens").value = SET.sens; game.api.sens = +SET.sens;
101
+ document.body.classList.toggle("steer-buttons", SET.steer === "buttons");
102
+ const cap = W.setQuality(SET.q); perf.max = cap; perf.pr = Math.min(perf.pr, cap); if (renderer.getPixelRatio() > cap) { renderer.setPixelRatio(cap); composer.setPixelRatio(cap); } lastW = 0; resize();
103
+ if (save) store.set("void.settings", SET);
104
+ }
105
+ menuEl.querySelectorAll(".seg[data-set]").forEach(seg => seg.addEventListener("click", e => { const b = e.target.closest("button"); if (!b) return; e.preventDefault(); SET[seg.dataset.set] = b.dataset.v; if (seg.dataset.set === "q") { perf.pr = W.QUALITY[b.dataset.v].pr; perf.down = 0; } applySettings();
106
+ atmos.setWeather(SET.weather); }));
107
+ document.getElementById("gSens").addEventListener("input", e => { SET.sens = +e.target.value; applySettings(); });
108
+ // the touch joystick: drag the knob; left/right steers, up/down pitches when flying
109
+ {
110
+ const st = document.getElementById("gStick"), knob = st.querySelector("i"); let id = null, cx = 0, cy = 0;
111
+ const set = (x, y) => { const r = st.clientWidth / 2 - 10, l = Math.min(1, Math.hypot(x, y) / r), a = Math.atan2(y, x), kx = Math.cos(a) * l * r, ky = Math.sin(a) * l * r; knob.style.transform = `translate(${kx}px, ${ky}px)`; game.api.setStick(kx / r, ky / r); };
112
+ st.addEventListener("pointerdown", e => { id = e.pointerId; const b = st.getBoundingClientRect(); cx = b.left + b.width / 2; cy = b.top + b.height / 2; try { st.setPointerCapture(id); } catch { } set(e.clientX - cx, e.clientY - cy); e.preventDefault(); });
113
+ st.addEventListener("pointermove", e => { if (e.pointerId === id) set(e.clientX - cx, e.clientY - cy); });
114
+ const end = e => { if (e.pointerId !== id) return; id = null; knob.style.transform = ""; game.api.setStick(0, 0); };
115
+ st.addEventListener("pointerup", end); st.addEventListener("pointercancel", end);
116
+ }
117
+ // headlights that light the road at night
118
+ const heads = new THREE.SpotLight(0xfff1d6, 0, 70, .55, .6, 1.2); heads.position.set(2.2, .7, 0); heads.target.position.set(18, -1.5, 0); carRoot.add(heads, heads.target);
119
+ police = createPolice(scene, game.api, sound, life);
120
+ races = createRaces(scene, game.api, sound, W.canvasTex, net);
121
+ nav = createNav(scene, game.api, W, ZONES, races.starts);
122
+ const extras = createExtras(W, game.api, nav, sound);
123
+ document.getElementById("gTaxi").onclick = () => extras.toggle();
124
+
125
+ // ---------- online: other real players' cars, name tags, emotes, proximity voice ----------
126
+ const remotes = new Map();
127
+ const tagTex = (text, col = "#ffffff") => W.canvasTex(512, 96, (g, w, h) => { g.fillStyle = "rgba(0,0,0,.55)"; g.fillRect(0, 0, w, h); g.fillStyle = col; g.font = "800 50px Inter, sans-serif"; g.textAlign = "center"; g.fillText(text, w / 2, 66); });
128
+ function remoteFor(p) {
129
+ let r = remotes.get(p.id);
130
+ const model = Object.keys(MODELS)[p.model | 0] || "hydra";
131
+ if (r && r.model !== model) { scene.remove(r.root); remotes.delete(p.id); r = null; }
132
+ if (!r) {
133
+ const c = buildCar(model), root = new THREE.Group(); root.add(c.group); c.setReveal(1); c.setThrust(0, 0, 0, 0); c.setWings(0, 0);
134
+ c.group.traverse(o => { if (o.isMesh) o.castShadow = true; });
135
+ const tag = new THREE.Sprite(new THREE.SpriteMaterial({ map: tagTex(p.name), depthTest: false, toneMapped: false })); tag.scale.set(5, .95, 1); tag.position.y = 2.6; root.add(tag);
136
+ const emo = new THREE.Sprite(new THREE.SpriteMaterial({ map: tagTex(""), depthTest: false, toneMapped: false })); emo.scale.set(6, 1.15, 1); emo.position.y = 3.8; emo.visible = false; root.add(emo);
137
+ scene.add(root); r = { root, car: c, tag, emo, model, name: p.name, paint: null, emoT: 0 }; remotes.set(p.id, r);
138
+ }
139
+ if (r.name !== p.name) { r.name = p.name; r.tag.material.map = tagTex(p.name); }
140
+ if (p.paint && r.paint !== p.paint) { r.paint = p.paint; r.car.setPaint(p.paint); }
141
+ return r;
142
+ }
143
+ net.on("change", () => { for (const id of [...remotes.keys()]) if (!net.players().some(p => p.id === id)) { scene.remove(remotes.get(id).root); remotes.delete(id); } renderPlayers(); });
144
+ net.on("status", t => { document.getElementById("gNetStatus").textContent = t; document.getElementById("gNetBtn").classList.toggle("on", net.online()); });
145
+ net.on("mic", on => { const b = document.getElementById("gMic"); b.classList.toggle("on", on); b.textContent = on ? "🎙 Mic on" : "🎙 Voice chat"; });
146
+ net.on("emote", (m, from) => { const r = remotes.get(from), e = EMOTES[m.e | 0]; if (r) { r.emo.material.map = tagTex(e, "#ffd23d"); r.emo.visible = true; r.emoT = 4; } feed(`${net.nameOf(from)}: ${e}`); });
147
+ function feed(t) { const f = document.getElementById("gFeed"); const d = document.createElement("div"); d.textContent = t; f.prepend(d); setTimeout(() => d.remove(), 7000); while (f.children.length > 5) f.lastChild.remove(); }
148
+ function renderPlayers() { document.getElementById("gPlayers").innerHTML = net.online() ? [`<b>${net.name} (you)</b>`, ...net.players().map(p => `<span>${p.vc ? "🎙 " : ""}${p.name}</span>`)].join("") : ""; }
149
+ {
150
+ const $ = id => document.getElementById(id), panel = $("gNetPanel");
151
+ $("gNetName").value = store.get("void.name") || "";
152
+ $("gNetBtn").onclick = () => { panel.hidden = !panel.hidden; };
153
+ $("gNetClose").onclick = () => panel.hidden = true;
154
+ const go = room => { const nm = $("gNetName").value; store.set("void.name", nm); net.join(room, nm); panel.hidden = true; };
155
+ $("gNetPublic").onclick = () => go("public-1");
156
+ $("gNetCreate").onclick = () => { const code = Math.random().toString(36).slice(2, 7); $("gNetCode").value = code; go("room-" + code); toast(`Room code: ${code}. Tell your friends!`); };
157
+ $("gNetJoin").onclick = () => { const code = $("gNetCode").value.trim().toLowerCase(); if (code) go("room-" + code); };
158
+ $("gNetLeave").onclick = () => { net.leave(); panel.hidden = true; };
159
+ $("gMic").onclick = () => net.setMic(!net.mic);
160
+ $("gEmotes").innerHTML = EMOTES.map((e, k) => `<button class="pill" data-e="${k}">${e}</button>`).join("");
161
+ $("gEmotes").onclick = ev => { const b = ev.target.closest("[data-e]"); if (!b || !net.online()) return; net.send({ t: "emote", e: +b.dataset.e }); feed(`You: ${EMOTES[+b.dataset.e]}`); };
162
+ }
163
+ W.setTime(store.get("void.time") || "night");
164
+ // fill the car's reflection cube once before the first frame, so the paint never samples an empty one
165
+
166
+ $("osmCredit").textContent = W.credit;
167
+ // the garage: the Build panel over the game, the game paused underneath
168
+ function openGarage(on) { document.body.classList.toggle("garage", on); game.pause(on); if (on && car.repair) { car.repair(); applyBuild(); if (game.state) game.state.hp = 100; } }
169
+ $("gGarageClose").onclick = () => openGarage(false);
170
+ const nozzles = (car.nozzles || [[.9, .3, 1], [.9, .3, -1], [-.95, .38, 1], [-.95, .38, -1]]).map(([x, y, s]) => new THREE.Vector3(x, y - .5, s));
171
+
172
+ // ---------- configurator ----------
173
+ const OPTS = {
174
+ paint: { label: "Paint", items: [["Void Black", "#0a0a0c"], ["Stealth Grey", "#2b2d32"], ["Liquid Silver", "#9fa3aa"], ["Ghost White", "#e9e9ea"], ["Blood Red", "#6f0a12"], ["Ember Orange", "#c9480c"], ["Ion Blue", "#123a8c"], ["Venom Green", "#2d6a1e"], ["Candy Purple", "#4a1270"], ["Sunset Gold", "#b8862a"], ["Pearl Pink", "#e8a6c0"], ["Arctic Teal", "#1f8a8a"], ["Lime Rush", "#8acb1a"], ["Cherry Pop", "#d2163c"], ["Midnight Navy", "#0d1838"], ["Chrome", "#d8dadd"]] },
175
+ finish: { label: "Finish", seg: true, items: [["Gloss", "gloss"], ["Satin", "satin"], ["Matte", "matte"]] },
176
+ rim: { label: "Wheels", items: [["Black", "#121215"], ["Gunmetal", "#3a3d44"], ["Silver", "#b8bcc4"], ["Bronze", "#7a5a32"], ["Gold", "#c9a227"], ["Red", "#b0141f"], ["White", "#e8e8ea"], ["Ion", "#2ad8e8"]] },
177
+ cal: { label: "Calipers", items: [["Red", "#c1121f"], ["Black", "#2a2a30"], ["Yellow", "#e0b000"], ["White", "#e8e8e8"], ["Ion", "#3df5ff"]] },
178
+ trim: { label: "Accents", items: [["Red", "#c1121f"], ["Black", "#16161a"], ["White", "#e8e8e8"], ["Gold", "#b8912e"], ["Ion", "#3df5ff"]] },
179
+ light: { label: "Lights", items: [["Ice", "#e8fbff"], ["Amber", "#ffb347"], ["Ion", "#6ad8ff"], ["Violet", "#b38cff"]] },
180
+ glow: { label: "Underglow", items: [["Off", ""], ["White", "#ffffff"], ["Red", "#ff2233"], ["Ion", "#3df5ff"], ["Violet", "#9b5cff"]] },
181
+ spoiler: { label: "Spoiler", seg: true, items: [["Stock", "none"], ["Ducktail", "ducktail"], ["GT wing", "gt"], ["Swan neck", "swan"], ["Rally", "rally"]] },
182
+ livery: { label: "Livery", seg: true, items: [["Clean", "none"], ["Twin stripes", "stripes"], ["Centre stripe", "center"], ["Side stripe", "side"], ["Race #42", "race"]] },
183
+ livc: { label: "Livery colour", items: [["White", "#f2f2f2"], ["Red", "#c1121f"], ["Black", "#101012"], ["Gold", "#c9a227"], ["Ion", "#3df5ff"], ["Orange", "#ff6a00"]] },
184
+ tint: { label: "Windows", seg: true, items: [["Light", "light"], ["Dark", "dark"], ["Limo", "limo"], ["Mirror", "mirror"]] },
185
+ flame: { label: "Nitro flames", items: [["Blue", "#4fa8ff"], ["Orange", "#ff7a1a"], ["Green", "#3dff6a"], ["Purple", "#b05cff"], ["Pink", "#ff4fd8"]] },
186
+ horn: { label: "Horn", seg: true, items: [["Classic", 0], ["Air horn", 1], ["Tune", 2]] },
187
+ };
188
+ OPTS.model = { label: "Car", seg: true, items: Object.entries(MODELS).map(([k, m]) => [m.name, k]) };
189
+ const DEFAULT = { model: 0, paint: 0, finish: 0, rim: 0, cal: 0, trim: 0, light: 0, glow: 0, spoiler: 0, livery: 0, livc: 0, tint: 1, flame: 0, horn: 0 };
190
+ let build = { ...DEFAULT, ...(store.get("void.build2") || {}), ...(store.get("void.build3") || {}) };
191
+ try { const h = new URLSearchParams(location.hash.slice(1)).get("b"); if (h) { const v = h.split(".").map(Number); Object.keys(DEFAULT).forEach((k, i) => { if (OPTS[k].items[v[i]]) build[k] = v[i]; }); } } catch { }
192
+ function applyBuild() {
193
+ useModel(OPTS.model.items[build.model][1]);
194
+ car.setSpoiler(OPTS.spoiler.items[build.spoiler][1]); car.setLivery(OPTS.livery.items[build.livery][1], OPTS.livc.items[build.livc][1]);
195
+ car.setTint(OPTS.tint.items[build.tint][1]); car.setFlameColor(OPTS.flame.items[build.flame][1]);
196
+ car.setPaint(OPTS.paint.items[build.paint][1]); car.setFinish(OPTS.finish.items[build.finish][1]);
197
+ car.setRim(OPTS.rim.items[build.rim][1]); car.setAccent(OPTS.cal.items[build.cal][1]); car.setTrim(OPTS.trim.items[build.trim][1]); car.setLight(OPTS.light.items[build.light][1]);
198
+ const gl = OPTS.glow.items[build.glow][1]; if (gl) fx.glow.material.color.set(gl).multiplyScalar(1.4);
199
+ store.set("void.build3", build);
200
+ $("sum").innerHTML = `<b>${car.name.toUpperCase()} &middot; ${OPTS.paint.items[build.paint][0]}</b>${OPTS.spoiler.items[build.spoiler][0]} spoiler, ${OPTS.livery.items[build.livery][0].toLowerCase()} livery, ${OPTS.finish.items[build.finish][0]} paint, ${OPTS.rim.items[build.rim][0].toLowerCase()} wheels, ${OPTS.cal.items[build.cal][0].toLowerCase()} calipers, ${OPTS.trim.items[build.trim][0].toLowerCase()} accents, ${OPTS.light.items[build.light][0].toLowerCase()} lights${gl ? ", " + OPTS.glow.items[build.glow][0].toLowerCase() + " underglow" : ""}`;
201
+ for (const b of document.querySelectorAll("#cfgBody button")) b.setAttribute("aria-pressed", String(build[b.dataset.k] === +b.dataset.i));
202
+ for (const k in OPTS) { const n = document.querySelector(`[data-name="${k}"]`); if (n) n.textContent = OPTS[k].items[build[k]][0]; }
203
+ }
204
+ const ORDER = ["model", "paint", "finish", "livery", "livc", "spoiler", "rim", "cal", "trim", "tint", "light", "glow", "flame", "horn"];
205
+ $("cfgBody").innerHTML = ORDER.map(k => [k, OPTS[k]]).map(([k, o]) => `<div class="grp"><div class="grp-h">${o.label}<b data-name="${k}"></b></div><div class="${o.seg ? "seg" : "sw"}">${o.items.map(([n, c], i) => o.seg
206
+ ? `<button data-k="${k}" data-i="${i}">${n}</button>`
207
+ : `<button data-k="${k}" data-i="${i}" title="${n}" aria-label="${o.label}: ${n}" style="background:${c || "repeating-linear-gradient(45deg,#222 0 4px,#111 4px 8px)"}"></button>`).join("")}</div></div>`).join("");
208
+ $("cfgBody").addEventListener("click", e => { const b = e.target.closest("button"); if (!b) return; build[b.dataset.k] = +b.dataset.i; applyBuild(); });
209
+ $("reset").onclick = () => { build = { ...DEFAULT, model: build.model }; applyBuild(); toast("Back to black and red"); };
210
+ $("share").onclick = async () => {
211
+ const url = location.origin + location.pathname + "#b=" + Object.keys(DEFAULT).map(k => build[k]).join(".");
212
+ try { await navigator.clipboard.writeText(url); toast("Link to your build copied"); } catch { prompt("Copy your build link", url); }
213
+ };
214
+ applyBuild();
215
+ let toastT;
216
+ function toast(t) { const el = $("toast"); el.textContent = t; el.classList.add("on"); clearTimeout(toastT); toastT = setTimeout(() => el.classList.remove("on"), 2200); }
217
+
218
+ // ---------- sound ----------
219
+ function setSound(on) { sound.setOn(on); $("snd").setAttribute("aria-pressed", String(on)); $("snd").textContent = on ? "Sound on" : "Sound off"; if (on && mode === "watch" && w.playing) sound.startSong(w.t); }
220
+ $("snd").onclick = () => setSound(!sound.on);
221
+ $("rev").onclick = () => { if (!sound.on) setSound(true); sound.rev(); };
222
+
223
+ // ---------- modes ----------
224
+ let mode = "home";
225
+ const w = { t: 0, playing: false, dragging: false };
226
+ function go(next) {
227
+ if (next === mode) return;
228
+ $("fade").classList.add("on");
229
+ setTimeout(() => {
230
+ if (mode === "play") { game.exit(); openGarage(false); }
231
+ if (mode === "watch") { sound.stopSong(); w.playing = false; }
232
+ mode = next; document.body.dataset.mode = next;
233
+ if (next === "home") scrollTo(0, 0);
234
+ if (next === "watch") { if (!sound.on) setSound(true); playFrom(0); }
235
+ if (next === "play") { game.enter(); if (SET.radio !== "score") sound.setRadio(SET.radio); }
236
+ if (mode !== "play" && sound.radio && sound.radio !== "score") sound.setRadio("score");
237
+ $("fade").classList.remove("on");
238
+ }, 320);
239
+ }
240
+ document.addEventListener("click", e => { const b = e.target.closest("[data-go]"); if (b) { e.preventDefault(); go(b.dataset.go); } });
241
+ $("exit").onclick = () => go("home");
242
+ addEventListener("keydown", e => {
243
+ if (e.code === "Escape" && mode === "play" && !document.body.classList.contains("garage")) { menu(); return; }
244
+ if (e.code === "Escape" && mode !== "home") go("home");
245
+ if (mode === "watch") {
246
+ if (e.code === "Space") { e.preventDefault(); togglePlay(); }
247
+ if (e.code === "ArrowRight") seek(w.t + 4); if (e.code === "ArrowLeft") seek(w.t - 4);
248
+ }
249
+ });
250
+
251
+ // watch player
252
+ function playFrom(t) { w.t = clamp(t, 0, TOTAL); w.playing = true; $("wEnd").classList.remove("on"); if (sound.on) sound.startSong(w.t); setPlayIcon(); }
253
+ function pause() { w.playing = false; sound.stopSong(); setPlayIcon(); }
254
+ function togglePlay() { if (w.playing) pause(); else playFrom(w.t >= TOTAL - .05 ? 0 : w.t); }
255
+ function seek(t) { w.t = clamp(t, 0, TOTAL); if (w.playing) playFrom(w.t); }
256
+ function setPlayIcon() { $("wPlay").innerHTML = w.playing ? "&#10074;&#10074;" : "&#9654;"; $("wPlay").setAttribute("aria-label", w.playing ? "Pause" : "Play"); }
257
+ $("wPlay").onclick = togglePlay;
258
+ $("wAgain").onclick = () => playFrom(0);
259
+ const scrub = $("wScrub"); scrub.max = TOTAL;
260
+ scrub.addEventListener("input", () => { w.dragging = true; w.t = +scrub.value; if (w.playing) { sound.stopSong(); } });
261
+ scrub.addEventListener("change", () => { w.dragging = false; if (w.playing) playFrom(+scrub.value); });
262
+ $("wTicks").innerHTML = CHAPTERS.filter(c => c[1]).map(c => `<button style="left:${c[0] * BAR / TOTAL * 100}%" data-t="${c[0] * BAR}">${c[1]}</button>`).join("");
263
+ $("wTicks").addEventListener("click", e => { const b = e.target.closest("button"); if (b) { seek(+b.dataset.t); if (!w.playing) playFrom(+b.dataset.t); } });
264
+ const fmt = s => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;
265
+
266
+ // drag to turn the car on the home and build screens
267
+ const orbit = { a: .7, v: 0, drag: false, x: 0 };
268
+ addEventListener("pointerdown", e => { if ((mode !== "build" && mode !== "home") || e.target !== $("gl") && !e.target.closest(".drag-hint, #buildUI") || e.target.closest(".cfg, button")) return; orbit.drag = true; orbit.x = e.clientX; });
269
+ addEventListener("pointermove", e => { if (!orbit.drag) return; orbit.v = (e.clientX - orbit.x) * -.006; orbit.a += orbit.v; orbit.x = e.clientX; });
270
+ addEventListener("pointerup", () => { orbit.drag = false; });
271
+
272
+ // ---------- resize: ignore the phone address bar sliding, follow rotation and folding ----------
273
+ let lastW = 0, lastH = 0;
274
+ function resize() {
275
+ const ww = innerWidth, hh = Math.max(innerHeight, document.documentElement.clientHeight);
276
+ if (!ww || !hh) return;
277
+ if (ww === lastW && Math.abs(hh - lastH) < 140 && lastW) return;
278
+ lastW = ww; lastH = hh; renderer.setSize(ww, hh, false); composer.setSize(ww, hh);
279
+ bloom.resolution.set(Math.max(1, ww * W.bloomRes), Math.max(1, hh * W.bloomRes)); camera.aspect = ww / hh;
280
+ }
281
+ addEventListener("resize", resize); addEventListener("orientationchange", () => setTimeout(resize, 200));
282
+ if (window.visualViewport) visualViewport.addEventListener("resize", resize);
283
+ resize();
284
+ const fovFor = f => { const a = camera.aspect; if (a >= 1.5) return f; const h = 2 * Math.atan(Math.tan(f * Math.PI / 360) * 1.5); return Math.min(88, 2 * Math.atan(Math.tan(h / 2) / a) * 180 / Math.PI); };
285
+
286
+ // ---------- the showroom pose (home and build) ----------
287
+ const showFr = frame(); W.track.sample(W.track.D[W.track.idxX(0)], showFr);
288
+ const intro = { t: -1 }; // the car drives in once the loader lifts
289
+ function showroom(dt, time) {
290
+ let introX = 0, introV = 0;
291
+ if (intro.t >= 0 && intro.t < 3.2) { intro.t += dt; const u = Math.min(1, intro.t / 3.2); introX = -46 * Math.pow(1 - u, 3); introV = 46 * 3 * Math.pow(1 - u, 2) / 3.2; }
292
+ else if (intro.t < 0) introX = -46;
293
+ if (!orbit.drag) { orbit.v *= .94; orbit.a += orbit.v + (REDUCED ? 0 : dt * (mode === "home" ? .16 : .1)); }
294
+ const hf = 2 * Math.atan(Math.tan(fovFor(38) * Math.PI / 360) * camera.aspect), fit = 3.1 / Math.tan(hf / 2); // fit the whole car across the screen
295
+ const scrolled = mode === "home" ? clamp(scrollY / innerHeight) : 0, dist = Math.max(mode === "build" ? 8.8 : 8.2, fit) + scrolled * 2;
296
+ const cam = { pos: new THREE.Vector3(Math.cos(orbit.a) * dist, 1.5 + scrolled * 4, Math.sin(orbit.a) * dist), look: new THREE.Vector3(0, .5 - scrolled * .4, 0), fov: 38 };
297
+ if (camera.aspect < 1) cam.look.y = mode === "build" ? -1.1 : -.2;
298
+ else if (mode === "build") { const right = new THREE.Vector3().subVectors(cam.look, cam.pos).cross(new THREE.Vector3(0, 1, 0)).normalize(); cam.look.addScaledVector(right, 1.7); }
299
+ const pos = showFr.p.clone(); pos.x += introX; const fr = { ...showFr, p: pos };
300
+ if (introX < -.01) cam.look.x = Math.max(introX * .35, -8);
301
+ return { pos, quat: new THREE.Quaternion(), fr, speed: introV * 3.6, g: 1, alt: 0, vs: 0, thrust: { power: 0, angle: 0, deploy: 0 }, wings: 0, air: false, cam, inside: false, screenOn: false, reveal: 1, rpm: 900, gear: 1, load: .1, engine: .6, mode: "PARK", zones: [] };
302
+ }
303
+
304
+ // ---------- per frame ----------
305
+ const clock = new THREE.Clock();
306
+ let lastGauge = 0, lastChips = 0, cycleT = 0;
307
+ // the speedometer: a dial with a glowing arc, the speed, the gear (or altitude when flying) and what you're in
308
+ const gauge = document.getElementById("gGauge"), gx = gauge.getContext("2d");
309
+ function drawGauge(S) {
310
+ const W2 = gauge.width, c = W2 / 2, r = c - 22, a0 = Math.PI * .75, a1 = Math.PI * 2.25, max = S.veh === "plane" ? 600 : S.veh === "boat" ? 140 : 360, f = Math.min(1, S.speed / max);
311
+ gx.clearRect(0, 0, W2, W2);
312
+ gx.beginPath(); gx.arc(c, c, r + 14, 0, 7); gx.fillStyle = "rgba(6,8,14,.62)"; gx.fill();
313
+ gx.lineCap = "round"; gx.lineWidth = 14; gx.beginPath(); gx.arc(c, c, r, a0, a1); gx.strokeStyle = "rgba(255,255,255,.12)"; gx.stroke();
314
+ const grd = gx.createLinearGradient(0, W2, W2, 0); grd.addColorStop(0, "#3df5ff"); grd.addColorStop(.6, "#ffffff"); grd.addColorStop(1, "#ff2a3a");
315
+ gx.beginPath(); gx.arc(c, c, r, a0, a0 + (a1 - a0) * f); gx.strokeStyle = grd; gx.shadowColor = "#3df5ff"; gx.shadowBlur = 16; gx.stroke(); gx.shadowBlur = 0;
316
+ gx.lineWidth = 2; gx.strokeStyle = "rgba(255,255,255,.5)"; for (let k = 0; k <= 12; k++) { const a = a0 + (a1 - a0) * k / 12, i = r - 18, o = r - (k % 3 ? 24 : 30); gx.beginPath(); gx.moveTo(c + Math.cos(a) * i, c + Math.sin(a) * i); gx.lineTo(c + Math.cos(a) * o, c + Math.sin(a) * o); gx.stroke(); }
317
+ gx.fillStyle = "#fff"; gx.textAlign = "center"; gx.font = `900 ${W2 * .22}px Unbounded, Inter, sans-serif`; gx.fillText(Math.round(S.speed), c, c + W2 * .06);
318
+ gx.font = `700 ${W2 * .055}px Inter, sans-serif`; gx.fillStyle = "rgba(255,255,255,.6)"; gx.fillText("KM/H", c, c + W2 * .14);
319
+ gx.font = `800 ${W2 * .07}px Unbounded, Inter, sans-serif`; gx.fillStyle = S.air ? "#3df5ff" : "#ffd23d";
320
+ gx.fillText(S.air || S.veh === "plane" || S.veh === "heli" ? `${Math.round(S.alt)} m` : S.veh === "boat" ? "BOAT" : `GEAR ${S.gear}`, c, c + W2 * .3);
321
+ if (S.nitro > .1) { gx.font = `800 ${W2 * .05}px Inter, sans-serif`; gx.fillStyle = "#3df5ff"; gx.fillText("NITRO", c, c - W2 * .16); }
322
+ }
323
+ let wasWrecked = false, wreckPose = null; const wrecks = [];
324
+ const perf = { t: 0, n: 0, pr: renderer.getPixelRatio(), max: renderer.getPixelRatio(), down: 0 };
325
+ applySettings();
326
+ let lastHud = 0, prevGear = 1, feedFlip = 0;
327
+ function frameLoop(fixed) {
328
+ const raw = fixed ? 0 : clock.getDelta(), dt = fixed || Math.min(.05, raw), time = clock.elapsedTime;
329
+ // adaptive resolution: drop the pixel count when frames run slow, bring it back when there is headroom
330
+ if (!fixed && raw < .5) {
331
+ perf.t += raw; perf.n++;
332
+ if (perf.t > 1.5) {
333
+ const avg = perf.t / perf.n, was = perf.pr;
334
+ if (avg > 1 / 45 && perf.pr > .6) perf.pr = Math.max(.6, perf.pr - (avg > 1 / 25 ? .25 : .12));
335
+ else if (avg > 1 / 40 && mode === "play" && ++perf.down >= 3 && SET.q !== "low") { // still slow at the lowest resolution: drop a quality level
336
+ perf.down = 0; SET.q = { ultra: "high", high: "medium", medium: "low" }[SET.q]; perf.pr = W.QUALITY[SET.q].pr; applySettings(false); toast(`Graphics set to ${SET.q} to keep it smooth`);
337
+ }
338
+ else if (avg < 1 / 58 && perf.pr < perf.max) perf.pr = Math.min(perf.max, perf.pr + .08);
339
+ if (perf.pr !== was) { renderer.setPixelRatio(perf.pr); composer.setPixelRatio(perf.pr); lastW = 0; resize(); }
340
+ perf.t = perf.n = 0;
341
+ }
342
+ }
343
+ let S;
344
+ if (mode === "watch") {
345
+ if (w.playing && !w.dragging) {
346
+ const st = sound.on ? sound.songTime() : null;
347
+ w.t = st != null ? st : w.t + dt;
348
+ if (w.t >= TOTAL) { w.t = TOTAL; pause(); $("wEnd").classList.add("on"); }
349
+ }
350
+ S = watch.at(w.t, time, camera.aspect, fovFor);
351
+ if (!w.dragging) scrub.value = w.t;
352
+ scrub.style.setProperty("--p", (w.t / TOTAL * 100) + "%");
353
+ $("wTime").textContent = `${fmt(w.t)} / ${fmt(TOTAL)}`;
354
+ const ch = S.chapter, cap = $("wCap");
355
+ if (cap.dataset.ch !== ch[1]) { cap.dataset.ch = ch[1]; cap.classList.add("hide"); setTimeout(() => { $("wNum").textContent = ch[1] ? String(CHAPTERS.indexOf(ch) + 1).padStart(2, "0") : ""; $("wTitle").textContent = ch[1]; $("wSub").textContent = ch[2]; cap.classList.toggle("hide", !ch[1]); }, 250); }
356
+ $("telem").style.opacity = S.bar > 2 && !S.inside && S.bar < 17.5 ? 1 : 0;
357
+ $("tSpd").textContent = Math.round(S.speed); $("tG").textContent = S.g.toFixed(1); $("tAlt").textContent = Math.round(S.alt);
358
+ $("dream").style.opacity = S.dream; $("fade").style.opacity = S.fade;
359
+ } else if (mode === "play") S = game.update(dt, time, camera.aspect);
360
+ else S = showroom(dt, time);
361
+ life.update(dt, time, mode === "play" ? S.player : null, camera.position);
362
+ if (mode === "play") {
363
+ police.update(dt, time); races.update(dt, time); nav.update();
364
+ const st = game.state, stars = police.stars;
365
+ document.getElementById("gStars").textContent = stars ? "★".repeat(stars) + "☆".repeat(5 - stars) : "";
366
+ document.getElementById("gStars").classList.toggle("bust", police.bust > .5);
367
+ const pr = races.progress();
368
+ net.tick(dt, { p: [st.x, st.y, st.z, st.yaw, st.pitch, st.roll].map(v => Math.round(v * 100) / 100), m: Object.keys(MODELS).indexOf(car.model), c: OPTS.paint.items[build.paint][1], v: Math.round(S.speed), a: S.air ? 1 : 0, r: pr ? pr.race : 0, rp: pr ? pr.rp : 0, rf: pr ? pr.rf : 0, w: stars });
369
+ for (const p of net.players()) {
370
+ const at = net.sample(p); const r = remoteFor(p); r.at = at;
371
+ if (!at || at.stale) { r.root.visible = false; continue; }
372
+ r.root.visible = true; r.root.position.set(at.x, at.y, at.z); r.root.rotation.set(0, -at.yaw, 0); r.car.group.rotation.set(at.roll, 0, at.pitch, "XYZ");
373
+ r.car.setThrust(at.air ? .6 : 0, at.air && at.v > 90 ? 1 : 0, at.air ? 1 : 0, time); r.car.setWings(at.air && at.v > 100 ? 1 : 0, time);
374
+ for (const wh of r.car.wheels) wh.rotation.z -= at.v / 3.6 * dt / .37;
375
+ if (r.emoT > 0 && (r.emoT -= dt) <= 0) r.emo.visible = false;
376
+ const dx = st.x - at.x, dz = st.z - at.z, d = Math.hypot(dx, dz);
377
+ net.setVolume(p.id, 1 - d / 260);
378
+ if (d < 3.4 && d > .01 && Math.abs(st.y - at.y) < 2) { st.x += dx / d * (3.4 - d) * .5; st.z += dz / d * (3.4 - d) * .5; st.vel.multiplyScalar(.9); }
379
+ }
380
+ } else { for (const r of remotes.values()) r.root.visible = false; net.tick(dt, null); } // the host keeps relaying from the menus
381
+ W.city.update(time, camera.position);
382
+ W.follow(S.pos);
383
+ if (mode !== "watch") $("fade").style.opacity = "";
384
+
385
+ // the car, or the plane / helicopter / boat
386
+ const veh = mode === "play" ? S.veh || "car" : "car";
387
+ carRoot.visible = veh === "car";
388
+ vehicles.show(veh === "car" ? null : veh, S.pos, S.quat, S, time, dt);
389
+ if (S.splash) for (let k = 0; k < 6; k++) { const pf = fx.puffs[fx.puffI++ % fx.puffs.length]; pf.s.position.copy(S.pos).add(new THREE.Vector3((Math.random() - .5) * 3, .3, (Math.random() - .5) * 3)); pf.life = 1; pf.s.visible = true; pf.grow = .8; pf.s.scale.setScalar(.8); pf.s.material.color.set(0xeaf6ff); pf.v.set((Math.random() - .5) * 6, 4 + Math.random() * 4, (Math.random() - .5) * 6); }
390
+ if (veh === "boat" && S.speed > 12 && Math.random() < .6) { const back = new THREE.Vector3(-3.6, .1, (Math.random() - .5) * 2).applyQuaternion(S.quat).add(S.pos); const pf = fx.puffs[fx.puffI++ % fx.puffs.length]; pf.s.position.copy(back); pf.life = 1; pf.s.visible = true; pf.grow = .5; pf.s.scale.setScalar(.5); pf.s.material.color.set(0xf4fbff); pf.v.set((Math.random() - .5) * 2, .6, (Math.random() - .5) * 2); }
391
+ const night = W.timeOfDay !== "day";
392
+ heads.intensity = night && veh === "car" ? (W.timeOfDay === "night" ? 260 : 120) : 0;
393
+ W.sky.position.copy(camera.position); W.grade.uniforms.time.value = time % 100;
394
+ W.grade.uniforms.blur.value = mode === "play" ? Math.max(0, Math.min(1, (S.speed - 160) / 220)) * .9 + (S.nitro || 0) * .5 : 0;
395
+ atmos.update(dt, time, S, mode === "play" ? game.state : null);
396
+ W.city.poolMat.opacity = W.timeOfDay === "night" ? 1 : W.timeOfDay === "sunset" ? .45 : 0; W.city.poolMat.visible = W.timeOfDay !== "day";
397
+ extras.sky(dt, time);
398
+ // the living city: when switched on, the day turns and the weather changes on its own
399
+ if (SET.cycle === "on" && mode === "play" && (cycleT += dt) > 150) { cycleT = 0; cycleTime(); if (Math.random() < .5) { const w = ["clear", "clear", "rain", "fog", "storm", "snow"][Math.floor(Math.random() * 6)]; atmos.setWeather(w); SET.weather = w; } }
400
+ if (mode === "play") { extras.update(dt, time); goals.stats.coins = extras.coins().got; goals.update(dt, game.state, S.speed); if (time - lastChips > 2) { lastChips = time; chips(); } }
401
+ if (mode === "play" && time - lastGauge > .05) { lastGauge = time; drawGauge(S); const fu = document.getElementById("gFuel"); if (fu && S.fuel != null) { fu.style.setProperty("--v", S.fuel); fu.classList.toggle("low", S.fuel < .2); } }
402
+ car.group.position.copy(S.pos); car.group.quaternion.copy(S.quat);
403
+ car.setReveal(S.reveal);
404
+ car.setThrust(S.thrust.power, S.thrust.angle, S.thrust.deploy, time);
405
+ car.setFlame(S.nitro || 0, time);
406
+ // damage: dent the model where it was hit; a destroyed car is left where it crashed and a fresh one is built for you
407
+ const gs = mode === "play" ? game.state : null;
408
+ if (gs && gs.impacts && gs.impacts.length && car.damage) { carRoot.updateMatrixWorld(true); for (const im of gs.impacts.splice(0)) car.damage(carRoot.worldToLocal(new THREE.Vector3(im.x, im.y, im.z)), im.p); }
409
+ if (S.wrecked && !wasWrecked) { car.wreck && car.wreck(); wreckPose = { p: carRoot.position.clone(), q: carRoot.quaternion.clone() }; }
410
+ if (!S.wrecked && wasWrecked && wreckPose && inner) {
411
+ const wg = inner.group; carRoot.remove(wg); wg.position.copy(wreckPose.p); wg.quaternion.copy(wreckPose.q); scene.add(wg);
412
+ wrecks.push({ g: wg, t: 30 }); if (wrecks.length > 4) { const o = wrecks.shift(); scene.remove(o.g); }
413
+ useModel(car.model, true); applyBuild(); wreckPose = null;
414
+ }
415
+ wasWrecked = !!S.wrecked;
416
+ for (const w of wrecks) { w.t -= dt; if (Math.random() < .25 && w.t > 10) { const pf = fx.puffs[fx.puffI++ % fx.puffs.length]; pf.s.position.copy(w.g.position).add(new THREE.Vector3((Math.random() - .5) * 2, 1, (Math.random() - .5) * 2)); pf.life = 1; pf.s.visible = true; pf.grow = .6; pf.s.scale.setScalar(.6); pf.s.material.color.set(0x2a2a2a); pf.v.set(0, 2, 0); } }
417
+ for (let k = wrecks.length - 1; k >= 0; k--) if (wrecks[k].t <= 0) { scene.remove(wrecks[k].g); wrecks.splice(k, 1); }
418
+ car.setWings(S.wings, time);
419
+ const roll = S.speed / 3.6 * dt / .37;
420
+ for (const wh of car.wheels) wh.rotation.z -= S.air ? roll * .15 : roll;
421
+ car.group.updateMatrixWorld(true);
422
+
423
+ // shadow, underglow, exhaust, speed lines
424
+ const fr = S.fr, ground = clamp(1 - S.pos.y / 3) * (fr.u.y > .8 ? 1 : 0);
425
+ fx.shadow.position.set(S.pos.x, S.pos.y > .5 ? .07 : S.pos.y + .07, S.pos.z); fx.shadow.material.opacity = veh === "car" ? ground : 0; fx.shadow.rotation.z = Math.atan2(-fr.f.z, fr.f.x);
426
+ const glowOn = !!OPTS.glow.items[build.glow][1];
427
+ fx.glow.position.copy(fx.shadow.position).y += .01; fx.glow.rotation.z = fx.shadow.rotation.z; fx.glow.material.opacity = glowOn ? ground * .85 : 0;
428
+ if (S.thrust.power > .3) for (const n of nozzles) if (Math.random() < .18) {
429
+ const pf = fx.puffs[fx.puffI++ % fx.puffs.length], wp = n.clone().applyMatrix4(car.group.matrixWorld);
430
+ pf.s.position.copy(wp); pf.life = 1; pf.s.visible = true; pf.s.scale.setScalar(.4); pf.grow = .4; pf.s.material.color.set(0xc8d2e1);
431
+ pf.v.copy(fr.u).multiplyScalar(-(1 - S.thrust.angle) * 7).addScaledVector(fr.f, -S.thrust.angle * 9 - S.speed / 3.6 * .2).add(new THREE.Vector3(Math.random() - .5, Math.random() - .5, Math.random() - .5).multiplyScalar(1.5));
432
+ }
433
+ const emit = (p, v, col, size, life = 1) => { const pf = fx.puffs[fx.puffI++ % fx.puffs.length]; pf.s.position.copy(p); pf.life = life; pf.s.visible = true; pf.s.scale.setScalar(size); pf.s.material.color.set(col); pf.v.copy(v); pf.grow = size; };
434
+ if (mode === "play" && S.hp != null) {
435
+ const eng = new THREE.Vector3(-1.2, .9, 0).applyMatrix4(car.group.matrixWorld);
436
+ if (S.hp < 55 && !S.wrecked && Math.random() < (S.hp < 25 ? .5 : .2)) emit(eng, new THREE.Vector3((Math.random() - .5), 1.5 + Math.random(), (Math.random() - .5)), S.hp < 25 ? 0x222222 : 0x9a9a9a, .5);
437
+ if (S.hp < 20 && !S.wrecked && Math.random() < .35) emit(eng, new THREE.Vector3(0, 2.5, 0), 0xff7a1a, .35, .5);
438
+ if (S.sparks > .5) for (let k = 0; k < 4; k++) emit(S.pos.clone().add(new THREE.Vector3(0, .5, 0)), new THREE.Vector3((Math.random() - .5) * 12, Math.random() * 6, (Math.random() - .5) * 12), 0xffd27a, .12, .35);
439
+ if (S.boom > .95) for (let k = 0; k < 40; k++) emit(S.pos.clone().add(new THREE.Vector3(0, 1, 0)), new THREE.Vector3((Math.random() - .5) * 18, Math.random() * 14, (Math.random() - .5) * 18), k % 3 ? 0xff7a1a : 0x333333, 1.2, 1.4);
440
+ }
441
+ for (const pf of fx.puffs) if (pf.life > 0) {
442
+ pf.life -= dt * .9; pf.s.position.addScaledVector(pf.v, dt); pf.v.multiplyScalar(.97);
443
+ pf.s.scale.setScalar((pf.grow || .4) + (1 - pf.life) * 4.5); pf.s.material.opacity = Math.max(0, pf.life) * .5; if (pf.life <= 0) pf.s.visible = false;
444
+ }
445
+ const lineA = smooth(240, 320, S.speed) * (S.inside ? 0 : 1);
446
+ fx.lines.material.opacity = lineA * .08;
447
+ if (lineA > .01) {
448
+ const d = new THREE.Object3D();
449
+ for (let i = 0; i < fx.LINES; i++) {
450
+ const sd = fx.lineSeed[i]; sd[0] -= S.speed / 3.6 * dt * 1.6; if (sd[0] < -40) sd[0] += 80;
451
+ d.position.copy(fr.p).addScaledVector(fr.f, sd[0]).addScaledVector(fr.u, sd[1]).addScaledVector(fr.s, sd[2]); d.quaternion.copy(S.quat); d.scale.set(1.5 + S.speed * .018, 1, 1);
452
+ d.updateMatrix(); fx.lines.setMatrixAt(i, d.matrix);
453
+ }
454
+ fx.lines.instanceMatrix.needsUpdate = true;
455
+ }
456
+
457
+ // the front seat and its screens
458
+ if (S.screenOn) {
459
+ if (!COARSE || (feedFlip++ & 1)) interior.renderFeed(scene);
460
+ if (time - lastHud > .1) {
461
+ lastHud = time;
462
+ const hud = { time, speed: S.speed, alt: S.alt, vs: S.vs, mode: S.mode, zones: S.zones, gear: S.gear, rpm: S.rpm };
463
+ interior.drawHud(hud); interior.drawCluster(hud);
464
+ }
465
+ }
466
+ interior.wheel.rotation.x = 0;
467
+
468
+ // camera
469
+ const c = S.cam, shake = REDUCED ? 0 : (Math.max(0, S.g - 2) * .004 + S.thrust.power * .01 + (S.shake || 0) * .25 + (S.nitro || 0) * .02) * (S.inside ? .25 : 1);
470
+ camera.position.copy(c.pos).add(new THREE.Vector3(Math.sin(time * 53) * shake, Math.sin(time * 61 + 1) * shake, Math.sin(time * 47 + 2) * shake));
471
+ camera.up.copy(c.up || new THREE.Vector3(0, 1, 0)); camera.lookAt(c.look);
472
+ camera.fov = fovFor(c.fov); camera.near = S.inside || S.screenOn ? .02 : .05; camera.updateProjectionMatrix();
473
+ camLight.position.copy(camera.position).add(new THREE.Vector3(0, 3, 0)); camLight.target.position.copy(S.pos);
474
+ scene.fog.far = lerp(950, 2600, smooth(20, 160, S.alt)) * W.weatherFog; scene.fog.near = lerp(120, 400, smooth(20, 160, S.alt)) * W.weatherFog;
475
+ camera.far = scene.fog.far * 1.1 + 150; camera.updateProjectionMatrix(); // nothing past the fog gets drawn
476
+ // refresh the car's reflections every few frames (the car hides from its own camera)
477
+ // (no shadows, no crowds, a short view: it only has to look right in the paint)
478
+
479
+
480
+ // the car's own sound
481
+ if (S.gear > prevGear && !S.air && S.speed > 20) sound.pop();
482
+ prevGear = S.gear;
483
+ sound.car({ rpm: S.rpm, load: S.load, engine: mode === "build" || mode === "home" ? .4 : S.engine, thrust: S.thrust.power, speed: S.speed, inside: S.inside });
484
+
485
+ composer.render();
486
+ }
487
+
488
+ setLoad(95);
489
+ renderer.compile(scene, camera);
490
+ let raf;
491
+ let frameErr = 0;
492
+ const loop = () => { raf = requestAnimationFrame(loop); try { frameLoop(); } catch (e) { if (frameErr++ < 3) console.error(e); } }; // one bad frame never stops the game
493
+ loop();
494
+ setLoad(100);
495
+ setTimeout(() => { $("loader").classList.add("done"); setTimeout(() => { intro.t = 0; if (sound.on) sound.rev(); }, 450); }, 900);
496
+ document.addEventListener("visibilitychange", () => {
497
+ if (document.hidden) { cancelAnimationFrame(raf); if (mode === "watch" && w.playing) pause(); if (sound.ctx) sound.ctx.suspend(); }
498
+ else { clock.getDelta(); loop(); if (sound.on && sound.ctx) sound.ctx.resume(); }
499
+ });
500
+ window.VOID = { step: (n = 1, dt = 1 / 30) => { for (let i = 0; i < n; i++) frameLoop(dt); }, W, car, life, carCube, carEnv, get police() { return police; }, get races() { return races; }, get nav() { return nav; }, net, orbit, go, seek: t => { w.t = t; if (w.playing) playFrom(t); }, pause, get w() { return w; }, game }; // handy for testing in the console
static/npc.js CHANGED
@@ -99,7 +99,7 @@ export function createLife(scene, roads, walkways, COARSE) {
99
  const cross = (axis, k) => axis === 0 ? ax(k) : sz(k); // the coordinate of the k-th crossing road along this axis
100
  const crossW = (axis, k) => axis === 0 ? avW(k) : stW(k);
101
  const roadC = (axis, road) => axis === 0 ? sz(road) : ax(road);
102
- const N = COARSE ? 600 : 1500, NP = COARSE ? 1200 : 3000;
103
 
104
  // ---- vehicles ----
105
  const carMat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: .32, metalness: .55, envMapIntensity: 1.1 });
@@ -165,7 +165,7 @@ export function createLife(scene, roads, walkways, COARSE) {
165
  };
166
 
167
  // ---- per frame ----
168
- const legQ = new THREE.Quaternion(), legM = new THREE.Matrix4(), Z = new THREE.Vector3(0, 0, 1), squash = new THREE.Vector3(), m4 = new THREE.Matrix4(), q = new THREE.Quaternion(), e = new THREE.Euler(), Y = new THREE.Vector3(0, 1, 0), pos = new THREE.Vector3(), one = new THREE.Vector3(1, 1, 1), zero = new THREE.Vector3();
169
  const buckets = new Map(), tmp = {}, cell = new Map(), CELL = 30;
170
  let frameN = 0;
171
  function decide(c, k) { // at the crossing k: straight on, or turn onto the cross road
@@ -305,7 +305,7 @@ export function createLife(scene, roads, walkways, COARSE) {
305
  e.set(lie * Math.PI / 2 * .95, yaw + (p.fall ? p.fall.rot : 0), 0, "YXZ"); q.setFromEuler(e); m4.compose(pos.set(x, y, z), q, one);
306
  bodies.setMatrixAt(pk, m4); heads.setMatrixAt(pk, m4); hair.setMatrixAt(pk, m4);
307
  const swing = p.wait > 0 || p.down > 0 ? 0 : Math.sin(walk) * .5;
308
- for (const [leg, sgn, off] of [[legL, 1, .1], [legR, -1, -.1]]) { legQ.setFromAxisAngle(Z, swing * sgn); legM.compose(pos.set(0, .86, off), legQ, one); leg.setMatrixAt(pk, m4.clone().multiply(legM)); }
309
  bodies.setColorAt(pk, p.shirt); heads.setColorAt(pk, p.skin); legL.setColorAt(pk, p.pants); legR.setColorAt(pk, p.pants); hair.setColorAt(pk, p.hairC); pk++;
310
  }
311
  }
 
99
  const cross = (axis, k) => axis === 0 ? ax(k) : sz(k); // the coordinate of the k-th crossing road along this axis
100
  const crossW = (axis, k) => axis === 0 ? avW(k) : stW(k);
101
  const roadC = (axis, road) => axis === 0 ? sz(road) : ax(road);
102
+ const N = COARSE ? 500 : 1100, NP = COARSE ? 900 : 2000;
103
 
104
  // ---- vehicles ----
105
  const carMat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: .32, metalness: .55, envMapIntensity: 1.1 });
 
165
  };
166
 
167
  // ---- per frame ----
168
+ const legQ = new THREE.Quaternion(), legM = new THREE.Matrix4(), legT = new THREE.Matrix4(), Z = new THREE.Vector3(0, 0, 1), squash = new THREE.Vector3(), m4 = new THREE.Matrix4(), q = new THREE.Quaternion(), e = new THREE.Euler(), Y = new THREE.Vector3(0, 1, 0), pos = new THREE.Vector3(), one = new THREE.Vector3(1, 1, 1), zero = new THREE.Vector3();
169
  const buckets = new Map(), tmp = {}, cell = new Map(), CELL = 30;
170
  let frameN = 0;
171
  function decide(c, k) { // at the crossing k: straight on, or turn onto the cross road
 
305
  e.set(lie * Math.PI / 2 * .95, yaw + (p.fall ? p.fall.rot : 0), 0, "YXZ"); q.setFromEuler(e); m4.compose(pos.set(x, y, z), q, one);
306
  bodies.setMatrixAt(pk, m4); heads.setMatrixAt(pk, m4); hair.setMatrixAt(pk, m4);
307
  const swing = p.wait > 0 || p.down > 0 ? 0 : Math.sin(walk) * .5;
308
+ for (const [leg, sgn, off] of [[legL, 1, .1], [legR, -1, -.1]]) { legQ.setFromAxisAngle(Z, swing * sgn); legM.compose(pos.set(0, .86, off), legQ, one); leg.setMatrixAt(pk, legT.copy(m4).multiply(legM)); }
309
  bodies.setColorAt(pk, p.shirt); heads.setColorAt(pk, p.skin); legL.setColorAt(pk, p.pants); legR.setColorAt(pk, p.pants); hair.setColorAt(pk, p.hairC); pk++;
310
  }
311
  }
static/race.js CHANGED
@@ -12,6 +12,7 @@ export const ROUTES = [
12
  { id: "park", name: "Park Loop ×2", pts: [G(2, 12), G(5, 12), G(5, 18), G(2, 18), G(2, 12), G(5, 12), G(5, 18), G(2, 18), G(2, 13)] },
13
  { id: "bridge", name: "Bridge Run", pts: [G(7, 10), G(12, 10), [1400, 0, 0], [1690, 0, 0]] },
14
  { id: "downtown", name: "Downtown Dash", pts: [G(8, 13), G(12, 13), G(12, 19), G(9, 19), G(9, 15), G(11, 15)] },
 
15
  { id: "sky", name: "Sky Rings", air: true, pts: [[420, 0, -40], [420, 90, -160], [520, 120, -300], [430, 150, -450], [250, 170, -520], [60, 150, -460], [-60, 120, -330], [-120, 90, -180], [-260, 70, 60], [-400, 60, 250]] },
16
  ];
17
  const RIVALS = [["VIPER", 0xd21f2b], ["BLAZE", 0xff6a00], ["NOVA", 0x1f6fe0]];
 
12
  { id: "park", name: "Park Loop ×2", pts: [G(2, 12), G(5, 12), G(5, 18), G(2, 18), G(2, 12), G(5, 12), G(5, 18), G(2, 18), G(2, 13)] },
13
  { id: "bridge", name: "Bridge Run", pts: [G(7, 10), G(12, 10), [1400, 0, 0], [1690, 0, 0]] },
14
  { id: "downtown", name: "Downtown Dash", pts: [G(8, 13), G(12, 13), G(12, 19), G(9, 19), G(9, 15), G(11, 15)] },
15
+ { id: "drag", name: "Runway Drag", pts: [[-2600, 0, 0], [-2350, 0, 0], [-2100, 0, 0], [-1960, 0, 0]] },
16
  { id: "sky", name: "Sky Rings", air: true, pts: [[420, 0, -40], [420, 90, -160], [520, 120, -300], [430, 150, -450], [250, 170, -520], [60, 150, -460], [-60, 120, -330], [-120, 90, -180], [-260, 70, 60], [-400, 60, 250]] },
17
  ];
18
  const RIVALS = [["VIPER", 0xd21f2b], ["BLAZE", 0xff6a00], ["NOVA", 0x1f6fe0]];
static/style.css CHANGED
@@ -379,3 +379,16 @@ body[data-mode="play"] .hub-chip { display: none !important; }
379
  .g-menu[hidden] + * {} .g-menu:not([hidden]) > * { animation: menuIn .28s cubic-bezier(.2,.8,.2,1) both; }
380
  @keyframes menuIn { from { opacity: 0; transform: translateY(12px) scale(.98); } }
381
  @media (max-width: 820px) { .stats-row { grid-template-columns: repeat(2, minmax(0, 1fr)); } .goals { grid-template-columns: minmax(0, 1fr); } #playUI .hud-tr .chips { display: none; } }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  .g-menu[hidden] + * {} .g-menu:not([hidden]) > * { animation: menuIn .28s cubic-bezier(.2,.8,.2,1) both; }
380
  @keyframes menuIn { from { opacity: 0; transform: translateY(12px) scale(.98); } }
381
  @media (max-width: 820px) { .stats-row { grid-template-columns: repeat(2, minmax(0, 1fr)); } .goals { grid-template-columns: minmax(0, 1fr); } #playUI .hud-tr .chips { display: none; } }
382
+ .g-welcome { max-width: 460px !important; text-align: left; }
383
+ .g-welcome h2 { font: 900 30px var(--wide); margin: 0 0 4px; } .g-welcome .sub { color: var(--mute); margin: 0 0 14px; }
384
+ .g-welcome .tips { display: grid; gap: 8px; margin-bottom: 14px; }
385
+ .g-welcome .tips div { display: flex; align-items: center; gap: 12px; padding: 10px 12px; border-radius: 14px; background: rgba(255,255,255,.06); border: 1px solid rgba(255,255,255,.08); font-size: 13.5px; }
386
+ .g-welcome .tips b { font-size: 24px; } .g-welcome kbd { padding: 1px 6px; font-size: 11px; }
387
+ .g-welcome .big-go { width: 100%; padding: 14px; font-size: 14px; }
388
+ .touch-only { display: none; } @media (pointer: coarse) { .touch-only { display: block; } }
389
+ .g-job { padding: 7px 16px; border-radius: 12px; background: rgba(60,46,0,.8); border: 1px solid rgba(255,210,61,.6); color: #ffe48a; font: 700 14px var(--body); white-space: nowrap; }
390
+ .g-job[hidden] { display: none; }
391
+ @media (max-width: 820px) { .g-job { font-size: 12px; white-space: normal; } }
392
+ /* the menu takes its own scrolling (it sits inside the click-through play layer) */
393
+ .g-menu { pointer-events: auto !important; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; touch-action: pan-y; }
394
+ .g-panel { overscroll-behavior: contain; }
static/world.js CHANGED
@@ -148,15 +148,17 @@ export async function createWorld(canvas, COARSE) {
148
  captureCity();
149
  }
150
  // quality: Low / Medium / High / Ultra (the adaptive system steps it down by itself when frames run slow)
151
- const QUALITY = { low: { pr: .8, shadow: 0, bloom: false, grade: false }, medium: { pr: 1, shadow: 1024, bloom: true, grade: true }, high: { pr: 1.5, shadow: 2048, bloom: true, grade: true }, ultra: { pr: 2, shadow: 4096, bloom: true, grade: true } };
152
- let quality = "high";
153
  function setQuality(q) {
154
  const Q = QUALITY[q] || QUALITY.high; quality = q;
155
  const on = Q.shadow > 0;
156
  if (renderer.shadowMap.enabled !== on) { renderer.shadowMap.enabled = on; scene.traverse(o => { if (o.material) (Array.isArray(o.material) ? o.material : [o.material]).forEach(m => m.needsUpdate = true); }); }
157
  sun.castShadow = on;
158
  if (on && sun.shadow.mapSize.x !== Q.shadow) { sun.shadow.mapSize.set(Q.shadow, Q.shadow); if (sun.shadow.map) { sun.shadow.map.dispose(); sun.shadow.map = null; } }
159
- bloom.enabled = Q.bloom; grade.enabled = Q.grade;
 
 
160
  return Math.min(devicePixelRatio || 1, Q.pr);
161
  }
162
  function setWeatherLook(dim, over) { wxDim = dim; wxOver = over; setTime(timeOfDay); }
@@ -251,7 +253,7 @@ export async function createWorld(canvas, COARSE) {
251
  for (let i = 0; i < 90; i++) { const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: smokeTex, transparent: true, depthWrite: false, opacity: 0 })); s.visible = false; scene.add(s); puffs.push({ s, life: 0, v: new THREE.Vector3() }); }
252
 
253
  return {
254
- renderer, scene, camera, composer, bloom, grade, sky, sunDir, setWeatherLook, setFlash, weatherFog: 1, setQuality, get quality() { return quality; }, QUALITY, camLight, canvasTex, radial, buildings, city, setTime, follow, captureCity, get timeOfDay() { return timeOfDay; }, studioEnv,
255
  roads: city.roads, footprints: city.footprints, parks: city.parks, water: city.water, beaches: city.beaches, walkways: city.walkways, bounds: city.bounds, credit: city.credit,
256
  track: { P, F, S, U, D, N, loopIn, loopOut, rampIn, roadEnd, idxX, sample },
257
  fx: { shadow, glow, lines, LINES, lineSeed, puffs, puffI: 0 },
 
148
  captureCity();
149
  }
150
  // quality: Low / Medium / High / Ultra (the adaptive system steps it down by itself when frames run slow)
151
+ const QUALITY = { low: { pr: .75, shadow: 0, bloom: false, grade: false, msaa: 0, bres: .25 }, medium: { pr: 1, shadow: 1024, bloom: true, grade: true, msaa: 0, bres: .3 }, high: { pr: 1.5, shadow: 2048, bloom: true, grade: true, msaa: 4, bres: .5 }, ultra: { pr: 2, shadow: 4096, bloom: true, grade: true, msaa: 4, bres: .5 } };
152
+ let quality = "high"; const W0 = { bres: .5 };
153
  function setQuality(q) {
154
  const Q = QUALITY[q] || QUALITY.high; quality = q;
155
  const on = Q.shadow > 0;
156
  if (renderer.shadowMap.enabled !== on) { renderer.shadowMap.enabled = on; scene.traverse(o => { if (o.material) (Array.isArray(o.material) ? o.material : [o.material]).forEach(m => m.needsUpdate = true); }); }
157
  sun.castShadow = on;
158
  if (on && sun.shadow.mapSize.x !== Q.shadow) { sun.shadow.mapSize.set(Q.shadow, Q.shadow); if (sun.shadow.map) { sun.shadow.map.dispose(); sun.shadow.map = null; } }
159
+ bloom.enabled = Q.bloom; grade.enabled = Q.grade; W0.bres = Q.bres;
160
+ // multisampling only where the card can afford it (it is the biggest cost on laptop graphics)
161
+ for (const t of [composer.renderTarget1, composer.renderTarget2]) if (t.samples !== Q.msaa) { t.samples = Q.msaa; t.dispose(); }
162
  return Math.min(devicePixelRatio || 1, Q.pr);
163
  }
164
  function setWeatherLook(dim, over) { wxDim = dim; wxOver = over; setTime(timeOfDay); }
 
253
  for (let i = 0; i < 90; i++) { const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: smokeTex, transparent: true, depthWrite: false, opacity: 0 })); s.visible = false; scene.add(s); puffs.push({ s, life: 0, v: new THREE.Vector3() }); }
254
 
255
  return {
256
+ renderer, scene, camera, composer, bloom, grade, sky, sunDir, setWeatherLook, setFlash, weatherFog: 1, setQuality, get quality() { return quality; }, QUALITY, get bloomRes() { return W0.bres; }, camLight, canvasTex, radial, buildings, city, setTime, follow, captureCity, get timeOfDay() { return timeOfDay; }, studioEnv,
257
  roads: city.roads, footprints: city.footprints, parks: city.parks, water: city.water, beaches: city.beaches, walkways: city.walkways, bounds: city.bounds, credit: city.credit,
258
  track: { P, F, S, U, D, N, loopIn, loopOut, rampIn, roadEnd, idxX, sample },
259
  fx: { shadow, glow, lines, LINES, lineSeed, puffs, puffI: 0 },