27:18Gemini 4 Hydrogen: Cheaper Tokens, More Expensive Answers?
Nov 13, 2026 · YouTube
18:40ERNIE 5.5 Flash Preview vs GLM 5.3 Flash: Baidu's new model is very impressive!
Nov 11, 2026 · YouTube
36:22Fable 5.2 robbing me blind, plus: Nex AGI's N2.6 vs GLM 5.3 Flash
Nov 11, 2026 · YouTube
14:03Gemini 4 Carbon: Can it handle my challenges? (First look with one-shot coding tests)
Nov 10, 2026 · YouTube
47:51Ranking major U.S. Open-Weights Models. (Where does Ripple 65B fit in?)
Nov 6, 2026 · YouTube
10:57"Crouton Alpha": the latest super-efficient coding model by Meta?
Nov 3, 2026 · YouTube
38:58Testing Particle-1: a post-trained DeepSeek V4.1 Flash specializing in coding and efficiency
Oct 28, 2026 · YouTube
22:14GPT-6.1 Terra Pro vs Terra: How Much Better Is Pro?
Oct 27, 2026 · YouTube
29:55Kimi K3.1 Pro Looked Incredible. Then I Kept Testing.
Oct 26, 2026 · YouTube
31:28Is this company reselling GPT Sol 6.1 at a loss (for non-agentic/text-only)?🤔 Is this sustainable?
Oct 20, 2026 · YouTube
17:58Nemotron 3.5 Super VL vs Opus 5.5: Testing NVIDIA’s new coding juggernaut
Oct 15, 2026 · YouTube
16:04Testing a *massive* new open-weights model 🤯: Muse Spark Open (vs. Nemotron, Opus 5.5, and more)
Oct 15, 2026 · YouTube
16:43Gemini 4 Argon: Great 🐈 Animation, but a broken escalator. (Coding challenge vs Opus 5.5, Sol 6.1)
Oct 13, 2026 · YouTube
16:37Meta's new "Muse Wonder" AI is impressive... but can it compete with Anthropic's models?
Oct 12, 2026 · YouTube
11:12WOW... Haiku 5.5 is very impressive. RIP OpenAI?
Oct 7, 2026 · YouTube
22:47Mistral Large 4 Is Cheap. But Is It Good Enough to Compete?
Oct 6, 2026 · YouTube
22:02Is Pareto 26.10 Preview Just Routing to GPT Sol? I Tested It Against Sol 6.1 Pro
Oct 1, 2026 · YouTube
11:22I Tested Sonnet 5.5 Against Opus 5.5. Is It Actually Cheaper?
Sep 28, 2026 · YouTube
30:00Did Elon Musk's team "train the gay away"... and make Grok 4.7 worse?
Sep 26, 2026 · YouTube
10:58So... how much better is Claude Opus 5.5 vs. GPT-6 Sol, really?
Sep 23, 2026 · YouTube
9:38Claude Opus 5.5... the BEST new model for coding!! 🤩
Sep 22, 2026 · YouTube
29:00Grok 4.7: improved, but GLM 5.3 FlashX beat it anyway (benchmark against Gemini, Sol, etc.)
Sep 22, 2026 · YouTube
16:54Stealth Union Alpha: Is this another cheap GPT model? (better than Luna, cheaper than Terra?)
Sep 16, 2026 · YouTube
16:45DeepSeek V4.1 Flash Is Shockingly Good for the Price
Sep 10, 2026 · YouTube
17:14How much better is GPT-6 Astra over Claude Opus 5? Real Website and Coding Tests
Sep 5, 2026 · YouTube
29:13Implementing a multiplayer game with GPT-6 Astra (+ Gemini 3.8, Opus 5, Sol Pro)
Sep 5, 2026 · YouTube
19:42Meta Muse Spark 1.3 Review: A Huge Leap Forward
Sep 2, 2026 · YouTube
17:31Testing Gemini 3.8 Flash on Real Coding Challenges (vs. other models)
Sep 2, 2026 · YouTube
19:45Fable 5.1 writes an animated novel using Ren'Py... did it do better than Sol Pro 5.6?
Sep 1, 2026 · YouTube
14:09Testing IBM Granite-4.2-8B! Can it name 100 women?
Aug 31, 2026 · YouTube
17:37Tencent Hy4 Preview Tested: Is It Really Better Than Kimi K3 and GLM 5.3?
Aug 28, 2026 · YouTube
23:58Qwen 3.8 Flash Tested: UI, Coding, Physics & more - compared to Opus 5, Sol Pro, Grok
Aug 27, 2026 · YouTube
You are a game developer who ships browser demos that have to work on the first click, in front of an audience, on someone else's laptop.
Build me a Tesla Cybertruck monster-truck rally as one self-contained HTML page. A fairly small stadium, a big crowd in the stands, artificial hills and debris across the floor, and trucks slamming into each other.
Then make it match the spec below exactly. The spec is the challenge; a great-looking rally that ignores it is a miss.
.html page. No build step. Saved to disk and double-clicked, it runs.localStorage, sessionStorage, cookies or indexedDB. It runs in a sandboxed frame where touching them throws.Both are checkable in ten seconds, which is why they are here.
#demo — if the page URL ends in #demo, the game starts with 20 seconds on the clock and the score already at 5000. This must run through the real game state, not a cosmetic overlay. Everything else behaves normally.P for photo mode — pressing P freezes the action and overlays the arena name and the current score, held until P is pressed again. The simulation stops; it does not keep playing behind the card.One sentence: the name of your rally and what it looks like.
Exactly one fenced html block containing the whole page and nothing else.
Exactly four bullets.
#demo sets, and why it is not an overlay.P is pressed — the render loop, the physics step, or both.Cyber Crush Rally at the Voltage Bowl: five stainless-steel Cybertrucks on monster-truck wheels jump dirt hills, flatten junk cars and ram each other under stadium floodlights, inside a small neon-ringed bowl packed with a bouncing crowd on every side.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Cyber Crush Rally · Voltage Bowl</title>
<link rel="icon" href="data:,">
<style>
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#05070d;color:#fff;font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
canvas{display:block;outline:none}
#hud{position:fixed;inset:0;pointer-events:none;user-select:none;z-index:2}
.lbl{font-size:11px;letter-spacing:.25em;opacity:.75;font-weight:700}
.impact{font-family:Impact,"Arial Black","Franklin Gothic Heavy",sans-serif}
#arena{position:absolute;left:18px;top:14px}
#arena .name{font-size:34px;letter-spacing:.06em;line-height:1;text-shadow:0 0 12px rgba(0,229,255,.85),0 2px 0 #000}
#arena .sub{margin-top:5px;font-size:12px;letter-spacing:.3em;font-weight:700;color:#9fefff}
.live{color:#ff4d4d}
#demoTag{display:none;margin-top:6px;font-size:11px;letter-spacing:.3em;font-weight:800;background:#ff2bd6;color:#000;padding:2px 8px;border-radius:4px;width:max-content}
#clockBox{position:absolute;left:50%;top:10px;transform:translateX(-50%);text-align:center;background:rgba(0,0,0,.5);border:1px solid rgba(255,255,255,.15);padding:6px 24px 8px;border-radius:10px}
#clock{font-size:44px;line-height:1;font-variant-numeric:tabular-nums}
#clock.hurry{color:#ff5a4a}
#scoreBox{position:absolute;right:18px;top:10px;text-align:right;background:rgba(0,0,0,.5);border:1px solid rgba(255,255,255,.15);padding:6px 18px 8px;border-radius:10px;min-width:170px}
#score{font-size:40px;line-height:1;color:#ffe066;font-variant-numeric:tabular-nums}
#rivals{position:absolute;right:18px;top:96px;width:230px;font-size:12px}
.rv{display:flex;align-items:center;gap:8px;margin:5px 0;background:rgba(0,0,0,.4);padding:4px 8px;border-radius:6px}
.rv .sw{width:10px;height:10px;border-radius:2px;flex:0 0 10px}
.rv .nm{flex:0 0 100px;font-weight:800;letter-spacing:.08em}
.rv .bar{flex:1;height:6px;background:rgba(255,255,255,.15);border-radius:3px;overflow:hidden}
.rv .bar i{display:block;height:100%;width:100%}
.rv.dead .nm{color:#ff6b5a}
#armor{position:absolute;left:18px;bottom:56px;width:250px}
#armor .bar{height:10px;background:rgba(255,255,255,.15);border-radius:5px;overflow:hidden;margin-top:4px}
#armorFill{display:block;height:100%;width:100%;background:linear-gradient(90deg,#00e5ff,#7cffea)}
#help{position:absolute;left:50%;bottom:14px;transform:translateX(-50%);background:rgba(0,0,0,.6);padding:8px 16px;border-radius:8px;font-size:13px;letter-spacing:.05em;white-space:nowrap}
#help b{color:#00e5ff}
#popups{position:absolute;left:50%;top:24%;width:0;height:0}
.pop{position:absolute;left:0;white-space:nowrap;font-size:30px;letter-spacing:.05em;text-shadow:0 0 10px rgba(255,160,0,.9),0 2px 0 #000}
.pop.big{font-size:44px;color:#ffe066}
.pop.bad{color:#ff6b5a}
.card{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;z-index:5;pointer-events:none}
.hidden{display:none!important}
#photo{background:radial-gradient(ellipse at center,rgba(0,0,0,0) 45%,rgba(0,0,0,.7) 100%)}
#photo .frame{position:absolute;inset:22px;border:2px solid rgba(255,255,255,.85)}
.plate{text-align:center;background:rgba(5,8,14,.78);padding:26px 54px;border-top:4px solid #00e5ff;border-bottom:4px solid #00e5ff}
.plate .pn{font-size:72px;letter-spacing:.06em;line-height:1.05;text-shadow:0 0 20px rgba(0,229,255,.8)}
.plate .ps{font-size:56px;color:#ffe066;line-height:1.1}
.plate .ph{margin-top:10px;font-size:12px;letter-spacing:.3em;opacity:.85}
#over{background:rgba(0,0,0,.35)}
#boot,#err{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column;z-index:9;background:#05070d;text-align:center;padding:20px}
#boot .t{font-size:40px;letter-spacing:.08em;text-shadow:0 0 16px rgba(0,229,255,.8)}
#err{display:none}
#err p{max-width:560px;opacity:.85;line-height:1.5}
</style>
</head>
<body>
<div id="hud">
<div id="arena"><div class="name impact arenaName">VOLTAGE BOWL</div><div class="sub">CYBER CRUSH RALLY · <span class="live">● LIVE</span></div><div id="demoTag">DEMO</div></div>
<div id="clockBox"><div class="lbl">TIME</div><div id="clock" class="impact">2:00</div></div>
<div id="scoreBox"><div class="lbl">SCORE</div><div id="score" class="impact">0</div></div>
<div id="rivals"></div>
<div id="armor"><div class="lbl">YOUR ARMOR</div><div class="bar"><i id="armorFill"></i></div></div>
<div id="help">DRIVE <b>W A S D</b> or <b>ARROW KEYS</b> · <b>SPACE</b> handbrake · <b>P</b> photo mode · <b>R</b> restart</div>
<div id="popups"></div>
</div>
<div id="photo" class="card hidden"><div class="frame"></div><div class="plate"><div class="lbl">PHOTO MODE</div><div class="pn impact arenaName">VOLTAGE BOWL</div><div class="ps impact" id="photoScore">0</div><div class="ph">SCORE · PRESS P TO RESUME</div></div></div>
<div id="over" class="card hidden"><div class="plate"><div class="lbl">TIME!</div><div class="pn impact arenaName">VOLTAGE BOWL</div><div class="lbl" style="margin-top:8px">FINAL SCORE</div><div class="ps impact" id="finalScore">0</div><div class="ph">PRESS R TO RALLY AGAIN</div></div></div>
<div id="boot"><div class="t impact">VOLTAGE BOWL</div><div class="lbl" style="margin-top:10px">LOADING THE ARENA…</div></div>
<div id="err"><div class="t impact" style="font-size:34px">THE ARENA FAILED TO LOAD</div><p>Couldn't load three.js from cdn.jsdelivr.net. This page needs that one request — check the network connection and reload.</p></div>
<script>
setTimeout(function(){ if(!window.__rallyBooted){ document.getElementById('boot').style.display='none'; document.getElementById('err').style.display='flex'; } }, 9000);
</script>
<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js';
window.__rallyBooted = true;
function showErr(msg){
const e=document.getElementById('err'); e.querySelector('p').textContent=msg;
e.style.display='flex'; document.getElementById('boot').style.display='none';
}
try { main(); } catch(err){ console.error(err); showErr('Something broke while building the arena: '+(err && err.message)); }
function main(){
// ---------------------------------------------------------------- constants
const ARENA_NAME='VOLTAGE BOWL';
document.querySelectorAll('.arenaName').forEach(e=>e.textContent=ARENA_NAME);
const R=56, TR=1.55, COFF=1.45, BODY_Y=1.3, G=24, STEP=1/120, GAME_TIME=120;
const clamp=(v,a,b)=>v<a?a:(v>b?b:v);
const wrapA=a=>{ while(a>Math.PI)a-=2*Math.PI; while(a<-Math.PI)a+=2*Math.PI; return a; };
let seed=1337;
const rnd=()=>{ seed=(seed+0x6D2B79F5)|0; let t=Math.imul(seed^(seed>>>15),1|seed); t=(t+Math.imul(t^(t>>>7),61|t))^t; return ((t^(t>>>14))>>>0)/4294967296; };
const isDemo=()=>location.hash==='#demo';
// ---------------------------------------------------------------- renderer
let renderer;
try { renderer=new THREE.WebGLRenderer({antialias:true,powerPreference:'high-performance'}); }
catch(e){ throw new Error('WebGL is not available in this browser.'); }
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,2));
renderer.setSize(innerWidth,innerHeight);
renderer.shadowMap.enabled=true;
renderer.shadowMap.type=THREE.PCFSoftShadowMap;
renderer.toneMapping=THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure=1.05;
renderer.domElement.tabIndex=0;
document.body.appendChild(renderer.domElement);
const maxAniso=renderer.capabilities.getMaxAnisotropy();
const scene=new THREE.Scene();
scene.background=new THREE.Color(0x070a14);
scene.fog=new THREE.Fog(0x070a14,110,260);
const camera=new THREE.PerspectiveCamera(55,innerWidth/innerHeight,0.5,600);
// environment map built in-page (for the stainless look)
{
const pmrem=new THREE.PMREMGenerator(renderer);
const env=new THREE.Scene(); env.background=new THREE.Color(0x151a26);
const pm=new THREE.MeshBasicMaterial({color:0xffffff});
for(let i=0;i<8;i++){ const p=new THREE.Mesh(new THREE.PlaneGeometry(5,2.2),pm); const a=i/8*Math.PI*2; p.position.set(Math.cos(a)*10,5,Math.sin(a)*10); p.lookAt(0,0,0); env.add(p); }
const warm=new THREE.Mesh(new THREE.PlaneGeometry(60,60),new THREE.MeshBasicMaterial({color:0x4a3522})); warm.rotation.x=-Math.PI/2; warm.position.y=-3; env.add(warm);
scene.environment=pmrem.fromScene(env,0.04).texture;
}
scene.add(new THREE.HemisphereLight(0xa8b8ff,0x3a2a18,1.0));
const sun=new THREE.DirectionalLight(0xfff1dd,2.3);
sun.position.set(30,75,22); sun.castShadow=true; sun.shadow.mapSize.set(2048,2048);
Object.assign(sun.shadow.camera,{left:-66,right:66,top:66,bottom:-66,near:10,far:200});
sun.shadow.bias=-0.0006; scene.add(sun);
const fill=new THREE.DirectionalLight(0x6fa8ff,0.7); fill.position.set(-40,40,-30); scene.add(fill);
function canvasTex(w,h,draw){
const c=document.createElement('canvas'); c.width=w; c.height=h;
draw(c.getContext('2d'),w,h);
const t=new THREE.CanvasTexture(c); t.colorSpace=THREE.SRGBColorSpace; t.anisotropy=maxAniso; return t;
}
// ---------------------------------------------------------------- terrain (artificial hills)
const HILLS=[
{x:0,z:0,rx:10,rz:10,rot:0,h:3.4},
{x:-27,z:-12,rx:7,rz:12,rot:0.5,h:2.8},
{x:26,z:14,rx:7,rz:12,rot:-0.45,h:3.0},
{x:20,z:-27,rx:6.5,rz:6.5,rot:0,h:2.3},
{x:-20,z:27,rx:6.5,rz:6.5,rot:0,h:2.2},
{x:-40,z:10,rx:3.5,rz:9,rot:0.2,h:1.6},
{x:40,z:-8,rx:3.5,rz:9,rot:-0.2,h:1.6},
];
for(const hl of HILLS){ hl.c=Math.cos(hl.rot); hl.s=Math.sin(hl.rot); }
function groundH(x,z){
let y=0;
for(let i=0;i<HILLS.length;i++){ const hl=HILLS[i];
const dx=x-hl.x, dz=z-hl.z;
const lx=(dx*hl.c-dz*hl.s)/hl.rx, lz=(dx*hl.s+dz*hl.c)/hl.rz;
const d2=lx*lx+lz*lz;
if(d2<1){ y+=hl.h*0.5*(1+Math.cos(Math.PI*Math.sqrt(d2))); }
}
return y;
}
const dirtTex=canvasTex(512,512,(g,w,h)=>{
g.fillStyle='#5e4029'; g.fillRect(0,0,w,h);
for(let i=0;i<40;i++){ const x=rnd()*w,y=rnd()*h,r=20+rnd()*60; const gr=g.createRadialGradient(x,y,0,x,y,r); gr.addColorStop(0,rnd()<.5?'rgba(40,26,15,.35)':'rgba(130,96,62,.25)'); gr.addColorStop(1,'rgba(0,0,0,0)'); g.fillStyle=gr; g.fillRect(x-r,y-r,2*r,2*r); }
for(let i=0;i<9000;i++){ const v=60+rnd()*90|0; g.fillStyle=`rgba(${v+30},${v},${v-25},${0.3+rnd()*0.5})`; const s=1+rnd()*2.5; g.fillRect(rnd()*w,rnd()*h,s,s); }
g.strokeStyle='rgba(25,15,8,.35)'; g.lineWidth=7;
for(let i=0;i<6;i++){ g.beginPath(); const y0=rnd()*h; for(let x=0;x<=w;x+=16){ g.lineTo(x,y0+Math.sin(x/60+i)*30); } g.stroke(); }
});
dirtTex.wrapS=dirtTex.wrapT=THREE.RepeatWrapping; dirtTex.repeat.set(10,10);
{
const geo=new THREE.PlaneGeometry(2*R+6,2*R+6,150,150); geo.rotateX(-Math.PI/2);
const p=geo.attributes.position; const col=new Float32Array(p.count*3);
for(let i=0;i<p.count;i++){ const x=p.getX(i), z=p.getZ(i); const hh=groundH(x,z); p.setY(i,hh);
const n=0.8+hh*0.06+(rnd()-0.5)*0.06; col[i*3]=n; col[i*3+1]=n*0.97; col[i*3+2]=n*0.92; }
geo.setAttribute('color',new THREE.BufferAttribute(col,3)); geo.computeVertexNormals();
const floor=new THREE.Mesh(geo,new THREE.MeshStandardMaterial({map:dirtTex,vertexColors:true,roughness:1,metalness:0}));
floor.receiveShadow=true; scene.add(floor);
}
// ---------------------------------------------------------------- wall + stands + crowd
{
const banner=canvasTex(2048,128,(g,w,h)=>{
g.fillStyle='#0b0f1a'; g.fillRect(0,0,1024,h);
g.fillStyle='#ff7a00'; g.fillRect(1024,0,1024,h);
g.textAlign='center'; g.textBaseline='middle'; g.font='bold 78px Impact, "Arial Black", sans-serif';
g.fillStyle='#fff'; g.fillText(ARENA_NAME,512,64);
g.fillStyle='#00e5ff'; g.fillRect(0,112,1024,8);
g.fillStyle='#111'; g.fillText('CYBER CRUSH RALLY',1536,64);
});
banner.wrapS=THREE.RepeatWrapping; banner.repeat.set(-6,1);
const wall=new THREE.Mesh(new THREE.CylinderGeometry(R+0.6,R+0.6,2.4,128,1,true),new THREE.MeshStandardMaterial({map:banner,side:THREE.BackSide,roughness:.7}));
wall.position.y=1.2; scene.add(wall);
const rail=new THREE.Mesh(new THREE.TorusGeometry(R+0.6,0.14,6,160),new THREE.MeshBasicMaterial({color:0x00e5ff}));
rail.rotation.x=Math.PI/2; rail.position.y=2.45; scene.add(rail);
}
const ROWS=14, SR=1.5, SY=0.9, BASE=3.0, R0=R+1.2;
{
const pts=[new THREE.Vector2(R0,0),new THREE.Vector2(R0,BASE)];
for(let i=0;i<ROWS;i++){ const a=R0+i*SR, y=BASE+i*SY; pts.push(new THREE.Vector2(a+SR,y)); pts.push(new THREE.Vector2(a+SR,y+SY)); }
const outR=R0+ROWS*SR, topY=BASE+ROWS*SY;
pts.push(new THREE.Vector2(outR,topY+4)); pts.push(new THREE.Vector2(outR+1,topY+4)); pts.push(new THREE.Vector2(outR+1,0));
const stands=new THREE.Mesh(new THREE.LatheGeometry(pts,128),new THREE.MeshStandardMaterial({color:0x3a3f4c,roughness:.9,side:THREE.DoubleSide}));
scene.add(stands);
// light towers
const poleM=new THREE.MeshStandardMaterial({color:0x555b66,metalness:.6,roughness:.5});
const headM=new THREE.MeshBasicMaterial({color:0xf4f8ff});
for(let i=0;i<8;i++){ const a=(i+0.5)/8*Math.PI*2; const r=outR+2.5;
const pole=new THREE.Mesh(new THREE.CylinderGeometry(0.35,0.5,32,8),poleM); pole.position.set(Math.cos(a)*r,16,Math.sin(a)*r); scene.add(pole);
const hd=new THREE.Mesh(new THREE.BoxGeometry(7,3,0.6),headM); hd.position.set(Math.cos(a)*r,32,Math.sin(a)*r); hd.lookAt(0,0,0); scene.add(hd); }
// two big screens on the stand tops
const scr=canvasTex(1024,400,(g,w,h)=>{
const gr=g.createLinearGradient(0,0,0,h); gr.addColorStop(0,'#04121c'); gr.addColorStop(1,'#12031a'); g.fillStyle=gr; g.fillRect(0,0,w,h);
g.textAlign='center'; g.textBaseline='middle'; g.fillStyle='#fff'; g.shadowColor='#00e5ff'; g.shadowBlur=30;
g.font='bold 150px Impact, "Arial Black", sans-serif'; g.fillText(ARENA_NAME,w/2,170);
g.shadowBlur=0; g.fillStyle='#ff9f0a'; g.font='bold 60px Impact, "Arial Black", sans-serif'; g.fillText('CYBER CRUSH RALLY',w/2,300);
g.fillStyle='#ff3b30'; g.beginPath(); g.arc(60,50,16,0,7); g.fill(); g.font='bold 34px Arial'; g.textAlign='left'; g.fillText('LIVE',86,52);
});
for(const a of [Math.PI*0.5,Math.PI*1.5]){
const s=new THREE.Mesh(new THREE.PlaneGeometry(26,10),new THREE.MeshBasicMaterial({map:scr}));
s.position.set(Math.cos(a)*(outR-1),topY+10,Math.sin(a)*(outR-1)); s.lookAt(0,topY+6,0); scene.add(s);
const back=new THREE.Mesh(new THREE.BoxGeometry(27,11,0.8),poleM); back.position.copy(s.position); back.quaternion.copy(s.quaternion); back.translateZ(-0.45); scene.add(back);
}
}
// crowd — two instanced meshes (bodies + heads), all the way round
const crowd={};
{
const seats=[];
for(let i=0;i<ROWS;i++){ const rad=R0+i*SR+0.75, y=BASE+i*SY; const n=Math.floor(2*Math.PI*rad/0.78);
for(let k=0;k<n;k++){ if(rnd()<0.06) continue; const a=(k+(rnd()-0.5)*0.3)/n*Math.PI*2; seats.push([a,rad+(rnd()-0.5)*0.25,y]); } }
const N=seats.length; crowd.N=N;
const bodies=new THREE.InstancedMesh(new THREE.BoxGeometry(0.5,0.75,0.36),new THREE.MeshLambertMaterial(),N);
const heads=new THREE.InstancedMesh(new THREE.BoxGeometry(0.3,0.32,0.3),new THREE.MeshLambertMaterial(),N);
const d=new THREE.Object3D(), c=new THREE.Color();
const skins=[0xf1c9a5,0xd9a47a,0xa8714a,0x6e4428,0xffe0c4];
crowd.by=new Float32Array(N); crowd.hy=new Float32Array(N); crowd.f=new Float32Array(N); crowd.p=new Float32Array(N); crowd.a=new Float32Array(N);
for(let i=0;i<N;i++){ const [a,r,y]=seats[i]; const x=Math.cos(a)*r, z=Math.sin(a)*r;
d.position.set(x,y+0.45,z); d.lookAt(0,y+0.45,0); d.updateMatrix(); bodies.setMatrixAt(i,d.matrix);
d.position.set(x,y+1.02,z); d.updateMatrix(); heads.setMatrixAt(i,d.matrix);
const r2=rnd(); if(r2<0.2) c.set(0x00e5ff); else if(r2<0.3) c.set(0xff3b30); else c.setHSL(rnd(),0.55+rnd()*0.3,0.35+rnd()*0.3);
bodies.setColorAt(i,c); c.set(skins[(rnd()*skins.length)|0]); heads.setColorAt(i,c);
crowd.by[i]=y+0.45; crowd.hy[i]=y+1.02; crowd.f[i]=6+rnd()*5; crowd.p[i]=rnd()*6.28; crowd.a[i]=0.5+rnd();
}
bodies.instanceMatrix.setUsage(THREE.DynamicDrawUsage); heads.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
scene.add(bodies); scene.add(heads); crowd.bodies=bodies; crowd.heads=heads;
}
{ // stars
const n=700, pos=new Float32Array(n*3);
for(let i=0;i<n;i++){ const a=rnd()*6.283, e=0.25+rnd()*1.2, r=400; pos[i*3]=Math.cos(a)*Math.cos(e)*r; pos[i*3+1]=Math.sin(e)*r; pos[i*3+2]=Math.sin(a)*Math.cos(e)*r; }
const g=new THREE.BufferGeometry(); g.setAttribute('position',new THREE.BufferAttribute(pos,3));
scene.add(new THREE.Points(g,new THREE.PointsMaterial({color:0xaabbff,size:1.6,sizeAttenuation:false,fog:false})));
}
// ---------------------------------------------------------------- particles
const PV=`attribute vec3 aColor; attribute float aSize; attribute float aAlpha; uniform float uScale; varying vec3 vC; varying float vA;
void main(){ vC=aColor; vA=aAlpha; vec4 mv=modelViewMatrix*vec4(position,1.0); gl_PointSize=aSize*uScale/max(0.1,-mv.z); gl_Position=projectionMatrix*mv; }`;
const PF=`varying vec3 vC; varying float vA; void main(){ vec2 p=gl_PointCoord-0.5; float d=length(p); if(d>0.5) discard; gl_FragColor=vec4(vC, vA*smoothstep(0.5,0.1,d)); }`;
const pUniform={value:1};
function makeParticles(N,additive,baseA){
const P={N,additive,baseA,head:0,pos:new Float32Array(N*3),col:new Float32Array(N*3),size:new Float32Array(N),alpha:new Float32Array(N),
vel:new Float32Array(N*3),life:new Float32Array(N),max:new Float32Array(N),s0:new Float32Array(N),grow:new Float32Array(N),grav:new Float32Array(N)};
for(let i=0;i<N;i++) P.pos[i*3+1]=-9999;
const g=new THREE.BufferGeometry();
g.setAttribute('position',new THREE.BufferAttribute(P.pos,3)); g.setAttribute('aColor',new THREE.BufferAttribute(P.col,3));
g.setAttribute('aSize',new THREE.BufferAttribute(P.size,1)); g.setAttribute('aAlpha',new THREE.BufferAttribute(P.alpha,1));
const m=new THREE.ShaderMaterial({uniforms:{uScale:pUniform},vertexShader:PV,fragmentShader:PF,transparent:true,depthWrite:false,blending:additive?THREE.AdditiveBlending:THREE.NormalBlending});
const pts=new THREE.Points(g,m); pts.frustumCulled=false; scene.add(pts); P.geo=g; return P;
}
const SMK=makeParticles(1800,false,0.55), FX=makeParticles(1200,true,1);
function emit(P,x,y,z,vx,vy,vz,life,size,r,g,b,grav,grow){
const i=P.head; P.head=(P.head+1)%P.N; const i3=i*3;
P.pos[i3]=x; P.pos[i3+1]=y; P.pos[i3+2]=z; P.vel[i3]=vx; P.vel[i3+1]=vy; P.vel[i3+2]=vz;
P.col[i3]=r; P.col[i3+1]=g; P.col[i3+2]=b; P.life[i]=life; P.max[i]=life; P.s0[i]=size; P.size[i]=size; P.grow[i]=grow; P.grav[i]=grav; P.alpha[i]=P.baseA;
P.dirtyC=true;
}
function updParticles(P,dt){
const {pos,vel,life,max,alpha,size,s0,grow,grav}=P; const dr=Math.exp(-1.2*dt);
for(let i=0;i<P.N;i++){ if(life[i]<=0) continue; life[i]-=dt; const i3=i*3;
if(life[i]<=0){ alpha[i]=0; pos[i3+1]=-9999; continue; }
vel[i3+1]-=grav[i]*dt; vel[i3]*=dr; vel[i3+2]*=dr;
pos[i3]+=vel[i3]*dt; pos[i3+1]+=vel[i3+1]*dt; pos[i3+2]+=vel[i3+2]*dt;
if(pos[i3+1]<0.05){ pos[i3+1]=0.05; vel[i3+1]*=-0.3; }
const k=life[i]/max[i]; alpha[i]=P.additive?k:Math.min(1,k*1.5)*P.baseA; size[i]=s0[i]*(1+grow[i]*(1-k)); }
const a=P.geo.attributes; a.position.needsUpdate=true; a.aAlpha.needsUpdate=true; a.aSize.needsUpdate=true;
if(P.dirtyC){ a.aColor.needsUpdate=true; P.dirtyC=false; }
}
function clearParticles(P){ for(let i=0;i<P.N;i++){ P.life[i]=0; P.alpha[i]=0; P.pos[i*3+1]=-9999; } }
function sparks(x,y,z,n){ for(let i=0;i<n;i++){ const a=Math.random()*6.283, s=4+Math.random()*10; emit(FX,x,y,z,Math.cos(a)*s,2+Math.random()*8,Math.sin(a)*s,0.3+Math.random()*0.5,0.28,1,0.6+Math.random()*0.3,0.2,22,0); } }
function puff(x,y,z,n,r,g,b,spd,size){ for(let i=0;i<n;i++){ const a=Math.random()*6.283, s=spd*(0.4+Math.random()*0.6); emit(SMK,x,y,z,Math.cos(a)*s,0.5+Math.random()*2,Math.sin(a)*s,0.8+Math.random()*0.6,size,r,g,b,0.5,2); } }
// ---------------------------------------------------------------- obstacles
const statics=[]; // {x,z,r,kind}
const tireM=new THREE.MeshStandardMaterial({color:0x1a1a1a,roughness:.95});
const tireGeoS=new THREE.TorusGeometry(0.75,0.32,8,18);
for(const [x,z] of [[-10,-22],[13,-13],[-14,11],[10,23],[33,-30],[-36,-30],[-45,-4],[46,20]]){
const g=new THREE.Group(); const y=groundH(x,z);
for(let i=0;i<3;i++){ const m=new THREE.Mesh(tireGeoS,i===2&&rnd()<.6?new THREE.MeshStandardMaterial({color:0xffd400,roughness:.8}):tireM); m.rotation.x=Math.PI/2; m.position.y=0.32+i*0.62; m.castShadow=true; g.add(m); }
g.position.set(x,y,z); scene.add(g); statics.push({x,z,r:1.15,kind:'tire'});
}
const concM=new THREE.MeshStandardMaterial({color:0x9a9a96,roughness:.9}), yelM=new THREE.MeshStandardMaterial({color:0xffc400,roughness:.7});
for(const [x,z,rot] of [[-30,6,1.2],[33,-1,0.3],[0,27,0],[-8,-46,0.1],[12,46,-0.2]]){
const g=new THREE.Group();
const base=new THREE.Mesh(new THREE.BoxGeometry(3.2,0.35,1.0),concM); base.position.y=0.18;
const top=new THREE.Mesh(new THREE.BoxGeometry(3.2,0.75,0.55),concM); top.position.y=0.72;
const st=new THREE.Mesh(new THREE.BoxGeometry(3.22,0.12,0.57),yelM); st.position.y=1.05;
for(const m of [base,top,st]){ m.castShadow=true; m.receiveShadow=true; g.add(m); }
g.position.set(x,groundH(x,z),z); g.rotation.y=rot; scene.add(g);
const ax=Math.cos(rot), az=-Math.sin(rot);
statics.push({x:x+ax*0.95,z:z+az*0.95,r:0.75,kind:'conc'},{x:x-ax*0.95,z:z-az*0.95,r:0.75,kind:'conc'});
}
const cars=[];
const glassM=new THREE.MeshStandardMaterial({color:0x0a0c10,metalness:.9,roughness:.15,side:THREE.DoubleSide});
for(const [x,z,rot] of [[-2.4,-15,0],[0,-15,0.05],[2.4,-15,-0.04],[32,-38,1.1],[-30,-36,-0.7],[-12,43,1.6],[42,30,0.4],[-46,-18,2.2]]){
const g=new THREE.Group(); const cm=new THREE.MeshStandardMaterial({color:new THREE.Color().setHSL(rnd()*0.12,0.45,0.28+rnd()*0.15),roughness:.8,metalness:.3});
const b=new THREE.Mesh(new THREE.BoxGeometry(1.8,0.7,4.0),cm); b.position.y=0.55;
const cab=new THREE.Mesh(new THREE.BoxGeometry(1.6,0.6,2.0),cm); cab.position.set(0,1.2,-0.2);
const w=new THREE.Mesh(new THREE.BoxGeometry(1.62,0.4,1.7),glassM); w.position.set(0,1.2,-0.2);
for(const m of [b,cab,w]){ m.castShadow=true; g.add(m); }
g.position.set(x,groundH(x,z),z); g.rotation.y=rot; scene.add(g);
cars.push({x,z,r:1.9,crushed:false,k:0,mesh:g,mat:cm,base:cm.color.clone()});
}
const barrelTex=canvasTex(64,128,(g,w,h)=>{ g.fillStyle='#fff'; g.fillRect(0,0,w,h); g.fillStyle='#222'; g.fillRect(0,26,w,12); g.fillRect(0,90,w,12); });
const barrelGeo=new THREE.CylinderGeometry(0.45,0.45,1.1,14);
const barrels=[];
{
const cols=[0xff6a00,0xd62828,0x1e6bff,0xffcc00];
for(const [cx,cz] of [[17,-6],[-18,-1],[-3,40],[-40,27]]){
for(const [ox,oz] of [[-0.55,-0.55],[0.55,-0.55],[-0.55,0.55],[0.55,0.55]]){
const m=new THREE.Mesh(barrelGeo,new THREE.MeshStandardMaterial({map:barrelTex,color:cols[(rnd()*4)|0],roughness:.5,metalness:.4})); m.castShadow=true; scene.add(m);
barrels.push({hx:cx+ox,hz:cz+oz,mesh:m,x:0,z:0,y:0,vx:0,vz:0,vy:0,w:0,invM:10,invI:0,rx:0,rz:0,sx:0,sz:0,cool:0});
}
}
}
function resetObstacles(){
for(const c of cars){ c.crushed=false; c.k=0; c.mesh.scale.set(1,1,1); c.mat.color.copy(c.base); }
for(const b of barrels){ b.x=b.hx; b.z=b.hz; b.y=groundH(b.x,b.z)+0.55; b.vx=b.vz=b.vy=0; b.rx=b.rz=b.sx=b.sz=0; b.cool=0; }
}
// ---------------------------------------------------------------- trucks
const bodyGeo=(()=>{ const s=new THREE.Shape(); s.moveTo(-2.9,0); s.lineTo(2.9,0); s.lineTo(2.95,0.6); s.lineTo(0.2,1.55); s.lineTo(-2.9,0.95);
const g=new THREE.ExtrudeGeometry(s,{depth:2.4,bevelEnabled:false}); g.translate(0,0,-1.2); g.rotateY(-Math.PI/2); return g; })();
const winGeo=(()=>{ const s=new THREE.Shape(); s.moveTo(1.5,0.98); s.lineTo(0.2,1.44); s.lineTo(-1.4,1.14); s.lineTo(-1.4,0.9); s.lineTo(1.4,0.9);
const g=new THREE.ExtrudeGeometry(s,{depth:2.44,bevelEnabled:false}); g.translate(0,0,-1.22); g.rotateY(-Math.PI/2); return g; })();
const wsGeo=(()=>{ const g=new THREE.BufferGeometry();
g.setAttribute('position',new THREE.BufferAttribute(new Float32Array([-1.1,1.115,1.5, 1.1,1.115,1.5, 1.1,1.513,0.35, -1.1,1.513,0.35]),3));
g.setIndex([0,1,2,0,2,3]); g.computeVertexNormals(); return g; })();
const treadTex=canvasTex(256,32,(g,w,h)=>{ g.fillStyle='#161616'; g.fillRect(0,0,w,h); g.fillStyle='#050505'; for(let x=0;x<w;x+=16) g.fillRect(x,0,7,h); });
const tireMat=new THREE.MeshStandardMaterial({map:treadTex,roughness:.95});
const tireGeo=new THREE.CylinderGeometry(1,1,0.85,22); tireGeo.rotateZ(Math.PI/2);
const hubGeo=new THREE.CylinderGeometry(0.48,0.48,0.88,12); hubGeo.rotateZ(Math.PI/2);
const spokeGeo=new THREE.BoxGeometry(0.9,0.14,1.25);
const stripeGeo=new THREE.BoxGeometry(0.02,0.1,5.6), barGeo=new THREE.BoxGeometry(2.3,0.07,0.08), beaconGeo=new THREE.BoxGeometry(0.9,0.1,0.25);
const chassisGeo=new THREE.BoxGeometry(2.0,0.45,4.6), axleGeo=new THREE.BoxGeometry(3.1,0.18,0.18);
const darkM=new THREE.MeshStandardMaterial({color:0x22252b,metalness:.6,roughness:.5});
const headM=new THREE.MeshBasicMaterial({color:0xffffff}), tailM=new THREE.MeshBasicMaterial({color:0xff2020});
const markerGeo=new THREE.ConeGeometry(0.5,1,4); markerGeo.rotateX(Math.PI);
const CHARRED=new THREE.Color(0x2a2522);
const DEFS=[
{name:'YOU',color:0x00e5ff,tint:0.0,player:true,max:27,accel:21},
{name:'RAZORBACK',color:0xff3b30,tint:0.18,max:23.5,accel:18,bias:16,flank:1},
{name:'VOLTAGE',color:0xff9f0a,tint:0.18,max:23,accel:17.5,bias:8,flank:-1},
{name:'GRIDLOCK',color:0x7cff3a,tint:0.15,max:22,accel:17,bias:3,flank:1},
{name:'EXOSKELETON',color:0xff2bd6,tint:0.18,max:23.5,accel:18.5,bias:11,flank:-1},
];
if(DEFS.length!==5) throw new Error('rally needs exactly five trucks');
function makeTruck(def){
const g=new THREE.Group(); scene.add(g);
const body=new THREE.Group(); body.position.y=BODY_Y; g.add(body);
const steel=new THREE.Color(0xc4c8ce).lerp(new THREE.Color(def.color),def.tint);
const bodyMat=new THREE.MeshStandardMaterial({color:steel.clone(),metalness:.85,roughness:.3});
const accentMat=new THREE.MeshStandardMaterial({color:def.color,emissive:def.color,emissiveIntensity:.6,roughness:.4});
const hubMat=new THREE.MeshStandardMaterial({color:def.color,metalness:.7,roughness:.35});
const shell=new THREE.Mesh(bodyGeo,bodyMat); shell.castShadow=true; body.add(shell);
body.add(new THREE.Mesh(winGeo,glassM)); body.add(new THREE.Mesh(wsGeo,glassM));
for(const s of [-1,1]){ const m=new THREE.Mesh(stripeGeo,accentMat); m.position.set(s*1.212,0.32,0); body.add(m); }
const lb=new THREE.Mesh(barGeo,headM); lb.position.set(0,0.56,2.955); body.add(lb);
const tl=new THREE.Mesh(barGeo,tailM); tl.position.set(0,0.9,-2.905); body.add(tl);
const bc=new THREE.Mesh(beaconGeo,accentMat); bc.position.set(0,1.58,0.2); body.add(bc);
const ch=new THREE.Mesh(chassisGeo,darkM); ch.position.y=1.1; ch.castShadow=true; g.add(ch);
for(const z of [1.9,-1.9]){ const a=new THREE.Mesh(axleGeo,darkM); a.position.set(0,1.0,z); g.add(a); }
const spinners=[], fronts=[];
for(const [x,z] of [[1.55,1.9],[-1.55,1.9],[1.55,-1.9],[-1.55,-1.9]]){
const piv=new THREE.Group(); piv.position.set(x,1.0,z); g.add(piv);
const sp=new THREE.Group(); piv.add(sp);
const tire=new THREE.Mesh(tireGeo,tireMat); tire.castShadow=true; sp.add(tire);
sp.add(new THREE.Mesh(hubGeo,hubMat)); sp.add(new THREE.Mesh(spokeGeo,darkM));
spinners.push(sp); if(z>0) fronts.push(piv);
}
let marker=null;
if(!def.player){ marker=new THREE.Mesh(markerGeo,new THREE.MeshBasicMaterial({color:def.color})); marker.position.y=5.3; g.add(marker); }
return {name:def.name,color:def.color,isPlayer:!!def.player,maxSpeed:def.max,accel:def.accel,maxRev:10,
x:0,z:0,y:0,vx:0,vz:0,vy:0,h:0,w:0,vF:0,airT:0,lastGH:0,invM:1,invI:1/3.2,
health:100,maxHealth:100,wrecked:false,wreckT:0,invuln:0,rollDir:1,throttle:0,steer:0,handbrake:false,
flash:0,squash:0,spin:0,steerVis:0,group:g,body,bodyMat,steel,spinners,fronts,marker,
ai:def.player?null:{bias:def.bias,flank:def.flank,mode:'attack',timer:8,retarget:0,target:null,lastTarget:null,lastHitBy:null,wx:0,wz:0,stuck:0,revT:0}};
}
const trucks=DEFS.map(makeTruck);
const player=trucks[0];
const SPAWNS=[-90,-18,54,126,198].map(d=>d*Math.PI/180);
const pairCool=trucks.map(()=>trucks.map(()=>0));
function placeTruck(t,ang,rad){
t.x=Math.cos(ang)*rad; t.z=Math.sin(ang)*rad; t.h=Math.atan2(-t.x,-t.z);
t.vx=t.vz=t.vy=t.w=t.vF=0; t.y=groundH(t.x,t.z); t.lastGH=t.y; t.airT=0;
t.health=t.maxHealth; t.wrecked=false; t.wreckT=0; t.flash=0; t.squash=0;
t.group.position.set(t.x,t.y,t.z); t.group.quaternion.setFromAxisAngle(_up,t.h);
}
function respawn(t){
let best=0,bs=-1;
for(let i=0;i<24;i++){ const a=Math.random()*Math.PI*2; const x=Math.cos(a)*44, z=Math.sin(a)*44; let md=1e9;
for(const o of trucks) if(o!==t) md=Math.min(md,Math.hypot(o.x-x,o.z-z)); if(md>bs){bs=md;best=a;} }
placeTruck(t,best,44); t.y+=4; t.invuln=2;
if(t.ai){ t.ai.mode='attack'; t.ai.target=null; t.ai.timer=8; t.ai.revT=0; t.ai.stuck=0; }
if(t.isPlayer) popup('BACK IN!','');
}
// ---------------------------------------------------------------- game state
const state={time:GAME_TIME,score:0,running:true};
let simTime=0, crowdEx=0.2, shake=0, photo=false, camYaw=0;
// ---------------------------------------------------------------- audio (Web Audio, generated)
let AC=null; const A={}; let lastCrash=0;
function initAudio(){
if(AC){ if(AC.state==='suspended'&&!photo) AC.resume(); return; }
try{
AC=new (window.AudioContext||window.webkitAudioContext)();
A.master=AC.createGain(); A.master.gain.value=0.55; A.master.connect(AC.destination);
const len=AC.sampleRate*2, buf=AC.createBuffer(1,len,AC.sampleRate), d=buf.getChannelData(0);
for(let i=0;i<len;i++) d[i]=Math.random()*2-1; A.noise=buf;
A.eng1=AC.createOscillator(); A.eng1.type='sawtooth'; A.eng2=AC.createOscillator(); A.eng2.type='square';
A.engF=AC.createBiquadFilter(); A.engF.type='lowpass'; A.engF.frequency.value=500;
A.engG=AC.createGain(); A.engG.gain.value=0; const g2=AC.createGain(); g2.gain.value=0.5;
A.eng1.connect(A.engF); A.eng2.connect(g2); g2.connect(A.engF); A.engF.connect(A.engG); A.engG.connect(A.master);
A.eng1.frequency.value=40; A.eng2.frequency.value=20; A.eng1.start(); A.eng2.start();
const src=AC.createBufferSource(); src.buffer=buf; src.loop=true;
const bp=AC.createBiquadFilter(); bp.type='bandpass'; bp.frequency.value=900; bp.Q.value=0.5;
A.crowdG=AC.createGain(); A.crowdG.gain.value=0.04; src.connect(bp); bp.connect(A.crowdG); A.crowdG.connect(A.master); src.start();
if(photo) AC.suspend();
}catch(e){ AC=null; }
}
function crash(k){
if(!AC||!A.noise) return; const t=AC.currentTime; if(t-lastCrash<0.06) return; lastCrash=t; k=clamp(k,0.05,1);
const s=AC.createBufferSource(); s.buffer=A.noise; const f=AC.createBiquadFilter(); f.type='lowpass'; f.frequency.value=600+k*2600;
const g=AC.createGain(); g.gain.setValueAtTime(0.9*k,t); g.gain.exponentialRampToValueAtTime(0.001,t+0.25+k*0.5);
s.connect(f); f.connect(g); g.connect(A.master); s.start(t,Math.random()*1.2); s.stop(t+1);
const o=AC.createOscillator(); o.type='sine'; o.frequency.setValueAtTime(90,t); o.frequency.exponentialRampToValueAtTime(35,t+0.3);
const og=AC.createGain(); og.gain.setValueAtTime(0.8*k,t); og.gain.exponentialRampToValueAtTime(0.001,t+0.4);
o.connect(og); og.connect(A.master); o.start(t); o.stop(t+0.5);
}
function updateAudio(){
if(!AC||!A.eng1) return; const t=AC.currentTime, sp=Math.abs(player.vF), th=player.throttle>0?1:0;
const f=38+sp*3.2+th*14;
A.eng1.frequency.setTargetAtTime(f,t,0.06); A.eng2.frequency.setTargetAtTime(f*0.5,t,0.06);
A.engF.frequency.setTargetAtTime(300+sp*40+th*400,t,0.08);
A.engG.gain.setTargetAtTime(state.running&&!player.wrecked?0.07:0.015,t,0.1);
A.crowdG.gain.setTargetAtTime(0.03+crowdEx*0.12,t,0.2);
}
// ---------------------------------------------------------------- HUD
const $=id=>document.getElementById(id);
const clockEl=$('clock'), scoreEl=$('score'), armorEl=$('armorFill'), popEl=$('popups');
const fmt=n=>Math.round(n).toLocaleString('en-US');
const rivalRows=trucks.slice(1).map(t=>{
const row=document.createElement('div'); row.className='rv'; const hex='#'+t.color.toString(16).padStart(6,'0');
row.innerHTML=`<span class="sw" style="background:${hex}"></span><span class="nm">${t.name}</span><span class="bar"><i style="background:${hex}"></i></span>`;
$('rivals').appendChild(row); return {t,row,bar:row.querySelector('i')};
});
const pops=[];
function popup(text,cls){
const d=document.createElement('div'); d.className='pop impact '+(cls||''); d.textContent=text; popEl.appendChild(d);
pops.push({el:d,life:1.4,max:1.4}); while(pops.length>5){ pops.shift().el.remove(); }
}
function addScore(pts,label){ if(!state.running||pts<=0) return; state.score+=pts; popup(label+' +'+fmt(pts),pts>=500?'big':''); }
function updateHUD(){
const s=Math.ceil(state.time); clockEl.textContent=Math.floor(s/60)+':'+String(s%60).padStart(2,'0');
clockEl.classList.toggle('hurry',state.time<10);
scoreEl.textContent=fmt(state.score);
armorEl.style.width=(player.health/player.maxHealth*100)+'%';
for(const r of rivalRows){ r.bar.style.width=(r.t.health/r.t.maxHealth*100)+'%'; r.row.classList.toggle('dead',r.t.wrecked); }
pops.forEach((p,i)=>{ const k=1-p.life/p.max; p.el.style.transform=`translate(-50%, ${i*46-k*50}px) scale(${1+Math.max(0,0.12-k)*3})`; p.el.style.opacity=p.life<0.4?p.life/0.4:1; });
}
// ---------------------------------------------------------------- input
const keys=new Set();
addEventListener('keydown',e=>{
initAudio();
if(['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Space'].includes(e.code)) e.preventDefault();
if(e.code==='KeyP'){ if(!e.repeat) togglePhoto(); return; }
if(photo) return;
if(e.code==='KeyR'){ if(!e.repeat) newGame(); return; }
keys.add(e.code);
});
addEventListener('keyup',e=>keys.delete(e.code));
addEventListener('blur',()=>keys.clear());
addEventListener('pointerdown',()=>{ try{ window.focus(); renderer.domElement.focus(); }catch(e){} initAudio(); });
addEventListener('hashchange',()=>{ if(photo) togglePhoto(); newGame(); });
function togglePhoto(){
photo=!photo;
if(photo){ keys.clear(); $('photoScore').textContent=fmt(state.score); $('photo').classList.remove('hidden'); if(AC) AC.suspend(); }
else { $('photo').classList.add('hidden'); if(AC) AC.resume(); }
}
// ---------------------------------------------------------------- collision model
// n points from A toward B (or toward the static thing). Returns closing speed at the contact point.
function resolve(Ab,cx,cz,nx,nz,pen,B,e){
const raX=cx-Ab.x, raZ=cz-Ab.z;
const vaX=Ab.vx+Ab.w*raZ, vaZ=Ab.vz-Ab.w*raX;
let vbX=0,vbZ=0,imB=0,iiB=0,rbX=0,rbZ=0;
if(B){ rbX=cx-B.x; rbZ=cz-B.z; vbX=B.vx+B.w*rbZ; vbZ=B.vz-B.w*rbX; imB=B.invM; iiB=B.invI; }
const tot=Ab.invM+imB;
Ab.x-=nx*pen*Ab.invM/tot; Ab.z-=nz*pen*Ab.invM/tot;
if(B){ B.x+=nx*pen*imB/tot; B.z+=nz*pen*imB/tot; }
const vn=(vbX-vaX)*nx+(vbZ-vaZ)*nz;
if(vn>=0) return 0;
const raN=raZ*nx-raX*nz, rbN=rbZ*nx-rbX*nz;
const j=-(1+e)*vn/(Ab.invM+imB+raN*raN*Ab.invI+rbN*rbN*iiB);
Ab.vx-=j*nx*Ab.invM; Ab.vz-=j*nz*Ab.invM; Ab.w-=raN*j*Ab.invI;
if(B){ B.vx+=j*nx*imB; B.vz+=j*nz*imB; B.w+=rbN*j*iiB; }
return -vn;
}
function circlesOf(t){ const sh=Math.sin(t.h)*COFF, ch=Math.cos(t.h)*COFF; return [[t.x+sh,t.z+ch],[t.x-sh,t.z-ch]]; }
function applyDamage(t,dmg,by){
if(t.wrecked||t.invuln>0||dmg<=0) return;
if(t.isPlayer) dmg*=0.65;
t.health-=dmg; t.flash=1;
if(t.health<=0) wreck(t,by);
}
function wreck(t,by){
t.health=0; t.wrecked=true; t.wreckT=0; t.vy+=7; t.rollDir=Math.random()<.5?-1:1; t.w+=t.rollDir*(3+Math.random()*3);
const y=t.y+1.8; for(let i=0;i<50;i++){ const a=Math.random()*6.283,s=2+Math.random()*7; emit(FX,t.x,y,t.z,Math.cos(a)*s,2+Math.random()*7,Math.sin(a)*s,0.5+Math.random()*0.6,1.1,1,0.45+Math.random()*0.3,0.1,4,1.2); }
puff(t.x,y,t.z,30,0.12,0.11,0.1,5,1.8); sparks(t.x,y,t.z,40); crash(1); crowdEx=Math.min(1.5,crowdEx+0.8);
if(t.isPlayer){ popup('YOU GOT WRECKED','bad'); shake+=0.8; }
else if(by&&by.isPlayer) addScore(1000,t.name+' WRECKED!');
}
function startRetreat(t,ax,az){
const a=t.ai; a.mode='retreat'; a.timer=1.6+Math.random()*1.6; a.lastTarget=a.target;
let ang=(ax!==undefined)?Math.atan2(ax,az):Math.random()*Math.PI*2; ang+=(Math.random()-0.5)*1.4;
let wx=t.x+Math.sin(ang)*22, wz=t.z+Math.cos(ang)*22; const r=Math.hypot(wx,wz), lim=R-12;
if(r>lim){ wx*=lim/r; wz*=lim/r; } a.wx=wx; a.wz=wz;
}
function hitEvent(a,b,impact,aggA,aggB,cx,cy,cz,nx,nz){
aggA=Math.max(0,aggA); aggB=Math.max(0,aggB); const sA=aggA/(aggA+aggB+1e-3);
const dmgB=impact*3.4*(0.2+0.8*sA), dmgA=impact*3.4*(0.2+0.8*(1-sA));
const bWasOk=!b.wrecked, aWasOk=!a.wrecked;
applyDamage(b,dmgB,a); applyDamage(a,dmgA,b);
const victim=sA>=0.5?b:a;
if(victim.airT<0.05) victim.vy+=Math.min(7,impact*0.22);
sparks(cx,cy,cz,Math.min(60,impact*4|0)); crash(impact/20); crowdEx=Math.min(1.5,crowdEx+impact/30);
if(a.isPlayer||b.isPlayer){
shake+=impact*0.03;
const share=a.isPlayer?sA:1-sA, other=a.isPlayer?b:a, otherOk=a.isPlayer?bWasOk:aWasOk;
if(otherOk&&!other.wrecked){ const pts=Math.round(impact*30*(0.25+share)/10)*10; addScore(pts,share>0.5?'SLAM':'TRADED PAINT'); }
}
if(impact>5){
if(a.ai&&!a.wrecked){ a.ai.lastHitBy=b; startRetreat(a,-nx,-nz); }
if(b.ai&&!b.wrecked){ b.ai.lastHitBy=a; startRetreat(b,nx,nz); }
}
}
function landing(t,v){
t.squash=Math.min(1,v/16);
for(let i=0;i<14;i++){ const a=i/14*6.283; emit(SMK,t.x+Math.cos(a)*2,t.y+0.3,t.z+Math.sin(a)*2,Math.cos(a)*5,1+Math.random(),Math.sin(a)*5,0.9,1.3,0.45,0.33,0.22,0.5,2); }
if(v>10) crash(v/40);
if(t.isPlayer){ shake+=v*0.012; if(t.airT>0.9) addScore(Math.round(t.airT*200/10)*10,'BIG AIR'); }
if(t.airT>0.9) crowdEx=Math.min(1.5,crowdEx+0.25);
}
function collide(){
// truck vs truck
for(let i=0;i<trucks.length;i++) for(let j=i+1;j<trucks.length;j++){
const a=trucks[i], b=trucks[j];
if(Math.abs(a.y-b.y)>2.6) continue;
if(Math.abs(a.x-b.x)>7||Math.abs(a.z-b.z)>7) continue;
const ca=circlesOf(a), cb=circlesOf(b); let best=null, bp=0;
for(const p of ca) for(const q of cb){ const dx=q[0]-p[0], dz=q[1]-p[1], d=Math.hypot(dx,dz), pen=2*TR-d; if(pen>bp){ bp=pen; best=[p,q,dx,dz,d]; } }
if(!best) continue;
const [p,q,dx,dz,d0]=best; const d=d0||1e-4, nx=d0?dx/d:1, nz=d0?dz/d:0;
const cx=p[0]+nx*(TR-bp/2), cz=p[1]+nz*(TR-bp/2);
const aggA=a.vx*nx+a.vz*nz, aggB=-(b.vx*nx+b.vz*nz);
const impact=resolve(a,cx,cz,nx,nz,bp,b,0.35);
if(impact>2.5&&pairCool[i][j]<=0){ pairCool[i][j]=0.35; hitEvent(a,b,impact,aggA,aggB,cx,Math.max(a.y,b.y)+1.6,cz,nx,nz); }
}
for(const t of trucks){
const hAbove=t.y-groundH(t.x,t.z);
for(const c of circlesOf(t)){
// wall
const r=Math.hypot(c[0],c[1]);
if(r+TR>R){ const nx=c[0]/r, nz=c[1]/r, pen=r+TR-R; const cx=c[0]+nx*TR, cz=c[1]+nz*TR;
const imp=resolve(t,cx,cz,nx,nz,pen,null,0.35);
if(imp>8){ sparks(cx,t.y+1.2,cz,imp*2|0); crash(imp/35); if(imp>10) applyDamage(t,(imp-10)*1.8,null); if(t.isPlayer) shake+=imp*0.015; } }
if(hAbove>2.2) continue;
// static obstacles (tire stacks, concrete barriers)
for(const s of statics){ const dx=s.x-c[0], dz=s.z-c[1]; const d=Math.hypot(dx,dz); if(d<TR+s.r&&d>1e-4){
const nx=dx/d, nz=dz/d, pen=TR+s.r-d; const imp=resolve(t,c[0]+nx*TR,c[1]+nz*TR,nx,nz,pen,null,0.3);
if(imp>6){ const col=s.kind==='tire'?0.08:0.6; puff(s.x,t.y+1,s.z,8,col,col,col,4,0.9); crash(imp/40); if(imp>12) applyDamage(t,(imp-12)*1.2,null); if(t.isPlayer) shake+=imp*0.01; } } }
// junk cars (crushable)
for(const car of cars){ if(car.crushed) continue; const dx=car.x-c[0], dz=car.z-c[1]; const d=Math.hypot(dx,dz); if(d<TR+car.r&&d>1e-4){
const sp=Math.hypot(t.vx,t.vz);
if(sp>5||t.vy<-4){ car.crushed=true; t.vy=Math.max(t.vy,0)+5; t.vx*=0.85; t.vz*=0.85;
sparks(car.x,t.y+1,car.z,25); puff(car.x,t.y+0.8,car.z,14,0.3,0.28,0.26,4,1.2); crash(0.7); crowdEx=Math.min(1.5,crowdEx+0.3);
if(t.isPlayer){ addScore(150,'CAR CRUSH'); shake+=0.3; } }
else { const nx=dx/d, nz=dz/d; resolve(t,c[0]+nx*TR,c[1]+nz*TR,nx,nz,TR+car.r-d,null,0.2); } } }
// barrels (dynamic)
for(const b of barrels){ if(Math.abs(t.y+1-b.y)>2.2) continue; const dx=b.x-c[0], dz=b.z-c[1]; const d=Math.hypot(dx,dz); if(d<TR+0.5&&d>1e-4){
const nx=dx/d, nz=dz/d; const imp=resolve(t,c[0]+nx*TR,c[1]+nz*TR,nx,nz,TR+0.5-d,b,0.4);
if(imp>3){ b.vy+=imp*0.45; b.sx+=(Math.random()-.5)*imp*1.5; b.sz+=(Math.random()-.5)*imp*1.5; crash(imp/50);
if(t.isPlayer&&b.cool<=0){ b.cool=1; addScore(25,'BARREL'); } } } }
}
}
}
function updBarrels(dt){
for(const b of barrels){
if(b.cool>0) b.cool-=dt;
b.vy-=G*dt; b.x+=b.vx*dt; b.z+=b.vz*dt; b.y+=b.vy*dt;
const gh=groundH(b.x,b.z)+0.55;
if(b.y<=gh){ b.y=gh; if(b.vy<-3) b.vy*=-0.35; else b.vy=0; const f=Math.exp(-2.5*dt); b.vx*=f; b.vz*=f; const s=Math.exp(-4*dt); b.sx*=s; b.sz*=s; }
b.rx+=b.sx*dt; b.rz+=b.sz*dt;
const r=Math.hypot(b.x,b.z); if(r>R-0.5){ const nx=b.x/r, nz=b.z/r; b.x=nx*(R-0.5); b.z=nz*(R-0.5); const vn=b.vx*nx+b.vz*nz; if(vn>0){ b.vx-=1.5*vn*nx; b.vz-=1.5*vn*nz; } }
for(const s of statics){ const dx=b.x-s.x, dz=b.z-s.z, d=Math.hypot(dx,dz); if(d<s.r+0.5&&d>1e-4){ const nx=dx/d,nz=dz/d; b.x=s.x+nx*(s.r+0.5); b.z=s.z+nz*(s.r+0.5); const vn=b.vx*nx+b.vz*nz; if(vn<0){ b.vx-=1.5*vn*nx; b.vz-=1.5*vn*nz; } } }
}
for(let i=0;i<barrels.length;i++) for(let j=i+1;j<barrels.length;j++){ const a=barrels[i], c=barrels[j]; const dx=c.x-a.x, dz=c.z-a.z, d=Math.hypot(dx,dz);
if(d<0.9&&d>1e-4){ const p=(0.9-d)/2, nx=dx/d, nz=dz/d; a.x-=nx*p; a.z-=nz*p; c.x+=nx*p; c.z+=nz*p; const rv=(c.vx-a.vx)*nx+(c.vz-a.vz)*nz; if(rv<0){ a.vx+=rv*nx*0.8; a.vz+=rv*nz*0.8; c.vx-=rv*nx*0.8; c.vz-=rv*nz*0.8; } } }
}
// ---------------------------------------------------------------- AI
function pickTarget(t){
const a=t.ai; let best=null, bc=1e9;
const onPlayer=trucks.filter(o=>o!==t&&o.ai&&o.ai.mode==='attack'&&o.ai.target===player).length;
for(const c of trucks){ if(c===t||c.wrecked) continue;
if(c.isPlayer&&onPlayer>=2) continue;
const d=Math.hypot(c.x-t.x,c.z-t.z);
const others=trucks.filter(o=>o!==t&&o.ai&&o.ai.target===c).length;
const cost=d*(0.7+Math.random()*0.6)-(c.isPlayer?a.bias:0)+others*14+(c===a.lastTarget?10:0)-(c===a.lastHitBy?8:0);
if(cost<bc){ bc=cost; best=c; } }
a.target=best; a.retarget=4+Math.random()*4;
}
function aiThink(t,dt){
const a=t.ai;
if(t.wrecked){ t.throttle=0; t.steer=0; t.handbrake=false; return; }
a.timer-=dt; a.retarget-=dt;
if(a.mode==='retreat'&&(a.timer<=0||Math.hypot(a.wx-t.x,a.wz-t.z)<6)){ a.mode='attack'; a.timer=7+Math.random()*4; a.target=null; }
if(a.mode==='attack'){
if(!a.target||a.target.wrecked||a.retarget<=0) pickTarget(t);
if(a.timer<=0) startRetreat(t);
}
let tx=0,tz=0;
if(a.mode==='retreat'){ tx=a.wx; tz=a.wz; }
else if(a.target){ const g=a.target; const dx=g.x-t.x, dz=g.z-t.z, d=Math.hypot(dx,dz)+1e-3;
const lead=Math.min(1.2,d/Math.max(10,Math.hypot(t.vx,t.vz)));
const off=a.flank*Math.min(9,d*0.3);
tx=g.x+g.vx*lead+(-dz/d)*off; tz=g.z+g.vz*lead+(dx/d)*off; }
let dx=tx-t.x, dz=tz-t.z; const d=Math.hypot(dx,dz)+1e-3; dx/=d; dz/=d;
let sx=0,sz=0;
for(const o of trucks){ if(o===t||o===a.target) continue; const ox=t.x-o.x, oz=t.z-o.z, od=Math.hypot(ox,oz);
if(od<14&&od>0.01){ const k=(14-od)/14*(o.ai?1:0.5); sx+=ox/od*k; sz+=oz/od*k; } }
dx+=sx*1.3; dz+=sz*1.3;
const r=Math.hypot(t.x,t.z); if(r>R-12){ const k=(r-(R-12))/12; dx-=t.x/r*k*2; dz-=t.z/r*k*2; }
const diff=wrapA(Math.atan2(dx,dz)-t.h);
if(a.revT>0){ a.revT-=dt; t.throttle=-1; t.steer=-(Math.sign(diff)||1); t.handbrake=false; return; }
t.steer=clamp(diff*2.4,-1,1);
t.throttle=Math.abs(diff)<1.4?1:0.45;
t.handbrake=Math.abs(diff)>1.2&&t.vF>12;
if(t.throttle>0&&Math.abs(t.vF)<1.5&&t.airT<0.1){ a.stuck+=dt; if(a.stuck>1.0){ a.revT=0.9+Math.random()*0.5; a.stuck=0; } }
else a.stuck=Math.max(0,a.stuck-dt);
}
// ---------------------------------------------------------------- truck physics
function integrateTruck(t,dt){
if(t.invuln>0) t.invuln-=dt;
if(t.wrecked){ t.wreckT+=dt; t.throttle=0; t.steer=0; t.handbrake=false; if(t.wreckT>(t.isPlayer?3:4.5)){ respawn(t); return; } }
const sh=Math.sin(t.h), ch=Math.cos(t.h);
const onG=(t.y-groundH(t.x,t.z))<0.35;
let vF=t.vx*sh+t.vz*ch, vL=t.vx*ch-t.vz*sh;
if(onG){
if(t.throttle>0){ if(vF<t.maxSpeed) vF+=t.accel*t.throttle*dt; }
else if(t.throttle<0){ if(vF>0.5) vF-=34*dt; else if(vF>-t.maxRev) vF-=14*dt; }
else vF-=vF*0.9*dt;
if(vF>t.maxSpeed+2) vF-=(vF-t.maxSpeed)*2*dt;
vL*=Math.exp(-(t.wrecked?2.5:(t.handbrake?1.1:7.5))*dt);
if(t.wrecked) vF*=Math.exp(-2.5*dt);
t.vx=sh*vF+ch*vL; t.vz=ch*vF-sh*vL;
const gx=groundH(t.x+0.5,t.z)-groundH(t.x-0.5,t.z), gz=groundH(t.x,t.z+0.5)-groundH(t.x,t.z-0.5);
t.vx-=gx*G*0.35*dt; t.vz-=gz*G*0.35*dt;
const tr=1.9*(1-0.35*Math.min(1,Math.abs(vF)/30))*(t.handbrake?1.45:1);
const tw=t.wrecked?0:t.steer*tr*clamp(vF/5,-1,1);
t.w+=(tw-t.w)*Math.min(1,6*dt);
} else { const f=Math.exp(-0.05*dt); t.vx*=f; t.vz*=f; t.w*=Math.exp(-0.4*dt); }
t.vF=vF;
t.h+=t.w*dt; t.x+=t.vx*dt; t.z+=t.vz*dt;
const gh=groundH(t.x,t.z);
t.vy-=G*dt; t.y+=t.vy*dt;
if(t.y<=gh){
if(t.airT>0.2&&t.vy<-6) landing(t,-t.vy);
t.y=gh; t.vy=clamp((gh-t.lastGH)/dt,-16,16); t.airT=0;
} else t.airT+=dt;
t.lastGH=gh;
}
function truckFx(t){
const sh=Math.sin(t.h), ch=Math.cos(t.h);
if(t.airT<0.05&&Math.abs(t.vF)>7&&Math.random()<0.25){ const s=Math.random()<.5?-1:1;
emit(SMK,t.x-sh*1.9+ch*1.55*s,t.y+0.3,t.z-ch*1.9-sh*1.55*s,-t.vx*0.1+(Math.random()-.5)*2,1+Math.random()*1.5,-t.vz*0.1+(Math.random()-.5)*2,0.9,1.1,0.42,0.31,0.2,0.8,2.2); }
const hp=t.health/t.maxHealth, hx=t.x+sh*2, hz=t.z+ch*2, hy=t.y+2.3;
if((t.wrecked||hp<0.5)&&Math.random()<(t.wrecked?0.5:0.08)){ const g=t.wrecked?0.1:0.3; emit(SMK,hx,hy,hz,(Math.random()-.5),2.5,(Math.random()-.5),1.6,1.3,g,g,g,-1,2.5); }
if((t.wrecked||hp<0.25)&&Math.random()<(t.wrecked?0.45:0.12)) emit(FX,hx+(Math.random()-.5),hy-0.3,hz+(Math.random()-.5),0,3,0,0.5,0.9,1,0.45,0.1,-1,0.5);
}
// ---------------------------------------------------------------- step (the whole simulation)
function playerInput(){
if(state.running&&!player.wrecked){
const up=keys.has('KeyW')||keys.has('ArrowUp'), dn=keys.has('KeyS')||keys.has('ArrowDown');
const lf=keys.has('KeyA')||keys.has('ArrowLeft'), rt=keys.has('KeyD')||keys.has('ArrowRight');
player.throttle=up?1:(dn?-1:0); player.steer=(lf?1:0)-(rt?1:0); player.handbrake=keys.has('Space');
} else { player.throttle=0; player.steer=0; player.handbrake=!state.running; }
}
function endGame(){
state.running=false; $('finalScore').textContent=fmt(state.score); $('over').classList.remove('hidden');
popup('TIME!','big'); crowdEx=1.5;
}
function step(dt){
simTime+=dt;
if(state.running){ state.time-=dt; if(state.time<=0){ state.time=0; endGame(); } }
playerInput();
for(const t of trucks) if(t.ai) aiThink(t,dt);
for(const t of trucks) integrateTruck(t,dt);
collide();
updBarrels(dt);
for(const t of trucks) truckFx(t);
for(const c of cars) if(c.crushed&&c.k<1) c.k=Math.min(1,c.k+dt*6);
for(const row of pairCool) for(let j=0;j<row.length;j++) if(row[j]>0) row[j]-=dt;
crowdEx*=Math.exp(-0.45*dt); shake=Math.min(1.2,shake*Math.exp(-6*dt));
for(let i=pops.length-1;i>=0;i--){ pops[i].life-=dt; if(pops[i].life<=0){ pops[i].el.remove(); pops.splice(i,1); } }
}
// ---------------------------------------------------------------- visuals
const _up=new THREE.Vector3(0,1,0), _ax=new THREE.Vector3(1,0,0), _az=new THREE.Vector3(0,0,1);
const _n=new THREE.Vector3(), _f=new THREE.Vector3(), _x=new THREE.Vector3(), _m=new THREE.Matrix4(), _q=new THREE.Quaternion(), _q2=new THREE.Quaternion();
const _c=new THREE.Color(), camBase=new THREE.Vector3(), _v=new THREE.Vector3(), _t=new THREE.Vector3();
function updateVisuals(dt){
for(const t of trucks){
const onG=t.airT<0.05;
if(onG){ const e=1.2; _n.set(-(groundH(t.x+e,t.z)-groundH(t.x-e,t.z))/(2*e),1,-(groundH(t.x,t.z+e)-groundH(t.x,t.z-e))/(2*e)).normalize(); } else _n.copy(_up);
_f.set(Math.sin(t.h),0,Math.cos(t.h)); _f.addScaledVector(_n,-_f.dot(_n)).normalize();
_x.crossVectors(_n,_f); _m.makeBasis(_x,_n,_f); _q.setFromRotationMatrix(_m);
if(!onG){ _q2.setFromAxisAngle(_ax,clamp(-t.vy*0.03,-0.5,0.5)); _q.multiply(_q2); }
let lift=0;
if(t.wrecked){ const k=Math.min(1,t.wreckT*1.8); _q2.setFromAxisAngle(_az,t.rollDir*1.6*k); _q.multiply(_q2); lift=2.0*k; }
t.group.quaternion.slerp(_q,1-Math.exp(-(onG?12:4)*dt));
t.group.position.set(t.x,t.y+lift,t.z);
t.squash*=Math.exp(-6*dt);
t.body.position.y=BODY_Y-t.squash*0.35; t.body.scale.y=1-t.squash*0.08;
t.body.rotation.z=clamp(-t.w*t.vF*0.004,-0.12,0.12);
t.spin+=t.vF*dt; for(const s of t.spinners) s.rotation.x=t.spin;
t.steerVis+=(t.steer*0.45-t.steerVis)*Math.min(1,10*dt); for(const f of t.fronts) f.rotation.y=t.steerVis;
t.flash=Math.max(0,t.flash-dt*3);
_c.copy(t.steel).lerp(CHARRED,(1-t.health/t.maxHealth)*0.65); t.bodyMat.color.copy(_c);
t.bodyMat.emissive.setRGB(t.flash*0.9,t.flash*0.15,0);
t.group.visible=!(t.invuln>0&&Math.floor(simTime*12)%2===0);
if(t.marker){ t.marker.visible=!t.wrecked; t.marker.position.y=5.3+Math.sin(simTime*3+t.color)*0.2; t.marker.rotation.y=simTime*2; }
}
for(const c of cars){ c.mesh.scale.y=1-0.72*c.k; if(c.crushed) c.mat.color.copy(c.base).multiplyScalar(1-0.45*c.k); }
for(const b of barrels){ b.mesh.position.set(b.x,b.y,b.z); b.mesh.rotation.set(b.rx,0,b.rz); }
}
function updateCrowd(){
const {N,by,hy,f,p,a}=crowd, B=crowd.bodies.instanceMatrix.array, H=crowd.heads.instanceMatrix.array, ex=0.06+crowdEx*0.4;
for(let i=0;i<N;i++){ const s=Math.sin(simTime*f[i]+p[i]); const up=s>0?s*ex*a[i]:0; B[i*16+13]=by[i]+up; H[i*16+13]=hy[i]+up; }
crowd.bodies.instanceMatrix.needsUpdate=true; crowd.heads.instanceMatrix.needsUpdate=true;
}
function updateCamera(dt,snap){
const p=player;
if(snap) camYaw=p.h; else if(p.wrecked) camYaw+=0.5*dt; else camYaw+=wrapA(p.h-camYaw)*(1-Math.exp(-3.2*dt));
let cx=p.x-Math.sin(camYaw)*13.5, cz=p.z-Math.cos(camYaw)*13.5;
const r=Math.hypot(cx,cz), lim=R-1; let extra=0; if(r>lim){ extra=(r-lim)*0.5; cx*=lim/r; cz*=lim/r; }
const cy=Math.max(p.y*0.6+6.2+extra,groundH(cx,cz)+2.5);
_v.set(cx,cy,cz);
if(snap) camBase.copy(_v); else camBase.lerp(_v,1-Math.exp(-5*dt));
camera.position.copy(camBase);
if(shake>0.002) camera.position.add(_v.set((Math.random()-.5)*shake,(Math.random()-.5)*shake,(Math.random()-.5)*shake));
_t.set(p.x+Math.sin(camYaw)*5,p.y+1.6,p.z+Math.cos(camYaw)*5);
camera.lookAt(_t);
}
// ---------------------------------------------------------------- new game (the only place the clock and score are initialised)
function newGame(){
const demo=isDemo();
state.time=demo?20:GAME_TIME; state.score=demo?5000:0; state.running=true;
$('demoTag').style.display=demo?'block':'none';
$('over').classList.add('hidden');
for(const p of pops) p.el.remove(); pops.length=0;
trucks.forEach((t,i)=>{ placeTruck(t,SPAWNS[i],36); t.invuln=0; if(t.ai){ Object.assign(t.ai,{mode:'attack',timer:6+Math.random()*4,retarget:0,target:null,lastTarget:null,lastHitBy:null,stuck:0,revT:0}); } });
for(const row of pairCool) row.fill(0);
resetObstacles(); clearParticles(SMK); clearParticles(FX);
crowdEx=0.4; shake=0; keys.clear();
updateVisuals(1/60); updateCamera(0,true); updateHUD();
popup(demo?'DEMO · 20 SECONDS':'GO!','big');
}
function onResize(){
renderer.setSize(innerWidth,innerHeight); camera.aspect=innerWidth/innerHeight; camera.updateProjectionMatrix();
pUniform.value=renderer.getPixelRatio()*innerHeight/(2*Math.tan(THREE.MathUtils.degToRad(camera.fov/2)));
}
addEventListener('resize',onResize); onResize();
newGame();
document.getElementById('boot').style.display='none';
// ---------------------------------------------------------------- loop
let last=performance.now(), acc=0;
function frame(now){
requestAnimationFrame(frame);
let dt=(now-last)/1000; last=now; if(dt>0.1) dt=0.1; if(dt<0) dt=0;
if(!photo){
acc+=dt; let n=0;
while(acc>=STEP&&n<10){ step(STEP); acc-=STEP; n++; }
if(n>=10) acc=0;
updateVisuals(dt); updParticles(SMK,dt); updParticles(FX,dt); updateCrowd(); updateCamera(dt,false); updateAudio(); updateHUD();
} else acc=0;
renderer.render(scene,camera);
}
requestAnimationFrame(frame);
}
</script>
</body>
</html>
Five trucks: Four mechanisms keep the rivals spread out:
flank is ±1 per rival), so rivals arc in for side hits instead of lining up nose-to-tail. After any hard hit, both AI trucks peel away to a retreat waypoint for 1.6–3.2 seconds.Demo mode: state.time=demo?20:GAME_TIME; state.score=demo?5000:0; inside newGame(), where demo = location.hash==='#demo'. It is not an overlay because these are the same fields everything else uses:
step() decrements state.time and calls endGame() at zero.addScore() adds to state.score.The 5000 therefore grows with slams, and the round genuinely ends after 20 seconds. Changing the hash, or pressing R, re-runs the same initialiser.
Photo mode: P stops the physics step and everything else in the simulation. While photo is true, the frame loop does not call step() and drops its time accumulator. Nothing that advances the game runs:
The render loop keeps running and redraws the identical frozen frame under the card, so a window resize still displays correctly. Nothing advances until P is pressed again.
Collisions: Each truck is two circles along its heading (radius 1.55, ±1.45 m apart) on a 120 Hz fixed step.
j = −(1+e)·vₙ / (1/mₐ + 1/m_b + (rₐ×n)²/Iₐ + (r_b×n)²/I_b), is applied to both linear and angular velocity, so off-centre hits spin trucks.