Showcase

Time only moves when you move, built by Clover 35B A3B Preview

Hostedvia DaBenchCustom endpoint
Running live in your browserNew tab
Speed
396tok/s
First token included
Written
19Ktokens
Time to build
48.0s
Clover 35B A3B Preview's builds and scores
Show the code the model wrote
HTML53,653 characters
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SUPERHOT — TIME FROZEN</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { overflow: hidden; background: #000; font-family: 'Courier New', monospace; }
canvas { display: block; }
#hud {
  position: fixed; top: 0; left: 0; width: 100%; height: 100%;
  pointer-events: none; z-index: 10;
}
#crosshair {
  position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
  z-index: 11; pointer-events: none;
}
#crosshair::before, #crosshair::after {
  content: ''; position: absolute; background: rgba(255,255,255,0.7);
}
#crosshair::before { width: 20px; height: 2px; top: -1px; left: -10px; }
#crosshair::after { width: 2px; height: 20px; top: -10px; left: -1px; }
#health {
  position: fixed; bottom: 40px; left: 40px; z-index: 11;
  pointer-events: none; display: flex; gap: 8px; align-items: center;
}
.heart { font-size: 28px; color: #ff3333; text-shadow: 0 0 10px #ff0000; transition: all 0.3s; }
.heart.lost { color: #333; text-shadow: none; }
#enemy-count {
  position: fixed; bottom: 40px; right: 40px; z-index: 11;
  pointer-events: none; color: #ff6633; font-size: 24px; text-shadow: 0 0 15px #ff3300;
  font-family: 'Courier New', monospace; letter-spacing: 2px;
}
#time-dial {
  position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%);
  z-index: 11; pointer-events: none; text-align: center;
}
#time-label { color: #ffaa44; font-size: 12px; letter-spacing: 4px; margin-bottom: 4px; text-shadow: 0 0 10px #ff6600; }
#time-bar-bg { width: 200px; height: 4px; background: rgba(255,100,0,0.2); border: 1px solid rgba(255,100,0,0.4); }
#time-bar { height: 100%; background: linear-gradient(90deg, #ff3300, #ffaa00); width: 50%; transition: width 0.1s; box-shadow: 0 0 10px #ff6600; }
#message {
  position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
  z-index: 20; pointer-events: none; text-align: center; display: none;
}
#message h1 { font-size: 64px; letter-spacing: 8px; text-shadow: 0 0 40px currentColor; }
#message .sub { font-size: 18px; margin-top: 20px; opacity: 0.7; letter-spacing: 3px; }
#demo-toggle {
  position: fixed; top: 20px; right: 20px; z-index: 30;
  background: rgba(255,50,0,0.2); border: 1px solid rgba(255,100,0,0.5);
  color: #ff6633; padding: 8px 16px; cursor: pointer; font-family: 'Courier New', monospace;
  font-size: 12px; letter-spacing: 2px; pointer-events: all;
}
#demo-toggle:hover { background: rgba(255,50,0,0.4); }
#start-screen {
  position: fixed; top: 0; left: 0; width: 100%; height: 100%;
  z-index: 50; background: rgba(0,0,0,0.9);
  display: flex; flex-direction: column; align-items: center; justify-content: center;
  cursor: pointer;
}
#start-screen h1 {
  font-size: 72px; color: #ff4400; letter-spacing: 12px;
  text-shadow: 0 0 60px #ff2200, 0 0 120px #ff0000;
  font-family: 'Courier New', monospace;
}
#start-screen .subtitle {
  color: #ff8844; font-size: 18px; letter-spacing: 6px; margin-top: 20px;
}
#start-screen .click {
  color: #ffaa66; font-size: 14px; letter-spacing: 4px; margin-top: 60px;
  animation: pulse 2s infinite;
}
@keyframes pulse { 0%,100% { opacity: 0.4; } 50% { opacity: 1; } }
#damage-overlay {
  position: fixed; top: 0; left: 0; width: 100%; height: 100%;
  z-index: 9; pointer-events: none; background: radial-gradient(ellipse at center, transparent 50%, rgba(255,0,0,0.4) 100%);
  opacity: 0; transition: opacity 0.1s;
}
</style>
</head>
<body>
<div id="start-screen">
  <h1>TIME FROZEN</h1>
  <div class="subtitle">A SUPERHOT EXPERIENCE</div>
  <div class="click">[ CLICK TO ENTER ]</div>
</div>
<div id="crosshair"></div>
<div id="health"></div>
<div id="enemy-count"></div>
<div id="time-dial"><div id="time-label">TIME SCALE</div><div id="time-bar-bg"><div id="time-bar"></div></div></div>
<div id="damage-overlay"></div>
<div id="message"><h1></h1><div class="sub"></div></div>
<button id="demo-toggle">DEMO: OFF</button>

<script type="importmap">
{
  "imports": {
    "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
    "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
  }
}
</script>
<script type="module">
import * as THREE from 'three';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';

// ─── GLOBALS ───
let scene, camera, renderer, composer, bloomPass, vignettePass, grainPass;
let clock = new THREE.Clock();
let timeScale = 0.05;
let targetTimeScale = 0.05;
let playerHealth = 6;
let maxHealth = 6;
let enemiesRemaining = 0;
let enemiesKilled = 0;
let totalEnemies = 6;
let gameActive = false;
let demoMode = false;
let demoBotActive = false;
let demoBotState = 'patrol';
let demoBotTarget = null;
let demoBotPath = [];
let demoBotPathIdx = 0;
let demoBotShootTimer = 0;
let demoBotDodgeTimer = 0;
let demoBotLastShot = 0;

// Player
const player = {
  position: new THREE.Vector3(0, 1.7, 0),
  velocity: new THREE.Vector3(),
  direction: new THREE.Vector3(),
  moveForward: false, moveBackward: false, moveLeft: false, moveRight: false,
  canJump: false,
  yaw: 0, pitch: 0,
  radius: 0.4,
  height: 1.7,
  speed: 5.5,
  health: 6,
  invincible: 0,
  shootCooldown: 0,
  recoil: 0,
  bobPhase: 0,
};

// World bounds
const worldBounds = { minX: -25, maxX: 25, minZ: -25, maxZ: 25 };

// Objects
let enemies = [];
let projectiles = [];
let trails = [];
let particles = [];
let muzzleFlashes = [];
let impactSparks = [];
let gunGroup;
let gunMesh;
let gunLight;

// Audio
let audioCtx, ambientGain, ambientOsc1, ambientOsc2;
let masterGain;

// ─── PROCEDURAL TEXTURES ───
function createConcreteTexture() {
  const c = document.createElement('canvas');
  c.width = 512; c.height = 512;
  const ctx = c.getContext('2d');
  ctx.fillStyle = '#555555';
  ctx.fillRect(0, 0, 512, 512);
  for (let i = 0; i < 80000; i++) {
    const x = Math.random() * 512, y = Math.random() * 512;
    const b = Math.floor(Math.random() * 60 + 40);
    ctx.fillStyle = `rgb(${b},${b},${b})`;
    ctx.fillRect(x, y, 1.5, 1.5);
  }
  // Stain lines
  for (let i = 0; i < 20; i++) {
    ctx.strokeStyle = `rgba(${30+Math.random()*30},${30+Math.random()*30},${30+Math.random()*30},0.3)`;
    ctx.lineWidth = Math.random() * 3 + 1;
    ctx.beginPath();
    ctx.moveTo(Math.random() * 512, Math.random() * 512);
    ctx.bezierCurveTo(Math.random()*512, Math.random()*512, Math.random()*512, Math.random()*512, Math.random()*512, Math.random()*512);
    ctx.stroke();
  }
  const tex = new THREE.CanvasTexture(c);
  tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
  tex.repeat.set(4, 4);
  return tex;
}

