Source code

Gridstorm

Exactly what your browser runs — written by Claude Opus 5.5. 1,388 lines across 1 file, plus the shared arcade kit (pause menu, audio, scores) every game loads.

Play it

games/play/gridstorm.html · 1,388 lines

<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<title>Gridstorm — PromptArcade</title>
<style>
html,body{margin:0;height:100%;background:#03040c;color:#eaf6ff;overflow:hidden;font-family:Manrope,system-ui,sans-serif;touch-action:none;-webkit-user-select:none;user-select:none}
#game{position:fixed;inset:0;z-index:1;cursor:crosshair}
#game canvas{display:block;width:100%;height:100%}
#fx{position:fixed;inset:0;z-index:2;pointer-events:none}
#gs-hud{position:fixed;top:10px;left:10px;right:100px;z-index:30;display:flex;gap:6px;pointer-events:none;flex-wrap:wrap}
#gs-score b{min-width:5ch}
#gs-mult b{color:#7dffb0}
#gs-oc{transition:box-shadow .2s ease}
#gs-oc .bar{position:relative;width:70px;height:6px;margin-top:5px;border-radius:4px;background:rgba(255,255,255,.1);overflow:hidden}
#gs-oc .bar i{position:absolute;inset:0;width:0;border-radius:4px;background:linear-gradient(90deg,#5ab8ff,#e8f6ff)}
#gs-oc.on{box-shadow:0 0 18px rgba(120,200,255,.6)}
@media (max-width:560px){#gs-hud{right:130px}#gs-bombs{display:none}#gs-oc .bar{width:50px}}
.gs-stick{position:fixed;z-index:40;width:130px;height:130px;margin:-65px 0 0 -65px;border-radius:50%;border:2px solid rgba(120,220,255,.3);display:none;pointer-events:none}
.gs-stick i{position:absolute;left:50%;top:50%;width:52px;height:52px;margin:-26px 0 0 -26px;border-radius:50%;background:rgba(120,220,255,.3)}
.gs-btn{position:fixed;right:16px;z-index:42;width:64px;height:64px;border-radius:50%;border:2px solid rgba(150,215,255,.6);background:rgba(120,190,255,.15);color:#cfeaff;font:800 11px Manrope,sans-serif;display:none}
#gs-bomb{bottom:170px}
#gs-dash{bottom:250px;border-color:rgba(255,230,138,.6);background:rgba(255,220,120,.12);color:#ffeab0}
@media (pointer:coarse){.gs-btn{display:block}}
</style></head><body>
<div id="game" aria-label="Gridstorm: a honeycomb arena floating over a storm"></div>
<canvas id="fx" aria-hidden="true"></canvas>
<div id="gs-hud" class="pa-hud">
  <div class="pa-stat" id="gs-score"><small>Score</small><b>0</b></div>
  <div class="pa-stat" id="gs-mult"><small>Multiplier</small><b>×1</b></div>
  <div class="pa-stat" id="gs-lives"><small>Ships</small><b>3</b></div>
  <div class="pa-stat" id="gs-bombs"><small>Surges</small><b>3</b></div>
  <div class="pa-stat" id="gs-oc"><small>Overcharge</small><div class="bar"><i></i></div></div>
</div>
<div class="gs-stick" id="gs-s1"><i></i></div><div class="gs-stick" id="gs-s2"><i></i></div>
<button type="button" class="gs-btn" id="gs-bomb">SURGE</button>
<button type="button" class="gs-btn" id="gs-dash">DASH</button>
<script>
window.paConfig = {
  slug: "gridstorm", title: "Gridstorm", native: true, music: "space", unit: "points",
  controls: [["WASD / arrows", "Move"], ["Arrows (with WASD)", "Aim and fire"], ["Mouse", "Aim — hold to fire (or always-fire toggle F)"], ["Shift / E", "Dash: a short burst you can't be hit in, and it charges the floor"], ["Space / right-click", "Surge: clears the arena"], ["Touch", "Left thumb moves · right thumb aims and fires"], ["Shockwaves", "Every kill rings out and pops anything it reaches — herd them close and chain them"], ["Overcharge", "Stand on lit cells and your shots pierce and fire faster"], ["Shellbacks", "Shielded on the side facing you: flank them, or catch them in a shockwave"], ["Thunderheads", "Watch for the bright warning ring — lightning lands there a moment later"], ["Supercells", "Now and then a giant storm rolls in. Chain shockwaves into it to bring it down"]]
};
</script>
<script src="/games/play/pa-score.js"></script>
<script src="/games/play/pa-gate.js"></script>
<script src="/games/play/pa-kit.js"></script>
<script type="module">
import * as THREE from "/vendor/three/three.module.min.js";
 
(() => {
"use strict";
// A twin-stick shooter on a honeycomb of charge cells floating over a thunderstorm. Every kill rings out as a
// shockwave that detonates anything it reaches, so packs chain. The rules run in arena pixels (1700 x 1050);
// the 3D world is the same arena at S pixels per unit, with the floor cells rising and glowing as they charge.
const TAU = Math.PI * 2;
const $ = (id) => document.getElementById(id);
const { clamp, rand } = PA;
const AW = 1700, AH = 1050, S = 20;
const WX = (x) => (x - AW / 2) / S, WZ = (y) => (y - AH / 2) / S;
/* ---------------- renderer + post ---------------- */
const mount = document.getElementById("game");
const renderer = new THREE.WebGLRenderer({ antialias: false, powerPreference: "high-performance" });
const dprCap = () => Math.min(PA.isTouch ? 1.5 : 2, devicePixelRatio || 1);
renderer.setPixelRatio(dprCap());
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
mount.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x05040d);
scene.fog = new THREE.FogExp2(0x070516, 0.012);
const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.3, 500);
const hdr = (c, k) => new THREE.Color(c).multiplyScalar(k);
 
function makePost() {
  const ext = renderer.extensions;
  const fullFloat = ext.has("EXT_color_buffer_float"), hdrOk = fullFloat || ext.has("EXT_color_buffer_half_float");
  const type = hdrOk ? THREE.HalfFloatType : THREE.UnsignedByteType;
  const main = new THREE.WebGLRenderTarget(1, 1, { type, samples: hdrOk && !fullFloat ? 0 : PA.isTouch ? 2 : 4 });
  const LV = 5, lv = [], tmp = [];
  for (let i = 0; i < LV; i++) {
    lv.push(new THREE.WebGLRenderTarget(1, 1, { type, depthBuffer: false }));
    tmp.push(new THREE.WebGLRenderTarget(1, 1, { type, depthBuffer: false }));
  }
  const cam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
  const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2));
  quad.frustumCulled = false;
  const pscene = new THREE.Scene();
  pscene.add(quad);
  const vs = "varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }";
  const mk = (fs, uniforms) => new THREE.ShaderMaterial({ vertexShader: vs, fragmentShader: fs, uniforms, depthTest: false, depthWrite: false });
  const box4 = "vec3 c = 0.25 * (texture2D(tex, vUv + px * vec2(-0.5, -0.5)).rgb + texture2D(tex, vUv + px * vec2(0.5, -0.5)).rgb + texture2D(tex, vUv + px * vec2(-0.5, 0.5)).rgb + texture2D(tex, vUv + px * vec2(0.5, 0.5)).rgb);";
  const bright = mk([
    "uniform sampler2D tex; uniform vec2 px; uniform float thr; varying vec2 vUv;",
    "void main(){", box4,
    "  float l = max(c.r, max(c.g, c.b));",
    "  float knee = thr * 0.5, soft = clamp(l - thr + knee, 0.0, 2.0 * knee);",
    "  soft = soft * soft / (4.0 * knee + 1e-4);",
    "  gl_FragColor = vec4(min(c * max(soft, l - thr) / max(l, 1e-4), vec3(30.0)), 1.0);",
    "}"].join("\n"), { tex: { value: null }, px: { value: new THREE.Vector2() }, thr: { value: hdrOk ? 0.95 : 0.7 } });
  const down = mk("uniform sampler2D tex; uniform vec2 px; varying vec2 vUv; void main(){ " + box4 + " gl_FragColor = vec4(c, 1.0); }",
    { tex: { value: null }, px: { value: new THREE.Vector2() } });
  const blur = mk([
    "uniform sampler2D tex; uniform vec2 dir; varying vec2 vUv;",
    "void main(){",
    "  vec3 c = texture2D(tex, vUv).rgb * 0.2270270270;",
    "  c += (texture2D(tex, vUv + dir * 1.3846153846).rgb + texture2D(tex, vUv - dir * 1.3846153846).rgb) * 0.3162162162;",
    "  c += (texture2D(tex, vUv + dir * 3.2307692308).rgb + texture2D(tex, vUv - dir * 3.2307692308).rgb) * 0.0702702703;",
    "  gl_FragColor = vec4(c, 1.0);",
    "}"].join("\n"), { tex: { value: null }, dir: { value: new THREE.Vector2() } });
  const comp = mk([
    "uniform sampler2D tScene, b0, b1, b2, b3, b4; uniform float strength, grain, time, hurt, chroma; varying vec2 vUv;",
    "void main(){",
    "  vec2 q = vUv - 0.5;",
    "  vec3 c;",
    "  c.r = texture2D(tScene, vUv + q * chroma * 0.012).r;",
    "  c.g = texture2D(tScene, vUv).g;",
    "  c.b = texture2D(tScene, vUv - q * chroma * 0.012).b;",
    "  vec3 b = texture2D(b0, vUv).rgb * 0.5 + texture2D(b1, vUv).rgb * 0.6 + texture2D(b2, vUv).rgb * 0.75 + texture2D(b3, vUv).rgb * 0.85 + texture2D(b4, vUv).rgb * 0.95;",
    "  c += b * strength;",
    "  float vig = dot(q, q);",
    "  c *= 1.0 - vig * 0.85;",
    "  c += vec3(1.0, 0.2, 0.45) * hurt * smoothstep(0.08, 0.4, vig);",
    "  gl_FragColor = vec4(c, 1.0);",
    "  #include <tonemapping_fragment>",
    "  #include <colorspace_fragment>",
    "  float n = fract(sin(dot(gl_FragCoord.xy + fract(time) * 97.0, vec2(12.9898, 78.233))) * 43758.5453);",
    "  gl_FragColor.rgb += (n - 0.5) * grain;",
    "}"].join("\n"), {
    tScene: { value: main.texture }, b0: { value: lv[0].texture }, b1: { value: lv[1].texture }, b2: { value: lv[2].texture },
    b3: { value: lv[3].texture }, b4: { value: lv[4].texture }, strength: { value: 0.5 }, grain: { value: 0.02 }, time: { value: 0 }, hurt: { value: 0 }, chroma: { value: 0.1 }
  });
  const pass = (m, target) => { quad.material = m; renderer.setRenderTarget(target); renderer.render(pscene, cam); };
  return {
    comp,
    setSize(w, h) {
      main.setSize(w, h);
      for (let i = 0; i < LV; i++) {
        const lw = Math.max(1, w >> (i + 1)), lh = Math.max(1, h >> (i + 1));
        lv[i].setSize(lw, lh); tmp[i].setSize(lw, lh);
      }
    },
    render(sc, cm, t) {
      renderer.setRenderTarget(main);
      renderer.render(sc, cm);
      bright.uniforms.tex.value = main.texture;
      bright.uniforms.px.value.set(1 / main.width, 1 / main.height);
      pass(bright, lv[0]);
      for (let i = 0; i < LV; i++) {
        if (i) {
          down.uniforms.tex.value = lv[i - 1].texture;
          down.uniforms.px.value.set(1 / lv[i - 1].width, 1 / lv[i - 1].height);
          pass(down, lv[i]);
        }
        blur.uniforms.tex.value = lv[i].texture; blur.uniforms.dir.value.set(1 / lv[i].width, 0);
        pass(blur, tmp[i]);
        blur.uniforms.tex.value = tmp[i].texture; blur.uniforms.dir.value.set(0, 1 / lv[i].height);
        pass(blur, lv[i]);
      }
      comp.uniforms.time.value = t;
      pass(comp, null);
    }
  };
}
const post = makePost();
function canvasTex(w, h, paint, o) {
  const cv = document.createElement("canvas");
  cv.width = w; cv.height = h;
  paint(cv.getContext("2d"), w, h);
  const t = new THREE.CanvasTexture(cv);
  t.colorSpace = o && o.linear ? THREE.NoColorSpace : THREE.SRGBColorSpace;
  if (o && o.repeat) { t.wrapS = t.wrapT = THREE.RepeatWrapping; }
  t.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
  return t;
}
const glowTex = canvasTex(128, 128, (g, w) => {
  const gr = g.createRadialGradient(w / 2, w / 2, 0, w / 2, w / 2, w / 2);
  gr.addColorStop(0, "rgba(255,255,255,1)"); gr.addColorStop(.2, "rgba(255,255,255,.5)"); gr.addColorStop(.55, "rgba(255,255,255,.1)"); gr.addColorStop(1, "rgba(255,255,255,0)");
  g.fillStyle = gr; g.fillRect(0, 0, w, w);
});
function glowSprite(color, scale) {
  const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTex, color, blending: THREE.AdditiveBlending, depthWrite: false, transparent: true }));
  s.scale.setScalar(scale);
  return s;
}
/* ---------------- particles + shards ---------------- */
const PMAX = 3000;
const pPos = new Float32Array(PMAX * 3), pCol = new Float32Array(PMAX * 3), pSize = new Float32Array(PMAX);
const pGeo = new THREE.BufferGeometry();
pGeo.setAttribute("position", new THREE.BufferAttribute(pPos, 3).setUsage(THREE.DynamicDrawUsage));
pGeo.setAttribute("color", new THREE.BufferAttribute(pCol, 3).setUsage(THREE.DynamicDrawUsage));
pGeo.setAttribute("size", new THREE.BufferAttribute(pSize, 1).setUsage(THREE.DynamicDrawUsage));
const pointsMat = new THREE.ShaderMaterial({
  transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
  uniforms: { scale: { value: 600 } },
  vertexShader: "uniform float scale; attribute float size; attribute vec3 color; varying vec3 vC; void main(){ vC = color; vec4 mv = modelViewMatrix * vec4(position, 1.0); gl_PointSize = max(1.0, size * scale / -mv.z); gl_Position = projectionMatrix * mv; }",
  fragmentShader: "varying vec3 vC; void main(){ float d = length(gl_PointCoord - 0.5); float a = smoothstep(0.5, 0.05, d); gl_FragColor = vec4(vC * a * a, 1.0); }"
});
const ptsMesh = new THREE.Points(pGeo, pointsMat);
ptsMesh.frustumCulled = false;
scene.add(ptsMesh);
const parts = [];
const C3 = (hex, k) => { const c = new THREE.Color(hex); return [c.r * k, c.g * k, c.b * k]; };
function burst(x, z, o) {
  o = o || {};
  const n = o.n || 16, cols = o.colors || [0xffffff];
  for (let i = 0; i < n && parts.length < PMAX; i++) {
    const a = o.angle != null ? o.angle + rand(-1, 1) * (o.spread || 0.6) : Math.random() * TAU;
    const sp = (o.speed || 6) * rand(0.3, 1), life = (o.life || 0.6) * rand(0.5, 1.1);
    parts.push({ x, y: o.y == null ? 0.4 : o.y, z, vx: Math.cos(a) * sp, vy: rand(0.2, 1) * (o.up == null ? 3 : o.up), vz: Math.sin(a) * sp, g: o.g == null ? 6 : o.g,
      life, max: life, size: (o.size || 0.22) * rand(0.6, 1.3), c: C3(cols[(Math.random() * cols.length) | 0], o.bright || 2.4) });
  }
}
function updateParts(dt) {
  let j = 0;
  for (let i = 0; i < parts.length; i++) {
    const p = parts[i];
    p.life -= dt;
    if (p.life <= 0) continue;
    p.vy -= p.g * dt;
    p.x += p.vx * dt; p.y += p.vy * dt; p.z += p.vz * dt;
    if (p.y < 0.03) { p.y = 0.03; p.vy *= -0.4; p.vx *= 0.7; p.vz *= 0.7; }
    parts[j++] = p;
  }
  parts.length = j;
  for (let i = 0; i < j; i++) {
    const p = parts[i], k = p.life / p.max;
    pPos[i * 3] = p.x; pPos[i * 3 + 1] = p.y; pPos[i * 3 + 2] = p.z;
    pCol[i * 3] = p.c[0] * k; pCol[i * 3 + 1] = p.c[1] * k; pCol[i * 3 + 2] = p.c[2] * k;
    pSize[i] = p.size;
  }
  pGeo.setDrawRange(0, j);
  pGeo.attributes.position.needsUpdate = true; pGeo.attributes.color.needsUpdate = true; pGeo.attributes.size.needsUpdate = true;
}
// Glass shards: real little tetrahedra that tumble, bounce on the floor and fade.
const SMAX = 420;
const shardMesh = new THREE.InstancedMesh(new THREE.TetrahedronGeometry(0.2), new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.15, metalness: 0.2, emissive: 0xffffff, emissiveIntensity: 0.35, transparent: true, opacity: 0.9 }), SMAX);
shardMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
shardMesh.setColorAt(0, new THREE.Color(1, 1, 1));
shardMesh.count = 0;
shardMesh.frustumCulled = false;
scene.add(shardMesh);
const shards = [];
function shatter(x, z, color, n) {
  const c = new THREE.Color(color);
  for (let i = 0; i < n; i++) {
    if (shards.length >= SMAX) shards.shift();
    const a = Math.random() * TAU, sp = rand(1.5, 6.5);
    shards.push({ x: x + rand(-0.8, 0.8), y: rand(0.15, 0.6), z: z + rand(-0.35, 0.35), vx: Math.cos(a) * sp, vy: rand(2, 7), vz: Math.sin(a) * sp * 0.7 + 1.2,
      rx: rand(0, TAU), ry: rand(0, TAU), wx: rand(-14, 14), wy: rand(-14, 14), s: rand(0.5, 1.25), life: rand(1.4, 2.4), c });
  }
}
const m4 = new THREE.Matrix4(), q4 = new THREE.Quaternion(), e4 = new THREE.Euler(), v4 = new THREE.Vector3(), s4 = new THREE.Vector3();
function updateShards(dt) {
  let j = 0;
  for (let i = 0; i < shards.length; i++) {
    const s = shards[i];
    s.life -= dt;
    if (s.life <= 0) continue;
    s.vy -= 20 * dt;
    s.x += s.vx * dt; s.y += s.vy * dt; s.z += s.vz * dt;
    if (s.y < 0.08) { s.y = 0.08; s.vy *= -0.35; s.vx *= 0.6; s.vz *= 0.6; s.wx *= 0.6; s.wy *= 0.6; }
    s.rx += s.wx * dt; s.ry += s.wy * dt;
    shards[j++] = s;
  }
  shards.length = j;
  for (let i = 0; i < j; i++) {
    const s = shards[i], k = Math.min(1, s.life / 0.5) * s.s;
    e4.set(s.rx, s.ry, 0); q4.setFromEuler(e4);
    m4.compose(v4.set(s.x, s.y, s.z), q4, s4.set(k, k, k));
    shardMesh.setMatrixAt(i, m4);
    shardMesh.setColorAt(i, s.c);
  }
  shardMesh.count = j;
  shardMesh.instanceMatrix.needsUpdate = true;
  if (shardMesh.instanceColor) shardMesh.instanceColor.needsUpdate = true;
}
// ribbon trails (ball paths, beams)
const TV = 9000;
const tPos = new Float32Array(TV * 3), tCol = new Float32Array(TV * 3);
const tGeo = new THREE.BufferGeometry();
tGeo.setAttribute("position", new THREE.BufferAttribute(tPos, 3).setUsage(THREE.DynamicDrawUsage));
tGeo.setAttribute("color", new THREE.BufferAttribute(tCol, 3).setUsage(THREE.DynamicDrawUsage));
const trailMesh = new THREE.Mesh(tGeo, new THREE.MeshBasicMaterial({ vertexColors: true, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide }));
trailMesh.frustumCulled = false;
scene.add(trailMesh);
let tv = 0;
const camDir = new THREE.Vector3();
function ribbon(tr, col, width, taper) {
  const n = tr.length / 3;
  if (n < 2) return;
  for (let i = 1; i < n && tv + 6 <= TV; i++) {
    const ax = tr[i * 3 - 3], ay = tr[i * 3 - 2], az = tr[i * 3 - 1], bx = tr[i * 3], by = tr[i * 3 + 1], bz = tr[i * 3 + 2];
    const dx = bx - ax, dy = by - ay, dz = bz - az;
    camDir.set(camera.position.x - bx, camera.position.y - by, camera.position.z - bz).normalize();
    const px = dy * camDir.z - dz * camDir.y, py = dz * camDir.x - dx * camDir.z, pz = dx * camDir.y - dy * camDir.x;
    const pl = Math.hypot(px, py, pz) || 1;
    const k0 = taper === false ? 1 : (i - 1) / (n - 1), k1 = taper === false ? 1 : i / (n - 1);
    const w0 = width * k0 / pl, w1 = width * k1 / pl;
    const v = [ax - px * w0, ay - py * w0, az - pz * w0, ax + px * w0, ay + py * w0, az + pz * w0, bx - px * w1, by - py * w1, bz - pz * w1, bx + px * w1, by + py * w1, bz + pz * w1];
    for (const q of [0, 1, 2, 1, 3, 2]) {
      tPos[tv * 3] = v[q * 3]; tPos[tv * 3 + 1] = v[q * 3 + 1]; tPos[tv * 3 + 2] = v[q * 3 + 2];
      const k = q < 2 ? k0 : k1, kk = taper === false ? 1 : k * k;
      tCol[tv * 3] = col[0] * kk; tCol[tv * 3 + 1] = col[1] * kk; tCol[tv * 3 + 2] = col[2] * kk;
      tv++;
    }
  }
}
/* ================= storm floor =================
   The arena is a honeycomb of charge cells over a sea of storm cloud. Cells don't move: they light up.
   Blasts, shockwaves and lightning pour charge into nearby cells, and the charge bleeds away again. */
