Source code

Skystack

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

Play it

games/play/skystack.html · 833 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>Skystack — PromptArcade</title>
<style>
html,body{margin:0;height:100%;overflow:hidden;background:#5aa9e6;font-family:Manrope,system-ui,sans-serif;touch-action:none;-webkit-user-select:none;user-select:none}
#game{position:fixed;inset:0}
#game canvas{display:block;width:100%;height:100%}
#sk-panel{position:fixed;top:60px;left:50%;transform:translateX(-50%);z-index:30;pointer-events:none;min-width:132px;padding:8px 18px 9px;border-radius:14px;text-align:center;
  background:linear-gradient(#20242c,#121419);border:2px solid #474c57;box-shadow:0 8px 24px rgba(0,0,0,.35),inset 0 1px 0 rgba(255,255,255,.08)}
#sk-panel small{display:block;font:700 10px 'JetBrains Mono',monospace;letter-spacing:.18em;color:#9aa3b2;text-transform:uppercase}
#sk-score{display:block;font:800 clamp(34px,7vw,52px)/1.05 'JetBrains Mono',monospace;color:#ffb347;text-shadow:0 0 12px rgba(255,170,60,.65)}
#sk-panel span{display:block;font:700 9px 'JetBrains Mono',monospace;letter-spacing:.3em;color:#6f7685}
#sk-combo{position:fixed;top:168px;left:0;right:0;text-align:center;z-index:30;pointer-events:none;font:800 15px 'JetBrains Mono',monospace;letter-spacing:.16em;color:#fff;text-shadow:0 2px 10px rgba(0,0,0,.45);opacity:0;transition:opacity .3s}
#sk-hint{position:fixed;bottom:40px;left:0;right:0;text-align:center;z-index:30;pointer-events:none;font:700 14px Manrope,sans-serif;color:#fff;text-shadow:0 1px 6px rgba(0,0,0,.5);transition:opacity .5s}
</style></head><body>
<div id="game" aria-label="Skystack: a skyscraper rising over a city"></div>
<div id="sk-panel"><small id="sk-dist">Brick row</small><b id="sk-score">0</b><span>FLOOR</span></div>
<div id="sk-combo"></div><div id="sk-hint">Tap, click or press Space to lower the floor</div>
<script>
window.paConfig = {
  slug: "skystack", title: "Skystack", native: true, music: "lofi", unit: "floors",
  controls: [["Space / click / tap", "Lower the floor off the crane"], ["Flush drops", "Three in a row brace the tower: no sway for four floors"], ["Hot streak", "From the third flush in a row, each flush floor grows back a little"], ["Sky lobby", "Every tenth floor the next one comes wider"], ["Wind", "From floor 5 the tower sways: drop where the top is, not where it was"]]
};
</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";
// A skyscraper built one floor at a time. A crane swings each floor in on a cable, alternating sides;
// whatever overhangs the floor below is sheared off. The building climbs through five districts, from
// brick walk-ups to a glass spire, while the day turns to night around it. Wind sways the tower, flush
// drops brace it (and a hot streak of them grows the floor back), and every tenth floor is a wide sky lobby.
// A tower crane climbs with the building, slewing its jib to follow each floor in.
const $ = (id) => document.getElementById(id);
const PA = window.PA;
/* ---------------- 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;
}
 
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMappingExposure = 1.25;
post.comp.uniforms.strength.value = 0.45;
post.comp.uniforms.grain.value = 0.012;
scene.background = null;
scene.fog = new THREE.Fog(0xcfeaff, 45, 160);
const cam = camera;
cam.fov = 32; cam.near = 0.5; cam.far = 900;
const hemi = new THREE.HemisphereLight(0xffffff, 0x445566, 0.9);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffffff, 1.6);
sun.position.set(10, 30, 6); sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
Object.assign(sun.shadow.camera, { left: -12, right: 12, top: 12, bottom: -12, near: 1, far: 80 });
scene.add(sun); scene.add(sun.target);
 
const H = 1, START = 6, SPEED0 = 7.5, PERFECT = 0.14, BASE_H = 10;
let stack = [], debris = [], sparks = [], moving = null, windT = 0, windX = 0, windZ = 0, warned = false, axis = "x", dir = 1, speed = SPEED0, score = 0;
let kick = 0;
let streak = 0, bestStreak = 0, flush = 0, braced = 0, braceK = 0, over = false, camY = 0, camD = 30, running = false, clock = 0, night = 0, skyF = 0;
 
/* ---------- districts: each ten floors gets its own facade ---------- */
const DISTRICTS = [
  { name: "Brick row", style: "brick", wall: "#8e4a36", trim: "#eadfce", glass: "#26323d", lit: "#ffd38a", roof: "#5b5550" },
  { name: "Concrete block", style: "ribbon", wall: "#a3a7ab", trim: "#d3d5d8", glass: "#30485a", lit: "#fff1c4", roof: "#6c7075" },
  { name: "Glass tower", style: "curtain", wall: "#4d8ea6", trim: "#d6edf4", glass: "#4d8ea6", lit: "#eaf7ff", roof: "#3f5560" },
  { name: "Deco heights", style: "deco", wall: "#dccba4", trim: "#c49a3c", glass: "#2a313d", lit: "#ffcf7a", roof: "#a8946a" },
  { name: "The spire", style: "spire", wall: "#1c2331", trim: "#7fe0ff", glass: "#121824", lit: "#a6ecff", roof: "#121824" }
];
const LOBBY = { name: "Lobby", style: "lobby", wall: "#7d8288", trim: "#d9dcdf", glass: "#2b3c48", lit: "#fff0c8", roof: "#5d6166" };
function districtOf(i) { return i <= 0 ? LOBBY : DISTRICTS[Math.min(DISTRICTS.length - 1, Math.floor((i - 1) / 10))]; }
// one facade tile is 2 world units wide and one floor tall: a colour map plus a map of the windows that light up at night
function paintFacade(D) {
  const W = 256, Hh = 128, c = document.createElement("canvas"), e = document.createElement("canvas");
  c.width = e.width = W; c.height = e.height = Hh;
  const g = c.getContext("2d"), q = e.getContext("2d");
  q.fillStyle = "#000"; q.fillRect(0, 0, W, Hh);
  g.fillStyle = D.wall; g.fillRect(0, 0, W, Hh);
  const win = (x, y, w, h, frame) => {
    if (frame) { g.fillStyle = D.trim; g.fillRect(x - frame, y - frame, w + frame * 2, h + frame * 2); }
    const gr = g.createLinearGradient(x, y, x + w, y + h); gr.addColorStop(0, D.glass); gr.addColorStop(1, shade(D.glass, 26));
    g.fillStyle = gr; g.fillRect(x, y, w, h);
    g.fillStyle = "rgba(255,255,255,.12)"; g.fillRect(x, y, w * .35, h);
    if (Math.random() < .45) { q.fillStyle = D.lit; q.globalAlpha = .55 + Math.random() * .45; q.fillRect(x, y, w, h); q.globalAlpha = 1; }
  };
  if (D.style === "brick") {
    g.strokeStyle = "rgba(40,18,12,.35)"; g.lineWidth = 1.5;
    for (let y = 4; y < Hh; y += 9) { g.beginPath(); g.moveTo(0, y); g.lineTo(W, y); g.stroke(); for (let x = (y / 9 & 1) * 11; x < W; x += 22) { g.beginPath(); g.moveTo(x, y); g.lineTo(x, y + 9); g.stroke(); } }
    for (const x of [26, 154]) { win(x, 34, 76, 62, 6); g.fillStyle = D.trim; g.fillRect(x - 10, 100, 96, 8); }
  } else if (D.style === "ribbon") {
    g.fillStyle = D.trim; g.fillRect(0, 0, W, 18); g.fillRect(0, Hh - 18, W, 18);
    for (let x = 0; x < W; x += 64) win(x + 3, 34, 58, 60, 0);
  } else if (D.style === "curtain") {
    for (let x = 0; x < W; x += 32) win(x + 2, 6, 28, Hh - 16, 0);
    g.fillStyle = D.trim; for (let x = 0; x < W; x += 32) g.fillRect(x, 0, 2, Hh); g.fillRect(0, Hh - 10, W, 10); g.fillRect(0, 44, W, 2);
  } else if (D.style === "deco") {
    for (let x = 0; x < W; x += 64) { g.fillStyle = D.trim; g.fillRect(x, 0, 8, Hh); win(x + 22, 18, 26, 92, 3); }
    g.fillStyle = shade(D.wall, -20); g.fillRect(0, 0, W, 8); g.fillStyle = D.trim; g.fillRect(0, 8, W, 3);
  } else if (D.style === "spire") {
    for (let x = 0; x < W; x += 21) for (let y = 12; y < Hh - 12; y += 36) win(x + 3, y, 15, 28, 0);
    g.fillStyle = D.trim; g.fillRect(0, 0, W, 3); g.fillRect(0, Hh - 3, W, 3);
    q.fillStyle = D.trim; q.fillRect(0, 0, W, 3); q.fillRect(0, Hh - 3, W, 3);
  } else {
    // lobby: tall glass with doors, read over ten floors of podium
    g.fillStyle = D.trim; g.fillRect(0, 0, W, Hh);
    for (let x = 0; x < W; x += 64) win(x + 6, 10, 52, Hh - 20, 0);
  }
  const map = new THREE.CanvasTexture(c), em = new THREE.CanvasTexture(e);
  for (const t of [map, em]) { t.wrapS = t.wrapT = THREE.RepeatWrapping; t.anisotropy = 4; }
  map.colorSpace = THREE.SRGBColorSpace; em.colorSpace = THREE.SRGBColorSpace;
  return { map, em };
}
function shade(hex, n) { const v = parseInt(hex.slice(1), 16); const f = (s) => Math.max(0, Math.min(255, ((v >> s) & 255) + n)); return `rgb(${f(16)},${f(8)},${f(0)})`; }
for (const D of [LOBBY, ...DISTRICTS]) Object.assign(D, paintFacade(D));
 
const geo = new THREE.BoxGeometry(1, 1, 1);
const sideMats = new Set();
// box faces: +x, -x, +y, -y, +z, -z. Sides get the facade at a repeat that matches their width.
function makeMats(D, w, d, h) {
  const side = (len) => {
    const map = D.map.clone(), em = D.em.clone();
    map.repeat.set(len / 2, h); em.repeat.set(len / 2, h);
    map.needsUpdate = em.needsUpdate = true;
    const m = new THREE.MeshStandardMaterial({ map, emissiveMap: em, emissive: 0xffffff, emissiveIntensity: night * 1.2, roughness: .62, metalness: D.style === "curtain" || D.style === "spire" ? .35 : .05 });
    sideMats.add(m); return m;
  };
  const roof = new THREE.MeshStandardMaterial({ color: D.roof, roughness: .85 });
  return [side(d), side(d), roof, roof, side(w), side(w)];
}
function resizeMats(s) {
  const reps = [s.d, s.d, 0, 0, s.w, s.w];
  s.m.material.forEach((m, k) => { if (m.map) { m.map.repeat.x = reps[k] / 2; m.emissiveMap.repeat.x = reps[k] / 2; } });
}
function disposeMesh(m) {
  for (const mat of new Set(m.material)) { if (mat.map) { mat.map.dispose(); mat.emissiveMap.dispose(); sideMats.delete(mat); } mat.dispose(); }
}
function slab(w, d, x, y, z, i, h = H) {
  const D = districtOf(i);
  const m = new THREE.Mesh(geo, makeMats(D, w, d, h / H));
  m.scale.set(w, h, d); m.position.set(x, y, z);
  m.castShadow = true; m.receiveShadow = true;
  scene.add(m);
  return { m, w, d, x, z, y };
}
 
/* ---------- the city below and the sky around ---------- */
const GY = -BASE_H + .5;
// streets every 20 units; the tower's own block is a plaza
const streetTex = canvasTex(512, 512, (g, w) => {
  g.fillStyle = "#3a4046"; g.fillRect(0, 0, w, w);
  for (let i = 0; i < 2500; i++) { g.fillStyle = `rgba(${Math.random() < .5 ? "255,255,255" : "0,0,0"},${Math.random() * .05})`; g.fillRect(Math.random() * w, Math.random() * w, 3, 3); }
  // one block: pavement, kerb, then half a road on each side
  const R = w * 0.1, K = w * 0.02;
  g.fillStyle = "#24282d"; g.fillRect(0, 0, w, R); g.fillRect(0, w - R, w, R); g.fillRect(0, 0, R, w); g.fillRect(w - R, 0, R, w);
  g.fillStyle = "#8d9196"; g.fillRect(R, R, w - 2 * R, K); g.fillRect(R, w - R - K, w - 2 * R, K); g.fillRect(R, R, K, w - 2 * R); g.fillRect(w - R - K, R, K, w - 2 * R);
  g.fillStyle = "#e9d9a0";
  for (let x = 0; x < w; x += 28) { g.fillRect(x, 0, 14, 2); g.fillRect(x, w - 2, 14, 2); g.fillRect(0, x, 2, 14); g.fillRect(w - 2, x, 2, 14); }
  g.fillStyle = "#4a5a48"; g.fillRect(R + K + 6, R + K + 6, w - 2 * (R + K + 6), w - 2 * (R + K + 6));
}, { repeat: true });
streetTex.repeat.set(30, 30);
streetTex.offset.set(0.5, 0.5);
const ground = new THREE.Mesh(new THREE.PlaneGeometry(600, 600), new THREE.MeshStandardMaterial({ map: streetTex, roughness: .95 }));
ground.rotation.x = -Math.PI / 2; ground.position.y = GY; ground.receiveShadow = true; scene.add(ground);
// city blocks: instanced towers with a window texture that lights up at night
const winTex = canvasTex(128, 256, (g, w, h) => {
  g.fillStyle = "#000"; g.fillRect(0, 0, w, h);
  for (let y = 6; y < h - 4; y += 12) for (let x = 6; x < w - 4; x += 14) if (Math.random() < .5) { g.fillStyle = `rgba(255,${200 + Math.random() * 40},${130 + Math.random() * 80},${.5 + Math.random() * .5})`; g.fillRect(x, y, 8, 7); }
}, { repeat: true });
const wallTex = canvasTex(128, 256, (g, w, h) => {
  g.fillStyle = "#fff"; g.fillRect(0, 0, w, h);
  for (let y = 6; y < h - 4; y += 12) for (let x = 6; x < w - 4; x += 14) { g.fillStyle = "rgba(40,60,80,.55)"; g.fillRect(x, y, 8, 7); }
  g.fillStyle = "rgba(0,0,0,.08)"; for (let y = 0; y < h; y += 12) g.fillRect(0, y, w, 2);
}, { repeat: true });
const cityWall = new THREE.MeshStandardMaterial({ color: 0xffffff, map: wallTex, emissive: 0xffffff, emissiveMap: winTex, emissiveIntensity: 0, roughness: .8, metalness: .1 });
const cityRoof = new THREE.MeshStandardMaterial({ color: 0x5b6168, roughness: .9 });
const blocks = [];
// keep the view onto the podium clear: anything between the camera and the tower stays below the
// sight line from the camera to the upper podium, so no neighbour's roof hides where the first floors land
const CAM_AZ = Math.PI / 4, EL_LOW = .42, EL_START = .62;
function clearH(x, z, w, d) {
  const hd = Math.hypot(w, d) / 2;
  let cap = Infinity;
  for (const az of [CAM_AZ - .2, CAM_AZ, CAM_AZ + .2]) {
    const ux = Math.sin(az), uz = Math.cos(az);
    const t = x * ux + z * uz, lat = Math.abs(x * uz - z * ux);
    if (t <= 0 || lat > START / 2 + hd + 2) continue;
    // the sight line rises from the podium (aimed a few floors below its top) at the shallowest camera angle
    cap = Math.min(cap, (-3 + Math.max(0, t - hd) * Math.tan(EL_LOW) - .6) - GY);
  }
  return Math.max(1.2, cap);
}
for (let gx = -6; gx <= 6; gx++) for (let gz = -6; gz <= 6; gz++) {
  if (Math.abs(gx) <= 0 && Math.abs(gz) <= 0) continue;
  const cx = gx * 20, cz = gz * 20, r = Math.hypot(cx, cz);
  if (r > 125) continue;
  // two to four buildings to a block, taller further out so the tower always reads as the star
  const n = 2 + ((Math.random() * 3) | 0), slots = [[-4, -4], [4, -4], [-4, 4], [4, 4]].sort(() => Math.random() - .5);
  for (let k = 0; k < n; k++) {
    const w = 5 + Math.random() * 2.5, d = 5 + Math.random() * 2.5, bx = cx + slots[k][0], bz = cz + slots[k][1];
    let h = 2 + Math.random() * (r < 30 ? 5 : r < 60 ? 10 : 18) + (Math.random() < .08 ? 14 : 0);
    h = Math.min(h, clearH(bx, bz, w, d));
    blocks.push([bx, bz, w, d, h]);
  }
}
const city = new THREE.InstancedMesh(geo, [cityWall, cityWall, cityRoof, cityRoof, cityWall, cityWall], blocks.length);
{
  const o = new THREE.Object3D(), col = new THREE.Color();
  blocks.forEach(([x, z, w, d, h], i) => {
    o.position.set(x, GY + h / 2, z); o.scale.set(w, h, d); o.updateMatrix();
    city.setMatrixAt(i, o.matrix);
    col.setHSL(.55 + Math.random() * .12, .06 + Math.random() * .12, .5 + Math.random() * .3); city.setColorAt(i, col);
  });
  city.castShadow = false; city.receiveShadow = true; scene.add(city);
}
// traffic: head and tail lights streaming along the streets
const CARS = 900;
const carGeo = new THREE.BufferGeometry();
{
  const p = new Float32Array(CARS * 3), a = new Float32Array(CARS * 4);
  for (let i = 0; i < CARS; i++) {
    const alongX = Math.random() < .5, line = (((Math.random() * 13) | 0) - 6) * 20 + 10, side = Math.random() < .5 ? 1 : -1;
    p.set([0, GY + .25, 0], i * 3);
    a.set([alongX ? 1 : 0, line + side * 1.1, side * (5 + Math.random() * 5), Math.random() * 240], i * 4);
  }
  carGeo.setAttribute("position", new THREE.BufferAttribute(p, 3)); carGeo.setAttribute("car", new THREE.BufferAttribute(a, 4));
}
const carMat = new THREE.ShaderMaterial({
  transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
  uniforms: { time: { value: 0 }, night: { value: 0 }, scale: { value: 600 } },
  vertexShader: `uniform float time, scale; attribute vec4 car; varying vec3 vC;
    void main(){
      float s = mod(car.w + time * car.z, 240.0) - 120.0;
      vec3 p = position;
      if (car.x > 0.5) { p.x = s; p.z = car.y; } else { p.z = s; p.x = car.y; }
      // cars heading toward the camera show headlights, the others tail lights
      vC = car.z > 0.0 ? vec3(1.0, 0.95, 0.8) : vec3(1.0, 0.18, 0.12);
      vec4 mv = modelViewMatrix * vec4(p, 1.0);
      gl_PointSize = max(1.0, 0.5 * scale / -mv.z);
      gl_Position = projectionMatrix * mv;
    }`,
  fragmentShader: "uniform float night; varying vec3 vC; void main(){ float d = length(gl_PointCoord - 0.5); float a = smoothstep(0.5, 0.1, d); gl_FragColor = vec4(vC * a * (0.25 + night * 2.2), 1.0); }"
});
const cars = new THREE.Points(carGeo, carMat); cars.frustumCulled = false; scene.add(cars);
// street lamps: a warm glow on every corner after dark
const lampPts = [];
for (let gx = -6; gx <= 6; gx++) for (let gz = -6; gz <= 6; gz++) { const x = gx * 20 + 10, z = gz * 20 + 10; if (Math.hypot(x, z) < 130) lampPts.push(x + 2.3, GY + .8, z + 2.3, x - 2.3, GY + .8, z - 2.3); }
const lampGeo = new THREE.BufferGeometry(); lampGeo.setAttribute("position", new THREE.Float32BufferAttribute(lampPts, 3));
const lampMat = new THREE.PointsMaterial({ color: 0xffc070, size: 1.6, map: glowTex, transparent: true, opacity: 0, depthWrite: false, blending: THREE.AdditiveBlending });
scene.add(new THREE.Points(lampGeo, lampMat));
const cityLights = [];
for (const [x, z, w, d, h] of blocks) for (let k = 0; k < h * .5; k++) { const side = Math.random() < .5, f = Math.random() < .5 ? -1 : 1; cityLights.push(side ? x + f * (w / 2 + .05) : x + (Math.random() - .5) * w, GY + Math.random() * h, side ? z + (Math.random() - .5) * d : z + f * (d / 2 + .05)); }
const lightsGeo = new THREE.BufferGeometry(); lightsGeo.setAttribute("position", new THREE.Float32BufferAttribute(cityLights, 3));
const lightsMat = new THREE.PointsMaterial({ color: hdr(0xffd28a, 2), size: .32, transparent: true, opacity: 0, depthWrite: false });
scene.add(new THREE.Points(lightsGeo, lightsMat));
// the sky: a dome with the sun, a glow round it, and stars that come out as you climb into the night
const skyMat = new THREE.ShaderMaterial({
  side: THREE.BackSide, depthWrite: false, fog: false,
  uniforms: { top: { value: new THREE.Color() }, bot: { value: new THREE.Color() }, sunCol: { value: new THREE.Color() }, sunDir: { value: new THREE.Vector3(0.4, 0.3, -0.85).normalize() }, night: { value: 0 }, time: { value: 0 } },
  vertexShader: "varying vec3 vD; void main(){ vD = normalize(position); vec4 p = projectionMatrix * modelViewMatrix * vec4(position, 1.0); gl_Position = p.xyww; }",
  fragmentShader: `uniform vec3 top, bot, sunCol, sunDir; uniform float night, time; varying vec3 vD;
    float h(vec3 p){ return fract(sin(dot(p, vec3(12.9898, 78.233, 37.719))) * 43758.5453); }
    void main(){
      float y = vD.y;
      vec3 col = mix(bot, top, smoothstep(-0.05, 0.55, y));
      float sd = max(0.0, dot(vD, sunDir));
      col += sunCol * (pow(sd, 8.0) * 0.35 + pow(sd, 90.0) * 1.2) * (1.0 - night * 0.6);
      col += sunCol * smoothstep(0.9993, 0.9997, sd) * 6.0 * (1.0 - night);
      // stars
      vec3 q = floor(vD * 260.0);
      float st = step(0.9965, h(q)) * smoothstep(0.0, 0.25, y);
      col += vec3(0.85, 0.9, 1.0) * st * night * (0.6 + 0.4 * sin(time * 3.0 + h(q + 1.0) * 30.0)) * 1.6;
      // a faint band of milky way at night
      float band = exp(-pow(dot(vD, normalize(vec3(0.3, 0.6, 0.74))) * 4.0, 2.0));
      col += vec3(0.35, 0.3, 0.6) * band * night * 0.12 * smoothstep(0.0, 0.4, y);
      gl_FragColor = vec4(col, 1.0);
    }`
});
const sky = new THREE.Mesh(new THREE.SphereGeometry(800, 32, 16), skyMat);
sky.renderOrder = -1;
scene.add(sky);
// soft clouds you climb through on the way up
const cloudTex = (() => {
  const c = document.createElement("canvas"); c.width = c.height = 128; const g = c.getContext("2d");
  for (let k = 0; k < 7; k++) { const x = 30 + Math.random() * 68, y = 50 + Math.random() * 28, r = 22 + Math.random() * 20, gr = g.createRadialGradient(x, y, 0, x, y, r); gr.addColorStop(0, "rgba(255,255,255,.9)"); gr.addColorStop(1, "rgba(255,255,255,0)"); g.fillStyle = gr; g.fillRect(0, 0, 128, 128); }
  const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
})();
const clouds = [];
for (let i = 0; i < 26; i++) {
  const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: cloudTex, transparent: true, opacity: .7, depthWrite: false, fog: false }));
  const a = Math.random() * Math.PI * 2, r = 8 + Math.random() * 30;
  s.position.set(Math.cos(a) * r, 12 + Math.random() * 34, Math.sin(a) * r);
  const k = 10 + Math.random() * 14; s.scale.set(k, k * .55, 1);
  s.userData.v = .2 + Math.random() * .4; scene.add(s); clouds.push(s);
}
// time of day by height: morning at street level, a midnight sky at the spire
const SKY = [
  { f: 0, top: [90, 169, 230], bot: [207, 234, 255], sun: [255, 255, 255], si: 1.6, hi: .9, night: 0 },
  { f: 12, top: [74, 143, 214], bot: [255, 224, 168], sun: [255, 236, 200], si: 1.5, hi: .85, night: .05 },
  { f: 24, top: [70, 64, 150], bot: [255, 150, 105], sun: [255, 170, 110], si: 1.2, hi: .7, night: .35 },
  { f: 34, top: [26, 30, 80], bot: [120, 80, 150], sun: [180, 150, 220], si: .6, hi: .5, night: .75 },
  { f: 44, top: [4, 7, 18], bot: [26, 34, 78], sun: [140, 160, 230], si: .35, hi: .38, night: 1 }
];
function skyAt(f) {
  let a = SKY[0], b = SKY[SKY.length - 1];
  for (let i = 0; i < SKY.length - 1; i++) if (f >= SKY[i].f && f <= SKY[i + 1].f) { a = SKY[i]; b = SKY[i + 1]; break; }
  if (f > b.f) a = b;
  const k = a === b ? 0 : (f - a.f) / (b.f - a.f), mix = (p, q) => p.map((v, j) => Math.round(v + (q[j] - v) * k));
  return { top: mix(a.top, b.top), bot: mix(a.bot, b.bot), sun: mix(a.sun, b.sun), si: a.si + (b.si - a.si) * k, hi: a.hi + (b.hi - a.hi) * k, night: a.night + (b.night - a.night) * k };
}
function applySky(f) {
  const s = skyAt(f);
  skyMat.uniforms.top.value.setRGB(s.top[0] / 255, s.top[1] / 255, s.top[2] / 255, THREE.SRGBColorSpace);
  skyMat.uniforms.bot.value.setRGB(s.bot[0] / 255, s.bot[1] / 255, s.bot[2] / 255, THREE.SRGBColorSpace);
  skyMat.uniforms.sunCol.value.setRGB(s.sun[0] / 255, s.sun[1] / 255, s.sun[2] / 255, THREE.SRGBColorSpace);
  // the sun sinks toward the horizon as the tower climbs into the evening
  skyMat.uniforms.sunDir.value.set(0.42, Math.max(-0.05, 0.5 - f * 0.012), -0.85).normalize();
  scene.fog.color.setRGB(s.bot[0] / 255, s.bot[1] / 255, s.bot[2] / 255, THREE.SRGBColorSpace);
  sun.color.setRGB(s.sun[0] / 255, s.sun[1] / 255, s.sun[2] / 255, THREE.SRGBColorSpace); sun.intensity = s.si; hemi.intensity = s.hi;
  skyF = s.night;
}
 