function createMetalTexture() {
  const c = document.createElement('canvas');
  c.width = 256; c.height = 256;
  const ctx = c.getContext('2d');
  ctx.fillStyle = '#444';
  ctx.fillRect(0, 0, 256, 256);
  for (let i = 0; i < 256; i++) {
    const v = Math.floor(Math.random() * 30 + 50);
    ctx.fillStyle = `rgb(${v},${v},${v+10})`;
    ctx.fillRect(0, i, 256, 1);
  }
  const tex = new THREE.CanvasTexture(c);
  tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
  return tex;
}

function createRustTexture() {
  const c = document.createElement('canvas');
  c.width = 256; c.height = 256;
  const ctx = c.getContext('2d');
  ctx.fillStyle = '#3a2215';
  ctx.fillRect(0, 0, 256, 256);
  for (let i = 0; i < 50000; i++) {
    const x = Math.random() * 256, y = Math.random() * 256;
    const r = Math.floor(Math.random() * 80 + 40);
    const g = Math.floor(Math.random() * 30 + 10);
    const b = Math.floor(Math.random() * 15 + 5);
    ctx.fillStyle = `rgb(${r},${g},${b})`;
    ctx.fillRect(x, y, 2, 2);
  }
  const tex = new THREE.CanvasTexture(c);
  tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
  return tex;
}

// ─── AUDIO SYSTEM ───
function initAudio() {
  audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  masterGain = audioCtx.createGain();
  masterGain.gain.value = 0.4;
  masterGain.connect(audioCtx.destination);

  // Ambient drone
  ambientGain = audioCtx.createGain();
  ambientGain.gain.value = 0.08;
  ambientGain.connect(masterGain);

  ambientOsc1 = audioCtx.createOscillator();
  ambientOsc1.type = 'sawtooth';
  ambientOsc1.frequency.value = 55;
  ambientOsc1.connect(ambientGain);
  ambientOsc1.start();

  ambientOsc2 = audioCtx.createOscillator();
  ambientOsc2.type = 'sine';
  ambientOsc2.frequency.value = 55.5;
  ambientOsc2.connect(ambientGain);
  ambientOsc2.start();

  // Filter for ambient
  const filter = audioCtx.createBiquadFilter();
  filter.type = 'lowpass';
  filter.frequency.value = 200;
  filter.connect(ambientGain);
}

function playSound(type, tScale) {
  if (!audioCtx) return;
  const now = audioCtx.currentTime;
  const pitchShift = Math.max(0.1, tScale);

  switch(type) {
    case 'shoot': {
      const bufSize = Math.floor(audioCtx.sampleRate * 0.15);
      const buf = audioCtx.createBuffer(1, bufSize, audioCtx.sampleRate);
      const data = buf.getChannelData(0);
      for (let i = 0; i < bufSize; i++) {
        data[i] = (Math.random() * 2 - 1) * Math.exp(-i / (bufSize * 0.08));
      }
      const src = audioCtx.createBufferSource();
      src.buffer = buf;
      const g = audioCtx.createGain();
      g.gain.setValueAtTime(0.6, now);
      g.gain.exponentialRampToValueAtTime(0.001, now + 0.15);
      const f = audioCtx.createBiquadFilter();
      f.type = 'lowpass';
      f.frequency.value = 3000 * pitchShift;
      src.connect(f).connect(g).connect(masterGain);
      src.start(now);
      break;
    }
    case 'hit': {
      const bufSize = Math.floor(audioCtx.sampleRate * 0.3);
      const buf = audioCtx.createBuffer(1, bufSize, audioCtx.sampleRate);
      const data = buf.getChannelData(0);
      for (let i = 0; i < bufSize; i++) {
        data[i] = (Math.random() * 2 - 1) * Math.exp(-i / (bufSize * 0.15)) * Math.sin(i * 0.05);
      }
      const src = audioCtx.createBufferSource();
      src.buffer = buf;
      const g = audioCtx.createGain();
      g.gain.setValueAtTime(0.4, now);
      g.gain.exponentialRampToValueAtTime(0.001, now + 0.3);
      const f = audioCtx.createBiquadFilter();
      f.type = 'bandpass';
      f.frequency.value = 800 * pitchShift;
      f.Q.value = 2;
      src.connect(f).connect(g).connect(masterGain);
      src.start(now);
      break;
    }
    case 'enemy_hit': {
      const osc = audioCtx.createOscillator();
      osc.type = 'square';
      osc.frequency.setValueAtTime(400 * pitchShift, now);
      osc.frequency.exponentialRampToValueAtTime(100 * pitchShift, now + 0.2);
      const g = audioCtx.createGain();
      g.gain.setValueAtTime(0.3, now);
      g.gain.exponentialRampToValueAtTime(0.001, now + 0.2);
      osc.connect(g).connect(masterGain);
      osc.start(now);
      osc.stop(now + 0.2);
      break;
    }
    case 'enemy_die': {
      const bufSize = Math.floor(audioCtx.sampleRate * 0.8);
      const buf = audioCtx.createBuffer(1, bufSize, audioCtx.sampleRate);
      const data = buf.getChannelData(0);
      for (let i = 0; i < bufSize; i++) {
        data[i] = (Math.random() * 2 - 1) * Math.exp(-i / (bufSize * 0.2)) * (1 + Math.sin(i * 0.01) * 0.5);
      }
      const src = audioCtx.createBufferSource();
      src.buffer = buf;
      const g = audioCtx.createGain();
      g.gain.setValueAtTime(0.5, now);
      g.gain.exponentialRampToValueAtTime(0.001, now + 0.8);
      const f = audioCtx.createBiquadFilter();
      f.type = 'lowpass';
      f.frequency.value = 500 * pitchShift;
      src.connect(f).connect(g).connect(masterGain);
      src.start(now);
      break;
    }
    case 'player_hit': {
      const osc = audioCtx.createOscillator();
      osc.type = 'sawtooth';
      osc.frequency.setValueAtTime(200, now);
      osc.frequency.exponentialRampToValueAtTime(50, now + 0.3);
      const g = audioCtx.createGain();
      g.gain.setValueAtTime(0.4, now);
      g.gain.exponentialRampToValueAtTime(0.001, now + 0.3);
      osc.connect(g).connect(masterGain);
      osc.start(now);
      osc.stop(now + 0.3);
      break;
    }
    case 'impact': {
      const bufSize = Math.floor(audioCtx.sampleRate * 0.1);
      const buf = audioCtx.createBuffer(1, bufSize, audioCtx.sampleRate);
      const data = buf.getChannelData(0);
      for (let i = 0; i < bufSize; i++) {
        data[i] = (Math.random() * 2 - 1) * Math.exp(-i / (bufSize * 0.1));
      }
      const src = audioCtx.createBufferSource();
      src.buffer = buf;
      const g = audioCtx.createGain();
      g.gain.setValueAtTime(0.3, now);
      g.gain.exponentialRampToValueAtTime(0.001, now + 0.1);
      const f = audioCtx.createBiquadFilter();
      f.type = 'highpass';
      f.frequency.value = 1000 * pitchShift;
      src.connect(f).connect(g).connect(masterGain);
      src.start(now);
      break;
    }
  }
}

function updateAmbient(tScale) {
  if (!audioCtx) return;
  const pitch = Math.max(0.15, tScale);
  if (ambientOsc1) ambientOsc1.frequency.value = 55 * pitch;
  if (ambientOsc2) ambientOsc2.frequency.value = 55.5 * pitch;
  if (ambientGain) ambientGain.gain.value = 0.05 + tScale * 0.1;
}