const HS = 26, HW = Math.sqrt(3) * HS, HR = HS * 1.5;           // hex radius, column step, row step
const HX = Math.ceil(AW / HW) + 2, HY = Math.ceil(AH / HR) + 2;
const hexC = new Float32Array(HX * HY), hexPos = [];
for (let y = 0; y < HY; y++) for (let x = 0; x < HX; x++) hexPos.push([x * HW + (y & 1 ? HW / 2 : 0) - HW / 2, y * HR - HR / 2]);
function zap(px, py, force, radius) {
  // force is roughly how hard the blast hits; negative values (old pulls) do nothing
  if (force <= 0) return;
  const amt = Math.min(1.2, force / 900), R = radius + HS;
  const y0 = Math.max(0, Math.floor((py - R) / HR)), y1 = Math.min(HY - 1, Math.ceil((py + R) / HR) + 1);
  const x0 = Math.max(0, Math.floor((px - R) / HW)), x1 = Math.min(HX - 1, Math.ceil((px + R) / HW) + 1);
  for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) {
    const i = y * HX + x, [cx, cy] = hexPos[i], d = Math.hypot(cx - px, cy - py);
    if (d > R) continue;
    hexC[i] = Math.min(1.4, hexC[i] + amt * (1 - d / R));
  }
}
function updateGrid(dt) {
  const k = Math.exp(-dt * 2.6);
  for (let i = 0; i < hexC.length; i++) hexC[i] *= k;
  // now and then the storm flickers somewhere on its own
  if (Math.random() < dt * .4) zap(rand(0, AW), rand(0, AH), rand(120, 320), rand(90, 220));
}
 
/* ---------------- scene setup ---------------- */
scene.background = new THREE.Color(0x04050f);
scene.fog = new THREE.Fog(0x06081a, 60, 150);
camera.fov = 42; camera.near = 1; camera.far = 400;
renderer.toneMappingExposure = 1.05;
post.comp.uniforms.strength.value = 0.6;
const bufSize = new THREE.Vector2();
let camD = 44;
const CAM_TILT = new THREE.Vector3(0, 1, 0.72).normalize();
function resize3d() {
  renderer.setPixelRatio(dprCap());
  renderer.setSize(innerWidth, innerHeight);
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.getDrawingBufferSize(bufSize);
  post.setSize(bufSize.x, bufSize.y);
  pointsMat.uniforms.scale.value = bufSize.y / (2 * Math.tan(THREE.MathUtils.degToRad(camera.fov) / 2));
  // landscape: about 34 units of arena top to bottom; portrait: about 30 units across
  const tv = Math.tan(THREE.MathUtils.degToRad(camera.fov) / 2), th = tv * camera.aspect;
  camD = camera.aspect >= 1 ? 17 / tv : Math.max(17 / tv, 15 / th);
}
const tmpV = new THREE.Vector3();
function toScreen(x, y, h) {
  tmpV.set(WX(x), h == null ? 0.8 : h, WZ(y)).project(camera);
  return { x: (tmpV.x + 1) / 2 * innerWidth, y: (1 - tmpV.y) / 2 * innerHeight };
}
// screen point to arena pixels, through the floor plane
const ray = new THREE.Raycaster(), ndc = new THREE.Vector2(), floorPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.8), hitV = new THREE.Vector3();
function screenToWorld(sx, sy) {
  ndc.set(sx / innerWidth * 2 - 1, -(sy / innerHeight) * 2 + 1);
  ray.setFromCamera(ndc, camera);
  if (!ray.ray.intersectPlane(floorPlane, hitV)) return { x: AW / 2, y: AH / 2 };
  return { x: hitV.x * S + AW / 2, y: hitV.z * S + AH / 2 };
}
 
/* ---------------- lights ---------------- */
scene.add(new THREE.HemisphereLight(0x6f86d8, 0x0a0816, 0.55));
const keyL = new THREE.DirectionalLight(0xbfd0ff, 0.9); keyL.position.set(-20, 40, 18); scene.add(keyL);
const shipL = new THREE.PointLight(0x7fe6ff, 10, 9, 1.6); scene.add(shipL);
const boltL = [0, 1].map(() => { const l = new THREE.PointLight(0xdfe8ff, 0, 22, 1.4); scene.add(l); return l; });
 