/* ---------- the tower crane: a lattice mast that climbs with the building and slews to follow each floor ---------- */
const latticeTex = canvasTex(64, 64, (g, w) => {
  g.clearRect(0, 0, w, w); g.strokeStyle = "#fff"; g.lineWidth = 5;
  g.strokeRect(2, 2, w - 4, w - 4);
  g.beginPath(); g.moveTo(0, 0); g.lineTo(w, w); g.moveTo(w, 0); g.lineTo(0, w); g.lineWidth = 3; g.stroke();
}, { repeat: true });
const craneYellow = new THREE.MeshStandardMaterial({ color: 0xf2b630, map: latticeTex, alphaTest: .5, side: THREE.DoubleSide, roughness: .55, metalness: .3 });
const craneMat = new THREE.MeshStandardMaterial({ color: 0x2b2f36, roughness: .5, metalness: .6 });
const MAST = new THREE.Vector2(8.5, -8.5), MAST_W = 1.3;
const mastTex = latticeTex.clone(); mastTex.needsUpdate = true;
const mastMat = craneYellow.clone(); mastMat.map = mastTex;
const mast = new THREE.Mesh(new THREE.BoxGeometry(MAST_W, 1, MAST_W).translate(0, .5, 0), mastMat);
mast.castShadow = true; scene.add(mast);
const slew = new THREE.Group(); scene.add(slew);
{
  const jibTex = latticeTex.clone(); jibTex.needsUpdate = true; jibTex.repeat.set(26, 1);
  const jibMat = craneYellow.clone(); jibMat.map = jibTex;
  const jib = new THREE.Mesh(new THREE.BoxGeometry(26, .9, .9).translate(13, 0, 0), jibMat); jib.castShadow = true;
  const cjTex = latticeTex.clone(); cjTex.needsUpdate = true; cjTex.repeat.set(8, 1);
  const cjMat = craneYellow.clone(); cjMat.map = cjTex;
  const counter = new THREE.Mesh(new THREE.BoxGeometry(8, .8, 1.1).translate(-4, 0, 0), cjMat);
  const weight = new THREE.Mesh(new THREE.BoxGeometry(2, 1.6, 1.6), new THREE.MeshStandardMaterial({ color: 0x8b9096, roughness: .8 })); weight.position.set(-7, -.6, 0);
  const cab = new THREE.Mesh(new THREE.BoxGeometry(1.6, 1.3, 1.4), new THREE.MeshStandardMaterial({ color: 0xf2b630, roughness: .4, metalness: .2 })); cab.position.set(1.1, -1, .9);
  const cabGlass = new THREE.Mesh(new THREE.BoxGeometry(.05, .7, 1.1), new THREE.MeshStandardMaterial({ color: 0x223344, roughness: .1, metalness: .8, emissive: 0x334455 })); cabGlass.position.set(1.93, -.9, .9);
  const peak = new THREE.Mesh(new THREE.ConeGeometry(.9, 4, 4).translate(0, 2, 0), craneYellow.clone());
  const tieMat = new THREE.LineBasicMaterial({ color: 0x1d2026 });
  const tie = new THREE.LineSegments(new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 4, 0), new THREE.Vector3(20, .4, 0), new THREE.Vector3(0, 4, 0), new THREE.Vector3(-7, .4, 0)]), tieMat);
  const beacon = new THREE.Mesh(new THREE.SphereGeometry(.16, 8, 6), new THREE.MeshBasicMaterial({ color: hdr(0xff3030, 4) })); beacon.position.y = 4.1;
  const tip = beacon.clone(); tip.position.set(26, .5, 0);
  slew.add(jib, counter, weight, cab, cabGlass, peak, tie, beacon, tip);
  slew.userData.beacons = [beacon, tip];
}
const trolley = new THREE.Mesh(new THREE.BoxGeometry(1, .4, 1), craneMat); scene.add(trolley);
const cable = new THREE.Mesh(new THREE.CylinderGeometry(.035, .035, 1, 6), craneMat); scene.add(cable);
const hook = new THREE.Mesh(new THREE.BoxGeometry(.5, .4, .5), new THREE.MeshStandardMaterial({ color: 0xf2b630, roughness: .5 })); scene.add(hook);
const slingGeo = new THREE.BufferGeometry(); slingGeo.setAttribute("position", new THREE.Float32BufferAttribute(new Array(24).fill(0), 3));
const slings = new THREE.LineSegments(slingGeo, new THREE.LineBasicMaterial({ color: 0x1d2026 })); scene.add(slings);
let jibY = 8, slewA = Math.PI * .75, trolleyR = 12;
function placeCrane(dt) {
  // the mast tops out a few floors above the tower and climbs as it grows
  const want = Math.max(8, stack.length * H + 6.5);
  jibY += (want - jibY) * Math.min(1, dt * 1.5);
  mast.position.set(MAST.x, GY, MAST.y); mast.scale.y = jibY - GY - .45;
  mastTex.repeat.set(1, mast.scale.y / MAST_W);
  slew.position.set(MAST.x, jibY, MAST.y);
  const show = !!moving && !over;
  cable.visible = hook.visible = slings.visible = trolley.visible = show;
  if (show) {
    const { x, y, z } = moving.m.position, dx = x - MAST.x, dz = z - MAST.y;
    let a = Math.atan2(-dz, dx), d = a - slewA;
    while (d > Math.PI) d -= Math.PI * 2; while (d < -Math.PI) d += Math.PI * 2;
    slewA += d * Math.min(1, dt * 12);
    trolleyR = Math.hypot(dx, dz);
  }
  slew.rotation.y = slewA;
  const tx = MAST.x + Math.cos(slewA) * trolleyR, tz = MAST.y - Math.sin(slewA) * trolleyR;
  trolley.position.set(tx, jibY - .62, tz); trolley.rotation.y = slewA;
  const bl = Math.sin(clock * 3) > .6;
  for (const b of slew.userData.beacons) b.visible = bl && night > .15;
  if (!show) return;
  const { x, y, z } = moving.m.position, hy = y + 1.6, topY = jibY - .8;
  hook.position.set(x, hy, z);
  cable.position.set((x + tx) / 2, (hy + topY) / 2, (z + tz) / 2); cable.scale.y = Math.hypot(topY - hy, x - tx, z - tz);
  cable.lookAt(tx, topY, tz); cable.rotateX(Math.PI / 2);
  const p = slingGeo.attributes.position, hw = moving.w * .42, hd = moving.d * .42;
  [[hw, hd], [-hw, hd], [hw, -hd], [-hw, -hd]].forEach(([dx, dz], k) => { p.setXYZ(k * 2, x, hy - .2, z); p.setXYZ(k * 2 + 1, x + dx, y + .5, z + dz); });
  p.needsUpdate = true;
}
 