// ─── SCENE SETUP ───
function initScene() {
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0x0a0a12);
  scene.fog = new THREE.FogExp2(0x0a0a12, 0.018);

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 200);
  camera.position.set(0, 1.7, 0);

  renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.0;
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  document.body.appendChild(renderer.domElement);

  // Post-processing
  composer = new EffectComposer(renderer);
  composer.addPass(new RenderPass(scene, camera));

  bloomPass = new UnrealBloomPass(
    new THREE.Vector2(window.innerWidth, window.innerHeight),
    1.2, 0.4, 0.2
  );
  composer.addPass(bloomPass);

  // Vignette + grain shader
  const vignetteShader = {
    uniforms: {
      tDiffuse: { value: null },
      darkness: { value: 1.2 },
      offset: { value: 1.1 },
      grainAmount: { value: 0.04 },
      grainTime: { value: 0 },
    },
    vertexShader: `
      varying vec2 vUv;
      void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
      }
    `,
    fragmentShader: `
      uniform sampler2D tDiffuse;
      uniform float darkness;
      uniform float offset;
      uniform float grainAmount;
      uniform float grainTime;
      varying vec2 vUv;
      
      float rand(vec2 co) {
        return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);
      }
      
      void main() {
        vec4 color = texture2D(tDiffuse, vUv);
        
        // Vignette
        vec2 uv = vUv * (1.0 - vUv.yx);
        float vig = uv.x * uv.y * darkness * offset;
        vig = pow(vig, 0.25);
        color.rgb *= vig;
        
        // Grain
        float grain = rand(vUv * grainTime) * grainAmount;
        color.rgb += grain - grainAmount * 0.5;
        
        // Subtle color grade - warm shadows, cool highlights
        color.r *= 1.02;
        color.b *= 0.98;
        
        gl_FragColor = color;
      }
    `
  };
  vignettePass = new ShaderPass(vignetteShader);
  composer.addPass(vignettePass);

  // Lighting
  const ambientLight = new THREE.AmbientLight(0x1a1a2e, 0.3);
  scene.add(ambientLight);

  // Key light - dramatic dusk sun
  const keyLight = new THREE.DirectionalLight(0xff6633, 2.5);
  keyLight.position.set(-30, 15, -20);
  keyLight.castShadow = true;
  keyLight.shadow.mapSize.width = 2048;
  keyLight.shadow.mapSize.height = 2048;
  keyLight.shadow.camera.near = 0.5;
  keyLight.shadow.camera.far = 100;
  keyLight.shadow.camera.left = -40;
  keyLight.shadow.camera.right = 40;
  keyLight.shadow.camera.top = 40;
  keyLight.shadow.camera.bottom = -40;
  keyLight.shadow.bias = -0.0001;
  keyLight.shadow.normalBias = 0.02;
  scene.add(keyLight);

  // Rim light
  const rimLight = new THREE.DirectionalLight(0x4466aa, 0.8);
  rimLight.position.set(20, 8, 15);
  scene.add(rimLight);

  // Practical point lights
  const practicalColors = [0xff4400, 0xff6600, 0xff2200];
  for (let i = 0; i < 4; i++) {
    const pl = new THREE.PointLight(practicalColors[i], 3, 15);
    pl.position.set(
      (Math.random() - 0.5) * 30,
      3 + Math.random() * 2,
      (Math.random() - 0.5) * 30
    );
    scene.add(pl);
  }
}

// ─── BUILD ARENA ───
function buildArena() {
  const concreteTex = createConcreteTexture();
  const metalTex = createMetalTexture();
  const rustTex = createRustTexture();

  const concreteMat = new THREE.MeshStandardMaterial({
    map: concreteTex, roughness: 0.85, metalness: 0.1,
  });
  const darkConcreteMat = new THREE.MeshStandardMaterial({
    map: concreteTex, roughness: 0.9, metalness: 0.05, color: 0x333333,
  });
  const metalMat = new THREE.MeshStandardMaterial({
    map: metalTex, roughness: 0.3, metalness: 0.8,
  });
  const rustMat = new THREE.MeshStandardMaterial({
    map: rustTex, roughness: 0.7, metalness: 0.3, color: 0x884422,
  });
  const emissiveMat = new THREE.MeshStandardMaterial({
    color: 0xff4400, emissive: 0xff4400, emissiveIntensity: 2, roughness: 0.3, metalness: 0.1,
  });
  const emissiveBlue = new THREE.MeshStandardMaterial({
    color: 0x4488ff, emissive: 0x4488ff, emissiveIntensity: 2, roughness: 0.3, metalness: 0.1,
  });

  // Floor
  const floorGeo = new THREE.PlaneGeometry(60, 60);
  const floor = new THREE.Mesh(floorGeo, concreteMat);
  floor.rotation.x = -Math.PI / 2;
  floor.receiveShadow = true;
  scene.add(floor);

  // Grid lines on floor
  const gridHelper = new THREE.PolarGridHelper(30, 64, 32, 128, 0x222222, 0x222222);
  gridHelper.position.y = 0.01;
  scene.add(gridHelper);

  // Outer walls
  const wallMat = darkConcreteMat;
  function createWall(x, y, z, w, h, d) {
    const geo = new THREE.BoxGeometry(w, h, d);
    const mesh = new THREE.Mesh(geo, wallMat);
    mesh.position.set(x, y, z);
    mesh.castShadow = true;
    mesh.receiveShadow = true;
    scene.add(mesh);
    return mesh;
  }

  // Back wall
  createWall(0, 4, -30, 60, 8, 1);
  // Left wall
  createWall(-30, 4, 0, 1, 8, 60);
  // Right wall
  createWall(30, 4, 0, 1, 8, 60);
  // Front wall (with gap for entrance)
  createWall(-15, 4, 30, 20, 8, 1);
  createWall(15, 4, 30, 20, 8, 1);
  createWall(0, 7, 30, 10, 2, 1);

  // Pillars
  const pillarPositions = [
    [-15, 0, -15], [15, 0, -15], [-15, 0, 15], [15, 0, 15],
    [-20, 0, -5], [20, 0, -5], [-20, 0, 5], [20, 0, 5],
  ];
  pillarPositions.forEach(([x, , z]) => {
    const pillar = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.6, 8, 8), darkConcreteMat);
    pillar.position.set(x, 4, z);
    pillar.castShadow = true;
    pillar.receiveShadow = true;
    scene.add(pillar);

    // Pillar cap
    const cap = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.3, 1.4), metalMat);
    cap.position.set(x, 8.15, z);
    cap.castShadow = true;
    scene.add(cap);
  });

  // Cover obstacles
  function createBox(x, y, z, w, h, d, mat) {
    const geo = new THREE.BoxGeometry(w, h, d);
    const mesh = new THREE.Mesh(geo, mat);
    mesh.position.set(x, y + h / 2, z);
    mesh.castShadow = true;
    mesh.receiveShadow = true;
    scene.add(mesh);
    return mesh;
  }

  // Central cover
  createBox(0, 0, -5, 3, 1.2, 1.5, rustMat);
  createBox(-8, 0, 5, 2, 1, 4, metalMat);
  createBox(8, 0, 5, 2, 1, 4, metalMat);
  createBox(-12, 0, -10, 4, 1.5, 2, darkConcreteMat);
  createBox(12, 0, -10, 4, 1.5, 2, darkConcreteMat);
  createBox(-5, 0, 12, 3, 0.8, 3, rustMat);
  createBox(5, 0, 12, 3, 0.8, 3, rustMat);
  createBox(0, 0, 10, 2, 1, 2, metalMat);

  // Ramps / platforms
  const rampGeo = new THREE.BoxGeometry(6, 0.3, 3);
  const ramp1 = new THREE.Mesh(rampGeo, darkConcreteMat);
  ramp1.position.set(-10, 1.5, -20);
  ramp1.rotation.z = 0.15;
  ramp1.castShadow = true;
  ramp1.receiveShadow = true;
  scene.add(ramp1);

  const ramp2 = new THREE.Mesh(rampGeo, darkConcreteMat);
  ramp2.position.set(10, 1.5, -20);
  ramp2.rotation.z = -0.15;
  ramp2.castShadow = true;
  ramp2.receiveShadow = true;
  scene.add(ramp2);

  // Emissive strips on walls
  function createEmissiveStrip(x, y, z, w, h, d, color) {
    const geo = new THREE.BoxGeometry(w, h, d);
    const mat = new THREE.MeshStandardMaterial({
      color, emissive: color, emissiveIntensity: 3, roughness: 0.2, metalness: 0.1,
    });
    const mesh = new THREE.Mesh(geo, mat);
    mesh.position.set(x, y, z);
    scene.add(mesh);

    // Add a point light near it
    const pl = new THREE.PointLight(color, 2, 8);
    pl.position.set(x, y + 0.5, z);
    scene.add(pl);
  }

  createEmissiveStrip(-29.8, 2, -10, 0.1, 0.1, 5, 0xff4400);
  createEmissiveStrip(29.8, 2, 10, 0.1, 0.1, 5, 0xff4400);
  createEmissiveStrip(-10, 2, -29.8, 5, 0.1, 0.1, 0x4488ff);
  createEmissiveStrip(10, 2, -29.8, 5, 0.1, 0.1, 0x4488ff);

  // Ceiling beams
  for (let x = -20; x <= 20; x += 10) {
    const beam = new THREE.Mesh(new THREE.BoxGeometry(0.8, 0.8, 60), darkConcreteMat);
    beam.position.set(x, 8, 0);
    beam.castShadow = true;
    scene.add(beam);
  }

  // Rain particles (static, for visual)
  const rainGeo = new THREE.BufferGeometry();
  const rainPositions = [];
  for (let i = 0; i < 3000; i++) {
    rainPositions.push(
      (Math.random() - 0.5) * 60,
      Math.random() * 20,
      (Math.random() - 0.5) * 60
    );
  }
  rainGeo.setAttribute('position', new THREE.Float32BufferAttribute(rainPositions, 3));
  const rainMat = new THREE.PointsMaterial({
    color: 0x8888aa, size: 0.05, transparent: true, opacity: 0.3,
    blending: THREE.AdditiveBlending, depthWrite: false,
  });
  const rain = new THREE.Points(rainGeo, rainMat);
  scene.add(rain);
  window._rain = rain;
}