/* ---------------- the storm below ---------------- */
const seaMat = new THREE.ShaderMaterial({
  uniforms: { time: { value: 0 }, flash: { value: 0 }, flashAt: { value: new THREE.Vector2() } },
  vertexShader: "varying vec2 vP; void main(){ vP = position.xz; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }",
  fragmentShader: `uniform float time, flash; uniform vec2 flashAt; varying vec2 vP;
    float h(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
    float n(vec2 p){ vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix(mix(h(i), h(i + vec2(1, 0)), f.x), mix(h(i + vec2(0, 1)), h(i + vec2(1, 1)), f.x), f.y); }
    float fbm(vec2 p){ float s = 0.0, a = 0.5; for (int i = 0; i < 5; i++){ s += n(p) * a; p = p * 2.03 + vec2(1.7, 9.2); a *= 0.5; } return s; }
    void main(){
      vec2 p = vP * 0.03;
      float c = fbm(p + vec2(time * 0.02, time * 0.012));
      float c2 = fbm(p * 1.7 - vec2(time * 0.03, 0.0) + c);
      vec3 col = mix(vec3(0.012, 0.014, 0.04), vec3(0.07, 0.08, 0.2), smoothstep(0.35, 0.8, c2));
      col += vec3(0.08, 0.05, 0.16) * smoothstep(0.6, 0.9, c);
      float d = length(vP - flashAt);
      col += vec3(0.55, 0.62, 1.0) * flash * c2 * (exp(-d * d * 0.0004) * 1.6 + 0.12);
      gl_FragColor = vec4(col, 1.0);
    }`,
  fog: false
});
const sea = new THREE.Mesh(new THREE.PlaneGeometry(700, 700).rotateX(-Math.PI / 2), seaMat);
sea.position.y = -16;
scene.add(sea);
 
/* ---------------- honeycomb floor: one instance per charge cell ---------------- */
const CELL_R = HS / S - 0.07;
const hexGeo = new THREE.CylinderGeometry(CELL_R, CELL_R, 0.7, 6, 1).translate(0, -0.35, 0);
const hexN = hexPos.length;
const aCharge = new THREE.InstancedBufferAttribute(new Float32Array(hexN), 1).setUsage(THREE.DynamicDrawUsage);
const aSeed = new THREE.InstancedBufferAttribute(new Float32Array(hexN), 1);
hexGeo.setAttribute("aCharge", aCharge); hexGeo.setAttribute("aSeed", aSeed);
const hexMat = new THREE.ShaderMaterial({
  uniforms: { time: { value: 0 }, uPlayer: { value: new THREE.Vector3() }, uFlash: { value: [new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4()] }, uBomb: { value: 0 }, uR: { value: CELL_R }, fogColor: { value: scene.fog.color }, fogNear: { value: 60 }, fogFar: { value: 150 } },
  vertexShader: `attribute float aCharge, aSeed; varying vec3 vW, vN; varying float vC, vSeed, vY; varying vec2 vL;
    void main(){
      vec3 p = position;
      float top = step(-0.001, p.y);
      p.y += top * min(aCharge, 1.4) * 0.5;
      vec4 w = modelMatrix * instanceMatrix * vec4(p, 1.0);
      vW = w.xyz; vN = normal; vC = aCharge; vSeed = aSeed; vY = position.y; vL = position.xz;
      gl_Position = projectionMatrix * viewMatrix * w;
    }`,
  fragmentShader: `uniform float time, uBomb, uR, fogNear, fogFar; uniform vec3 uPlayer, fogColor; uniform vec4 uFlash[3];
    varying vec3 vW, vN; varying float vC, vSeed, vY; varying vec2 vL;
    void main(){
      float c = vC;
      vec3 col;
      float lit = 0.0;
      vec3 pd = vW - uPlayer; float pl = exp(-dot(pd.xz, pd.xz) * 0.06);
      for (int i = 0; i < 3; i++){ vec2 d = vW.xz - uFlash[i].xy; lit += uFlash[i].w * exp(-dot(d, d) * 0.025); }
      if (vN.y > 0.5) {
        float hx = max(abs(vL.x), abs(vL.x) * 0.5 + abs(vL.y) * 0.866) / (0.866 * uR);   // 0 centre .. 1 edge (pointy along z)
        float e = smoothstep(0.82, 0.95, hx);
        float sweep = 0.5 + 0.5 * sin(time * 1.6 - vW.x * 0.18 + vW.z * 0.11 + vSeed * 2.0);
        col = vec3(0.004, 0.006, 0.014) * (0.7 + vSeed * 0.6);
        col += vec3(0.006, 0.01, 0.024) * (1.0 - hx);
        col += vec3(0.3, 0.62, 1.0) * e * (0.03 + sweep * 0.035 + c * 2.4);
        col += vec3(0.18, 0.42, 1.0) * c * c * 0.55 * (1.0 - e);
        col += vec3(1.0) * smoothstep(0.95, 1.4, c) * 0.6 * (1.0 - hx);
        col += vec3(0.35, 0.85, 1.0) * pl * (0.12 + e * 0.6);
        col += vec3(0.75, 0.82, 1.0) * lit * (0.25 + e);
        col += vec3(0.6, 0.85, 1.0) * uBomb * (0.15 + e * 0.8);
      } else {
        float band = smoothstep(-0.3, 0.0, vY);
        col = vec3(0.003, 0.004, 0.01) + vec3(0.25, 0.55, 1.0) * c * band * 1.2 + vec3(0.3, 0.7, 1.0) * pl * band * 0.2 + vec3(0.6, 0.7, 1.0) * lit * band * 0.4;
      }
      float fd = length(vW - cameraPosition);
      col = mix(col, fogColor, smoothstep(fogNear, fogFar, fd));
      gl_FragColor = vec4(col, 1.0);
    }`
});
const hexMesh = new THREE.InstancedMesh(hexGeo, hexMat, hexN);
{
  const m = new THREE.Matrix4();
  for (let i = 0; i < hexN; i++) {
    m.makeTranslation(WX(hexPos[i][0]), 0, WZ(hexPos[i][1]));
    hexMesh.setMatrixAt(i, m);
    aSeed.array[i] = Math.random();
  }
}
// only the cells inside the arena (plus a ragged rim) are kept
{
  let j = 0; const m = new THREE.Matrix4();
  for (let i = 0; i < hexN; i++) {
    const [x, y] = hexPos[i];
    if (x < -HS * 0.6 || x > AW + HS * 0.6 || y < -HS * 0.6 || y > AH + HS * 0.6) { m.makeScale(0, 0, 0); hexMesh.setMatrixAt(i, m); }
    j++;
  }
}
hexMesh.frustumCulled = false;
scene.add(hexMesh);
// the arena's underside: a dark slab, so the floor reads as a floating platform
const under = new THREE.Mesh(new THREE.BoxGeometry(AW / S + 2.4, 2.6, AH / S + 2.4).translate(0, -2.05, 0), new THREE.MeshStandardMaterial({ color: 0x080a16, roughness: 0.7, metalness: 0.5 }));
scene.add(under);
for (const [x, z] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) {
  const fin = new THREE.Mesh(new THREE.ConeGeometry(2.6, 9, 6).rotateX(Math.PI), new THREE.MeshStandardMaterial({ color: 0x0a0d1c, roughness: 0.6, metalness: 0.6 }));
  fin.position.set(x * (AW / S / 2 - 3), -7.5, z * (AH / S / 2 - 3));
  scene.add(fin);
  const lamp = glowSprite(hdr(0x7fc8ff, 2.2), 4); lamp.position.set(x * (AW / S / 2 - 3), -12, z * (AH / S / 2 - 3)); scene.add(lamp);
}
 
/* ---------------- arena fence ---------------- */
const fenceMat = new THREE.ShaderMaterial({
  transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
  uniforms: { time: { value: 0 }, hot: { value: 0 } },
  vertexShader: "varying vec2 vU; void main(){ vU = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }",
  fragmentShader: `uniform float time, hot; varying vec2 vU;
    void main(){
      float a = pow(1.0 - vU.y, 2.2) * 0.55 + smoothstep(0.03, 0.0, abs(vU.y - 0.98)) * 0.4;
      float scan = 0.55 + 0.45 * sin(vU.x * 260.0 - time * 6.0);
      vec3 col = vec3(0.35, 0.7, 1.0) * a * (0.6 + scan * 0.4) * (1.0 + hot * 2.0);
      gl_FragColor = vec4(col, 1.0);
    }`
});
{
  const hw = AW / S / 2 + 0.6, hd = AH / S / 2 + 0.6, FH = 1.4;
  for (const [len, x, z, ry] of [[hw * 2, 0, -hd, 0], [hw * 2, 0, hd, Math.PI], [hd * 2, -hw, 0, Math.PI / 2], [hd * 2, hw, 0, -Math.PI / 2]]) {
    const f = new THREE.Mesh(new THREE.PlaneGeometry(len, FH).translate(0, FH / 2, 0), fenceMat);
    f.position.set(x, 0, z); f.rotation.y = ry; scene.add(f);
    const rail = new THREE.Mesh(new THREE.BoxGeometry(len, 0.12, 0.12), new THREE.MeshBasicMaterial({ color: hdr(0x8fd0ff, 2.6) }));
    rail.position.set(x, 0.05, z); rail.rotation.y = ry; scene.add(rail);
  }
  for (const [x, z] of [[-hw, -hd], [hw, -hd], [-hw, hd], [hw, hd]]) {
    const p = new THREE.Mesh(new THREE.CylinderGeometry(0.45, 0.6, 3, 6).translate(0, 1.5, 0), new THREE.MeshStandardMaterial({ color: 0x1a1f36, roughness: 0.35, metalness: 0.8 }));
    p.position.set(x, 0, z); scene.add(p);
    const cap = new THREE.Mesh(new THREE.OctahedronGeometry(0.42), new THREE.MeshBasicMaterial({ color: hdr(0x9fe0ff, 3) }));
    cap.position.set(x, 3.5, z); scene.add(cap);
  }
}
 
/* ---------------- rain ---------------- */
const RAIN = 900;
const rainGeo = new THREE.BufferGeometry();
{
  const p = new Float32Array(RAIN * 6), s = new Float32Array(RAIN * 2);
  for (let i = 0; i < RAIN; i++) {
    const x = rand(-40, 40), y = rand(0, 16), z = rand(-30, 30), sd = Math.random();
    p.set([x, y, z, x - 0.12, y + 0.8, z - 0.05], i * 6); s[i * 2] = sd; s[i * 2 + 1] = sd;
  }
  rainGeo.setAttribute("position", new THREE.BufferAttribute(p, 3)); rainGeo.setAttribute("seed", new THREE.BufferAttribute(s, 1));
}
const rainMat = new THREE.ShaderMaterial({
  transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
  uniforms: { time: { value: 0 }, origin: { value: new THREE.Vector3() } },
  vertexShader: `uniform float time; uniform vec3 origin; attribute float seed; varying float vA;
    void main(){
      vec3 p = position;
      p.y = mod(p.y - time * (22.0 + seed * 8.0) + seed * 16.0, 16.0) - 1.0;
      p.x += origin.x; p.z += origin.z;
      vA = 0.06 + seed * 0.1;
      gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);
    }`,
  fragmentShader: "varying float vA; void main(){ gl_FragColor = vec4(vec3(0.55, 0.7, 1.0) * vA, 1.0); }"
});
const rain = new THREE.LineSegments(rainGeo, rainMat);
rain.frustumCulled = false;
scene.add(rain);
 