/* ---------- birds by day, a helicopter at dusk, and a warning light on the roof ---------- */
const birdGeo = new THREE.BufferGeometry();
birdGeo.setAttribute("position", new THREE.Float32BufferAttribute([0, 0, .15, -.6, .3, -.1, 0, 0, -.1, 0, 0, .15, 0, 0, -.1, .6, .3, -.1], 3));
birdGeo.computeVertexNormals();
const BIRDS = 26, birds = new THREE.InstancedMesh(birdGeo, new THREE.MeshBasicMaterial({ color: 0x1e2228, side: THREE.DoubleSide, transparent: true }), BIRDS);
birds.frustumCulled = false; scene.add(birds);
const birdState = Array.from({ length: BIRDS }, (_, i) => ({ r: 14 + (i % 5) * 1.6 + Math.random() * 2, y: 4 + Math.random() * 3 + (i % 3) * 1.2, a: (i / BIRDS) * 1.2, ph: Math.random() * 6, sp: .25 + Math.random() * .04 }));
const heli = new THREE.Group();
{
  const body = new THREE.Mesh(new THREE.SphereGeometry(.7, 14, 10), new THREE.MeshStandardMaterial({ color: 0x2e3440, roughness: .4, metalness: .5 })); body.scale.set(1.4, 1, 1);
  const tail = new THREE.Mesh(new THREE.BoxGeometry(2.2, .18, .18), body.material); tail.position.x = -1.8;
  const rotor = new THREE.Mesh(new THREE.BoxGeometry(4.2, .04, .2), new THREE.MeshBasicMaterial({ color: 0x15181c })); rotor.position.y = .8;
  const lightR = new THREE.Mesh(new THREE.SphereGeometry(.1, 6, 4), new THREE.MeshBasicMaterial({ color: hdr(0xff3a3a, 5) })); lightR.position.set(0, -.7, 0);
  const spot = new THREE.SpotLight(0xfff2d0, 0, 40, .35, .5, 1.2); spot.position.set(.6, -.5, 0); spot.target.position.set(4, -20, 0);
  heli.add(body, tail, rotor, lightR, spot, spot.target);
  heli.userData = { rotor, lightR, spot };
}
scene.add(heli);
const roofLight = new THREE.Mesh(new THREE.SphereGeometry(.14, 8, 6), new THREE.MeshBasicMaterial({ color: hdr(0xff2a2a, 5) }));
scene.add(roofLight);
const roofGlow = glowSprite(hdr(0xff3030, 1.6), 2.2); scene.add(roofGlow);
function placeLife(dt) {
  const n = stack.length * H, o = new THREE.Object3D(), day = 1 - night;
  birds.visible = day > .1;
  birds.material.opacity = Math.min(1, day * 1.3);
  for (let i = 0; i < BIRDS; i++) {
    const b = birdState[i];
    b.a += dt * b.sp;
    const a = b.a, x = Math.cos(a) * b.r, z = Math.sin(a) * b.r, flap = Math.sin(clock * 9 + b.ph);
    o.position.set(x, n + b.y + Math.sin(clock * .8 + b.ph) * .5, z);
    o.rotation.set(0, -a, 0);
    o.scale.set(.45, .45 * flap, .45);
    o.updateMatrix(); birds.setMatrixAt(i, o.matrix);
  }
  birds.instanceMatrix.needsUpdate = true;
  // the helicopter circles at sunset and after dark, sweeping its searchlight over the tower
  const ha = clock * .16;
  heli.visible = night > .2;
  heli.position.set(Math.cos(ha) * 26, n + 6 + Math.sin(clock * .5) * 1.5, Math.sin(ha) * 26);
  heli.rotation.y = -ha - Math.PI / 2;
  heli.userData.rotor.rotation.y = clock * 30;
  heli.userData.lightR.visible = Math.sin(clock * 6) > .3;
  heli.userData.spot.intensity = night * 120;
  const t = stack[stack.length - 1];
  if (t) {
    roofLight.position.set(t.m.position.x, t.m.position.y + .7, t.m.position.z);
    roofGlow.position.copy(roofLight.position);
    const on = Math.sin(clock * 2.5) > .2 && night > .1;
    roofLight.visible = roofGlow.visible = on && !over;
  }
}
 