// ─── GUN MODEL ───
function buildGun() {
  gunGroup = new THREE.Group();

  const gunMetal = new THREE.MeshStandardMaterial({
    color: 0x222222, roughness: 0.2, metalness: 0.9,
  });
  const gunGrip = new THREE.MeshStandardMaterial({
    color: 0x332211, roughness: 0.6, metalness: 0.1,
  });
  const gunAccent = new THREE.MeshStandardMaterial({
    color: 0xff4400, emissive: 0xff4400, emissiveIntensity: 1, roughness: 0.3, metalness: 0.2,
  });

  // Barrel
  const barrel = new THREE.Mesh(new THREE.CylinderGeometry(0.03, 0.04, 0.4, 8), gunMetal);
  barrel.rotation.x = Math.PI / 2;
  barrel.position.set(0, 0.02, -0.2);
  gunGroup.add(barrel);

  // Body
  const body = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.08, 0.25), gunMetal);
  body.position.set(0, -0.02, -0.05);
  gunGroup.add(body);

  // Grip
  const grip = new THREE.Mesh(new THREE.BoxGeometry(0.04, 0.12, 0.06), gunGrip);
  grip.position.set(0, -0.09, 0.05);
  grip.rotation.x = 0.3;
  gunGroup.add(grip);

  // Slide detail
  const slide = new THREE.Mesh(new THREE.BoxGeometry(0.055, 0.03, 0.2), gunAccent);
  slide.position.set(0, 0.03, -0.1);
  gunGroup.add(slide);

  // Muzzle flash light
  gunLight = new THREE.PointLight(0xff6600, 0, 5);
  gunLight.position.set(0, 0.02, -0.4);
  gunGroup.add(gunLight);

  gunGroup.position.set(0.25, -0.22, -0.35);
  camera.add(gunGroup);
  scene.add(camera);
}

// ─── ENEMY SYSTEM ───
function createEnemy(position) {
  const group = new THREE.Group();

  // Materials
  const bodyMat = new THREE.MeshStandardMaterial({
    color: 0x443322, roughness: 0.6, metalness: 0.2,
  });
  const accentMat = new THREE.MeshStandardMaterial({
    color: 0xff4400, emissive: 0xff4400, emissiveIntensity: 0.5, roughness: 0.3, metalness: 0.3,
  });
  const eyeMat = new THREE.MeshStandardMaterial({
    color: 0xff2200, emissive: 0xff2200, emissiveIntensity: 2, roughness: 0.1, metalness: 0.1,
  });
  const jointMat = new THREE.MeshStandardMaterial({
    color: 0x222222, roughness: 0.3, metalness: 0.8,
  });

  // Torso
  const torso = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.35, 0.8, 8), bodyMat);
  torso.position.y = 1.3;
  torso.castShadow = true;
  group.add(torso);

  // Chest plate
  const chest = new THREE.Mesh(new THREE.BoxGeometry(0.5, 0.4, 0.15), accentMat);
  chest.position.set(0, 1.4, 0.18);
  group.add(chest);

  // Head
  const head = new THREE.Mesh(new THREE.SphereGeometry(0.2, 8, 8), bodyMat);
  head.position.y = 1.9;
  head.castShadow = true;
  group.add(head);

  // Eyes
  const eyeL = new THREE.Mesh(new THREE.SphereGeometry(0.04, 6, 6), eyeMat);
  eyeL.position.set(-0.08, 1.95, -0.17);
  group.add(eyeL);
  const eyeR = new THREE.Mesh(new THREE.SphereGeometry(0.04, 6, 6), eyeMat);
  eyeR.position.set(0.08, 1.95, -0.17);
  group.add(eyeR);

  // Helmet ridge
  const helmet = new THREE.Mesh(new THREE.TorusGeometry(0.2, 0.03, 6, 12), jointMat);
  helmet.position.set(0, 1.98, 0);
  helmet.rotation.x = Math.PI / 2;
  group.add(helmet);

  // Arms
  const armL = new THREE.Group();
  const armLUpper = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.07, 0.4, 6), bodyMat);
  armLUpper.position.y = -0.2;
  armL.add(armLUpper);
  const armLLower = new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.06, 0.35, 6), bodyMat);
  armLLower.position.y = -0.42;
  armL.add(armLLower);
  armL.position.set(-0.4, 1.5, 0);
  group.add(armL);

  const armR = new THREE.Group();
  const armRUpper = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.07, 0.4, 6), bodyMat);
  armRUpper.position.y = -0.2;
  armR.add(armRUpper);
  const armRLower = new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.06, 0.35, 6), bodyMat);
  armRLower.position.y = -0.42;
  armR.add(armRLower);
  armR.position.set(0.4, 1.5, 0);
  group.add(armR);

  // Weapon in right hand
  const weapon = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.05, 0.3), jointMat);
  weapon.position.set(0, -0.6, -0.15);
  weapon.rotation.x = 0.2;
  armR.add(weapon);

  // Legs
  const legL = new THREE.Group();
  const legLUpper = new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.08, 0.45, 6), bodyMat);
  legLUpper.position.y = -0.22;
  legL.add(legLUpper);
  const legLLower = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.07, 0.4, 6), bodyMat);
  legLLower.position.y = -0.45;
  legL.add(legLLower);
  legL.position.set(-0.15, 0.9, 0);
  group.add(legL);

  const legR = new THREE.Group();
  const legRUpper = new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.08, 0.45, 6), bodyMat);
  legRUpper.position.y = -0.22;
  legR.add(legRUpper);
  const legRLower = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.07, 0.4, 6), bodyMat);
  legRLower.position.y = -0.45;
  legR.add(legRLower);
  legR.position.set(0.15, 0.9, 0);
  group.add(legR);

  // Enemy light
  const eLight = new THREE.PointLight(0xff4400, 1, 4);
  eLight.position.y = 1.5;
  group.add(eLight);

  group.position.copy(position);
  scene.add(group);

  const enemy = {
    group,
    hp: 3,
    maxHp: 3,
    state: 'patrol',
    stateTimer: 0,
    patrolTarget: null,
    lastKnownPlayerPos: null,
    lastShotTime: 0,
    shootCooldown: 2 + Math.random() * 1.5,
    animPhase: Math.random() * Math.PI * 2,
    animSpeed: 2 + Math.random(),
    deathAnim: 0,
    isDead: false,
    hitFlash: 0,
    // Animation references
    armL, armR, legL, legR,
    eyeL, eyeR,
    chest,
    eLight,
  };

  return enemy;
}