/* ---------------- instanced parts ---------------- */
const shadowTex = canvasTex(64, 64, (g, w) => {
  const gr = g.createRadialGradient(w / 2, w / 2, 0, w / 2, w / 2, w / 2);
  gr.addColorStop(0, "rgba(0,0,0,.8)"); gr.addColorStop(1, "rgba(0,0,0,0)");
  g.fillStyle = gr; g.fillRect(0, 0, w, w);
});
const WHITE = new THREE.Color(1, 1, 1);
class Inst {
  constructor(geo, mat, cap) {
    this.m = new THREE.InstancedMesh(geo, mat, cap);
    this.m.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
    this.m.setColorAt(0, WHITE);
    this.m.count = 0; this.m.frustumCulled = false; this.n = 0; this.cap = cap;
    scene.add(this.m);
  }
  add(x, y, z, rx, ry, rz, sx, sy, sz, col) {
    if (this.n >= this.cap) return;
    e4.set(rx, ry, rz, "YXZ"); q4.setFromEuler(e4);
    m4.compose(v4.set(x, y, z), q4, s4.set(sx, sy, sz));
    this.m.setMatrixAt(this.n, m4);
    this.m.setColorAt(this.n, col || WHITE);
    this.n++;
  }
  flush() {
    this.m.count = this.n; this.n = 0;
    this.m.instanceMatrix.needsUpdate = true;
    if (this.m.instanceColor) this.m.instanceColor.needsUpdate = true;
  }
}
const basic = (o) => new THREE.MeshBasicMaterial(Object.assign({ color: 0xffffff }, o));
const ADDM = (o) => basic(Object.assign({ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending }, o));
const metal = (o) => new THREE.MeshStandardMaterial(Object.assign({ color: 0xffffff, roughness: 0.3, metalness: 0.55 }, o));
const SPH = new THREE.SphereGeometry(1, 18, 12);
const I = {
  shadow: new Inst(new THREE.PlaneGeometry(1, 1).rotateX(-Math.PI / 2), basic({ map: shadowTex, transparent: true, depthWrite: false, color: 0xffffff }), 400),
  // jelly sparks: a translucent bell with a hot core
  bell: new Inst(new THREE.SphereGeometry(1, 20, 10, 0, TAU, 0, Math.PI * 0.55), ADDM({ opacity: 0.55, side: THREE.DoubleSide }), 220),
  core: new Inst(new THREE.SphereGeometry(1, 12, 8), basic(), 600),
  // darts: a needle hull with a glowing spine
  needle: new Inst(new THREE.OctahedronGeometry(1), metal({ roughness: 0.25, metalness: 0.7, emissive: 0x2a0a02 }), 200),
  spine: new Inst(new THREE.BoxGeometry(1, 1, 1), basic(), 900),
  // shellbacks: an armoured ball and a curved shield
  shellBody: new Inst(new THREE.IcosahedronGeometry(1, 1), metal({ roughness: 0.4, metalness: 0.6, flatShading: true }), 160),
  shield: new Inst(new THREE.CylinderGeometry(1, 1, 1, 18, 1, true, -1.05, 2.1), ADDM({ side: THREE.DoubleSide, opacity: 0.9 }), 160),
  // seeders: three petals round a core
  petal: new Inst(SPH, metal({ roughness: 0.35, metalness: 0.5, emissive: 0x1a1000 }), 400),
  // mines: an eight-point star
  mine: new Inst(new THREE.OctahedronGeometry(1), basic(), 160),
  // eels: a head and a string of fins
  eelHead: new Inst(SPH, metal({ roughness: 0.3, metalness: 0.5, emissive: 0x120420 }), 80),
  fin: new Inst(new THREE.BoxGeometry(1, 1, 1), basic(), 900),
  // thunderheads and supercells: dark puffs with a lit rim
  puff: null,
  // bullets, motes
  bullet: new Inst(new THREE.BoxGeometry(1, 1, 1), basic(), 700),
  gem: new Inst(new THREE.OctahedronGeometry(1), basic(), 400),
  halo: new Inst(new THREE.PlaneGeometry(1, 1).rotateX(-Math.PI / 2), ADDM({ map: glowTex }), 400),
  disc: new Inst(new THREE.CircleGeometry(1, 40).rotateX(-Math.PI / 2), ADDM({ opacity: 1 }), 24)
};
const puffMat = new THREE.ShaderMaterial({
  uniforms: { time: { value: 0 } },
  vertexShader: `uniform float time; varying vec3 vN, vV, vCol; varying vec3 vW;
    float h3(vec3 p){ return fract(sin(dot(p, vec3(12.9898, 78.233, 37.719))) * 43758.5453); }
    float n3(vec3 p){ vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
      return mix(mix(mix(h3(i), h3(i + vec3(1, 0, 0)), f.x), mix(h3(i + vec3(0, 1, 0)), h3(i + vec3(1, 1, 0)), f.x), f.y),
                 mix(mix(h3(i + vec3(0, 0, 1)), h3(i + vec3(1, 0, 1)), f.x), mix(h3(i + vec3(0, 1, 1)), h3(i + vec3(1, 1, 1)), f.x), f.y), f.z); }
    void main(){
      // lumpy, slowly boiling puffs
      vec3 p = position * (1.0 + (n3(position * 2.6 + vec3(time * 0.4, instanceMatrix[3].x, instanceMatrix[3].z)) - 0.5) * 0.34);
      vec4 w = modelMatrix * instanceMatrix * vec4(p, 1.0);
      vW = w.xyz;
      vN = normalize(mat3(modelMatrix * instanceMatrix) * normal);
      vV = normalize(cameraPosition - w.xyz);
      vCol = instanceColor;
      gl_Position = projectionMatrix * viewMatrix * w;
    }`,
  fragmentShader: `uniform float time; varying vec3 vN, vV, vCol, vW;
    float h(vec3 p){ return fract(sin(dot(p, vec3(12.9898, 78.233, 37.719))) * 43758.5453); }
    void main(){
      float rim = pow(1.0 - max(0.0, dot(vN, vV)), 2.4);
      float n = h(floor(vW * 3.0 + vec3(0.0, time * 0.6, 0.0)));
      vec3 base = mix(vec3(0.006, 0.006, 0.016), vec3(0.03, 0.032, 0.07), max(0.0, vN.y)) * (0.75 + n * 0.25);
      float hot = vCol.r;   // instance colour carries the inner flash in r, the rim strength in g
      vec3 col = base + vec3(0.45, 0.55, 1.0) * rim * vCol.g * 0.8 + vec3(0.8, 0.85, 1.0) * hot * (0.3 + n * 0.7);
      gl_FragColor = vec4(col, 1.0);
    }`
});
I.puff = new Inst(SPH, puffMat, 120);
 
/* ---------------- the storm-chaser ---------------- */
const ship = new THREE.Group();
{
  const hull = new THREE.Mesh(new THREE.CylinderGeometry(0.42, 0.55, 0.26, 24), metal({ color: 0xdfe8f5, roughness: 0.22, metalness: 0.75 }));
  const dome = new THREE.Mesh(new THREE.SphereGeometry(0.3, 18, 10, 0, TAU, 0, Math.PI / 2), basic({ color: hdr(0x5ef2ff, 2.2) }));
  dome.position.y = 0.12;
  const belt = new THREE.Mesh(new THREE.TorusGeometry(0.52, 0.035, 8, 32).rotateX(Math.PI / 2), basic({ color: hdr(0x9fe8ff, 2.4) }));
  ship.add(hull, dome, belt);
  const gun = new THREE.Group();
  const barrel = new THREE.Mesh(new THREE.BoxGeometry(0.75, 0.1, 0.16), metal({ color: 0x9aa6c0 }));
  barrel.position.x = 0.6;
  const tip = new THREE.Mesh(new THREE.BoxGeometry(0.1, 0.12, 0.18), basic({ color: hdr(0xffe68a, 3) }));
  tip.position.x = 0.98;
  gun.add(barrel, tip);
  for (const sd of [-1, 1]) { const pod = new THREE.Mesh(new THREE.SphereGeometry(0.17, 12, 8), metal({ color: 0x7c88a8 })); pod.position.set(-0.1, 0, sd * 0.55); gun.add(pod); const pl = new THREE.Mesh(new THREE.SphereGeometry(0.07, 8, 6), basic({ color: hdr(0x5ef2ff, 3) })); pl.position.set(-0.26, 0, sd * 0.55); gun.add(pl); }
  ship.add(gun);
  ship.userData.gun = gun;
  const rotor = new THREE.Mesh(new THREE.TorusGeometry(0.85, 0.04, 6, 40, 1.25), basic({ color: hdr(0xaaeeff, 2) }));
  rotor.rotation.x = Math.PI / 2;
  const rotorG = new THREE.Group();
  for (let k = 0; k < 3; k++) { const r = rotor.clone(); r.rotation.z = k * TAU / 3; rotorG.add(r); }
  ship.add(rotorG);
  ship.userData.rotor = rotorG;
  const ocRing = new THREE.Mesh(new THREE.RingGeometry(1.05, 1.2, 48).rotateX(-Math.PI / 2), ADDM({ color: hdr(0xbfe6ff, 2.2) }));
  ocRing.position.y = -0.6;
  ship.add(ocRing);
  ship.userData.oc = ocRing;
  const halo = glowSprite(hdr(0x5ef2ff, 0.6), 2);
  ship.add(halo);
}
ship.scale.setScalar(1.3);
scene.add(ship);
const shipShadow = new THREE.Mesh(new THREE.PlaneGeometry(2.2, 2.2).rotateX(-Math.PI / 2), basic({ map: shadowTex, transparent: true, depthWrite: false }));
scene.add(shipShadow);
 
/* ---------------- particles: arena pixels in, world units out ---------------- */
const toHex = (c) => (typeof c === "number" ? c : new THREE.Color(c).getHex());
const fx = {
  burst(x, y, o) {
    o = o || {};
    burst(WX(x), WZ(y), { n: Math.ceil((o.n || 16) * 0.8), colors: (o.colors || [o.color || "#ffffff"]).map(toHex), speed: (o.speed || 200) / S * 1.1, life: o.life || 0.6, size: Math.max(0.12, (o.size || 2) / S * 3), y: 0.8, up: 2.4, g: 4, angle: o.angle, spread: o.spread, bright: 2.6 });
  },
  update(dt) { updateParts(dt); updateShards(dt); },
  clear() { parts.length = 0; shards.length = 0; }
};
const texts = new PA.Texts();
/* ================= state ================= */
let P, bullets, enemies, gems, clouds, strikes, waves, bestChain, spawnT, t, score, mult, multXp, lives, bombs, nextLife, wave, alive, fireCd, overT, spawnBudget, alwaysFire = false, bombFlash = 0, kills;
// added in 3D: dash, overcharge from lit cells, and the supercell
let dashT, dashCd, dashDir, ocT, boss, nextBoss, cellsDowned;
const DASH_T = 0.2, DASH_CD = 1.3, DASH_SP = 1500, OC_T = 1.6;
let mouse = { x: 0, y: 0, down: false, seen: false };
const COL = { player: "#eaffff", bullet: "#ffe68a", drift: "#9fd8ff", dart: "#ff7a59", shell: "#7dffcf", seeder: "#ffd34d", mine: "#fff3b0", eel: "#c58bff", cloud: "#8fa6ff", cell: "#c9b8ff", gem: "#7dffb0", bolt: "#f4f7ff" };
 
function reset() {
  P = { x: AW / 2, y: AH / 2, vx: 0, vy: 0, a: 0, inv: 2, dead: 0 };
  bullets = []; enemies = []; gems = []; clouds = []; strikes = []; waves = []; bestChain = 0;
  spawnT = 1.2; t = 0; score = 0; mult = 1; multXp = 0; lives = 3; bombs = 3; nextLife = 75000; wave = 0; alive = true; fireCd = 0; overT = 0; spawnBudget = 0; kills = 0;
  dashT = 0; dashCd = 0; dashDir = 0; ocT = 0; boss = null; nextBoss = 80; cellsDowned = 0;
  fx.clear(); texts.clear();
  hexC.fill(0);
  paint();
  clearScene();
}
function paint() {
  PA.stat("gs-score", score.toLocaleString());
  PA.stat("gs-mult", "×" + mult);
  PA.stat("gs-lives", lives);
  PA.stat("gs-bombs", bombs);
}
 
/* ================= enemies ================= */
/* the storm's own cast:
   drift      jelly sparks that wander on the breeze
   dart       needles that stop, take aim (you see the line) and lunge
   shell      shellbacks: a shield faces you, so flank them or use a shockwave
   seeder     pods that circle at range and sow mines
   mine       sown by seeders; fizzle out after a while, but make great chain fuel
   eel        zigzag current that only moves in straight runs and right-angle turns
   cloud      thunderheads: call lightning onto the spot you're heading for */
const TYPES = {
  drift: { r: 14, hp: 1, pts: 25, speed: 62 },
  dart: { r: 14, hp: 1, pts: 50, speed: 560 },
  shell: { r: 17, hp: 2, pts: 100, speed: 95 },
  seeder: { r: 16, hp: 2, pts: 100, speed: 150 },
  mine: { r: 7, hp: 1, pts: 10, speed: 0 },
  eel: { r: 12, hp: 1, pts: 150, speed: 210 },
  cloud: { r: 30, hp: 14, pts: 200, speed: 28 },
  cell: { r: 66, hp: 90, pts: 5000, speed: 34 }
};
const CARD = [0, Math.PI / 2, Math.PI, -Math.PI / 2];
function spawn(type, x, y) {
  const T = TYPES[type];
  if (x == null) {
    // spawn away from the player, never on top of them
    for (let i = 0; i < 12; i++) { x = rand(40, AW - 40); y = rand(40, AH - 40); if (Math.hypot(x - P.x, y - P.y) > 300) break; }
  }
  const e = { type, x, y, vx: 0, vy: 0, r: T.r, hp: T.hp, a: rand(0, TAU), birth: 0.7, seed: Math.random() };
  if (type === "drift") { e.dir = rand(0, TAU); }
  if (type === "dart") { e.mode = "aim"; e.timer = rand(0.6, 1.2); e.dashA = 0; }
  if (type === "shell") { e.face = Math.atan2(P.y - y, P.x - x); }
  if (type === "seeder") { e.drop = rand(1.2, 2.4); e.orb = Math.atan2(y - P.y, x - P.x); }
  if (type === "mine") { e.life = 9; }
  if (type === "eel") { e.tail = []; for (let i = 0; i < 18; i++) e.tail.push([x, y]); e.dir = CARD[(Math.random() * 4) | 0]; e.turnT = rand(0.5, 1); }
  if (type === "cloud") { e.charge = 2.4; e.pulse = 0; }
  if (type === "cell") { e.charge = 3; e.pulse = 0; e.brood = 5; e.max = T.hp; e.hitT = 0; }
  enemies.push(e);
  return e;
}
function spawnCorners(type, n) {
  const corners = [[60, 60], [AW - 60, 60], [60, AH - 60], [AW - 60, AH - 60]];
  const far = corners.sort((a, b) => Math.hypot(b[0] - P.x, b[1] - P.y) - Math.hypot(a[0] - P.x, a[1] - P.y)).slice(0, 2);
  for (let i = 0; i < n; i++) { const c = far[i % 2]; spawn(type, c[0] + rand(-30, 30), c[1] + rand(-30, 30)); }
}
function director(dt) {
  spawnT -= dt;
  if (spawnT > 0) return;
  wave++;
  const lvl = t / 30;
  spawnT = Math.max(0.8, 2.5 - lvl * 0.3);
  const r = Math.random();
  const pick = (arr) => arr[(Math.random() * arr.length) | 0];
  const pool = ["drift", "dart"];
  if (t > 20) pool.push("shell");
  if (t > 35) pool.push("seeder");
  if (t > 55) pool.push("eel");
  const n = Math.min(20, 4 + Math.floor(lvl * 2.4));
  if (r < 0.18 && t > 25) spawnCorners(pick(pool), n + 4);
  else for (let i = 0; i < n; i++) spawn(pick(pool));
  if (t > 45 && Math.random() < 0.18 && clouds.length < 2) clouds.push(spawn("cloud"));
  if (boss) spawnT *= 1.5;
  else if (t >= nextBoss) {
    // a supercell rolls in: far from you, slow, and it takes a lot of chained shockwaves to bring down
    let x = AW / 2, y = AH / 2, far = -1;
    for (const [cx, cy] of [[220, 220], [AW - 220, 220], [220, AH - 220], [AW - 220, AH - 220]]) { const d = Math.hypot(cx - P.x, cy - P.y); if (d > far) { far = d; x = cx; y = cy; } }
    boss = spawn("cell", x, y); boss.birth = 1.6;
    nextBoss = t + 110;
    texts.add(P.x, P.y - 60, "SUPERCELL INBOUND", { color: COL.cell, size: 26, life: 2.2, vy: -20 });
    PA.sfx("boom", { pitch: .5 }); PA.shake(8, .8);
  }
}
 