/* ---------- dust when a floor lands ---------- */
const dustTex = canvasTex(64, 64, (g, w) => { const gr = g.createRadialGradient(w / 2, w / 2, 0, w / 2, w / 2, w / 2); gr.addColorStop(0, "rgba(255,255,255,.55)"); gr.addColorStop(1, "rgba(255,255,255,0)"); g.fillStyle = gr; g.fillRect(0, 0, w, w); });
const puffs = [];
function dust(m) {
  for (let i = 0; i < 10; i++) {
    const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: dustTex, color: 0xd8d2c8, transparent: true, depthWrite: false, opacity: .35 }));
    const e = (Math.random() * 4) | 0, u = Math.random() - .5;
    const ox = e < 2 ? (e ? 1 : -1) * m.w / 2 : u * m.w, oz = e < 2 ? u * m.d : (e === 2 ? 1 : -1) * m.d / 2;
    s.position.set(m.m.position.x + ox, m.y - .45, m.m.position.z + oz);
    s.scale.setScalar(.6);
    scene.add(s);
    puffs.push({ s, vx: ox * .5 + (Math.random() - .5), vz: oz * .5 + (Math.random() - .5), t: 0 });
  }
}
function updateDust(dt) {
  for (let i = puffs.length - 1; i >= 0; i--) {
    const p = puffs[i];
    p.t += dt;
    p.s.position.x += p.vx * dt; p.s.position.z += p.vz * dt; p.s.position.y += dt * .3;
    p.s.scale.setScalar(.5 + p.t * 1.6); p.s.material.opacity = Math.max(0, .35 * (1 - p.t / .8));
    if (p.t > .8) { scene.remove(p.s); p.s.material.dispose(); puffs.splice(i, 1); }
  }
}
 