function spawnEnemies() {
  enemies = [];
  const spawnPositions = [
    new THREE.Vector3(-15, 0, -15),
    new THREE.Vector3(15, 0, -15),
    new THREE.Vector3(-15, 0, 15),
    new THREE.Vector3(15, 0, 15),
    new THREE.Vector3(0, 0, -20),
    new THREE.Vector3(0, 0, 20),
  ];
  spawnPositions.forEach(pos => {
    enemies.push(createEnemy(pos));
  });
  enemiesRemaining = enemies.length;
  updateHUD();
}

function updateEnemies(dt) {
  const scaledDt = dt * timeScale;
  const playerPos = player.position.clone();

  enemies.forEach(enemy => {
    if (enemy.isDead) {
      enemy.deathAnim += scaledDt;
      if (enemy.deathAnim < 2) {
        // Death animation: tumble and explode
        enemy.group.rotation.x += scaledDt * 2;
        enemy.group.rotation.z += scaledDt * 1.5;
        enemy.group.position.y -= scaledDt * 0.5;
        // Emit embers
        if (Math.random() < 0.3) {
          emitEmbers(enemy.group.position.clone().add(new THREE.Vector3(0, 1, 0)));
        }
      } else {
        // Remove dead enemy
        scene.remove(enemy.group);
        enemy.group.traverse(child => {
          if (child.geometry) child.geometry.dispose();
          if (child.material) {
            if (Array.isArray(child.material)) child.material.forEach(m => m.dispose());
            else child.material.dispose();
          }
        });
      }
      return;
    }

    const distToPlayer = enemy.group.position.distanceTo(playerPos);
    const hasLineOfSight = checkLineOfSight(enemy.group.position, playerPos);

    // State machine
    switch (enemy.state) {
      case 'patrol':
        if (!enemy.patrolTarget || enemy.group.position.distanceTo(enemy.patrolTarget) < 1) {
          enemy.patrolTarget = new THREE.Vector3(
            (Math.random() - 0.5) * 30,
            0,
            (Math.random() - 0.5) * 30
          );
        }
        if (distToPlayer < 12 && hasLineOfSight) {
          enemy.state = 'spot';
          enemy.stateTimer = 1.5;
          enemy.lastKnownPlayerPos = playerPos.clone();
        }
        // Move toward patrol target
        const dir = enemy.patrolTarget.clone().sub(enemy.group.position).normalize();
        enemy.group.position.add(dir.multiplyScalar(scaledDt * 1.5));
        // Clamp to world
        enemy.group.position.x = Math.max(worldBounds.minX + 2, Math.min(worldBounds.maxX - 2, enemy.group.position.x));
        enemy.group.position.z = Math.max(worldBounds.minZ + 2, Math.min(worldBounds.maxZ - 2, enemy.group.position.z));
        enemy.group.rotation.y = Math.atan2(dir.x, dir.z);
        // Animate walk
        enemy.animPhase += scaledDt * enemy.animSpeed;
        enemy.legL.rotation.x = Math.sin(enemy.animPhase) * 0.5;
        enemy.legR.rotation.x = -Math.sin(enemy.animPhase) * 0.5;
        enemy.armL.rotation.x = -Math.sin(enemy.animPhase) * 0.3;
        enemy.armR.rotation.x = Math.sin(enemy.animPhase) * 0.3;
        break;

      case 'spot':
        enemy.stateTimer -= scaledDt;
        enemy.state = 'attack';
        enemy.lastKnownPlayerPos = playerPos.clone();
        break;

      case 'attack':
        // Face player
        const lookDir = playerPos.clone().sub(enemy.group.position);
        lookDir.y = 0;
        enemy.group.rotation.y = Math.atan2(lookDir.x, lookDir.z);

        // Move toward player if far, strafe if close
        if (distToPlayer > 10) {
          const moveDir = lookDir.clone().normalize();
          enemy.group.position.add(moveDir.multiplyScalar(scaledDt * 2));
        } else if (distToPlayer < 6) {
          const awayDir = lookDir.clone().normalize().multiplyScalar(-1);
          enemy.group.position.add(awayDir.multiplyScalar(scaledDt * 1.5));
        }
        // Strafe
        const strafeDir = new THREE.Vector3(-lookDir.z, 0, lookDir.x).multiplyScalar(
          Math.sin(Date.now() * 0.002) > 0 ? 1 : -1
        );
        enemy.group.position.add(strafeDir.multiplyScalar(scaledDt * 1));

        // Clamp
        enemy.group.position.x = Math.max(worldBounds.minX + 1, Math.min(worldBounds.maxX - 1, enemy.group.position.x));
        enemy.group.position.z = Math.max(worldBounds.minZ + 1, Math.min(worldBounds.maxZ - 1, enemy.group.position.z));

        // Shoot
        enemy.lastShotTime += scaledDt;
        if (enemy.lastShotTime >= enemy.shootCooldown && distToPlayer < 20 && hasLineOfSight) {
          enemy.lastShotTime = 0;
          shootProjectileFromEnemy(enemy);
        }

        // Animate idle/tension
        enemy.animPhase += scaledDt * enemy.animSpeed * 0.5;
        enemy.armR.rotation.z = Math.sin(enemy.animPhase) * 0.1 - 0.3;
        enemy.armL.rotation.z = -0.2;
        enemy.eyeL.material.emissiveIntensity = 2 + Math.sin(enemy.animPhase * 3) * 0.5;
        enemy.eLight.intensity = 1 + Math.sin(enemy.animPhase * 2) * 0.5;
        break;
    }

    // Hit flash
    if (enemy.hitFlash > 0) {
      enemy.hitFlash -= scaledDt;
      enemy.chest.material.emissiveIntensity = enemy.hitFlash * 3;
    } else {
      enemy.chest.material.emissiveIntensity = 0.5;
    }
  });
}

function shootProjectileFromEnemy(enemy) {
  if (enemy.isDead) return;
  const start = enemy.group.position.clone().add(new THREE.Vector3(0, 1.5, 0));
  const dir = player.position.clone().sub(start).normalize();
  // Add some inaccuracy
  dir.x += (Math.random() - 0.5) * 0.15;
  dir.y += (Math.random() - 0.5) * 0.1;
  dir.z += (Math.random() - 0.5) * 0.15;
  dir.normalize();

  const projGeo = new THREE.SphereGeometry(0.08, 8, 8);
  const projMat = new THREE.MeshStandardMaterial({
    color: 0xff4400, emissive: 0xff4400, emissiveIntensity: 3, roughness: 0.1, metalness: 0.1,
  });
  const projMesh = new THREE.Mesh(projGeo, projMat);
  projMesh.position.copy(start);
  scene.add(projMesh);

  const pLight = new THREE.PointLight(0xff4400, 2, 6);
  projMesh.add(pLight);

  projectiles.push({
    mesh: projMesh,
    light: pLight,
    velocity: dir.multiplyScalar(8),
    life: 4,
    trailTimer: 0,
  });

  playSound('shoot', timeScale);
}