/* shockwaves: every shot kill rings out along the grid, and the ring's front
   detonates whatever it crosses, which rings out again, so tight packs chain */
const WAVE_SPEED = 520, WAVE_R = 82, WAVE_GROW = 14, WAVE_MAX = 150, CHAIN_CAP = 8;
function killEnemy(e, byBomb, from) {
  if (e.dead) return;
  e.dead = true;
  kills++;
  const c = COL[e.type];
  const big = e.type === "cloud" || e.type === "cell", huge = e.type === "cell";
  const depth = from ? from.depth + 1 : 0, root = from ? from.root : { n: 0 };
  if (!byBomb) {
    root.n++;
    if (root.n > bestChain) bestChain = root.n;
    if (from && (root.n === 3 || root.n % 5 === 0)) texts.add(e.x, e.y - 22, "CHAIN " + root.n, { color: "#fff", size: 12 + Math.min(10, root.n), life: .7 });
    waves.push({ x: e.x, y: e.y, r: 0, max: huge ? 460 : Math.min(WAVE_MAX, WAVE_R + depth * WAVE_GROW), depth, root, c, hit: new Set([e]) });
  }
  fx.burst(e.x, e.y, { n: huge ? 260 : big ? 120 : 34, color: c, speed: huge ? 900 : big ? 600 : 360, life: huge ? 1.4 : .9, size: 2.6, shape: "spark", drag: 2.6 });
  zap(e.x, e.y, big ? 1800 : 520, huge ? 600 : big ? 260 : 120);
  shatter(WX(e.x), WZ(e.y), c, huge ? 70 : big ? 22 : e.type === "mine" ? 2 : 6);
  if (!byBomb) {
    const pts = TYPES[e.type].pts * mult * (huge ? 1 : Math.min(CHAIN_CAP, depth + 1));
    score += pts;
    if (pts >= 500) texts.add(e.x, e.y, pts.toLocaleString(), { color: c, size: 14, life: .6 });
    const ng = huge ? 30 : big ? 8 : e.type === "mine" ? 0 : 1 + (Math.random() < .3);
    for (let i = 0; i < ng; i++) gems.push({ x: e.x, y: e.y, vx: rand(-90, 90) * (huge ? 3 : 1), vy: rand(-90, 90) * (huge ? 3 : 1), life: 7 });
    if (huge) { cellsDowned++; texts.add(e.x, e.y - 40, "SUPERCELL DOWN  +" + pts.toLocaleString(), { color: "#ffffff", size: 26, life: 2, vy: -24 }); }
  }
  if (big) { clouds = clouds.filter((w) => w !== e); strikes = strikes.filter((k) => k.from !== e || k.t <= 0); PA.sfx("boom"); PA.shake(huge ? 22 : 10, huge ? 1.2 : .5); if (huge) { boss = null; PA.flash("#d8ccff", 400); } }
  else PA.sfx("explode", { pitch: 1.5 + Math.random() * .6, vol: .35 });
  if (score >= nextLife) { nextLife += 75000; lives++; bombs++; texts.add(P.x, P.y - 40, "+1 SHIP +1 SURGE", { color: "#fff", size: 18, life: 1.6 }); PA.sfx("levelup"); }
  paint();
}
function bomb() {
  if (!alive || bombs <= 0 || P.dead > 0 || PA.state !== "play") return;
  bombs--;
  bombFlash = 1;
  for (const e of enemies) {
    if (e.type === "cell") { e.hp -= 25; e.hitT = .3; if (e.hp <= 0) killEnemy(e); continue; }
    killEnemy(e, true);
  }
  strikes = [];
  for (let i = 0; i < 6; i++) zap(P.x, P.y, 2400, 900);
  PA.sfx("boom"); PA.shake(16, .8); PA.flash("#ffffff", 500);
  P.inv = Math.max(P.inv, 1.2);
  paint();
}
function hitPlayer() {
  if (P.inv > 0 || P.dead > 0 || dashT > 0) return;
  lives--; mult = 1; multXp = 0;
  P.dead = 2;
  fx.burst(P.x, P.y, { n: 200, colors: ["#fff", "#5ef2ff", "#ffe68a"], speed: 700, life: 1.4, size: 3, shape: "spark" });
  for (let i = 0; i < 4; i++) zap(P.x, P.y, 2600, 600);
  PA.sfx("boom"); PA.shake(20, 1); PA.flash("#ff4d6b", 500);
  // clear the board so respawns are fair
  waves = [];
  for (const e of enemies) { if (e.type === "cell") continue; e.dead = true; fx.burst(e.x, e.y, { n: 8, color: COL[e.type], speed: 200, life: .6, shape: "spark" }); }
  clouds = []; strikes = []; ocT = 0; dashT = 0;
  paint();
  if (lives <= 0) { alive = false; overT = 1.6; }
}
 
/* ================= input ================= */
const s1 = { el: $("gs-s1"), id: null, ox: 0, oy: 0, dx: 0, dy: 0 }, s2 = { el: $("gs-s2"), id: null, ox: 0, oy: 0, dx: 0, dy: 0 };
addEventListener("pointermove", (e) => {
  if (e.pointerType === "mouse") { mouse.x = e.clientX; mouse.y = e.clientY; mouse.seen = true; }
  for (const s of [s1, s2]) if (s.id === e.pointerId) {
    let dx = e.clientX - s.ox, dy = e.clientY - s.oy; const d = Math.hypot(dx, dy), m = 50;
    if (d > m) { dx = dx / d * m; dy = dy / d * m; }
    s.dx = dx / m; s.dy = dy / m; s.el.firstElementChild.style.transform = `translate(${dx}px,${dy}px)`;
  }
});
addEventListener("pointerdown", (e) => {
  if (e.target.closest && e.target.closest("button,#pa-gate,.pa-layer,.pa-tb")) return;
  if (e.pointerType === "mouse") { if (e.button === 2) bomb(); else mouse.down = true; return; }
  const s = e.clientX < view.w / 2 ? s1 : s2;
  if (s.id != null) return;
  s.id = e.pointerId; s.ox = e.clientX; s.oy = e.clientY; s.dx = s.dy = 0;
  s.el.style.display = "block"; s.el.style.left = e.clientX + "px"; s.el.style.top = e.clientY + "px";
});
const up = (e) => {
  if (e.pointerType === "mouse") { mouse.down = false; return; }
  for (const s of [s1, s2]) if (s.id === e.pointerId) { s.id = null; s.dx = s.dy = 0; s.el.style.display = "none"; s.el.firstElementChild.style.transform = ""; }
};
addEventListener("pointerup", up); addEventListener("pointercancel", up);
addEventListener("contextmenu", (e) => e.preventDefault());
$("gs-bomb").addEventListener("pointerdown", (e) => { e.stopPropagation(); e.preventDefault(); bomb(); });
$("gs-dash").addEventListener("pointerdown", (e) => { e.stopPropagation(); e.preventDefault(); dash(); });
PA.onKey((e) => {
  if (e.code === "Space") { e.preventDefault(); bomb(); }
  if (e.code === "ShiftLeft" || e.code === "ShiftRight" || e.code === "KeyE") dash();
  if (e.code === "KeyF") { alwaysFire = !alwaysFire; PA.toast(alwaysFire ? "Always-fire on" : "Always-fire off", 1400); }
});
 
/* ================= dash + overcharge ================= */
function dash() {
  if (!alive || !P || P.dead > 0 || dashCd > 0 || PA.state !== "play") return;
  const sp = Math.hypot(P.vx, P.vy);
  dashDir = sp > 40 ? Math.atan2(P.vy, P.vx) : P.aim != null ? P.aim : P.a;
  dashT = DASH_T; dashCd = DASH_CD;
  PA.sfx("whoosh", { pitch: 1.3 }); PA.shake(3, .15);
}
// the charge of the cell under a point
function cellAt(px, py) {
  const y = clamp(Math.round((py + HR / 2) / HR), 0, HY - 1);
  const x = clamp(Math.round((px + HW / 2 - (y & 1 ? HW / 2 : 0)) / HW), 0, HX - 1);
  return hexC[y * HX + x];
}
 