/* ---------- weld sparks on a flush drop ---------- */
const sparkMat = new THREE.PointsMaterial({ color: hdr(0xffc36b, 3.5), size: .2, transparent: true, depthWrite: false });
function weld(m) {
  const n = 48, pos = new Float32Array(n * 3), vel = [];
  for (let i = 0; i < n; i++) {
    // sparks start along the seam under the new floor and spray outward
    const e = (Math.random() * 4) | 0, u = Math.random() - .5;
    const ox = e < 2 ? (e ? 1 : -1) * m.w / 2 : u * m.w, oz = e < 2 ? u * m.d : (e === 2 ? 1 : -1) * m.d / 2;
    pos.set([m.m.position.x + ox, m.y - .5, m.m.position.z + oz], i * 3);
    vel.push(ox * .8 + (Math.random() - .5) * 2, 2 + Math.random() * 4, oz * .8 + (Math.random() - .5) * 2);
  }
  const g = new THREE.BufferGeometry(); g.setAttribute("position", new THREE.BufferAttribute(pos, 3));
  const p = new THREE.Points(g, sparkMat.clone()); scene.add(p);
  sparks.push({ p, vel, t: 0 });
}
 
function resize() {
  const w = innerWidth, h = innerHeight, a = w / h;
  cam.aspect = a; cam.updateProjectionMatrix();
  // far enough back that the crane's whole swing fits across the screen
  camD = Math.max(30, 37 / a);
  // keep the haze the same however far back the camera sits
  scene.fog.near = camD + 15; scene.fog.far = camD + 130;
  renderer.setPixelRatio(dprCap());
  renderer.setSize(w, h);
  const b = renderer.getDrawingBufferSize(new THREE.Vector2());
  post.setSize(b.x, b.y);
  carMat.uniforms.scale.value = b.y / (2 * Math.tan(THREE.MathUtils.degToRad(cam.fov) / 2));
}
addEventListener("resize", resize); resize();
 