function checkLineOfSight(from, to) {
  const dir = to.clone().sub(from);
  const dist = dir.length();
  const normalizedDir = dir.normalize();

  const raycaster = new THREE.Raycaster(from, normalizedDir, 0, dist);
  // We need to check against world geometry
  // For simplicity, check against known obstacle positions
  const midPoint = from.clone().add(to).multiplyScalar(0.5);

  // Simple distance check through walls
  const wallCheckPoints = [
    new THREE.Vector3(-30, 4, 0), new THREE.Vector3(30, 4, 0),
    new THREE.Vector3(0, 4, -30), new THREE.Vector3(0, 4, 30),
  ];

  for (let i = 0; i < 20; i++) {
    const t = i / 20;
    const pt = from.clone().lerp(to, t);
    // Check if point is inside any wall
    for (const wall of wallCheckPoints) {
      const d = pt.distanceTo(wall);
      if (d < 1.5 && pt.y < 6) return false;
    }
  }
  return true;
}

// ─── PARTICLES ───
function emitEmbers(position) {
  const geo = new THREE.SphereGeometry(0.03, 4, 4);
  const mat = new THREE.MeshStandardMaterial({
    color: 0xff6600, emissive: 0xff4400, emissiveIntensity: 2,
  });
  for (let i = 0; i < 5; i++) {
    const mesh = new THREE.Mesh(geo, mat.clone());
    mesh.position.copy(position);
    scene.add(mesh);
    particles.push({
      mesh,
      velocity: new THREE.Vector3(
        (Math.random() - 0.5) * 3,
        Math.random() * 3 + 1,
        (Math.random() - 0.5) * 3
      ),
      life: 1 + Math.random(),
      maxLife: 1 + Math.random(),
    });
  }
}

function emitSparks(position, normal) {
  const geo = new THREE.SphereGeometry(0.02, 3, 3);
  const mat = new THREE.MeshStandardMaterial({
    color: 0xffaa44, emissive: 0xff6600, emissiveIntensity: 3,
  });
  for (let i = 0; i < 8; i++) {
    const mesh = new THREE.Mesh(geo, mat.clone());
    mesh.position.copy(position);
    scene.add(mesh);
    particles.push({
      mesh,
      velocity: new THREE.Vector3(
        (Math.random() - 0.5) * 5 + normal.x * 2,
        Math.random() * 4 + normal.y * 2,
        (Math.random() - 0.5) * 5 + normal.z * 2
      ),
      life: 0.5 + Math.random() * 0.5,
      maxLife: 0.5 + Math.random() * 0.5,
    });
  }
}

function updateParticles(dt) {
  const scaledDt = dt * timeScale;
  particles = particles.filter(p => {
    p.life -= scaledDt;
    if (p.life <= 0) {
      scene.remove(p.mesh);
      p.mesh.geometry.dispose();
      p.mesh.material.dispose();
      return false;
    }
    p.velocity.y -= scaledDt * 5; // gravity
    p.mesh.position.add(p.velocity.clone().multiplyScalar(scaledDt));
    p.mesh.material.opacity = p.life / p.maxLife;
    p.mesh.material.transparent = true;
    return true;
  });
}

// ─── PROJECTILES ───
function updateProjectiles(dt) {
  const scaledDt = dt * timeScale;
  projectiles = projectiles.filter(p => {
    p.life -= scaledDt;
    p.trailTimer += scaledDt;
    p.mesh.position.add(p.velocity.clone().multiplyScalar(scaledDt));

    // Trail
    if (p.trailTimer > 0.02) {
      p.trailTimer = 0;
      const trailGeo = new THREE.SphereGeometry(0.04, 4, 4);
      const trailMat = new THREE.MeshStandardMaterial({
        color: 0xff4400, emissive: 0xff4400, emissiveIntensity: 2, transparent: true, opacity: 0.6,
      });
      const trail = new THREE.Mesh(trailGeo, trailMat);
      trail.position.copy(p.mesh.position);
      scene.add(trail);
      trails.push({ mesh: trail, life: 0.3, maxLife: 0.3 });
    }

    // Check hit player
    const distToPlayer = p.mesh.position.distanceTo(player.position);
    if (distToPlayer < 0.8) {
      damagePlayer(1);
      // Impact effect
      emitSparks(p.mesh.position, p.velocity.clone().normalize());
      playSound('impact', timeScale);
      scene.remove(p.mesh);
      p.light.dispose();
      return false;
    }

    // Check hit enemies (player shooting)
    enemies.forEach(enemy => {
      if (!enemy.isDead && p.mesh.position.distanceTo(enemy.group.position) < 1.2) {
        hitEnemy(enemy, 1);
        emitSparks(p.mesh.position, p.velocity.clone().normalize());
        playSound('impact', timeScale);
        scene.remove(p.mesh);
        p.light.dispose();
        return false;
      }
    });

    // Remove if out of world
    if (p.mesh.position.x < worldBounds.minX || p.mesh.position.x > worldBounds.maxX ||
        p.mesh.position.z < worldBounds.minZ || p.mesh.position.z > worldBounds.maxZ ||
        p.mesh.position.y < 0 || p.life <= 0) {
      scene.remove(p.mesh);
      p.light.dispose();
      return false;
    }
    return true;
  });

  // Update trails
  trails = trails.filter(t => {
    t.life -= scaledDt;
    if (t.life <= 0) {
      scene.remove(t.mesh);
      t.mesh.geometry.dispose();
      t.mesh.material.dispose();
      return false;
    }
    t.mesh.material.opacity = (t.life / t.maxLife) * 0.6;
    return true;
  });
}

// ─── COMBAT ───
function playerShoot() {
  if (!gameActive || player.shootCooldown > 0) return;
  player.shootCooldown = 0.25;
  player.recoil = 0.1;

  // Muzzle flash
  gunLight.intensity = 5;
  setTimeout(() => { gunLight.intensity = 0; }, 50);

  // Flash light that illuminates scene
  const flashLight = new THREE.PointLight(0xff6600, 8, 10);
  flashLight.position.copy(player.position);
  const flashDir = new THREE.Vector3(0, 0, -1);
  flashDir.applyAxisAngle(new THREE.Vector3(0, 1, 0), player.yaw);
  flashLight.position.add(flashDir.multiplyScalar(0.5));
  scene.add(flashLight);
  setTimeout(() => scene.remove(flashLight), 80);

  // Raycast for hits
  const raycaster = new THREE.Raycaster();
  const dir = new THREE.Vector3(0, 0, -1);
  dir.applyAxisAngle(new THREE.Vector3(0, 1, 0), player.yaw);
  dir.applyAxisAngle(new THREE.Vector3(1, 0, 0), player.pitch);
  raycaster.set(player.position.clone(), dir);
  raycaster.far = 100;

  // Check enemy hits
  let hitEnemy = false;
  enemies.forEach(enemy => {
    if (enemy.isDead) return;
    const enemyBox = new THREE.Box3().setFromObject(enemy.group);
    const intersects = raycaster.ray.intersectBox(enemyBox, new THREE.Vector3());
    if (intersects) {
      hitEnemy(enemy, 1);
      hitEnemy = true;
      // Spark at hit point
      emitSparks(intersects, dir.clone().negate());
    }
  });

  // Muzzle flash tracer
  const tracerGeo = new THREE.CylinderGeometry(0.005, 0.005, 2, 4);
  const tracerMat = new THREE.MeshStandardMaterial({
    color: 0xffaa44, emissive: 0xff8800, emissiveIntensity: 5,
  });
  const tracer = new THREE.Mesh(tracerGeo, tracerMat);
  tracer.position.copy(player.position);
  const start = player.position.clone().add(dir.clone().multiplyScalar(0.5));
  tracer.position.copy(start);
  tracer.lookAt(start.clone().add(dir.clone().multiplyScalar(10)));
  tracer.rotateX(Math.PI / 2);
  scene.add(tracer);
  setTimeout(() => scene.remove(tracer), 100);

  playSound('shoot', timeScale);
}