/* ================= update ================= */
function update(dt) {
  if (PA.state !== "play" || !P) { updateGrid(dt); return; }
  t += dt;
  updateGrid(dt);
  bombFlash = Math.max(0, bombFlash - dt * 2);
  if (!alive) { overT -= dt; fx.update(dt); if (overT <= 0 && !P.sent) { P.sent = true; finish(); } return; }
  if (P.dead > 0) {
    P.dead -= dt;
    if (P.dead <= 0) { P.x = AW / 2; P.y = AH / 2; P.vx = P.vy = 0; P.inv = 2.5; spawnT = 2; }
  } else {
    P.inv = Math.max(0, P.inv - dt);
    // arrows steer only when WASD isn't in use; with WASD held they aim instead
    const wasd = PA.down("KeyW", "KeyA", "KeyS", "KeyD");
    let mx = wasd ? (PA.down("KeyD") ? 1 : 0) - (PA.down("KeyA") ? 1 : 0) : (PA.down("ArrowRight") ? 1 : 0) - (PA.down("ArrowLeft") ? 1 : 0);
    let my = wasd ? (PA.down("KeyS") ? 1 : 0) - (PA.down("KeyW") ? 1 : 0) : (PA.down("ArrowDown") ? 1 : 0) - (PA.down("ArrowUp") ? 1 : 0);
    if (s1.id != null) { mx = s1.dx; my = s1.dy; }
    const ml = Math.hypot(mx, my); if (ml > 1) { mx /= ml; my /= ml; }
    const SP = 420;
    dashCd = Math.max(0, dashCd - dt);
    if (dashT > 0) {
      // a dash ignores the sticks for a moment, and pours charge into the cells it crosses
      dashT -= dt;
      P.vx = Math.cos(dashDir) * DASH_SP; P.vy = Math.sin(dashDir) * DASH_SP;
      zap(P.x, P.y, 700, 70);
      if (Math.random() < .9) fx.burst(P.x, P.y, { n: 3, colors: ["#ffe68a", "#ffffff", "#9fe8ff"], speed: 120, life: .4, size: 2.4 });
      if (dashT <= 0) { P.vx *= .35; P.vy *= .35; }
    } else { P.vx += (mx * SP - P.vx) * Math.min(1, dt * 12); P.vy += (my * SP - P.vy) * Math.min(1, dt * 12); }
    // overcharge: standing on lit cells charges your guns
    if (cellAt(P.x, P.y) > .5) { if (ocT <= 0) { texts.add(P.x, P.y - 34, "OVERCHARGE", { color: "#cfeaff", size: 15, life: .8, vy: -30 }); PA.sfx("power", { pitch: 1.6, vol: .2 }); } ocT = OC_T; }
    else ocT = Math.max(0, ocT - dt);
    P.x = clamp(P.x + P.vx * dt, 14, AW - 14); P.y = clamp(P.y + P.vy * dt, 14, AH - 14);
    if (ml > 0.1) P.a = Math.atan2(my, mx);
    // gentle wake in the grid
    if (ml > 0.1) zap(P.x - P.vx * .05, P.y - P.vy * .05, 40, 60);
    // aim + fire
    let aim = null, firing = false;
    if (s2.id != null && Math.hypot(s2.dx, s2.dy) > 0.25) { aim = Math.atan2(s2.dy, s2.dx); firing = true; }
    else if (mouse.seen) { const w = screenToWorld(mouse.x, mouse.y); aim = Math.atan2(w.y - P.y, w.x - P.x); firing = mouse.down || alwaysFire; }
    // keyboard-only: arrow keys aim+fire when WASD is used to move
    const ax = (PA.down("ArrowRight") ? 1 : 0) - (PA.down("ArrowLeft") ? 1 : 0), ay = (PA.down("ArrowDown") ? 1 : 0) - (PA.down("ArrowUp") ? 1 : 0);
    if ((ax || ay) && wasd) { aim = Math.atan2(ay, ax); firing = true; }
    P.aim = aim;
    fireCd -= dt;
    if (firing && aim != null && fireCd <= 0) {
      const oc = ocT > 0;
      fireCd = oc ? 0.065 : 0.085;
      const streams = score > 150000 ? 4 : score > 40000 ? 3 : 2;
      const spread = streams >= 3 ? 0.09 : 0.05;
      for (let i = 0; i < streams; i++) {
        const a = aim + (i - (streams - 1) / 2) * spread;
        const off = (i - (streams - 1) / 2) * 6;
        bullets.push({ x: P.x + Math.cos(aim + 1.57) * off, y: P.y + Math.sin(aim + 1.57) * off, vx: Math.cos(a) * 1050 + P.vx * .3, vy: Math.sin(a) * 1050 + P.vy * .3, life: 1.1, pierce: oc ? 2 : 0, oc, hits: null });
      }
      PA.sfx("laser", { pitch: 1.8 + Math.random() * .2, vol: .18 });
    }
  }
  director(dt);
 
  // bullets
  for (const b of bullets) {
    b.x += b.vx * dt; b.y += b.vy * dt; b.life -= dt;
    if (b.x < 0 || b.y < 0 || b.x > AW || b.y > AH) { b.life = 0; fx.burst(clamp(b.x, 0, AW), clamp(b.y, 0, AH), { n: 3, color: COL.bullet, speed: 120, life: .25, shape: "spark" }); zap(b.x, b.y, 90, 50); }
  }
  // enemies
  for (const e of enemies) {
    if (e.dead) continue;
    if (e.birth > 0) { e.birth -= dt; continue; }
    const T = TYPES[e.type], dx = P.x - e.x, dy = P.y - e.y, d = Math.hypot(dx, dy) || 1;
    const chase = P.dead > 0 ? 0 : 1;
    e.a += dt * 3;
    if (e.type === "drift") {
      e.dir += Math.sin(t * 1.7 + e.seed * 9) * dt * 1.4;
      e.vx = Math.cos(e.dir) * T.speed + dx / d * 28 * chase; e.vy = Math.sin(e.dir) * T.speed + dy / d * 28 * chase;
    } else if (e.type === "dart") {
      e.timer -= dt;
      if (e.mode === "aim") {
        const k = Math.pow(0.02, dt); e.vx *= k; e.vy *= k;
        if (chase) e.dashA = Math.atan2(dy, dx);
        if (e.timer <= 0 && chase) { e.mode = "dash"; e.timer = 0.42; e.vx = Math.cos(e.dashA) * T.speed; e.vy = Math.sin(e.dashA) * T.speed; PA.sfx("laser", { pitch: .7, vol: .12 }); }
      } else {
        const k = Math.pow(0.4, dt); e.vx *= k; e.vy *= k;
        if (e.timer <= 0) { e.mode = "aim"; e.timer = rand(0.7, 1.2); }
      }
    } else if (e.type === "shell") {
      let da = Math.atan2(dy, dx) - e.face; while (da > Math.PI) da -= TAU; while (da < -Math.PI) da += TAU;
      e.face += clamp(da, -1.5 * dt, 1.5 * dt);
      e.vx += (dx / d * T.speed * chase - e.vx) * dt * 2; e.vy += (dy / d * T.speed * chase - e.vy) * dt * 2;
    } else if (e.type === "seeder") {
      e.orb += dt * 0.45;
      const gx = clamp(P.x + Math.cos(e.orb) * 330, 40, AW - 40), gy = clamp(P.y + Math.sin(e.orb) * 330, 40, AH - 40);
      const sx = gx - e.x, sy = gy - e.y, sd = Math.hypot(sx, sy) || 1, sp = Math.min(T.speed, sd * 2);
      e.vx += (sx / sd * sp - e.vx) * dt * 2.5; e.vy += (sy / sd * sp - e.vy) * dt * 2.5;
      e.drop -= dt;
      if (e.drop <= 0 && chase) {
        e.drop = rand(1.6, 2.6);
        if (enemies.filter((o) => o.type === "mine").length < 36) { const m = spawn("mine", e.x, e.y); m.birth = 0.25; PA.sfx("blip", { pitch: .6, vol: .15 }); }
      }
    } else if (e.type === "mine") {
      e.vx = e.vy = 0; e.life -= dt;
      if (e.life <= 0) { e.dead = true; fx.burst(e.x, e.y, { n: 5, color: COL.mine, speed: 60, life: .3 }); }
    } else if (e.type === "eel") {
      e.turnT -= dt;
      if (e.turnT <= 0 && chase) {
        e.turnT = rand(0.45, 1.0);
        // right-angle turns only: head along whichever axis has more ground to cover, now and then the other
        const horiz = (Math.abs(dx) > Math.abs(dy)) !== (Math.random() < 0.25);
        e.dir = horiz ? (dx > 0 ? 0 : Math.PI) : (dy > 0 ? Math.PI / 2 : -Math.PI / 2);
      }
      e.vx = Math.cos(e.dir) * T.speed; e.vy = Math.sin(e.dir) * T.speed;
      e.tail.unshift([e.x, e.y]); if (e.tail.length > 26) e.tail.pop();
    } else if (e.type === "cell") {
      // the supercell keeps its distance, broods jelly sparks, and lands lightning in threes
      e.pulse += dt; e.hitT = Math.max(0, e.hitT - dt);
      const want = d > 360 ? 1 : d < 260 ? -1 : 0;
      e.vx += (dx / d * T.speed * want * chase - e.vx) * dt; e.vy += (dy / d * T.speed * want * chase - e.vy) * dt;
      e.charge -= dt; e.brood -= dt;
      if (e.charge <= 0 && chase) {
        e.charge = Math.max(1.6, 2.6 - t / 300);
        const fx0 = clamp(P.x + P.vx * 0.4, 20, AW - 20), fy0 = clamp(P.y + P.vy * 0.4, 20, AH - 20), side = Math.atan2(P.vy, P.vx) + Math.PI / 2;
        for (const k of [0, -1, 1]) strikes.push({ x: clamp(fx0 + Math.cos(side) * k * 120, 20, AW - 20), y: clamp(fy0 + Math.sin(side) * k * 120, 20, AH - 20), t: 1.1 + Math.abs(k) * .15, flash: 0, from: e });
        PA.sfx("blip", { pitch: .35, vol: .3 });
      }
      if (e.brood <= 0 && chase) { e.brood = 5.5; for (let i = 0; i < 4; i++) { const s = spawn("drift", clamp(e.x + rand(-60, 60), 30, AW - 30), clamp(e.y + rand(-60, 60), 30, AH - 30)); s.birth = .5; } }
    } else if (e.type === "cloud") {
      e.pulse += dt;
      e.vx += (dx / d * T.speed * chase - e.vx) * dt; e.vy += (dy / d * T.speed * chase - e.vy) * dt;
      e.charge -= dt;
      if (e.charge <= 0 && chase) {
        // lightning lands where you're heading, after a warning ring
        e.charge = Math.max(1.5, 3.2 - t / 120);
        strikes.push({ x: clamp(P.x + P.vx * 0.45 + rand(-50, 50), 20, AW - 20), y: clamp(P.y + P.vy * 0.45 + rand(-50, 50), 20, AH - 20), t: 1.05, flash: 0, from: e });
        PA.sfx("blip", { pitch: .45, vol: .25 });
      }
    }
    e.x += e.vx * dt; e.y += e.vy * dt;
    if (e.x < e.r) { e.x = e.r; e.vx = Math.abs(e.vx); if (e.dir != null) e.dir = Math.PI - e.dir; }
    if (e.x > AW - e.r) { e.x = AW - e.r; e.vx = -Math.abs(e.vx); if (e.dir != null) e.dir = Math.PI - e.dir; }
    if (e.y < e.r) { e.y = e.r; e.vy = Math.abs(e.vy); if (e.dir != null) e.dir = -e.dir; }
    if (e.y > AH - e.r) { e.y = AH - e.r; e.vy = -Math.abs(e.vy); if (e.dir != null) e.dir = -e.dir; }
    // touch player
    if (P.dead <= 0 && d < e.r + 11) hitPlayer();
    if (e.type === "eel" && P.dead <= 0) for (let i = 4; i < e.tail.length; i += 3) if (Math.hypot(P.x - e.tail[i][0], P.y - e.tail[i][1]) < 15) { hitPlayer(); break; }
  }
  // bullet vs enemy
  for (const b of bullets) {
    if (b.life <= 0) continue;
    for (const e of enemies) {
      if (e.dead || e.birth > 0 || (b.hits && b.hits.has(e))) continue;
      if (Math.abs(b.x - e.x) > e.r + 6 || Math.abs(b.y - e.y) > e.r + 6) {
        if (e.type === "eel") for (let i = 3; i < e.tail.length; i += 3) if (Math.hypot(b.x - e.tail[i][0], b.y - e.tail[i][1]) < 12) { b.life = 0; fx.burst(b.x, b.y, { n: 3, color: COL.eel, speed: 100, life: .2 }); break; }
        continue;
      }
      if (Math.hypot(b.x - e.x, b.y - e.y) < e.r + 5) {
        // overcharged shots punch through a couple of targets
        if (b.pierce > 0 && e.type !== "cell" && e.type !== "cloud") { b.pierce--; (b.hits || (b.hits = new Set())).add(e); }
        else b.life = 0;
        if (e.type === "shell") {
          // the shield covers the side facing you: shots from the front glance off
          let da = Math.atan2(b.y - e.y, b.x - e.x) - e.face; while (da > Math.PI) da -= TAU; while (da < -Math.PI) da += TAU;
          if (Math.abs(da) < 1.05) { fx.burst(b.x, b.y, { n: 3, color: "#ffffff", speed: 220, life: .2, shape: "spark" }); break; }
        }
        if (e.type === "cell") e.hitT = .12;
        if (--e.hp <= 0) killEnemy(e);
        else { fx.burst(b.x, b.y, { n: 4, color: COL[e.type], speed: 160, life: .3, shape: "spark" }); zap(e.x, e.y, 200, 70); }
        break;
      }
    }
  }
  updateWaves(dt);
  updateStrikes(dt);
  bullets = bullets.filter((b) => b.life > 0);
  enemies = enemies.filter((e) => !e.dead);
  // gems raise the multiplier
  for (const g of gems) {
    g.life -= dt;
    const dx = P.x - g.x, dy = P.y - g.y, d = Math.hypot(dx, dy) || 1;
    if (d < 150 && P.dead <= 0) { g.vx += dx / d * 1800 * dt; g.vy += dy / d * 1800 * dt; }
    g.vx *= 0.96; g.vy *= 0.96;
    g.x += g.vx * dt; g.y += g.vy * dt;
    if (d < 18 && P.dead <= 0) {
      g.life = 0; multXp++;
      const need = mult < 10 ? 10 : 25;
      if (multXp >= need) { multXp = 0; mult++; texts.add(P.x, P.y - 30, "×" + mult, { color: COL.gem, size: 20, life: .8 }); PA.sfx("power", { pitch: 1 + mult * .02 }); paint(); }
      else PA.sfx("blip", { pitch: 2 + multXp * .03, vol: .2 });
    }
  }
  gems = gems.filter((g) => g.life > 0);
  fx.update(dt); texts.update(dt);
  PA.music.intensity(Math.min(1, enemies.length / 40));
  PA.stat("gs-score", score.toLocaleString());
  ocBar.style.width = (ocT / OC_T * 100) + "%"; ocBox.classList.toggle("on", ocT > 0);
}
function updateWaves(dt) {
  for (const w of waves) {
    const r0 = w.r;
    w.r = Math.min(w.max, w.r + WAVE_SPEED * dt);
    // light the cells the ring front sweeps over
    const R = w.r, y0 = Math.max(0, Math.floor((w.y - R) / HR)), y1 = Math.min(HY - 1, Math.ceil((w.y + R) / HR) + 1);
    const x0 = Math.max(0, Math.floor((w.x - R) / HW)), x1 = Math.min(HX - 1, Math.ceil((w.x + R) / HW) + 1);
    for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) {
      const i = y * HX + x, d = Math.hypot(hexPos[i][0] - w.x, hexPos[i][1] - w.y);
      if (d > r0 - HS && d <= R + HS * .5) hexC[i] = Math.min(1.4, hexC[i] + dt * 9);
    }
    for (const e of enemies) {
      if (e.dead || e.birth > 0 || w.hit.has(e)) continue;
      const d = Math.hypot(e.x - w.x, e.y - w.y);
      if (d - e.r > w.r) continue;
      w.hit.add(e);
      if (e.type === "cloud") { e.hp -= 4; if (e.hp <= 0) killEnemy(e, false, w); }
      else if (e.type === "cell") { e.hp -= 3 + Math.min(4, w.depth); e.hitT = .25; texts.add(e.x + rand(-40, 40), e.y - 50, "-" + (3 + Math.min(4, w.depth)), { color: COL.cell, size: 14, life: .6 }); if (e.hp <= 0) killEnemy(e, false, w); }
      else killEnemy(e, false, w);
    }
    if (w.r >= w.max) w.life = (w.life == null ? 0.25 : w.life - dt);
  }
  waves = waves.filter((w) => w.life == null || w.life > 0);
}
function updateStrikes(dt) {
  for (const k of strikes) {
    if (k.t > 0) {
      k.t -= dt;
      if (k.t <= 0) {
        k.flash = 0.3;
        fx.burst(k.x, k.y, { n: 40, colors: ["#ffffff", "#bcd0ff", "#ffe68a"], speed: 420, life: .5, size: 2.4, shape: "spark" });
        zap(k.x, k.y, 900, 140); PA.sfx("explode", { pitch: .8, vol: .4 }); PA.shake(5, .25);
        if (P.dead <= 0 && Math.hypot(P.x - k.x, P.y - k.y) < 46) hitPlayer();
        boltHit(k);
        // lightning hits the storm too, but scores nothing
        for (const e of enemies) if (!e.dead && e.type !== "cloud" && e.type !== "cell" && e.birth <= 0 && Math.hypot(e.x - k.x, e.y - k.y) < 46 + e.r) killEnemy(e, true);
      }
    } else k.flash -= dt;
  }
  strikes = strikes.filter((k) => k.t > 0 || k.flash > 0);
}
function finish() {
  PA.sfx("gameover");
  PA.gameOver(score, { kicker: "All ships lost", title: score > 200000 ? "Storm legend!" : score > 50000 ? "Electric!" : "Run complete", stats: [["Time", Math.floor(t / 60) + "m " + Math.floor(t % 60) + "s"], ["Kills", kills.toLocaleString()], ["Best chain", bestChain], ["Final multiplier", "×" + mult], ["Supercells downed", cellsDowned]] });
  if (window.paXP) window.paXP.award("gridstorm", { score, kills });
}
 
 
/* ================= render ================= */
const ocBox = $("gs-oc"), ocBar = ocBox.querySelector("i");
const CLOUD_PUFFS = [[0, 0, 1], [-.68, .18, .7], [.68, .14, .72], [-.3, -.42, .64], [.34, -.4, .6]];
const CELL_PUFFS = [[0, 0, .78], [-.62, .2, .55], [.6, .22, .56], [-.25, -.55, .5], [.32, -.5, .5], [-.8, -.3, .4], [.82, -.24, .42], [0, .62, .48], [-.45, .6, .38], [.48, .58, .4]];
const camT = new THREE.Vector3();
let camInit = false, lastT = 0, ambT = 2, seaFlash = 0;
const bolts = [], flashes = [0, 1, 2].map(() => ({ x: 0, z: 0, w: 0 })), shipTrail = [];
const colCache = new Map();
function hc(c, k) {
  const key = c + "|" + k;
  let v = colCache.get(key);
  if (!v) { v = hdr(c, k); colCache.set(key, v); }
  return v;
}
const tmpC = new THREE.Color();
function clearScene() { bolts.length = 0; shipTrail.length = 0; camInit = false; for (const f of flashes) f.w = 0; }
function flash(x, z, k) {
  let f = flashes[0];
  for (const o of flashes) if (o.w < f.w) f = o;
  f.x = x; f.z = z; f.w = k;
  let l = boltL[0];
  for (const o of boltL) if (o.intensity < l.intensity) l = o;
  l.position.set(x, 3, z); l.intensity = 70 * k;
}
function makeBolt(ax, ay, az, bx, by, bz, life, amp) {
  const N = 14, pts = [], L = Math.hypot(bx - ax, by - ay, bz - az), A = (amp || 1) * Math.min(1.8, L * 0.07);
  for (let i = 0; i <= N; i++) {
    const f = i / N, j = i === 0 || i === N ? 0 : Math.sin(f * Math.PI);
    pts.push(ax + (bx - ax) * f + rand(-1, 1) * A * j, ay + (by - ay) * f + rand(-.3, .3) * A * j, az + (bz - az) * f + rand(-1, 1) * A * j);
  }
  const branches = [];
  for (let b = 0; b < 2; b++) {
    const i = 3 + ((Math.random() * 8) | 0), br = [pts[i * 3], pts[i * 3 + 1], pts[i * 3 + 2]], a = rand(0, TAU);
    for (let s = 1; s <= 4; s++) br.push(br[s * 3 - 3] + Math.cos(a) * L * .05 + rand(-.4, .4), br[s * 3 - 2] - L * .04, br[s * 3 - 1] + Math.sin(a) * L * .05 + rand(-.4, .4));
    branches.push(br);
  }
  return { pts, branches, life, max: life };
}
function boltHit(k) {
  const live = k.from && !k.from.dead;
  const sx = live ? WX(k.from.x) : WX(k.x) + rand(-4, 4), sy = live ? (k.from.type === "cell" ? 4.4 : 3.2) : 40, sz = live ? WZ(k.from.y) : WZ(k.y) - 16;
  bolts.push(makeBolt(sx, sy, sz, WX(k.x), 0.1, WZ(k.y), 0.32));
  flash(WX(k.x), WZ(k.y), 2.2);
  seaFlash = Math.max(seaFlash, 0.35);
}
// the floor height under a point, so shadows sit on raised cells
const floorY = (x, y) => Math.min(1.4, cellAt(x, y)) * 0.5 + 0.03;
 