function clear() {
  for (const s of stack) { scene.remove(s.m); disposeMesh(s.m); }
  for (const d of debris) { scene.remove(d.m); disposeMesh(d.m); }
  for (const s of sparks) { scene.remove(s.p); s.p.geometry.dispose(); s.p.material.dispose(); }
  if (moving) { scene.remove(moving.m); disposeMesh(moving.m); }
  for (const p of puffs) { scene.remove(p.s); p.s.material.dispose(); }
  stack = []; debris = []; sparks = []; puffs.length = 0; moving = null;
}
function reset() {
  clear();
  score = 0; streak = 0; bestStreak = 0; flush = 0; braced = 0; braceK = 0; over = false; speed = SPEED0; axis = "x"; camY = 0; running = true;
  windT = 0; windX = 0; windZ = 0; warned = false;
  // a ten-storey podium for the tower to stand on
  const base = slab(START, START, 0, -BASE_H / 2 + .5, 0, 0, BASE_H);
  stack.push({ ...base, y: 0 });
  applySky(0);
  $("sk-score").textContent = "0"; $("sk-dist").textContent = districtOf(1).name;
  $("sk-hint").style.opacity = 1;
  spawn();
}
function top() { return stack[stack.length - 1]; }
function say(text, ms = 1000) { const c = $("sk-combo"); c.textContent = text; c.style.opacity = 1; clearTimeout(c.t); c.t = setTimeout(() => (c.style.opacity = 0), ms); }
/* wind: once the tower is a few floors up it sways, the top most of all, so
   the floor rides a fixed line while the landing spot drifts under it */