function hitEnemy(enemy, damage) {
  if (enemy.isDead) return;
  enemy.hp -= damage;
  enemy.hitFlash = 0.3;
  enemy.state = 'spot';
  enemy.lastKnownPlayerPos = player.position.clone();

  playSound('enemy_hit', timeScale);

  if (enemy.hp <= 0) {
    enemy.isDead = true;
    enemy.deathAnim = 0;
    enemiesRemaining--;
    enemiesKilled++;
    playSound('enemy_die', timeScale);
    emitEmbers(enemy.group.position.clone().add(new THREE.Vector3(0, 1, 0)));

    // Big explosion light
    const expLight = new THREE.PointLight(0xff4400, 10, 15);
    expLight.position.copy(enemy.group.position).add(new THREE.Vector3(0, 1.5, 0));
    scene.add(expLight);
    setTimeout(() => scene.remove(expLight), 300);

    updateHUD();
    if (enemiesRemaining <= 0 && !demoMode) {
      setTimeout(() => showLevelClear(), 1000);
    }
  }
}

function damagePlayer(damage) {
  if (player.invincible > 0) return;
  player.health -= damage;
  player.invincible = 0.5;
  playSound('player_hit', timeScale);

  // Damage overlay
  const overlay = document.getElementById('damage-overlay');
  overlay.style.opacity = '1';
  setTimeout(() => overlay.style.opacity = '0', 200);

  updateHUD();

  if (player.health <= 0) {
    showDeath();
  }
}

// ─── PLAYER MOVEMENT ───
function updatePlayer(dt) {
  const scaledDt = dt * timeScale;

  // Invincibility
  if (player.invincible > 0) player.invincible -= dt;

  // Shoot cooldown
  if (player.shootCooldown > 0) player.shootCooldown -= dt;

  // Recoil recovery
  if (player.recoil > 0) {
    player.recoil *= 0.85;
    if (player.recoil < 0.001) player.recoil = 0;
  }

  // Movement input
  const moveDir = new THREE.Vector3();
  if (player.moveForward) moveDir.z -= 1;
  if (player.moveBackward) moveDir.z += 1;
  if (player.moveLeft) moveDir.x -= 1;
  if (player.moveRight) moveDir.x += 1;
  moveDir.applyAxisAngle(new THREE.Vector3(0, 1, 0), player.yaw);
  moveDir.normalize();

  // Calculate movement speed for time scaling
  const moveSpeed = moveDir.length();
  const actualMoveSpeed = moveSpeed * player.speed;

  // Apply movement
  if (moveSpeed > 0.01) {
    player.position.x += moveDir.x * actualMoveSpeed * dt;
    player.position.z += moveDir.z * actualMoveSpeed * dt;

    // Head bob
    player.bobPhase += dt * 10;
  }

  // Clamp to world
  player.position.x = Math.max(worldBounds.minX + 1, Math.min(worldBounds.maxX - 1, player.position.x));
  player.position.z = Math.max(worldBounds.minZ + 1, Math.min(worldBounds.maxZ - 1, player.position.z));

  // Camera position
  camera.position.copy(player.position);
  camera.position.y += Math.sin(player.bobPhase) * 0.03 * moveSpeed;

  // Camera rotation
  camera.rotation.order = 'YXZ';
  camera.rotation.y = player.yaw;
  camera.rotation.x = player.pitch;

  // Gun position
  if (gunGroup) {
    gunGroup.position.set(0.25, -0.22 - Math.sin(player.bobPhase) * 0.02 * moveSpeed, -0.35);
    gunGroup.rotation.x = -player.recoil;
    gunGroup.rotation.z = -player.recoil * 0.3;
  }

  // Time scale calculation
  const motionMagnitude = moveSpeed + Math.abs(player.yaw * 0.01) + Math.abs(player.pitch * 0.01);
  targetTimeScale = 0.05 + motionMagnitude * 0.95;
  targetTimeScale = Math.min(1.0, targetTimeScale);

  // Smooth time scale transition
  timeScale += (targetTimeScale - timeScale) * 0.1;

  // Update demo bot if active
  if (demoMode && demoBotActive) {
    updateDemoBot(dt);
  }
}

// ─── DEMO BOT ───
function updateDemoBot(dt) {
  const scaledDt = dt * timeScale;

  switch (demoBotState) {
    case 'patrol':
      if (demoBotTarget === null || demoBot.position.distanceTo(demoBotTarget) < 1) {
        demoBotTarget = new THREE.Vector3(
          (Math.random() - 0.5) * 25,
          0,
          (Math.random() - 0.5) * 25
        );
      }
      const toTarget = demoBotTarget.clone().sub(demoBot.position);
      demoBot.position.add(toTarget.normalize().multiplyScalar(scaledDt * 2));
      demoBot.rotation.y = Math.atan2(toTarget.x, toTarget.z);
      break;

    case 'hunt':
      if (demoBotTarget) {
        const toPlayer = demoBotTarget.clone().sub(demoBot.position);
        demoBot.rotation.y = Math.atan2(toPlayer.x, toPlayer.z);

        const dist = demoBot.position.distanceTo(demoBotTarget);
        if (dist > 8) {
          demoBot.position.add(toPlayer.normalize().multiplyScalar(scaledDt * 3));
        } else if (dist < 5) {
          demoBot.position.add(toPlayer.normalize().multiplyScalar(-scaledDt * 2));
        }

        // Strafe
        const strafe = new THREE.Vector3(-toPlayer.z, 0, toPlayer.x);
        demoBot.position.add(strafe.multiplyScalar(scaledDt * 1.5));

        // Shoot
        demoBotShootTimer += scaledDt;
        if (demoBotShootTimer > 1.5 && dist < 15) {
          demoBotShootTimer = 0;
          // Simulate bot shooting - create projectile toward player
          const projGeo = new THREE.SphereGeometry(0.08, 8, 8);
          const projMat = new THREE.MeshStandardMaterial({
            color: 0x4488ff, emissive: 0x4488ff, emissiveIntensity: 3,
          });
          const projMesh = new THREE.Mesh(projGeo, projMat);
          projMesh.position.copy(demoBot.position).add(new THREE.Vector3(0, 1.5, 0));
          scene.add(projMesh);
          const pLight = new THREE.PointLight(0x4488ff, 2, 6);
          projMesh.add(pLight);
          const dir = player.position.clone().sub(projMesh.position).normalize();
          dir.x += (Math.random() - 0.5) * 0.2;
          dir.y += (Math.random() - 0.5) * 0.1;
          dir.z += (Math.random() - 0.5) * 0.2;
          dir.normalize();
          projectiles.push({
            mesh: projMesh, light: pLight,
            velocity: dir.multiplyScalar(10),
            life: 4, trailTimer: 0,
          });
          playSound('shoot', timeScale);
        }
      }
      break;

    case 'dodge':
      demoBotDodgeTimer += scaledDt;
      if (demoBotDodgeTimer > 0.5) {
        demoBotDodgeTimer = 0;
        demoBotState = 'hunt';
      }
      // Dodge perpendicular to incoming threat
      const dodgeDir = new THREE.Vector3(
        (Math.random() - 0.5) * 2,
        0,
        (Math.random() - 0.5) * 2
      ).normalize();
      demoBot.position.add(dodgeDir.multiplyScalar(scaledDt * 4));
      break;
  }

  // Clamp bot position
  demoBot.position.x = Math.max(worldBounds.minX + 1, Math.min(worldBounds.maxX - 1, demoBot.position.x));
  demoBot.position.z = Math.max(worldBounds.minZ + 1, Math.min(worldBounds.maxZ - 1, demoBot.position.z));

  // Check if bot should hunt player
  const distToPlayer = demoBot.position.distanceTo(player.position);
  if (distToPlayer < 15 && checkLineOfSight(demoBot.position, player.position)) {
    demoBotState = 'hunt';
    demoBotTarget = player.position.clone();
  } else if (distToPlayer > 20) {
    demoBotState = 'patrol';
  }
}