function ringPts(x, z, r, y, n, a0, a1) {
  const p = [];
  for (let i = 0; i <= n; i++) { const a = a0 + (a1 - a0) * i / n; p.push(x + Math.cos(a) * r, y, z + Math.sin(a) * r); }
  return p;
}
const C3v = (c, k) => { tmpC.set(c); return [tmpC.r * k, tmpC.g * k, tmpC.b * k]; };
 
function drawEnemy(e, tt) {
  const X = WX(e.x), Z = WZ(e.y), r = e.r / S * (e.type === "cell" ? 1 : 1.4), c = COL[e.type];
  const bornT = e.type === "cell" ? 1.6 : e.type === "mine" ? .25 : .7;
  const born = e.birth > 0 ? clamp(1 - e.birth / bornT, 0, 1) : 1;
  const drop = (1 - born) * (1 - born) * 9;
  const sc = 0.35 + 0.65 * born;
  const fy = floorY(e.x, e.y);
  if (e.type !== "mine") I.shadow.add(X, fy, Z, 0, 0, 0, r * (e.type === "cell" ? 2.4 : 2.8), 1, r * (e.type === "cell" ? 2.4 : 2.8), tmpC.setScalar(born * (e.type === "cloud" || e.type === "cell" ? .55 : .8)));
  const y = 0.9 + drop + fy * 0.6;
  if (e.type !== "cloud" && e.type !== "cell") I.halo.add(X, fy + .02, Z, 0, 0, 0, r * 5, 1, r * 5, hc(c, .4 * born));
  if (e.type === "drift") {
    const p = 1 + Math.sin(tt * 5 + e.seed * 9) * .12, h = Math.atan2(e.vy, e.vx);
    I.bell.add(X, y, Z, 0, 0, 0, r * p * sc, r * 0.95 * sc, r * p * sc, hc(c, .5));
    I.core.add(X, y + .12, Z, 0, 0, 0, r * .26 * sc, r * .26 * sc, r * .26 * sc, hc(c, 2.2));
    // three tendrils trail behind the bell
    const col = C3v(c, 1.2 * born);
    for (let k = -1; k <= 1; k++) {
      const pts = [], ox = Math.cos(h + Math.PI / 2) * k * r * .45, oz = Math.sin(h + Math.PI / 2) * k * r * .45;
      for (let j = 0; j <= 4; j++) {
        const f = j / 4, w = Math.sin(tt * 7 + j + k * 2 + e.seed * 5) * r * .25;
        pts.push(X + ox - Math.cos(h) * f * r * 1.6 + Math.cos(h + Math.PI / 2) * w, y - .1 - f * .55, Z + oz - Math.sin(h) * f * r * 1.6 + Math.sin(h + Math.PI / 2) * w);
      }
      ribbon(pts.reverse(), col, .05);
    }
  } else if (e.type === "dart") {
    const a = e.mode === "aim" ? e.dashA : Math.atan2(e.vy, e.vx);
    const q = e.mode === "aim" ? Math.sin(tt * 45) * .05 : 0;
    if (e.mode === "aim" && e.birth <= 0 && P.dead <= 0) {
      // the line it's about to lunge along, brighter as it winds up
      const k = clamp(1 - e.timer / 1.1, 0, 1), col = C3v(c, .25 + k * 1.6);
      for (let d = r * 1.8; d < r + 230 / S; d += .7) ribbon([X + Math.cos(a) * d, .35 + fy, Z + Math.sin(a) * d, X + Math.cos(a) * (d + .32), .35 + fy, Z + Math.sin(a) * (d + .32)], col, .06, false);
    }
    I.needle.add(X + q, y, Z, 0, -a, 0, r * 1.5 * sc, r * .38 * sc, r * .5 * sc, hc(c, .9));
    I.spine.add(X + q, y + .05, Z, 0, -a, 0, r * 2.3 * sc, .07, .09, hc(c, e.mode === "dash" ? 5 : 2.6));
    if (e.mode === "dash") ribbon([X - Math.cos(a) * 2.2, y, Z - Math.sin(a) * 2.2, X, y, Z], C3v(c, 2), .22);
  } else if (e.type === "shell") {
    I.shellBody.add(X, y, Z, tt * .7, e.a, 0, r * .62 * sc, r * .62 * sc, r * .62 * sc, hc(c, .7));
    I.core.add(X, y + r * .45, Z, 0, 0, 0, r * .18, r * .18, r * .18, hc(c, 3.4));
    I.shield.add(X, y, Z, 0, Math.PI / 2 - e.face, 0, r * sc, r * .95 * sc, r * sc, hc(0xe8fff6, 1.9));
  } else if (e.type === "seeder") {
    const rot = e.a * .8;
    for (let k = 0; k < 3; k++) {
      const a = rot + k * TAU / 3;
      I.petal.add(X + Math.cos(a) * r * .55 * sc, y, Z + Math.sin(a) * r * .55 * sc, 0, -a, 0, r * .52 * sc, r * .22 * sc, r * .28 * sc, hc(c, .85));
    }
    I.core.add(X, y, Z, 0, 0, 0, r * .26, r * .26, r * .26, hc(c, 3.6));
  } else if (e.type === "mine") {
    const blink = e.life < 2 && Math.floor(tt * 10) % 2 ? .3 : 1, k = 2.4 * blink;
    I.mine.add(X, .55 + fy, Z, 0, e.a, 0, r * 1.35, r * .45, r * .45, hc(c, k));
    I.mine.add(X, .55 + fy, Z, 0, e.a + Math.PI / 2, 0, r * 1.35, r * .45, r * .45, hc(c, k));
    I.mine.add(X, .55 + fy, Z, 0, e.a + Math.PI / 4, 0, r * .8, r * 1.1, r * .8, hc(c, k * .7));
  } else if (e.type === "eel") {
    const a = e.dir || 0;
    I.eelHead.add(X, y, Z, 0, -a, 0, r * 1.15 * sc, r * .5 * sc, r * .62 * sc, hc(c, .9));
    for (const sd of [-1, 1]) I.core.add(X + Math.cos(a) * r * .6 - Math.sin(a) * sd * r * .3, y + r * .25, Z + Math.sin(a) * r * .6 + Math.cos(a) * sd * r * .3, 0, 0, 0, .08, .08, .08, hc(0xffffff, 4));
    const pts = [X, y, Z];
    for (let i = 2; i < e.tail.length; i += 2) pts.push(WX(e.tail[i][0] + rand(-3, 3)), y - .05, WZ(e.tail[i][1] + rand(-3, 3)));
    ribbon(pts.reverse(), C3v(c, 2.2), .1);
    for (let i = 3; i < e.tail.length - 1; i += 3) {
      const [x0, y0] = e.tail[i], [x2, y2] = e.tail[i + 1], fa = Math.atan2(y0 - y2, x0 - x2), l = 9 * (1 - i / e.tail.length) + 3;
      I.fin.add(WX(x0), y - .05, WZ(y0), 0, -fa, 0, .08, .06, l * 2 / S, hc(c, 3));
    }
  } else if (e.type === "cloud" || e.type === "cell") {
    const big = e.type === "cell", puffs = big ? CELL_PUFFS : CLOUD_PUFFS, p = 1 + Math.sin(e.pulse * 2) * .04;
    const cy = (big ? 4.6 : 3.2) + drop, rot = big ? e.pulse * .15 : 0, cr = Math.cos(rot), sr = Math.sin(rot);
    const hotNow = e.charge < .6 || e.hitT > 0;
    for (let i = 0; i < puffs.length; i++) {
      const [px, py, pr] = puffs[i], ox = (px * cr - py * sr) * r, oz = (px * sr + py * cr) * r;
      const hot = hotNow ? .35 + Math.random() * .65 : Math.random() < .02 ? .5 : 0;
      I.puff.add(X + ox, cy + Math.sin(e.pulse * 1.3 + i) * .12 - (pr - .7) * r * .2, Z + oz, 0, 0, 0, pr * r * p * sc, pr * r * p * .78 * sc, pr * r * p * sc, tmpC.setRGB(hot, big ? 1.6 : 1.2, 0));
    }
    // rain curtain under the cloud
    const col = C3v(big ? 0x9f8cff : 0x8fa6ff, big ? .5 : .32);
    for (let k = 0; k < (big ? 10 : 5); k++) {
      const a = k * 2.4 + e.seed * 7, rr = r * .6 * ((k * .37 + e.seed) % 1), x = X + Math.cos(a) * rr, z = Z + Math.sin(a) * rr;
      ribbon([x, cy - .3, z, x - .2, fy, z + .1], col, .03, false);
    }
    if (big && Math.random() < .2) {
      const a = rand(0, TAU), b = a + rand(1, 2.4);
      bolts.push(makeBolt(X + Math.cos(a) * r * .7, cy + .2, Z + Math.sin(a) * r * .7, X + Math.cos(b) * r * .7, cy + .1, Z + Math.sin(b) * r * .7, .1, .5));
    }
  }
}
 