const SWAY_FROM = 4;
function swayAmp(n) { const k = Math.max(0, n - SWAY_FROM); return Math.min(2.6, 0.05 * k + 0.0009 * k * k) * (1 - braceK); }
function gust(t) { return Math.sin(t * 0.9) * 0.72 + Math.sin(t * 2.1 + 1) * 0.28; }
// live sway of floor j in a tower whose top floor is n
function sway(j, n) {
  if (j <= 0 || n <= 0) return [0, 0];
  const s = swayAmp(n) * gust(windT) * (j / n) * (j / n);
  return [s * windX, s * windZ];
}
function spawn() {
  const t = top(), i = stack.length;
  axis = axis === "x" ? "z" : "x";
  // every tenth floor is a sky lobby: the next floor comes in wider than the one below
  const lobby = score > 0 && score % 10 === 0;
  const w = lobby ? Math.min(START, t.w + 1.2) : t.w, d = lobby ? Math.min(START, t.d + 1.2) : t.d;
  const s = slab(w, d, axis === "x" ? -9 : t.x, i * H, axis === "z" ? -9 : t.z, i);
  moving = s; dir = 1; moving.pos = -9; moving.lobby = lobby && (w > t.w || d > t.d);
  if (moving.lobby) say("SKY LOBBY: A WIDER FLOOR", 1600);
}
function drop() {
  if (!running || over || !moving || PA.state !== "play") return;
  $("sk-hint").style.opacity = 0;
  const t = top(), m = moving, n = stack.length - 1, live = sway(n, n);
  const delta = axis === "x" ? m.x - (t.x + live[0]) : m.z - (t.z + live[1]);
  const size = axis === "x" ? t.w : t.d;
  const overlap = size - Math.abs(delta);
  if (overlap <= 0) { // missed entirely
    fall(m, axis, delta > 0 ? 1 : -1);
    moving = null;
    return gameOver();
  }
  const i = stack.length;
  // back to tower coordinates: the cross-axis tracks the top, so it lines up exactly
  if (axis === "x") { m.x = t.x + delta; m.z = t.z; } else { m.z = t.z + delta; m.x = t.x; }
  if (m.lobby && Math.abs(delta) < size / 2) {
    // a sky lobby lands whole as long as its middle is over the floor below: it cantilevers out
    streak = 0;
    m.m.position.set(m.x + live[0], m.y, m.z + live[1]);
    PA.sfx("thud", { pitch: .9 }); PA.tone({ freq: 523, to: 784, type: "triangle", dur: .25, vol: .08 });
  } else if (Math.abs(delta) < PERFECT) {
    // flush: snap into line and keep the full size
    streak++; flush++; bestStreak = Math.max(bestStreak, streak);
    if (axis === "x") m.x = t.x; else m.z = t.z;
    m.w = t.w; m.d = t.d;
    // a hot streak grows the floor back a little, up to the podium's footprint
    const grow = streak >= 3 && (m.w < START || m.d < START);
    if (grow) { m.w = Math.min(START, m.w + .3); m.d = Math.min(START, m.d + .3); }
    m.m.scale.set(m.w, H, m.d); resizeMats(m);
    m.m.position.set(m.x + live[0], m.y, m.z + live[1]);
    weld(m);
    PA.sfx("thud", { pitch: 1.9, vol: .6 }); PA.tone({ freq: 1320, type: "square", dur: .05, vol: .04 }); PA.tone({ freq: 1320, type: "square", dur: .05, vol: .03, delay: .07 });
    if (streak % 3 === 0) { braced = 4; say(grow ? "BRACED + REGROW" : "BRACED: NO SWAY FOR 4 FLOORS", 1500); PA.sfx("power", { pitch: .8 }); }
    else say(grow ? `FLUSH ×${streak} · REGROW` : streak >= 2 ? `FLUSH ×${streak}` : "FLUSH", 900);
    if (grow) PA.tone({ freq: 660, to: 990, type: "triangle", dur: .2, vol: .05, delay: .1 });
  } else {
    streak = 0;
    const cut = Math.abs(delta), sign = Math.sign(delta);
    if (axis === "x") {
      m.w = overlap; m.x = t.x + delta / 2;
      const fx = m.x + sign * (overlap / 2 + cut / 2);
      debrisPiece(cut, t.d, fx + live[0], m.y, m.z + live[1], i, sign, "x");
    } else {
      m.d = overlap; m.z = t.z + delta / 2;
      const fz = m.z + sign * (overlap / 2 + cut / 2);
      debrisPiece(t.w, cut, m.x + live[0], m.y, fz + live[1], i, sign, "z");
    }
    m.m.scale.set(m.w, H, m.d); resizeMats(m); m.m.position.set(m.x + live[0], m.y, m.z + live[1]);
    PA.sfx("thud", { pitch: 1.2 + Math.min(0.6, stack.length * 0.01) });
  }
  if (braced > 0 && !(streak && streak % 3 === 0)) braced--;
  dust(m); kick = .22;
  stack.push(m);
  score = stack.length - 1;
  $("sk-score").textContent = score;
  const D = districtOf(score + 1);
  if ($("sk-dist").textContent !== D.name) { $("sk-dist").textContent = D.name; if (score > 1) say(D.name.toUpperCase(), 1400); }
  applySky(score);
  speed = Math.min(16, SPEED0 + score * 0.12);
  if (!warned && score === SWAY_FROM + 1) { warned = true; say("WIND PICKING UP", 1400); }
  moving = null;
  spawn();
}
function debrisPiece(w, d, x, y, z, i, sign, ax) {
  const p = slab(w, d, x, y, z, i);
  p.vy = 0; p.vx = ax === "x" ? sign * 2.5 : 0; p.vz = ax === "z" ? sign * 2.5 : 0;
  p.rx = (ax === "z" ? sign : 0) * (1 + Math.random()); p.rz = (ax === "x" ? -sign : 0) * (1 + Math.random());
  debris.push(p);
}
function fall(m, ax, sign) { m.vy = 0; m.vx = ax === "x" ? sign * 3 : 0; m.vz = ax === "z" ? sign * 3 : 0; m.rx = ax === "z" ? sign * 2 : 0; m.rz = ax === "x" ? -sign * 2 : 0; debris.push(m); }
function gameOver() {
  over = true;
  PA.sfx("gameover");
  setTimeout(() => {
    PA.gameOver(score, { kicker: score > 0 ? "The floor slipped off the crane" : "Missed the first floor", title: score >= 50 ? "Supertall!" : score >= 40 ? "Topped out the spire!" : score >= 25 ? "Skyscraper!" : score >= 10 ? "High rise!" : score > 0 ? "Off the ground" : "Not a single floor", unit: "floors", stats: [["District", districtOf(score).name], ["Flush drops", flush], ["Best streak", "×" + bestStreak]] });
    if (window.paXP) window.paXP.award("skystack", { score });
  }, 900);
}
 
addEventListener("pointerdown", (e) => { if (e.target.closest && e.target.closest("button,#pa-gate,.pa-layer,.pa-tb")) return; drop(); });
PA.onKey((e) => { if (e.code === "Space" || e.code === "Enter" || e.code === "ArrowDown") { e.preventDefault(); drop(); } });
 