// Create demo bot
let demoBot;
function createDemoBot() {
  demoBot = new THREE.Group();
  const mat = new THREE.MeshStandardMaterial({ color: 0x4488ff, roughness: 0.5, metalness: 0.3 });
  const torso = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.35, 0.8, 8), mat);
  torso.position.y = 1.3;
  demoBot.add(torso);
  const head = new THREE.Mesh(new THREE.SphereGeometry(0.2, 8, 8), mat);
  head.position.y = 1.9;
  demoBot.add(head);
  const eye = new THREE.Mesh(new THREE.SphereGeometry(0.05, 6, 6),
    new THREE.MeshStandardMaterial({ color: 0x4488ff, emissive: 0x4488ff, emissiveIntensity: 3 }));
  eye.position.set(0, 1.95, -0.17);
  demoBot.add(eye);
  demoBot.position.set(5, 0, 5);
  scene.add(demoBot);
}

// ─── HUD ───
function updateHUD() {
  // Health hearts
  const healthEl = document.getElementById('health');
  healthEl.innerHTML = '';
  for (let i = 0; i < maxHealth; i++) {
    const heart = document.createElement('span');
    heart.className = 'heart' + (i >= player.health ? ' lost' : '');
    heart.textContent = '♥';
    healthEl.appendChild(heart);
  }

  // Enemy count
  document.getElementById('enemy-count').textContent =
    `ENEMIES: ${enemiesRemaining} / ${totalEnemies}`;

  // Time dial
  document.getElementById('time-bar').style.width = (timeScale * 100) + '%';
}

function showLevelClear() {
  gameActive = false;
  document.exitPointerLock();
  const msg = document.getElementById('message');
  msg.style.display = 'block';
  msg.querySelector('h1').textContent = 'LEVEL CLEAR';
  msg.querySelector('h1').style.color = '#ffaa00';
  msg.querySelector('.sub').textContent = 'CLICK TO RESTART';
  document.addEventListener('click', restartGame, { once: true });
}

function showDeath() {
  gameActive = false;
  document.exitPointerLock();
  const msg = document.getElementById('message');
  msg.style.display = 'block';
  msg.querySelector('h1').textContent = 'YOU DIED';
  msg.querySelector('h1').style.color = '#ff2200';
  msg.querySelector('.sub').textContent = 'CLICK TO RESTART';
  document.addEventListener('click', restartGame, { once: true });
}

function restartGame() {
  document.getElementById('message').style.display = 'none';
  resetGameState();
  lockPointer();
}

function resetGameState() {
  player.health = maxHealth;
  player.position.set(0, 1.7, 0);
  player.velocity.set(0, 0, 0);
  player.invincible = 0;
  player.shootCooldown = 0;

  // Remove old enemies
  enemies.forEach(e => {
    if (e.group && e.group.parent) scene.remove(e.group);
  });

  // Remove old projectiles
  projectiles.forEach(p => {
    if (p.mesh.parent) scene.remove(p.mesh);
  });

  // Remove old particles
  particles.forEach(p => {
    if (p.mesh.parent) scene.remove(p.mesh);
  });

  // Remove trails
  trails.forEach(t => {
    if (t.mesh.parent) scene.remove(t.mesh);
  });

  enemies = [];
  projectiles = [];
  particles = [];
  trails = [];
  enemiesRemaining = 0;
  enemiesKilled = 0;
  timeScale = 0.05;
  targetTimeScale = 0.05;

  spawnEnemies();
  updateHUD();
  gameActive = true;
  lockPointer();
}

function lockPointer() {
  renderer.domElement.requestPointerLock();
}

// ─── INPUT ───
function setupInput() {
  document.addEventListener('keydown', (e) => {
    switch (e.code) {
      case 'KeyW': player.moveForward = true; break;
      case 'KeyS': player.moveBackward = true; break;
      case 'KeyA': player.moveLeft = true; break;
      case 'KeyD': player.moveRight = true; break;
    }
  });

  document.addEventListener('keyup', (e) => {
    switch (e.code) {
      case 'KeyW': player.moveForward = false; break;
      case 'KeyS': player.moveBackward = false; break;
      case 'KeyA': player.moveLeft = false; break;
      case 'KeyD': player.moveRight = false; break;
    }
  });

  document.addEventListener('mousemove', (e) => {
    if (document.pointerLockElement !== renderer.domElement) return;
    player.yaw -= e.movementX * 0.002;
    player.pitch -= e.movementY * 0.002;
    player.pitch = Math.max(-Math.PI / 2.2, Math.min(Math.PI / 2.2, player.pitch));
  });

  document.addEventListener('mousedown', (e) => {
    if (e.button === 0 && gameActive) {
      playerShoot();
    }
  });

  document.addEventListener('pointerlockchange', () => {
    if (document.pointerLockElement !== renderer.domElement && gameActive) {
      // Pause or keep going
    }
  });

  // Demo toggle
  document.getElementById('demo-toggle').addEventListener('click', (e) => {
    demoMode = !demoMode;
    e.target.textContent = 'DEMO: ' + (demoMode ? 'ON' : 'OFF');
    if (demoMode) {
      createDemoBot();
      demoBotActive = true;
      demoBotState = 'patrol';
      demoBotTarget = new THREE.Vector3(0, 0, 0);
    } else {
      if (demoBot && demoBot.parent) scene.remove(demoBot);
      demoBotActive = false;
    }
  });

  // Start screen
  document.getElementById('start-screen').addEventListener('click', () => {
    document.getElementById('start-screen').style.display = 'none';
    initAudio();
    resetGameState();
  });
}

// ─── MAIN LOOP ───
function animate() {
  requestAnimationFrame(animate);

  const dt = Math.min(clock.getDelta(), 0.05); // Cap delta time

  // Update rain
  if (window._rain) {
    const positions = window._rain.geometry.attributes.position.array;
    for (let i = 1; i < positions.length; i += 3) {
      positions[i] -= dt * (8 + timeScale * 12);
      if (positions[i] < 0) positions[i] = 20;
    }
    window._rain.geometry.attributes.position.needsUpdate = true;
  }

  if (gameActive) {
    updatePlayer(dt);
    updateEnemies(dt);
    updateProjectiles(dt);
    updateParticles(dt);
    updateAmbient(timeScale);
    updateHUD();

    // Update vignette grain time based on motion
    vignettePass.uniforms.grainTime.value += dt * (1 + timeScale * 5);

    // Bloom intensity based on time scale
    bloomPass.strength = 0.8 + timeScale * 0.8;

    // Fog density based on time scale (more fog when frozen)
    scene.fog.density = 0.018 + (1 - timeScale) * 0.015;

    // Tone mapping exposure based on time scale
    renderer.toneMappingExposure = 0.8 + timeScale * 0.4;

    // Color grade shift based on time scale
    vignettePass.uniforms.darkness.value = 1.0 + (1 - timeScale) * 0.5;
  }

  composer.render();
}

// ─── INIT ───
function init() {
  initScene();
  buildArena();
  buildGun();
  spawnEnemies();
  setupInput();
  updateHUD();
  animate();
}

init();
</script>
</body>
</html>

Same prompt, other models

8 more
Compare side by side

One email when a new model lands on the board or in the showcase. Unsubscribe anytime.