function render(tt) {
  const dt = clamp(tt - lastT, 0, .05); lastT = tt;
  const w = view.w, h = view.h;
  const playing = P && PA.state !== "gate";
 
  /* camera */
  const tanV = Math.tan(THREE.MathUtils.degToRad(camera.fov) / 2), tanH = tanV * camera.aspect;
  const halfW = camD * tanH * S * .92, halfH = camD * tanV * S * .9;
  let tx = AW / 2, ty = AH / 2;
  if (playing) {
    tx = AW < halfW * 2 - 160 ? AW / 2 : clamp(P.x, halfW - 80, AW - halfW + 80);
    ty = AH < halfH * 2 - 160 ? AH / 2 : clamp(P.y + 40, halfH - 80, AH - halfH + 120);
  }
  const want = new THREE.Vector3(WX(tx), 0, WZ(ty));
  if (!camInit) { camT.copy(want); camInit = true; } else camT.lerp(want, Math.min(1, dt * 5));
  const sh = PA.shakeOffset();
  if (playing) camera.position.copy(camT).addScaledVector(CAM_TILT, camD);
  else {
    // title screen: a slow drift over the whole arena
    const a = Math.sin(tt * .12) * .5, d = camD * 1.25;
    camera.position.set(camT.x + Math.sin(a) * d * .55, camT.y + d * .8, camT.z + Math.cos(a) * d * .55);
  }
  camera.position.x += sh.x * .03; camera.position.z += sh.y * .03;
  camera.lookAt(camT);
  camera.updateMatrixWorld();
 
  /* world */
  aCharge.array.set(hexC); aCharge.needsUpdate = true;
  hexMat.uniforms.time.value = tt;
  hexMat.uniforms.uBomb.value = bombFlash;
  for (let i = 0; i < 3; i++) { const f = flashes[i]; f.w *= Math.exp(-dt * 8); hexMat.uniforms.uFlash.value[i].set(f.x, f.z, 0, f.w); }
  for (const l of boltL) l.intensity *= Math.exp(-dt * 10);
  fenceMat.uniforms.time.value = tt; fenceMat.uniforms.hot.value = bombFlash;
  rainMat.uniforms.time.value = tt; rainMat.uniforms.origin.value.copy(camT);
  puffMat.uniforms.time.value = tt;
  // lightning in the storm below the arena
  ambT -= dt;
  if (ambT <= 0) {
    ambT = rand(1.2, 3.6);
    const a = rand(0, TAU), rr = rand(55, 110), x = Math.cos(a) * rr, z = Math.sin(a) * rr - 20;
    bolts.push(makeBolt(x + rand(-6, 6), 18, z + rand(-6, 6), x, -16, z, .28, 1.4));
    seaFlash = 1; seaMat.uniforms.flashAt.value.set(x, z);
    if (Math.random() < .5) PA.sfx("boom", { pitch: .3 + Math.random() * .2, vol: .05 });
  }
  seaFlash *= Math.exp(-dt * 6);
  seaMat.uniforms.time.value = tt; seaMat.uniforms.flash.value = seaFlash * (.7 + Math.random() * .3);
 
  tv = 0;
  if (playing) {
    hexMat.uniforms.uPlayer.value.set(WX(P.x), 0, WZ(P.y));
    /* the ship */
    const shown = P.dead <= 0 && alive && !(P.inv > 0 && dashT <= 0 && Math.floor(tt * 14) % 2);
    ship.visible = shown; shipShadow.visible = P.dead <= 0 && alive;
    const X = WX(P.x), Z = WZ(P.y), fy = floorY(P.x, P.y);
    ship.position.set(X, .85 + fy * .6 + Math.sin(tt * 3) * .06, Z);
    ship.rotation.set(P.vy / 420 * .28, 0, -P.vx / 420 * .28, "YXZ");
    ship.userData.gun.rotation.y = -(P.aim != null ? P.aim : P.a);
    ship.userData.rotor.rotation.y = tt * 9;
    const oc = ship.userData.oc;
    oc.visible = ocT > 0; oc.scale.setScalar(1 + Math.sin(tt * 10) * .06); oc.material.opacity = Math.min(1, ocT / OC_T * 1.5);
    shipShadow.position.set(X, fy, Z);
    shipL.position.set(X, 1.6 + fy, Z); shipL.intensity = P.dead > 0 ? 0 : 10 + (ocT > 0 ? 8 : 0);
    if (shown && (dashT > 0 || Math.hypot(P.vx, P.vy) > 60)) shipTrail.push([X, ship.position.y - .1, Z, tt]);
    while (shipTrail.length && tt - shipTrail[0][3] > (dashT > 0 ? .35 : .22)) shipTrail.shift();
    if (shipTrail.length > 1) ribbon(shipTrail.flatMap((p) => [p[0], p[1], p[2]]), dashT > 0 ? [2.6, 2.2, 1.2] : [.5, 1.3, 1.8], dashT > 0 ? .45 : .18);
 
    /* motes, bullets */
    for (const g of gems) I.gem.add(WX(g.x), .7 + Math.sin(tt * 4 + g.x) * .12 + floorY(g.x, g.y) * .6, WZ(g.y), 0, tt * 3, 0, .2, .32, .2, hc(0x7dffb0, 2.8 * Math.min(1, g.life)));
    for (const b of bullets) {
      const a = Math.atan2(b.vy, b.vx);
      I.bullet.add(WX(b.x), .85, WZ(b.y), 0, -a, 0, b.oc ? 1.6 : 1.2, b.oc ? .12 : .08, b.oc ? .12 : .08, b.oc ? hc(0x9fdcff, 3.2) : hc(0xffc94d, 2.4));
    }
    /* shockwaves */
    for (const wv of waves) {
      const k = wv.life == null ? 1 - (wv.r / wv.max) * .5 : Math.max(0, wv.life / .25) * .5;
      const R = wv.r / S, x = WX(wv.x), z = WZ(wv.y), n = Math.max(24, Math.min(90, (R * 5) | 0));
      const pts = ringPts(x, z, R, .4, n, 0, TAU);
      ribbon(pts, C3v(wv.c, 2.4 * k), .09, false);
      ribbon(ringPts(x, z, R, .3, n, 0, TAU), C3v(wv.c, .35 * k), .55, false);
    }
    /* strikes */
    for (const k of strikes) {
      if (k.t <= 0) continue;
      const q = 1 - k.t / 1.05, x = WX(k.x), z = WZ(k.y), R = 46 / S, y = floorY(k.x, k.y) + .05;
      const col = C3v(0xfff0aa, .5 + q * 1.8);
      for (let d = 0; d < 16; d++) { const a0 = d * TAU / 16 + tt * 1.2; ribbon(ringPts(x, z, R, y, 3, a0, a0 + TAU / 32), col, .07, false); }
      I.disc.add(x, y - .01, z, 0, 0, 0, R * Math.max(.05, q), 1, R * Math.max(.05, q), tmpC.setRGB(q * .5, q * .45, q * .25));
    }
    /* enemies */
    for (const e of enemies) if (!e.dead) drawEnemy(e, tt);
  } else {
    ship.visible = false; shipShadow.visible = false; shipL.intensity = 0;
  }
  /* bolts */
  for (let i = bolts.length - 1; i >= 0; i--) {
    const b = bolts[i];
    b.life -= dt;
    if (b.life <= 0) { bolts.splice(i, 1); continue; }
    const a = b.life / b.max, f = a * (.7 + Math.random() * .3);
    ribbon(b.pts, [3.4 * f, 3.6 * f, 4.4 * f], .12, false);
    ribbon(b.pts, [.4 * f, .5 * f, 1.2 * f], .7, false);
    for (const br of b.branches) ribbon(br, [2 * f, 2.2 * f, 3 * f], .06);
  }
  for (const k in I) I[k].flush();
  tGeo.setDrawRange(0, tv);
  tGeo.attributes.position.needsUpdate = true; tGeo.attributes.color.needsUpdate = true;
  post.comp.uniforms.hurt.value = P && P.dead > 1.4 ? (P.dead - 1.4) * 1.2 : 0;
  post.comp.uniforms.chroma.value = .1 + (dashT > 0 ? 1.2 : 0) + bombFlash * 2;
  post.render(scene, camera, tt);
 
  /* overlay */
  ctx.setTransform(view.dpr, 0, 0, view.dpr, 0, 0);
  ctx.clearRect(0, 0, w, h);
  if (!playing) return;
  ctx.save();
  ctx.textAlign = "center"; ctx.textBaseline = "middle";
  for (const t of texts.list) {
    const s = toScreen(t.x, t.y, 1.4), k = t.life / t.max, pop = k > .85 ? 1 + (k - .85) * 3 : 1;
    ctx.globalAlpha = Math.min(1, k * 2);
    ctx.font = "700 " + Math.round(t.size * pop * (w < 560 ? .85 : 1)) + "px Manrope, system-ui, sans-serif";
    ctx.shadowColor = t.color; ctx.shadowBlur = 12; ctx.fillStyle = t.color;
    ctx.fillText(t.text, s.x, s.y);
  }
  ctx.restore();
  // dash cooldown pip under the ship
  if (P.dead <= 0 && alive && dashCd > 0) {
    const s = toScreen(P.x, P.y, .2);
    ctx.strokeStyle = "rgba(255,230,138,.7)"; ctx.lineWidth = 2.5; ctx.lineCap = "round";
    ctx.beginPath(); ctx.arc(s.x, s.y + 26, 7, -Math.PI / 2, -Math.PI / 2 + TAU * (1 - dashCd / DASH_CD)); ctx.stroke();
  }
  // the supercell's health
  if (boss && !boss.dead) {
    const bw = Math.min(360, w * .6), bx = w / 2 - bw / 2, by = w < 560 ? 128 : 70, k = clamp(boss.hp / boss.max, 0, 1);
    ctx.font = "700 11px 'JetBrains Mono', ui-monospace, monospace"; ctx.textAlign = "center"; ctx.fillStyle = "#e4dcff";
    ctx.fillText("SUPERCELL", w / 2, by - 8);
    ctx.fillStyle = "rgba(255,255,255,.12)"; ctx.fillRect(bx, by, bw, 6);
    const gr = ctx.createLinearGradient(bx, 0, bx + bw, 0); gr.addColorStop(0, "#7a6cff"); gr.addColorStop(1, "#e8d8ff");
    ctx.fillStyle = gr; ctx.fillRect(bx, by, bw * k, 6);
  }
  // aim reticle
  if (mouse.seen && PA.state === "play") {
    ctx.strokeStyle = ocT > 0 ? "rgba(207,234,255,.9)" : "rgba(255,230,138,.8)"; ctx.lineWidth = 1.5;
    ctx.beginPath(); ctx.arc(mouse.x, mouse.y, 9, 0, TAU); ctx.moveTo(mouse.x - 14, mouse.y); ctx.lineTo(mouse.x - 5, mouse.y); ctx.moveTo(mouse.x + 5, mouse.y); ctx.lineTo(mouse.x + 14, mouse.y); ctx.stroke();
  }
}
 
/* ================= boot ================= */
const view = PA.canvas($("fx"), { onResize: () => resize3d() });
const ctx = view.ctx;
addEventListener("resize", resize3d);
resize3d();
// distant lightning flickers across the floor behind the start screen
setInterval(() => { if (PA.state !== "play") zap(rand(0, AW), rand(0, AH), rand(250, 700), rand(80, 220)); }, 600);
PA.onStart(reset);
PA.loop(update, render);
window.__gs = {
  get state() { return { score, lives, enemies: enemies && enemies.length, t, bestChain, waves: waves && waves.length, px: P && P.x, py: P && P.y, lit: hexC.reduce((m, c) => Math.max(m, c), 0), oc: ocT, dash: dashT, boss: boss ? boss.hp : null, cells: cellsDowned, mult }; },
  cheat() { lives = 99; }, god() { P.inv = 1e9; }, warp(s) { t = s; }, spawn(type) { const e = spawn(type); if (type === "cloud") clouds.push(e); return e.type; },
  boss() { nextBoss = t; spawnT = 0; }, dash, charge() { zap(P.x, P.y, 2000, 200); }, aim(x, y) { mouse.seen = true; const s = toScreen(x, y, .8); mouse.x = s.x; mouse.y = s.y; }, fire(v) { mouse.down = v; mouse.seen = true; },
  get player() { return P; }, get bossE() { return boss; },
  hurtBoss(n) { if (boss) { boss.hp -= n; if (boss.hp <= 0) killEnemy(boss); } }
};
})();
</script>
</body></html>