let last = performance.now();
function frame(now) {
  requestAnimationFrame(frame);
  const dt = Math.min(0.05, (now - last) / 1000); last = now;
  if (PA.isPaused && PA.isPaused()) return;
  clock += dt;
  if (!over && PA.state === "play") {
    windT += dt;
    // the wind leans along whichever way the floor slides, swinging round between floors
    const tx = axis === "x" ? 1 : 0, tz = 1 - tx;
    windX += (tx - windX) * Math.min(1, dt * 1.5); windZ += (tz - windZ) * Math.min(1, dt * 1.5);
  }
  braceK += ((braced > 0 ? 1 : 0) - braceK) * Math.min(1, dt * 2);
  {
    // ease every floor toward its swayed spot so new floors settle in without popping
    const n = stack.length - 1, e = Math.min(1, dt * 10);
    for (let j = 1; j <= n; j++) {
      const s = stack[j], o = sway(j, n), mp = s.m.position;
      mp.x += (s.x + o[0] - mp.x) * e; mp.z += (s.z + o[1] - mp.z) * e;
    }
  }
  if (moving && !over && PA.state === "play") {
    moving.pos += dir * speed * dt;
    if (moving.pos > 9) { moving.pos = 9; dir = -1; } else if (moving.pos < -9) { moving.pos = -9; dir = 1; }
    const t = top(), n = stack.length - 1, o = sway(n, n);
    // the line is fixed to the tower's footing; only the cross-axis follows the swaying top
    if (axis === "x") { moving.x = t.x + moving.pos; moving.z = t.z + o[1]; } else { moving.z = t.z + moving.pos; moving.x = t.x + o[0]; }
    moving.m.position.set(moving.x, moving.y, moving.z);
  }
  placeCrane(dt); placeLife(dt); updateDust(dt);
  for (const d of debris) {
    d.vy -= 30 * dt; d.m.position.x += d.vx * dt; d.m.position.y += d.vy * dt; d.m.position.z += d.vz * dt;
    d.m.rotation.x += d.rx * dt; d.m.rotation.z += d.rz * dt;
  }
  for (let i = debris.length - 1; i >= 0; i--) if (debris[i].m.position.y < -BASE_H - 2) { scene.remove(debris[i].m); disposeMesh(debris[i].m); debris.splice(i, 1); }
  for (const s of sparks) {
    s.t += dt; const p = s.p.geometry.attributes.position;
    for (let i = 0; i < p.count; i++) { s.vel[i * 3 + 1] -= 14 * dt; p.setXYZ(i, p.getX(i) + s.vel[i * 3] * dt, p.getY(i) + s.vel[i * 3 + 1] * dt, p.getZ(i) + s.vel[i * 3 + 2] * dt); }
    p.needsUpdate = true; s.p.material.opacity = Math.max(0, 1 - s.t / .8);
  }
  for (let i = sparks.length - 1; i >= 0; i--) if (sparks[i].t > .8) { scene.remove(sparks[i].p); sparks[i].p.geometry.dispose(); sparks[i].p.material.dispose(); sparks.splice(i, 1); }
  // night comes on with height: lit windows glow, the city twinkles
  night += (skyF - night) * Math.min(1, dt * 1.5);
  for (const m of sideMats) m.emissiveIntensity = night * 1.2;
  cityWall.emissiveIntensity = night * 2.4;
  lightsMat.opacity = Math.min(1, night * 1.4);
  lampMat.opacity = Math.min(1, night * 1.5);
  carMat.uniforms.time.value = clock; carMat.uniforms.night.value = night;
  skyMat.uniforms.time.value = clock; skyMat.uniforms.night.value = night;
  // clouds drift by; they thin out when they come close to the camera and darken after sunset
  const ck = 1 - night * .72;
  for (const c of clouds) {
    c.position.x += c.userData.v * dt; if (c.position.x > 40) c.position.x = -40;
    const dc = c.position.distanceTo(cam.position);
    // a cloud sitting right across the line of sight to the top of the tower thins out, so it never hides where the floor lands
    const ax = -cam.position.x, ay = camY + .5 - cam.position.y, az2 = -cam.position.z, aa = ax * ax + ay * ay + az2 * az2;
    const px = c.position.x - cam.position.x, py = c.position.y - cam.position.y, pz = c.position.z - cam.position.z;
    const u = Math.min(1, Math.max(0, (px * ax + py * ay + pz * az2) / aa));
    const off = Math.hypot(px - ax * u, py - ay * u, pz - az2 * u), clr = Math.min(1, Math.max(.08, (off - 3) / (c.scale.x * .45)));
    c.material.opacity = .55 * Math.min(1, Math.max(0, (dc - 10) / 14)) * (u < 1 ? clr : 1);
    c.material.color.setRGB(ck, ck * 1.02, ck * 1.1 + night * .1);
  }
  // camera rises with the tower and drifts gently round it; pulls back at the end to show the whole thing
  const targetY = over ? stack.length * H * 0.5 - BASE_H * .3 : Math.max(0, stack.length * H - 1.5);
  camY += (targetY - camY) * Math.min(1, dt * 3);
  const D = over ? Math.max(camD, stack.length * H * 1.9 + 14) : camD;
  cam.userData.d = (cam.userData.d || D) + (D - (cam.userData.d || D)) * Math.min(1, dt * 2);
  // the first floors are seen from higher up, looking down onto the podium so the landing spot is
  // easy to read; the view eases down to the usual angle as the tower climbs past ten floors
  const elT = over ? EL_LOW : EL_LOW + (EL_START - EL_LOW) * Math.max(0, 1 - score / 10);
  cam.userData.el = cam.userData.el == null ? elT : cam.userData.el + (elT - cam.userData.el) * Math.min(1, dt * 2);
  const az = CAM_AZ + Math.sin(clock * .07) * .12, el = cam.userData.el, dd = cam.userData.d;
  cam.position.set(Math.sin(az) * dd * Math.cos(el), camY + dd * Math.sin(el), Math.cos(az) * dd * Math.cos(el));
  kick *= Math.exp(-dt * 9);
  cam.position.y -= kick * Math.sin(clock * 40) * .5;
  // early on, aim a touch above the podium so it and the hanging floor sit clear of the score panel
  const lift = over ? 0 : 1.2 * Math.max(0, 1 - score / 10);
  cam.lookAt(0, camY + lift, 0);
  sky.position.copy(cam.position);
  sun.position.set(10, 30 + camY, 6); sun.target.position.set(0, camY, 0);
  post.render(scene, cam, clock);
}
requestAnimationFrame(frame);
PA.onStart(reset);
reset(); running = false;
window.__sk = { drop,
  // test hook: line the floor up with the swaying top plus an offset, then drop it
  dropAt(off) {
    if (!moving) return;
    const t = top(), n = stack.length - 1, o = sway(n, n);
    moving.pos = (axis === "x" ? o[0] : o[1]) + off;
    if (axis === "x") { moving.x = t.x + moving.pos; moving.z = t.z + o[1]; } else { moving.z = t.z + moving.pos; moving.x = t.x + o[0]; }
    drop();
  },
  get score() { return score; }, get streak() { return streak; }, get braced() { return braced; }, get lobby() { return !!(moving && moving.lobby); },
  get delta() { const t = top(), n = stack.length - 1, o = sway(n, n); return moving ? (axis === "x" ? moving.x - (t.x + o[0]) : moving.z - (t.z + o[1])) : null; },
  get sway() { const n = stack.length - 1; return swayAmp(n) * gust(windT); } };
</script>
</body></html>