This Minecraft remake uses Python simulation and ModernGL rendering. Start the server from the project root:
+
python games/prototype/bossbench/play_server.py
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Connecting to local server…
+
Every 200 ms, your input becomes a standard action packet: six 33 ms key windows, each with up to four keys plus mouse movement. The packet goes to the same simulation as make_policy_env. Pausing stops the world. Replays use bossbench/policy-replay@1; import simulates each packet again and checks the final-state hash. Scripted Demo is a reference controller that reads internal state, not a trained model; it does not start RL training.
+
+
+
+
+
+
+
+
diff --git a/environments/games/web/games/minecraft_remake/manifest.json b/environments/games/web/games/minecraft_remake/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..b56ce3c6ed48e5eefb5170c2b5cda5ae09d63ca2
--- /dev/null
+++ b/environments/games/web/games/minecraft_remake/manifest.json
@@ -0,0 +1,79 @@
+{
+ "schema": "bossbench/game-manifest@1",
+ "engine": "python",
+ "game": "minecraft_remake",
+ "title": "Minecraft: Voxel Arena",
+ "dimension": "3d",
+ "native_hz": 60,
+ "max_seconds": {
+ "3d/minecraft_iron_golem": 300,
+ "3d/minecraft_zombie": 90,
+ "3d/minecraft_ender_dragon": 300,
+ "3d/minecraft_wither": 300,
+ "3d/minecraft_warden": 300,
+ "3d/minecraft_skeleton": 300,
+ "3d/minecraft_zombie_leader": 300
+ },
+ "renderer": "moderngl",
+ "rules": "minecraft-arena@7",
+ "tiers": {
+ "easy": 0.0,
+ "normal": 0.5,
+ "hard": 1.0
+ },
+ "tiers_source": "prototype/bossbench/mc4d.py TIERS (read by bossbench.make_policy_env and the play server)",
+ "cases": [
+ "3d/minecraft_iron_golem",
+ "3d/minecraft_ender_dragon",
+ "3d/minecraft_wither",
+ "3d/minecraft_warden",
+ "3d/minecraft_skeleton",
+ "3d/minecraft_zombie_leader"
+ ],
+ "retired_cases": {
+ "3d/minecraft_zombie": "2026-11-10 user request: remove the green-skinned grappler. It remains registered in FORMAL_CASES under frozen @4 rules, but is excluded from the benchmark list (scope.BENCH_RETIRED). Its media was moved to archived history."
+ },
+ "formal_cases": [
+ "3d/minecraft_iron_golem",
+ "3d/minecraft_zombie",
+ "3d/minecraft_ender_dragon",
+ "3d/minecraft_wither"
+ ],
+ "formal_note": "FORMAL_CASES (prototype/bossbench/scope.py): their rules stay exactly @4 (difficulty tables, behaviour, arena, kit, time limit, observation layout); d = 0.5 of each was evaluated 16 times in reports/mc-bow-comparison-20261020. 3d/minecraft_zombie stays exactly as in @4 and is reported \"uncalibrated\" against the tier windows (1.4-3.2 s fights); the user decided on 2026-11-04 to keep it at @4 (no re-calibration).",
+ "round_20261102_scenes": [
+ "3d/minecraft_iron_golem",
+ "3d/minecraft_ender_dragon",
+ "3d/minecraft_wither"
+ ],
+ "round_20261103_scenes": [
+ "3d/minecraft_warden",
+ "3d/minecraft_skeleton",
+ "3d/minecraft_zombie_leader"
+ ],
+ "kits": {
+ "diamond": "diamond sword 7 + full diamond armor 20 / 8 (flung giant, green-skinned grappler, purple-breathing flyer, triple-headed floating cannon, shockwave beast)",
+ "iron": "iron sword 6 + full iron armor 15 / 0 (mobile archer, summoner)",
+ "source": "prototype/bossbench/mc4d.py KITS / SCENE_KIT (the same on every tier)"
+ },
+ "options": {
+ "weapon": [
+ "sword",
+ "bow"
+ ],
+ "camera": [
+ "first",
+ "third"
+ ]
+ },
+ "play_page": "web/games/minecraft_remake/index.html",
+ "server": "prototype/bossbench/play_server.py",
+ "launch": "powershell -NoProfile -ExecutionPolicy Bypass -File web/games/minecraft_remake/run_server.ps1",
+ "url": "http://127.0.0.1:8765/",
+ "simulation": [
+ "prototype/bossbench/mc4d.py",
+ "prototype/bossbench/mcskin.py",
+ "prototype/bossbench/rig.py"
+ ],
+ "scripted_controller": "bossbench.mc_scripted.scripted(case) -> packet text (prototype/bossbench/mc_scripted.py)",
+ "golden": "prototype/tests/mc4d_golden_20261107_arena7.json (rules minecraft-arena@7); frozen guards: mc4d_golden_20261103_arena6.json (@6), mc4d_golden_20261103.json (@5), mc4d_golden_20261102.json (@4), mc4d_golden_20261031.json (@3), mc4d_golden.json (@1, MD5 e778e5d30f6941ab44a91c86da8bd115)"
+}
diff --git a/environments/games/web/games/minecraft_remake/play.js b/environments/games/web/games/minecraft_remake/play.js
new file mode 100644
index 0000000000000000000000000000000000000000..61f3eafee5055c40b294fa984737d8c5bd755019
--- /dev/null
+++ b/environments/games/web/games/minecraft_remake/play.js
@@ -0,0 +1,338 @@
+/* Minecraft remake play page client: samples real keyboard/mouse input into standard 200 ms packets
+ (6 hold sets of <= 4 keys + mouse dx dy dz), sends them to the local Python play server, and plays back the
+ 6 frames per packet that the real ModernGL renderer returns. The page itself simulates nothing. */
+(function () {
+ 'use strict';
+ const $ = s => document.querySelector(s);
+ const KEYS = ['W', 'A', 'S', 'D', 'Space', 'Shift', 'J', 'K', 'L', 'Q', 'E', 'R', 'LMB', 'RMB'];
+ const CODE = {KeyW: 'W', KeyA: 'A', KeyS: 'S', KeyD: 'D', Space: 'Space', ShiftLeft: 'Shift', ShiftRight: 'Shift',
+ KeyJ: 'J', KeyK: 'RMB'};
+ const SUB_MS = 200 / 6;
+ const view = $('#view'), capture = $('#capture');
+ let API = '', sid = null, meta = null, state = null, running = false, mode = 'idle'; // idle | play | demo | replay
+ let down = new Set(), taps = new Set(), mouse = [0, 0, 0], subs = [], timer = null;
+ let queue = [], sending = false, clock0 = 0, subsDone = 0;
+ let frames = [], lastShown = 0, replayQueue = [], replayExpect = null, pending = false, epoch = 0;
+
+ function status(text) { $('#status').textContent = text; }
+ function overlay(text) {
+ $('#overlay').hidden = !text;
+ $('#overlay-text').textContent = text || '';
+ }
+
+ // ------------------------------------------------------------------ server connection
+ async function api(path, body) {
+ const opt = body === undefined ? {} : {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)};
+ const r = await fetch(API + path, opt);
+ const data = await r.json();
+ if (!r.ok) throw Error(data.error || r.statusText);
+ return data;
+ }
+ async function connect() {
+ const bases = location.protocol.startsWith('http') && location.port === '8765' ? [''] :
+ ['', 'http://127.0.0.1:8765'];
+ for (const base of bases) {
+ try {
+ const r = await fetch(base + '/api/meta', {cache: 'no-store'});
+ if (!r.ok) continue;
+ meta = await r.json();
+ API = base;
+ $('#offline').hidden = true;
+ $('#rules').textContent = meta.rules;
+ const sel = $('#case');
+ if (!sel.options.length) for (const c of meta.cases) {
+ const o = document.createElement('option');
+ o.value = c.id; o.textContent = c.name; sel.appendChild(o);
+ }
+ tierControl();
+ $('#hz').textContent = meta.native_hz + ' Hz';
+ status('Connected to local server (' + meta.rules + ' · ' + meta.native_hz + ' Hz). Select a boss, then click Start Challenge.');
+ overlay('Select a boss to start');
+ return true;
+ } catch (e) { /* try next */ }
+ }
+ $('#offline').hidden = false;
+ overlay('');
+ status('Could not connect. Start the local Python server using the command shown on screen.');
+ return false;
+ }
+ $('#retry').onclick = connect;
+
+ // ------------------------------------------------------------------ public difficulty: three tiers (2026-11-02)
+ // Rebuilt from the server's declaration (mc4d.TIERS via /api/meta), the same source make_policy_env reads, so the
+ // page can never offer a difficulty the public interface does not. Each option shows the meeting's target window.
+ function tierControl() {
+ const sel = $('#difficulty'), keep = sel.value || meta.default_tier;
+ if (!meta.tiers || !meta.tiers.length) return;
+ sel.textContent = '';
+ for (const t of meta.tiers) {
+ const o = document.createElement('option');
+ o.value = t.name; o.textContent = t.label + '(d=' + t.difficulty + ')';
+ o.selected = t.name === keep; sel.appendChild(o);
+ }
+ tierHint();
+ }
+ function tierInfo(name) { return meta && meta.tiers ? meta.tiers.find(t => t.name === name) : null; }
+ function tierHint() {
+ const t = tierInfo($('#difficulty').value);
+ $('#tier-hint').textContent = t ? 'Reference script target: ' + t.target_seconds[0] + '–' + t.target_seconds[1] + ' seconds to win' : '';
+ }
+ $('#difficulty').onchange = tierHint;
+
+ // ------------------------------------------------------------------ input sampling
+ function heldNow() {
+ const all = new Set([...down, ...taps]);
+ taps.clear();
+ const out = [];
+ for (const k of ['W', 'S', 'A', 'D']) if (all.has(k)) { out.push(k); break; }
+ for (const k of ['Space', 'Shift', 'LMB', 'J', 'RMB']) if (all.has(k) && out.length < 4) out.push(k);
+ return out;
+ }
+ function packetText(sets, m) {
+ const mx = m.map((v, i) => Math.max(i === 2 ? -5 : -1000, Math.min(i === 2 ? 5 : 1000, Math.round(v))));
+ return '<|action_start|> ' + mx.join(' ') + ' ; ' + sets.map(s => s.join(',')).join(' ; ') + ' <|action_end|>';
+ }
+ function takePacket() {
+ while (subs.length < 6) subs.push(heldNow());
+ const p = packetText(subs, mouse);
+ subs = []; mouse = [0, 0, 0];
+ return p;
+ }
+ // Wall-clock scheduler: one hold set per 33.3 ms of real time, whatever the timer jitter, so the world runs at
+ // real speed; packets go out in order, one request at a time (a lagging server gets up to 5 per request).
+ function sampleClock() {
+ if (!running || mode !== 'play') return;
+ const due = Math.floor((performance.now() - clock0) / SUB_MS);
+ if (due - subsDone > 18) subsDone = due - 6; // tab stalled: drop the backlog instead of a burst
+ while (subsDone < due) {
+ if (arrows.has('ArrowLeft')) mouse[0] -= 7;
+ if (arrows.has('ArrowRight')) mouse[0] += 7;
+ if (arrows.has('ArrowUp')) mouse[1] -= 4;
+ if (arrows.has('ArrowDown')) mouse[1] += 4;
+ subs.push(heldNow());
+ subsDone++;
+ if (subs.length >= 6) queue.push(takePacket());
+ }
+ pump();
+ }
+ async function pump() {
+ if (sending || !queue.length || !sid) return;
+ sending = true;
+ const batch = queue.splice(0, 5), my = epoch;
+ try {
+ const r = await api('/api/step', {sid, packets: batch, frames: true});
+ if (my === epoch) accept(r);
+ } catch (e) { status('Server error: ' + e.message); pause(); }
+ finally { sending = false; if (queue.length && my === epoch) pump(); }
+ }
+ function lock() {
+ try { const p = capture.requestPointerLock && capture.requestPointerLock(); if (p && p.catch) p.catch(() => {}); } catch (e) { /* headless */ }
+ }
+ document.addEventListener('pointerlockchange', () => {
+ if (document.pointerLockElement !== capture && running && mode === 'play') {
+ pause(); status('Mouse unlocked (Esc) · Paused. Click Resume to continue.');
+ }
+ });
+ const arrows = new Set();
+ window.addEventListener('keydown', e => {
+ if (['INPUT', 'SELECT', 'TEXTAREA'].includes(document.activeElement.tagName)) return;
+ if (e.code === 'Escape' || e.code === 'KeyP') { if (running) pause(); return; }
+ if (e.code.startsWith('Arrow')) { arrows.add(e.code); e.preventDefault(); return; }
+ if (e.code === 'KeyQ' || e.code === 'Digit1' || e.code === 'Digit2') {
+ const want = e.code === 'Digit1' ? 'sword' : e.code === 'Digit2' ? 'bow' : null;
+ if (!want || (state && state.player.weapon !== want)) mouse[2] += 1;
+ e.preventDefault(); return;
+ }
+ const k = CODE[e.code];
+ if (k) { e.preventDefault(); down.add(k); taps.add(k); }
+ });
+ window.addEventListener('keyup', e => {
+ if (e.code.startsWith('Arrow')) arrows.delete(e.code);
+ const k = CODE[e.code];
+ if (k) down.delete(k);
+ });
+ capture.addEventListener('contextmenu', e => e.preventDefault());
+ capture.addEventListener('pointerdown', e => {
+ capture.focus();
+ if (running && mode === 'play' && document.pointerLockElement !== capture) lock();
+ const k = e.button === 2 ? 'RMB' : e.button === 0 ? 'LMB' : null;
+ if (k) { down.add(k); taps.add(k); }
+ e.preventDefault();
+ });
+ window.addEventListener('pointerup', e => { down.delete(e.button === 2 ? 'RMB' : 'LMB'); });
+ window.addEventListener('mousemove', e => {
+ if (document.pointerLockElement === capture) { mouse[0] += e.movementX; mouse[1] += e.movementY; }
+ else if (e.buttons && e.target === capture) { mouse[0] += e.movementX; mouse[1] += e.movementY; }
+ });
+ capture.addEventListener('wheel', e => { e.preventDefault(); mouse[2] += e.deltaY > 0 ? 1 : -1; }, {passive: false});
+ document.querySelectorAll('[data-key]').forEach(b => {
+ b.onpointerdown = e => { e.preventDefault(); b.setPointerCapture(e.pointerId); down.add(b.dataset.key); taps.add(b.dataset.key); };
+ b.onpointerup = b.onpointercancel = () => down.delete(b.dataset.key);
+ });
+ document.querySelectorAll('[data-wheel]').forEach(b => { b.onclick = () => { mouse[2] += 1; }; });
+ function releaseAll() { down.clear(); taps.clear(); arrows.clear(); }
+ window.addEventListener('blur', () => { releaseAll(); if (running && mode === 'play') { pause(); status('Window lost focus · Paused. Click Resume to continue.'); } });
+ document.addEventListener('visibilitychange', () => { if (document.hidden) { releaseAll(); if (running) pause(); } });
+
+ // ------------------------------------------------------------------ stepping and frames
+ function accept(r) {
+ state = r.state || r;
+ if (r.frames && r.frames.length) {
+ if (frames.length > 12) frames = frames.slice(-6); // keep latency bounded
+ frames.push(...r.frames);
+ }
+ panel();
+ if (state.outcome) finish();
+ }
+ function showFrames(now) {
+ if (frames.length && now - lastShown >= SUB_MS - 2) {
+ view.src = frames.shift();
+ lastShown = now;
+ }
+ requestAnimationFrame(showFrames);
+ }
+ requestAnimationFrame(showFrames);
+ async function still() {
+ if (!sid) return;
+ const r = await api('/api/still', {sid});
+ frames = [r.frame];
+ state = r.state; panel();
+ }
+ function panel() {
+ if (!state) return;
+ const p = state.player, b = state.boss;
+ $('#time').textContent = state.t.toFixed(1) + ' / ' + state.max_seconds + ' s';
+ const o = state.options || {}, tier = tierInfo(o.resolved_from_tier);
+ $('#tier').textContent = tier ? tier.label + ' · d=' + o.difficulty : 'd=' + o.difficulty;
+ $('#php').textContent = p.hp.toFixed(1) + ' / ' + p.max_hp + (p.wither_effect_s > 0 ? ' (Wither damage for ' + p.wither_effect_s.toFixed(0) + 's)' : '');
+ $('#wpn').textContent = (p.kit === 'iron' ? 'Iron ' : 'Diamond ') + (p.weapon === 'sword' ? 'sword ' + Math.round(p.attack_charge * 100) + '%' :
+ 'Bow ' + (p.bow_drawing ? Math.round(p.bow_charge * 100) + '%' : 'ready') + ' · Hits ' + p.arrows_hit + '/' + p.arrows_fired);
+ $('#bname').textContent = b.name;
+ $('#bhp').textContent = b.hp.toFixed(1) + ' / ' + b.max_hp;
+ $('#bphase').textContent = b.phase + (b.armored ? ' · Half-health armor' : '') + (b.crystals !== null ? ' · Crystals ' + b.crystals : '') +
+ (b.minions !== null && b.minions !== undefined ? ' · Minions ' + b.minions : '') +
+ (b.darkness_s ? ' · Darkness ' + b.darkness_s.toFixed(0) + 's' : '');
+ }
+ function finish() {
+ stopLoop();
+ // Show the terminal frame at once: frames play back ~0.2 s behind the simulation, so the result overlay would
+ // otherwise sit on a frame where the boss still has health left.
+ if (frames.length) { view.src = frames[frames.length - 1]; frames = []; }
+ window.__bbOutcome = state.outcome; // read by web/tools/bench_media.py ui
+ const label = {win: 'Victory', loss: 'Failure', timeout: 'Time up'}[state.outcome] || state.outcome;
+ overlay(label + ' · ' + state.t.toFixed(2) + ' seconds');
+ if (mode === 'replay' && replayExpect) verifyReplay();
+ else status('Match over: ' + label + ' · ' + state.packets + ' action packets. You can export the replay.');
+ }
+
+ // ------------------------------------------------------------------ loop control
+ function stopLoop() { running = false; clearInterval(timer); timer = null; $('#pause').textContent = 'Resume'; }
+ function startLoop() {
+ if (!sid || (state && state.outcome)) return;
+ running = true; $('#pause').textContent = 'Pause'; overlay('');
+ clearInterval(timer);
+ if (mode === 'play') { subs = []; mouse = [0, 0, 0]; clock0 = performance.now(); subsDone = 0; timer = setInterval(sampleClock, 8); }
+ else timer = setInterval(tickAuto, 200);
+ }
+ function pause() { stopLoop(); releaseAll(); if (document.pointerLockElement) document.exitPointerLock(); overlay(state && state.outcome ? $('#overlay-text').textContent : 'Paused'); }
+ async function tickAuto() {
+ if (pending || !running) return;
+ pending = true;
+ const my = epoch;
+ try {
+ if (mode === 'demo') {
+ const r = await api('/api/scripted', {sid, n: 1, frames: true});
+ if (my === epoch) accept(r);
+ } else if (mode === 'replay') {
+ if (!replayQueue.length) { if (state && !state.outcome) { stopLoop(); verifyReplay(); } }
+ else { const r = await api('/api/step', {sid, packets: [replayQueue.shift()], frames: true}); if (my === epoch) accept(r); }
+ }
+ } catch (e) { status('Server error: ' + e.message); stopLoop(); }
+ finally { pending = false; }
+ }
+ async function newSession(caseId, useMode, tier) {
+ if (!meta && !(await connect())) return false;
+ epoch++; stopLoop(); frames = []; replayQueue = []; replayExpect = null; queue = []; window.__bbOutcome = null;
+ if (sid) api('/api/close', {sid}).catch(() => {});
+ const body = {case: caseId || $('#case').value, seed: Number($('#seed').value), tier: tier || $('#difficulty').value,
+ weapon: $('#weapon').value, camera: $('#camera').value};
+ $('#case').value = body.case;
+ $('#difficulty').value = body.tier; tierHint();
+ const r = await api('/api/new', body);
+ sid = r.sid; state = r.state; mode = useMode; panel();
+ await still();
+ return true;
+ }
+ $('#start').onclick = async () => {
+ try {
+ if (!(await newSession(null, 'play'))) return;
+ status('Match in progress: click the screen to lock the mouse (Esc unlocks and pauses). One action packet every 200 ms.');
+ capture.focus(); startLoop();
+ } catch (e) { status('Unable to start: ' + e.message); }
+ };
+ $('#pause').onclick = () => {
+ if (running) pause();
+ else if (sid && state && !state.outcome) { startLoop(); capture.focus(); if (mode === 'play') lock(); }
+ };
+ $('#step').onclick = async () => {
+ if (!sid || (state && state.outcome)) return;
+ if (running) pause();
+ overlay('Step');
+ const sets = Array.from({length: 6}, () => heldNow());
+ if (mode === 'demo') { accept(await api('/api/scripted', {sid, n: 1, frames: true})); }
+ else if (mode === 'replay') { if (replayQueue.length) accept(await api('/api/step', {sid, packets: [replayQueue.shift()], frames: true})); }
+ else { const p = packetText(sets, mouse); mouse = [0, 0, 0]; accept(await api('/api/step', {sid, packets: [p], frames: true})); }
+ };
+ async function demo(caseId, tier) {
+ if (!(await newSession(caseId, 'demo', tier))) return false;
+ status('Scripted Demo: a reference controller reads internal state and emits valid 200 ms action packets.');
+ startLoop();
+ return true;
+ }
+ $('#demo').onclick = () => demo(null).catch(e => status('Demo failed: ' + e.message));
+ $('#export').onclick = async () => {
+ if (!sid) { status('No match is available to export yet.'); return; }
+ const data = await api('/api/replay?sid=' + sid);
+ const blob = new Blob([JSON.stringify(data, null, 1)], {type: 'application/json'});
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ a.download = data.case_id.replace('/', '__') + '-seed' + data.engine_seed + '.replay.json';
+ a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000);
+ status('Exported ' + data.steps + ' action packets (' + data.rules + ') · Final-state hash: ' + data.final_hash.slice(0, 12));
+ };
+ $('#import').onclick = () => $('#file').click();
+ $('#file').onchange = async e => {
+ const file = e.target.files[0]; e.target.value = '';
+ if (!file) return;
+ try {
+ if (file.size > 12e6) throw Error('Replay must be 12 MB or smaller');
+ await importReplay(JSON.parse(await file.text()));
+ } catch (err) { status('Import failed: ' + err.message); }
+ };
+ async function importReplay(data) {
+ if (!meta && !(await connect())) return;
+ epoch++; stopLoop(); frames = [];
+ const r = await api('/api/import', {replay: data});
+ if (sid) api('/api/close', {sid}).catch(() => {});
+ sid = r.sid; state = r.state; mode = 'replay'; panel();
+ replayQueue = data.packets.slice(); replayExpect = r.expect;
+ $('#case').value = data.case_id;
+ await still();
+ status('Replay rules verified (' + data.rules + ') · Playing back ' + replayQueue.length + ' action packets…');
+ startLoop();
+ }
+ async function verifyReplay() {
+ const v = await api('/api/verify', {sid});
+ const ok = v.final_hash === replayExpect.final_hash && v.outcome === replayExpect.outcome && v.ticks === replayExpect.ticks;
+ status('Replay finished: ' + ({win: 'Victory', loss: 'Failure', timeout: 'Time up'}[v.outcome] || 'Replay ended before the match concluded') + ' · ' + v.ticks + ' ticks · ' + (ok ? 'Final-state hash matches ✓' : 'Final state differs from replay ✗ (' + v.final_hash.slice(0, 10) + ' vs ' + String(replayExpect.final_hash).slice(0, 10) + ')'));
+ replayExpect = null;
+ }
+
+ // ------------------------------------------------------------------ harness hook (web/tools/bench_media.py ui)
+ window.bossbenchUI = {
+ demo: (caseId, tier) => demo(caseId, tier),
+ start: (caseId, tier) => newSession(caseId, 'play', tier).then(() => { startLoop(); return true; }),
+ state: () => state, connected: () => !!meta,
+ };
+ connect();
+})();
diff --git a/environments/games/web/games/minecraft_remake/style.css b/environments/games/web/games/minecraft_remake/style.css
new file mode 100644
index 0000000000000000000000000000000000000000..44bae1e3b5b021f240b86cb2bcba75afd399786f
--- /dev/null
+++ b/environments/games/web/games/minecraft_remake/style.css
@@ -0,0 +1,44 @@
+:root{color-scheme:dark;--paper:#ece6d6;--muted:#a7b3a2;--accent:#8fd16a;--bg:#1b1f17;--panel:#262c21;--edge:#4a5940;--warn:#e7b35d}
+*{box-sizing:border-box}
+body{margin:0;background:var(--bg) radial-gradient(circle at 20% -10%,#2f3a26 0,transparent 55%);color:var(--paper);font:15px/1.6 'Segoe UI','Microsoft YaHei',sans-serif}
+main{max-width:1180px;margin:auto;padding:24px 24px 40px}
+header{display:flex;gap:24px;align-items:baseline;justify-content:space-between;margin-bottom:18px}
+h1{font-family:Georgia,'Microsoft YaHei',serif;font-size:29px;font-weight:600;line-height:1.3;margin:6px 0;letter-spacing:.5px}
+header p{margin:0;color:var(--muted);font-size:13px}
+code{font-family:Consolas,monospace;font-size:12px;color:var(--accent)}
+a{color:var(--accent)}
+a:focus-visible,button:focus-visible,input:focus-visible,select:focus-visible,#capture:focus-visible{outline:3px solid var(--accent);outline-offset:3px}
+.layout{display:grid;grid-template-columns:minmax(0,854px) 240px;gap:20px}
+.stage{position:relative;align-self:start;border:2px solid #10130d;box-shadow:0 0 0 1px var(--edge);background:#0b0d09;aspect-ratio:854/480}
+#view{display:block;width:100%;height:100%;image-rendering:pixelated;user-select:none}
+#capture{position:absolute;inset:0;cursor:crosshair;touch-action:none}
+#overlay{pointer-events:none;position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#0d110a55}
+#overlay[hidden]{display:none}
+#overlay div{padding:12px 25px;background:#141a10ee;text-align:center;border:2px solid var(--edge);font-size:22px;font-family:Georgia,'Microsoft YaHei',serif}
+#offline{position:absolute;inset:0;display:flex;flex-direction:column;justify-content:center;padding:28px 40px;background:#12160fef;font-size:14px}
+#offline[hidden]{display:none}
+#offline h2{margin:0 0 8px;font-size:20px;color:var(--warn)}
+#offline pre{white-space:pre-wrap;background:#0a0c08;border:1px solid var(--edge);padding:10px 12px;font:13px Consolas,monospace;color:#d8f0c4}
+.toolbar{display:flex;flex-wrap:wrap;gap:9px;padding:12px;background:var(--panel);border:1px solid var(--edge);border-top:0}
+button,select,input{font:inherit;border:1px solid var(--edge);border-radius:2px;background:#30382a;color:var(--paper);padding:7px 10px}
+button{cursor:pointer;box-shadow:inset 0 -3px 0 #1d2318}
+button:hover{border-color:var(--accent)}
+button.primary{background:#5d8f3c;color:#0f140b;font-weight:700;box-shadow:inset 0 -3px 0 #3d6524}
+select,input[type=number]{width:100%}
+aside label{display:block;margin:12px 0 5px;color:var(--muted);font-size:13px}
+.hint{margin:5px 0 0;color:var(--muted);font-size:12px}
+aside h2{font-size:17px;margin:18px 0 10px}
+aside>div:first-child h2{margin-top:0}
+.panel{margin-top:16px;padding:10px 12px;background:var(--panel);border:1px solid var(--edge)}
+.row{display:flex;justify-content:space-between;gap:10px;font-size:13px;color:var(--muted)}
+.row b{color:var(--paper);font-weight:600;text-align:right}
+dl{margin:8px 0}
+dt{color:var(--accent);font-family:Consolas,monospace;font-size:12px}
+dd{margin:0 0 10px;font-size:13px;color:var(--muted)}
+#status{min-height:28px;margin:10px 0;color:var(--warn);font-size:13px;overflow-wrap:anywhere}
+.note{color:var(--muted);font-size:13px}
+.mobile{display:none;gap:6px;flex-wrap:wrap;padding:10px;background:var(--panel);border:1px solid var(--edge);border-top:0}
+.mobile button{flex:1 1 22%;padding:12px 4px}
+footer{border-top:1px solid var(--edge);margin-top:25px;padding-top:14px;display:flex;gap:18px;flex-wrap:wrap;font-size:13px}
+@media (max-width:900px){.layout{grid-template-columns:1fr}main{padding:14px}header{flex-direction:column;gap:6px}.mobile{display:flex}}
+@media (pointer:coarse){.mobile{display:flex}}
diff --git a/environments/games/web/games/nfsmw_remake/compact_actions.json b/environments/games/web/games/nfsmw_remake/compact_actions.json
new file mode 100644
index 0000000000000000000000000000000000000000..248e057098e2b89933c8ac97b286c905e54fb338
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/compact_actions.json
@@ -0,0 +1,269 @@
+{
+ "schema": "bossbench/compact-actions@1",
+ "game": "nfsmw_remake",
+ "version": "nfsmw-compact@1",
+ "note": "Four heads, 4 x 13 x 2 x 6 = 624 actions, each held for one 200 ms packet (6 sub-steps of 2 native ticks). No mouse: this game reads none. Pedal and steering are duty cycles over the 6 sub-steps because the car model integrates them: the wheel slews towards the key held and back to centre at the same rate (nfscore.js carStep), so a steering key held for 3 of 6 sub-steps keeps the current angle, 4 or 6 winds it on, 2 lets it come back slowly, none returns it to centre. Options chosen from the reference controller (harness/duty_stats.js: 16001 packets, all six events x three tiers x seeds 1-2) and tested by projecting every reference packet onto this set (harness/compact_sim.js, the same projection as compact.py): versions with 11 steering options lost speed-trap hard 4->2 and the final normal 3->2; the 2/6 ease options brought them back.",
+ "heads": [
+ {
+ "name": "pedal",
+ "options": [
+ {
+ "label": "none"
+ },
+ {
+ "label": "throttle_light",
+ "note": "the reference's corner exit: drive force limited by the friction circle",
+ "subs": [
+ [],
+ [],
+ [],
+ [],
+ [],
+ [
+ "W"
+ ]
+ ]
+ },
+ {
+ "label": "throttle",
+ "keys": [
+ "W"
+ ]
+ },
+ {
+ "label": "brake",
+ "keys": [
+ "S"
+ ]
+ }
+ ],
+ "note": "full throttle 65% of the reference packets, brake 16%, one sub-step in six 11% (corner exits, where the friction circle leaves little drive). A half throttle option was tried and dropped: it changed no result (v6 vs v7)."
+ },
+ {
+ "name": "steer",
+ "options": [
+ {
+ "label": "none"
+ },
+ {
+ "label": "left_tap",
+ "note": "drag series: A and D are lane changes on a press (modes_drag.js input), so one press per packet",
+ "tap": [
+ "A"
+ ]
+ },
+ {
+ "label": "left_ease",
+ "subs": [
+ [],
+ [],
+ [
+ "A"
+ ],
+ [],
+ [
+ "A"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "left_hold",
+ "subs": [
+ [
+ "A"
+ ],
+ [],
+ [
+ "A"
+ ],
+ [],
+ [
+ "A"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "left_hold_late",
+ "subs": [
+ [],
+ [
+ "A"
+ ],
+ [],
+ [
+ "A"
+ ],
+ [],
+ [
+ "A"
+ ]
+ ]
+ },
+ {
+ "label": "left_more",
+ "subs": [
+ [
+ "A"
+ ],
+ [
+ "A"
+ ],
+ [],
+ [
+ "A"
+ ],
+ [],
+ [
+ "A"
+ ]
+ ]
+ },
+ {
+ "label": "left_full",
+ "keys": [
+ "A"
+ ]
+ },
+ {
+ "label": "right_tap",
+ "tap": [
+ "D"
+ ]
+ },
+ {
+ "label": "right_ease",
+ "subs": [
+ [],
+ [],
+ [
+ "D"
+ ],
+ [],
+ [
+ "D"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "right_hold",
+ "subs": [
+ [
+ "D"
+ ],
+ [],
+ [
+ "D"
+ ],
+ [],
+ [
+ "D"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "right_hold_late",
+ "subs": [
+ [],
+ [
+ "D"
+ ],
+ [],
+ [
+ "D"
+ ],
+ [],
+ [
+ "D"
+ ]
+ ]
+ },
+ {
+ "label": "right_more",
+ "subs": [
+ [
+ "D"
+ ],
+ [
+ "D"
+ ],
+ [],
+ [
+ "D"
+ ],
+ [],
+ [
+ "D"
+ ]
+ ]
+ },
+ {
+ "label": "right_full",
+ "keys": [
+ "D"
+ ]
+ }
+ ],
+ "note": "left_tap / right_tap: one press per packet, the lane change of the drag series (modes_drag.js reads pressed A / D there). The duty options steer everywhere else."
+ },
+ {
+ "name": "nitrous",
+ "options": [
+ {
+ "label": "none"
+ },
+ {
+ "label": "nitrous",
+ "note": "only burns while the throttle is down (nfscore.js carStep)",
+ "keys": [
+ "Shift"
+ ]
+ }
+ ],
+ "note": "only burns while the throttle is down (nfscore.js carStep: engaged needs thr > 0)"
+ },
+ {
+ "name": "press",
+ "note": "J (slow motion), K / L (gears, drag series only) and R (reset) act on a press (pressed.has in game.js), so each is one press at the start of the packet. The handbrake is held, and it shares this head because a handbrake turn and a gear change or a reset are never wanted in the same 200 ms.",
+ "options": [
+ {
+ "label": "none"
+ },
+ {
+ "label": "shift_up",
+ "tap": [
+ "K"
+ ]
+ },
+ {
+ "label": "shift_down",
+ "tap": [
+ "L"
+ ]
+ },
+ {
+ "label": "slowmo",
+ "tap": [
+ "J"
+ ]
+ },
+ {
+ "label": "reset",
+ "tap": [
+ "R"
+ ]
+ },
+ {
+ "label": "handbrake",
+ "note": "held, not a press: carStep reads it every tick. The reference controller never uses it; kept because it is a basic control of the event. It shares this head with the single presses because a handbrake turn and a gear change or a reset are never wanted in the same 200 ms",
+ "keys": [
+ "Space"
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/environments/games/web/games/nfsmw_remake/cops.js b/environments/games/web/games/nfsmw_remake/cops.js
new file mode 100644
index 0000000000000000000000000000000000000000..7c4d43a227d7de5861b5401ab8effb10b5e53439
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/cops.js
@@ -0,0 +1,158 @@
+/* Police. Rules read from AI/Common/AIPursuit.cpp unless noted (all values in the VLT pursuitlevels table are approximations, by tier):
+ - busted meter: :1887-1940, up while a cop sees the player, the player is under BustSpeed and the nearest cop is within 15 m, down twice
+ as fast otherwise, busted above 5 (kBustedTimeout, kBustedCopDistance :1607-8; Sim/Common/Simulation.cpp:345 for the task rates);
+ - during a manual-reset flash the distance is x6 and the rate x4 (:1895-1909);
+ - sight: 150 m ahead of the cop, 50 m behind it, and the world ray must be clear (AIVehicleCopCar.cpp:88-168), helicopter 250 m (AIVehicleHelicopter.cpp:114);
+ - evade: more than 7 s unseen, then (unseen + hidden time) / evadetimeout reaches 1 (:2027-2061); seen again, it decays x0.93 per task (:2097);
+ - roadblocks: a request every 8-12 s with a probability (:2459-2507); a roadblock's cops join the chase after a spike hit (SpikesHit :2791);
+ - formations: FOLLOW, ROLLING_BLOCK, BOX_IN, PIT (:976-1010), cops within 60 m qualify (kFormationCandidateDistance :1221);
+ - spikes: a tyre over the strip punctures and blows 0.5 s later (DamageRacer.cpp:12), grip x0.3 (SuspensionRacer.cpp:1569);
+ - destroying cops: bonus multiplier up to 3 inside DestroyCopBonusTime (IncNumCopsDestroyed :917).
+ A cop is a free body, not on rails: with sight it drives straight at its slot (sight means the straight line is clear), without sight it follows
+ the route towards where the player was last seen. All decisions draw from the game RNG, and the controller never copies the game. */
+(function (root) {
+ 'use strict';
+ const M = root.NfsmwGame, C = M.C, N = root.NativeBench, clamp = C.clamp, P = C.PLAYER;
+ const BUST_MAX = 5, BUST_DIST = 15, FRONT_LOS = 150, REAR_LOS = 50, HELI_LOS = 250, EVADE_AFTER = 7, RESET_DIST = 6, RESET_RATE = 4, RECYCLE_DIST = 320, RECYCLE_S = 6, BARRIER_R = 2.6, BARRIER_KEEP = 0.62;
+ const wrapTo = (R, v, ref) => { if (!R.loop) return v; let ds = (v - ref) % R.L; if (ds > R.L / 2) ds -= R.L; else if (ds < -R.L / 2) ds += R.L; return ref + ds; };
+ M.wrapTo = wrapTo;
+ // o: copsMax, top, grip, accel, spawnGap, formations, rbChance, spikeChance, heli, heliAfter, heliFuel, heliGap, bustKph
+ M.initPolice = (g, o) => {
+ g.pol = Object.assign({ bust: 0, seen: 0, sinceSeen: 0, evade: 0, spawnT: o.spawnGap, rbT: 9, formT: 4, formation: 'FOLLOW', pursuitT: 0, destroyed: 0, bonusT: 0, bonusMult: 1, lockT: 0, lastS: g.s, heliT: o.heliAfter, combo: 0, sawNow: 1, inSight: 1 }, o);
+ g.cops = []; g.props = []; g.blocks = []; g.heli = null; g.puncT = 0; g.punc = 0;
+ };
+ M.spawnCop = (g, s, lat, dir, state = 'chase', h) => {
+ const R = g.route, a = C.routeAt(R, s, lat), c = { x: a.x, y: a.y, h: h !== undefined ? h : dir > 0 ? a.h : a.h + Math.PI, v: state === 'rb' ? 0 : 20, s, lat, hp: 100, state, chasing: state === 'chase' ? 1 : 0, dead: 0, gone: 0, slot: g.cops.length, sees: 0, hitT: 0, deadT: 0, lostT: 0 };
+ g.cops.push(c); return c;
+ };
+ const destroy = (g, c, why) => {
+ c.dead = 1; c.chasing = 0; c.deadT = 4; const p = g.pol; p.destroyed++;
+ p.bonusMult = p.bonusT > 0 ? Math.min(3, p.bonusMult + 1) : 1; p.bonusT = 8; p.combo = p.bonusMult;
+ g.events.push({ type: 'cop_destroyed', why, mult: p.bonusMult });
+ };
+ M.destroyCop = destroy;
+ // Slot offsets in the player's frame: [metres ahead, metres to the left]. Numbers are original: the formation classes' tables are VLT-driven.
+ const SLOTS = { FOLLOW: [[-11, -2.5], [-11, 2.5], [-22, 0], [-30, -4], [-30, 4]], ROLLING_BLOCK: [[14, -3.2], [14, 3.2], [24, 0], [-12, 0], [-22, 3]], BOX_IN: [[-6, -4.2], [-6, 4.2], [12, 0], [-14, 0], [-22, 0]], PIT: [[-3, -3.4], [-3, 3.4], [-12, 0], [-22, 3], [-22, -3]] };
+ function stepCop(g, c, wdt, losTick) {
+ const p = g.pol, R = g.route, car = g.car;
+ if (c.deadT > 0) { c.deadT -= wdt; c.v = Math.max(0, c.v - 12 * wdt); c.x += Math.cos(c.h) * c.v * wdt; c.y += Math.sin(c.h) * c.v * wdt; if (c.deadT <= 0) c.gone = 1; return; }
+ const dx = car.x - c.x, dy = car.y - c.y, dist = Math.hypot(dx, dy);
+ c.s = C.routeNear(R, c.x, c.y, wrapTo(R, c.s, g.s), 30, 30); c.lat = C.routeLat(R, c.x, c.y, c.s);
+ if (losTick) { const dot = (Math.cos(c.h) * dx + Math.sin(c.h) * dy) / (dist || 1); c.sees = (dist < REAR_LOS || (dist < FRONT_LOS && dot > 0)) && C.lineClear(c.x, c.y, car.x, car.y) ? 1 : 0; }
+ if (c.state === 'rb') { // parked across the road; joins in once the player is past or a strip was hit
+ if (g.s - c.s > 12 || c.join) { c.state = 'chase'; c.chasing = 1; }
+ else return;
+ }
+ let tx, ty;
+ if (c.sees && dist < 60) { // in formation (kFormationCandidateDistance)
+ const slots = SLOTS[p.formation], sl = slots[c.slot % slots.length], ch = Math.cos(car.h), sh = Math.sin(car.h), lead = C.speed(car) * 0.25;
+ tx = car.x + ch * (sl[0] + lead) - sh * sl[1]; ty = car.y + sh * (sl[0] + lead) + ch * sl[1];
+ if (p.formation === 'PIT' && (c.slot % slots.length) < 2 && dist < 9) { tx = car.x + ch * lead; ty = car.y + sh * lead; } // the ram itself
+ } else if (c.sees) { const lead = C.speed(car) * 0.35; tx = car.x + Math.cos(car.h) * lead; ty = car.y + Math.sin(car.h) * lead; }
+ else { // search: along the route towards the last known position (the route is where the sim keeps its cops)
+ const dS = wrapTo(R, p.lastS, c.s) - c.s, dirn = dS >= 0 ? 1 : -1, a = C.routeAt(R, c.s + dirn * Math.max(10, c.v * 0.6), clamp(c.lat, -3, 3)); tx = a.x; ty = a.y;
+ }
+ let want = Math.atan2(ty - c.y, tx - c.x) - c.h; want = Math.atan2(Math.sin(want), Math.cos(want));
+ const grip = P.grip * p.grip, rate = grip / Math.max(c.v, 6);
+ c.h += clamp(want, -rate * wdt, rate * wdt);
+ // Speed: the road's limit ahead, its class top, and the gap to its slot when it has sight (it has to hold station, not overshoot).
+ const prof = C.profile(R, grip, P.aero, P.brake * 0.9, p.top); let lim = Math.min(C.profileAt(R, prof, c.s + c.v * 0.3), C.profileAt(R, prof, c.s - c.v * 0.3));
+ if (Math.abs(want) > 0.9) lim = Math.min(lim, 12);
+ if (!c.sees) lim = Math.min(lim, p.searchTop);
+ else if (dist < 60) { const sd = Math.hypot(tx - c.x, ty - c.y), ahead = Math.cos(want) > 0; lim = Math.min(lim, Math.max(4, C.speed(car) + (ahead ? clamp(sd * 0.5, -6, p.close) : -6))); }
+ if (c.v > lim) c.v = Math.max(lim, c.v - P.brake * 0.9 * wdt);
+ else c.v = Math.min(lim, c.v + Math.max(0.5, C.driveAt(c.v) * p.accel - P.drag * c.v * c.v - P.roll) * wdt);
+ c.x += Math.cos(c.h) * c.v * wdt; c.y += Math.sin(c.h) * c.v * wdt;
+ const q = C.road(c.x, c.y), over = q.d + 1.2; if (over > 0) { c.x -= q.nx * over; c.y -= q.ny * over; c.v *= 1 - Math.min(0.4, 2 * wdt); }
+ }
+ // Contact with the player: equal masses along the normal, closing speed scrapes the cop's damage (DamageVehicle::OnImpact; the table is VLT).
+ function contact(g, c) {
+ const car = g.car, dx = car.x - c.x, dy = car.y - c.y, d2 = dx * dx + dy * dy, R2 = M.carRadius * 2; if (d2 >= R2 * R2) return;
+ const d = Math.max(0.01, Math.sqrt(d2)), nx = dx / d, ny = dy / d, cvx = Math.cos(c.h) * c.v, cvy = Math.sin(c.h) * c.v, rel = (car.vx - cvx) * nx + (car.vy - cvy) * ny, push = R2 - d;
+ car.x += nx * push * 0.5; car.y += ny * push * 0.5; c.x -= nx * push * 0.5; c.y -= ny * push * 0.5;
+ if (rel >= 0) return;
+ const j = -0.75 * rel; car.vx += nx * j; car.vy += ny * j; c.v = Math.max(0, c.v - j * (Math.cos(c.h) * -nx + Math.sin(c.h) * -ny) * -1); if (c.v > 90) c.v = 90;
+ if (c.hitT <= 0 && -rel > 3) {
+ c.hitT = 0.4; g.lastHit = 0.25; g.hits++; const dmg = -rel * g.pol.copFrail; c.hp -= dmg;
+ if (c.state === 'rb') { c.join = 1; for (const o of g.cops) if (o.state === 'rb') o.join = 1; }
+ g.events.push({ type: 'cop_contact', speed: -rel, hp: c.hp });
+ if (c.hp <= 0) destroy(g, c, 'ram');
+ }
+ }
+ const spawnAway = (g) => {
+ const p = g.pol, R = g.route, ahead = (p.sawNow || p.aheadBlind) && N.rand(g) < p.aheadChance, S = g.s + (ahead ? 320 + N.rand(g) * 120 : -(210 + N.rand(g) * 90)), lat = (N.rand(g) < 0.5 ? -1 : 1) * R.halfW * 0.4;
+ if (!R.loop && (S < 20 || S > R.L - 20)) return;
+ const c = M.spawnCop(g, S, lat, ahead ? -1 : 1, 'chase');
+ c.slot = p.nextSlot = (p.nextSlot || 0) + 1;
+ };
+ function stepRoadblocks(g, wdt) {
+ const p = g.pol, R = g.route; p.rbT -= wdt;
+ // AIPursuit.cpp:2459: a request every 8-12 s; the probability and the spike chance are the heat level's VLT values (approximations).
+ if (p.rbT <= 0) {
+ p.rbT = 8 + N.rand(g) * 4;
+ if (!g.props.some(x => x.type === 'barrier') && p.rbChance > 0 && N.rand(g) < p.rbChance && C.speed(g.car) > 15 && !p.lockT) {
+ const S = g.s + Math.max(180, C.speed(g.car) * 5.5), a = C.routeAt(R, S), h = a.h, kN = Math.abs(a.k); if (kN < 0.012) {
+ const hw = R.halfW, gapSide = N.rand(g) < 0.5 ? -1 : 1, gapW = p.rbGap, block = []; for (let l = -hw + 1.8; l < hw - 1.6; l += 4.3) if (gapSide * l < hw - gapW || Math.abs(l) < 0) block.push(l);
+ block.forEach((l, i) => { if (i % 2 === 0) { const c = M.spawnCop(g, S, l, 1, 'rb', h + Math.PI / 2); c.slot = i; } else { const b = C.routeAt(R, S, l); g.props.push({ type: 'barrier', x: b.x, y: b.y, h: h + Math.PI / 2, s: S, lat: l, ttl: 40 }); } g.blocks.push({ s: S, lat: l }); });
+ if (N.rand(g) < p.spikeChance) { const S2 = S - 26, side = -gapSide, L = hw + 3, l0 = gapSide * (hw - gapW) + side * 0 - gapSide * L / 2, b = C.routeAt(R, S2, l0); g.props.push({ type: 'spike', x: b.x, y: b.y, h: h, s: S2, lat: l0, len: L, ttl: 40 }); }
+ g.events.push({ type: 'roadblock', s: S, gap: gapSide });
+ }
+ }
+ }
+ for (const o of g.props) if (o.ttl !== undefined) { o.ttl -= wdt; if (o.ttl <= 0 || g.s - wrapTo(R, o.s, g.s) > 160) o.gone = 1; }
+ g.props = g.props.filter(o => !o.gone);
+ g.blocks = g.blocks.filter(b => g.s - wrapTo(R, b.s, g.s) < 40);
+ for (const o of g.props) if (o.type === 'barrier' && !o.gone) { const dx = g.car.x - o.x, dy = g.car.y - o.y; if (dx * dx + dy * dy < BARRIER_R * BARRIER_R) { const v = C.speed(g.car); g.car.vx *= BARRIER_KEEP; g.car.vy *= BARRIER_KEEP; o.gone = 1; g.hits++; g.lastHit = 0.3; g.events.push({ type: 'barrier', speed: v }); for (const k of g.cops) if (k.state === 'rb') k.join = 1; } }
+ // Spikes: wheels are ±0.9 m off the centreline; each side over the strip is two tyres, punctured now and blown 0.5 s later.
+ const c = g.car;
+ for (const o of g.props) if (o.type === 'spike' && !o.used) {
+ const a = C.routeAt(R, o.s), ds = (c.x - a.x) * Math.cos(a.h) + (c.y - a.y) * Math.sin(a.h);
+ if (Math.abs(ds) < C.speed(c) * wdt + 0.6) { let n = 0; for (const w of [-0.9, 0.9]) if (Math.abs(g.lat + w - o.lat) < o.len / 2) n += 2; if (n && !g.flash) { o.used = 1; g.punc = Math.max(g.punc, n); g.puncT = 0.5; for (const k of g.cops) if (k.state === 'rb') k.join = 1; g.events.push({ type: 'spikes', tyres: n }); } }
+ }
+ if (g.puncT > 0) { g.puncT -= wdt; if (g.puncT <= 0) c.tires = Math.max(c.tires, g.punc); }
+ }
+ function stepHeli(g, wdt) {
+ const p = g.pol, car = g.car; if (!p.heli) return;
+ if (!g.heli) { p.heliT -= wdt; if (p.heliT <= 0 && !p.lockT) { g.heli = { x: car.x - Math.cos(car.h) * 200, y: car.y - Math.sin(car.h) * 200, z: 34, h: car.h, fuel: p.heliFuel, sees: 0, gone: 0 }; g.events.push({ type: 'helicopter' }); } return; }
+ const h = g.heli, sp = C.speed(car), lead = sp * 0.4 + 30, ch = Math.cos(car.h), sh = Math.sin(car.h), tx = car.x + ch * lead, ty = car.y + sh * lead, dx = tx - h.x, dy = ty - h.y, d = Math.hypot(dx, dy) || 1, v = Math.min(85, d * 1.4); // AIActionHeliPursuit.cpp:26,leadDist
+ h.x += dx / d * v * wdt; h.y += dy / d * v * wdt; h.h = Math.atan2(dy, dx); h.fuel -= wdt; h.sees = Math.hypot(car.x - h.x, car.y - h.y) < HELI_LOS ? 1 : 0;
+ if (h.fuel <= 0) { g.heli = null; p.heliT = p.heliGap; g.events.push({ type: 'helicopter_leaves' }); }
+ }
+ // Returns nothing; updates sight, the bust meter, spawns and contacts. evadeOn: whether the evade meter runs (pursuit only).
+ M.stepPolice = (g, wdt, evadeOn) => {
+ const p = g.pol, car = g.car, R = g.route, losTick = g.t % 4 === 0;
+ if (p.bonusT > 0) p.bonusT = Math.max(0, p.bonusT - wdt);
+ if (p.lockT > 0) p.lockT = Math.max(0, p.lockT - wdt);
+ p.formT -= wdt; if (p.formT <= 0) { p.formT = 9 + N.rand(g) * 6; p.formation = p.formations[Math.floor(N.rand(g) * p.formations.length) % p.formations.length]; }
+ let seen = 0, near = Infinity;
+ for (const c of g.cops) { if (c.gone) continue; c.hitT = Math.max(0, c.hitT - wdt); stepCop(g, c, wdt, losTick); if (!c.dead && c.state !== 'rb') { if (c.sees) seen = 1; near = Math.min(near, Math.hypot(car.x - c.x, car.y - c.y)); } contact(g, c); }
+ // Out of sight and far behind for a while: gone, so the slot can spawn a cop that can still engage (RemoveUnwantedVehicles / StartFlee; the distances are approximations).
+ for (const c of g.cops) { if (c.dead || c.state === 'rb') continue; const far = !c.sees && Math.hypot(car.x - c.x, car.y - c.y) > RECYCLE_DIST; c.lostT = far ? c.lostT + wdt : 0; if (c.lostT > RECYCLE_S) c.gone = 1; }
+ g.cops = g.cops.filter(c => !c.gone);
+ for (let i = 0; i < g.cops.length; i++) for (let j = i + 1; j < g.cops.length; j++) { const a = g.cops[i], b = g.cops[j]; if (a.dead || b.dead) continue; const dx = a.x - b.x, dy = a.y - b.y, d2 = dx * dx + dy * dy; if (d2 < 10 && d2 > 1e-4 && a.state !== 'rb' && b.state !== 'rb') { const d = Math.sqrt(d2), pu = (3.2 - d) * 0.5; a.x += dx / d * pu; a.y += dy / d * pu; b.x -= dx / d * pu; b.y -= dy / d * pu; } }
+ stepHeli(g, wdt); if (g.heli && g.heli.sees) seen = 1;
+ stepRoadblocks(g, wdt);
+ p.sawNow = seen;
+ const active = g.cops.filter(c => !c.dead && c.state !== 'rb').length;
+ p.spawnT -= wdt; if (p.spawnT <= 0 && active < p.copsMax && !p.lockT) { p.spawnT = p.spawnGap; spawnAway(g); }
+ // Bust meter (AIPursuit.cpp:1889-1940, the flash rules at :1895-1909).
+ const flashing = g.flash > 0, bdist = BUST_DIST * (flashing ? RESET_DIST : 1), slow = flashing || C.speed(car) < p.bustSpeed;
+ if (seen) { p.seen += wdt; p.sinceSeen = 0; p.lastS = g.s; p.pursuitT += wdt; } else p.sinceSeen += wdt;
+ // mIsPerpInSight is "a cop saw the perp within the last 7 s" (AIPursuit.cpp:2000), not "a cop sees the perp now".
+ p.inSight = p.sinceSeen < EVADE_AFTER ? 1 : 0;
+ p.bust = Math.max(0, p.bust + (p.inSight && slow && near < bdist ? (flashing ? RESET_RATE : 1) : -2) * wdt);
+ if (evadeOn) {
+ if (seen) p.evade *= Math.pow(0.93, wdt * 15);
+ else if (p.sinceSeen > EVADE_AFTER) p.evade = Math.max(p.evade, Math.min(1, p.sinceSeen / p.evadeTimeout));
+ }
+ if (p.bust > BUST_MAX) { p.bust = BUST_MAX; g.lose('busted'); }
+ };
+ M.BUST_MAX = BUST_MAX;
+ M.bustHp = g => Math.round((BUST_MAX - g.pol.bust) * 10);
+ // Road users for the controller: decided poses only.
+ M.copUsers = (g, R, out) => {
+ const add = (s, lat, vs, cop, vl = 0) => out.push({ s: wrapTo(R, s, g.s), lat, vs, r: 2, cop, vl });
+ for (const c of g.cops) { if (c.gone) continue; const dh = c.h - C.routeAt(R, c.s).h, still = c.dead || c.state === 'rb'; add(c.s, c.lat, still ? 0 : c.v * Math.cos(dh), still ? 0 : 1, still ? 0 : c.v * Math.sin(dh)); }
+ for (const o of g.props) if (o.type === 'barrier') add(o.s, o.lat, 0); else if (o.type === 'spike' && !o.used) for (let l = -o.len / 2; l <= o.len / 2 + 0.01; l += 2) add(o.s, o.lat + l, 0);
+ };
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/nfsmw_remake/draw.js b/environments/games/web/games/nfsmw_remake/draw.js
new file mode 100644
index 0000000000000000000000000000000000000000..09c5cd581b317a7f8c194d576c34cad689dcc524
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/draw.js
@@ -0,0 +1,166 @@
+/* NFS Most Wanted events - Module.draw: the WebGL chase view plus an original Canvas 2D HUD (speed, gear, nitrous and Speedbreaker
+ gauges, route minimap, event panel). BossBench additions: both public health bars, fight timer and the native tick rate.
+ Read-only on the game state.
+ 2026-11-08: what the agent needs from the picture alone.
+ - Threat telegraphs: a warning strip when a roadblock or spike strip is on the road ahead, when a cop holds a ramming slot
+ beside the car, when the helicopter's light is on the car, when the bust meter rises; edge arrows for cops and rivals
+ outside the picture (behind, round a corner); a frame around the rear-view mirror when a cop is in it.
+ - The drag series' manual box: a tachometer with the shift window (the perfect-shift band of carStep) and a light that turns
+ green there, the launch band during staging, and the keys to press. A player who only holds W knew none of this.
+ - HUD panels keep to the screen edges and are smaller, so more of the road and the cars stays visible.
+ Everything here is drawn from state the simulation already decided this tick; nothing is written back. */
+(function (root) {
+ 'use strict';
+ const M = root.NfsmwGame, C = M.C, R = M.R3;
+ const W = 854, H = 480;
+ const panel = (c, x, y, w, h, a = 0.58) => { c.fillStyle = `rgba(10,14,22,${a})`; c.beginPath(); c.roundRect(x, y, w, h, 6); c.fill(); };
+ const bar = (c, x, y, w, h, v, col, back = 'rgba(255,255,255,.14)') => { c.fillStyle = back; c.fillRect(x, y, w, h); c.fillStyle = col; c.fillRect(x, y, w * C.clamp(v, 0, 1), h); };
+ const LABEL = { time: 'Time expired', gap: 'Rival pulled away', blown: 'Engine blown', totaled: 'Crash wreck', busted: 'Busted', knocked: 'Eliminated in last place', score: 'Lost on total score' };
+ // HUD rectangles [x0, y0, x1, y1]; the view metric counts a target under one of these as not visible.
+ const RECT = { tier: [8, 8, 150, 46], event: [158, 8, 696, 46], clock: [704, 8, 846, 46], speedo: [708, 392, 846, 472], map: [10, 372, 108, 470], tach: [708, 352, 846, 382] };
+ M.hudRects = Object.values(RECT);
+ const FONT = '"Microsoft YaHei",Consolas,sans-serif';
+ function minimap(g, c) {
+ const R0 = g.route, size = 98, x0 = RECT.map[0], y0 = RECT.map[1], big = R0.name === 'downtown', span = R0.name === 'strip' ? 700 : big ? 200 : 460, k = size / 2 / span;
+ panel(c, x0, y0, size, size, 0.62); c.save(); c.beginPath(); c.rect(x0, y0, size, size); c.clip();
+ const car = g.car, tx = u => x0 + size / 2 + (u - car.x) * k, ty = v => y0 + size / 2 - (v - car.y) * k;
+ c.lineWidth = Math.max(2.4, 8 * k * 6); c.strokeStyle = 'rgba(190,200,215,.28)';
+ for (const st of C.streets) { c.beginPath(); st.forEach((p, i) => i ? c.lineTo(tx(p[0]), ty(p[1])) : c.moveTo(tx(p[0]), ty(p[1]))); c.stroke(); }
+ c.strokeStyle = 'rgba(245,240,225,.85)'; c.beginPath(); for (let i = 0; i <= R0.n; i += 6) { const u = i % R0.n; const px = tx(R0.x[u]), py = ty(R0.y[u]); i ? c.lineTo(px, py) : c.moveTo(px, py); } if (R0.loop) c.closePath(); c.stroke();
+ const dot = (x, y, col, r = 3) => { c.fillStyle = col; c.beginPath(); c.arc(tx(x), ty(y), r, 0, 7); c.fill(); };
+ for (const gt of g.gates || []) if (!gt.done) { const a = C.routeAt(R0, gt.s !== undefined ? gt.s : g.s0 + gt.at); dot(a.x, a.y, gt.kind === 'trap' ? '#ffb037' : '#7dff9a', 3.2); }
+ for (const r of g.rivals) if (!r.gone) dot(r.x, r.y, r.name === 'champion' ? '#ff4a3a' : '#ffffff');
+ for (const b of g.breakers || []) if (!(b.rearm > 0)) dot(b.x, b.y, '#ff8a3c', 3);
+ for (const p of g.cops) if (!p.gone && !p.dead) dot(p.x, p.y, (g.t >> 4) % 2 ? '#4a8cff' : '#ff4a5a');
+ for (const p of g.props || []) if (!p.gone && p.type !== 'cone') dot(p.x, p.y, p.type === 'spike' ? '#ffd020' : '#ffe030', 2.4);
+ if (g.heli && !g.heli.gone) dot(g.heli.x, g.heli.y, '#ffffff', 2.6);
+ c.translate(tx(car.x), ty(car.y)); c.rotate(-car.h); c.fillStyle = '#ffb060'; c.beginPath(); c.moveTo(7, 0); c.lineTo(-4, 4); c.lineTo(-4, -4); c.closePath(); c.fill(); c.restore();
+ }
+ // ---- telegraphs: everything here is a fact the sim decided already (a placed prop, a cop's position, the formation) ----
+ const warnings = [];
+ function threats(g, info) {
+ warnings.length = 0; info.warn = []; info.arrows = []; info.flames = []; info.cover = [];
+ const car = g.car, R = g.route, sp = Math.max(C.speed(car), 5), ch = Math.cos(car.h), sh = Math.sin(car.h);
+ if (g.outcome) return;
+ // roadblock / spikes on the road ahead (cops.js places them max(180, 5.5 v) m ahead; the original 250 m)
+ let rb = null, sk = null;
+ for (const p of g.props || []) { if (p.gone || p.used) continue; const ds = M.wrapTo ? M.wrapTo(R, p.s, g.s) - g.s : p.s - g.s; if (ds <= 0 || ds > 320) continue; if (p.type === 'spike') { if (!sk || ds < sk.ds) sk = { ds, p }; } else if (p.type === 'barrier') { if (!rb || ds < rb.ds) rb = { ds, p }; } }
+ if (rb) { warnings.push({ col: '#ffb020', text: `Roadblock ahead: ${Math.round(rb.ds)} m (${(rb.ds / sp).toFixed(1)} s)` }); info.warn.push('roadblock'); }
+ if (sk) { warnings.push({ col: '#ffd020', text: `Spike strip: ${Math.round(sk.ds)} m · on the ${sk.p.lat > 0 ? 'left' : 'right'} side` }); info.warn.push('spikes'); }
+ // ramming formation: a cop with sight inside 12 m while PIT or BOX_IN is the formation
+ if (g.pol) {
+ const close = g.cops.filter(k => !k.dead && !k.gone && k.state !== 'rb' && k.sees && Math.hypot(k.x - car.x, k.y - car.y) < 12);
+ if (close.length && (g.pol.formation === 'PIT' || g.pol.formation === 'BOX_IN')) { const k = close[0], side = (-(k.x - car.x) * sh + (k.y - car.y) * ch) > 0 ? 'left' : 'right'; warnings.push({ col: '#ff4a5a', text: g.pol.formation === 'PIT' ? `Police car ${side} rear ready to ram` : 'Police car box-in' }); info.warn.push('pit'); }
+ if (g.heli && !g.heli.gone && g.heli.sees) { warnings.push({ col: '#cfe0ff', text: 'Helicopter spotlight locked on' }); info.warn.push('heli'); }
+ if (g.pol.bust > 0.03) info.warn.push('bust');
+ }
+ // edge arrows: cops within 160 m and rivals within 200 m that are not in the main picture
+ const sc = R3sc(g);
+ const arrow = (kind, ref, x, y, col) => {
+ if (!sc) return; const p = sc.project(x, y, 0.8); const inside = p.front && p.x > 8 && p.x < W - 8 && p.y > 50 && p.y < H - 8; if (inside) return;
+ // direction in the car's frame -> a point on an ellipse around the screen centre
+ const dx = x - car.x, dy = y - car.y, fwd = dx * ch + dy * sh, left = -dx * sh + dy * ch, ang = Math.atan2(-left, fwd); // 0 = ahead, +pi/2 = right
+ info.arrows.push({ kind, ref, ang, dist: Math.hypot(dx, dy), col });
+ };
+ g.cops.forEach((k, i) => { if (!k.gone && !k.dead && Math.hypot(k.x - car.x, k.y - car.y) < 160) arrow('cop', i, k.x, k.y, (g.t >> 3) % 2 ? '#ff4a5a' : '#4a8cff'); });
+ g.rivals.forEach((r, i) => { if (!r.gone && !r.out && Math.hypot(r.x - car.x, r.y - car.y) < 200) arrow('rival', i, r.x, r.y, r.name === 'champion' ? '#ff4a3a' : '#ffffff'); });
+ g.rivals.forEach((r, i) => { if (!r.gone && !r.out && (r.nosT > 0 || r.trapNos > 0) && r.nos > 0.02) info.flames.push(i); });
+ if (g.heli && !g.heli.gone) arrow('heli', 0, g.heli.x, g.heli.y, '#e8f0ff');
+ }
+ let cur = null; const R3sc = () => cur; // the scene this frame was rendered with (R3.render returns it)
+ function drawArrows(c, info) {
+ // one arrow per side of the screen at most: overlapping arrows (two rivals right behind) read as one, the nearest wins
+ const drawn = [];
+ for (const a of [...info.arrows].sort((p, q) => p.dist - q.dist)) {
+ const s = Math.sin(a.ang), co = Math.cos(a.ang), x = W / 2 + s * 380, y = H / 2 + 24 - co * 200;
+ let cx = C.clamp(x, 26, W - 26), cy = C.clamp(y, 64, H - 70);
+ if (cy >= H - 100 && Math.abs(cx - W / 2) < 130) cx = W / 2 + (s >= 0 ? 130 : -130); // behind: either side of the car, not over it
+ if (cy > 350 && (cx < 122 || cx > 696)) cy = 350; // clear of the minimap and the speedometer
+ if (drawn.some(d => Math.hypot(d[0] - cx, d[1] - cy) < 34)) continue; drawn.push([cx, cy]);
+ const near = C.clamp(1 - a.dist / 160, 0.25, 1), size = 9 + 9 * near;
+ c.save(); c.translate(cx, cy); c.rotate(a.ang); c.globalAlpha = 0.55 + 0.45 * near; c.fillStyle = 'rgba(0,0,0,.6)'; c.beginPath(); c.moveTo(0, -size - 3); c.lineTo(size * 0.85 + 3, size * 0.6 + 2); c.lineTo(-size * 0.85 - 3, size * 0.6 + 2); c.closePath(); c.fill();
+ c.fillStyle = a.col; c.beginPath(); c.moveTo(0, -size); c.lineTo(size * 0.85, size * 0.6); c.lineTo(-size * 0.85, size * 0.6); c.closePath(); c.fill(); c.restore();
+ c.globalAlpha = 1; c.font = 'bold 10px Consolas,monospace'; c.fillStyle = '#ffffff'; c.textAlign = 'center'; c.fillText(Math.round(a.dist) + 'm', cx, cy + (cy > H / 2 ? -14 : 22)); c.textAlign = 'left';
+ }
+ }
+ // One row at the bottom centre, on the road just in front of the bumper: the horizon band (y 150-190), where a roadblock
+ // 200 m ahead appears, stays clear.
+ function drawWarnings(c, g) {
+ if (!warnings.length) return;
+ c.font = `bold 14px ${FONT}`; const widths = warnings.map(w => c.measureText(w.text).width + 30), total = widths.reduce((a, b) => a + b, 0) + 8 * (warnings.length - 1), y = H - 32;
+ let x = W / 2 - total / 2;
+ M.hudInfo.cover.push([x, y, x + total, y + 24]);
+ for (const [i, w] of warnings.entries()) {
+ const tw = widths[i], on = (g.t >> 3) % 2 === 0;
+ c.fillStyle = 'rgba(10,10,14,.72)'; c.beginPath(); c.roundRect(x, y, tw, 24, 4); c.fill(); c.strokeStyle = w.col; c.lineWidth = on ? 3 : 1.5; c.stroke();
+ c.fillStyle = w.col; c.beginPath(); c.moveTo(x + 9, y + 18); c.lineTo(x + 15, y + 6); c.lineTo(x + 21, y + 18); c.closePath(); c.fill(); c.fillStyle = '#111'; c.fillRect(x + 14.2, y + 10, 1.6, 4.5);
+ c.fillStyle = '#ffffff'; c.textAlign = 'left'; c.fillText(w.text, x + 25, y + 17); x += tw + 8;
+ }
+ }
+ // mirror frame (renderer3d draws the mirror image itself); red border while a cop is in it
+ function mirrorFrame(c, g) {
+ const sc = R3sc(g); if (!sc || !sc.mirrorOn) return; const [x0, y0, x1, y1] = sc.mirrorRect;
+ const copIn = g.cops.some(k => { if (k.gone || k.dead) return false; const dx = k.x - g.car.x, dy = k.y - g.car.y, fwd = dx * Math.cos(g.car.h) + dy * Math.sin(g.car.h); return fwd < 0 && Math.hypot(dx, dy) < 120; });
+ c.strokeStyle = copIn && (g.t >> 3) % 2 ? '#ff4a5a' : 'rgba(230,236,245,.85)'; c.lineWidth = 2.5; c.strokeRect(x0 - 1, y0 - 1, x1 - x0 + 2, y1 - y0 + 2);
+ c.font = `10px ${FONT}`; c.fillStyle = 'rgba(230,236,245,.85)'; c.fillText('Rearview mirror', x0 + 3, y1 + 11);
+ }
+ // tachometer: fraction of the current gear's top speed (carStep's u), shift band 0.88-0.99, limiter at 1
+ function tach(g, c) {
+ const car = g.car, [x, y, x1, y1] = RECT.tach, w = x1 - x, h = y1 - y, staging = g.pre > 0 && g.rev !== undefined;
+ const fwd = Math.max(0, car.vx * Math.cos(car.h) + car.vy * Math.sin(car.h)), u = staging ? g.rev : C.clamp(fwd / C.TOPS[car.gear], 0, 1.05);
+ const band = staging ? [0.62, 0.86] : [0.88, 0.99], inBand = u >= band[0] && u <= band[1];
+ panel(c, x, y, w, h, 0.7); const bx = x + 6, bw = w - 12, by = y + 6;
+ c.fillStyle = 'rgba(255,255,255,.12)'; c.fillRect(bx, by, bw, 9);
+ c.fillStyle = 'rgba(90,255,140,.55)'; c.fillRect(bx + bw * band[0], by, bw * (band[1] - band[0]), 9);
+ if (!staging) { c.fillStyle = 'rgba(255,70,60,.55)'; c.fillRect(bx + bw * 0.99, by, bw * 0.01 + 2, 9); }
+ c.fillStyle = inBand ? '#7dff9a' : u > band[1] ? '#ff5a4a' : '#ffd08a'; c.fillRect(bx, by + 2, bw * C.clamp(u, 0, 1), 5);
+ c.font = `bold 11px ${FONT}`; c.fillStyle = inBand ? '#7dff9a' : '#c6d0dc';
+ c.fillText(staging ? (inBand ? 'Launch RPM ✓ Hold steady' : g.rev < band[0] ? 'Hold W to raise RPM into the green zone' : 'RPM too high; release W briefly') : car.gear >= 5 ? 'Top gear · Stay below the redline' : inBand ? '▶ Press K to upshift' : u > band[1] ? 'Press K to upshift now!' : `RPM → Green zone: press K`, bx, by + 21);
+ if (inBand && !staging && car.gear < 5 && (g.t >> 2) % 2) { c.strokeStyle = '#7dff9a'; c.lineWidth = 2; c.strokeRect(x + 1, y + 1, w - 2, h - 2); }
+ }
+ M.draw = function (g, c) {
+ const sc = R.render(g, c), info = {}; cur = sc;
+ M.hudInfo = info;
+ const car = g.car, kmh = C.speed(car) * 3.6, h = g.health(), hud = (M.MODES[g.key].hud || (() => ({ label: '', detail: '' })))(g);
+ threats(g, info);
+ // knockout: the mode's text measures the last rival still in, and after the win none is left ( 11-06 item 7)
+ if (g.key === 'knockout' && g.outcome === 'win') hud.detail = `${g.laps} / ${g.laps} laps · All rivals eliminated`;
+ if (g.sb) { const v = c.createRadialGradient(W / 2, H / 2, 150, W / 2, H / 2, 520); v.addColorStop(0, 'rgba(120,170,255,0)'); v.addColorStop(1, 'rgba(70,110,220,.42)'); c.fillStyle = v; c.fillRect(0, 0, W, H); }
+ // hit: a red vignette at the edges, not a full-screen wash, so the road stays readable
+ if (g.lastHit > 0) { const v = c.createRadialGradient(W / 2, H / 2, 170, W / 2, H / 2, 500); v.addColorStop(0, 'rgba(220,40,30,0)'); v.addColorStop(1, `rgba(220,40,30,${Math.min(0.75, g.lastHit * 1.6)})`); c.fillStyle = v; c.fillRect(0, 0, W, H); }
+ if (g.flash > 0 && (g.t >> 3) % 2) { c.fillStyle = 'rgba(255,255,255,.1)'; c.fillRect(0, 0, W, H); }
+ mirrorFrame(c, g);
+ info.cover.push(RECT.tier, RECT.event, RECT.clock, RECT.speedo, RECT.map); if (g.manual) info.cover.push(RECT.tach); if (sc && sc.mirrorOn) info.cover.push(sc.mirrorRect);
+ // event panel: boss_hp and player_hp under their event-specific names
+ const [ex0, ey0, ex1] = RECT.event; panel(c, ex0, ey0, ex1 - ex0, 38);
+ c.font = `bold 12px ${FONT}`; c.fillStyle = '#f2ecdc'; c.textAlign = 'left'; c.fillText(hud.label || '', ex0 + 8, ey0 + 14);
+ c.font = `11px ${FONT}`; c.fillStyle = '#c6d0dc'; c.textAlign = 'right'; c.fillText(hud.detail || '', ex1 - 8, ey0 + 14); c.textAlign = 'left';
+ bar(c, ex0 + 8, ey0 + 20, ex1 - ex0 - 16, 5, h[3] ? h[2] / h[3] : 0, '#ff8a3c');
+ bar(c, ex0 + 8, ey0 + 28, ex1 - ex0 - 16, 5, h[1] ? h[0] / h[1] : 0, h[0] / (h[1] || 1) < 0.25 ? '#ff4a3a' : '#5bd18a');
+ // clock and tier
+ const [cx0, cy0, cx1] = RECT.clock; panel(c, cx0, cy0, cx1 - cx0, 38); c.textAlign = 'right'; c.font = 'bold 16px Consolas,monospace'; c.fillStyle = '#f2ecdc'; c.fillText((g.t / M.hz).toFixed(1) + ' s', cx1 - 8, cy0 + 18);
+ c.font = 'bold 10px Consolas,monospace'; c.fillStyle = '#9fd0ff'; c.fillText(M.hz + 'Hz · tick ' + g.t, cx1 - 8, cy0 + 32); c.textAlign = 'left';
+ const [tx0, ty0, tx1] = RECT.tier; panel(c, tx0, ty0, tx1 - tx0, 38); c.font = 'bold 11px Consolas,monospace'; c.fillStyle = '#ffd08a'; c.fillText((g.tier || '').toUpperCase() + ' d=' + g.d, tx0 + 8, ty0 + 16); c.fillStyle = '#b8c2cc'; c.font = '10px Consolas,monospace'; c.fillText(M.version, tx0 + 8, ty0 + 30);
+ // speedometer
+ const [sx0, sy0, sx1, sy1] = RECT.speedo; panel(c, sx0, sy0, sx1 - sx0, sy1 - sy0); c.textAlign = 'right'; c.font = 'bold 32px Consolas,monospace'; c.fillStyle = '#ffffff'; c.fillText(String(Math.round(kmh)), sx1 - 40, sy0 + 34);
+ c.font = '10px Consolas,monospace'; c.fillStyle = '#a8b4c0'; c.fillText('KM/H', sx1 - 8, sy0 + 34);
+ c.font = 'bold 18px Consolas,monospace'; c.fillStyle = car.over ? '#ff5a4a' : '#ffd08a'; c.textAlign = 'center'; c.fillText(String(car.gear + 1), sx0 + 14, sy0 + 26); c.textAlign = 'left';
+ c.font = '9px Consolas,monospace'; c.fillStyle = '#9fc8ff'; c.fillText('NOS', sx0 + 6, sy0 + 52); bar(c, sx0 + 34, sy0 + 45, sx1 - sx0 - 42, 7, car.nos, car.nosOn ? '#bfe4ff' : '#4aa0ff');
+ c.fillStyle = '#ffd08a'; c.fillText('SLOW', sx0 + 6, sy0 + 64); bar(c, sx0 + 34, sy0 + 57, sx1 - sx0 - 42, 7, g.sbMeter, g.sb ? '#ffffff' : '#ffb84a');
+ if (g.manual) { c.fillStyle = '#ff9a7a'; c.fillText('HEAT', sx0 + 6, sy0 + 76); bar(c, sx0 + 34, sy0 + 70, sx1 - sx0 - 42, 6, car.heat, car.heat > 0.6 ? '#ff4a3a' : '#ffa14a'); }
+ if (g.manual) tach(g, c);
+ minimap(g, c);
+ if (M.MODES[g.key].hudExtra) M.MODES[g.key].hudExtra(g, c, { panel, bar, W, H });
+ drawArrows(c, info); drawWarnings(c, g);
+ if (g.pre > 0) {
+ c.font = 'bold 54px Consolas,monospace'; c.textAlign = 'center'; c.fillStyle = '#ffe28a'; c.fillText(String(Math.ceil(g.pre)), W / 2, 210);
+ if (g.manual) { c.font = `bold 14px ${FONT}`; c.fillStyle = '#ffffff'; c.fillText('Manual gears: K upshift · L downshift · A / D change lanes', W / 2, 238); }
+ c.textAlign = 'left';
+ }
+ if (g.outcome) { c.fillStyle = 'rgba(0,0,0,.42)'; c.fillRect(0, H / 2 - 44, W, 88); c.font = 'bold 36px "Microsoft YaHei",sans-serif'; c.textAlign = 'center'; c.fillStyle = g.outcome === 'win' ? '#7dff9a' : '#ff6a5a'; c.fillText(g.outcome === 'win' ? 'Challenge complete' : g.outcome === 'timeout' ? 'Time up' : (LABEL[g.lossReason] || 'Challenge Failed'), W / 2, H / 2 + 13); c.textAlign = 'left'; }
+ return sc;
+ };
+ M.renderStatus = ctx => R.status(ctx);
+ M.renderMetrics = ctx => R.metrics(ctx);
+ M.closeRenderer = ctx => R.close(ctx);
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/nfsmw_remake/game.js b/environments/games/web/games/nfsmw_remake/game.js
new file mode 100644
index 0000000000000000000000000000000000000000..12729d0a847f5fc40c0639ed862c3cc00d348efc
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/game.js
@@ -0,0 +1,167 @@
+/* Need for Speed: Most Wanted (2005) events, rules nfsmw-arena@2 - the module: cases, tiers, the tick, the health mapping.
+ A race has no health bars, so the public contract maps onto the event's own win and loss conditions:
+ boss_hp is what is left of the event (route metres from a high-water mark, so it never jumps back), and player_hp
+ is what the opponent still needs to beat you (clock, gap, score margin, bust meter). See
+ Independent reimplementation; facts read from the CC0 decompilation dbalatoni13/nfsmw@80993f3 are cited as file:line
+ in that repository. All art is procedural; no game data (VLT attributes, models, textures, audio, maps) is used. */
+(function (root) {
+ 'use strict';
+ const N = root.NativeBench, M = root.NfsmwGame, C = M.C;
+ const HZ = 60, DT = 1 / HZ;
+ // Tiers are one fight at three paces: event length, opponent skill, traffic and police pressure all scale continuously.
+ // The original has no mode gate on these values (GRace.h: Easy/Medium/Hard is a per-event parameter), so hard stays 0.85.
+ const TIERS = { easy: 0.2, normal: 0.5, hard: 0.85 };
+ // Piecewise linear through the three tier values, extrapolated beyond them, so any d in [0,1] is a valid fight.
+ const tierValue = (d, [e, n, h]) => d <= TIERS.normal ? n + (e - n) * (TIERS.normal - d) / (TIERS.normal - TIERS.easy) : n + (h - n) * (d - TIERS.normal) / (TIERS.hard - TIERS.normal);
+ const tierOf = d => d <= (TIERS.easy + TIERS.normal) / 2 ? 'easy' : d <= (TIERS.normal + TIERS.hard) / 2 ? 'normal' : 'hard';
+ M.MODES = M.MODES || {};
+
+ const CASES = [
+ { id: 'nfsmw/tollbooth', name: 'Tollbooth Race (Coastal Highway)' },
+ { id: 'nfsmw/drag', name: 'Drag Series (Highway 99)' },
+ { id: 'nfsmw/speedtrap', name: 'Speed Trap (Coastal Highway)' },
+ { id: 'nfsmw/knockout', name: 'Lap Knockout (Downtown Night Race)' },
+ { id: 'nfsmw/pursuit', name: 'Police Pursuit (Bounty + Escape)' },
+ { id: 'nfsmw/street_champion', name: 'Street Champion Showdown (Multi-leg Race + Police)' },
+ ];
+ Object.assign(M, {
+ id: 'nfsmw_remake', version: 'nfsmw-arena@2', hz: HZ, maxSeconds: 300, dimension: '3d', renderer: 'webgl-nfsmw',
+ title: 'Need for Speed: Most Wanted · Street Challenges', cases: CASES, tiers: TIERS, tierValue, tierOf, DT,
+ controls: {
+ 'W': 'throttle', 'S': 'brake; reverse at low speed', 'A / D': 'Steer left / right (steering increases while held and decreases at higher speed)', 'Space': 'Handbrake (drift)',
+ 'Shift': 'nitrous', 'J': 'Toggle slow motion (time slows and downforce increases)', 'K / L': 'Manual upshift / downshift in drag races (A / D change lanes)', 'R': 'Reset onto the route (easier to bust during the 2-second flashing period)',
+ },
+ });
+
+ // SB: world time scale is in the ITimeManager data (not in the repository), approximation 0.45; the handling side is
+ // SuspensionRacer.cpp:936 Tweak_GameBreakerExtraGs (-2 g of extra downforce) with a 1/3 s physics ramp-out (:937).
+ const SB_SCALE = 0.45, SB_GRIP = 2 * 9.81, SB_RAMP = 1 / 3, SB_SECONDS = 6;
+ const RESET_INVULN = 2; // ResetCar.cpp:26 Tweak_ResetInvulnerablitiyTime
+
+ class Game {
+ constructor(id, seed, d) {
+ this.id = id; this.key = id.split('/')[1]; this.d = d; this.tier = tierOf(d);
+ this.t = 0; this.outcome = null; this.events = []; this.seed = seed;
+ // The multiply decorrelates neighbouring seeds; xorshift has a fixed point at zero.
+ this.rng = (Math.imul((seed >>> 0) + 1, 2654435761) >>> 0) || 1;
+ this.pre = 1.2; this.clock = 0; // staging countdown; event clock in world seconds
+ this.sb = 0; this.sbMeter = 1; this.sbRamp = 0; // Speedbreaker
+ this.flash = 0; this.resets = 0; this.hits = 0; this.nearMisses = 0; this.manual = 0; this.lastHit = 0;
+ this.slowT = 0; this.s = 0; this.s0 = 0; this.prog = 0; this.total = 1; this.lat = 0; this.offRoute = 0;
+ this.traffic = []; this.rivals = []; this.cops = []; this.props = []; this.gates = []; this.status = '';
+ const mode = M.MODES[this.key]; if (!mode) throw Error('Unknown event ' + id);
+ this.routeKey = mode.route(d);
+ mode.init(this, d);
+ this.camH = this.car.h; this.heldBrake = 0; this.flashT = 0; this.heli = null;
+ }
+ get route() { return C.routes[this.routeKey]; }
+ placeCar(s, lat, speed = 0) {
+ const a = C.routeAt(this.route, s, lat), c = C.newCar(a.x, a.y, a.h);
+ c.vx = Math.cos(a.h) * speed; c.vy = Math.sin(a.h) * speed;
+ this.car = c; this.s = s; this.lat = lat;
+ }
+ update(keys, pressed) {
+ const mode = M.MODES[this.key], car = this.car;
+ this.heldBrake = keys.has('S') ? 1 : 0;
+ // Chase camera: lags the heading (state only the renderer reads; it cannot affect the simulation).
+ { let dh = car.h - this.camH; dh = Math.atan2(Math.sin(dh), Math.cos(dh)); this.camH += dh * Math.min(1, DT * 5.5); }
+ if (this.lastHit > 0) this.lastHit = Math.max(0, this.lastHit - DT);
+ if (this.flash > 0) this.flash = Math.max(0, this.flash - DT);
+ if (pressed.has('J') && (this.sb || this.sbMeter > 0.05)) { this.sb = this.sb ? 0 : 1; if (!this.sb) this.sbRamp = SB_RAMP; this.events.push({ type: this.sb ? 'slowmo_on' : 'slowmo_off' }); }
+ if (this.sb) { this.sbMeter = Math.max(0, this.sbMeter - DT / SB_SECONDS); if (this.sbMeter <= 0) { this.sb = 0; this.sbRamp = SB_RAMP; } }
+ else if (this.sbRamp > 0) this.sbRamp = Math.max(0, this.sbRamp - DT);
+ const wdt = DT * (this.sb ? SB_SCALE : 1);
+ if (this.pre > 0) { // staging: the world runs, the car is held at the line
+ this.pre = Math.max(0, this.pre - DT);
+ if (mode.staging) mode.staging(this, keys, pressed, DT);
+ M.stepTraffic(this, wdt); if (mode.idle) mode.idle(this, wdt);
+ return;
+ }
+ if (pressed.has('R')) this.resetCar();
+ const speed = C.speed(car), fwd = car.vx * Math.cos(car.h) + car.vy * Math.sin(car.h);
+ const inp = {
+ thr: keys.has('W') ? 1 : 0, brk: keys.has('S'), steer: (keys.has('A') ? 1 : 0) - (keys.has('D') ? 1 : 0), hb: keys.has('Space'), nos: keys.has('Shift'),
+ up: this.manual && pressed.has('K'), down: this.manual && pressed.has('L'), manual: !!this.manual, reverse: keys.has('S') && fwd < 2 && speed < 6,
+ sbGrip: this.sb ? SB_GRIP : SB_GRIP * this.sbRamp / SB_RAMP,
+ };
+ if (mode.input) mode.input(this, inp, keys, pressed);
+ C.carStep(car, inp, wdt, this.P || C.PLAYER);
+ if (car.hit > 3) { this.hits++; if (car.hit > 6) this.lastHit = 0.4; this.events.push({ type: 'wall', speed: car.hit }); }
+ if (!this.sb && speed > 35) this.sbMeter = Math.min(1, this.sbMeter + wdt * 0.02);
+ this.slowT = C.speed(car) < 2 ? this.slowT + DT : 0;
+ this.clock += wdt;
+ this.trackProgress();
+ M.stepTraffic(this, wdt);
+ mode.tick(this, wdt);
+ }
+ // Progress is route distance from a high-water mark, inside a short window so a junction can't jump to another leg.
+ trackProgress() {
+ const R = this.route, c = this.car;
+ this.s = C.routeNear(R, c.x, c.y, this.s);
+ this.lat = C.routeLat(R, c.x, c.y, this.s);
+ this.offRoute = Math.abs(this.lat) > R.halfW + 3 ? 1 : 0;
+ if (!this.offRoute && this.s - this.s0 > this.prog) this.prog = Math.min(this.total, this.s - this.s0);
+ }
+ resetCar() {
+ const s = this.s0 + this.prog, a = C.routeAt(this.route, s, 0), keep = this.car;
+ Object.assign(keep, { x: a.x, y: a.y, h: a.h, vx: 0, vy: 0, r: 0, steer: 0, gear: 0, clutch: 0, tires: 0 }); // tyres: approximation, see SOURCES.md
+ this.s = s; this.lat = 0; this.slowT = 0; this.flash = RESET_INVULN; this.resets++;
+ this.events.push({ type: 'reset' });
+ }
+ win() { if (!this.outcome) { this.outcome = 'win'; this.events.push({ type: 'win' }); } }
+ lose(why) { if (!this.outcome) { this.outcome = 'loss'; this.lossReason = why; this.events.push({ type: 'loss', why }); } }
+ health() { return M.MODES[this.key].health(this); }
+ }
+ Object.assign(M, { Game, DT, copyGame: g => Object.assign(Object.create(Game.prototype), N.copy(g)) });
+
+ // ---------------- traffic (AIActionTraffic: stays in lane at the speed limit, does not race, does not dodge) ----------------
+ const carRadius = 1.6;
+ M.carRadius = carRadius;
+ M.spawnTraffic = (g, n, opt = {}) => {
+ g.trafficOpt = { ahead: opt.ahead || 420, spread: opt.spread || 620, opposing: opt.opposing === undefined ? 0.35 : opt.opposing, lanes: opt.lanes || null };
+ for (let i = 0; i < n; i++) {
+ const t = { s: 0, lat: 0, dir: 1, v: 0, x: 0, y: 0, h: 0, crash: 0, vx: 0, vy: 0, nm: 0, paint: i % 6 };
+ placeTraffic(g, t, g.s + 90 + (g.trafficOpt.spread + g.trafficOpt.ahead) * (i + N.rand(g)) / n);
+ g.traffic.push(t);
+ }
+ };
+ const lanesOf = (R, dir) => dir > 0 ? [-R.halfW * 0.25, -R.halfW * 0.72] : [R.halfW * 0.25, R.halfW * 0.72];
+ function placeTraffic(g, t, s) {
+ const R = g.route, o = g.trafficOpt;
+ t.dir = N.rand(g) < o.opposing ? -1 : 1; t.nm = 0; t.crash = 0; t.vx = 0; t.vy = 0;
+ const lanes = o.lanes || lanesOf(R, t.dir); t.lat = lanes[Math.floor(N.rand(g) * lanes.length) % lanes.length];
+ t.v = t.dir * (17 + N.rand(g) * 9); t.s = s;
+ if (!R.loop) t.s = C.clamp(s, 40, R.L - 40);
+ const a = C.routeAt(R, t.s, t.lat); t.x = a.x; t.y = a.y; t.h = t.dir > 0 ? a.h : a.h + Math.PI;
+ }
+ M.stepTraffic = (g, wdt) => {
+ const R = g.route, c = g.car;
+ for (const t of g.traffic) {
+ if (t.crash) { // knocked out of lane: a free body that coasts to a stop
+ t.x += t.vx * wdt; t.y += t.vy * wdt; const f = Math.max(0, 1 - 1.6 * wdt); t.vx *= f; t.vy *= f; t.h += t.crash * wdt; t.crash *= f;
+ const q = C.road(t.x, t.y), over = q.d + 1.2; if (over > 0) { t.x -= q.nx * over; t.y -= q.ny * over; t.vx = 0; t.vy = 0; }
+ t.s = C.routeNear(R, t.x, t.y, t.s, 10, 10); t.lat = C.routeLat(R, t.x, t.y, t.s);
+ } else {
+ t.s += t.v * wdt; const a = C.routeAt(R, t.s, t.lat); t.x = a.x; t.y = a.y; t.h = t.dir > 0 ? a.h : a.h + Math.PI;
+ }
+ const rel = t.s - g.s;
+ if (rel < -140 || rel > g.trafficOpt.ahead + g.trafficOpt.spread + 60 || (!R.loop && (t.s < 30 || t.s > R.L - 30))) { placeTraffic(g, t, g.s + g.trafficOpt.ahead + N.rand(g) * g.trafficOpt.spread); continue; }
+ const dx = c.x - t.x, dy = c.y - t.y, dist2 = dx * dx + dy * dy;
+ if (dist2 < 30 && !t.nm && C.speed(c) > 25) { const d = Math.sqrt(dist2); if (d > carRadius * 2 + 0.4 && d < 4.6) { t.nm = 1; g.nearMisses++; g.sbMeter = Math.min(1, g.sbMeter + 0.04); } }
+ if (dist2 < (carRadius * 2) * (carRadius * 2)) M.bump(g, t, dx, dy, dist2, 0.8);
+ }
+ };
+ // Player against a lighter body: momentum exchange along the contact normal. Returns the closing speed.
+ M.bump = (g, o, dx, dy, dist2, mass) => {
+ const c = g.car, d = Math.max(0.01, Math.sqrt(dist2)), nx = dx / d, ny = dy / d;
+ const moving = o.v !== undefined && !o.crash, ovx = moving ? Math.cos(o.h) * Math.abs(o.v) : o.vx, ovy = moving ? Math.sin(o.h) * Math.abs(o.v) : o.vy;
+ const rel = (c.vx - ovx) * nx + (c.vy - ovy) * ny, push = carRadius * 2 - d;
+ c.x += nx * push * 0.6; c.y += ny * push * 0.6;
+ if (rel >= 0) return 0;
+ const j = -(1.3) * rel * mass / (1 + mass);
+ c.vx += nx * j; c.vy += ny * j; c.r += ((nx * c.vy - ny * c.vx) > 0 ? 1 : -1) * Math.min(0.8, -rel * 0.02);
+ o.vx = ovx - nx * j / mass * 1.0; o.vy = ovy - ny * j / mass * 1.0; if (o.v !== undefined && !o.crash) o.crash = nx * Math.sin(o.h) - ny * Math.cos(o.h) > 0 ? 0.8 : -0.8;
+ if (-rel > 4) { g.hits++; g.lastHit = 0.4; g.events.push({ type: 'crash', speed: -rel }); }
+ return -rel;
+ };
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/nfsmw_remake/index.html b/environments/games/web/games/nfsmw_remake/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..521187bc57cc47a4e32109e72d3d0d01aaf2cf6f
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/index.html
@@ -0,0 +1,7 @@
+
+Need for Speed: Most Wanted · Street Challenges(nfsmw-arena@2)
+
Need for Speed: Most Wanted · Street Challenges
2005 original rules, independently recreated from CC0 decompilation · Native 60 Hz · Third-person WebGL · Original procedural city
Replays save inputs and the seed, then simulate the match again and verify the final state. Scripted Demo reads internal state for verification; it does not start RL training.
+
+
+
diff --git a/environments/games/web/games/nfsmw_remake/manifest.json b/environments/games/web/games/nfsmw_remake/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..9efed7b0533c3de38c643ebf3fbc091dea3a88c3
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/manifest.json
@@ -0,0 +1,55 @@
+{
+ "schema": "bossbench/game-manifest@1",
+ "engine": "independent",
+ "game": "nfsmw_remake",
+ "module": "NfsmwGame",
+ "title": "Need for Speed Most Wanted: Street Challenges",
+ "dimension": "3d",
+ "native_hz": 60,
+ "max_seconds": 300,
+ "renderer": "webgl-nfsmw",
+ "rules": "nfsmw-arena@2",
+ "cases": [
+ "nfsmw/tollbooth",
+ "nfsmw/drag",
+ "nfsmw/speedtrap",
+ "nfsmw/knockout",
+ "nfsmw/pursuit",
+ "nfsmw/street_champion"
+ ],
+ "scripts": [
+ "_native/runtime.js",
+ "_boss3d/vendor/three.min.js",
+ "nfsmw_remake/nfscore.js",
+ "nfsmw_remake/game.js",
+ "nfsmw_remake/rivals.js",
+ "nfsmw_remake/modes_tollbooth.js",
+ "nfsmw_remake/modes_drag.js",
+ "nfsmw_remake/modes_speedtrap.js",
+ "nfsmw_remake/modes_knockout.js",
+ "nfsmw_remake/cops.js",
+ "nfsmw_remake/modes_pursuit.js",
+ "nfsmw_remake/scripted.js",
+ "nfsmw_remake/renderer3d.js",
+ "nfsmw_remake/draw.js"
+ ],
+ "sim_scripts": [
+ "_native/runtime.js",
+ "nfsmw_remake/nfscore.js",
+ "nfsmw_remake/game.js",
+ "nfsmw_remake/rivals.js",
+ "nfsmw_remake/modes_tollbooth.js",
+ "nfsmw_remake/modes_drag.js",
+ "nfsmw_remake/modes_speedtrap.js",
+ "nfsmw_remake/modes_knockout.js",
+ "nfsmw_remake/cops.js",
+ "nfsmw_remake/modes_pursuit.js",
+ "nfsmw_remake/scripted.js"
+ ],
+ "play_page": "web/games/nfsmw_remake/index.html",
+ "scripted_controller": "NfsmwGame.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]}; pure car-model look-ahead, others extrapolated at constant speed (NfsmwGame.oracle is an alias)",
+ "tests": [
+ "nfsmw_remake/tests/mechanics.js"
+ ],
+ "source": "https://github.com/dbalatoni13/nfsmw/tree/80993f35224c61d2f1b135beba76c6f8234c7940 (CC0-1.0)"
+}
diff --git a/environments/games/web/games/nfsmw_remake/modes_drag.js b/environments/games/web/games/nfsmw_remake/modes_drag.js
new file mode 100644
index 0000000000000000000000000000000000000000..560f4e8b7775bbe6f015ed4effd1be8ebbaa8511
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/modes_drag.js
@@ -0,0 +1,113 @@
+/* Drag (GRace.h kRaceType_Drag), run as a series the way a Blacklist rival is fought (Wikipedia: "win against the racer in a
+ successive series of races"). Rules that exist only here, all from the decompilation:
+ - manual gearbox with a perfect-shift bonus (EngineRacer EPerfectShift; the window width is VLT, approximation);
+ - over-rev heat, EngineRacer.cpp:1340-1345: +0.45/s on the limiter, -0.1/s otherwise, torque -25% from 0.6, blown at 1;
+ - the car steers itself and the driver changes lanes (AIVehicle.cpp IsDragSteering, ChangeDragLanes);
+ - total on hard contact, DamageDragster.cpp: above 100 mph, losing more than 40 mph in one impact destroys the car;
+ - launch: GetPerfectLaunchRange, EngineRacer.cpp:127-135 (a band a quarter of the rev range below the redline).
+ boss_hp = metres left in the whole series; player_hp = metres the rival still needs in this heat. */
+(function (root) {
+ 'use strict';
+ const M = root.NfsmwGame, C = M.C, clamp = C.clamp;
+ const MPH = C.MPH, KILL_SPEED = 100 * MPH, KILL_DELTA = 40 * MPH, STAGE = 2.5; // AIActionRace.cpp:99 Tweak_UnstageTime
+ const LANES = [-7.5, -2.5, 2.5, 7.5], REV_UP = 1.5, REV_DOWN = 1.1, LAUNCH = [0.62, 0.86], START_S = 60, LANE_RATE = 7, LANE_GAIN = 2.2;
+ const startHeat = g => {
+ const lane = g.heat % 2 ? 2 : 1, rl = g.heat % 2 ? 1 : 2;
+ g.placeCar(START_S, LANES[lane]); g.s0 = START_S; g.lane = lane; g.pre = STAGE; g.rev = 0; g.prevV = 0; g.heatProg = 0;
+ g.gates = [{ s: START_S + g.heatLen, at: g.heatLen, done: 0 }];
+ g.rivals = [M.newRival(g, { s: START_S, lat: LANES[rl], skill: clamp(g.rivalSkill + M.formOf(g), 0, 1), drag: true, paint: 1 })];
+ g.traffic = []; M.spawnTraffic(g, g.trafficN, { opposing: 0, lanes: LANES, spread: Math.max(0, g.heatLen - 240), ahead: 140 });
+ // highwater across heats: every heat restarts the car at the line, and prog is measured from heatBase
+ g.prog = 0; g.total = g.heatLen;
+ };
+ M.MODES.drag = {
+ route: () => 'strip',
+ init(g, d) {
+ g.P = Object.assign({}, C.PLAYER, { overheat: true });
+ g.manual = 1; g.noGlue = 1;
+ g.heats = Math.round(M.tierValue(d, [1, 2, 6])); g.heatLen = M.tierValue(d, [1000, 1500, 1500]); g.seriesLen = g.heats * g.heatLen;
+ g.rivalSkill = M.tierValue(d, [0.2, 0.5, 0.8]); g.trafficN = Math.round(M.tierValue(d, [3, 6, 10]));
+ g.heat = 0; g.launch = 0;
+ startHeat(g);
+ },
+ staging(g, keys, pressed, dt) {
+ g.rev = clamp(g.rev + (keys.has('W') ? REV_UP : -REV_DOWN) * dt, 0, 1);
+ if (g.pre <= 0) { const inBand = g.rev >= LAUNCH[0] && g.rev <= LAUNCH[1]; g.launch = inBand ? 1 : 0; if (inBand) { g.car.bonus = 1.2; g.events.push({ type: 'perfect_launch' }); } else if (g.rev > LAUNCH[1]) g.car.clutch = 0.45; }
+ g.prevV = 0;
+ },
+ idle(g) { for (const r of g.rivals) { const a = C.routeAt(g.route, r.s, r.lat); r.x = a.x; r.y = a.y; r.h = a.h; } },
+ input(g, inp, keys, pressed) {
+ if (pressed.has('A') && g.lane < LANES.length - 1) g.lane++;
+ if (pressed.has('D') && g.lane > 0) g.lane--;
+ // Lane keeper: the driver has no wheel here (IsDragSteering), a fixed servo turns the lane error into steering.
+ const R = g.route, c = g.car, a = C.routeAt(R, g.s), lat = C.routeLat(R, c.x, c.y, g.s), v = Math.max(C.speed(c), 6);
+ let dh = c.h - a.h; dh = Math.atan2(Math.sin(dh), Math.cos(dh));
+ // Lateral error -> a heading limited to LANE_RATE across the road -> the yaw rate that reaches it -> the wheel for that rate.
+ const lim = LANE_RATE / v, want = clamp((LANES[g.lane] - lat) * LANE_GAIN / v, -lim, lim), full = v * Math.tan(C.steerRange(v / C.MPH) * Math.PI / 180) / C.PLAYER.wheelbase;
+ inp.steer = clamp((want - dh) * 3 / full, -1, 1); inp.hb = false;
+ },
+ tick(g, wdt) {
+ const c = g.car, v = C.speed(c);
+ if (g.prevV > KILL_SPEED && g.prevV - v > KILL_DELTA) return g.lose('totaled');
+ g.prevV = v;
+ if (c.blown) return g.lose('blown');
+ for (const r of g.rivals) M.stepRival(g, r, wdt);
+ const rv = g.rivals[0];
+ if (g.prog >= g.heatLen) {
+ g.events.push({ type: 'heat_won', heat: g.heat, gap: g.heatLen - rv.prog });
+ g.heat++;
+ if (g.heat >= g.heats) return g.win();
+ startHeat(g);
+ return;
+ }
+ if (rv.prog >= g.heatLen) g.lose('gap');
+ },
+ health(g) {
+ const rv = g.rivals[0], left = Math.max(0, g.heatLen - rv.prog), done = g.outcome === 'win' ? g.seriesLen : g.heat * g.heatLen + g.prog;
+ return [g.outcome === 'loss' ? 0 : left, g.heatLen, Math.max(0, g.seriesLen - done), g.seriesLen];
+ },
+ hud(g) { const rv = g.rivals[0]; return { label: 'Drag Race', detail: `Heat ${Math.min(g.heat + 1, g.heats)} / ${g.heats} · Rival needs ${Math.max(0, g.heatLen - rv.prog).toFixed(0)} m · ${g.pre > 0 ? 'RPM ' + Math.round(g.rev * 100) + '%' : 'Gear ' + (g.car.gear + 1)}` }; },
+ // Reference: launch inside the band, shift inside the window, change lanes for traffic, nitrous when nothing is close.
+ scripted(g) {
+ const holds = [[], [], [], [], [], []], c = g.car;
+ if (g.pre > 0) { // feather the throttle so the revs sit in the launch band when the lights go
+ let rev = g.rev, left = g.pre;
+ for (let i = 0; i < 6; i++) { const on = rev < (LAUNCH[0] + LAUNCH[1]) / 2 - 0.02 && left < 1.2; if (on) holds[i].push('W'); rev = clamp(rev + (on ? REV_UP : -REV_DOWN) * (2 / 60), 0, 1); left -= 2 / 60; }
+ return { holds, mouse: [0, 0, 0] };
+ }
+ const P = g.P, k = M.ctl.copyCar(c), fwd0 = Math.max(0, c.vx * Math.cos(c.h) + c.vy * Math.sin(c.h)); let press = -1;
+ // After a hit the box is still in a tall gear with almost no drive: one gear down per packet until the revs are useful.
+ const lug = c.gear > 0 && c.clutch <= 0 && fwd0 < C.TOPS[c.gear - 1] * 0.8;
+ for (let i = 0; i < 6; i++) {
+ const u = Math.max(0, k.vx * Math.cos(k.h) + k.vy * Math.sin(k.h)) / C.TOPS[k.gear];
+ if (press < 0 && k.gear < 5 && u >= 0.9) press = i;
+ C.carStep(k, { thr: 1, brk: false, steer: 0, hb: false, nos: false, manual: true, up: false, down: false, sbGrip: 0 }, 1 / 30, P);
+ }
+ // Lane plan: for each lane and a short wait before moving, the time until first contact with anything on the road.
+ const users = M.ctl.roadUsers(g, g.route), v = C.speed(c), lane = g.lane, HORIZON_S = 6, STAY_S = 3.4;
+ const contact = (target, wait) => {
+ // The same first-order lane servo the car runs (rate capped, gain LANE_GAIN), started 0.2 s late for the wheel to slew.
+ let lat = g.lat;
+ for (let t = 0.1; t < HORIZON_S; t += 0.1) {
+ if (t > wait + 0.2) lat += clamp((LANES[target] - lat) * LANE_GAIN, -LANE_RATE, LANE_RATE) * 0.1;
+ const sp = g.s + v * t;
+ for (const o of users) { const ds = o.s + o.vs * t - sp, ds0 = o.s + o.vs * (t - 0.1) - (g.s + v * (t - 0.1)); if (o.s > g.s + 1 && Math.abs(o.lat - lat) < 3.6 && ((ds > 1 && ds < 6.5) || (ds0 > 1 && ds <= 1))) return t; }
+ }
+ return HORIZON_S;
+ };
+ const here = contact(lane, 0);
+ let bestT = here, go = lane;
+ // Stay put until contact is near: a move costs nothing only if nothing else is decided on the way. Then take the lane
+ // that stays clear longest, nearer lanes first on a tie. A wrong late move is cheaper than weaving through everything.
+ if (here < STAY_S) { let bs = here; for (let l = 0; l < LANES.length; l++) { if (l === lane) continue; const t = contact(l, 0), v2 = t - 0.25 * Math.abs(l - lane); if (t > here + 0.5 && v2 > bs) { bs = v2; bestT = t; go = l; } } }
+ const move = Math.sign(go - lane);
+ // A blocked lane with nowhere to go: braking costs seconds on this gearing, a total above 100 mph costs the event.
+ const blocked = bestT < 0.8 && !move, coast = bestT < 1.2 && !move;
+ // Top gear on the limiter only cooks the engine (EngineRacer.cpp:1340): lift until the speed is back under it.
+ const onLimiter = c.gear === 5 && Math.max(0, c.vx * Math.cos(c.h) + c.vy * Math.sin(c.h)) >= C.TOPS[5] * 0.995;
+ const nos = c.nos > 0.02 && v > 30 && here > 3 && c.clutch <= 0 && !c.over && v < C.TOPS[5] * 0.97;
+ for (let i = 0; i < 6; i++) { if (blocked) holds[i].push('S'); else if (!onLimiter && !coast) holds[i].push('W'); if (nos && !blocked) holds[i].push('Shift'); if (i === press && !lug) holds[i].push('K'); if (i === 0 && lug) holds[i].push('L'); if (i === 0 && move) holds[i].push(move > 0 ? 'A' : 'D'); }
+ return { holds, mouse: [0, 0, 0] };
+ },
+ };
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/nfsmw_remake/modes_knockout.js b/environments/games/web/games/nfsmw_remake/modes_knockout.js
new file mode 100644
index 0000000000000000000000000000000000000000..9df70caef60df4591c69ff873679bef1d6cbec5c
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/modes_knockout.js
@@ -0,0 +1,57 @@
+/* Lap Knockout (GRace.h kRaceType_Knockout; GRaceStatus.h GRacerInfo::KnockOut, mKnockedOut). A short downtown circuit at night:
+ when every car but one has finished the lap, that last car is out. One lap per rival, so the field sets the length.
+ boss_hp = route metres left in the whole event; player_hp = metres the slowest remaining rival still needs to finish this
+ lap (at 0 every rival is home and the player is the one knocked out). The field and the circuit are original: race data is VLT. */
+(function (root) {
+ 'use strict';
+ const M = root.NfsmwGame, C = M.C, S0 = 40, ROW = 9;
+ M.MODES.knockout = {
+ route: () => 'downtown',
+ init(g, d) {
+ const R = g.route, field = Math.round(M.tierValue(d, [1, 2, 5]));
+ // The grid is short of the line, so lap 1 is partial and its length is part of the event's pace.
+ const first = Math.min(R.L, M.tierValue(d, [420, 520, 694])), start = R.L - first + S0;
+ g.L = R.L; g.first = first; g.laps = field; g.total = first + (field - 1) * R.L; g.lap = 0; g.s0 = start; g.placeCar(start, -2.2);
+ const lo = M.tierValue(d, [0.12, 0.2, 0.3]), hi = M.tierValue(d, [0.12, 0.34, 0.62]);
+ g.rivals = [];
+ // Two columns, a full row apart: the player is alone on the last row. Skill runs from the back of the grid to the front, as a Blacklist field does.
+ for (let i = 0; i < field; i++) {
+ const r = M.newRival(g, { s: start + ROW * (Math.floor(i / 2) + 1), lat: i % 2 ? -2.2 : 2.2, skill: C.clamp((field > 1 ? C.lerp(lo, hi, i / (field - 1)) : lo) + M.formOf(g), 0, 1), paint: i % 4 });
+ r.s0 = start; r.prog = r.s - start; g.rivals.push(r);
+ }
+ g.gates = [{ s: R.L + S0, at: 0, kind: 'line', keep: 1, done: 0 }];
+ M.spawnTraffic(g, Math.round(M.tierValue(d, [0, 2, 3])), { ahead: 120, spread: 260, opposing: 0 });
+ },
+ idle() {},
+ tick(g, wdt) {
+ const alive = g.rivals.filter(r => !r.out);
+ for (const r of alive) M.stepRival(g, r, wdt);
+ // Rivals ride rails, so they part sideways here rather than drive through each other.
+ for (let i = 0; i < alive.length; i++) for (let j = i + 1; j < alive.length; j++) {
+ const a = alive[i], b = alive[j], ds = a.s - b.s, dl = a.lat - b.lat;
+ if (Math.abs(ds) < 6 && Math.abs(dl) < 3.2) { const push = (dl >= 0 ? 1 : -1) * 2.4 * wdt, e = g.route.halfW - 2.1; a.lat = C.clamp(a.lat + push, -e, e); b.lat = C.clamp(b.lat - push, -e, e); if (Math.abs(ds) < 4.4 && a.v !== b.v) { const back = ds < 0 ? a : b; back.v = Math.max(0, back.v - 6 * wdt); } }
+ }
+ const end = g.first + g.lap * g.L, pending = alive.filter(r => r.prog < end), youIn = g.prog >= end;
+ if (!youIn && pending.length === 0) return g.lose('knocked');
+ // <= 1, not === 1: two rivals crossing on the same tick take pending from 2 to 0, and the last car still goes out.
+ if (youIn && pending.length <= 1) {
+ const out = pending[0] || alive.reduce((a, b) => b.prog < a.prog ? b : a); out.out = 1; out.gone = 1; g.events.push({ type: 'knockout', lap: g.lap }); g.lap++;
+ if (g.rivals.every(r => r.out)) { g.prog = g.total; g.win(); }
+ }
+ },
+ health(g) {
+ const end = g.first + g.lap * g.L; let worst = 0;
+ for (const r of g.rivals) if (!r.out) worst = Math.max(worst, end - r.prog);
+ // A win knocks out the last rival, so no rival is left to measure: player_hp stays full rather than reading as a loss.
+ return [g.outcome === 'loss' ? 0 : g.outcome === 'win' ? g.L : C.clamp(worst, 0, g.L), g.L, g.outcome === 'win' ? 0 : Math.max(0, g.total - g.prog), g.total];
+ },
+ hud(g) { const alive = g.rivals.filter(r => !r.out); const place = 1 + alive.filter(r => r.prog > g.prog).length; return { label: 'Lap Knockout', detail: `Lap ${Math.min(g.lap + 1, g.laps)} / ${g.laps} · Place ${place} / ${alive.length + 1} · Last-place rival needs ${M.MODES.knockout.health(g)[0].toFixed(0)} m` }; }, // draw.js calls hud unbound: no `this`
+ // Reference: a tighter line, and slow motion (J, the public Speedbreaker key: +2 g of downforce) only while it would brake,
+ // for a corner or for a car ahead. Seeds 1-32: normal 22 -> 32, hard 24 -> 32.
+ scripted(g) {
+ const opt = { margin: 0.96 }, pk = M.ctl.drive(g, opt);
+ if (g.pre <= 0) { const why = M.ctl.planDrive(g, opt).why, want = why === 'speed' || why === 'contact'; if (want !== !!g.sb && (g.sb || g.sbMeter > 0.15) && pk.holds[0].length < 4) pk.holds[0].push('J'); }
+ return pk;
+ },
+ };
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/nfsmw_remake/modes_pursuit.js b/environments/games/web/games/nfsmw_remake/modes_pursuit.js
new file mode 100644
index 0000000000000000000000000000000000000000..a08fa3edb87bbff291e51d8d8269fb695deae952
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/modes_pursuit.js
@@ -0,0 +1,437 @@
+/* Free-roam pursuit (AI/Common/AIPursuit.cpp, rules listed in cops.js). The event is the Blacklist's own gate: raise a bounty, then get away.
+ Bounty accrues only while a cop can see the player (:1920 AddToPendingRepPointsNormal runs inside the in-sight branch) and in lumps for
+ destroying cops, with the multiplier up to 3 (:917). Then the evade meter must fill. Clearing a stage raises the heat: after the lock-out
+ (:2061 LockoutCops) a new pursuit starts at the next level. The heat values are VLT data, so every number below is an approximation.
+ Pursuit Breakers: EPursuitBreaker exists in the decompilation, the placement and radius are map data; here two per lap, original.
+ boss_hp = stages x 200 minus bounty and evade progress, both from high-water marks, so it never jumps back; player_hp = the bust meter. */
+(function (root) {
+ 'use strict';
+ const M = root.NfsmwGame, C = M.C, N = root.NativeBench, clamp = C.clamp;
+ const BOUNTY_UNITS = 100, EVADE_UNITS = 100, S0 = 5560, BREAKER_R = 46;
+ const heat = (g, d) => {
+ const lvl = g.stage / Math.max(1, g.stages - 1); // inside the event the heat climbs a little, tier sets the base
+ return { copsMax: Math.round(M.tierValue(d, [2, 3, 5])) + (g.stage > 1 ? 1 : 0), top: M.tierValue(d, [52, 66, 70]) + lvl * 4 };
+ };
+ const startStage = (g, d) => {
+ const p = g.pol, h = heat(g, d);
+ p.copsMax = h.copsMax; p.top = h.top; p.seen = 0; p.sinceSeen = 0; p.evade = 0; p.lockT = g.stage ? 3 : 0; p.spawnT = g.stage ? 3.5 : p.spawnGap;
+ g.stageBounty = 0; g.stageEvadeHW = 0;
+ if (!g.stage) { const c = M.spawnCop(g, g.s - 85, 2, 1); c.slot = 0; c.v = 34; }
+ else g.events.push({ type: 'heat_up', stage: g.stage });
+ };
+ // ---------------- Reference controllers for these two events (2026-11-11 recalibration). Only these two events call them; the shared
+ // planDrive / drive in scripted.js are untouched. Read decided state only (poses, timers, the episode seed), never the live RNG: the
+ // champion's look-ahead rolls copies forward in a fixed independent scenario. Both keep a little memory per game object (WeakMap); a
+ // repeated call on the same state returns the same packet (tests/leak_probe.js asks five times per packet).
+
+ // Pursuit. The strategy follows whether this heat level brings a helicopter (g.pol.heli, fixed when the pursuit starts; the HUD shows
+ // helicopter once one is up). In the block's tight corners the cops lose sight within seconds, so without a helicopter (250 m sight) the bounty
+ // stops growing there: d = 0.65-0.7 timed out 8/8 when the switch was the stage count instead.
+ // - no helicopter: the 11-06 controller. While bounty is owed, hold station just ahead of the chase so it keeps sight; once the 7 s in-sight
+ // grace (cops.js inSight, AIPursuit.cpp:2000) covers what is owed with 5 s to spare, or the bounty is full, run on the racing line with
+ // nitrous, through any Pursuit Breaker with a cop near. Same rule at every tier (the 11-06 version started early on easy only).
+ // - helicopter: the downtown block, ported from the 600-hour dataset pipeline's tools/trajectory_dataset/pursuit_recovery_source_v87.js
+ // (read-only there; its route table, path smoothing and follower, config speed 42, owed 34, lane spread 3). Into the block by one of
+ // five connector streets, laps of its tight corners until the stage clears, back out to the coast between stages.
+ // Added to both: blown tyres are reset once no chasing cop is within 95 m (11-06 rule); on the block, a cop within 6 m with the car under
+ // BustSpeed + 2 means it is pinned, so it floors it instead of braking for the corner.
+ const pursuitPolicy = (() => {
+ const HIDE = true, HIDE_GAP = 175, HIDE_SEE = 520, SPEED = 42, OWED = 34, REENTER_OWED = 8, LANE_SPREAD = 3, EARLY_MARGIN = 5, RESET_NEAR = 95, UNPIN_R = 6, FAR_COP = 110, MID_COP = 70, TOP_FAR = 20, TOP_MID = 30;
+ const memory = new WeakMap();
+ function choice(g) { let n = g.seed ^ Math.imul(g.stage + 1, 0x9e3779b1); n = Math.imul(n ^ (n >>> 16), 0x21f0aaad); n = Math.imul(n ^ (n >>> 15), 0x735a2d97); return ((n ^ (n >>> 15)) >>> 0) / 4294967296; }
+ const lane = g => (choice(g) - 0.5) * 2 * LANE_SPREAD;
+ // Connector streets from the coast road into the downtown block (nfscore.js STREETS), outer end first.
+ const routes = [[[0, -520], [0, -80]], [[420, -520], [420, 3], [46, 3]], [[-400, -520], [-400, 0], [-85, 0]], [[0, 400], [0, 80]], [[-400, 560], [-400, 0], [-85, 0]]];
+ const nearestCop = g => { let near = Infinity; for (const k of g.cops) if (!k.dead && k.state !== 'rb') near = Math.min(near, Math.hypot(g.car.x - k.x, g.car.y - k.y)); return near; };
+ function sixSteer(c, target, sp, scale) {
+ const rate = (sp < 15 ? 7 : sp < 40 ? 5 : 3.6) * scale / 30, keys = []; let st = c.steer;
+ for (let i = 0; i < 6; i++) { let k0 = 0, error = Infinity; for (const k of [0, 1, -1]) { const n = st + clamp(k - st, -rate, rate), e = Math.abs(n - target); if (e < error) { error = e; k0 = k; } } keys.push(k0); st += clamp(k0 - st, -rate, rate); }
+ return keys;
+ }
+ // Drop collinear points, then round each corner with the largest arc (16, 12, 8 m) that stays on the road.
+ function smooth(points) {
+ const sparse = [points[0]];
+ for (let i = 1; i < points.length - 1; i++) {
+ const a = sparse[sparse.length - 1], b = points[i], c = points[i + 1], ux = b[0] - a[0], uy = b[1] - a[1], vx = c[0] - b[0], vy = c[1] - b[1], L = Math.hypot(ux, uy) * Math.hypot(vx, vy);
+ if (L < 0.01) continue;
+ if (Math.abs(ux * vy - uy * vx) / L < 0.01 && (ux * vx + uy * vy) / L > 0.999) continue;
+ sparse.push(b);
+ }
+ sparse.push(points[points.length - 1]); points = sparse;
+ const out = [points[0]];
+ for (let i = 1; i < points.length - 1; i++) {
+ const a = points[i - 1], b = points[i], c = points[i + 1], la = Math.hypot(b[0] - a[0], b[1] - a[1]), lc = Math.hypot(c[0] - b[0], c[1] - b[1]);
+ if (la < 30 || lc < 30) { out.push(b); continue; }
+ const ux = (a[0] - b[0]) / la, uy = (a[1] - b[1]) / la, vx = (c[0] - b[0]) / lc, vy = (c[1] - b[1]) / lc;
+ const theta = Math.acos(clamp(ux * vx + uy * vy, -1, 1)); if (theta < 0.3 || theta > 2.9) { out.push(b); continue; }
+ let arc = null;
+ for (const radius of [16, 12, 8]) {
+ const tangent = radius / Math.tan(theta / 2); if (tangent > Math.min(la, lc) * 0.4) continue;
+ const hl = Math.hypot(ux + vx, uy + vy), distance = radius / Math.sin(theta / 2), cx = b[0] + (ux + vx) / hl * distance, cy = b[1] + (uy + vy) / hl * distance;
+ const ax = b[0] + ux * tangent, ay = b[1] + uy * tangent, angle = Math.atan2(ay - cy, ax - cx), sign = -Math.sign(ux * vy - uy * vx), sweep = Math.PI - theta;
+ const n = Math.ceil(radius * sweep / 2), candidate = [];
+ for (let j = 0; j <= n; j++) { const t = angle + sign * sweep * j / n; candidate.push([cx + Math.cos(t) * radius, cy + Math.sin(t) * radius]); }
+ if (candidate.every(p => C.road(p[0], p[1]).d < -1.8)) { arc = candidate; break; }
+ }
+ out.push(...(arc || [b]));
+ }
+ out.push(points[points.length - 1]); return out;
+ }
+ // Pure pursuit along mem.points, speed limited by the path's curvature and the tyres; null at the end of the path.
+ function follow(g, mem) {
+ if (mem.rawPoints !== mem.points) { mem.points = smooth(mem.points); mem.rawPoints = mem.points; }
+ const c = g.car, sp = C.speed(c), points = mem.points; let i = mem.i;
+ while (i < points.length - 1) { const a = points[i], b = points[i + 1], dx = b[0] - a[0], dy = b[1] - a[1], l2 = dx * dx + dy * dy; const t = ((c.x - a[0]) * dx + (c.y - a[1]) * dy) / l2; if (t > 1 || Math.hypot(c.x - b[0], c.y - b[1]) < 3.5) { i++; continue; } break; }
+ mem.i = i;
+ if (i >= points.length - 1) return null;
+ const a = points[i], b = points[i + 1], dx = b[0] - a[0], dy = b[1] - a[1], length = Math.hypot(dx, dy);
+ const t = clamp(((c.x - a[0]) * dx + (c.y - a[1]) * dy) / (length * length), 0, 1), remaining = length * (1 - t);
+ let look = Math.max(5, sp * 0.45), x = a[0] + dx * t, y = a[1] + dy * t, j = i;
+ while (look > 0 && j < points.length - 1) { const dest = points[j + 1], d = Math.hypot(dest[0] - x, dest[1] - y); if (d >= look) { x += (dest[0] - x) * look / d; y += (dest[1] - y) * look / d; break; } look -= d; x = dest[0]; y = dest[1]; j++; }
+ const lag = 0.1 * (g.sb ? 0.45 : 1); let angle = Math.atan2(y - c.y - c.vy * lag, x - c.x - c.vx * lag) - c.h - c.r * lag; angle = Math.atan2(Math.sin(angle), Math.cos(angle));
+ const L = Math.max(3, Math.hypot(x - c.x, y - c.y)), kappa = 2 * Math.sin(angle) / L;
+ const nose = C.road(c.x + Math.cos(c.h) * 3.2, c.y + Math.sin(c.h) * 3.2).d > -0.5;
+ if (sp < 7 && (Math.abs(angle) > 0.9 || nose)) {
+ const clear = C.road(c.x - Math.cos(c.h) * 3.5, c.y - Math.sin(c.h) * 3.5).d < -0.6, side = angle > 0 ? 1 : -1;
+ const pk = M.ctl.toPacket({ keys: sixSteer(c, clear ? -side : side, sp, g.sb ? 0.45 : 1), thr: clear ? 0 : 6, brk: clear, nos: false });
+ if (g.sb) pk.holds[0].push('J'); return pk;
+ }
+ const target = clamp(Math.atan(kappa * C.PLAYER.wheelbase) / (C.steerRange(sp / C.MPH) * Math.PI / 180), -1, 1);
+ const end = !mem.continuous && i + 1 === points.length - 1;
+ let future = SPEED, ds = -length * t, upcoming = 0;
+ const grip = (C.PLAYER.grip + (g.sb ? 19.62 : 0)) * C.tireFactor(c) * 0.78;
+ for (let k = i; k < points.length - 2 && ds < 150; k++) {
+ const a = points[k], b = points[k + 1], c0 = points[k + 2], d1 = Math.hypot(b[0] - a[0], b[1] - a[1]), d2 = Math.hypot(c0[0] - b[0], c0[1] - b[1]), d3 = Math.hypot(c0[0] - a[0], c0[1] - a[1]);
+ ds += d1; const curv = Math.abs(2 * ((b[0] - a[0]) * (c0[1] - b[1]) - (b[1] - a[1]) * (c0[0] - b[0])) / Math.max(0.001, d1 * d2 * d3));
+ if (ds < sp * 1.5 + 10) upcoming = Math.max(upcoming, curv);
+ if (curv > 0.0001) future = Math.min(future, Math.sqrt(grip / curv + 2 * 8 * Math.max(0, ds - 6)));
+ }
+ const limit = Math.min(future, Math.sqrt(grip / (Math.abs(kappa) + 0.0001)), end ? Math.sqrt(2 * 8 * Math.max(0, remaining - 3)) : SPEED);
+ const brk = sp > limit + 0.8, keys = sixSteer(c, brk ? target / 1.45 : target, sp, g.sb ? 0.45 : 1);
+ const spare = Math.max(0, 1 - sp * sp * Math.abs(kappa) / grip);
+ const thr = Math.max(1, Math.min(6, Math.round(6 * spare / 0.55)));
+ let pinned = false; for (const k of g.cops) if (!k.dead && k.state !== 'rb' && Math.hypot(c.x - k.x, c.y - k.y) < UNPIN_R) pinned = true;
+ pinned = pinned && sp < g.pol.bustSpeed + 2;
+ const pk = pinned ? M.ctl.toPacket({ keys: sixSteer(c, target, sp, g.sb ? 0.45 : 1), thr: 6, brk: false, nos: c.nos > 0.02 }) : M.ctl.toPacket({ keys, thr: brk ? 0 : thr, brk, nos: false });
+ const want = (upcoming > 0.035 || Math.abs(angle) > 0.3) && sp > 10;
+ if (want !== !!g.sb && (g.sb || g.sbMeter > 0.2) && pk.holds[0].length < 4) pk.holds[0].push('J');
+ return pk;
+ }
+ const nearestS = (R, x, y) => { let best = 0, dist = Infinity; for (let i = 0; i < R.n; i++) { const d = Math.hypot(R.x[i] - x, R.y[i] - y); if (d < dist) { dist = d; best = i * R.ds; } } return best; };
+ // One lap of the downtown block starting at the point nearest (x, y). routeAt returns one shared object: copy before the next call.
+ function lapFrom(x, y) { const R = C.routes.downtown, best = nearestS(R, x, y), pts = []; for (let s = 4; s < R.L + 4; s += 4) { const p = C.routeAt(R, best + s); pts.push([p.x, p.y]); } const last = C.routeAt(R, best); pts.push([last.x, last.y]); return pts; }
+ function startReturn(g, mem, escape, entryS) {
+ const join = { ...C.routeAt(g.route, entryS + 35) };
+ mem.points = [[g.car.x, g.car.y], ...escape.slice(0, -1).reverse(), [join.x, join.y]]; mem.i = 0; mem.mode = 'return'; mem.continuous = false; mem.returnPending = false;
+ mem.escape = escape; mem.entryS = entryS;
+ }
+ // One heat stage: the 11-06 coast run.
+ function coastRun(g, owed, p) {
+ const R = g.route, nearest = nearestCop(g), opt = { ram: true }, covered = 7 - p.sinceSeen - EARLY_MARGIN > owed;
+ // Hide: bounty full, nobody sees the car, and a roadblock is already set up ahead (g.blocks, decided state). Driving past it re-sights the
+ // car (50 m all round, AIVehicleCopCar.cpp:88-89) and restarts the 7 s + evade clock; instead stop HIDE_GAP m short of it, outside its
+ // 150 m view, and let the evade meter run. A car under 15 m/s draws no new roadblock (cops.js stepRoadblocks).
+ if (HIDE && owed <= 0 && !p.sawNow) { let ahead = Infinity; for (const b of g.blocks) { const ds = M.wrapTo(R, b.s, g.s) - g.s; if (ds > 0 && ds < ahead) ahead = ds; }
+ if (ahead < HIDE_SEE) { const room = ahead - HIDE_GAP, sp = C.speed(g.car); if (room < 3) return M.ctl.toPacket({ thr: 0, brk: sp > 2, nos: false }); return M.ctl.drive(g, { ram: true, nos: false, top: Math.max(4, Math.sqrt(2 * 8 * Math.max(0, room - 3))) }); } }
+ if (owed > 0 && !covered) { opt.nos = false; if (nearest > FAR_COP || !p.sawNow) opt.top = TOP_FAR; else if (nearest > MID_COP) opt.top = TOP_MID; }
+ if (owed <= 0 || covered) for (const b of g.breakers) { const ds = M.wrapTo(R, b.s, g.s) - g.s; if (ds > 0 && ds < 130 && !b.rearm && nearest < 90) opt.lat = b.lat; }
+ return M.ctl.drive(g, opt);
+ }
+ return function policy(g) {
+ let mem = memory.get(g); if (!mem) { mem = { stage: g.stage, mode: 'coast' }; memory.set(g, mem); }
+ if (g.car.tires > 0 && g.flash <= 0 && nearestCop(g) > RESET_NEAR) { mem.mode = 'coast'; mem.reenter = mem.reenter || g.bountyNeed - g.stageBounty > 0; return { holds: [['R'], [], [], [], [], []], mouse: [0, 0, 0] }; }
+ const owed = g.bountyNeed - g.stageBounty, p = g.pol;
+ if (!g.pol.heli) return coastRun(g, owed, p);
+ if (g.stage !== mem.stage) {
+ mem.stage = g.stage;
+ if (mem.mode === 'city') mem.returnPending = false;
+ else if (mem.mode !== 'coast') startReturn(g, mem, mem.escape, mem.entryS);
+ }
+ if (mem.mode === 'city') {
+ const pk = follow(g, mem); if (pk) return pk;
+ if (mem.returnPending) { startReturn(g, mem, mem.escape, mem.entryS); return follow(g, mem); }
+ mem.points = [[g.car.x, g.car.y], ...mem.cityPoints]; mem.i = 0; return follow(g, mem);
+ }
+ if (mem.mode === 'return' || mem.mode === 'inside') {
+ if (mem.mode === 'inside' && mem.i >= mem.points.length - 2) mem.continuous = true;
+ const pk = follow(g, mem); if (pk) return pk;
+ mem.continuous = false; mem.mode = 'coast';
+ }
+ if (mem.mode === 'coast' && owed <= (mem.reenter ? REENTER_OWED : OWED)) {
+ mem.reenter = false;
+ const R = g.route, choices = routes.map(points => { const best = nearestS(R, points[0][0], points[0][1]); let ds = (best - g.s) % R.L; if (ds < 30) ds += R.L; return { points, s: g.s + ds, ds }; });
+ const ranked = choices.sort((a, b) => a.ds - b.ds), options = ranked.filter(r => r.ds < ranked[0].ds + 1100).slice(0, 3);
+ const target = options[Math.min(options.length - 1, Math.floor(choice(g) * options.length))];
+ mem.escape = target.points.map(q => q.slice()); mem.entryS = target.s; mem.mode = 'approach';
+ }
+ if (mem.mode === 'approach') {
+ const distance = mem.entryS - g.s;
+ if (distance < 100) {
+ const approach = { ...C.routeAt(g.route, mem.entryS - 150) }, end = mem.escape[mem.escape.length - 1];
+ mem.cityPoints = lapFrom(end[0], end[1]);
+ mem.points = [[approach.x, approach.y], ...mem.escape, ...mem.cityPoints]; mem.i = 0; mem.mode = 'city'; mem.continuous = true;
+ return follow(g, mem);
+ }
+ return M.ctl.drive(g, { ram: true, lat: lane(g), margin: 0.9, top: Math.min(70, Math.sqrt(12 * 12 + 2 * 8 * Math.max(0, distance - 12))) });
+ }
+ return M.ctl.drive(g, { ram: true, lat: lane(g), margin: 0.9 });
+ };
+ })();
+
+ // Street champion. Ported from the dataset pipeline's tools/trajectory_dataset/street_interaction_source_v42.js (read-only there). v42
+ // replaced the page's M.ctl with a modified copy of scripted.js; here that copy is private to this event. Kept from v42: lane choice with
+ // hysteresis, Speedbreaker grip in the racing line and friction circle, and each packet picks one of nine driving choices by rolling copies
+ // of the game 120 ticks forward with the RNG set to one fixed scenario (never the live RNG). Added: blown tyres are reset once no chasing
+ // cop is within 95 m (the 11-06 rule v42 dropped), and a roadblock already placed ahead (g.blocks, decided state) adds its widest gap as a
+ // candidate lane and pulls the score towards it: a 2 s rollout cannot see a block 300 m away, and at 55 m/s the car cannot cross the
+ // road in the 2 s it does see (seeds 4, 8, 13, 22, 24 hard: busted or out-run behind a block).
+ const championPolicy = (() => {
+ const HOLD_SETS = 6, DT = 1 / 60, CONTACT = 3.5, RESET_NEAR = 95, GAP_AHEAD = 360, GAP_CLEAR = 3.3, GAP_EDGE = 1.6, GAP_PULL = 8;
+ const laneMem = new WeakMap();
+ function laneTarget(g, R, S, others, speed, base) {
+ const edge = R.halfW - 2.2, prev = laneMem.get(g) ?? g.lat;
+ const lanes = [clamp(prev, -edge, edge), base, -edge, edge, -edge * .5, 0, edge * .5];
+ let best = lanes[0], bs = -Infinity;
+ for (const lat of lanes) {
+ let sc = -Math.abs(lat - prev) * 3 - .15 * Math.abs(lat - base);
+ for (const o of others) {
+ const ds = o.s - S; if (ds < -10 || ds > 200) continue;
+ const closing = speed - o.vs, tt = closing > 1 ? Math.max(0, ds) / closing : ds < 30 ? 0.5 : 99;
+ if (tt > 4) continue;
+ const gap = Math.abs(o.lat + (o.vl || 0) * Math.min(tt, 1) - lat);
+ if (gap < 3.8) sc -= (3.8 - gap) * (5 - tt) * 5;
+ }
+ if (sc > bs) { bs = sc; best = lat; }
+ }
+ laneMem.set(g, best); return best;
+ }
+ function roadUsers(g, R) {
+ const out = [], L = R.L;
+ const near = v => { if (!R.loop) return v; let ds = (v - g.s) % L; if (ds > L / 2) ds -= L; else if (ds < -L / 2) ds += L; return Math.abs(v - g.s) <= L / 2 ? v : g.s + ds; };
+ for (const t of g.traffic) out.push({ s: near(t.s), lat: t.lat, vs: t.crash ? 0 : t.v, r: 2 });
+ for (const r of g.rivals) if (!r.out) out.push({ s: near(r.s), lat: r.lat, vs: r.v, r: 2, a: r.v < 25 ? 5 : 0 });
+ M.copUsers(g, R, out);
+ return out;
+ }
+ const lines = new Map();
+ function racingLine(R, P, grip, brake, top) {
+ let L = lines.get(R.name);
+ if (!L) {
+ const n = R.n, lat = new Float64Array(n), edge = R.halfW - 2.4, wrap = i => R.loop ? (i + n) % n : Math.max(0, Math.min(n - 1, i)), K = Math.max(2, Math.round(10 / R.ds));
+ const nx = i => -Math.sin(R.h[i]), ny = i => Math.cos(R.h[i]), px = i => R.x[i] + nx(i) * lat[i], py = i => R.y[i] + ny(i) * lat[i];
+ for (let it = 0; it < 400; it++) for (let i = 0; i < n; i++) { const a = wrap(i - K), b = wrap(i + K), tx = (px(a) + px(b)) / 2 - px(i), ty = (py(a) + py(b)) / 2 - py(i); lat[i] = clamp(lat[i] + 0.5 * (tx * nx(i) + ty * ny(i)), -edge, edge); }
+ const kap = new Float64Array(n);
+ for (let i = 0; i < n; i++) { const a = wrap(i - K), b = wrap(i + K), x1 = px(i) - px(a), y1 = py(i) - py(a), x2 = px(b) - px(i), y2 = py(b) - py(i), l1 = Math.hypot(x1, y1), l2 = Math.hypot(x2, y2), l3 = Math.hypot(x1 + x2, y1 + y2); kap[i] = l1 && l2 && l3 ? Math.abs(2 * (x1 * y2 - y1 * x2) / (l1 * l2 * l3)) : 0; }
+ L = { lat, kap, prof: new Map() }; lines.set(R.name, L);
+ }
+ const key = [grip, brake, top].map(v => v.toFixed(3)).join('|'); let v = L.prof.get(key);
+ if (!v) {
+ v = new Float64Array(R.n);
+ for (let i = 0; i < R.n; i++) v[i] = L.kap[i] > P.aero + 1e-5 ? Math.min(top, Math.sqrt(grip / (L.kap[i] - P.aero))) : top;
+ for (let p = 0; p < (R.loop ? 2 : 1); p++) for (let i = R.n - 1; i >= 0; i--) { const j = i + 1 < R.n ? i + 1 : R.loop ? 0 : i, lim = Math.sqrt(v[j] * v[j] + 2 * brake * R.ds); if (lim < v[i]) v[i] = lim; }
+ L.prof.set(key, v);
+ }
+ return { lat: L.lat, prof: v };
+ }
+ const lineLat = (R, lat, s) => { let i = Math.round(s / R.ds); if (R.loop) { i %= R.n; if (i < 0) i += R.n; } else i = clamp(i, 0, R.n - 1); return lat[i]; };
+ function contactTime(g, others, S, speed, lat) {
+ const rate = 4, HORIZON_S = 3;
+ for (let t = 0.1; t < HORIZON_S; t += 0.1) {
+ const dl = lat - g.lat, l = g.lat + Math.sign(dl) * Math.min(Math.abs(dl), rate * t), sp = S + speed * t;
+ for (const o of others) {
+ if (o.s <= S) continue;
+ const ol = o.lat + (o.vl || 0) * Math.min(t, 2), ds = o.s + o.vs * t + 0.5 * (o.a || 0) * t * t - sp, t0 = t - 0.1, ds0 = o.s + o.vs * t0 + 0.5 * (o.a || 0) * t0 * t0 - (S + speed * t0);
+ if (Math.abs(ol - l) < CONTACT && ((ds > 0 && Math.hypot(ds, ol - l) < CONTACT) || (ds0 > 0 && ds <= 0))) return t;
+ }
+ }
+ return HORIZON_S;
+ }
+ function steerKeys(c, target, speed, wscale) {
+ const rate = (speed < 15 ? 7 : speed < 40 ? 5 : 3.6) * wscale * 2 * DT, out = []; let st = c.steer;
+ for (let i = 0; i < HOLD_SETS; i++) {
+ let best = 0, bd = Infinity;
+ for (const k of [0, 1, -1]) { const n = st + clamp(k - st, -rate, rate), e = Math.abs(n - target); if (e < bd - 1e-9) { bd = e; best = k; } }
+ out.push(best); st += clamp(best - st, -rate, rate);
+ }
+ return out;
+ }
+ function planDrive(g, opt = {}) {
+ const R = g.route, c = g.car, P = g.P || C.PLAYER, S = g.s, speed = C.speed(c), tire = C.tireFactor(c);
+ const margin = opt.margin || 0.92, top = opt.top || C.TOPS[5], wscale = g.sb ? 0.45 : 1;
+ const line = racingLine(R, P, (P.grip + 19.62 * (g.sb ? 1 : g.sbRamp / (1 / 3))) * tire * margin, P.brake * 0.8, top), prof = line.prof;
+ const others = roadUsers(g, R), base = opt.lat !== undefined ? opt.lat : lineLat(R, line.lat, S + speed * 0.8), lat = opt.fixedLane ? base : laneTarget(g, R, S, others, speed, base), onLine = lat === base && opt.lat === undefined;
+ const lag = 0.1 * wscale, px = c.x + c.vx * lag, py = c.y + c.vy * lag, ph = c.h + c.r * lag, Ld = Math.max(7, speed * 0.62);
+ const sNear = C.routeNear(R, px, py, S, 8, 16), aim = C.routeAt(R, sNear + Ld, onLine ? lineLat(R, line.lat, sNear + Ld) : lat);
+ let alpha = Math.atan2(aim.y - py, aim.x - px) - ph; alpha = Math.atan2(Math.sin(alpha), Math.cos(alpha));
+ const far = C.routeAt(R, S + 18, lat); let off = Math.atan2(far.y - c.y, far.x - c.x) - c.h; off = Math.atan2(Math.sin(off), Math.cos(off));
+ const nose = C.road(c.x + Math.cos(c.h) * 3.2, c.y + Math.sin(c.h) * 3.2).d > -0.5;
+ if (speed < 7 && (Math.abs(off) > 0.9 || nose)) {
+ const clearBehind = C.road(c.x - Math.cos(c.h) * 3.5, c.y - Math.sin(c.h) * 3.5).d < -0.6, side = off > 0 ? 1 : -1;
+ return { keys: steerKeys(c, clearBehind ? -side : side, speed, wscale), thr: clearBehind ? 0 : HOLD_SETS, brk: clearBehind, nos: false, lat, contact: 3, why: 'recover' };
+ }
+ const kappa = 2 * Math.sin(alpha) / Ld, delta = Math.atan(kappa * P.wheelbase), range = C.steerRange(speed / C.MPH) * Math.PI / 180;
+ const vlim = Math.min(C.profileAt(R, prof, S + speed * 0.2), C.profileAt(R, prof, S + speed * 0.45));
+ const contact = contactTime(g, opt.ram ? others.filter(o => !o.cop) : others, S, speed, lat), over = speed > vlim + 0.8, brk = over || contact < 0.8, coast = !brk && contact < 1.2;
+ const grip = (P.grip + 19.62 * (g.sb ? 1 : g.sbRamp / (1 / 3)) + P.aero * speed * speed) * tire, ay = speed * speed * Math.abs(kappa), spare = Math.max(0, 1 - ay / grip);
+ const allowed = spare / 0.55 * grip * 1.1, drive = Math.max(1, C.driveAt(speed) * P.accel), thr = coast ? 0 : Math.round(HOLD_SETS * clamp(allowed / drive, 0.17, 1));
+ const nos = !brk && !coast && (opt.forceNos ? c.nos > 0.02 && speed > 12 : c.nos > 0.02 && speed > 18 && opt.nos !== false && thr === HOLD_SETS && C.profileAt(R, prof, S + speed * 1.8) > speed + 8);
+ return { keys: steerKeys(c, clamp(delta / range, -1, 1), speed, wscale), thr: brk ? 0 : thr, brk, nos, lat, contact, why: over ? 'speed' : contact < 0.8 ? 'contact' : coast ? 'coast' : 'drive' };
+ }
+ function toPacket(plan) {
+ const holds = [];
+ for (let i = 0; i < HOLD_SETS; i++) {
+ const h = [], k = plan.keys ? plan.keys[i] : 0;
+ if (plan.brk) h.push('S'); else if (plan.thr >= HOLD_SETS || Math.floor((i + 1) * plan.thr / HOLD_SETS) > Math.floor(i * plan.thr / HOLD_SETS)) h.push('W');
+ if (k) h.push(k > 0 ? 'A' : 'D');
+ if (plan.nos) h.push('Shift');
+ holds.push(h);
+ }
+ return { holds, mouse: [0, 0, 0] };
+ }
+ function packet(g, choice) {
+ if (g.pre > .21) return toPacket({ thr: HOLD_SETS, brk: false, nos: false });
+ const opt = { ram: true, margin: 1.02 }; if (choice.lat !== null) { opt.lat = choice.lat; opt.fixedLane = true; }
+ const p = planDrive(g, opt), sp = C.speed(g.car);
+ if (choice.gas && p.why !== 'recover') { p.brk = false; p.thr = 6; p.nos = g.car.nos > .02 && sp > 18; }
+ const pk = toPacket(p);
+ const sb = choice.sb === undefined ? (sp > 18 && (p.why === 'speed' || Math.abs(g.car.steer) > .65)) : choice.sb;
+ if (sb !== !!g.sb && (g.sb || g.sbMeter > .2) && pk.holds[0].length < 4) pk.holds[0].push('J');
+ return pk;
+ }
+ // Keys held at the end of the last packet, kept per game tick so a repeated call on one state starts every rollout from the same keys.
+ const heldMem = new WeakMap();
+ const heldBefore = g => { const m = heldMem.get(g); return !m ? [] : m.t === g.t ? m.prev : m.next; };
+ const heldAfter = (g, next) => heldMem.set(g, { t: g.t, prev: heldBefore(g), next });
+ function session(g, held) {
+ const s = Object.create(N.Session.prototype); s.module = M; s.game = M.copyGame(g);
+ s.game.rng = 2463534242; s.game.seed = 0; s.held = held.slice(); s.inputs = []; s.recording = false; s.events = []; // one fixed scenario, not the live draws
+ return s;
+ }
+ // The widest free stretch across the next roadblock within GAP_AHEAD m: between parked cars, barriers and the road edges.
+ function roadblockGap(g) {
+ const R = g.route, hw = R.halfW; let S = Infinity;
+ for (const b of g.blocks) { const bs = M.wrapTo(R, b.s, g.s); if (bs > g.s + 3 && bs < S) S = bs; }
+ if (S === Infinity || S - g.s > GAP_AHEAD) return null;
+ const occ = []; for (const b of g.blocks) if (Math.abs(M.wrapTo(R, b.s, g.s) - S) < 1) occ.push([b.lat - GAP_CLEAR, b.lat + GAP_CLEAR]);
+ occ.sort((x, y) => x[0] - y[0]);
+ let lo = -hw + GAP_EDGE, best = null; const hi = hw - GAP_EDGE;
+ for (const [x, y] of occ) { if (x > lo && (!best || Math.min(x, hi) - lo > best[1] - best[0])) best = [lo, Math.min(x, hi)]; lo = Math.max(lo, y); }
+ if (hi > lo && (!best || hi - lo > best[1] - best[0])) best = [lo, hi];
+ return best && best[1] > best[0] ? { s: S, lat: (best[0] + best[1]) / 2 } : null;
+ }
+ return function policy(g) {
+ if (g.car.tires > 0 && g.flash <= 0) {
+ let near = Infinity; for (const k of g.cops) if (!k.dead && k.state !== 'rb') near = Math.min(near, Math.hypot(g.car.x - k.x, g.car.y - k.y));
+ if (near > RESET_NEAR) { heldAfter(g, []); return { holds: [['R'], [], [], [], [], []], mouse: [0, 0, 0] }; }
+ }
+ const held = heldBefore(g), edge = g.route.halfW - 2.6;
+ const choices = [{ lat: null }, { lat: g.lat }, { lat: -edge * .85 }, { lat: edge * .85 }, { lat: -edge * .4 }, { lat: edge * .4 },
+ { lat: null, gas: true }, { lat: g.lat, gas: true }, { lat: null, sb: true }];
+ const gap = roadblockGap(g); if (gap) choices.push({ lat: gap.lat }, { lat: gap.lat, gas: true });
+ let best = null, bestScore = -Infinity;
+ for (const choice of choices) {
+ const s = session(g, held), first = packet(s.game, choice); let proximity = 0;
+ for (let t = 0; t < 120 && !s.game.outcome; t += 12) {
+ s.packet(t === 0 ? first : packet(s.game, choice));
+ const z = s.game, sp = C.speed(z.car);
+ for (const cop of z.cops) if (!cop.dead && !cop.gone) { const d = Math.hypot(z.car.x - cop.x, z.car.y - cop.y); proximity = Math.max(proximity, Math.max(0, 4 - d) * (sp < 15 ? 3 : 1)); }
+ }
+ const z = s.game, road = C.routeAt(z.route, z.s), a = N.angle(z.car.h - road.h);
+ const score = (z.prog - g.prog) * 3 + C.speed(z.car) * .65 - (z.hits - g.hits) * 8
+ - (z.pol.bust - g.pol.bust) * 90 - (z.car.tires - g.car.tires) * 200 - proximity * 12
+ - Math.max(0, Math.abs(z.lat) - edge) * 10 - a * a * 5 + (z.car.nos - g.car.nos) * 8
+ + (z.outcome === 'win' ? 100000 : 0) - (z.outcome && z.outcome !== 'win' ? 100000 : 0)
+ - (gap && z.s < gap.s ? Math.abs(z.lat - gap.lat) * GAP_PULL : 0);
+ if (score > bestScore) { bestScore = score; best = first; }
+ }
+ heldAfter(g, best.holds[5].slice().sort()); return best;
+ };
+ })();
+
+ M.MODES.pursuit = {
+ route: () => 'coast',
+ init(g, d) {
+ g.s0 = S0; g.total = 1e9; g.pre = 0; g.placeCar(S0, -2.5, 34); g.car.gear = 3; // spotted at speed: a pursuit has no starting grid
+ g.stages = Math.round(M.tierValue(d, [1, 1, 3])); g.stage = 0; g.diff = d;
+ g.bountyNeed = M.tierValue(d, [10, 32, 34]); g.prog = 0;
+ M.initPolice(g, { copsMax: 2, top: 60, grip: M.tierValue(d, [0.78, 0.85, 0.92]), accel: M.tierValue(d, [0.8, 0.95, 1.05]), spawnGap: M.tierValue(d, [12, 9, 7]), formations: d < 0.35 ? ['FOLLOW'] : d < 0.7 ? ['FOLLOW', 'ROLLING_BLOCK', 'PIT'] : ['FOLLOW', 'ROLLING_BLOCK', 'BOX_IN', 'PIT'],
+ rbChance: M.tierValue(d, [0, 0.45, 0.7]), spikeChance: M.tierValue(d, [0, 0.25, 0.5]), rbGap: M.tierValue(d, [8, 7, 6]), heli: d > 0.7, heliAfter: 30, heliFuel: 22, heliGap: 30, bustSpeed: M.tierValue(d, [7, 10, 13]), searchTop: M.tierValue(d, [34, 42, 50]), close: M.tierValue(d, [8, 11, 14]), copFrail: 3.2, aheadChance: M.tierValue(d, [0.25, 0.35, 0.45]), evadeTimeout: M.tierValue(d, [8, 13, 15]) });
+ g.breakers = []; const R = g.route;
+ for (const off of [500, 1500, 2600, 3600, 4600]) { for (const side of [1]) { const s = (S0 + off) % R.L, a = C.routeAt(R, s, side * (R.halfW - 1.5)); g.breakers.push({ s, lat: side * (R.halfW - 2.5), x: a.x, y: a.y, h: a.h, fired: 0, rearm: 0 }); } }
+ g.bountyTotal = 0;
+ startStage(g, d);
+ M.spawnTraffic(g, Math.round(M.tierValue(d, [4, 7, 10])));
+ },
+ idle(g) { for (const c of g.cops) { const a = C.routeAt(g.route, c.s, c.lat); c.x = a.x; c.y = a.y; c.h = a.h; } },
+ tick(g, wdt) {
+ const p = g.pol, R = g.route, before = p.destroyed;
+ M.stepPolice(g, wdt, g.stageBounty >= g.bountyNeed);
+ if (g.outcome) return;
+ // Pursuit Breaker: driving through the structure brings it down on whatever is around it.
+ for (const b of g.breakers) {
+ if (b.rearm > 0) b.rearm -= wdt;
+ const bs = M.wrapTo(R, b.s, g.s);
+ if (!b.rearm && Math.abs(g.s - bs) < C.speed(g.car) * wdt + 2 && Math.abs(g.lat - b.lat) < 3.4) {
+ b.rearm = 60; g.events.push({ type: 'trap_collapse' });
+ for (const c of g.cops) if (!c.dead && c.state !== 'rb' && Math.hypot(c.x - b.x, c.y - b.y) < BREAKER_R) M.destroyCop(g, c, 'breaker');
+ for (const t of g.traffic) if (!t.crash && Math.hypot(t.x - b.x, t.y - b.y) < 14) { t.crash = 0.6; t.vx = Math.cos(t.h) * Math.abs(t.v) * 0.4; t.vy = Math.sin(t.h) * Math.abs(t.v) * 0.4; }
+ }
+ }
+ // Bounty: seconds in sight, plus a lump per destroyed cop x the multiplier.
+ if (g.stageBounty < g.bountyNeed) {
+ if (p.inSight) g.stageBounty += wdt;
+ if (p.destroyed > before) g.stageBounty += 1.5 * p.bonusMult * (p.destroyed - before);
+ g.stageBounty = Math.min(g.bountyNeed, g.stageBounty);
+ }
+ g.stageEvadeHW = Math.max(g.stageEvadeHW, g.stageBounty >= g.bountyNeed ? p.evade : 0);
+ if (p.evade >= 1 && g.stageBounty >= g.bountyNeed) {
+ g.events.push({ type: 'evaded', stage: g.stage }); g.stage++;
+ if (g.stage >= g.stages) return g.win();
+ for (const c of g.cops) c.gone = 1; g.cops = [];
+ p.evade = 0; startStage(g, g.diff);
+ }
+ },
+ health(g) {
+ const total = g.stages * (BOUNTY_UNITS + EVADE_UNITS);
+ if (g.outcome === 'win') return [M.bustHp(g), 50, 0, total];
+ const done = g.stage * (BOUNTY_UNITS + EVADE_UNITS) + BOUNTY_UNITS * g.stageBounty / g.bountyNeed + EVADE_UNITS * g.stageEvadeHW;
+ return [g.outcome === 'loss' ? 0 : M.bustHp(g), 50, Math.max(0, total - done), total];
+ },
+ hud(g) { const p = g.pol, s = Math.min(g.stage + 1, g.stages); return { label: 'Police pursuit', detail: `Heat ${s} / ${g.stages} · Bounty ${(100 * g.stageBounty / g.bountyNeed).toFixed(0)}% · Escape ${(100 * p.evade).toFixed(0)}% · Cops ${g.cops.filter(c => !c.dead).length}${g.heli ? ' · Helicopter' : ''}` }; },
+ // Reference controller: pursuitPolicy above.
+ scripted(g) { return pursuitPolicy(g); },
+ hudExtra(g, c, u) { const p = g.pol; if (p.bust > 0.03) { c.font = 'bold 13px "Microsoft YaHei",sans-serif'; c.fillStyle = '#ff6a5a'; c.textAlign = 'center'; c.fillText('Busted ' + Math.round(100 * p.bust / M.BUST_MAX) + '%', u.W / 2, 78); c.textAlign = 'left'; } },
+ };
+ // Razor. GRace kRaceType_P2P with GetIsPursuitRace: the rival and the police at once. Wikipedia: the rematch is "another 5-street racing pink
+ // slip". Streets are legs of the route here; the player must keep ahead of Razor while the chase is on.
+ // boss_hp = route metres left; player_hp = the lesser of Razor's remaining share and the bust meter's, per mille.
+ M.MODES.street_champion = {
+ route: () => 'coast',
+ init(g, d) {
+ const S = 1500; g.s0 = S; g.total = Math.max(120, M.tierValue(d, [920, 2500, 7000])); g.legs = Math.max(1, Math.round(M.tierValue(d, [1, 2, 5]))); /* floors: d < 0.05 extrapolated to a negative route and 0 streets */ g.placeCar(S, -2.2);
+ g.rivals = [M.newRival(g, { s: S + 9, lat: 2.2, skill: C.clamp(M.tierValue(d, [0.1, 0.3, 0.5]) + M.formOf(g), 0, 1), paint: 3, name: 'champion' })];
+ g.rivals[0].s0 = S; g.rivals[0].prog = 9; g.glue = 0.7;
+ M.initPolice(g, { copsMax: Math.round(M.tierValue(d, [1, 2, 4])), top: M.tierValue(d, [56, 62, 66]), grip: M.tierValue(d, [0.75, 0.82, 0.9]), accel: M.tierValue(d, [0.75, 0.9, 1]), spawnGap: M.tierValue(d, [16, 12, 9]), formations: d < 0.35 ? ['FOLLOW'] : ['FOLLOW', 'ROLLING_BLOCK', 'PIT'], rbChance: M.tierValue(d, [0, 0.35, 0.6]), spikeChance: M.tierValue(d, [0, 0.15, 0.4]), rbGap: M.tierValue(d, [8, 7.5, 6.5]), heli: false, heliAfter: 1e6, heliFuel: 0, heliGap: 1e6, bustSpeed: M.tierValue(d, [6, 9, 12]), searchTop: 40, close: M.tierValue(d, [6, 9, 12]), copFrail: 3.2, aheadChance: M.tierValue(d, [0.2, 0.5, 0.6]), aheadBlind: 1, evadeTimeout: 1e9 });
+ g.gates = []; for (let i = 1; i <= g.legs; i++) g.gates.push({ at: g.total * i / g.legs, done: 0, kind: 'line' });
+ g.next = 0;
+ M.spawnTraffic(g, Math.round(M.tierValue(d, [5, 8, 11])));
+ },
+ idle(g) { for (const r of g.rivals) { const a = C.routeAt(g.route, r.s, r.lat); r.x = a.x; r.y = a.y; r.h = a.h; } },
+ tick(g, wdt) {
+ const r = g.rivals[0];
+ M.stepRival(g, r, wdt); M.stepPolice(g, wdt, false);
+ if (g.outcome) return;
+ while (g.next < g.gates.length && g.prog >= g.gates[g.next].at) { g.gates[g.next].done = 1; g.next++; g.events.push({ type: 'leg', leg: g.next }); }
+ if (g.prog >= g.total) return g.win();
+ if (r.prog >= g.total) g.lose('gap');
+ },
+ health(g) {
+ const r = g.rivals[0], a = clamp((g.total - r.prog) / g.total, 0, 1), b = M.bustHp(g) / 50, hp = g.outcome === 'loss' ? 0 : Math.round(Math.min(a, b) * 1000);
+ return [hp, 1000, g.outcome === 'win' ? 0 : Math.max(0, g.total - g.prog), g.total];
+ },
+ hud(g) { const r = g.rivals[0], lead = g.prog - r.prog; return { label: 'Street Champion Showdown', detail: `Leg ${Math.min(g.next + 1, g.legs)} / ${g.legs} · ${lead >= 0 ? 'Ahead by' : 'Behind by'} ${Math.abs(lead).toFixed(0)} m · Cops ${g.cops.filter(c => !c.dead).length}` }; },
+ scripted(g) { return championPolicy(g); },
+ hudExtra(g, c, u) { M.MODES.pursuit.hudExtra(g, c, u); },
+ };
+ void N;
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/nfsmw_remake/modes_speedtrap.js b/environments/games/web/games/nfsmw_remake/modes_speedtrap.js
new file mode 100644
index 0000000000000000000000000000000000000000..9b700bd358225027132863b0ab9f116d4c67a5c1
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/modes_speedtrap.js
@@ -0,0 +1,62 @@
+/* Speed Trap (GRace.h kRaceType_SpeedTrap). Crossing order does not matter: "each checkpoint's total speed is accumulated to
+ determine the winner" (Wikipedia). The speed at each camera is what counts, so the driver saves nitrous for the camera, and the
+ rival does the same (AIActionRace.cpp CheckSpeedTraps: nitrous 1-3 s ahead by skill, Tweak_SpeedTrapSkillBoost :50), with
+ half the usual catch-up glue (AIVehicle.cpp:2053 Tweak_SpeedTrapCatchupGlue 0.5). GRaceStatus.h keeps one speed per trap.
+ boss_hp = route metres left to the last camera; player_hp = cushion + score lead over the traps both cars have crossed. The
+ camera positions and the cushion are original (the race database is VLT data): cameras sit on the fastest ground nearby. */
+(function (root) {
+ 'use strict';
+ const M = root.NfsmwGame, C = M.C, P = C.PLAYER, KMH = 3.6, S0 = 900;
+ M.MODES.speedtrap = {
+ route: () => 'coast',
+ init(g, d) {
+ const R = g.route, v = C.profile(R, P.grip, P.aero, P.brake, C.TOPS[5]);
+ g.total = M.tierValue(d, [900, 3100, 7800]); g.s0 = S0; g.placeCar(S0, -2.1); g.glue = 0.5;
+ const count = Math.max(2, Math.round(g.total / 480)), reach = C.reachable(R, v, S0, g.total + 100, P);
+ g.gates = [];
+ for (let i = 1; i <= count; i++) {
+ let at = g.total * i / count;
+ if (i < count) { let best = at, bv = -1; for (let x = at - 150; x <= at + 150; x += 6) { const u = reach[Math.round(x / R.ds)]; if (u > bv) { bv = u; best = x; } } at = best; }
+ g.gates.push({ at, kind: 'trap', done: 0, you: 0, them: 0, themDone: 0 });
+ }
+ // Pretraining engineering target from the existing deterministic vehicle/route
+ // reachability profile. No policy, sampled rival score or evaluation result is used.
+ // Freeze once at reset; keep health(), HUD, finish and win/loss rules unchanged.
+ g.reward_target_version = 'speedtrap-reachable-profile@1';
+ g.reward_target_cameras = g.gates.map(t => Math.round(reach[Math.round(t.at / R.ds)] * KMH * 1e6) / 1e6);
+ g.reward_target_score = Math.round(g.reward_target_cameras.reduce((a,b) => a+b, 0) * 1e6) / 1e6;
+ if (!Number.isFinite(g.reward_target_score) || g.reward_target_score <= 0) throw Error('invalid fixed speedtrap target');
+ g.next = 0; g.rNext = 0; g.you = 0; g.them = 0; g.flashT = 0; g.cushion = M.tierValue(d, [130, 95, 70]);
+ g.rivals = [M.newRival(g, { s: S0, lat: 2.1, skill: C.clamp(M.tierValue(d, [0.15, 0.42, 0.68]) + M.formOf(g), 0, 1), paint: 2 })];
+ M.spawnTraffic(g, Math.round(M.tierValue(d, [6, 9, 13])));
+ },
+ idle() {},
+ lead(g) { let lead = 0; for (let i = 0; i < g.gates.length; i++) { const t = g.gates[i]; if (t.done && t.themDone) lead += t.you - t.them; } return lead; },
+ tick(g, wdt) {
+ if (g.flashT > 0) g.flashT = Math.max(0, g.flashT - wdt);
+ const r = g.rivals[0];
+ while (g.rNext < g.gates.length && r.prog >= g.gates[g.rNext].at) { const t = g.gates[g.rNext]; t.them = r.v * KMH; t.themDone = 1; g.them += t.them; g.rNext++; }
+ if (g.rNext < g.gates.length) { const ahead = g.gates[g.rNext].at - r.prog, tt = ahead / Math.max(r.v, 5); if (tt < C.lerp(1, 3, r.skill)) r.trapNos = 0.2; }
+ M.stepRival(g, r, wdt);
+ while (g.next < g.gates.length && g.prog >= g.gates[g.next].at) { const t = g.gates[g.next]; t.done = 1; t.keep = 0; t.you = C.speed(g.car) * KMH; g.you += t.you; g.next++; g.flashT = 0.15; g.events.push({ type: 'speedtrap', kmh: t.you }); }
+ if (g.next >= g.gates.length) {
+ // The player's last camera ends the event. Cameras the rival has not reached yet are scored at the speed it would carry there.
+ let them = g.them; for (let i = g.rNext; i < g.gates.length; i++) them += M.projectRival(g, r, g.s0 + g.gates[i].at) * KMH;
+ g.themFinal = them;
+ if (g.you >= them) g.win(); else g.lose('score');
+ return;
+ }
+ if (g.cushion + this.lead(g) <= 0) g.lose('score');
+ },
+ health(g) {
+ const max = g.cushion * 2, hp = g.outcome === 'loss' ? 0 : C.clamp(g.cushion + this.lead(g), 0, max);
+ return [hp, max, g.outcome === 'win' ? 0 : Math.max(0, g.total - g.prog), g.total];
+ },
+ hud(g) { return { label: 'Speed Trap', detail: `Checkpoint ${Math.min(g.next + 1, g.gates.length)} / ${g.gates.length} · You: ${g.you.toFixed(0)} · Rival: ${g.them.toFixed(0)} km/h` }; },
+ // Reference: drive the line, and spend nitrous only in the last seconds before a camera.
+ scripted(g) {
+ const v = Math.max(C.speed(g.car), 5), t = g.gates[g.next], ahead = t ? (t.at - g.prog) / v : 99;
+ return M.ctl.drive(g, ahead < 2.8 ? { forceNos: true } : { nos: false });
+ },
+ };
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/nfsmw_remake/modes_tollbooth.js b/environments/games/web/games/nfsmw_remake/modes_tollbooth.js
new file mode 100644
index 0000000000000000000000000000000000000000..eabf8c7729cf21c7acaf61587589c8e0de6da1cb
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/modes_tollbooth.js
@@ -0,0 +1,41 @@
+/* Tollbooth (GRace.h kRaceType_Tollbooth): a solo run against the clock. Each gate grants more time and leftover seconds
+ carry over (Wikipedia, "Need for Speed: Most Wanted (2005)": "a checkpoint-styled solo race, in which players must hit
+ a set of checkpoints, each one within a set amount of time"; GRaceStatus.h NotifyTollboothCrossed counts them).
+ boss_hp = route metres left to the last gate; player_hp = clock in tenths of a second. The gate timings live in the
+ game's race database (VLT), so the allowance here is an approximation: slack x the car's own ideal time. */
+(function (root) {
+ 'use strict';
+ const M = root.NfsmwGame, C = M.C;
+ const P = C.PLAYER, TOP = C.TOPS[5];
+ M.MODES.tollbooth = {
+ route: () => 'coast',
+ init(g, d) {
+ const R = g.route, S0 = 3640;
+ g.total = M.tierValue(d, [860, 3250, 8000]);
+ g.s0 = S0; g.placeCar(S0, -2.1);
+ const slack = M.tierValue(d, [1.55, 1.34, 1.2]), v = C.profile(R, P.grip, P.aero, P.brake, TOP), spacing = 620;
+ const count = Math.max(2, Math.round(g.total / spacing));
+ g.gates = [];
+ let at = 0;
+ for (let i = 1; i <= count; i++) { const end = g.total * i / count; g.gates.push({ at: end, grant: C.driveTime(R, v, S0 + at, end - at, P, i === 1 ? 0 : 30) * slack, done: 0 }); at = end; }
+ g.next = 0; g.bank = g.gates[0].grant + 3; g.bankMax = g.bank;
+ M.spawnTraffic(g, Math.round(M.tierValue(d, [7, 11, 16])));
+ },
+ idle() {},
+ tick(g, wdt) {
+ g.bank -= wdt;
+ while (g.next < g.gates.length && g.prog >= g.gates[g.next].at) {
+ const gate = g.gates[g.next]; gate.done = 1; g.next++;
+ g.events.push({ type: 'gate', left: g.bank });
+ if (g.next < g.gates.length) { g.bank += g.gates[g.next].grant; g.bankMax = Math.max(g.bankMax, g.bank); }
+ }
+ if (g.prog >= g.total) return g.win();
+ if (g.bank <= 0) { g.bank = 0; g.lose('time'); }
+ },
+ health(g) {
+ const left = Math.max(0, g.total - g.prog);
+ return [Math.max(0, g.outcome === 'loss' ? 0 : Math.round(g.bank * 10)), Math.ceil(g.bankMax * 10), g.outcome === 'win' ? 0 : left, g.total];
+ },
+ hud(g) { return { label: 'Tollbooth', detail: `Gate ${Math.min(g.next + 1, g.gates.length)} / ${g.gates.length} · Time left: ${g.bank.toFixed(1)} s` }; },
+ };
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/nfsmw_remake/nfscore.js b/environments/games/web/games/nfsmw_remake/nfscore.js
new file mode 100644
index 0000000000000000000000000000000000000000..18d40d12f4a47c22f7a74eaf9811a0f7ba14edd7
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/nfscore.js
@@ -0,0 +1,237 @@
+/* Need for Speed: Most Wanted (2005) events, rules nfsmw-arena@1 - world and vehicle core.
+ Original procedural city: the roads are a union of capsules around authored polylines, so a car is free inside the
+ union and everything outside is a wall; sight lines sample the same function. Routes are rounded polylines sampled
+ every 2 m and measured along their own length (progress is route distance, never distance to a target).
+ Vehicle rules read from the CC0 decompilation dbalatoni13/nfsmw@80993f3 are cited inline; values that live in the
+ game's VLT data (mass, torque, grip) are not in that repository and are original approximations (see SOURCES.md).
+ Nothing here touches a game's RNG: every function is pure except for the car it is handed. */
+(function (root) {
+ 'use strict';
+ const M = root.NfsmwGame = root.NfsmwGame || {}, C = M.C = {};
+ const q4 = v => Math.round(v * 1e4) / 1e4; // static geometry is rounded once so trig ULPs cannot reach a replay
+ const clamp = (v, a, b) => v < a ? a : v > b ? b : v;
+ C.clamp = clamp; C.lerp = (a, b, t) => a + (b - a) * t;
+ C.MPH = 0.44704; C.KPH = 1 / 3.6;
+
+ // ---------------- authored routes: [x, y, corner radius] (original layout) ----------------
+ const ROUTES = {
+ // Coastal loop: the 1.5 km highway along the south shore, sweepers in the east, a chicane in the north, hills west.
+ coast: { loop: true, width: 17, pts: [[-760, -520, 90], [860, -520, 220], [980, -120, 160], [760, 260, 120], [820, 520, 100], [300, 560, 80], [220, 400, 45], [-60, 400, 45], [-140, 560, 70], [-620, 560, 120], [-820, 260, 90], [-640, 60, 70], [-860, -140, 90]] },
+ // Downtown block: the short circuit for the knockout, four fast corners and an inner chicane.
+ downtown: { loop: true, width: 15, pts: [[-85, -80, 26], [90, -80, 22], [90, -22, 15], [46, -22, 13], [46, 28, 13], [90, 28, 15], [90, 80, 22], [-85, 80, 26]] },
+ // Highway 99 drag strip: dead straight, four lanes, not connected to the city.
+ strip: { loop: false, width: 22, pts: [[-1500, -1000, 0], [1500, -1000, 0]] },
+ };
+ // Cross streets: never raced, they are what the pursuit is about (sight breaks, cops arriving from the side).
+ const STREETS = [
+ [[0, -520], [0, -80]], [[0, 80], [0, 400]], [[46, 3], [420, 3], [420, 260], [760, 260]], [[-85, 0], [-400, 0], [-400, 60], [-640, 60]],
+ [[420, 0], [420, -520]], [[-400, 0], [-400, -520]], [[420, 260], [300, 560]], [[-400, 60], [-400, 560]],
+ ];
+ const STREET_W = 13, DS = 2;
+
+ function buildRoute(name, def) {
+ const P = def.pts, n = P.length; // each corner becomes a tangent arc between two straights
+ const corner = i => {
+ const [x, y, r] = P[i], a = P[(i + n - 1) % n], b = P[(i + 1) % n];
+ const ax = a[0] - x, ay = a[1] - y, bx = b[0] - x, by = b[1] - y, la = Math.hypot(ax, ay), lb = Math.hypot(bx, by);
+ const ux = ax / la, uy = ay / la, vx = bx / lb, vy = by / lb, cos = clamp(ux * vx + uy * vy, -1, 1), th = Math.acos(cos);
+ const t = r / Math.tan(th / 2);
+ if (t > Math.min(la, lb) * 0.5 + 1e-6) throw Error(`${name}: corner ${i} radius too large`);
+ const hx = ux + vx, hy = uy + vy, hl = Math.hypot(hx, hy), dist = r / Math.sin(th / 2);
+ const cx = x + hx / hl * dist, cy = y + hy / hl * dist, sx = x + ux * t, sy = y + uy * t, ex = x + vx * t, ey = y + vy * t;
+ const turn = -Math.sign(ux * vy - uy * vx); // +1 = counter-clockwise
+ return { sx, sy, ex, ey, cx, cy, r, sweep: Math.PI - th, turn };
+ };
+ const out = { x: [], y: [], h: [], k: [] };
+ const push = (x, y, h, k) => { out.x.push(q4(x)); out.y.push(q4(y)); out.h.push(q4(h)); out.k.push(Math.round(k * 1e7) / 1e7); };
+ const dense = []; // 0.25 m polyline with curvature, resampled to DS below
+ const line = (ax, ay, bx, by) => { const L = Math.hypot(bx - ax, by - ay), m = Math.max(1, Math.ceil(L / 0.25)), h = Math.atan2(by - ay, bx - ax); for (let i = 0; i < m; i++) dense.push([ax + (bx - ax) * i / m, ay + (by - ay) * i / m, h, 0]); };
+ if (def.loop) {
+ const cs = P.map((_, i) => corner(i));
+ for (let i = 0; i < n; i++) {
+ const c = cs[i], d = cs[(i + 1) % n], a0 = Math.atan2(c.sy - c.cy, c.sx - c.cx), m = Math.max(1, Math.ceil(c.r * c.sweep / 0.25));
+ for (let j = 0; j < m; j++) { const a = a0 + c.turn * c.sweep * j / m; dense.push([c.cx + Math.cos(a) * c.r, c.cy + Math.sin(a) * c.r, a + c.turn * Math.PI / 2, c.turn / c.r]); }
+ line(c.ex, c.ey, d.sx, d.sy);
+ }
+ } else { for (let i = 0; i + 1 < n; i++) line(P[i][0], P[i][1], P[i + 1][0], P[i + 1][1]); dense.push([P[n - 1][0], P[n - 1][1], dense[dense.length - 1][2], 0]); }
+ let acc = 0, next = 0, last = dense[0];
+ dense.forEach((p, i) => { if (i) acc += Math.hypot(p[0] - last[0], p[1] - last[1]); last = p; while (acc >= next - 1e-9) { push(p[0], p[1], p[2], p[3]); next += DS; } });
+ const L = out.x.length * DS;
+ return { name, loop: !!def.loop, width: def.width, halfW: def.width / 2, ds: DS, n: out.x.length, L, x: out.x, y: out.y, h: out.h, k: out.k };
+ }
+ C.routes = {}; for (const [k, d] of Object.entries(ROUTES)) C.routes[k] = buildRoute(k, d);
+ // Route position (s is unbounded on a loop). Writes to a shared scratch object: copy the fields you keep.
+ const at = { x: 0, y: 0, h: 0, k: 0, nx: 0, ny: 0 };
+ C.routeAt = (R, s, lat = 0) => {
+ let u = s / R.ds; if (R.loop) { u %= R.n; if (u < 0) u += R.n; } else u = clamp(u, 0, R.n - 1.0001);
+ const i = Math.floor(u), f = u - i, j = (i + 1) % R.n;
+ let dh = R.h[j] - R.h[i]; if (dh > Math.PI) dh -= 2 * Math.PI; else if (dh < -Math.PI) dh += 2 * Math.PI;
+ at.h = R.h[i] + dh * f; at.k = R.k[i]; at.nx = -Math.sin(at.h); at.ny = Math.cos(at.h);
+ at.x = R.x[i] + (R.x[j] - R.x[i]) * f + at.nx * lat; at.y = R.y[i] + (R.y[j] - R.y[i]) * f + at.ny * lat;
+ return at;
+ };
+ // Nearest route distance within a window around a guess: junctions can never teleport progress to another leg.
+ C.routeNear = (R, x, y, guess, back = 40, fwd = 60) => {
+ let best = guess, bd = Infinity;
+ const g0 = Math.round(guess / R.ds) * R.ds;
+ for (let s = g0 - back; s <= g0 + fwd; s += R.ds) {
+ if (!R.loop && (s < 0 || s > R.L)) continue;
+ let u = Math.round(s / R.ds); if (R.loop) { u %= R.n; if (u < 0) u += R.n; } else u = clamp(u, 0, R.n - 1);
+ const dx = x - R.x[u], dy = y - R.y[u], d = dx * dx + dy * dy; if (d < bd) { bd = d; best = s; }
+ }
+ // refine inside the winning 2 m cell with the segment projection
+ const a = C.routeAt(R, best), ax = Math.cos(a.h), ay = Math.sin(a.h);
+ return best + clamp((x - a.x) * ax + (y - a.y) * ay, -R.ds, R.ds);
+ };
+ C.routeLat = (R, x, y, s) => { const a = C.routeAt(R, s); return (x - a.x) * a.nx + (y - a.y) * a.ny; };
+
+ // ---------------- the road union: 10 m grid of candidate capsules ----------------
+ const SEGS = []; const addPoly = (pts, hw, closed) => { const m = closed ? pts.length : pts.length - 1; for (let i = 0; i < m; i++) { const a = pts[i], b = pts[(i + 1) % pts.length]; SEGS.push({ ax: a[0], ay: a[1], bx: b[0], by: b[1], hw }); } };
+ for (const R of Object.values(C.routes)) { const pts = []; const step = R.name === 'strip' ? 50 : R.name === 'downtown' ? 2 : 4; for (let i = 0; i < R.n; i += step) pts.push([R.x[i], R.y[i]]); if (!R.loop) pts.push([R.x[R.n - 1], R.y[R.n - 1]]); addPoly(pts, R.halfW, R.loop); }
+ for (const st of STREETS) addPoly(st, STREET_W / 2, false);
+ C.streets = STREETS; C.streetW = STREET_W;
+ const CELL = 10, X0 = -1560, Y0 = -1060, NX = 310, NY = 180, GRID = new Array(NX * NY);
+ SEGS.forEach((g, gi) => {
+ const pad = g.hw + CELL * 1.5, x0 = Math.floor((Math.min(g.ax, g.bx) - pad - X0) / CELL), x1 = Math.floor((Math.max(g.ax, g.bx) + pad - X0) / CELL), y0 = Math.floor((Math.min(g.ay, g.by) - pad - Y0) / CELL), y1 = Math.floor((Math.max(g.ay, g.by) + pad - Y0) / CELL);
+ for (let j = Math.max(0, y0); j <= Math.min(NY - 1, y1); j++) for (let i = Math.max(0, x0); i <= Math.min(NX - 1, x1); i++) { const px = X0 + (i + 0.5) * CELL, py = Y0 + (j + 0.5) * CELL, dx = g.bx - g.ax, dy = g.by - g.ay, t = clamp(((px - g.ax) * dx + (py - g.ay) * dy) / (dx * dx + dy * dy || 1), 0, 1); if (Math.hypot(px - g.ax - t * dx, py - g.ay - t * dy) <= pad) { const c = i + j * NX; (GRID[c] || (GRID[c] = [])).push(gi); } }
+ });
+ // d > 0 means d metres outside the union; (nx, ny) points from the road centre towards the car.
+ const hit = { d: 0, nx: 0, ny: 0 };
+ C.road = (x, y) => {
+ const i = Math.floor((x - X0) / CELL), j = Math.floor((y - Y0) / CELL);
+ hit.d = 99; hit.nx = 0; hit.ny = 0;
+ if (i < 0 || j < 0 || i >= NX || j >= NY) return hit;
+ const c = GRID[i + j * NX]; if (!c) return hit;
+ for (let k = 0; k < c.length; k++) {
+ const g = SEGS[c[k]], dx = g.bx - g.ax, dy = g.by - g.ay, t = clamp(((x - g.ax) * dx + (y - g.ay) * dy) / (dx * dx + dy * dy || 1), 0, 1), px = x - g.ax - t * dx, py = y - g.ay - t * dy, l = Math.sqrt(px * px + py * py), d = l - g.hw;
+ if (d < hit.d) { hit.d = d; if (l > 1e-6) { hit.nx = px / l; hit.ny = py / l; } else { hit.nx = 0; hit.ny = 0; } }
+ }
+ return hit;
+ };
+ C.onRoad = (x, y, margin = 0) => C.road(x, y).d < -margin;
+ // Sight line: buildings stand everywhere the road is not (AIVehicleCopCar::CanSeeTarget's world ray, sampled).
+ C.lineClear = (ax, ay, bx, by) => { const L = Math.hypot(bx - ax, by - ay), m = Math.ceil(L / 5); for (let i = 1; i < m; i++) if (C.road(ax + (bx - ax) * i / m, ay + (by - ay) * i / m).d > 2) return false; return true; };
+ C.bounds = { X0, Y0, NX, NY, CELL };
+
+ // ---------------- vehicle ----------------
+ const lookup = (tab, v, max) => { const u = clamp(v / max, 0, 1) * (tab.length - 1), i = Math.min(tab.length - 2, Math.floor(u)); return tab[i] + (tab[i + 1] - tab[i]) * (u - i); };
+ // SuspensionRacer.cpp:1077 SteeringRangeData, degrees over 0..160 mph; :1072 BrakeSteeringRangeMultiplier 1.45.
+ const STEER_RANGE = [40, 20, 10, 5.5, 4.5, 3.25, 2.9, 2.9, 2.9, 2.9], BRAKE_STEER = 1.45;
+ // Approximation (VLT transmission/engine data is not in the repository): an original six-speed road car.
+ const TOPS = [17, 30, 43, 55, 67, 84], DRIVE = [10.5, 8.2, 6.4, 5.0, 4.0, 3.1];
+ const PLAYER = { wheelbase: 2.7, grip: 12.5, aero: 0.0012, drag: 0.00039, roll: 0.25, brake: 13, accel: 1, radius: 1.5, nosBoost: 0.35, nosSeconds: 6, overheat: false };
+ C.PLAYER = PLAYER; C.TOPS = TOPS;
+ C.newCar = (x, y, h) => ({ x, y, h, vx: 0, vy: 0, r: 0, steer: 0, gear: 0, clutch: 0, bonus: 0, perfect: 0, nos: 1, nosOn: 0, heat: 0, blown: 0, tires: 0, hit: 0, drift: 0, over: 0 });
+ const NOS_MIN_MPH = 10; // EngineRacer.cpp:926 Tweak_MinSpeedForNosMPH; half of it keeps nitrous engaged (:950)
+ // Over-rev heat, EngineRacer.cpp:1340-1345: +0.45/s on the limiter, -0.1/s otherwise, blown at 1, -25% torque from 0.6.
+ const HEAT_UP = 0.45, HEAT_DOWN = -0.1, HEAT_PENALTY = 0.6, HEAT_TORQUE = 0.75;
+ const CLUTCH = 0.25, CLUTCH_FIRST = 0.05; // EngineRacer.cpp:34-35
+ C.steerRange = mph => lookup(STEER_RANGE, mph, 160);
+ C.tireFactor = c => 1 - 0.7 * (c.tires / 4); // SuspensionRacer.cpp:1569 Tweak_BlownTireTraction 0.3 on all four
+ // One step. inp: {thr, brk, steer in [-1,1] (+ = left), hb, nos, up, down, manual, reverse, sbGrip}. dt is world time.
+ C.carStep = (c, inp, dt, P = PLAYER) => {
+ const ch = Math.cos(c.h), sh = Math.sin(c.h);
+ let vf = c.vx * ch + c.vy * sh, vl = -c.vx * sh + c.vy * ch;
+ const speed = Math.hypot(vf, vl), mph = speed / C.MPH, tire = C.tireFactor(c);
+ // steering: input slews, range comes from the speed table
+ const rate = speed < 15 ? 7 : speed < 40 ? 5 : 3.6, want = clamp(inp.steer, -1, 1);
+ c.steer += clamp(want - c.steer, -rate * dt, rate * dt);
+ const range = lookup(STEER_RANGE, mph, 160) * (inp.hb || inp.brk ? BRAKE_STEER : 1), delta = c.steer * range * Math.PI / 180;
+ const grip0 = (P.grip + P.aero * speed * speed + (inp.sbGrip || 0)) * tire;
+ let target = vf * Math.tan(delta) / P.wheelbase, rmax = grip0 * 1.05 / Math.max(speed, 3);
+ if (inp.hb) rmax *= 1.9;
+ target = clamp(target, -rmax, rmax);
+ c.r += (target - c.r) * Math.min(1, dt * 9);
+ c.h += c.r * dt;
+ // gearbox and drive
+ if (c.clutch > 0) c.clutch = Math.max(0, c.clutch - dt);
+ if (c.bonus > 0) c.bonus = Math.max(0, c.bonus - dt);
+ const u = Math.max(vf, 0) / TOPS[c.gear];
+ if (inp.manual) {
+ if (inp.up && c.gear < 5) { const perfect = u >= 0.88 && u <= 0.99; c.clutch = perfect ? CLUTCH_FIRST : CLUTCH; if (perfect) { c.bonus = 1; c.perfect++; } c.gear++; }
+ else if (inp.down && c.gear > 0) { c.gear--; c.clutch = CLUTCH; }
+ } else if (c.clutch <= 0) {
+ if (u > 0.97 && c.gear < 5) { c.clutch = c.gear === 0 ? CLUTCH_FIRST : CLUTCH; c.gear++; }
+ else if (c.gear > 0 && vf < TOPS[c.gear - 1] * 0.82) c.gear--;
+ }
+ // nitrous, EngineRacer::DoNos
+ let boost = 1;
+ const engaged = !!inp.nos && inp.thr > 0 && c.nos > 0 && !c.blown && (mph >= NOS_MIN_MPH || (c.nosOn && mph >= NOS_MIN_MPH / 2));
+ if (engaged) { c.nos = Math.max(0, c.nos - dt / P.nosSeconds); boost = 1 + P.nosBoost; c.nosOn = 1; }
+ else { c.nosOn = 0; if (speed > 10) c.nos = Math.min(1, c.nos + dt * (speed > 50 ? 0.07 : 0.035)); }
+ const uNow = Math.max(vf, 0) / TOPS[c.gear], limiter = uNow >= 1;
+ c.over = limiter && inp.thr > 0 ? 1 : 0;
+ if (P.overheat && c.gear > 0) { c.heat = Math.max(0, c.heat + (c.over ? HEAT_UP : HEAT_DOWN) * dt); if (c.heat >= 1) c.blown = 1; }
+ let drive = 0;
+ if (!c.blown && c.clutch <= 0 && inp.thr > 0) {
+ const curve = uNow < 0.35 ? 0.75 + 0.25 * uNow / 0.35 : uNow < 0.9 ? 1 : uNow < 1 ? 1 - (uNow - 0.9) * 2 : 0;
+ drive = DRIVE[c.gear] * curve * inp.thr * boost * P.accel * tire * (c.heat > HEAT_PENALTY ? HEAT_TORQUE : 1) * (c.bonus > 0 ? 1.1 : 1);
+ }
+ // re-express velocity in the turned frame; rear tyres scrub the lateral part (handbrake drops them)
+ const ch2 = Math.cos(c.h), sh2 = Math.sin(c.h);
+ vf = c.vx * ch2 + c.vy * sh2; vl = -c.vx * sh2 + c.vy * ch2;
+ let ax = drive - P.drag * vf * Math.abs(vf) - P.roll * (Math.abs(vf) > 0.2 ? Math.sign(vf) : 0);
+ if (inp.brk) { if (vf > 0.3) ax -= P.brake * tire; else if (inp.reverse) ax -= 4.5; }
+ if (inp.hb && Math.abs(vf) > 0.3) ax -= 6 * Math.sign(vf);
+ const longLim = grip0 * 1.1; ax = clamp(ax, -longLim, longLim);
+ const used = Math.min(0.75, Math.abs(ax) / longLim * 0.55), latCap = grip0 * (inp.hb ? 0.42 : 1) * (1 - used);
+ vf += ax * dt;
+ if (inp.brk && !inp.reverse && vf < 0) vf = 0;
+ const dl = clamp(vl, -latCap * dt, latCap * dt); vl -= dl;
+ c.drift = Math.abs(vl) > 2.5 ? 1 : 0;
+ if (c.drift) vf -= Math.sign(vf) * Math.min(Math.abs(vf), 0.8 * dt);
+ c.vx = vf * ch2 - vl * sh2; c.vy = vf * sh2 + vl * ch2;
+ c.x += c.vx * dt; c.y += c.vy * dt;
+ // walls: everything outside the road union
+ const q = C.road(c.x, c.y), over = q.d + 1;
+ c.hit = 0;
+ if (over > 0) {
+ c.x -= q.nx * over; c.y -= q.ny * over;
+ const vn = c.vx * q.nx + c.vy * q.ny;
+ if (vn > 0) {
+ c.vx -= 1.25 * vn * q.nx; c.vy -= 1.25 * vn * q.ny;
+ const scrub = 1 - Math.min(0.3, vn * 0.012); c.vx *= scrub; c.vy *= scrub; c.hit = vn; if (vn > 3) c.r *= 0.3;
+ } else { c.vx *= 1 - 0.3 * dt; c.vy *= 1 - 0.3 * dt; }
+ }
+ };
+ C.speed = c => Math.hypot(c.vx, c.vy);
+ // Point-mass speed profile along a route: curvature limit with a backward braking pass. grip follows
+ // AIActionRace::GetPotentialSpeed (grip scaled by skill); the player's controller uses the player's own numbers.
+ const profiles = new Map();
+ C.profile = (R, grip, aero, brake, top) => {
+ const key = R.name + '|' + [grip, aero, brake, top].map(v => v.toFixed(3)).join('|');
+ let v = profiles.get(key); if (v) return v;
+ v = new Float64Array(R.n);
+ // Curvature is taken over +-6 m: a car starts turning before the arc begins and has not finished when it ends.
+ for (let i = 0; i < R.n; i++) {
+ let k = 0; for (let j = -3; j <= 3; j++) { const m = R.loop ? (i + j + R.n) % R.n : clamp(i + j, 0, R.n - 1); k = Math.max(k, Math.abs(R.k[m])); }
+ // k * v^2 = grip + aero v^2 -> v^2 = grip / (k - aero)
+ v[i] = k > aero + 1e-5 ? Math.min(top, Math.sqrt(grip / (k - aero))) : top;
+ }
+ const passes = R.loop ? 2 : 1;
+ for (let p = 0; p < passes; p++) for (let i = R.n - 1; i >= 0; i--) {
+ const j = i + 1 < R.n ? i + 1 : R.loop ? 0 : i;
+ const lim = Math.sqrt(v[j] * v[j] + 2 * brake * R.ds); if (lim < v[i]) v[i] = lim;
+ }
+ profiles.set(key, v); return v;
+ };
+ // Drive force at a speed in the gear an automatic box would hold: the same curve as carStep. Rivals and estimates use it.
+ C.driveAt = u => { let gear = 0; while (gear < 5 && u > TOPS[gear] * 0.97) gear++; const un = u / TOPS[gear], curve = un < 0.35 ? 0.75 + 0.25 * un / 0.35 : un < 0.9 ? 1 : Math.max(0, 1 - (un - 0.9) * 2); return DRIVE[gear] * curve; };
+ // Speed a car can actually carry along a stretch: forward pass over the limits. The profile alone reads top speed on the exit of any corner.
+ C.reachable = (R, v, s0, len, P = PLAYER, v0 = 0) => {
+ const out = []; let u = v0;
+ for (let s = 0; s <= len; s += R.ds) { const a = Math.max(0, C.driveAt(u) * P.accel - P.drag * u * u - P.roll); u = Math.min(C.profileAt(R, v, s0 + s), Math.sqrt(u * u + 2 * a * R.ds)); out.push(u); }
+ return out;
+ };
+ // Time for the car to cover a stretch: the profile's corner and braking limits with the gearbox's acceleration on top.
+ C.driveTime = (R, v, s0, len, P = PLAYER, v0 = 0) => {
+ let t = 0, u = v0;
+ for (let s = 0; s < len; s += R.ds) {
+ const vmax = C.profileAt(R, v, s0 + s), a = Math.max(0.2, C.driveAt(u) * P.accel - P.drag * u * u - P.roll);
+ u = Math.min(vmax, Math.sqrt(u * u + 2 * a * R.ds));
+ t += R.ds / Math.max(u, 3);
+ }
+ return t;
+ };
+ C.profileAt = (R, v, s) => { let i = Math.round(s / R.ds); if (R.loop) { i %= R.n; if (i < 0) i += R.n; } else i = clamp(i, 0, R.n - 1); return v[i]; };
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/nfsmw_remake/page.js b/environments/games/web/games/nfsmw_remake/page.js
new file mode 100644
index 0000000000000000000000000000000000000000..15efa5035cf621d8e32f9cc8666348c607eea8b7
--- /dev/null
+++ b/environments/games/web/games/nfsmw_remake/page.js
@@ -0,0 +1,135 @@
+/* Page-only layer for the human play page. Not listed in manifest.json: the public interface, the recordings and the source
+ fingerprint never load it, so nothing here can change a fight. The shared shell (_native/shell.js) owns the loop, the session,
+ the keys, and since 2026-11-08 also: restart after a result (click on the picture, Enter, R; not after a replay), focus back
+ to the picture after a button, a frame loop that survives a throw from M.draw (pause + reason in the status bar), and the
+ Module.pointerLock opt-out. This file only adds what the shell does not do ("only one race"):
+ - a panel over the picture before a race, while paused and after the result, with buttons that stay on the picture
+ (retry / next event), the event's control hints, and a hint for the reason a race was lost;
+ - N for the next event, Enter to start from the idle panel and to resume from the pause panel;
+ - focus back to the picture after picking an event or a tier in the lists, and when a game key is pressed on a button;
+ - pointer lock off (this game never uses the mouse; a locked cursor could not reach the buttons);
+ - a new 3D scene after a renderer failure: the shell pauses the race, but the old scene keeps its dead WebGL context.
+ It drives the shell only through its own buttons, so a race started here is exactly a race started from the toolbar.
+ Restart keys and clicks are never handled twice: Enter / R after a result are the shell's (its capture listener runs first
+ and stops the event), and the panel covers the canvas, so the shell's canvas click and the panel's click never both fire. */
+(function () {
+ 'use strict';
+ const M = window.GAME_MODULE, $ = s => document.querySelector(s), canvas = $('canvas'), panel = $('#nfs-panel');
+ if (!M || !canvas || !panel) return;
+ M.pointerLock = false; // read by the shell's double-click handler (shell.js, 2026-11-08)
+ let game = null, resultAt = 0, shown = '', broken = null, retryAt = 0;
+ const HINT = {
+ tollbooth: ['Passing a tollbooth adds time; you lose when the timer reaches zero', 'Release W or tap S before turns; use Shift for nitrous on straights'],
+ drag: ['Manual gears: press K to upshift when the RPM needle reaches green (L downshifts)', 'Hold W during the countdown to keep RPM in the green launch zone', 'Use A / D to change lanes and avoid traffic. Staying in the red zone blows the engine; a high-speed crash totals the car'],
+ speedtrap: ['Your speed is added at each checkpoint; beat the rival’s total to win', 'Use nitrous (Shift) 2–3 seconds before a speed checkpoint'],
+ knockout: ['The last-place driver is eliminated each lap; stay ahead', 'J toggles slow motion for stronger grip; use it before entering a turn'],
+ pursuit: ['Build the required bounty while police can see you, then lose them', 'The escape meter starts filling after seven seconds out of sight; nearby cops can bust you at low speed', 'Drive through orange pursuit breakers to crush nearby police cars'],
+ street_champion: ['Reach the final leg’s finish before your rival', 'Avoid arrest too: keep moving and never stop beside police cars'],
+ };
+ const TIP = {
+ 'drag|gap': 'Drag races use manual gears: press K when RPM enters green. Holding only W leaves you in first gear.',
+ 'drag|blown': 'Staying in the red zone overheats and blows the engine. Upshift with K promptly or release W briefly.',
+ 'drag|totaled': 'A high-speed collision totals the car. Change lanes with A / D before reaching traffic.',
+ 'tollbooth|time': 'Ease off the throttle before turns and use nitrous (Shift) on straights. Hitting walls wastes the most time.',
+ 'speedtrap|score': 'Save nitrous for speed checkpoints and cross each one as fast as possible.',
+ 'knockout|knocked': 'Press J before a turn for slow motion, better grip, and easier passing.',
+ 'pursuit|busted': 'The bust meter rises only when police are close and you are moving slowly. Keep moving and use orange pursuit breakers.',
+ 'street_champion|busted': 'The bust meter rises only when police are close and you are moving slowly. Keep your speed up.',
+ 'street_champion|gap': 'Your rival uses nitrous. Hold Shift on straights and take the inside line through turns.',
+ };
+ const LOSS = { time: 'Time expired', gap: 'Rival reached the finish first', blown: 'Engine blown', totaled: 'Crash wreck', busted: 'Busted', knocked: 'Eliminated in last place', score: 'Lost on total score' };
+ const nameOf = id => (M.cases.find(c => c.id === id) || { name: id }).name;
+ const running = () => $('#pause').textContent === 'Pause';
+ // Replay or race: the shell keeps that in a closure. Its status line says which one started (a replay: 'Replay verified…';
+ // a race or the demo: 'Recording this match…' / 'Scripted demo running…'), so a flag follows only those two kinds of message; anything else the
+ // status shows later (an export, an error) leaves it alone. After a replay the shell does not restart on Enter / R or on a
+ // click, so neither does the panel. (2026-11-08: reading the status text directly broke after an export rewrote it.)
+ let inReplay = false;
+ new MutationObserver(() => { const t = $('#status').textContent; if (/^Replay verified/.test(t)) inReplay = true; else if (/^(Recording this match|Scripted demo running)/.test(t)) inReplay = false; })
+ .observe($('#status'), { childList: true, characterData: true, subtree: true });
+ const replayMode = () => inReplay;
+ // A different event picked in the list after a result or while paused: the panel offers that event, not the old race.
+ const state = () => !game ? 'idle' : running() ? 'run' : $('#case').value !== game.id ? 'idle' : game.outcome ? 'result' : game.t > 0 ? 'paused' : 'idle';
+ const again = () => $('#start').click();
+ const resume = () => $('#pause').click();
+ function next() { const s = $('#case'); s.selectedIndex = (s.selectedIndex + 1) % s.options.length; s.dispatchEvent(new Event('change')); again(); }
+ const esc = s => String(s).replace(/[&<>]/g, ch => ({ '&': '&', '<': '<', '>': '>' })[ch]);
+
+ // ---- renderer failure (WebGL context lost). The shell catches a throw from M.draw and pauses the race with the reason in the
+ // status bar; the old scene, though, keeps its dead context and would fail on every frame. Here the scene is closed so the
+ // next draw builds a new one with a new context, at most once a second, and the error is passed on to the shell. ----
+ const draw0 = M.draw;
+ let lastT = -1;
+ M.draw = function (g, ctx) {
+ const advanced = g === game && g.t !== lastT; // the race ran since the last picture of this game
+ game = g; lastT = g.t;
+ if (broken && performance.now() < retryAt) {
+ paintBroken(ctx);
+ // Resumed before the new scene is up: pause again through the shell's own lost-focus path (it pauses only a running race).
+ if (advanced) { window.dispatchEvent(new Event('blur')); $('#status').textContent = 'Rebuilding 3D scene. Please wait before resuming.'; }
+ return;
+ }
+ try {
+ draw0.call(this, g, ctx);
+ if (broken) { broken = null; shown = ''; $('#status').textContent = '3D scene restored. Press Enter or click Resume to continue.'; }
+ } catch (e) {
+ broken = String(e && e.message || e).slice(0, 120); retryAt = performance.now() + 1000; shown = '';
+ try { M.closeRenderer(ctx); } catch (_) { /* a lost context cannot be cleaned further */ }
+ paintBroken(ctx);
+ throw e; // the shell's frame loop catches it: it pauses the race and shows the reason
+ }
+ };
+ function paintBroken(ctx) {
+ ctx.fillStyle = '#0b1016'; ctx.fillRect(0, 0, 854, 480); ctx.fillStyle = '#ffd08a'; ctx.font = 'bold 20px "Microsoft YaHei",sans-serif'; ctx.textAlign = 'center';
+ ctx.fillText('Screen error. Rebuilding 3D scene…', 427, 220); ctx.font = '13px Consolas,monospace'; ctx.fillStyle = '#a8b4c0'; ctx.fillText(broken || '', 427, 250); ctx.textAlign = 'left';
+ }
+
+ function render(st) {
+ const k = st === 'idle' ? ($('#case').value || '').split('/')[1] : game.key, title = st === 'idle' ? nameOf($('#case').value) : nameOf(game.id);
+ const hints = (HINT[k] || []).map(h => `
${esc(h)}
`).join(''), base = '
W accelerate · S brake / reverse · A / D steer · Space handbrake · Shift nitrous · J slow motion · R reset
';
+ let html = '';
+ if (st === 'idle') html = `
${esc(title)}
${hints}${base}
You can also click the screen to start
`;
+ else if (st === 'paused') html = `
${broken ? 'Screen error; paused' : 'Paused'}
${broken ? '
The 3D scene is rebuilding. When the picture returns, press Enter or click Resume.
' : ''}
${hints}${base}
`;
+ else if (st === 'result' && replayMode()) {
+ html = `
Replays save inputs and the seed, then simulate the match again and verify the final state. Scripted Demo reads internal state for verification; it does not start RL training.
+
+
+
diff --git a/environments/games/web/games/quake2_remake/input-hold.js b/environments/games/web/games/quake2_remake/input-hold.js
new file mode 100644
index 0000000000000000000000000000000000000000..ddd345da59abd0bfe426b052dd508a251a5160f7
--- /dev/null
+++ b/environments/games/web/games/quake2_remake/input-hold.js
@@ -0,0 +1,30 @@
+/* The shared shell (_native/shell.js) latches a tapped key only until the next macrotask, so a tap released before
+ the next native tick is lost. Since q2-arena@3 the tick is 16.7 ms (60 Hz), so a 20 ms minimum hold is enough:
+ this page delays every key / pointer release until 20 ms after the press. Page input only: the rules, the policy interface and recordings are
+ unaffected (a recording stores the keys each tick actually saw). */
+(function () {
+ 'use strict';
+ const HOLD = 20, down = new Map(), pdown = new Map();
+ const tracked = e => /^(Key[WASDJKLQER]|Space|ShiftLeft|ShiftRight|Arrow(Up|Down|Left|Right))$/.test(e.code);
+ const late = new WeakSet();
+ window.addEventListener('keydown', e => { if (tracked(e) && !down.has(e.code)) down.set(e.code, performance.now()); }, true);
+ window.addEventListener('keyup', e => {
+ if (late.has(e) || !tracked(e)) return;
+ const t0 = down.get(e.code); down.delete(e.code);
+ const wait = t0 === undefined ? 0 : HOLD - (performance.now() - t0);
+ if (wait <= 0) return;
+ e.stopImmediatePropagation(); e.preventDefault();
+ const target = e.target || window;
+ setTimeout(() => { const ev = new KeyboardEvent('keyup', { code: e.code, key: e.key, bubbles: true, cancelable: true }); late.add(ev); target.dispatchEvent(ev); }, wait);
+ }, true);
+ window.addEventListener('pointerdown', e => { pdown.set(e.pointerId, performance.now()); }, true);
+ window.addEventListener('pointerup', e => {
+ if (late.has(e)) return;
+ const t0 = pdown.get(e.pointerId); pdown.delete(e.pointerId);
+ const wait = t0 === undefined ? 0 : HOLD - (performance.now() - t0);
+ if (wait <= 0) return;
+ e.stopImmediatePropagation();
+ const target = e.target || window;
+ setTimeout(() => { const ev = new PointerEvent('pointerup', { bubbles: true, button: e.button, pointerId: e.pointerId }); late.add(ev); target.dispatchEvent(ev); }, wait);
+ }, true);
+})();
diff --git a/environments/games/web/games/quake2_remake/manifest.json b/environments/games/web/games/quake2_remake/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..1ac7979746881a63dd2c1b633a0993d092698b20
--- /dev/null
+++ b/environments/games/web/games/quake2_remake/manifest.json
@@ -0,0 +1,45 @@
+{
+ "schema": "bossbench/game-manifest@1",
+ "engine": "independent",
+ "game": "quake2_remake",
+ "module": "Quake2Game",
+ "title": "Quake II: Boss Arena",
+ "dimension": "3d",
+ "native_hz": 60,
+ "max_seconds": 300,
+ "renderer": "webgl-quake2",
+ "rules": "q2-arena@4",
+ "cases": [
+ "quake2/supertank",
+ "quake2/hornet",
+ "quake2/makron",
+ "quake2/tank_commander",
+ "quake2/gladiator",
+ "quake2/mutant"
+ ],
+ "scripts": [
+ "_native/runtime.js",
+ "_boss3d/vendor/three.min.js",
+ "quake2_remake/q2core.js",
+ "quake2_remake/q2player.js",
+ "quake2_remake/q2monsters.js",
+ "quake2_remake/game.js",
+ "quake2_remake/scripted.js",
+ "quake2_remake/renderer3d.js",
+ "quake2_remake/draw.js"
+ ],
+ "sim_scripts": [
+ "_native/runtime.js",
+ "quake2_remake/q2core.js",
+ "quake2_remake/q2player.js",
+ "quake2_remake/q2monsters.js",
+ "quake2_remake/game.js",
+ "quake2_remake/scripted.js"
+ ],
+ "play_page": "web/games/quake2_remake/index.html",
+ "scripted_controller": "Quake2Game.scripted(game) -> {holds:[6 key arrays], mouse:[dx,dy,0]}; deterministic look-ahead on copies (Quake2Game.oracle is an alias)",
+ "tests": [
+ "quake2_remake/tests/mechanics.js"
+ ],
+ "source": "https://github.com/id-Software/Quake-2/tree/372afde46e7defc9dd2d719a1732b8ace1fa096e (GPL-2.0)"
+}
diff --git a/environments/games/web/games/quake2_remake/q2core.js b/environments/games/web/games/quake2_remake/q2core.js
new file mode 100644
index 0000000000000000000000000000000000000000..f39a7c09ac900861aa7e0cd8b34076dfc4c8a858
--- /dev/null
+++ b/environments/games/web/games/quake2_remake/q2core.js
@@ -0,0 +1,264 @@
+/* Quake II (1997) boss arenas - core rules: units, Win32 CRT rand(), Quake II vector/angle helpers, the
+ axis-aligned brush world, box traces with CM_ClipBoxToBrush semantics and the edict slot allocator.
+ Independent JavaScript reimplementation written from id Software's GPL-2.0 source release
+ (github.com/id-Software/Quake-2, commit 372afde46e7defc9dd2d719a1732b8ace1fa096e): q_shared.c (AngleVectors,
+ anglemod), g_utils.c (vectoyaw, vectoangles, G_ProjectSource, G_Spawn, findradius), qcommon/cmodel.c
+ (CM_ClipBoxToBrush, CM_TestBoxInBrush), server/sv_world.c (SV_Trace, SV_ClipMoveToEntities). No engine code is
+ copied. Game data (pak files, models, textures, sounds, maps) is not part of the GPL release and none is used. */
+(function (root) {
+ 'use strict';
+ const M = root.Quake2Game = root.Quake2Game || {};
+ const Q = M.Q = M.Q || {};
+
+ // ---------------- constants (q_shared.h / g_local.h) ----------------
+ Q.FRAMETIME_MS = 100; // g_local.h FRAMETIME 0.1, sv_main.c sv.time = framenum*100
+ Q.CONTENTS_SOLID = 1; Q.CONTENTS_WINDOW = 2; Q.CONTENTS_LAVA = 8; Q.CONTENTS_SLIME = 16; Q.CONTENTS_WATER = 32;
+ Q.CONTENTS_PLAYERCLIP = 0x10000; Q.CONTENTS_MONSTERCLIP = 0x20000; Q.CONTENTS_MONSTER = 0x2000000; Q.CONTENTS_DEADMONSTER = 0x4000000;
+ Q.MASK_SOLID = Q.CONTENTS_SOLID | Q.CONTENTS_WINDOW;
+ Q.MASK_PLAYERSOLID = Q.CONTENTS_SOLID | Q.CONTENTS_PLAYERCLIP | Q.CONTENTS_WINDOW | Q.CONTENTS_MONSTER;
+ Q.MASK_MONSTERSOLID = Q.CONTENTS_SOLID | Q.CONTENTS_MONSTERCLIP | Q.CONTENTS_WINDOW | Q.CONTENTS_MONSTER;
+ Q.MASK_SHOT = Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_WINDOW | Q.CONTENTS_DEADMONSTER;
+ Q.MASK_OPAQUE = Q.CONTENTS_SOLID | Q.CONTENTS_SLIME | Q.CONTENTS_LAVA;
+ Q.MASK_WATER = Q.CONTENTS_WATER | Q.CONTENTS_LAVA | Q.CONTENTS_SLIME;
+ Q.SOLID_NOT = 0; Q.SOLID_TRIGGER = 1; Q.SOLID_BBOX = 2; Q.SOLID_BSP = 3;
+ Q.SVF_NOCLIENT = 1; Q.SVF_DEADMONSTER = 2; Q.SVF_MONSTER = 4;
+ Q.FL_FLY = 1; Q.FL_SWIM = 2; Q.FL_IMMUNE_LASER = 4; Q.FL_PARTIALGROUND = 256; Q.FL_NO_KNOCKBACK = 2048;
+ Q.DAMAGE_NO = 0; Q.DAMAGE_YES = 1; Q.DAMAGE_AIM = 2;
+ Q.DAMAGE_RADIUS = 1; Q.DAMAGE_NO_ARMOR = 2; Q.DAMAGE_ENERGY = 4; Q.DAMAGE_NO_KNOCKBACK = 8; Q.DAMAGE_BULLET = 16;
+ Q.DEAD_NO = 0; Q.DEAD_DYING = 1; Q.DEAD_DEAD = 2;
+ Q.STEPSIZE = 18; Q.MELEE_DISTANCE = 80; Q.DIST_EPSILON = 0.03125;
+ Q.RANGE_MELEE = 0; Q.RANGE_NEAR = 1; Q.RANGE_MID = 2; Q.RANGE_FAR = 3;
+ Q.SV_GRAVITY = 800; Q.SV_MAXVELOCITY = 2000; Q.SV_STOPSPEED = 100; Q.SV_FRICTION = 6;
+ Q.YAW = 1; Q.PITCH = 0; Q.ROLL = 2;
+
+ // ---------------- Win32 CRT rand() (the shipped 1997 build is MSVC; Quake II never calls srand) ----------------
+ // holdrand = holdrand * 214013 + 2531011; return (holdrand >> 16) & 0x7fff. The BossBench engine seed is the
+ // initial holdrand. random() and crandom() are the g_local.h macros.
+ Q.rand = g => { g.rnd = (Math.imul(g.rnd, 214013) + 2531011) >>> 0; return (g.rnd >>> 16) & 0x7fff; };
+ Q.random = g => (Q.rand(g) & 0x7fff) / 0x7fff;
+ Q.crandom = g => 2 * (Q.random(g) - 0.5);
+ Q.drawRand = (g, n) => { for (let i = 0; i < n; i++) Q.rand(g); }; // RNG draws of cosmetic effects (debris/gibs)
+
+ // ---------------- vectors (vec3_t as [x, y, z]) ----------------
+ // Deterministic trigonometry. Math.sin / Math.cos / Math.atan2 can differ in the last bit between V8 builds
+ // (Node vs Chrome, measured in this project), and the simulation must replay bit-identically in Node
+ // (calibration, page example recordings) and in the browser (harness, play page). These are fdlibm's kernels
+ // (k_sin.c, k_cos.c, s_atan.c, e_atan2.c) evaluated with + - * / only, Cody-Waite range reduction for |x| < 2^20.
+ const PIO2_1 = 1.57079632673412561417e+00, PIO2_1T = 6.07710050650619224932e-11, INVPIO2 = 6.36619772367581382433e-01;
+ const S1 = -1.66666666666666324348e-01, S2 = 8.33333333332248946124e-03, S3 = -1.98412698298579493134e-04,
+ S4 = 2.75573137070700676789e-06, S5 = -2.50507602534068634195e-08, S6 = 1.58969099521155010221e-10;
+ const C1 = 4.16666666666666019037e-02, C2 = -1.38888888888741095749e-03, C3 = 2.48015872894767294178e-05,
+ C4 = -2.75573143513906633035e-07, C5 = 2.08757232129817482790e-09, C6 = -1.13596475577881948265e-11;
+ const ksin = x => { const z = x * x; return x + x * z * (S1 + z * (S2 + z * (S3 + z * (S4 + z * (S5 + z * S6))))); };
+ const kcos = x => { const z = x * x; return 1 - 0.5 * z + z * z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6))))); };
+ function reduce(x) { const k = Math.round(x * INVPIO2); return [k & 3, (x - k * PIO2_1) - k * PIO2_1T]; }
+ Q.sin = x => { const [q, r] = reduce(x); return q === 0 ? ksin(r) : q === 1 ? kcos(r) : q === 2 ? -ksin(r) : -kcos(r); };
+ Q.cos = x => { const [q, r] = reduce(x); return q === 0 ? kcos(r) : q === 1 ? -ksin(r) : q === 2 ? -kcos(r) : ksin(r); };
+ const ATANHI = [4.63647609000806093515e-01, 7.85398163397448278999e-01, 9.82793723247329054082e-01, 1.57079632679489655800e+00];
+ const ATANLO = [2.26987774529616870924e-17, 3.06161699786838301793e-17, 1.39033110312309984516e-17, 6.12323399573676603587e-17];
+ const AT = [3.33333333333329318027e-01, -1.99999999998764832476e-01, 1.42857142725034663711e-01, -1.11111104054623557880e-01,
+ 9.09088713343650656196e-02, -7.69187620504482999495e-02, 6.66107313738753120669e-02, -5.83357013379057348645e-02,
+ 4.97687799461593236017e-02, -3.65315727442169155270e-02, 1.62858201153657823623e-02];
+ function atan(x) {
+ const neg = x < 0; let a = neg ? -x : x, id = -1;
+ if (a !== a) return a;
+ if (a >= 7.378697629483821e+19) return neg ? -(ATANHI[3] + ATANLO[3]) : ATANHI[3] + ATANLO[3]; // >= 2^66
+ if (a < 0.4375) { if (a < 1.862645149230957e-09) return x; }
+ else if (a < 1.1875) { if (a < 0.6875) { id = 0; a = (2 * a - 1) / (2 + a); } else { id = 1; a = (a - 1) / (a + 1); } }
+ else if (a < 2.4375) { id = 2; a = (a - 1.5) / (1 + 1.5 * a); }
+ else { id = 3; a = -1 / a; }
+ const z = a * a, w = z * z;
+ const s1 = z * (AT[0] + w * (AT[2] + w * (AT[4] + w * (AT[6] + w * (AT[8] + w * AT[10])))));
+ const s2 = w * (AT[1] + w * (AT[3] + w * (AT[5] + w * (AT[7] + w * AT[9]))));
+ if (id < 0) { const r = a - a * (s1 + s2); return neg ? -r : r; }
+ const r = ATANHI[id] - ((a * (s1 + s2) - ATANLO[id]) - a);
+ return neg ? -r : r;
+ }
+ const PI = 3.1415926535897931160e+00, PI_LO = 1.2246467991473531772e-16;
+ Q.atan2 = (y, x) => {
+ if (x !== x || y !== y) return NaN;
+ if (y === 0) return (x > 0 || (x === 0 && 1 / x > 0)) ? y : (1 / y > 0 ? PI : -PI);
+ if (x === 0) return y > 0 ? PI / 2 : -PI / 2;
+ const z = atan(Math.abs(y / x));
+ if (x > 0) return y > 0 ? z : -z;
+ return y > 0 ? PI - (z - PI_LO) : (z - PI_LO) - PI;
+ };
+ const DEG = Math.PI / 180;
+ Q.add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
+ Q.sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
+ Q.scale = (a, s) => [a[0] * s, a[1] * s, a[2] * s];
+ Q.ma = (a, s, b) => [a[0] + s * b[0], a[1] + s * b[1], a[2] + s * b[2]]; // VectorMA
+ Q.dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+ Q.len = a => Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]);
+ Q.cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+ Q.norm = a => { const l = Q.len(a); return l ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 0]; }; // VectorNormalize
+ Q.eq = (a, b) => a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
+ Q.copy3 = a => [a[0], a[1], a[2]];
+ Q.angleVectors = angles => {
+ const y = angles[1] * DEG, p = angles[0] * DEG, r = angles[2] * DEG;
+ const sy = Q.sin(y), cy = Q.cos(y), sp = Q.sin(p), cp = Q.cos(p), sr = Q.sin(r), cr = Q.cos(r);
+ return {
+ forward: [cp * cy, cp * sy, -sp],
+ right: [-1 * sr * sp * cy + -1 * cr * -sy, -1 * sr * sp * sy + -1 * cr * cy, -1 * sr * cp],
+ up: [cr * sp * cy + -sr * -sy, cr * sp * sy + -sr * cy, cr * cp],
+ };
+ };
+ // anglemod: 16-bit wrap; vectoyaw / vectoangles truncate to whole degrees exactly as g_utils.c does.
+ Q.anglemod = a => (360 / 65536) * (Math.trunc(a * (65536 / 360)) & 65535);
+ Q.vectoyaw = v => {
+ if (v[0] === 0) return v[1] > 0 ? 90 : v[1] < 0 ? -90 : 0;
+ let yaw = Math.trunc(Q.atan2(v[1], v[0]) * 180 / Math.PI);
+ if (yaw < 0) yaw += 360;
+ return yaw;
+ };
+ Q.vectoangles = v => {
+ let yaw, pitch;
+ if (v[1] === 0 && v[0] === 0) { yaw = 0; pitch = v[2] > 0 ? 90 : 270; }
+ else {
+ if (v[0]) yaw = Math.trunc(Q.atan2(v[1], v[0]) * 180 / Math.PI); else yaw = v[1] > 0 ? 90 : -90;
+ if (yaw < 0) yaw += 360;
+ const forward = Math.sqrt(v[0] * v[0] + v[1] * v[1]);
+ pitch = Math.trunc(Q.atan2(v[2], forward) * 180 / Math.PI);
+ if (pitch < 0) pitch += 360;
+ }
+ return [-pitch, yaw, 0];
+ };
+ Q.projectSource = (point, d, forward, right) => [ // G_ProjectSource
+ point[0] + forward[0] * d[0] + right[0] * d[1],
+ point[1] + forward[1] * d[0] + right[1] * d[1],
+ point[2] + forward[2] * d[0] + right[2] * d[1] + d[2]];
+ Q.ANGLE2SHORT = x => { const s = Math.trunc(x * 65536 / 360) & 65535; return s > 32767 ? s - 65536 : s; };
+ Q.SHORT2ANGLE = x => x * (360 / 65536);
+
+ // ---------------- world: axis-aligned brushes ----------------
+ // A brush is {mins, maxs, contents, mat}. The world of a case is static, so it is kept outside the game state
+ // (looked up by case key) and never copied or hashed per tick.
+ Q.worlds = {};
+ // CM_ClipBoxToBrush on the six axial planes of one box brush, with the trace box pushed into each plane.
+ function clipBoxToBox(tr, start, end, mins, maxs, bmin, bmax, contents, isPoint, sky) {
+ let enterfrac = -1, leavefrac = 1, clip = -1, getout = false, startout = false;
+ for (let k = 0; k < 6; k++) {
+ const axis = k >> 1, positive = (k & 1) === 0;
+ let dist = positive ? bmax[axis] : -bmin[axis];
+ if (!isPoint) dist -= positive ? mins[axis] : -maxs[axis];
+ const d1 = (positive ? start[axis] : -start[axis]) - dist, d2 = (positive ? end[axis] : -end[axis]) - dist;
+ if (d2 > 0) getout = true;
+ if (d1 > 0) startout = true;
+ if (d1 > 0 && d2 >= d1) return false; // completely in front of this face
+ if (d1 <= 0 && d2 <= 0) continue;
+ if (d1 > d2) { const f = (d1 - Q.DIST_EPSILON) / (d1 - d2); if (f > enterfrac) { enterfrac = f; clip = k; } }
+ else { const f = (d1 + Q.DIST_EPSILON) / (d1 - d2); if (f < leavefrac) leavefrac = f; }
+ }
+ if (!startout) { tr.startsolid = true; if (!getout) tr.allsolid = true; return true; }
+ if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < tr.fraction) {
+ if (enterfrac < 0) enterfrac = 0;
+ tr.fraction = enterfrac; const axis = clip >> 1, n = [0, 0, 0]; n[axis] = (clip & 1) === 0 ? 1 : -1;
+ tr.normal = n; tr.contents = contents; tr.sky = !!sky; return true;
+ }
+ return false;
+ }
+ // CM_TestBoxInBrush (start == end): inside unless outside some pushed plane.
+ function testBoxInBox(tr, p, mins, maxs, bmin, bmax, contents) {
+ for (let axis = 0; axis < 3; axis++) {
+ if (p[axis] + mins[axis] - bmax[axis] > 0) return false; // pushed +axis plane: dot(p) - (bmax - mins)
+ if (bmin[axis] - (p[axis] + maxs[axis]) > 0) return false;
+ }
+ tr.startsolid = tr.allsolid = true; tr.fraction = 0; tr.contents = contents; return true;
+ }
+ function boxTrace(brushes, start, mins, maxs, end, mask) {
+ const tr = { fraction: 1, startsolid: false, allsolid: false, normal: [0, 0, 0], contents: 0, ent: 0, sky: false };
+ const isPoint = !mins[0] && !mins[1] && !mins[2] && !maxs[0] && !maxs[1] && !maxs[2];
+ const position = start[0] === end[0] && start[1] === end[1] && start[2] === end[2];
+ for (const b of brushes) {
+ if (!(b.contents & mask)) continue;
+ if (position) { if (testBoxInBox(tr, start, mins, maxs, b.mins, b.maxs, b.contents)) return tr; continue; }
+ clipBoxToBox(tr, start, end, mins, maxs, b.mins, b.maxs, b.contents, isPoint, b.sky);
+ if (!tr.fraction) return tr; // CM_TraceToLeaf stops once something is hit at 0
+ }
+ return tr;
+ }
+ const Z3 = [0, 0, 0];
+ // SV_Trace: world first, then SOLID_BBOX edicts (owner/passent rules of SV_ClipMoveToEntities).
+ Q.trace = (g, start, mins, maxs, end, passent, mask) => {
+ mins = mins || Z3; maxs = maxs || Z3;
+ const tr = boxTrace(Q.worlds[g.key].brushes, start, mins, maxs, end, mask);
+ if (tr.fraction !== 0 && (mask & (Q.CONTENTS_MONSTER | Q.CONTENTS_DEADMONSTER))) {
+ const pass = passent >= 0 ? g.ents[passent] : null;
+ for (let i = 1; i < g.ents.length; i++) {
+ const e = g.ents[i];
+ if (!e.inuse || e.solid !== Q.SOLID_BBOX || i === passent) continue;
+ if (tr.allsolid) break;
+ if (pass && (e.owner === passent || pass.owner === i)) continue;
+ if (!(mask & Q.CONTENTS_DEADMONSTER) && (e.svflags & Q.SVF_DEADMONSTER)) continue;
+ if (!(mask & Q.CONTENTS_MONSTER)) continue;
+ const t2 = { fraction: 1, startsolid: false, allsolid: false, normal: [0, 0, 0], contents: 0, ent: i };
+ const bmin = Q.add(e.origin, e.mins), bmax = Q.add(e.origin, e.maxs);
+ if (start[0] === end[0] && start[1] === end[1] && start[2] === end[2]) testBoxInBox(t2, start, mins, maxs, bmin, bmax, Q.CONTENTS_MONSTER);
+ else clipBoxToBox(t2, start, end, mins, maxs, bmin, bmax, Q.CONTENTS_MONSTER, !mins[0] && !mins[1] && !mins[2] && !maxs[0] && !maxs[1] && !maxs[2]);
+ if (t2.allsolid || t2.startsolid || t2.fraction < tr.fraction) {
+ const wasStart = tr.startsolid;
+ tr.fraction = t2.fraction; tr.normal = t2.normal; tr.contents = t2.contents; tr.ent = i; tr.allsolid = t2.allsolid; tr.sky = false;
+ tr.startsolid = wasStart || t2.startsolid;
+ } else if (t2.startsolid) tr.startsolid = true;
+ }
+ }
+ tr.endpos = tr.fraction === 1 ? Q.copy3(end) : [start[0] + tr.fraction * (end[0] - start[0]), start[1] + tr.fraction * (end[1] - start[1]), start[2] + tr.fraction * (end[2] - start[2])];
+ return tr;
+ };
+ Q.pointcontents = (g, p) => {
+ let c = 0;
+ for (const b of Q.worlds[g.key].brushes)
+ if (p[0] >= b.mins[0] && p[0] <= b.maxs[0] && p[1] >= b.mins[1] && p[1] <= b.maxs[1] && p[2] >= b.mins[2] && p[2] <= b.maxs[2]) c |= b.contents;
+ return c;
+ };
+ // SV_LinkEdict absolute bounds, expanded by one unit on every side.
+ Q.absmin = e => [e.origin[0] + e.mins[0] - 1, e.origin[1] + e.mins[1] - 1, e.origin[2] + e.mins[2] - 1];
+ Q.absmax = e => [e.origin[0] + e.maxs[0] + 1, e.origin[1] + e.maxs[1] + 1, e.origin[2] + e.maxs[2] + 1];
+ Q.boxesOverlap = (a, b) => {
+ const amin = Q.absmin(a), amax = Q.absmax(a), bmin = Q.absmin(b), bmax = Q.absmax(b);
+ return amin[0] <= bmax[0] && amax[0] >= bmin[0] && amin[1] <= bmax[1] && amax[1] >= bmin[1] && amin[2] <= bmax[2] && amax[2] >= bmin[2];
+ };
+ Q.center = e => [e.origin[0] + (e.mins[0] + e.maxs[0]) * 0.5, e.origin[1] + (e.mins[1] + e.maxs[1]) * 0.5, e.origin[2] + (e.mins[2] + e.maxs[2]) * 0.5];
+ // findradius: inuse, not SOLID_NOT, centre of the box within rad.
+ Q.findradius = (g, org, rad) => {
+ const out = [];
+ for (let i = 1; i < g.ents.length; i++) {
+ const e = g.ents[i];
+ if (!e.inuse || e.solid === Q.SOLID_NOT) continue;
+ if (Q.len(Q.sub(org, Q.center(e))) > rad) continue;
+ out.push(i);
+ }
+ return out;
+ };
+
+ // ---------------- edicts ----------------
+ // Slot 0 is the world, slot 1 the player (maxclients 1). G_Spawn reuses a free slot freed more than 0.5 s ago
+ // (or at level start); the slot index decides the think order inside G_RunFrame.
+ Q.blankEdict = () => ({
+ inuse: true, classname: '', origin: [0, 0, 0], old_origin: [0, 0, 0], velocity: [0, 0, 0], avelocity: [0, 0, 0], angles: [0, 0, 0],
+ mins: [0, 0, 0], maxs: [0, 0, 0], solid: Q.SOLID_NOT, clipmask: 0, svflags: 0, flags: 0, movetype: 'none', owner: -1, enemy: -1,
+ takedamage: 0, health: 0, max_health: 0, mass: 0, deadflag: 0, think: null, nextthink: 0, touch: null, groundentity: -1,
+ freetime: 0, viewheight: 0, frame: 0, dmg: 0, radius_dmg: 0, dmg_radius: 0, count: 0, spawnflags: 0, gravity: 1, waterlevel: 0, linkcount: 0,
+ });
+ Q.spawn = g => {
+ for (let i = 2; i < g.ents.length; i++) {
+ const e = g.ents[i];
+ if (!e.inuse && (e.freetime < 2000 || g.ms - e.freetime > 500)) { g.ents[i] = Q.blankEdict(); return i; }
+ }
+ g.ents.push(Q.blankEdict()); return g.ents.length - 1;
+ };
+ Q.freeEdict = (g, i) => { g.ents[i] = { inuse: false, freetime: g.ms, classname: 'freed', solid: Q.SOLID_NOT }; };
+ // SV_RunThink: nextthink in ms; think when nextthink <= level.time (+1 ms tolerance of the 0.001 s epsilon).
+ Q.runThink = (g, i) => {
+ const e = g.ents[i];
+ if (!e.nextthink || e.nextthink <= 0 || e.nextthink > g.ms + 1) return true;
+ e.nextthink = 0;
+ const fn = Q.THINK[e.think];
+ if (!fn) throw Error('NULL think ' + e.think);
+ fn(g, i);
+ return false;
+ };
+ Q.THINK = { G_FreeEdict: (g, i) => Q.freeEdict(g, i) };
+ Q.TOUCH = {};
+ Q.event = (g, type, data) => { g.events.push(Object.assign({ type, t: g.t }, data || {})); };
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/quake2_remake/q2monsters.js b/environments/games/web/games/quake2_remake/q2monsters.js
new file mode 100644
index 0000000000000000000000000000000000000000..f3e237a05dcb5fcf747aed8805d4b0727a27764a
--- /dev/null
+++ b/environments/games/web/games/quake2_remake/q2monsters.js
@@ -0,0 +1,1181 @@
+/* Quake II (1997) boss arenas - monsters: the monster framework (g_monster.c M_MoveFrame, monster_think,
+ monster_start_go, M_CheckGround, monster_fire_*; g_ai.c ai_stand / ai_run / ai_charge / ai_move,
+ ai_checkattack, M_CheckAttack, FoundTarget / HuntTarget, visible / infront / range; m_move.c SV_movestep for
+ walking and flying monsters, M_CheckBottom, M_ChangeYaw, SV_StepDirection, SV_NewChaseDir, M_MoveToGoal;
+ g_phys.c SV_Physics_Step / SV_FlyMove; g_combat.c M_ReactToDamage) and the six boss fights of this game:
+ Super Tank (m_supertank.c, models/monsters/boss1), Hornet (m_boss2.c, boss2), Jorg + Makron (m_boss31.c /
+ m_boss32.c, boss3), Tank Commander (m_tank.c), Gladiator (m_gladiator.c) and Mutant (m_mutant.c). Move tables keep the original absolute frame numbers (m_*.h) because the code tests them.
+ Independent reimplementation from the GPL-2.0 source release, commit 372afde46e7defc9dd2d719a1732b8ace1fa096e. */
+(function (root) {
+ 'use strict';
+ const M = root.Quake2Game, Q = M.Q;
+ const { add, sub, scale, ma, dot, len, norm, copy3 } = Q;
+ const AI_STAND_GROUND = 1, AI_TEMP_STAND_GROUND = 2, AI_SOUND_TARGET = 4, AI_LOST_SIGHT = 8, AI_PURSUIT_LAST_SEEN = 16,
+ AI_PURSUE_NEXT = 32, AI_PURSUE_TEMP = 64, AI_HOLD_FRAME = 128, AI_GOOD_GUY = 256, AI_BRUTAL = 512, AI_DUCKED = 2048, AI_COMBAT_POINT = 4096;
+ const AS_STRAIGHT = 1, AS_SLIDING = 2, AS_MELEE = 3, AS_MISSILE = 4;
+ Q.AS = { AS_STRAIGHT, AS_SLIDING, AS_MELEE, AS_MISSILE };
+
+ // ---------------- move tables ----------------
+ // name: [firstframe, lastframe, frames, endfunc]; frame token [:][x], ai s/w/r/c/m/t/n.
+ const AI_OF = { s: 'stand', w: 'walk', r: 'run', c: 'charge', m: 'move', t: 'turn', n: null };
+ function moves(spec) {
+ const out = {};
+ for (const [name, [first, last, frames, end]] of Object.entries(spec)) {
+ const list = [];
+ for (const tok of frames.trim().split(/\s+/)) {
+ const m = /^([swrcmtn])(-?\d+(?:\.\d+)?)(?::(\w+?))?(?:x(\d+))?$/.exec(tok);
+ if (!m) throw Error('bad frame token ' + tok);
+ for (let n = Number(m[4] || 1); n > 0; n--) list.push([AI_OF[m[1]], Number(m[2]), m[3] && m[3] !== 'NULL' ? m[3] : null]);
+ }
+ if (list.length !== last - first + 1) throw Error('frame count ' + name);
+ out[name] = { first, last, frames: list, end };
+ }
+ return out;
+ }
+ const DEFS = Q.MONSTERS = {};
+
+ // ---------------- helpers (g_ai.c) ----------------
+ const eye = e => [e.origin[0], e.origin[1], e.origin[2] + e.viewheight];
+ Q.visible = (g, self, other) => {
+ const tr = Q.trace(g, eye(g.ents[self]), null, null, eye(g.ents[other]), self, Q.MASK_OPAQUE);
+ return tr.fraction === 1.0;
+ };
+ Q.visiblePoint = (g, self, point) => Q.trace(g, eye(g.ents[self]), null, null, point, self, Q.MASK_OPAQUE).fraction === 1.0;
+ Q.infront = (g, self, other) => {
+ const s = g.ents[self], forward = Q.angleVectors(s.angles).forward;
+ return dot(norm(sub(g.ents[other].origin, s.origin)), forward) > 0.3;
+ };
+ Q.range = (g, self, other) => {
+ const l = len(sub(g.ents[self].origin, g.ents[other].origin));
+ return l < Q.MELEE_DISTANCE ? Q.RANGE_MELEE : l < 500 ? Q.RANGE_NEAR : l < 1000 ? Q.RANGE_MID : Q.RANGE_FAR;
+ };
+ const link = (g, i) => { g.ents[i].linkcount++; };
+ const def = e => DEFS[e.classname];
+ const setMove = (e, name) => { e.monsterinfo.currentmove = name; };
+ const call = (g, i, fn, ...args) => { const f = def(g.ents[i])[fn]; if (f) f(g, i, ...args); };
+
+ // ---------------- movement (m_move.c) ----------------
+ function checkBottom(g, i) {
+ const e = g.ents[i], mins = add(e.origin, e.mins), maxs = add(e.origin, e.maxs);
+ let easy = true;
+ for (let x = 0; x <= 1 && easy; x++) for (let y = 0; y <= 1; y++) {
+ const p = [x ? maxs[0] : mins[0], y ? maxs[1] : mins[1], mins[2] - 1];
+ if (Q.pointcontents(g, p) !== Q.CONTENTS_SOLID) { easy = false; break; }
+ }
+ if (easy) return true;
+ const start = [(mins[0] + maxs[0]) * 0.5, (mins[1] + maxs[1]) * 0.5, mins[2]], stop = [start[0], start[1], start[2] - 2 * Q.STEPSIZE];
+ let tr = Q.trace(g, start, null, null, stop, i, Q.MASK_MONSTERSOLID);
+ if (tr.fraction === 1.0) return false;
+ const mid = tr.endpos[2];
+ for (let x = 0; x <= 1; x++) for (let y = 0; y <= 1; y++) {
+ const s = [x ? maxs[0] : mins[0], y ? maxs[1] : mins[1], mins[2]], t = [s[0], s[1], stop[2]];
+ tr = Q.trace(g, s, null, null, t, i, Q.MASK_MONSTERSOLID);
+ if (tr.fraction === 1.0 || mid - tr.endpos[2] > Q.STEPSIZE) return false;
+ }
+ return true;
+ }
+ function movestep(g, i, move, relink) {
+ const e = g.ents[i], oldorg = copy3(e.origin);
+ if (e.flags & (Q.FL_SWIM | Q.FL_FLY)) {
+ for (let k = 0; k < 2; k++) {
+ const neworg = add(e.origin, move);
+ if (k === 0 && e.enemy >= 0) {
+ if (e.goalentity < 0) e.goalentity = e.enemy;
+ const goal = g.ents[e.goalentity], dz = e.origin[2] - goal.origin[2];
+ if (goal.client) { if (dz > 40) neworg[2] -= 8; if (dz < 30) neworg[2] += 8; }
+ else { if (dz > 8) neworg[2] -= 8; else if (dz > 0) neworg[2] -= dz; else if (dz < -8) neworg[2] += 8; else neworg[2] += dz; }
+ }
+ const tr = Q.trace(g, e.origin, e.mins, e.maxs, neworg, i, Q.MASK_MONSTERSOLID);
+ if (tr.fraction === 1) { e.origin = copy3(tr.endpos); if (relink) link(g, i); return true; }
+ if (e.enemy < 0) break;
+ }
+ return false;
+ }
+ const stepsize = (e.monsterinfo.aiflags & 0) ? 1 : Q.STEPSIZE;
+ const neworg = add(e.origin, move); neworg[2] += stepsize;
+ const end = copy3(neworg); end[2] -= stepsize * 2;
+ let tr = Q.trace(g, neworg, e.mins, e.maxs, end, i, Q.MASK_MONSTERSOLID);
+ if (tr.allsolid) return false;
+ if (tr.startsolid) {
+ neworg[2] -= stepsize;
+ tr = Q.trace(g, neworg, e.mins, e.maxs, end, i, Q.MASK_MONSTERSOLID);
+ if (tr.allsolid || tr.startsolid) return false;
+ }
+ if (tr.fraction === 1) {
+ if (e.flags & Q.FL_PARTIALGROUND) { e.origin = add(e.origin, move); if (relink) link(g, i); e.groundentity = -1; return true; }
+ return false; // walked off an edge
+ }
+ e.origin = copy3(tr.endpos);
+ if (!checkBottom(g, i)) {
+ if (e.flags & Q.FL_PARTIALGROUND) { if (relink) link(g, i); return true; }
+ e.origin = oldorg; return false;
+ }
+ e.flags &= ~Q.FL_PARTIALGROUND;
+ e.groundentity = tr.ent;
+ if (relink) link(g, i);
+ return true;
+ }
+ Q.changeYaw = (g, i) => { // M_ChangeYaw
+ const e = g.ents[i], current = Q.anglemod(e.angles[1]), ideal = e.ideal_yaw;
+ if (current === ideal) return;
+ let move = ideal - current; const speed = e.yaw_speed;
+ if (ideal > current) { if (move >= 180) move -= 360; } else { if (move <= -180) move += 360; }
+ if (move > 0) { if (move > speed) move = speed; } else { if (move < -speed) move = -speed; }
+ e.angles[1] = Q.anglemod(current + move);
+ };
+ function stepDirection(g, i, yaw, dist) {
+ const e = g.ents[i];
+ e.ideal_yaw = yaw; Q.changeYaw(g, i);
+ const r = yaw * Math.PI * 2 / 360, move = [Q.cos(r) * dist, Q.sin(r) * dist, 0], old = copy3(e.origin);
+ if (movestep(g, i, move, false)) {
+ const delta = e.angles[1] - e.ideal_yaw;
+ if (delta > 45 && delta < 315) e.origin = old; // not turned far enough, so don't take the step
+ link(g, i);
+ return true;
+ }
+ link(g, i);
+ return false;
+ }
+ function newChaseDir(g, i, goal, dist) {
+ const e = g.ents[i];
+ if (goal < 0) return;
+ const olddir = Q.anglemod(Math.trunc(e.ideal_yaw / 45) * 45), turnaround = Q.anglemod(olddir - 180);
+ const gorg = g.ents[goal].origin, deltax = gorg[0] - e.origin[0], deltay = gorg[1] - e.origin[1], d = [0, 0, 0];
+ d[1] = deltax > 10 ? 0 : deltax < -10 ? 180 : -1;
+ d[2] = deltay < -10 ? 270 : deltay > 10 ? 90 : -1;
+ if (d[1] !== -1 && d[2] !== -1) {
+ const tdir = d[1] === 0 ? (d[2] === 90 ? 45 : 315) : (d[2] === 90 ? 135 : 215);
+ if (tdir !== turnaround && stepDirection(g, i, tdir, dist)) return;
+ }
+ if (((Q.rand(g) & 3) & 1) || Math.abs(Math.trunc(deltay)) > Math.abs(Math.trunc(deltax))) { const t = d[1]; d[1] = d[2]; d[2] = t; }
+ if (d[1] !== -1 && d[1] !== turnaround && stepDirection(g, i, d[1], dist)) return;
+ if (d[2] !== -1 && d[2] !== turnaround && stepDirection(g, i, d[2], dist)) return;
+ if (olddir !== -1 && stepDirection(g, i, olddir, dist)) return;
+ if (Q.rand(g) & 1) { for (let t = 0; t <= 315; t += 45) if (t !== turnaround && stepDirection(g, i, t, dist)) return; }
+ else { for (let t = 315; t >= 0; t -= 45) if (t !== turnaround && stepDirection(g, i, t, dist)) return; }
+ if (turnaround !== -1 && stepDirection(g, i, turnaround, dist)) return;
+ e.ideal_yaw = olddir; // can't move
+ if (!checkBottom(g, i)) e.flags |= Q.FL_PARTIALGROUND;
+ }
+ function closeEnough(g, i, goal, dist) {
+ const e = g.ents[i], t = g.ents[goal], amin = Q.absmin(e), amax = Q.absmax(e), gmin = Q.absmin(t), gmax = Q.absmax(t);
+ for (let k = 0; k < 3; k++) { if (gmin[k] > amax[k] + dist) return false; if (gmax[k] < amin[k] - dist) return false; }
+ return true;
+ }
+ function moveToGoal(g, i, dist) {
+ const e = g.ents[i], goal = e.goalentity;
+ if (e.groundentity < 0 && !(e.flags & (Q.FL_FLY | Q.FL_SWIM))) return;
+ if (e.enemy >= 0 && closeEnough(g, i, e.enemy, dist)) return;
+ if ((Q.rand(g) & 3) === 1 || !stepDirection(g, i, e.ideal_yaw, dist)) { if (g.ents[i].inuse) newChaseDir(g, i, goal, dist); }
+ }
+ const walkmove = (g, i, yaw, dist) => {
+ const e = g.ents[i];
+ if (e.groundentity < 0 && !(e.flags & (Q.FL_FLY | Q.FL_SWIM))) return false;
+ const r = yaw * Math.PI * 2 / 360;
+ return movestep(g, i, [Q.cos(r) * dist, Q.sin(r) * dist, 0], true);
+ };
+ Q.walkmove = walkmove;
+ function checkGround(g, i) { // M_CheckGround
+ const e = g.ents[i];
+ if (e.flags & (Q.FL_SWIM | Q.FL_FLY)) return;
+ if (e.velocity[2] > 100) { e.groundentity = -1; return; }
+ const point = [e.origin[0], e.origin[1], e.origin[2] - 0.25];
+ const tr = Q.trace(g, e.origin, e.mins, e.maxs, point, i, Q.MASK_MONSTERSOLID);
+ if (tr.normal[2] < 0.7 && !tr.startsolid) { e.groundentity = -1; return; }
+ if (!tr.startsolid && !tr.allsolid) { e.origin = copy3(tr.endpos); e.groundentity = tr.ent; e.velocity[2] = 0; }
+ }
+
+ // ---------------- AI (g_ai.c) ----------------
+ function foundTarget(g, i) {
+ const e = g.ents[i], mi = e.monsterinfo;
+ if (g.ents[e.enemy].client) { g.sight_entity = i; g.sight_entity_framenum = g.framenum; }
+ e.show_hostile = g.ms + 1000;
+ mi.last_sighting = copy3(g.ents[e.enemy].origin); mi.trail_time = g.ms;
+ huntTarget(g, i);
+ }
+ function huntTarget(g, i) {
+ const e = g.ents[i], mi = e.monsterinfo;
+ e.goalentity = e.enemy;
+ if (mi.aiflags & AI_STAND_GROUND) call(g, i, 'stand'); else call(g, i, 'run');
+ e.ideal_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin));
+ if (!(mi.aiflags & AI_STAND_GROUND)) mi.attack_finished = g.ms + 1000; // AttackFinished (self, 1)
+ }
+ // FindTarget: the sight entity (a monster that just found the player), the player's own noise (firing, jumping),
+ // impact noise for idle monsters, else the sight client checked by range / visibility / facing. Arena light is
+ // above light_level 5 everywhere, the arena is one PHS / area, and no monster here is an ambusher.
+ function findTarget(g, i) {
+ const e = g.ents[i], mi = e.monsterinfo;
+ let client, heardit = false;
+ if (g.sight_entity_framenum >= g.framenum - 1) {
+ client = g.sight_entity;
+ if (g.ents[client].enemy === e.enemy) return false;
+ } else if (g.sound_entity_framenum >= g.framenum - 1) { client = g.sound_entity; heardit = true; }
+ else if (e.enemy < 0 && g.sound2_entity_framenum >= g.framenum - 1) { client = g.sound2_entity; heardit = true; }
+ else { client = g.sight_client; if (client < 0) return false; }
+ const c = g.ents[client];
+ if (!c || !c.inuse) return false;
+ if (client === e.enemy) return true;
+ if (c.client) { /* FL_NOTARGET is never set */ }
+ else if (c.svflags & Q.SVF_MONSTER) { if (c.enemy < 0) return false; }
+ else if (!heardit) return false;
+ if (!heardit) {
+ const r = Q.range(g, i, client);
+ if (r === Q.RANGE_FAR) return false;
+ if (!Q.visible(g, i, client)) return false;
+ if (r === Q.RANGE_NEAR) { if ((c.show_hostile || 0) < g.ms && !Q.infront(g, i, client)) return false; }
+ else if (r === Q.RANGE_MID) { if (!Q.infront(g, i, client)) return false; }
+ e.enemy = client;
+ if (c.classname !== 'player_noise') {
+ mi.aiflags &= ~AI_SOUND_TARGET;
+ if (!g.ents[e.enemy].client) {
+ e.enemy = g.ents[e.enemy].enemy;
+ if (e.enemy < 0 || !g.ents[e.enemy].client) { e.enemy = -1; return false; }
+ }
+ }
+ } else {
+ const temp = sub(c.origin, e.origin);
+ if (len(temp) > 1000) return false; // too far to hear
+ e.ideal_yaw = Q.vectoyaw(temp); Q.changeYaw(g, i);
+ mi.aiflags |= AI_SOUND_TARGET;
+ e.enemy = client;
+ }
+ foundTarget(g, i);
+ if (!(mi.aiflags & AI_SOUND_TARGET)) call(g, i, 'sight');
+ return true;
+ }
+ const AIF = {
+ stand(g, i, dist) {
+ const e = g.ents[i], mi = e.monsterinfo;
+ if (dist) walkmove(g, i, e.angles[1], dist);
+ if (mi.aiflags & AI_STAND_GROUND) {
+ if (e.enemy >= 0) {
+ e.ideal_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin));
+ if (e.angles[1] !== e.ideal_yaw && (mi.aiflags & AI_TEMP_STAND_GROUND)) { mi.aiflags &= ~(AI_STAND_GROUND | AI_TEMP_STAND_GROUND); call(g, i, 'run'); }
+ Q.changeYaw(g, i);
+ aiCheckAttack(g, i, 0);
+ } else findTarget(g, i);
+ return;
+ }
+ if (findTarget(g, i)) return;
+ // pausetime is set far ahead in every path here, so the walk branch never runs; idle sounds do not exist.
+ },
+ walk(g, i, dist) { moveToGoal(g, i, dist); findTarget(g, i); },
+ turn(g, i, dist) { if (dist) walkmove(g, i, g.ents[i].angles[1], dist); if (findTarget(g, i)) return; Q.changeYaw(g, i); },
+ move(g, i, dist) { walkmove(g, i, g.ents[i].angles[1], dist); },
+ charge(g, i, dist) {
+ const e = g.ents[i];
+ e.ideal_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin));
+ Q.changeYaw(g, i);
+ if (dist) walkmove(g, i, e.angles[1], dist);
+ },
+ run(g, i, dist) { aiRun(g, i, dist); },
+ };
+ // M_CheckAttack (default) with the skill scaling of the attack chance.
+ Q.M_CheckAttack = (g, i) => {
+ const e = g.ents[i], mi = e.monsterinfo, en = g.ents[e.enemy];
+ if (en.health > 0) {
+ const tr = Q.trace(g, eye(e), null, null, eye(en), i, Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_SLIME | Q.CONTENTS_LAVA | Q.CONTENTS_WINDOW);
+ if (tr.ent !== e.enemy) return false;
+ }
+ if (g.ai.enemy_range === Q.RANGE_MELEE) {
+ if (g.skill === 0 && (Q.rand(g) & 3)) return false;
+ mi.attack_state = def(e).melee ? AS_MELEE : AS_MISSILE; return true;
+ }
+ if (!def(e).attack) return false;
+ if (g.ms < mi.attack_finished) return false;
+ if (g.ai.enemy_range === Q.RANGE_FAR) return false;
+ let chance;
+ if (mi.aiflags & AI_STAND_GROUND) chance = 0.4;
+ else if (g.ai.enemy_range === Q.RANGE_NEAR) chance = 0.1;
+ else if (g.ai.enemy_range === Q.RANGE_MID) chance = 0.02;
+ else return false;
+ if (g.skill === 0) chance *= 0.5; else if (g.skill >= 2) chance *= 2;
+ if (Q.random(g) < chance) { mi.attack_state = AS_MISSILE; mi.attack_finished = g.ms + 2000 * Q.random(g); return true; }
+ if (e.flags & Q.FL_FLY) mi.attack_state = Q.random(g) < 0.3 ? AS_SLIDING : AS_STRAIGHT;
+ return false;
+ };
+ // Boss2_CheckAttack / Jorg_CheckAttack / Makron_CheckAttack share one shape: no skill scaling, own chances.
+ function bossCheckAttack(near, mid) {
+ return (g, i) => {
+ const e = g.ents[i], mi = e.monsterinfo, en = g.ents[e.enemy];
+ if (en.health > 0) {
+ const tr = Q.trace(g, eye(e), null, null, eye(en), i, Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_SLIME | Q.CONTENTS_LAVA);
+ if (tr.ent !== e.enemy) return false;
+ }
+ const range = Q.range(g, i, e.enemy);
+ e.ideal_yaw = Q.vectoyaw(sub(en.origin, e.origin));
+ if (range === Q.RANGE_MELEE) { mi.attack_state = def(e).melee ? AS_MELEE : AS_MISSILE; return true; }
+ if (!def(e).attack) return false;
+ if (g.ms < mi.attack_finished) return false;
+ if (range === Q.RANGE_FAR) return false;
+ let chance;
+ if (mi.aiflags & AI_STAND_GROUND) chance = 0.4;
+ else if (range === Q.RANGE_NEAR) chance = near;
+ else if (range === Q.RANGE_MID) chance = mid;
+ else return false;
+ if (Q.random(g) < chance) { mi.attack_state = AS_MISSILE; mi.attack_finished = g.ms + 2000 * Q.random(g); return true; }
+ if (e.flags & Q.FL_FLY) mi.attack_state = Q.random(g) < 0.3 ? AS_SLIDING : AS_STRAIGHT;
+ return false;
+ };
+ }
+ const facingIdeal = e => { const d = Q.anglemod(e.angles[1] - e.ideal_yaw); return !(d > 45 && d < 315); };
+ function aiCheckAttack(g, i, dist) {
+ const e = g.ents[i], mi = e.monsterinfo;
+ if (e.goalentity >= 0 && (mi.aiflags & AI_SOUND_TARGET)) {
+ if (g.ms - (g.ents[e.enemy].teleport_time || 0) > 5000) {
+ if (e.goalentity === e.enemy) e.goalentity = -1; // no movetarget in these arenas
+ mi.aiflags &= ~AI_SOUND_TARGET;
+ if (mi.aiflags & AI_TEMP_STAND_GROUND) mi.aiflags &= ~(AI_STAND_GROUND | AI_TEMP_STAND_GROUND);
+ } else { e.show_hostile = g.ms + 1000; return false; }
+ }
+ g.ai.enemy_vis = false;
+ const en = e.enemy >= 0 ? g.ents[e.enemy] : null;
+ // hesDeadJim: AI_BRUTAL monsters (the Tank) keep going until the enemy is below -80; a player_noise target has
+ // no health either.
+ const dead = !en || !en.inuse || (en.health || 0) <= ((mi.aiflags & AI_BRUTAL) ? -80 : 0);
+ if (dead) {
+ e.enemy = -1;
+ if (e.oldenemy >= 0 && g.ents[e.oldenemy].inuse && g.ents[e.oldenemy].health > 0) { e.enemy = e.oldenemy; e.oldenemy = -1; huntTarget(g, i); }
+ else { mi.pausetime = g.ms + 100000000000; call(g, i, 'stand'); return true; }
+ }
+ e.show_hostile = g.ms + 1000;
+ g.ai.enemy_vis = Q.visible(g, i, e.enemy);
+ if (g.ai.enemy_vis) { mi.search_time = g.ms + 5000; mi.last_sighting = copy3(g.ents[e.enemy].origin); }
+ g.ai.enemy_infront = Q.infront(g, i, e.enemy);
+ g.ai.enemy_range = Q.range(g, i, e.enemy);
+ g.ai.enemy_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin));
+ if (mi.attack_state === AS_MISSILE) { // ai_run_missile
+ e.ideal_yaw = g.ai.enemy_yaw; Q.changeYaw(g, i);
+ if (facingIdeal(e)) { call(g, i, 'attack'); mi.attack_state = AS_STRAIGHT; }
+ return true;
+ }
+ if (mi.attack_state === AS_MELEE) {
+ e.ideal_yaw = g.ai.enemy_yaw; Q.changeYaw(g, i);
+ if (facingIdeal(e)) { call(g, i, 'melee'); mi.attack_state = AS_STRAIGHT; }
+ return true;
+ }
+ if (!g.ai.enemy_vis) return false;
+ return (def(e).checkattack || Q.M_CheckAttack)(g, i);
+ }
+ function aiRun(g, i, dist) {
+ const e = g.ents[i], mi = e.monsterinfo;
+ if (mi.aiflags & AI_SOUND_TARGET) {
+ if (len(sub(e.origin, g.ents[e.enemy].origin)) < 64) { mi.aiflags |= AI_STAND_GROUND | AI_TEMP_STAND_GROUND; call(g, i, 'stand'); return; }
+ moveToGoal(g, i, dist);
+ if (!findTarget(g, i)) return;
+ }
+ if (aiCheckAttack(g, i, dist)) return;
+ if (mi.attack_state === AS_SLIDING) { // ai_run_slide
+ e.ideal_yaw = g.ai.enemy_yaw; Q.changeYaw(g, i);
+ const ofs = mi.lefty ? 90 : -90;
+ if (walkmove(g, i, e.ideal_yaw + ofs, dist)) return;
+ mi.lefty = 1 - mi.lefty;
+ walkmove(g, i, e.ideal_yaw - ofs, dist);
+ return;
+ }
+ if (g.ai.enemy_vis) {
+ moveToGoal(g, i, dist);
+ mi.aiflags &= ~AI_LOST_SIGHT;
+ mi.last_sighting = copy3(g.ents[e.enemy].origin); mi.trail_time = g.ms;
+ mi.stall_pos = copy3(e.origin); mi.stall_t = g.ms; mi.chase_until = 0;
+ return;
+ }
+ // BossBench engagement rule (not in Quake II; meeting rule "a boss must never stop pursuing"): the lost-sight
+ // pursuit below can ping-pong between two course-correction targets when a large boss is flush against a pillar,
+ // and since every PURSUE_NEXT renews search_time the original 20 s fallback never fires. If the boss has neither
+ // seen the player nor moved 48 units for 3 s, it takes that original fallback early: 2 s of M_MoveToGoal straight
+ // at its enemy (SV_NewChaseDir steps around the obstacle).
+ if (mi.chase_until > g.ms) { moveToGoal(g, i, dist); return; }
+ if (!mi.stall_pos || len(sub(e.origin, mi.stall_pos)) > 48) { mi.stall_pos = copy3(e.origin); mi.stall_t = g.ms; }
+ else if (g.ms - mi.stall_t >= 3000) {
+ mi.chase_until = g.ms + 2000; mi.stall_pos = null;
+ mi.aiflags &= ~(AI_LOST_SIGHT | AI_PURSUIT_LAST_SEEN | AI_PURSUE_NEXT | AI_PURSUE_TEMP);
+ Q.event(g, 'boss_unstick', { classname: e.classname });
+ moveToGoal(g, i, dist);
+ return;
+ }
+ if (mi.search_time && g.ms > mi.search_time + 20000) { moveToGoal(g, i, dist); mi.search_time = 0; return; }
+ // Lost sight: chase last_sighting, then the player trail, with the course correction traces.
+ const save = e.goalentity, tempgoal = Q.spawn(g);
+ e.goalentity = tempgoal;
+ let fresh = false;
+ if (!(mi.aiflags & AI_LOST_SIGHT)) { mi.aiflags |= AI_LOST_SIGHT | AI_PURSUIT_LAST_SEEN; mi.aiflags &= ~(AI_PURSUE_NEXT | AI_PURSUE_TEMP); fresh = true; }
+ if (mi.aiflags & AI_PURSUE_NEXT) {
+ mi.aiflags &= ~AI_PURSUE_NEXT;
+ mi.search_time = g.ms + 5000;
+ let marker = null;
+ if (mi.aiflags & AI_PURSUE_TEMP) { mi.aiflags &= ~AI_PURSUE_TEMP; mi.last_sighting = copy3(mi.saved_goal); fresh = true; }
+ else if (mi.aiflags & AI_PURSUIT_LAST_SEEN) { mi.aiflags &= ~AI_PURSUIT_LAST_SEEN; marker = Q.trailPick(g, i, true); }
+ else marker = Q.trailPick(g, i, false);
+ if (marker) { mi.last_sighting = copy3(marker.origin); mi.trail_time = marker.timestamp; e.angles[1] = e.ideal_yaw = marker.yaw; fresh = true; }
+ }
+ let d1 = len(sub(e.origin, mi.last_sighting));
+ if (d1 <= dist) { mi.aiflags |= AI_PURSUE_NEXT; dist = d1; }
+ g.ents[tempgoal].origin = copy3(mi.last_sighting);
+ if (fresh) {
+ let tr = Q.trace(g, e.origin, e.mins, e.maxs, mi.last_sighting, i, Q.MASK_PLAYERSOLID);
+ if (tr.fraction < 1) {
+ const v = sub(g.ents[tempgoal].origin, e.origin);
+ d1 = len(v);
+ let center = tr.fraction;
+ const d2 = d1 * ((center + 1) / 2);
+ e.angles[1] = e.ideal_yaw = Q.vectoyaw(v);
+ const av = Q.angleVectors(e.angles);
+ let left_target = Q.projectSource(e.origin, [d2, -16, 0], av.forward, av.right);
+ tr = Q.trace(g, e.origin, e.mins, e.maxs, left_target, i, Q.MASK_PLAYERSOLID);
+ const left = tr.fraction;
+ let right_target = Q.projectSource(e.origin, [d2, 16, 0], av.forward, av.right);
+ tr = Q.trace(g, e.origin, e.mins, e.maxs, right_target, i, Q.MASK_PLAYERSOLID);
+ const right = tr.fraction;
+ center = (d1 * center) / d2;
+ if (left >= center && left > right) {
+ if (left < 1) left_target = Q.projectSource(e.origin, [d2 * left * 0.5, -16, 0], av.forward, av.right);
+ mi.saved_goal = copy3(mi.last_sighting); mi.aiflags |= AI_PURSUE_TEMP;
+ g.ents[tempgoal].origin = copy3(left_target); mi.last_sighting = copy3(left_target);
+ e.angles[1] = e.ideal_yaw = Q.vectoyaw(sub(g.ents[tempgoal].origin, e.origin));
+ } else if (right >= center && right > left) {
+ if (right < 1) right_target = Q.projectSource(e.origin, [d2 * right * 0.5, 16, 0], av.forward, av.right);
+ mi.saved_goal = copy3(mi.last_sighting); mi.aiflags |= AI_PURSUE_TEMP;
+ g.ents[tempgoal].origin = copy3(right_target); mi.last_sighting = copy3(right_target);
+ e.angles[1] = e.ideal_yaw = Q.vectoyaw(sub(g.ents[tempgoal].origin, e.origin));
+ }
+ }
+ }
+ moveToGoal(g, i, dist);
+ Q.freeEdict(g, tempgoal);
+ if (g.ents[i].inuse) g.ents[i].goalentity = save;
+ }
+ // M_ReactToDamage: the player is the only other combatant; damage from the monster itself is ignored.
+ Q.reactToDamage = (g, targ, attacker) => {
+ const t = g.ents[targ], a = g.ents[attacker];
+ if (!a || (!a.client && !(a.svflags & Q.SVF_MONSTER))) return;
+ if (attacker === targ || attacker === t.enemy) return;
+ if (a.client) {
+ t.monsterinfo.aiflags &= ~AI_SOUND_TARGET;
+ if (t.enemy >= 0 && g.ents[t.enemy].client) {
+ if (Q.visible(g, targ, t.enemy)) { t.oldenemy = attacker; return; }
+ t.oldenemy = t.enemy;
+ }
+ t.enemy = attacker;
+ if (!(t.monsterinfo.aiflags & AI_DUCKED)) foundTarget(g, targ);
+ }
+ };
+ Q.AI_DUCKED = AI_DUCKED;
+ Q.monsterPain = (g, i, attacker, kick, damage) => call(g, i, 'pain', attacker, kick, damage);
+ Q.monsterDie = (g, i, inflictor, attacker, damage, point) => call(g, i, 'die', inflictor, attacker, damage, point);
+ // monster_death_use: fliers drop out of the air; the case decides what the death triggers (Makron's spawn, the win).
+ Q.monsterDeathUse = (g, i) => {
+ const e = g.ents[i];
+ e.flags &= ~(Q.FL_FLY | Q.FL_SWIM);
+ e.monsterinfo.aiflags &= AI_GOOD_GUY;
+ Q.event(g, 'boss_killed', { classname: e.classname });
+ if (e.final) g.bossKilled = g.t + 1;
+ };
+
+ // ---------------- framework (g_monster.c) ----------------
+ function moveFrame(g, i) {
+ const e = g.ents[i], mi = e.monsterinfo;
+ let move = def(e).moves[mi.currentmove];
+ e.nextthink = g.ms + Q.FRAMETIME_MS;
+ if (mi.nextframe && mi.nextframe >= move.first && mi.nextframe <= move.last) { e.frame = mi.nextframe; mi.nextframe = 0; }
+ else {
+ if (e.frame === move.last && move.end) {
+ call(g, i, move.end);
+ move = def(e).moves[mi.currentmove];
+ if (e.svflags & Q.SVF_DEADMONSTER) return;
+ }
+ if (e.frame < move.first || e.frame > move.last) { mi.aiflags &= ~AI_HOLD_FRAME; e.frame = move.first; }
+ else if (!(mi.aiflags & AI_HOLD_FRAME)) { e.frame++; if (e.frame > move.last) e.frame = move.first; }
+ }
+ const [ai, dist, think] = move.frames[e.frame - move.first];
+ if (ai) AIF[ai](g, i, (mi.aiflags & AI_HOLD_FRAME) ? 0 : dist * mi.scale);
+ if (think && g.ents[i].inuse) call(g, i, think);
+ }
+ Q.THINK.monster_think = (g, i) => {
+ moveFrame(g, i);
+ const e = g.ents[i];
+ if (!e.inuse) return;
+ if (e.linkcount !== e.monsterinfo.linkcount) { e.monsterinfo.linkcount = e.linkcount; checkGround(g, i); }
+ };
+ // SV_Physics_Step: gravity, fly / ground friction and SV_FlyMove for a monster with velocity, then think. At 60 Hz
+ // (q2-arena@3) the physics runs every host frame with that frame's length (g.dt); the think still fires on its
+ // nextthink, i.e. every 100 ms server frame. lerp keeps the displacement of the last think for the renderer, which
+ // spreads it over the next 100 ms like the original client (cl_ents.c lerpfrac); it never feeds back into the rules.
+ // Friction in SV_Physics_Step is speed * (1 - frametime * friction) once per 100 ms server frame (x0.4 on the
+ // ground, x0.8 for a flier's vertical speed). Applied per 16/17 ms host frame it keeps the per-second decay with
+ // k^(ms/100) (precomputed, so Node and the browser agree bit for bit); below stopspeed the original subtracts a
+ // constant per second, which the linear form already keeps.
+ const FRICTION_K = { 16: [0.86363373567437107, 0.96492686487423818], 17: [0.85575648417344741, 0.96277609334680192] };
+ const frictionK = (g, fly) => { const k = FRICTION_K[Math.round(g.dt * 1000)]; if (!k) throw Error('host frame ' + g.dt); return k[fly ? 1 : 0]; };
+ Q.physicsStep = (g, i) => {
+ let e = g.ents[i];
+ if (e.groundentity < 0) checkGround(g, i);
+ for (let k = 0; k < 3; k++) e.velocity[k] = Math.max(-Q.SV_MAXVELOCITY, Math.min(Q.SV_MAXVELOCITY, e.velocity[k]));
+ const wasonground = e.groundentity >= 0, ft = g.dt;
+ if (!wasonground && !(e.flags & Q.FL_FLY)) e.velocity[2] -= e.gravity * Q.SV_GRAVITY * ft;
+ if ((e.flags & Q.FL_FLY) && e.velocity[2] !== 0) {
+ const speed = Math.abs(e.velocity[2]), control = speed < Q.SV_STOPSPEED ? Q.SV_STOPSPEED : speed;
+ let ns = speed < Q.SV_STOPSPEED ? speed - ft * control * Q.SV_FRICTION / 3 : speed * frictionK(g, true); if (ns < 0) ns = 0; e.velocity[2] *= ns / speed;
+ }
+ if (e.velocity[0] || e.velocity[1] || e.velocity[2]) {
+ if ((wasonground || (e.flags & (Q.FL_SWIM | Q.FL_FLY))) && !(e.health <= 0 && !checkBottom(g, i))) {
+ const speed = Math.sqrt(e.velocity[0] ** 2 + e.velocity[1] ** 2);
+ if (speed) {
+ const control = speed < Q.SV_STOPSPEED ? Q.SV_STOPSPEED : speed;
+ let ns = speed < Q.SV_STOPSPEED ? speed - ft * control * Q.SV_FRICTION : speed * frictionK(g, false); if (ns < 0) ns = 0; ns /= speed;
+ e.velocity[0] *= ns; e.velocity[1] *= ns;
+ }
+ }
+ flyMove(g, i, ft, (e.svflags & Q.SVF_MONSTER) ? Q.MASK_MONSTERSOLID : Q.MASK_SOLID);
+ link(g, i);
+ if (!g.ents[i].inuse) return;
+ }
+ const before = copy3(g.ents[i].origin);
+ if (Q.runThink(g, i) || !g.ents[i].inuse) return;
+ const after = g.ents[i].origin;
+ g.ents[i].lerp = [before[0] - after[0], before[1] - after[1], before[2] - after[2], g.ms];
+ };
+ function flyMove(g, i, time, mask) { // SV_FlyMove
+ const e = g.ents[i], primal = copy3(e.velocity), planes = [];
+ let original = copy3(e.velocity), time_left = time;
+ e.groundentity = -1;
+ for (let bump = 0; bump < 4; bump++) {
+ const end = [0, 1, 2].map(k => e.origin[k] + time_left * e.velocity[k]);
+ const tr = Q.trace(g, e.origin, e.mins, e.maxs, end, i, mask);
+ if (tr.allsolid) { e.velocity = [0, 0, 0]; return 3; }
+ if (tr.fraction > 0) { e.origin = copy3(tr.endpos); original = copy3(e.velocity); planes.length = 0; }
+ if (tr.fraction === 1) break;
+ if (tr.normal[2] > 0.7 && tr.ent === 0) e.groundentity = 0;
+ Q.impact(g, i, tr);
+ if (!g.ents[i].inuse) break;
+ time_left -= time_left * tr.fraction;
+ if (planes.length >= 5) { e.velocity = [0, 0, 0]; return 3; }
+ planes.push(tr.normal);
+ let k;
+ for (k = 0; k < planes.length; k++) {
+ const backoff = dot(original, planes[k]), nv = [0, 1, 2].map(c => { const v = original[c] - planes[k][c] * backoff; return v > -0.1 && v < 0.1 ? 0 : v; });
+ let j;
+ for (j = 0; j < planes.length; j++) if (j !== k && !Q.eq(planes[k], planes[j]) && dot(nv, planes[j]) < 0) break;
+ if (j === planes.length) { e.velocity = nv; break; }
+ }
+ if (k === planes.length) {
+ if (planes.length !== 2) { e.velocity = [0, 0, 0]; return 7; }
+ const dir = Q.cross(planes[0], planes[1]); e.velocity = scale(dir, dot(dir, e.velocity));
+ }
+ if (dot(e.velocity, primal) <= 0) { e.velocity = [0, 0, 0]; return 0; }
+ }
+ return 0;
+ }
+ // Spawn: SP_monster_* + monster_start; the first think is walkmonster_start_go / flymonster_start_go.
+ Q.spawnMonster = (g, classname, origin, yaw, opts) => {
+ const i = Q.spawn(g), e = g.ents[i], d = DEFS[classname];
+ Object.assign(e, {
+ classname, origin: copy3(origin), old_origin: copy3(origin), angles: [0, yaw, 0], ideal_yaw: yaw, mins: copy3(d.mins), maxs: copy3(d.maxs),
+ movetype: 'step', solid: Q.SOLID_BBOX, health: opts.health, gib_health: d.gib_health, mass: d.mass, flags: d.fly ? Q.FL_FLY : 0,
+ svflags: Q.SVF_MONSTER, takedamage: Q.DAMAGE_AIM, clipmask: Q.MASK_MONSTERSOLID, yaw_speed: 0, viewheight: 0, final: !!opts.final,
+ goalentity: -1, oldenemy: -1, movetarget: -1, show_hostile: 0, pain_debounce_time: 0, skinnum: 0, pos1: [0, 0, 0], count: 0,
+ think: d.fly ? 'flymonster_start_go' : 'walkmonster_start_go', nextthink: g.ms + Q.FRAMETIME_MS,
+ monsterinfo: { currentmove: d.startMove || 'stand', nextframe: 0, aiflags: 0, scale: 1, pausetime: 0, attack_finished: 0, attack_state: 0, lefty: 0,
+ search_time: 0, trail_time: 0, last_sighting: [0, 0, 0], saved_goal: [0, 0, 0], linkcount: 0, idle_time: 0,
+ stall_pos: null, stall_t: 0, chase_until: 0 },
+ });
+ if (d.immuneLaser) e.flags |= Q.FL_IMMUNE_LASER;
+ e.max_health = e.health;
+ const mv = d.moves[e.monsterinfo.currentmove];
+ e.frame = mv.first + (Q.rand(g) % (mv.last - mv.first + 1)); // monster_start picks a random first frame
+ if (opts.engage) e.engage = true;
+ return i;
+ };
+ function dropToFloor(g, i) { // M_droptofloor: lift one unit, trace 256 down, rest DIST_EPSILON above the floor
+ const e = g.ents[i];
+ e.origin[2] += 1;
+ const end = copy3(e.origin); end[2] -= 256;
+ const tr = Q.trace(g, e.origin, e.mins, e.maxs, end, i, Q.MASK_MONSTERSOLID);
+ if (tr.fraction === 1 || tr.allsolid) return;
+ e.origin = copy3(tr.endpos); link(g, i);
+ checkGround(g, i);
+ }
+ function startGo(g, i, fly) {
+ const e = g.ents[i];
+ if (!fly) { if (g.ms < 1000) dropToFloor(g, i); } else walkmove(g, i, 0, 0);
+ if (!e.yaw_speed) e.yaw_speed = fly ? 10 : 20;
+ e.viewheight = 25;
+ if (e.health <= 0) return; // monster_start_go: killed before it ever thought
+ e.monsterinfo.pausetime = 100000000000; call(g, i, 'stand');
+ e.think = 'monster_think'; e.nextthink = g.ms + Q.FRAMETIME_MS;
+ // monster_use by the arena trigger: an alerted boss hunts the player from the first frame.
+ if (e.engage && g.ents[1].health > 0) { e.enemy = 1; foundTarget(g, i); }
+ }
+ Q.THINK.walkmonster_start_go = (g, i) => startGo(g, i, false);
+ Q.THINK.flymonster_start_go = (g, i) => startGo(g, i, true);
+ // Muzzle helpers (G_ProjectSource with monster_flash_offset, monster yaw only).
+ const muzzle = (e, ofs) => { const av = Q.angleVectors(e.angles); return Q.projectSource(e.origin, ofs, av.forward, av.right); };
+ const aimAt = (g, start, target) => norm(sub(target, start));
+ const enemyEye = (g, e, lag) => { const en = g.ents[e.enemy], t = ma(en.origin, lag, en.velocity); t[2] += en.viewheight; return t; };
+ function flash(g, i, weapon, at, extra) { Q.fx(g, 'mflash', at, null, Object.assign({ weapon, owner: i }, extra || {})); }
+ Q.monsterFireBullet = (g, i, start, dir, damage, kick) => Q.fireBullet(g, i, start, dir, damage, kick, 300, 500, 'monster');
+ Q.monsterFireRocket = (g, i, start, dir, damage, speed) => Q.fireRocket(g, i, start, dir, damage, speed, damage + 20, damage);
+ // BossExplode: nine explosions a frame apart around the body, then the gibs (cosmetic; their RNG draws kept).
+ Q.THINK.BossExplode = (g, i) => {
+ const e = g.ents[i];
+ e.think = 'BossExplode';
+ const org = copy3(e.origin); org[2] += 24 + (Q.rand(g) & 15);
+ const OFS = [[-24, -24], [24, 24], [24, -24], [-24, 24], [-48, -48], [48, 48], [-48, 48], [48, -48]];
+ const n = e.count++;
+ if (n < 8) {
+ org[0] += OFS[n][0]; org[1] += OFS[n][1];
+ Q.fx(g, 'explosion', org, null, { big: true });
+ e.nextthink = g.ms + Q.FRAMETIME_MS;
+ return;
+ }
+ // case 8: four meat chunks, eight metal chunks, the chest, then the boss itself becomes the gear head.
+ for (let k = 0; k < 4; k++) Q.throwGib(g, i, 'meat', 500, true);
+ for (let k = 0; k < 8; k++) Q.throwGib(g, i, 'metal', 500, false);
+ Q.throwGib(g, i, 'chest', 500, true);
+ Q.throwHead(g, i, 'gear', 500, false);
+ g.ents[i].deadflag = Q.DEAD_DEAD; g.ents[i].gibbed = true;
+ Q.fx(g, 'gibs', Q.center(g.ents[i]), null, { size: 64 });
+ };
+ function bossDead(mins, maxs) {
+ return (g, i) => { const e = g.ents[i]; e.mins = mins; e.maxs = maxs; e.movetype = 'toss'; e.svflags |= Q.SVF_DEADMONSTER; e.nextthink = 0; };
+ }
+ const stand = (g, i) => setMove(g.ents[i], 'stand');
+ const runOrStand = (g, i) => setMove(g.ents[i], (g.ents[i].monsterinfo.aiflags & AI_STAND_GROUND) ? 'stand' : 'run');
+ const debounced = (g, e) => g.ms < e.pain_debounce_time;
+ const sound = () => {};
+
+ // ================= Super Tank (m_supertank.c) =================
+ DEFS.monster_supertank = {
+ name: 'Tracked Gun Carrier', health: 1500, gib_health: -500, mass: 800, mins: [-64, -64, 0], maxs: [64, 64, 112], gibs: 13,
+ moves: moves({
+ stand: [194, 253, 's0x60', null],
+ run: [128, 145, 'r12:TreadSound r12x17', null],
+ forward: [128, 145, 'w4:TreadSound w4x17', null],
+ pain3: [172, 175, 'm0x4', 'run'], pain2: [168, 171, 'm0x4', 'run'], pain1: [164, 167, 'm0x4', 'run'],
+ death: [98, 121, 'm0x23 m0:BossExplode', 'dead'],
+ attack2: [20, 46, 'c0x7 c0:supertankRocket m0x2 m0:supertankRocket m0x2 m0:supertankRocket m0x13', 'run'],
+ attack1: [0, 5, 'c0:supertankMachineGunx6', 'reattack1'],
+ end_attack1: [6, 19, 'm0x14', 'run'],
+ }),
+ stand, walk: (g, i) => setMove(g.ents[i], 'forward'), run: runOrStand, TreadSound: sound,
+ reattack1(g, i) {
+ const e = g.ents[i];
+ if (Q.visible(g, i, e.enemy)) setMove(e, Q.random(g) < 0.9 ? 'attack1' : 'end_attack1'); else setMove(e, 'end_attack1');
+ },
+ pain(g, i, other, kick, damage) {
+ const e = g.ents[i];
+ if (e.health < e.max_health / 2) e.skinnum = 1;
+ if (debounced(g, e)) return;
+ if (damage <= 25 && Q.random(g) < 0.2) return; // lessen the chance of pain frames
+ if (g.skill >= 2 && e.frame >= 20 && e.frame <= 33) return; // no pain while firing rockets
+ e.pain_debounce_time = g.ms + 3000;
+ if (g.skill === 3) return; // no pain anims in nightmare
+ setMove(e, damage <= 10 ? 'pain1' : damage <= 25 ? 'pain2' : 'pain3');
+ },
+ supertankRocket(g, i) {
+ const e = g.ents[i];
+ const ofs = e.frame === 27 ? [16.0, -22.5, 91.2] : e.frame === 30 ? [16.0, -33.4, 86.7] : [16.0, -42.8, 83.3];
+ const start = muzzle(e, ofs);
+ Q.monsterFireRocket(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 500);
+ flash(g, i, 'rocket', start);
+ },
+ supertankMachineGun(g, i) {
+ const e = g.ents[i], av = Q.angleVectors([0, e.angles[1], 0]);
+ const start = Q.projectSource(e.origin, [30.0, 30.0, 88.5], av.forward, av.right);
+ let forward = av.forward;
+ if (e.enemy >= 0) forward = aimAt(g, start, enemyEye(g, e, 0));
+ Q.monsterFireBullet(g, i, start, forward, 6, 4);
+ flash(g, i, 'mg', start);
+ },
+ attack(g, i) {
+ const e = g.ents[i], range = len(sub(g.ents[e.enemy].origin, e.origin));
+ if (range <= 160) setMove(e, 'attack1');
+ else setMove(e, Q.random(g) < 0.3 ? 'attack1' : 'attack2'); // fire rockets more often at distance
+ },
+ die(g, i) { const e = g.ents[i]; e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_NO; e.count = 0; setMove(e, 'death'); },
+ dead: bossDead([-60, -60, 0], [60, 60, 72]),
+ BossExplode: (g, i) => Q.THINK.BossExplode(g, i),
+ };
+
+ // ================= Hornet (m_boss2.c) =================
+ DEFS.monster_boss2 = {
+ name: 'Flying Gunship', health: 2000, gib_health: -200, mass: 1000, mins: [-56, -56, 0], maxs: [56, 56, 80], fly: true, immuneLaser: true, gibs: 13,
+ moves: moves({
+ stand: [0, 20, 's0x21', null],
+ walk: [50, 69, 'w8x20', null],
+ run: [50, 69, 'r8x20', null],
+ attack_pre_mg: [70, 78, 'c1x8 c1:boss2_attack_mg', null],
+ attack_mg: [79, 84, 'c1:Boss2MachineGunx5 c1:boss2_reattack_mg', null],
+ attack_post_mg: [85, 88, 'c1x4', 'run'],
+ attack_rocket: [89, 109, 'c1x12 m-20:Boss2Rocket c1x8', 'run'],
+ pain_heavy: [110, 127, 'm0x18', 'run'],
+ pain_light: [128, 131, 'm0x4', 'run'],
+ death: [132, 180, 'm0x48 m0:BossExplode', 'dead'],
+ }),
+ stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand,
+ checkattack: bossCheckAttack(0.8, 0.8),
+ attack(g, i) {
+ const e = g.ents[i], range = len(sub(g.ents[e.enemy].origin, e.origin));
+ if (range <= 125) setMove(e, 'attack_pre_mg'); else setMove(e, Q.random(g) <= 0.6 ? 'attack_pre_mg' : 'attack_rocket');
+ },
+ boss2_attack_mg: (g, i) => setMove(g.ents[i], 'attack_mg'),
+ boss2_reattack_mg(g, i) {
+ const e = g.ents[i];
+ if (Q.infront(g, i, e.enemy)) setMove(e, Q.random(g) <= 0.7 ? 'attack_mg' : 'attack_post_mg'); else setMove(e, 'attack_post_mg');
+ },
+ Boss2MachineGun(g, i) {
+ const e = g.ents[i];
+ for (const ofs of [[32, -40, 70], [32, 40, 70]]) { // boss2_firebullet_left, then _right
+ const start = muzzle(e, ofs);
+ Q.monsterFireBullet(g, i, start, aimAt(g, start, enemyEye(g, e, -0.2)), 6, 4);
+ flash(g, i, 'mg', start);
+ }
+ },
+ Boss2Rocket(g, i) {
+ const e = g.ents[i];
+ for (const ofs of [[22.0, 16.0, 10.0], [22.0, 8.0, 10.0], [22.0, -8.0, 10.0], [22.0, -16.0, 10.0]]) {
+ const start = muzzle(e, ofs);
+ Q.monsterFireRocket(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 500);
+ flash(g, i, 'rocket', start);
+ }
+ },
+ pain(g, i, other, kick, damage) {
+ const e = g.ents[i];
+ if (e.health < e.max_health / 2) e.skinnum = 1;
+ if (debounced(g, e)) return;
+ e.pain_debounce_time = g.ms + 3000;
+ setMove(e, damage < 30 ? 'pain_light' : 'pain_heavy');
+ },
+ die(g, i) { const e = g.ents[i]; e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_NO; e.count = 0; setMove(e, 'death'); },
+ dead: bossDead([-56, -56, 0], [56, 56, 80]),
+ BossExplode: (g, i) => Q.THINK.BossExplode(g, i),
+ };
+
+ // ================= Jorg (m_boss31.c), first form of the final boss =================
+ DEFS.monster_jorg = {
+ name: 'Twin-Cannon Mech', health: 3000, gib_health: -2000, mass: 1000, mins: [-80, -80, 0], maxs: [80, 80, 140], gibs: 13,
+ moves: moves({
+ stand: [112, 162, 's0:jorg_idle s0x32 s19 s11:jorg_step_left s0x2 s6 s9:jorg_step_right s0x7 s-2 s-17:jorg_step_left s0 s-12 s-14:jorg_step_right', null],
+ run: [168, 181, 'r17:jorg_step_left r0x3 r12 r8 r10 r33:jorg_step_right r0x3 r9x3', null],
+ walk: [168, 181, 'w17 w0x3 w12 w8 w10 w33 w0x3 w9x3', null],
+ pain3: [87, 111, 'm-28 m-6 m-3:jorg_step_left m-9 m0:jorg_step_right m0x3 m-7 m1 m-11 m-4 m0x2 m10 m11 m0 m10 m3 m10 m7:jorg_step_left m17 m0x2 m0:jorg_step_right', 'run'],
+ pain2: [84, 86, 'm0x3', 'run'], pain1: [81, 83, 'm0x3', 'run'],
+ death: [31, 80, 'm0x48 m0:MakronToss m0:BossExplode', 'dead'],
+ attack2: [18, 30, 'c0x6 c0:jorgBFG m0x6', 'run'],
+ start_attack1: [0, 7, 'c0x8', 'attack1'],
+ attack1: [8, 13, 'c0:jorg_firebulletx6', 'reattack1'],
+ end_attack1: [14, 17, 'm0x4', 'run'],
+ }),
+ stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, jorg_idle: sound, jorg_step_left: sound, jorg_step_right: sound,
+ checkattack: bossCheckAttack(0.4, 0.2),
+ attack(g, i) { setMove(g.ents[i], Q.random(g) <= 0.75 ? 'start_attack1' : 'attack2'); },
+ attack1: (g, i) => setMove(g.ents[i], 'attack1'),
+ reattack1(g, i) {
+ const e = g.ents[i];
+ if (Q.visible(g, i, e.enemy)) setMove(e, Q.random(g) < 0.9 ? 'attack1' : 'end_attack1'); else setMove(e, 'end_attack1');
+ },
+ jorg_firebullet(g, i) {
+ const e = g.ents[i];
+ for (const ofs of [[78.5, -47.1, 96], [78.5, 46.7, 96]]) { // jorg_firebullet_left, then _right
+ const start = muzzle(e, ofs);
+ Q.monsterFireBullet(g, i, start, aimAt(g, start, enemyEye(g, e, -0.2)), 6, 4);
+ flash(g, i, 'mg', start);
+ }
+ },
+ jorgBFG(g, i) {
+ const e = g.ents[i], start = muzzle(e, [6.3, -9, 111.2]);
+ Q.fireBFG(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 300, 200);
+ flash(g, i, 'bfg', start);
+ },
+ pain(g, i, other, kick, damage) {
+ const e = g.ents[i];
+ if (e.health < e.max_health / 2) e.skinnum = 1;
+ if (debounced(g, e)) return;
+ if (damage <= 40 && Q.random(g) <= 0.6) return;
+ if (e.frame >= 0 && e.frame <= 7 && Q.random(g) <= 0.005) return;
+ if (e.frame >= 8 && e.frame <= 13 && Q.random(g) <= 0.00005) return;
+ if (e.frame >= 18 && e.frame <= 25 && Q.random(g) <= 0.005) return;
+ e.pain_debounce_time = g.ms + 3000;
+ if (g.skill === 3) return;
+ if (damage <= 50) setMove(e, 'pain1'); else if (damage <= 100) setMove(e, 'pain2'); else if (Q.random(g) <= 0.3) setMove(e, 'pain3');
+ },
+ die(g, i) { const e = g.ents[i]; e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_NO; e.count = 0; setMove(e, 'death'); },
+ dead: bossDead([-60, -60, 0], [60, 60, 72]),
+ MakronToss(g, i) { // spawn Makron 0.8 s later at Jorg's origin
+ const k = Q.spawn(g), t = g.ents[k];
+ Object.assign(t, { classname: 'makron_spawner', origin: copy3(g.ents[i].origin), think: 'MakronSpawn', nextthink: g.ms + 800 });
+ },
+ BossExplode: (g, i) => Q.THINK.BossExplode(g, i),
+ };
+ // MakronSpawn: SP_monster_makron on the spawner edict, then jump at the player (400 forward, 200 up).
+ Q.THINK.MakronSpawn = (g, i) => {
+ const origin = copy3(g.ents[i].origin), d = DEFS.monster_makron, e = g.ents[i];
+ Object.assign(e, Q.blankEdict(), {
+ classname: 'monster_makron', origin, old_origin: copy3(origin), mins: copy3(d.mins), maxs: copy3(d.maxs), movetype: 'step', solid: Q.SOLID_BBOX,
+ health: g.makronHealth, gib_health: d.gib_health, mass: d.mass, svflags: Q.SVF_MONSTER, takedamage: Q.DAMAGE_AIM, clipmask: Q.MASK_MONSTERSOLID,
+ final: true, goalentity: -1, oldenemy: -1, movetarget: -1, show_hostile: 0, pain_debounce_time: 0, skinnum: 0, pos1: [0, 0, 0], count: 0,
+ yaw_speed: 0, viewheight: 0, think: 'walkmonster_start_go', nextthink: g.ms + Q.FRAMETIME_MS, angles: [0, 0, 0], ideal_yaw: 0,
+ monsterinfo: { currentmove: 'sight', nextframe: 0, aiflags: 0, scale: 1, pausetime: 0, attack_finished: 0, attack_state: 0, lefty: 0,
+ search_time: 0, trail_time: 0, last_sighting: [0, 0, 0], saved_goal: [0, 0, 0], linkcount: 0, idle_time: 0,
+ stall_pos: null, stall_t: 0, chase_until: 0 },
+ });
+ e.max_health = e.health;
+ const mv = d.moves.sight; e.frame = mv.first + (Q.rand(g) % (mv.last - mv.first + 1));
+ const p = g.ents[1];
+ if (p.health <= 0) return;
+ let vec = sub(p.origin, e.origin);
+ e.angles[1] = Q.vectoyaw(vec); // ideal_yaw stays 0 until HuntTarget
+ vec = norm(vec);
+ e.velocity = scale(vec, 400); e.velocity[2] = 200; e.groundentity = -1;
+ Q.event(g, 'makron_spawn');
+ };
+
+ // ================= Makron (m_boss32.c), second form =================
+ const MAKRON_BLASTER = [[-3.6, -24.1, 59.5], [-1.6, -19.3, 59.5], [-0.1, -14.4, 59.5], [2.0, -7.6, 59.5], [3.4, 1.3, 59.5], [3.7, 11.1, 59.5],
+ [-0.3, 22.3, 59.5], [-6, 33, 59.5], [-9.3, 36.4, 59.5], [-7, 35, 59.5], [-2.1, 29, 59.5], [3.9, 17.3, 59.5], [6.1, 5.8, 59.5], [5.9, -4.4, 59.5],
+ [4.2, -14.1, 59.5], [2.4, -18.8, 59.5], [-1.8, -25.5, 59.5]];
+ DEFS.monster_makron = {
+ name: 'Armored Pilot', health: 3000, gib_health: -2000, mass: 500, mins: [-30, -30, 0], maxs: [30, 30, 90], gibs: 5, startMove: 'sight',
+ moves: moves({
+ stand: [414, 473, 's0x60', null],
+ run: [477, 486, 'r3:makron_step_left r12 r8x2 r8:makron_step_right r6 r12 r9 r6 r12', null],
+ walk: [477, 486, 'r3:makron_step_left r12 r8x2 r8:makron_step_right r6 r12 r9 r6 r12', null],
+ pain6: [387, 413, 'm0x15 m0:makron_popup m0x7 m0:makron_taunt m0x3', 'run'],
+ pain5: [383, 386, 'm0x4', 'run'], pain4: [379, 382, 'm0x4', 'run'],
+ death2: [251, 345, 'm-15 m3 m-12 m0:makron_step_left m0x11 m11 m12 m11:makron_step_right m0x15 m5 m7 m6:makron_step_left m0x2 m-1 m2 m0x13 m-6 m-4 m-6:makron_step_right m-4 m-4:makron_step_left m0x4 m-2 m-5 m-3:makron_step_right m-8 m-3:makron_step_left m-7 m-4 m-4:makron_step_right m-6 m-7 m0:makron_step_left m0x12 m-2 m0x2 m2 m0 m27:makron_hit m26 m0:makron_brainsplorch m0x2', 'dead'],
+ sight: [188, 200, 'm0x13', 'run'],
+ attack3: [201, 208, 'c0x3 c0:makronBFG m0x4', 'run'],
+ attack4: [209, 234, 'c0x4 m0:MakronHyperblasterx17 m0x5', 'run'],
+ attack5: [235, 250, 'c0:makron_prerailgun c0x6 c0:MakronSaveloc m0:MakronRailgun m0x7', 'run'],
+ }),
+ stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, sight: (g, i) => setMove(g.ents[i], 'sight'),
+ makron_step_left: sound, makron_step_right: sound, makron_popup: sound, makron_hit: sound, makron_brainsplorch: sound,
+ makron_taunt: (g) => { Q.random(g); }, makron_prerailgun: (g, i) => Q.fx(g, 'railcharge', g.ents[i].origin, null, { owner: i }),
+ checkattack: bossCheckAttack(0.4, 0.2),
+ attack(g, i) {
+ const r = Q.random(g), e = g.ents[i];
+ setMove(e, r <= 0.3 ? 'attack3' : r <= 0.6 ? 'attack4' : 'attack5');
+ },
+ makronBFG(g, i) {
+ const e = g.ents[i], start = muzzle(e, [17, -19.5, 62.9]);
+ Q.fireBFG(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 300, 300);
+ flash(g, i, 'bfg', start);
+ },
+ MakronSaveloc(g, i) { const e = g.ents[i], en = g.ents[e.enemy]; e.pos1 = copy3(en.origin); e.pos1[2] += en.viewheight; },
+ MakronRailgun(g, i) {
+ const e = g.ents[i], start = muzzle(e, [-17.3, 7.8, 72.4]);
+ Q.fireRail(g, i, start, norm(sub(e.pos1, start)), 50, 100);
+ flash(g, i, 'rail', start);
+ },
+ MakronHyperblaster(g, i) {
+ const e = g.ents[i], start = muzzle(e, MAKRON_BLASTER[e.frame - 213]);
+ const dir = [0, 0, 0];
+ if (e.enemy >= 0) { const v = enemyEye(g, e, 0); dir[0] = Q.vectoangles(sub(v, start))[0]; }
+ dir[1] = e.frame <= 221 ? e.angles[1] - 10 * (e.frame - 221) : e.angles[1] + 10 * (e.frame - 229);
+ Q.fireBlaster(g, i, start, Q.angleVectors(dir).forward, 15, 1000, 'blaster', false);
+ flash(g, i, 'blaster', start);
+ },
+ pain(g, i, other, kick, damage) {
+ const e = g.ents[i];
+ if (e.health < e.max_health / 2) e.skinnum = 1;
+ if (debounced(g, e)) return;
+ if (damage <= 25 && Q.random(g) < 0.2) return;
+ e.pain_debounce_time = g.ms + 3000;
+ if (g.skill === 3) return;
+ if (damage <= 40) setMove(e, 'pain4');
+ else if (damage <= 110) setMove(e, 'pain5');
+ else if (damage <= 150) { // C's dangling else: the 0.35 retry belongs to this branch, >150 gives no pain
+ if (Q.random(g) <= 0.45) setMove(e, 'pain6'); else if (Q.random(g) <= 0.35) setMove(e, 'pain6');
+ }
+ },
+ die(g, i) {
+ const e = g.ents[i];
+ if (e.deadflag === Q.DEAD_DEAD) return;
+ e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_YES; setMove(e, 'death2');
+ },
+ dead: bossDead([-60, -60, 0], [60, 60, 72]),
+ };
+
+ // ---------------- shared helpers of the three unit monsters ----------------
+ // fire_hit (g_weapon.c), the melee hit of the Gladiator and the Mutant. Kept as in the source: `dir` is not
+ // normalized before VectorMA, so the trace runs from the attacker's origin far past the enemy along that line.
+ Q.fireHit = (g, i, aim, damage, kick) => {
+ const self = g.ents[i], en = g.ents[self.enemy];
+ let dir = sub(en.origin, self.origin);
+ let range = len(dir);
+ if (range > aim[0]) return false;
+ aim = copy3(aim);
+ if (aim[1] > self.mins[0] && aim[1] < self.maxs[0]) range -= en.maxs[0]; // straight on: back up to the box edge
+ else aim[1] = aim[1] < 0 ? en.mins[0] : en.maxs[0]; // side hit: out to the box edge
+ let point = ma(self.origin, range, dir);
+ const tr = Q.trace(g, self.origin, null, null, point, i, Q.MASK_SHOT);
+ let target = tr.ent;
+ if (tr.fraction < 1) {
+ const h = g.ents[tr.ent];
+ if (!h.takedamage) return false;
+ if ((h.svflags & Q.SVF_MONSTER) || h.client) target = self.enemy; // whatever it hits, it hits the enemy
+ }
+ const av = Q.angleVectors(self.angles);
+ point = ma(ma(ma(self.origin, range, av.forward), aim[1], av.right), aim[2], av.up);
+ dir = sub(point, en.origin);
+ Q.damage(g, target, i, i, dir, point, [0, 0, 0], damage, Math.trunc(kick / 2), Q.DAMAGE_NO_KNOCKBACK, 'hit');
+ const t = g.ents[target];
+ if (!(t.svflags & Q.SVF_MONSTER) && !t.client) return false;
+ // the special knockback: from the hit point towards the middle of the enemy's absolute box
+ const mid = [Q.absmin(en)[0] + 0.5 * (en.maxs[0] - en.mins[0]), Q.absmin(en)[1] + 0.5 * (en.maxs[1] - en.mins[1]), Q.absmin(en)[2] + 0.5 * (en.maxs[2] - en.mins[2])];
+ en.velocity = ma(en.velocity, kick, norm(sub(mid, point)));
+ if (en.velocity[2] > 0) en.groundentity = -1;
+ Q.fx(g, 'slash', point, null, { owner: i });
+ return true;
+ };
+ // Regular (non-boss) death: gib below gib_health, else the death move; the corpse can still take damage.
+ function unitDie(gibs, deathMove) {
+ return (g, i, inflictor, attacker, damage) => {
+ const e = g.ents[i];
+ if (e.health <= e.gib_health) {
+ for (const [kind, n, organic] of gibs.body) for (let k = 0; k < n; k++) Q.throwGib(g, i, kind, damage, organic);
+ Q.throwHead(g, i, gibs.head[0], damage, gibs.head[1]);
+ e.deadflag = Q.DEAD_DEAD; e.gibbed = true;
+ Q.fx(g, 'gibs', Q.center(e), null, { size: 32 });
+ return;
+ }
+ if (e.deadflag === Q.DEAD_DEAD) return;
+ e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_YES;
+ setMove(e, typeof deathMove === 'function' ? deathMove(g, e) : deathMove);
+ };
+ }
+ // M_FlyCheck / M_FliesOn / M_FliesOff: flies around a corpse (an effect, with its own random draws).
+ function flyCheck(g, i) {
+ const e = g.ents[i];
+ if (Q.random(g) > 0.5) return;
+ e.think = 'M_FliesOn'; e.nextthink = g.ms + 5000 + 10000 * Q.random(g);
+ }
+ Q.THINK.M_FliesOn = (g, i) => { const e = g.ents[i]; e.flies = true; e.think = 'M_FliesOff'; e.nextthink = g.ms + 60000; };
+ Q.THINK.M_FliesOff = (g, i) => { g.ents[i].flies = false; };
+
+ // ================= Tank Commander (m_tank.c, monster_tank_commander: the Tank with 1000 health, skin 2) =================
+ const TANK_MG = [[22.9, -0.7, 25.3], [22.2, 6.2, 22.3], [19.4, 13.1, 18.6], [19.4, 18.8, 18.6], [17.9, 25.0, 18.6], [14.1, 30.5, 20.6],
+ [9.3, 35.3, 22.1], [4.7, 38.4, 22.1], [-1.1, 40.4, 24.1], [-6.5, 41.2, 24.1], [3.2, 40.1, 24.7], [11.7, 36.7, 26.0], [18.9, 31.3, 26.0],
+ [24.4, 24.4, 26.4], [27.1, 17.1, 27.2], [28.5, 9.1, 28.0], [27.1, 2.2, 28.0], [24.9, -2.8, 28.0], [21.6, -7.0, 26.4]];
+ DEFS.monster_tank_commander = {
+ name: 'Chain-Gun Heavy Trooper', health: 1000, gib_health: -225, mass: 500, mins: [-32, -32, -16], maxs: [32, 32, 72], skin: 2,
+ moves: moves({
+ stand: [0, 29, 's0x30', null],
+ start_walk: [30, 33, 'w0 w6x2 w11:tank_footstep', 'walk'],
+ walk: [34, 49, 'w4 w5 w3 w2 w5x2 w4 w4:tank_footstep w3 w5 w4 w5 w7x2 w6 w6:tank_footstep', null],
+ start_run: [30, 33, 'r0 r6x2 r11:tank_footstep', 'run'],
+ run: [34, 49, 'r4 r5 r3 r2 r5x2 r4 r4:tank_footstep r3 r5 r4 r5 r7x2 r6 r6:tank_footstep', null],
+ pain1: [197, 200, 'm0x4', 'run'], pain2: [201, 205, 'm0x5', 'run'],
+ pain3: [206, 221, 'm-7 m0x3 m2 m0x2 m3 m0 m2 m0x5 m0:tank_footstep', 'run'],
+ attack_blast: [55, 70, 'c0x4 c-1 c-2 c-1x2 c0 c0:TankBlaster c0x2 c0:TankBlaster c0x2 c0:TankBlaster', 'reattack_blaster'],
+ reattack_blast: [65, 70, 'c0x2 c0:TankBlaster c0x2 c0:TankBlaster', 'reattack_blaster'],
+ attack_post_blast: [71, 76, 'm0x2 m2 m3 m2 m-2:tank_footstep', 'run'],
+ attack_strike: [77, 114, 'm3 m2x2 m1 m6 m7 m9:tank_footstep m2 m1 m2 m2:tank_footstep m2 m0x4 m-2x2 m0:tank_windup m0x6 m0:TankStrike m0 m-1x5 m-3 m-10x2 m-2 m-3 m-2:tank_footstep', 'poststrike'],
+ attack_pre_rocket: [115, 135, 'c0x11 c1 c2 c7x2 c7:tank_footstep c0x4 c-3', 'doattack_rocket'],
+ attack_fire_rocket: [136, 144, 'c-3 c0 c0:TankRocket c0x2 c0:TankRocket c0x2 c-1:TankRocket', 'refire_rocket'],
+ attack_post_rocket: [145, 167, 'c0 c-1x2 c0 c2 c3 c4 c2 c0x3 c-9 c-8 c-7 c-1 c-1:tank_footstep c0x7', 'run'],
+ attack_chain: [168, 196, 'c0x5 n0:TankMachineGunx19 c0x5', 'run'],
+ death: [222, 253, 'm-7 m-2x2 m1 m3 m6 m1x2 m2 m0x3 m-2 m0x2 m-3 m0x6 m-4 m-6 m-4 m-5 m-7 m-15:tank_thud m-5 m0x3', 'dead'],
+ }),
+ stand, walk: (g, i) => setMove(g.ents[i], 'walk'), sight: sound,
+ tank_footstep: sound, tank_thud: sound, tank_windup: sound, TankStrike: sound,
+ // tank_run: AI_BRUTAL against a client; from walk / start_run straight into run, otherwise via start_run.
+ run(g, i) {
+ const e = g.ents[i], mi = e.monsterinfo;
+ if (e.enemy >= 0 && g.ents[e.enemy].client) mi.aiflags |= AI_BRUTAL; else mi.aiflags &= ~AI_BRUTAL;
+ if (mi.aiflags & AI_STAND_GROUND) { setMove(e, 'stand'); return; }
+ setMove(e, mi.currentmove === 'walk' || mi.currentmove === 'start_run' ? 'run' : 'start_run');
+ },
+ pain(g, i, other, kick, damage) {
+ const e = g.ents[i];
+ if (e.health < e.max_health / 2) e.skinnum |= 1;
+ if (damage <= 10) return;
+ if (debounced(g, e)) return;
+ if (damage <= 30 && Q.random(g) > 0.2) return;
+ if (g.skill >= 2 && ((e.frame >= 115 && e.frame <= 144) || (e.frame >= 55 && e.frame <= 70))) return; // not while attacking
+ e.pain_debounce_time = g.ms + 3000;
+ if (g.skill === 3) return;
+ setMove(e, damage <= 30 ? 'pain1' : damage <= 60 ? 'pain2' : 'pain3');
+ },
+ TankBlaster(g, i) {
+ const e = g.ents[i], ofs = e.frame === 64 ? [20.7, -18.5, 28.7] : e.frame === 67 ? [16.6, -21.5, 30.1] : [11.8, -23.9, 32.1];
+ const start = muzzle(e, ofs);
+ Q.fireBlaster(g, i, start, sub(enemyEye(g, e, 0), start), 30, 800, 'blaster', false);
+ flash(g, i, 'blaster', start);
+ },
+ TankRocket(g, i) {
+ const e = g.ents[i], ofs = e.frame === 138 ? [6.2, 29.1, 49.1] : e.frame === 141 ? [6.9, 23.8, 49.1] : [8.3, 17.8, 49.5];
+ const start = muzzle(e, ofs);
+ Q.monsterFireRocket(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 550);
+ flash(g, i, 'rocket', start);
+ },
+ // The chaingun sweep: pitch at the enemy's eye, yaw by frame from +40 to -32 and back to +40 degrees off the facing
+ // it had when the burst started (the 19 firing frames have no AI function, so the Tank does not turn meanwhile).
+ TankMachineGun(g, i) {
+ const e = g.ents[i], start = muzzle(e, TANK_MG[e.frame - 173]), dir = [0, 0, 0];
+ if (e.enemy >= 0) dir[0] = Q.vectoangles(sub(enemyEye(g, e, 0), start))[0];
+ dir[1] = e.frame <= 182 ? e.angles[1] - 8 * (e.frame - 178) : e.angles[1] + 8 * (e.frame - 186);
+ Q.monsterFireBullet(g, i, start, Q.angleVectors(dir).forward, 20, 4);
+ flash(g, i, 'mg', start);
+ },
+ reattack_blaster(g, i) { // skill >= 2 only: 60 % another two bolts while the enemy is visible and alive
+ const e = g.ents[i];
+ if (g.skill >= 2 && Q.visible(g, i, e.enemy) && g.ents[e.enemy].health > 0 && Q.random(g) <= 0.6) { setMove(e, 'reattack_blast'); return; }
+ setMove(e, 'attack_post_blast');
+ },
+ doattack_rocket: (g, i) => setMove(g.ents[i], 'attack_fire_rocket'),
+ refire_rocket(g, i) { // skill >= 2 only: 40 % another volley
+ const e = g.ents[i];
+ if (g.skill >= 2 && g.ents[e.enemy].health > 0 && Q.visible(g, i, e.enemy) && Q.random(g) <= 0.4) { setMove(e, 'attack_fire_rocket'); return; }
+ setMove(e, 'attack_post_rocket');
+ },
+ poststrike(g, i) { g.ents[i].enemy = -1; DEFS.monster_tank_commander.run(g, i); },
+ attack(g, i) {
+ const e = g.ents[i], mi = e.monsterinfo;
+ if (g.ents[e.enemy].health < 0) { setMove(e, 'attack_strike'); mi.aiflags &= ~AI_BRUTAL; return; }
+ const range = len(sub(g.ents[e.enemy].origin, e.origin)), r = Q.random(g);
+ if (range <= 125) setMove(e, r < 0.4 ? 'attack_chain' : 'attack_blast');
+ else if (range <= 250) setMove(e, r < 0.5 ? 'attack_chain' : 'attack_blast');
+ else if (r < 0.33) setMove(e, 'attack_chain');
+ else if (r < 0.66) { setMove(e, 'attack_pre_rocket'); e.pain_debounce_time = g.ms + 5000; } // no pain for a while
+ else setMove(e, 'attack_blast');
+ },
+ die: unitDie({ body: [['meat', 1, true], ['metal', 4, false], ['chest', 1, true]], head: ['gear', false] }, 'death'),
+ dead: bossDead([-16, -16, -16], [16, 16, 0]),
+ };
+
+ // ================= Gladiator (m_gladiator.c) =================
+ DEFS.monster_gladiator = {
+ name: 'Blade-Arm Gunner', health: 400, gib_health: -175, mass: 400, mins: [-32, -32, -24], maxs: [32, 32, 64],
+ moves: moves({
+ stand: [0, 6, 's0x7', null],
+ walk: [7, 22, 'w15 w7 w6 w5 w2 w0 w2 w8 w12 w8 w5x2 w2x2 w1 w8', null],
+ run: [23, 28, 'r23 r14x2 r21 r12 r13', null],
+ attack_melee: [29, 45, 'c0x4 c0:gladiator_cleaver_swing c0 c0:GaldiatorMelee c0x3 c0:gladiator_cleaver_swing c0x2 c0:GaldiatorMelee c0x3', 'run'],
+ attack_gun: [46, 54, 'c0x3 c0:GladiatorGun c0x5', 'run'],
+ pain: [55, 60, 'm0x6', 'run'],
+ pain_air: [83, 89, 'm0x7', 'run'],
+ death: [61, 82, 'm0x22', 'dead'],
+ }),
+ stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, sight: sound, gladiator_cleaver_swing: sound,
+ melee: (g, i) => setMove(g.ents[i], 'attack_melee'),
+ GaldiatorMelee(g, i) { Q.fireHit(g, i, [Q.MELEE_DISTANCE, g.ents[i].mins[0], -4], 20 + (Q.rand(g) % 5), 300); },
+ // gladiator_attack: nothing inside MELEE_DISTANCE + 32 (a small safe zone); otherwise the eye position is saved
+ // NOW and the railgun fires along it on the fourth frame of attack_gun (0.4 s later).
+ attack(g, i) {
+ const e = g.ents[i], en = g.ents[e.enemy];
+ if (len(sub(e.origin, en.origin)) <= Q.MELEE_DISTANCE + 32) return;
+ e.pos1 = copy3(en.origin); e.pos1[2] += en.viewheight;
+ setMove(e, 'attack_gun');
+ },
+ GladiatorGun(g, i) {
+ const e = g.ents[i], start = muzzle(e, [30.0, 18.0, 28.0]);
+ Q.fireRail(g, i, start, norm(sub(e.pos1, start)), 50, 100);
+ flash(g, i, 'rail', start);
+ },
+ pain(g, i, other, kick, damage) {
+ const e = g.ents[i];
+ if (e.health < e.max_health / 2) e.skinnum = 1;
+ if (debounced(g, e)) {
+ if (e.velocity[2] > 100 && e.monsterinfo.currentmove === 'pain') setMove(e, 'pain_air');
+ return;
+ }
+ e.pain_debounce_time = g.ms + 3000;
+ Q.random(g); // which pain sound
+ if (g.skill === 3) return;
+ setMove(e, e.velocity[2] > 100 ? 'pain_air' : 'pain');
+ },
+ die: unitDie({ body: [['bone', 2, true], ['meat', 4, true]], head: ['head', true] }, 'death'),
+ dead: bossDead([-16, -16, -24], [16, 16, -8]),
+ };
+
+ // ================= Mutant (m_mutant.c) =================
+ function mutantCheckJump(g, i) {
+ const e = g.ents[i], en = g.ents[e.enemy], esize = en.maxs[2] - en.mins[2], emin = Q.absmin(en)[2];
+ if (Q.absmin(e)[2] > emin + 0.75 * esize) return false;
+ if (Q.absmax(e)[2] < emin + 0.25 * esize) return false;
+ const d = Math.sqrt((e.origin[0] - en.origin[0]) ** 2 + (e.origin[1] - en.origin[1]) ** 2);
+ if (d < 100) return false;
+ if (d > 100 && Q.random(g) < 0.9) return false;
+ return true;
+ }
+ DEFS.monster_mutant = {
+ name: 'Clawed Pouncer', health: 300, gib_health: -120, mass: 300, mins: [-32, -32, -24], maxs: [32, 32, 48],
+ moves: moves({
+ stand: [62, 112, 's0x51', null],
+ start_walk: [126, 129, 'w5x2 w-2 w1', 'mutant_walk_loop'],
+ walk: [130, 141, 'w3 w1 w5 w10 w13 w10 w0 w5 w6 w16 w15 w6', null],
+ run: [56, 61, 'r40 r40:mutant_step r24 r5:mutant_step r17 r10', null],
+ attack: [8, 14, 'c0x2 c0:mutant_hit_left c0x2 c0:mutant_hit_right c0:mutant_check_refire', 'run'],
+ jump: [0, 7, 'c0 c17 c15:mutant_jump_takeoff c15 c15:mutant_check_landing c0 c3 c0', 'run'],
+ pain1: [34, 38, 'm4 m-3 m-8 m2 m5', 'run'], pain2: [39, 44, 'm-24 m11 m5 m-2 m6 m4', 'run'],
+ pain3: [45, 55, 'm-22 m3x2 m2 m1x2 m6 m3 m2 m0 m1', 'run'],
+ death1: [15, 23, 'm0x9', 'dead'], death2: [24, 33, 'm0x10', 'dead'],
+ }),
+ stand, walk: (g, i) => setMove(g.ents[i], 'start_walk'), mutant_walk_loop: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand,
+ sight: sound,
+ mutant_step: g => { Q.rand(g); }, // (rand() + 1) % 3 picks a footstep sound
+ melee: (g, i) => setMove(g.ents[i], 'attack'),
+ mutant_hit_left(g, i) { Q.fireHit(g, i, [Q.MELEE_DISTANCE, g.ents[i].mins[0], 8], 10 + (Q.rand(g) % 5), 100); },
+ mutant_hit_right(g, i) { Q.fireHit(g, i, [Q.MELEE_DISTANCE, g.ents[i].maxs[0], 8], 10 + (Q.rand(g) % 5), 100); },
+ mutant_check_refire(g, i) { // claw again while in melee range (and half the time anyway on skill 3)
+ const e = g.ents[i], en = e.enemy >= 0 ? g.ents[e.enemy] : null;
+ if (!en || !en.inuse || en.health <= 0) return;
+ if ((g.skill === 3 && Q.random(g) < 0.5) || Q.range(g, i, e.enemy) === Q.RANGE_MELEE) e.monsterinfo.nextframe = 8;
+ },
+ attack: (g, i) => setMove(g.ents[i], 'jump'),
+ // The leap: 600 forward and 250 up from the facing at takeoff; AI_DUCKED suppresses pain until it lands.
+ mutant_jump_takeoff(g, i) {
+ const e = g.ents[i], forward = Q.angleVectors(e.angles).forward;
+ e.origin[2] += 1;
+ e.velocity = scale(forward, 600); e.velocity[2] = 250;
+ e.groundentity = -1;
+ e.monsterinfo.aiflags |= AI_DUCKED;
+ e.monsterinfo.attack_finished = g.ms + 3000;
+ e.touch = 'mutant_jump_touch';
+ Q.event(g, 'mutant_leap');
+ },
+ mutant_check_landing(g, i) { // hold this frame until landing; after 3 s in the air jump again
+ const e = g.ents[i], mi = e.monsterinfo;
+ if (e.groundentity >= 0) { mi.attack_finished = 0; mi.aiflags &= ~AI_DUCKED; return; }
+ mi.nextframe = g.ms > mi.attack_finished ? 1 : 4;
+ },
+ checkattack(g, i) { // mutant_checkattack: melee range first, then the 10 % leap check
+ const e = g.ents[i], mi = e.monsterinfo;
+ if (e.enemy < 0 || g.ents[e.enemy].health <= 0) return false;
+ if (Q.range(g, i, e.enemy) === Q.RANGE_MELEE) { mi.attack_state = AS_MELEE; return true; }
+ if (mutantCheckJump(g, i)) { mi.attack_state = AS_MISSILE; return true; }
+ return false;
+ },
+ pain(g, i) {
+ const e = g.ents[i];
+ if (e.health < e.max_health / 2) e.skinnum = 1;
+ if (debounced(g, e)) return;
+ e.pain_debounce_time = g.ms + 3000;
+ if (g.skill === 3) return;
+ const r = Q.random(g);
+ setMove(e, r < 0.33 ? 'pain1' : r < 0.66 ? 'pain2' : 'pain3');
+ },
+ die: unitDie({ body: [['bone', 2, true], ['meat', 4, true]], head: ['head', true] }, (g, e) => { e.skinnum = 1; return Q.random(g) < 0.5 ? 'death1' : 'death2'; }),
+ dead(g, i) {
+ const e = g.ents[i];
+ e.mins = [-16, -16, -24]; e.maxs = [16, 16, -8]; e.movetype = 'toss'; e.svflags |= Q.SVF_DEADMONSTER;
+ flyCheck(g, i);
+ },
+ };
+ // mutant_jump_touch: a hit at more than 400 u/s does 40 + 10 * random() with as much knockback.
+ Q.TOUCH.mutant_jump_touch = (g, i, other, plane) => {
+ const e = g.ents[i];
+ if (e.health <= 0) { e.touch = null; return; }
+ if (other > 0 && g.ents[other].takedamage && len(e.velocity) > 400) {
+ const normal = norm(e.velocity), point = ma(e.origin, e.maxs[0], normal);
+ const damage = Math.trunc(40 + 10 * Q.random(g));
+ Q.damage(g, other, i, i, e.velocity, point, normal, damage, damage, 0, 'mutant_leap');
+ }
+ if (!checkBottom(g, i)) {
+ if (e.groundentity >= 0) { e.monsterinfo.nextframe = 1; e.touch = null; }
+ return;
+ }
+ e.touch = null;
+ };
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/quake2_remake/q2player.js b/environments/games/web/games/quake2_remake/q2player.js
new file mode 100644
index 0000000000000000000000000000000000000000..35a029bd1577602e9fc1934a3450bdbd3fd9631e
--- /dev/null
+++ b/environments/games/web/games/quake2_remake/q2player.js
@@ -0,0 +1,852 @@
+/* Quake II (1997) boss arenas - the player: client input (cl_input.c CL_BaseMove, in_win.c IN_MouseMove),
+ player movement (qcommon/pmove.c Pmove), ClientThink / ClientBeginServerFrame (p_client.c), ClientEndServerFrame
+ (p_view.c falling damage, damage feedback), weapons (p_weapon.c Weapon_Generic and the eight weapons used here),
+ projectiles and hitscan (g_weapon.c), damage (g_combat.c T_Damage / T_RadiusDamage / CheckArmor / CanDamage) and
+ items (g_items.c armor, health, ammo). Independent reimplementation from the GPL-2.0 source release, commit
+ 372afde46e7defc9dd2d719a1732b8ace1fa096e; see q2core.js. */
+(function (root) {
+ 'use strict';
+ const M = root.Quake2Game, Q = M.Q;
+ const { add, sub, scale, ma, dot, len, norm, copy3 } = Q;
+
+ // ---------------- pmove.c constants and client cvar defaults (cl_main.c) ----------------
+ const PM = { stopspeed: 100, maxspeed: 300, duckspeed: 100, accelerate: 10, airaccelerate: 0, friction: 6 };
+ const PMF_DUCKED = 1, PMF_JUMP_HELD = 2, PMF_ON_GROUND = 4, PMF_TIME_WATERJUMP = 8, PMF_TIME_LAND = 16, PMF_TIME_TELEPORT = 32;
+ const CL = { forwardspeed: 200, sidespeed: 200, upspeed: 200, yawspeed: 140, anglespeedkey: 1.5, sensitivity: 3, m_yaw: 0.022, m_pitch: 0.022 };
+ const MIN_STEP_NORMAL = 0.7, STOP_EPSILON = 0.1, MAX_CLIP_PLANES = 5;
+ Q.PM = PM; Q.CL = CL;
+ const PLAYER_MINS = [-16, -16, -24], PLAYER_MAXS = [16, 16, 32];
+
+ // ---------------- items (g_items.c itemlist order; weapnext walks down the list, weapprev up) ----------------
+ const ITEMS = {
+ blaster: { index: 7, kind: 'weapon', name: 'Energy Pistol', ammo: null, quantity: 0 },
+ shotgun: { index: 8, kind: 'weapon', name: 'Shotgun', ammo: 'shells', quantity: 1 },
+ supershotgun: { index: 9, kind: 'weapon', name: 'Double Shotgun', ammo: 'shells', quantity: 2 },
+ machinegun: { index: 10, kind: 'weapon', name: 'Machinegun', ammo: 'bullets', quantity: 1 },
+ chaingun: { index: 11, kind: 'weapon', name: 'Chaingun', ammo: 'bullets', quantity: 1 },
+ rocketlauncher: { index: 14, kind: 'weapon', name: 'Rocket Launcher', ammo: 'rockets', quantity: 1 },
+ hyperblaster: { index: 15, kind: 'weapon', name: 'Pulse Cannon', ammo: 'cells', quantity: 1 },
+ railgun: { index: 16, kind: 'weapon', name: 'Coilgun', ammo: 'slugs', quantity: 1 },
+ };
+ const WEAPON_ORDER = Object.keys(ITEMS).sort((a, b) => ITEMS[a].index - ITEMS[b].index);
+ const AMMO_MAX = { bullets: 200, shells: 100, rockets: 50, cells: 200, slugs: 50 };
+ const AMMO_PICKUP = { shells: 10, bullets: 50, cells: 50, rockets: 5, slugs: 10 };
+ // gitem_armor_t: base_count, max_count, normal_protection, energy_protection. ArmorIndex checks jacket, combat, body.
+ const ARMOR = { jacket: [25, 50, 0.30, 0.00], combat: [50, 100, 0.60, 0.30], body: [100, 200, 0.80, 0.60] };
+ const ARMOR_ORDER = ['jacket', 'combat', 'body'];
+ Q.ITEMS = ITEMS; Q.ARMOR = ARMOR; Q.AMMO_MAX = AMMO_MAX; Q.WEAPON_ORDER = WEAPON_ORDER;
+ Q.armorIndex = p => ARMOR_ORDER.find(a => p.inv[a] > 0) || null;
+
+ // ---------------- player spawn (PutClientInServer + ChangeWeapon) ----------------
+ Q.spawnPlayer = (g, spec) => {
+ const p = g.ents[1] = Q.blankEdict();
+ Object.assign(p, {
+ classname: 'player', client: true, origin: copy3(spec.origin), old_origin: copy3(spec.origin), mins: copy3(PLAYER_MINS), maxs: copy3(PLAYER_MAXS),
+ viewheight: 22, health: 100, max_health: 100, mass: 200, takedamage: Q.DAMAGE_AIM, solid: Q.SOLID_BBOX, clipmask: Q.MASK_PLAYERSOLID,
+ movetype: 'walk', pain_debounce_time: 0, air_finished: 12000,
+ viewangles: [0, spec.yaw, 0], v_angle: [0, spec.yaw, 0],
+ pm: { origin: spec.origin.map(v => Math.trunc(v * 8)), velocity: [0, 0, 0], flags: 0, time: 0 }, old_pmove: null,
+ buttons: 0, oldbuttons: 0, latched: 0, weapon_thunk: false, inv: Object.assign({}, spec.inventory),
+ weapon: null, newweapon: spec.weapon, lastweapon: null, weaponstate: 0, gunframe: 0, machinegun_shots: 0,
+ kick_angles: [0, 0, 0], kick_origin: [0, 0, 0], oldvelocity: [0, 0, 0], damage_blood: 0, damage_armor: 0, damage_knockback: 0,
+ damage_from: [0, 0, 0], damage_alpha: 0, bonus_alpha: 0, fall_value: 0, fall_time: 0, mynoise: -1, mynoise2: -1, pickup: null, pickup_time: 0, fired: 0,
+ });
+ changeWeapon(g, p);
+ };
+
+ // ---------------- client side: usercmd from held keys and the per-tick mouse delta ----------------
+ // keys: Set of held key names, pressed: newly pressed keys, mouse: [dx, dy, dz] for this tick. msec is this host
+ // frame (16 or 17 ms at 60 Hz, q2-arena@3): one usercmd per client frame, as the original client at cl_maxfps 60.
+ Q.buildUsercmd = (g, keys, pressed, mouse, msec) => {
+ const p = g.ents[1], frametime = msec / 1000, speed = keys.has('Shift');
+ // CL_AdjustAngles: keyboard turning, cl_yawspeed 140 deg/s, x1.5 with the speed key held.
+ const turn = (speed ? frametime * CL.anglespeedkey : frametime) * CL.yawspeed;
+ if (keys.has('E')) p.viewangles[1] -= turn;
+ if (keys.has('Q')) p.viewangles[1] += turn;
+ // IN_MouseMove with freelook: yaw -= m_yaw*sensitivity*dx, pitch += m_pitch*sensitivity*dy.
+ p.viewangles[1] -= CL.m_yaw * CL.sensitivity * (mouse[0] || 0);
+ p.viewangles[0] += CL.m_pitch * CL.sensitivity * (mouse[1] || 0);
+ p.viewangles[1] = ((p.viewangles[1] % 360) + 360) % 360; // client angles stay unquantized; ANGLE2SHORT wraps
+ // CL_ClampPitch (delta_angles are zero here): +-89 degrees.
+ if (p.viewangles[0] > 89) p.viewangles[0] = 89;
+ if (p.viewangles[0] < -89) p.viewangles[0] = -89;
+ const cmd = { msec, buttons: 0, angles: p.viewangles.map(Q.ANGLE2SHORT), forwardmove: 0, sidemove: 0, upmove: 0 };
+ if (keys.has('D')) cmd.sidemove += CL.sidespeed;
+ if (keys.has('A')) cmd.sidemove -= CL.sidespeed;
+ if (keys.has('Space')) cmd.upmove += CL.upspeed;
+ if (keys.has('L')) cmd.upmove -= CL.upspeed;
+ if (keys.has('W')) cmd.forwardmove += CL.forwardspeed;
+ if (keys.has('S')) cmd.forwardmove -= CL.forwardspeed;
+ if (speed) { cmd.forwardmove *= 2; cmd.sidemove *= 2; cmd.upmove *= 2; } // (in_speed ^ cl_run 0)
+ if (keys.has('J') || keys.has('LMB')) cmd.buttons |= 1; // BUTTON_ATTACK
+ // Console commands bound to keys arrive before the move: weapnext (K / RMB / wheel up), weapprev (R / wheel down).
+ const next = pressed.has('K') || pressed.has('RMB') || (mouse[2] || 0) > 0, prev = pressed.has('R') || (mouse[2] || 0) < 0;
+ if (next) Q.cmdWeapCycle(g, -1); else if (prev) Q.cmdWeapCycle(g, +1);
+ return cmd;
+ };
+ // Cmd_WeapNext_f / Cmd_WeapPrev_f walk itemlist away from the current weapon and call Use_Weapon on every owned
+ // weapon; the loop only stops when it comes back to pers.weapon (Use_Weapon sets newweapon, not weapon), so the
+ // last successful use wins: weapnext ends on the nearest higher-index weapon (wrapping), weapprev on the nearest
+ // lower one. dir -1 = weapnext, +1 = weapprev (the order the C loop visits indices).
+ Q.cmdWeapCycle = (g, dir) => {
+ const p = g.ents[1];
+ if (!p.weapon || p.health <= 0) return;
+ const cur = WEAPON_ORDER.indexOf(p.weapon), n = WEAPON_ORDER.length;
+ for (let k = 1; k < n; k++) {
+ const w = WEAPON_ORDER[(cur + dir * k + n * 2) % n];
+ if (p.inv[w]) useWeapon(g, p, w);
+ }
+ };
+ function useWeapon(g, p, w) { // Use_Weapon
+ if (w === p.weapon) return;
+ const it = ITEMS[w];
+ if (it.ammo && (!p.inv[it.ammo] || p.inv[it.ammo] < it.quantity)) return;
+ p.newweapon = w;
+ }
+ Q.useWeapon = useWeapon;
+
+ // ---------------- Pmove ----------------
+ function pmTrace(g, start, mins, maxs, end) { return Q.trace(g, start, mins, maxs, end, 1, Q.MASK_PLAYERSOLID); }
+ function clipVelocity(v, n, overbounce) {
+ const backoff = dot(v, n) * overbounce, out = [0, 0, 0];
+ for (let i = 0; i < 3; i++) { out[i] = v[i] - n[i] * backoff; if (out[i] > -STOP_EPSILON && out[i] < STOP_EPSILON) out[i] = 0; }
+ return out;
+ }
+ function stepSlideMove_(g, pm, pml) {
+ const primal = copy3(pml.velocity), planes = [];
+ let time_left = pml.frametime;
+ for (let bump = 0; bump < 4; bump++) {
+ const end = [0, 1, 2].map(i => pml.origin[i] + time_left * pml.velocity[i]);
+ const tr = pmTrace(g, pml.origin, pm.mins, pm.maxs, end);
+ if (tr.allsolid) { pml.velocity[2] = 0; return; }
+ if (tr.fraction > 0) { pml.origin = copy3(tr.endpos); planes.length = 0; }
+ if (tr.fraction === 1) break;
+ if (pm.touch.length < 32) pm.touch.push(tr.ent);
+ time_left -= time_left * tr.fraction;
+ if (planes.length >= MAX_CLIP_PLANES) { pml.velocity = [0, 0, 0]; break; }
+ planes.push(tr.normal);
+ let i;
+ for (i = 0; i < planes.length; i++) {
+ pml.velocity = clipVelocity(pml.velocity, planes[i], 1.01);
+ let j;
+ for (j = 0; j < planes.length; j++) if (j !== i && dot(pml.velocity, planes[j]) < 0) break;
+ if (j === planes.length) break;
+ }
+ if (i === planes.length) {
+ if (planes.length !== 2) { pml.velocity = [0, 0, 0]; break; }
+ const dir = Q.cross(planes[0], planes[1]); pml.velocity = scale(dir, dot(dir, pml.velocity));
+ }
+ if (dot(pml.velocity, primal) <= 0) { pml.velocity = [0, 0, 0]; break; }
+ }
+ if (pm.s.time) pml.velocity = primal;
+ }
+ function stepSlideMove(g, pm, pml) {
+ const start_o = copy3(pml.origin), start_v = copy3(pml.velocity);
+ stepSlideMove_(g, pm, pml);
+ const down_o = copy3(pml.origin), down_v = copy3(pml.velocity);
+ const up = copy3(start_o); up[2] += Q.STEPSIZE;
+ let tr = pmTrace(g, up, pm.mins, pm.maxs, up);
+ if (tr.allsolid) return; // can't step up
+ pml.origin = up; pml.velocity = copy3(start_v);
+ stepSlideMove_(g, pm, pml);
+ const down = copy3(pml.origin); down[2] -= Q.STEPSIZE;
+ tr = pmTrace(g, pml.origin, pm.mins, pm.maxs, down);
+ if (!tr.allsolid) pml.origin = copy3(tr.endpos);
+ const down_dist = (down_o[0] - start_o[0]) ** 2 + (down_o[1] - start_o[1]) ** 2;
+ const up_dist = (pml.origin[0] - start_o[0]) ** 2 + (pml.origin[1] - start_o[1]) ** 2;
+ if (down_dist > up_dist || tr.normal[2] < MIN_STEP_NORMAL) { pml.origin = down_o; pml.velocity = down_v; return; }
+ pml.velocity[2] = down_v[2];
+ }
+ function friction(pm, pml) {
+ const v = pml.velocity, speed = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
+ if (speed < 1) { v[0] = 0; v[1] = 0; return; }
+ let drop = 0;
+ // SV_Trace always reports a ground surface (CM_BoxTrace starts from nullsurface); no slick surfaces here.
+ if (pm.groundentity >= 0) { const control = speed < PM.stopspeed ? PM.stopspeed : speed; drop += control * PM.friction * pml.frametime; }
+ let newspeed = speed - drop; if (newspeed < 0) newspeed = 0; newspeed /= speed;
+ v[0] *= newspeed; v[1] *= newspeed; v[2] *= newspeed;
+ }
+ function accelerate(pml, wishdir, wishspeed, accel) {
+ const currentspeed = dot(pml.velocity, wishdir), addspeed = wishspeed - currentspeed;
+ if (addspeed <= 0) return;
+ let accelspeed = accel * pml.frametime * wishspeed; if (accelspeed > addspeed) accelspeed = addspeed;
+ for (let i = 0; i < 3; i++) pml.velocity[i] += accelspeed * wishdir[i];
+ }
+ function airMove(g, pm, pml) {
+ const fmove = pm.cmd.forwardmove, smove = pm.cmd.sidemove;
+ let wishvel = [pml.forward[0] * fmove + pml.right[0] * smove, pml.forward[1] * fmove + pml.right[1] * smove, 0];
+ let wishspeed = len(wishvel); const wishdir = norm(wishvel);
+ const maxspeed = (pm.s.flags & PMF_DUCKED) ? PM.duckspeed : PM.maxspeed;
+ if (wishspeed > maxspeed) { wishvel = scale(wishvel, maxspeed / wishspeed); wishspeed = maxspeed; }
+ if (pm.groundentity >= 0) {
+ pml.velocity[2] = 0;
+ accelerate(pml, wishdir, wishspeed, PM.accelerate);
+ pml.velocity[2] = 0; // gravity > 0
+ if (!pml.velocity[0] && !pml.velocity[1]) return;
+ stepSlideMove(g, pm, pml);
+ } else {
+ accelerate(pml, wishdir, wishspeed, 1); // pm_airaccelerate 0
+ pml.velocity[2] -= Q.SV_GRAVITY * pml.frametime;
+ stepSlideMove(g, pm, pml);
+ }
+ }
+ function catagorizePosition(g, pm, pml) {
+ const point = [pml.origin[0], pml.origin[1], pml.origin[2] - 0.25];
+ if (pml.velocity[2] > 180) { pm.s.flags &= ~PMF_ON_GROUND; pm.groundentity = -1; }
+ else {
+ const tr = pmTrace(g, pml.origin, pm.mins, pm.maxs, point);
+ pml.groundsurface = tr.fraction < 1 || tr.startsolid;
+ if (tr.normal[2] < 0.7 && !tr.startsolid) { pm.groundentity = -1; pm.s.flags &= ~PMF_ON_GROUND; }
+ else {
+ pm.groundentity = tr.ent;
+ if (pm.s.flags & PMF_TIME_WATERJUMP) { pm.s.flags &= ~(PMF_TIME_WATERJUMP | PMF_TIME_LAND | PMF_TIME_TELEPORT); pm.s.time = 0; }
+ if (!(pm.s.flags & PMF_ON_GROUND)) {
+ pm.s.flags |= PMF_ON_GROUND;
+ if (pml.velocity[2] < -200) { pm.s.flags |= PMF_TIME_LAND; pm.s.time = pml.velocity[2] < -400 ? 25 : 18; }
+ }
+ }
+ if (pm.touch.length < 32) pm.touch.push(tr.ent);
+ }
+ pm.waterlevel = 0;
+ }
+ function checkJump(pm, pml) {
+ if (pm.s.flags & PMF_TIME_LAND) return;
+ if (pm.cmd.upmove < 10) { pm.s.flags &= ~PMF_JUMP_HELD; return; }
+ if (pm.s.flags & PMF_JUMP_HELD) return;
+ if (pm.groundentity < 0) return;
+ pm.s.flags |= PMF_JUMP_HELD; pm.groundentity = -1;
+ pml.velocity[2] += 270; if (pml.velocity[2] < 270) pml.velocity[2] = 270;
+ }
+ function checkDuck(g, pm, pml) {
+ pm.mins = [-16, -16, -24]; pm.maxs = [16, 16, 32];
+ if (pm.cmd.upmove < 0 && (pm.s.flags & PMF_ON_GROUND)) pm.s.flags |= PMF_DUCKED;
+ else if (pm.s.flags & PMF_DUCKED) { const tr = pmTrace(g, pml.origin, pm.mins, [16, 16, 32], pml.origin); if (!tr.allsolid) pm.s.flags &= ~PMF_DUCKED; }
+ if (pm.s.flags & PMF_DUCKED) { pm.maxs[2] = 4; pm.viewheight = -2; } else { pm.maxs[2] = 32; pm.viewheight = 22; }
+ }
+ const goodPosition = (g, pm) => { const o = pm.s.origin.map(v => v * 0.125); return !pmTrace(g, o, pm.mins, pm.maxs, o).allsolid; };
+ function snapPosition(g, pm, pml) {
+ const JITTER = [0, 4, 1, 2, 3, 5, 6, 7], sign = [0, 0, 0];
+ pm.s.velocity = pml.velocity.map(v => Math.trunc(v * 8));
+ for (let i = 0; i < 3; i++) {
+ sign[i] = pml.origin[i] >= 0 ? 1 : -1;
+ pm.s.origin[i] = Math.trunc(pml.origin[i] * 8);
+ if (pm.s.origin[i] * 0.125 === pml.origin[i]) sign[i] = 0;
+ }
+ const base = copy3(pm.s.origin);
+ for (let j = 0; j < 8; j++) {
+ const bits = JITTER[j]; pm.s.origin = copy3(base);
+ for (let i = 0; i < 3; i++) if (bits & (1 << i)) pm.s.origin[i] += sign[i];
+ if (goodPosition(g, pm)) return;
+ }
+ pm.s.origin = copy3(pml.previous_origin);
+ }
+ function initialSnapPosition(g, pm, pml) {
+ const OFS = [0, -1, 1], base = copy3(pm.s.origin);
+ for (let z = 0; z < 3; z++) for (let y = 0; y < 3; y++) for (let x = 0; x < 3; x++) {
+ pm.s.origin = [base[0] + OFS[x], base[1] + OFS[y], base[2] + OFS[z]];
+ if (goodPosition(g, pm)) { pml.origin = pm.s.origin.map(v => v * 0.125); pml.previous_origin = copy3(pm.s.origin); return; }
+ }
+ }
+ function pmove(g, pm) {
+ pm.touch = []; pm.viewangles = [0, 0, 0]; pm.viewheight = 0; pm.groundentity = -1; pm.waterlevel = 0;
+ const pml = { origin: pm.s.origin.map(v => v * 0.125), velocity: pm.s.velocity.map(v => v * 0.125), previous_origin: copy3(pm.s.origin), frametime: pm.cmd.msec * 0.001, groundsurface: false };
+ // PM_ClampAngles (delta_angles 0)
+ pm.viewangles = pm.cmd.angles.map(Q.SHORT2ANGLE);
+ if (pm.viewangles[0] > 89 && pm.viewangles[0] < 180) pm.viewangles[0] = 89;
+ else if (pm.viewangles[0] < 271 && pm.viewangles[0] >= 180) pm.viewangles[0] = 271;
+ let av = Q.angleVectors(pm.viewangles); pml.forward = av.forward; pml.right = av.right;
+ checkDuck(g, pm, pml);
+ if (pm.snapinitial) initialSnapPosition(g, pm, pml);
+ catagorizePosition(g, pm, pml);
+ if (pm.s.time) {
+ let msec = pm.cmd.msec >> 3; if (!msec) msec = 1;
+ if (msec >= pm.s.time) { pm.s.flags &= ~(PMF_TIME_WATERJUMP | PMF_TIME_LAND | PMF_TIME_TELEPORT); pm.s.time = 0; } else pm.s.time -= msec;
+ }
+ checkJump(pm, pml);
+ friction(pm, pml);
+ const angles = copy3(pm.viewangles);
+ if (angles[0] > 180) angles[0] -= 360;
+ angles[0] /= 3;
+ av = Q.angleVectors(angles); pml.forward = av.forward; pml.right = av.right;
+ airMove(g, pm, pml);
+ catagorizePosition(g, pm, pml);
+ snapPosition(g, pm, pml);
+ }
+
+ // ---------------- ClientThink ----------------
+ Q.clientThink = (g, cmd) => {
+ const p = g.ents[1];
+ const pm = { s: { origin: p.origin.map(v => Math.trunc(v * 8)), velocity: p.velocity.map(v => Math.trunc(v * 8)), flags: p.pm.flags, time: p.pm.time }, cmd };
+ pm.snapinitial = !p.old_pmove || JSON.stringify(p.old_pmove) !== JSON.stringify(pm.s);
+ pmove(g, pm);
+ p.pm = { origin: copy3(pm.s.origin), velocity: copy3(pm.s.velocity), flags: pm.s.flags, time: pm.s.time };
+ p.old_pmove = JSON.parse(JSON.stringify(p.pm));
+ p.origin = pm.s.origin.map(v => v * 0.125); p.velocity = pm.s.velocity.map(v => v * 0.125);
+ p.mins = copy3(pm.mins); p.maxs = copy3(pm.maxs);
+ if (p.groundentity >= 0 && pm.groundentity < 0 && cmd.upmove >= 10) { Q.playerNoise(g, p.origin, 'self'); Q.event(g, 'jump'); }
+ p.viewheight = pm.viewheight; p.groundentity = pm.groundentity;
+ p.v_angle = copy3(pm.viewangles);
+ touchTriggers(g, 1);
+ const seen = new Set();
+ for (const other of pm.touch) {
+ if (other <= 0 || seen.has(other)) continue; seen.add(other);
+ const o = g.ents[other];
+ if (o && o.inuse && o.touch && Q.TOUCH[o.touch]) Q.TOUCH[o.touch](g, other, 1, null);
+ }
+ p.oldbuttons = p.buttons; p.buttons = cmd.buttons; p.latched |= p.buttons & ~p.oldbuttons;
+ if ((p.latched & 1) && !p.weapon_thunk) { p.weapon_thunk = true; thinkWeapon(g); }
+ };
+ function touchTriggers(g, i) { // G_TouchTriggers for the player: item triggers overlapping the absolute box
+ const e = g.ents[i];
+ for (let k = 1; k < g.ents.length; k++) {
+ const t = g.ents[k];
+ if (!t.inuse || t.solid !== Q.SOLID_TRIGGER || !t.touch) continue;
+ if (Q.boxesOverlap(e, t)) Q.TOUCH[t.touch](g, k, i, null);
+ if (!e.inuse) return;
+ }
+ }
+
+ // ---------------- ClientBeginServerFrame / ClientEndServerFrame ----------------
+ Q.clientBeginServerFrame = g => {
+ const p = g.ents[1];
+ if (!p.weapon_thunk) thinkWeapon(g); else p.weapon_thunk = false;
+ if (p.deadflag) return;
+ if (!Q.visiblePoint(g, 1, Q.trailLastSpot(g).origin)) Q.playerTrailAdd(g, p.old_origin);
+ p.latched = 0;
+ };
+ Q.clientEndServerFrame = g => {
+ const p = g.ents[1];
+ fallingDamage(g, p);
+ damageFeedback(g, p);
+ // SV_CalcBlend drops the flashes after P_DamageFeedback added to them.
+ p.damage_alpha = Math.max(0, p.damage_alpha - 0.06); p.bonus_alpha = Math.max(0, p.bonus_alpha - 0.1);
+ p.oldvelocity = copy3(p.velocity);
+ p.kick_origin = [0, 0, 0]; p.kick_angles = [0, 0, 0];
+ };
+ function fallingDamage(g, p) { // P_FallingDamage
+ let delta;
+ if (p.oldvelocity[2] < 0 && p.velocity[2] > p.oldvelocity[2] && p.groundentity < 0) delta = p.oldvelocity[2];
+ else { if (p.groundentity < 0) return; delta = p.velocity[2] - p.oldvelocity[2]; }
+ delta = delta * delta * 0.0001;
+ if (delta < 15) return;
+ p.fall_value = Math.min(40, delta * 0.5); p.fall_time = g.ms + 300;
+ if (delta > 30) {
+ p.pain_debounce_time = g.ms;
+ let damage = Math.trunc((delta - 30) / 2); if (damage < 1) damage = 1;
+ Q.damage(g, 1, 0, 0, [0, 0, 1], p.origin, [0, 0, 0], damage, 0, 0, 'falling');
+ }
+ }
+ function damageFeedback(g, p) { // P_DamageFeedback: screen flash, and one rand() for the pain sound
+ let count = p.damage_blood + p.damage_armor;
+ if (!count) return;
+ if (count < 10) count = 10; // always make a visible effect
+ if (g.ms > p.pain_debounce_time) { Q.rand(g); p.pain_debounce_time = g.ms + 700; }
+ if (p.damage_alpha < 0) p.damage_alpha = 0;
+ p.damage_alpha = Math.min(0.6, Math.max(0.2, p.damage_alpha + count * 0.01));
+ p.damage_from_dir = sub(p.damage_from, p.origin);
+ p.damage_blood = 0; p.damage_armor = 0; p.damage_knockback = 0;
+ }
+ // PlayerNoise: the first call spawns the two player noise edicts (they hold slots in the edict list). Weapon
+ // and self noise (firing, jumping) go to mynoise / level.sound_entity, impact noise to mynoise2 / sound2_entity.
+ Q.playerNoise = (g, where, type) => {
+ const p = g.ents[1];
+ if (p.mynoise < 0) {
+ for (const k of ['mynoise', 'mynoise2']) { p[k] = Q.spawn(g); Object.assign(g.ents[p[k]], { classname: 'player_noise', svflags: Q.SVF_NOCLIENT, owner: 1, mins: [-8, -8, -8], maxs: [8, 8, 8], solid: Q.SOLID_NOT }); }
+ }
+ const n = type === 'impact' ? p.mynoise2 : p.mynoise;
+ if (type === 'impact') { g.sound2_entity = n; g.sound2_entity_framenum = g.framenum; } else { g.sound_entity = n; g.sound_entity_framenum = g.framenum; }
+ g.ents[n].origin = copy3(where || p.origin); g.ents[n].teleport_time = g.ms;
+ };
+
+ // ---------------- weapons ----------------
+ const READY = 0, ACTIVATING = 1, DROPPING = 2, FIRING = 3;
+ // Weapon_Generic(FRAME_ACTIVATE_LAST, FRAME_FIRE_LAST, FRAME_IDLE_LAST, FRAME_DEACTIVATE_LAST, pause, fire)
+ const WDEF = {
+ blaster: { frames: [4, 8, 52, 55], pause: [19, 32], fire: [5], fn: 'blaster' },
+ shotgun: { frames: [7, 18, 36, 39], pause: [22, 28, 34], fire: [8, 9], fn: 'shotgun' },
+ supershotgun: { frames: [6, 17, 57, 61], pause: [29, 42, 57], fire: [7], fn: 'supershotgun' },
+ machinegun: { frames: [3, 5, 45, 49], pause: [23, 45], fire: [4, 5], fn: 'machinegun' },
+ chaingun: { frames: [4, 31, 61, 64], pause: [38, 43, 51, 61], fire: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21], fn: 'chaingun' },
+ rocketlauncher: { frames: [4, 12, 50, 54], pause: [25, 33, 42, 50], fire: [5], fn: 'rocket' },
+ hyperblaster: { frames: [5, 20, 49, 53], pause: [], fire: [6, 7, 8, 9, 10, 11], fn: 'hyperblaster' },
+ railgun: { frames: [3, 18, 56, 61], pause: [56], fire: [4], fn: 'railgun' },
+ };
+ Q.WDEF = WDEF;
+ function changeWeapon(g, p) {
+ p.lastweapon = p.weapon; p.weapon = p.newweapon; p.newweapon = null; p.machinegun_shots = 0;
+ if (!p.weapon) return;
+ p.weaponstate = ACTIVATING; p.gunframe = 0;
+ }
+ function noAmmoWeaponChange(g, p) {
+ const has = (w, ammo, n = 1) => p.inv[w] && p.inv[ammo] >= n;
+ p.newweapon = has('railgun', 'slugs') ? 'railgun' : has('hyperblaster', 'cells') ? 'hyperblaster' : has('chaingun', 'bullets') ? 'chaingun'
+ : has('machinegun', 'bullets') ? 'machinegun' : has('supershotgun', 'shells', 2) ? 'supershotgun' : has('shotgun', 'shells') ? 'shotgun' : 'blaster';
+ }
+ function thinkWeapon(g) {
+ const p = g.ents[1];
+ if (p.health < 1) { p.newweapon = null; changeWeapon(g, p); }
+ if (p.weapon) weaponGeneric(g, p, WDEF[p.weapon]);
+ }
+ function weaponGeneric(g, p, w) {
+ const [ACT_LAST, FIRE_LAST, IDLE_LAST, DEACT_LAST] = w.frames;
+ const FIRE_FIRST = ACT_LAST + 1, IDLE_FIRST = FIRE_LAST + 1, DEACT_FIRST = IDLE_LAST + 1;
+ if (p.deadflag) return;
+ if (p.weaponstate === DROPPING) { if (p.gunframe === DEACT_LAST) { changeWeapon(g, p); return; } p.gunframe++; return; }
+ if (p.weaponstate === ACTIVATING) { if (p.gunframe === ACT_LAST) { p.weaponstate = READY; p.gunframe = IDLE_FIRST; return; } p.gunframe++; return; }
+ if (p.newweapon && p.weaponstate !== FIRING) { p.weaponstate = DROPPING; p.gunframe = DEACT_FIRST; return; }
+ if (p.weaponstate === READY) {
+ if ((p.latched | p.buttons) & 1) {
+ p.latched &= ~1;
+ const it = ITEMS[p.weapon];
+ if (!it.ammo || p.inv[it.ammo] >= it.quantity) { p.gunframe = FIRE_FIRST; p.weaponstate = FIRING; }
+ else { if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); }
+ } else {
+ if (p.gunframe === IDLE_LAST) { p.gunframe = IDLE_FIRST; return; }
+ for (const f of w.pause) if (p.gunframe === f && (Q.rand(g) & 15)) return;
+ p.gunframe++; return;
+ }
+ }
+ if (p.weaponstate === FIRING) {
+ let fired = false;
+ for (const f of w.fire) if (p.gunframe === f) { FIRE[w.fn](g, p); fired = true; break; }
+ if (!fired) p.gunframe++;
+ if (p.gunframe === IDLE_FIRST + 1) p.weaponstate = READY;
+ }
+ }
+ // P_ProjectSource (right handed), from the eye height.
+ const projectSource = (p, offset, forward, right) => Q.projectSource(p.origin, offset, forward, right);
+ const FIRE = {
+ blaster(g, p) { blasterFire(g, p, [0, 0, 0], 10, false, 'blaster'); p.gunframe++; },
+ hyperblaster(g, p) {
+ if (!(p.buttons & 1)) p.gunframe++;
+ else {
+ if (!p.inv.cells) { if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); }
+ else {
+ const rotation = (p.gunframe - 5) * 2 * Math.PI / 6;
+ blasterFire(g, p, [-4 * Q.sin(rotation), 0, 4 * Q.cos(rotation)], 20, true, 'hyperblaster');
+ p.inv.cells--;
+ }
+ p.gunframe++;
+ if (p.gunframe === 12 && p.inv.cells) p.gunframe = 6;
+ }
+ },
+ machinegun(g, p) {
+ if (!(p.buttons & 1)) { p.machinegun_shots = 0; p.gunframe++; return; }
+ p.gunframe = p.gunframe === 5 ? 4 : 5;
+ if (p.inv.bullets < 1) { p.gunframe = 6; if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); return; }
+ for (let i = 1; i < 3; i++) { p.kick_origin[i] = Q.crandom(g) * 0.35; p.kick_angles[i] = Q.crandom(g) * 0.7; }
+ p.kick_origin[0] = Q.crandom(g) * 0.35; p.kick_angles[0] = p.machinegun_shots * -1.5;
+ p.machinegun_shots = Math.min(9, p.machinegun_shots + 1);
+ const av = Q.angleVectors(add(p.v_angle, p.kick_angles));
+ const start = projectSource(p, [0, 8, p.viewheight - 8], av.forward, av.right);
+ Q.fireBullet(g, 1, start, av.forward, 8, 2, 300, 500, 'machinegun');
+ Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'machinegun'); p.inv.bullets--;
+ },
+ chaingun(g, p) {
+ if (p.gunframe === 14 && !(p.buttons & 1)) { p.gunframe = 32; return; }
+ else if (p.gunframe === 21 && (p.buttons & 1) && p.inv.bullets) p.gunframe = 15;
+ else p.gunframe++;
+ let shots = p.gunframe <= 9 ? 1 : p.gunframe <= 14 ? ((p.buttons & 1) ? 2 : 1) : 3;
+ if (p.inv.bullets < shots) shots = p.inv.bullets;
+ if (!shots) { if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); return; }
+ for (let i = 0; i < 3; i++) { p.kick_origin[i] = Q.crandom(g) * 0.35; p.kick_angles[i] = Q.crandom(g) * 0.7; }
+ for (let i = 0; i < shots; i++) {
+ const av = Q.angleVectors(p.v_angle), r = 7 + Q.crandom(g) * 4, u = Q.crandom(g) * 4;
+ const start = projectSource(p, [0, r, u + p.viewheight - 8], av.forward, av.right);
+ Q.fireBullet(g, 1, start, av.forward, 8, 2, 300, 500, 'chaingun');
+ }
+ Q.playerNoise(g, p.origin, 'weapon'); muzzle(g, p, 'chaingun'); p.inv.bullets -= shots;
+ },
+ shotgun(g, p) {
+ if (p.gunframe === 9) { p.gunframe++; return; }
+ const av = Q.angleVectors(p.v_angle);
+ p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -2;
+ const start = projectSource(p, [0, 8, p.viewheight - 8], av.forward, av.right);
+ Q.fireShotgun(g, 1, start, av.forward, 4, 8, 500, 500, 12, 'shotgun');
+ p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'shotgun'); p.inv.shells--;
+ },
+ supershotgun(g, p) {
+ const av = Q.angleVectors(p.v_angle);
+ p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -2;
+ const start = projectSource(p, [0, 8, p.viewheight - 8], av.forward, av.right);
+ let f = Q.angleVectors([p.v_angle[0], p.v_angle[1] - 5, p.v_angle[2]]).forward;
+ Q.fireShotgun(g, 1, start, f, 6, 12, 1000, 500, 10, 'sshotgun');
+ f = Q.angleVectors([p.v_angle[0], p.v_angle[1] + 5, p.v_angle[2]]).forward;
+ Q.fireShotgun(g, 1, start, f, 6, 12, 1000, 500, 10, 'sshotgun');
+ p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'supershotgun'); p.inv.shells -= 2;
+ },
+ rocket(g, p) {
+ const damage = 100 + Math.trunc(Q.random(g) * 20.0);
+ const av = Q.angleVectors(p.v_angle);
+ p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -1;
+ const start = projectSource(p, [8, 8, p.viewheight - 8], av.forward, av.right);
+ Q.fireRocket(g, 1, start, av.forward, damage, 650, 120, 120);
+ p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'rocketlauncher'); p.inv.rockets--;
+ },
+ railgun(g, p) {
+ const av = Q.angleVectors(p.v_angle);
+ p.kick_origin = scale(av.forward, -3); p.kick_angles[0] = -3;
+ const start = projectSource(p, [0, 7, p.viewheight - 8], av.forward, av.right);
+ Q.fireRail(g, 1, start, av.forward, 150, 250);
+ p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'railgun'); p.inv.slugs--;
+ },
+ };
+ function blasterFire(g, p, g_offset, damage, hyper, effect) {
+ const av = Q.angleVectors(p.v_angle);
+ const start = projectSource(p, add([24, 8, p.viewheight - 8], g_offset), av.forward, av.right);
+ p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -1;
+ Q.fireBlaster(g, 1, start, av.forward, damage, 1000, effect, hyper);
+ Q.playerNoise(g, start, 'weapon'); muzzle(g, p, hyper ? 'hyperblaster' : 'blaster');
+ }
+ function muzzle(g, p, weapon) { p.fired = g.ms; p.firedWeapon = weapon; }
+
+ // ---------------- hitscan and projectiles (g_weapon.c) ----------------
+ // check_dodge: skill 0 skips three out of four checks; no monster here has a dodge function.
+ function checkDodge(g, self) { if (g.skill === 0 && Q.random(g) > 0.25) return; }
+ function fireLead(g, self, start, aimdir, damage, kick, hspread, vspread, mod) {
+ const se = g.ents[self];
+ let tr = Q.trace(g, se.origin, null, null, start, self, Q.MASK_SHOT);
+ let end = null;
+ if (!(tr.fraction < 1.0)) {
+ const av = Q.angleVectors(Q.vectoangles(aimdir));
+ const r = Q.crandom(g) * hspread, u = Q.crandom(g) * vspread;
+ end = ma(ma(ma(start, 8192, av.forward), r, av.right), u, av.up);
+ tr = Q.trace(g, start, null, null, end, self, Q.MASK_SHOT);
+ }
+ if (tr.fraction < 1.0 && !tr.sky) {
+ const hit = g.ents[tr.ent];
+ if (tr.ent > 0 && hit.takedamage) Q.damage(g, tr.ent, self, self, aimdir, tr.endpos, tr.normal, damage, kick, Q.DAMAGE_BULLET, mod);
+ else { Q.fx(g, 'puff', tr.endpos, tr.normal); if (g.ents[self].client) Q.playerNoise(g, tr.endpos, 'impact'); }
+ }
+ Q.fx(g, 'tracer', start, null, { to: tr.endpos, from: self === 1 ? 'player' : 'monster' });
+ }
+ Q.fireBullet = (g, self, start, aimdir, damage, kick, hspread, vspread, mod) => fireLead(g, self, start, aimdir, damage, kick, hspread, vspread, mod);
+ Q.fireShotgun = (g, self, start, aimdir, damage, kick, hspread, vspread, count, mod) => { for (let i = 0; i < count; i++) fireLead(g, self, start, aimdir, damage, kick, hspread, vspread, mod); };
+ Q.fireBlaster = (g, self, start, dir, damage, speed, effect, hyper) => {
+ dir = norm(dir);
+ const i = Q.spawn(g), b = g.ents[i];
+ Object.assign(b, { classname: 'bolt', svflags: Q.SVF_DEADMONSTER, origin: copy3(start), old_origin: copy3(start), angles: Q.vectoangles(dir), velocity: scale(dir, speed),
+ movetype: 'flymissile', clipmask: Q.MASK_SHOT, solid: Q.SOLID_BBOX, effect, owner: self, touch: 'blaster_touch', nextthink: g.ms + 2000, think: 'G_FreeEdict', dmg: damage, spawnflags: hyper ? 1 : 0 });
+ if (g.ents[self].client) checkDodge(g, self);
+ const tr = Q.trace(g, g.ents[self].origin, null, null, b.origin, i, Q.MASK_SHOT);
+ if (tr.fraction < 1.0) { b.origin = ma(b.origin, -10, dir); Q.TOUCH.blaster_touch(g, i, tr.ent, null); }
+ };
+ Q.TOUCH.blaster_touch = (g, i, other, plane, sky) => {
+ const b = g.ents[i];
+ if (other === b.owner) return;
+ if (sky) { Q.freeEdict(g, i); return; }
+ if (g.ents[b.owner] && g.ents[b.owner].client) Q.playerNoise(g, b.origin, 'impact');
+ const o = g.ents[other];
+ if (other > 0 && o.takedamage) Q.damage(g, other, i, b.owner, b.velocity, b.origin, plane || [0, 0, 0], b.dmg, 1, Q.DAMAGE_ENERGY, b.spawnflags & 1 ? 'hyperblaster' : 'blaster');
+ else Q.fx(g, 'blasterhit', b.origin, plane);
+ Q.freeEdict(g, i);
+ };
+ Q.fireRocket = (g, self, start, dir, damage, speed, damage_radius, radius_damage) => {
+ const i = Q.spawn(g), r = g.ents[i];
+ Object.assign(r, { classname: 'rocket', origin: copy3(start), old_origin: copy3(start), movedir: copy3(dir), angles: Q.vectoangles(dir), velocity: scale(dir, speed),
+ movetype: 'flymissile', clipmask: Q.MASK_SHOT, solid: Q.SOLID_BBOX, effect: 'rocket', owner: self, touch: 'rocket_touch', nextthink: g.ms + 8000000 / speed, think: 'G_FreeEdict',
+ dmg: damage, radius_dmg: radius_damage, dmg_radius: damage_radius });
+ if (g.ents[self].client) checkDodge(g, self);
+ };
+ Q.TOUCH.rocket_touch = (g, i, other, plane, sky) => {
+ const r = g.ents[i];
+ if (other === r.owner) return;
+ if (sky) { Q.freeEdict(g, i); return; }
+ if (g.ents[r.owner] && g.ents[r.owner].client) Q.playerNoise(g, r.origin, 'impact');
+ const o = g.ents[other];
+ if (other > 0 && o.takedamage) Q.damage(g, other, i, r.owner, r.velocity, r.origin, plane || [0, 0, 0], r.dmg, 0, 0, 'rocket');
+ else if (other === 0) { let n = Q.rand(g) % 5; while (n--) Q.throwDebris(g, i, 2, r.origin); } // single player only
+ Q.radiusDamage(g, i, r.owner, r.radius_dmg, other, r.dmg_radius, 'r_splash');
+ Q.fx(g, 'explosion', ma(r.origin, -0.02, r.velocity), null, { big: r.dmg > 60 });
+ Q.freeEdict(g, i);
+ };
+ Q.fireRail = (g, self, start, aimdir, damage, kick) => {
+ const end = ma(start, 8192, aimdir);
+ let from = copy3(start), ignore = self, tr = null;
+ const mask = Q.MASK_SHOT;
+ let guard = 0;
+ while (ignore >= 0 && guard++ < 16) {
+ tr = Q.trace(g, from, null, null, end, ignore, mask);
+ const hit = g.ents[tr.ent];
+ if (tr.ent > 0 && (hit.svflags & Q.SVF_MONSTER || hit.client)) ignore = tr.ent; else ignore = -1;
+ if (tr.ent !== self && tr.ent > 0 && hit.takedamage) Q.damage(g, tr.ent, self, self, aimdir, tr.endpos, tr.normal, damage, kick, 0, 'railgun');
+ from = copy3(tr.endpos);
+ if (tr.fraction === 1) break;
+ }
+ if (g.ents[self].client) Q.playerNoise(g, tr.endpos, 'impact');
+ Q.fx(g, 'rail', start, null, { to: tr.endpos, from: self === 1 ? 'player' : 'monster' });
+ };
+ Q.fireBFG = (g, self, start, dir, damage, speed, damage_radius) => {
+ const i = Q.spawn(g), b = g.ents[i];
+ Object.assign(b, { classname: 'bfg blast', origin: copy3(start), old_origin: copy3(start), movedir: copy3(dir), angles: Q.vectoangles(dir), velocity: scale(dir, speed),
+ movetype: 'flymissile', clipmask: Q.MASK_SHOT, solid: Q.SOLID_BBOX, effect: 'bfg', owner: self, touch: 'bfg_touch', radius_dmg: damage, dmg_radius: damage_radius,
+ think: 'bfg_think', nextthink: g.ms + Q.FRAMETIME_MS, lasers: [] });
+ if (g.ents[self].client) checkDodge(g, self);
+ };
+ Q.TOUCH.bfg_touch = (g, i, other, plane, sky) => {
+ const b = g.ents[i];
+ if (other === b.owner) return;
+ if (sky) { Q.freeEdict(g, i); return; }
+ const o = g.ents[other];
+ if (other > 0 && o.takedamage) Q.damage(g, other, i, b.owner, b.velocity, b.origin, plane || [0, 0, 0], 200, 0, 0, 'bfg_blast');
+ Q.radiusDamage(g, i, b.owner, 200, other, 100, 'bfg_blast');
+ b.solid = Q.SOLID_NOT; b.touch = null;
+ b.origin = ma(b.origin, -0.1, b.velocity); b.velocity = [0, 0, 0];
+ b.effect = 'bfgexplode'; b.frame = 0; b.think = 'bfg_explode'; b.nextthink = g.ms + Q.FRAMETIME_MS; b.enemy = other; b.lasers = [];
+ Q.fx(g, 'bfgblast', b.origin);
+ };
+ Q.THINK.bfg_explode = (g, i) => {
+ const b = g.ents[i];
+ if (b.frame === 0) {
+ for (const k of Q.findradius(g, b.origin, b.dmg_radius)) {
+ const e = g.ents[k];
+ if (!e.takedamage || k === b.owner) continue;
+ if (!Q.canDamage(g, k, i) || !Q.canDamage(g, k, b.owner)) continue;
+ const dist = len(sub(b.origin, Q.center(e)));
+ const points = b.radius_dmg * (1.0 - Math.sqrt(dist / b.dmg_radius));
+ Q.damage(g, k, i, b.owner, b.velocity, e.origin, [0, 0, 0], Math.trunc(points), 0, Q.DAMAGE_ENERGY, 'bfg_effect');
+ }
+ }
+ b.nextthink = g.ms + Q.FRAMETIME_MS; b.frame++;
+ if (b.frame === 5) b.think = 'G_FreeEdict';
+ };
+ Q.THINK.bfg_think = (g, i) => {
+ const b = g.ents[i], dmg = 10;
+ b.lasers = [];
+ for (const k of Q.findradius(g, b.origin, 256)) {
+ const e = g.ents[k];
+ if (k === i || k === b.owner || !e.takedamage) continue;
+ if (!(e.svflags & Q.SVF_MONSTER) && !e.client) continue;
+ const point = Q.center(e), dir = norm(sub(point, b.origin));
+ let ignore = i, start = copy3(b.origin), end = ma(start, 2048, dir), tr = null, guard = 0;
+ while (guard++ < 8) {
+ tr = Q.trace(g, start, null, null, end, ignore, Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_DEADMONSTER);
+ if (tr.fraction === 1 && tr.ent === 0) break;
+ const h = g.ents[tr.ent];
+ if (tr.ent > 0 && h.takedamage && !(h.flags & Q.FL_IMMUNE_LASER) && tr.ent !== b.owner) Q.damage(g, tr.ent, i, b.owner, dir, tr.endpos, [0, 0, 0], dmg, 1, Q.DAMAGE_ENERGY, 'bfg_laser');
+ if (tr.ent <= 0 || (!(h.svflags & Q.SVF_MONSTER) && !h.client)) break;
+ ignore = tr.ent; start = copy3(tr.endpos);
+ }
+ b.lasers.push(tr.endpos);
+ }
+ b.nextthink = g.ms + Q.FRAMETIME_MS;
+ };
+ // SV_Physics_Toss for MOVETYPE_FLYMISSILE (no gravity), MOVETYPE_TOSS and MOVETYPE_BOUNCE (gibs, debris).
+ Q.physicsToss = (g, i) => {
+ Q.runThink(g, i);
+ let e = g.ents[i];
+ if (!e.inuse) return;
+ if (e.velocity[2] > 0) e.groundentity = -1;
+ if (e.groundentity >= 0) return;
+ for (let k = 0; k < 3; k++) e.velocity[k] = Math.max(-Q.SV_MAXVELOCITY, Math.min(Q.SV_MAXVELOCITY, e.velocity[k]));
+ const ft = g.dt; // 60 Hz host frame (q2-arena@3)
+ if (e.movetype !== 'flymissile') e.velocity[2] -= e.gravity * Q.SV_GRAVITY * ft;
+ e.angles = add(e.angles, scale(e.avelocity, ft));
+ const move = scale(e.velocity, ft);
+ const start = copy3(e.origin), end = add(start, move);
+ for (let retry = 0; retry < 2; retry++) {
+ const tr = Q.trace(g, start, e.mins, e.maxs, end, i, e.clipmask || Q.MASK_SOLID);
+ e.origin = copy3(tr.endpos);
+ if (tr.fraction !== 1.0) {
+ impact(g, i, tr);
+ if (!g.ents[i].inuse) return;
+ e = g.ents[i];
+ if (tr.ent > 0 && !g.ents[tr.ent].inuse) { e.origin = copy3(start); continue; }
+ e.velocity = clipVelocity(e.velocity, tr.normal, e.movetype === 'bounce' ? 1.5 : 1);
+ if (tr.normal[2] > 0.7 && (e.velocity[2] < 60 || e.movetype !== 'bounce')) { e.groundentity = tr.ent; e.velocity = [0, 0, 0]; e.avelocity = [0, 0, 0]; }
+ }
+ break;
+ }
+ };
+ // g_misc.c ThrowGib / ThrowHead / ThrowDebris: real edicts (they hold slots and draw the same rand() calls).
+ function velocityForDamage(g, damage) {
+ const v = [100.0 * Q.crandom(g), 100.0 * Q.crandom(g), 200.0 + 100.0 * Q.random(g)];
+ return scale(v, damage < 50 ? 0.7 : 1.2);
+ }
+ const clipGibVelocity = v => [Math.max(-300, Math.min(300, v[0])), Math.max(-300, Math.min(300, v[1])), Math.max(200, Math.min(500, v[2]))];
+ Q.throwGib = (g, self, kind, damage, organic) => {
+ const s = g.ents[self], size = scale(sub(s.maxs, s.mins), 0.5), base = add(Q.absmin(s), size);
+ const i = Q.spawn(g), e = g.ents[i];
+ e.classname = 'gib'; e.gib = kind;
+ e.origin = [base[0] + Q.crandom(g) * size[0], base[1] + Q.crandom(g) * size[1], base[2] + Q.crandom(g) * size[2]];
+ e.old_origin = copy3(e.origin);
+ Object.assign(e, { solid: Q.SOLID_NOT, flags: Q.FL_NO_KNOCKBACK, takedamage: Q.DAMAGE_YES, movetype: organic ? 'toss' : 'bounce', touch: organic ? 'gib_touch' : null });
+ e.velocity = clipGibVelocity(ma(s.velocity, organic ? 0.5 : 1.0, velocityForDamage(g, damage)));
+ e.avelocity = [Q.random(g) * 600, Q.random(g) * 600, Q.random(g) * 600];
+ e.think = 'G_FreeEdict'; e.nextthink = g.ms + 10000 + Q.random(g) * 10000;
+ };
+ Q.throwHead = (g, self, kind, damage, organic) => {
+ const e = g.ents[self];
+ Object.assign(e, { skinnum: 0, frame: 0, mins: [0, 0, 0], maxs: [0, 0, 0], solid: Q.SOLID_NOT, flags: e.flags | Q.FL_NO_KNOCKBACK, takedamage: Q.DAMAGE_YES,
+ movetype: organic ? 'toss' : 'bounce', touch: organic ? 'gib_touch' : null, classname: 'gib', gib: kind, head: true });
+ e.svflags &= ~Q.SVF_MONSTER;
+ e.velocity = clipGibVelocity(ma(e.velocity, organic ? 0.5 : 1.0, velocityForDamage(g, damage)));
+ e.avelocity = [0, Q.crandom(g) * 600, 0];
+ e.think = 'G_FreeEdict'; e.nextthink = g.ms + 10000 + Q.random(g) * 10000;
+ };
+ Q.TOUCH.gib_touch = (g, i) => { const e = g.ents[i]; if (e.groundentity < 0) return; e.touch = null; };
+ Q.throwDebris = (g, self, speed, origin) => {
+ const s = g.ents[self], i = Q.spawn(g), e = g.ents[i];
+ const v = [100 * Q.crandom(g), 100 * Q.crandom(g), 100 + 100 * Q.crandom(g)];
+ Object.assign(e, { classname: 'debris', origin: copy3(origin), old_origin: copy3(origin), velocity: ma(s.velocity, speed, v), movetype: 'bounce', solid: Q.SOLID_NOT, takedamage: Q.DAMAGE_YES });
+ e.avelocity = [Q.random(g) * 600, Q.random(g) * 600, Q.random(g) * 600];
+ e.think = 'G_FreeEdict'; e.nextthink = g.ms + 5000 + Q.random(g) * 5000; e.flags = 0;
+ };
+ function impact(g, i, tr) { // SV_Impact
+ const e1 = g.ents[i], e2 = g.ents[tr.ent];
+ if (e1.touch && e1.solid !== Q.SOLID_NOT) Q.TOUCH[e1.touch](g, i, tr.ent, tr.normal, tr.sky);
+ if (tr.ent > 0 && e2.inuse && e2.touch && e2.solid !== Q.SOLID_NOT && g.ents[i].inuse) Q.TOUCH[e2.touch](g, tr.ent, i, null, false);
+ }
+ Q.impact = impact;
+
+ // ---------------- damage (g_combat.c) ----------------
+ Q.canDamage = (g, targ, inflictor) => {
+ const t = g.ents[targ], from = g.ents[inflictor].origin;
+ const test = d => Q.trace(g, from, null, null, d, inflictor, Q.MASK_SOLID).fraction === 1.0;
+ if (test(t.origin)) return true;
+ for (const [dx, dy] of [[15, 15], [15, -15], [-15, 15], [-15, -15]]) if (test([t.origin[0] + dx, t.origin[1] + dy, t.origin[2]])) return true;
+ return false;
+ };
+ function checkArmor(g, ent, damage, dflags) {
+ if (!damage || !ent.client || (dflags & Q.DAMAGE_NO_ARMOR)) return 0;
+ const a = Q.armorIndex(ent);
+ if (!a) return 0;
+ let save = Math.ceil(((dflags & Q.DAMAGE_ENERGY) ? ARMOR[a][3] : ARMOR[a][2]) * damage);
+ if (save >= ent.inv[a]) save = ent.inv[a];
+ if (!save) return 0;
+ ent.inv[a] -= save;
+ return save;
+ }
+ Q.damage = (g, targ, inflictor, attacker, dir, point, normal, damage, knockback, dflags, mod) => {
+ const t = g.ents[targ];
+ if (!t.takedamage) return;
+ if (g.skill === 0 && t.client) { damage = Math.trunc(damage * 0.5); if (!damage) damage = 1; } // easy mode takes half damage
+ dir = norm(dir);
+ const a = g.ents[attacker];
+ if (!(dflags & Q.DAMAGE_RADIUS) && (t.svflags & Q.SVF_MONSTER) && a && a.client && t.enemy < 0 && t.health > 0) damage *= 2;
+ if (t.flags & Q.FL_NO_KNOCKBACK) knockback = 0;
+ if (!(dflags & Q.DAMAGE_NO_KNOCKBACK) && knockback && t.movetype !== 'none') {
+ const mass = t.mass < 50 ? 50 : t.mass;
+ const kvel = scale(dir, (t.client && attacker === targ ? 1600.0 : 500.0) * knockback / mass);
+ t.velocity = add(t.velocity, kvel);
+ }
+ let take = damage;
+ const asave = checkArmor(g, t, take, dflags); // no power armor, god mode or invulnerability in these arenas
+ take -= asave;
+ if (asave) Q.fx(g, 'spark', point, normal);
+ g.damageLog.push([targ, attacker, take, asave, mod]);
+ if (take) {
+ Q.fx(g, (t.svflags & Q.SVF_MONSTER) || t.client ? 'blood' : 'spark', point, normal);
+ t.health -= take;
+ if (t.health <= 0) {
+ if ((t.svflags & Q.SVF_MONSTER) || t.client) t.flags |= Q.FL_NO_KNOCKBACK;
+ killed(g, targ, inflictor, attacker, take, point);
+ return;
+ }
+ }
+ if (t.svflags & Q.SVF_MONSTER) {
+ Q.reactToDamage(g, targ, attacker);
+ // AI_DUCKED (the Mutant in mid-leap) suppresses the pain reaction
+ if (!(t.monsterinfo.aiflags & Q.AI_DUCKED) && take) { Q.monsterPain(g, targ, attacker, knockback, take); if (g.skill === 3) g.ents[targ].pain_debounce_time = g.ms + 5000; }
+ }
+ if (t.client) { t.damage_blood += take; t.damage_armor += asave; t.damage_knockback += knockback; t.damage_from = copy3(point); }
+ };
+ function killed(g, targ, inflictor, attacker, damage, point) {
+ const t = g.ents[targ];
+ if (t.health < -999) t.health = -999;
+ t.enemy = attacker;
+ if (t.client) { t.deadflag = Q.DEAD_DEAD; t.takedamage = Q.DAMAGE_NO; Q.event(g, 'player_die'); return; }
+ if ((t.svflags & Q.SVF_MONSTER) && t.deadflag !== Q.DEAD_DEAD) { t.touch = null; Q.monsterDeathUse(g, targ); }
+ Q.monsterDie(g, targ, inflictor, attacker, damage, point);
+ }
+ Q.radiusDamage = (g, inflictor, attacker, damage, ignore, radius, mod) => {
+ const inf = g.ents[inflictor];
+ for (const k of Q.findradius(g, inf.origin, radius)) {
+ if (k === ignore) continue;
+ const e = g.ents[k];
+ if (!e.takedamage) continue;
+ let points = damage - 0.5 * len(sub(inf.origin, Q.center(e)));
+ if (k === attacker) points *= 0.5;
+ if (points > 0 && Q.canDamage(g, k, inflictor)) {
+ const dir = sub(e.origin, inf.origin);
+ Q.damage(g, k, inflictor, attacker, dir, inf.origin, [0, 0, 0], Math.trunc(points), Math.trunc(points), Q.DAMAGE_RADIUS, mod);
+ }
+ }
+ };
+
+ // ---------------- items (Touch_Item) ----------------
+ Q.spawnItem = (g, type, origin) => {
+ const i = Q.spawn(g), e = g.ents[i];
+ Object.assign(e, { classname: type, item: type, origin: copy3(origin), mins: [-15, -15, -15], maxs: [15, 15, 15], solid: Q.SOLID_TRIGGER, touch: 'Touch_Item', movetype: 'toss', groundentity: 0 }); // droptofloor done
+ return i;
+ };
+ const PICKUP = {
+ health: (p) => healthPickup(p, 10, false), health_large: (p) => healthPickup(p, 25, false), stimpack: (p) => healthPickup(p, 2, true),
+ armor_shard: (p) => { const a = Q.armorIndex(p); if (!a) p.inv.jacket = 2; else p.inv[a] += 2; return true; },
+ armor_jacket: p => armorPickup(p, 'jacket'), armor_combat: p => armorPickup(p, 'combat'), armor_body: p => armorPickup(p, 'body'),
+ ammo_shells: p => ammoPickup(p, 'shells'), ammo_bullets: p => ammoPickup(p, 'bullets'), ammo_cells: p => ammoPickup(p, 'cells'),
+ ammo_rockets: p => ammoPickup(p, 'rockets'), ammo_slugs: p => ammoPickup(p, 'slugs'),
+ };
+ Q.PICKUP = PICKUP;
+ function healthPickup(p, count, ignoreMax) {
+ if (!ignoreMax && p.health >= p.max_health) return false;
+ p.health += count;
+ if (!ignoreMax && p.health > p.max_health) p.health = p.max_health;
+ return true;
+ }
+ function armorPickup(p, kind) { // Pickup_Armor with salvage
+ const old = Q.armorIndex(p), info = ARMOR[kind];
+ if (!old) { p.inv[kind] = info[0]; return true; }
+ const oldinfo = ARMOR[old];
+ if (info[2] > oldinfo[2]) {
+ const salvagecount = Math.trunc((oldinfo[2] / info[2]) * p.inv[old]);
+ let newcount = info[0] + salvagecount; if (newcount > info[1]) newcount = info[1];
+ p.inv[old] = 0; p.inv[kind] = newcount;
+ } else {
+ const salvagecount = Math.trunc((info[2] / oldinfo[2]) * info[0]);
+ let newcount = p.inv[old] + salvagecount; if (newcount > oldinfo[1]) newcount = oldinfo[1];
+ if (p.inv[old] >= newcount) return false;
+ p.inv[old] = newcount;
+ }
+ return true;
+ }
+ function ammoPickup(p, ammo) {
+ if (p.inv[ammo] === AMMO_MAX[ammo]) return false;
+ p.inv[ammo] = Math.min(AMMO_MAX[ammo], (p.inv[ammo] || 0) + AMMO_PICKUP[ammo]);
+ return true;
+ }
+ // Touch_Item. Health and armor are single-player items: taken once, then freed (G_FreeEdict), never respawned
+ // (q2-arena@4, 2026-11-07: a respawning medkit lets a player stand and trade hits with the boss). Ammo keeps the
+ // deathmatch timer (SetRespawn 30 s, original DoRespawn) so a three-minute fight cannot run out of rounds; ammo
+ // heals nothing. q2-arena@1-3 also respawned health (30 s) and armor (20 s).
+ const RESPAWN = { ammo_shells: 30, ammo_bullets: 30, ammo_cells: 30, ammo_rockets: 30, ammo_slugs: 30 };
+ Q.TOUCH.Touch_Item = (g, i, other) => {
+ const it = g.ents[i], p = g.ents[other];
+ if (!p.client || p.health < 1) return;
+ if (!PICKUP[it.item](p)) return;
+ p.bonus_alpha = 0.25; p.pickup = it.item; p.pickup_time = g.ms + 3000;
+ Q.event(g, 'pickup', { item: it.item });
+ if (!RESPAWN[it.item]) { Q.freeEdict(g, i); return; }
+ it.svflags |= Q.SVF_NOCLIENT; it.solid = Q.SOLID_NOT; it.nextthink = g.ms + RESPAWN[it.item] * 1000; it.think = 'DoRespawn';
+ };
+ Q.THINK.DoRespawn = (g, i) => { const it = g.ents[i]; it.svflags &= ~Q.SVF_NOCLIENT; it.solid = Q.SOLID_TRIGGER; Q.event(g, 'item_respawn', { item: it.item }); };
+
+ // ---------------- player trail (p_trail.c) ----------------
+ Q.playerTrailInit = g => { g.trail = { head: 0, spots: Array.from({ length: 8 }, () => ({ origin: [0, 0, 0], timestamp: 0, yaw: 0 })) }; };
+ Q.playerTrailAdd = (g, spot) => {
+ const tr = g.trail, prev = tr.spots[(tr.head - 1) & 7];
+ tr.spots[tr.head] = { origin: copy3(spot), timestamp: g.ms, yaw: Q.vectoyaw(sub(spot, prev.origin)) };
+ tr.head = (tr.head + 1) & 7;
+ };
+ Q.trailLastSpot = g => g.trail.spots[(g.trail.head - 1) & 7];
+ Q.trailPick = (g, self, first) => {
+ const tr = g.trail, mi = g.ents[self].monsterinfo;
+ let marker = tr.head;
+ for (let n = 8; n; n--) { if (tr.spots[marker].timestamp <= mi.trail_time) marker = (marker + 1) & 7; else break; }
+ if (!first) return tr.spots[marker];
+ if (Q.visiblePoint(g, self, tr.spots[marker].origin)) return tr.spots[marker];
+ const prev = tr.spots[(marker - 1) & 7];
+ if (Q.visiblePoint(g, self, prev.origin)) return prev;
+ return tr.spots[marker];
+ };
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/quake2_remake/renderer3d.js b/environments/games/web/games/quake2_remake/renderer3d.js
new file mode 100644
index 0000000000000000000000000000000000000000..1e233d3c6cdbf1d8c7d1f02a60f3d702ae345b8e
--- /dev/null
+++ b/environments/games/web/games/quake2_remake/renderer3d.js
@@ -0,0 +1,503 @@
+/* Quake II boss arenas - original procedural 3D art on Three.js r160 (MIT, shared read-only vendor copy in
+ web/games/_boss3d/vendor). First-person perspective from the player's eye with Quake II's 90 degree horizontal
+ field of view. Rendering is a pure function of the game state: it never writes the simulation and never draws
+ gameplay RNG; animation time comes from the state's tick counter. No Quake II models, skins or textures are used. */
+(function (root) {
+ 'use strict';
+ const T = root.THREE, M = root.Quake2Game, Q = M && M.Q;
+ if (!T) throw Error('Three.js is missing (web/games/_boss3d/vendor/three.min.js)');
+ const R = M.R3 = {};
+ const S = 1 / 32; // one Quake II unit = 1/32 scene unit
+ const byCanvas = new WeakMap();
+ const DEG = Math.PI / 180;
+ const qv = (x, y, z, out) => (out || new T.Vector3()).set(x * S, z * S, -y * S); // Quake (x fwd, y left, z up) -> three
+ function hash(x, y, s) { let n = Math.imul(x + 374761393 * s, 668265263) ^ Math.imul(y + s, 2246822519); n = Math.imul(n ^ (n >>> 13), 1274126177); return ((n ^ (n >>> 16)) >>> 0) / 4294967295; }
+
+ // ---------------- procedural textures (deterministic, generated once per scene) ----------------
+ function canvasTex(w, h, paint, opts = {}) {
+ const c = document.createElement('canvas'); c.width = w; c.height = h;
+ const q = c.getContext('2d'); paint(q, w, h);
+ const t = new T.CanvasTexture(c); t.colorSpace = T.SRGBColorSpace; t.wrapS = t.wrapT = T.RepeatWrapping; t.anisotropy = 2;
+ if (opts.nearest) { t.magFilter = T.NearestFilter; }
+ return t;
+ }
+ function noiseFill(q, w, h, base, amp, seed, grain = 1) {
+ const im = q.createImageData(w, h);
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
+ const n = (hash(Math.floor(x / grain), Math.floor(y / grain), seed) - 0.5) * amp + (hash(x >> 3, y >> 3, seed + 7) - 0.5) * amp * 0.6;
+ const i = (y * w + x) * 4; im.data[i] = base[0] + n; im.data[i + 1] = base[1] + n; im.data[i + 2] = base[2] + n * 0.9; im.data[i + 3] = 255;
+ }
+ q.putImageData(im, 0, 0);
+ }
+ const rivets = (q, xs, ys, col) => { q.fillStyle = col; for (const x of xs) for (const y of ys) { q.fillRect(x - 2, y - 2, 4, 4); } };
+ const PAINT = {
+ floor(q, w, h) { noiseFill(q, w, h, [74, 70, 62], 26, 3); q.strokeStyle = '#2b2925'; q.lineWidth = 3; for (let k = 0; k <= w; k += 64) { q.beginPath(); q.moveTo(k, 0); q.lineTo(k, h); q.stroke(); q.beginPath(); q.moveTo(0, k); q.lineTo(w, k); q.stroke(); }
+ q.strokeStyle = '#5c584e'; q.lineWidth = 1; for (let k = 8; k < w; k += 16) { q.beginPath(); q.moveTo(k, 0); q.lineTo(k, h); q.stroke(); } rivets(q, [6, 58, 70, 122, 134, 186, 198, 250], [6, 58, 70, 122, 134, 186, 198, 250], '#8e8778'); },
+ wall(q, w, h) { noiseFill(q, w, h, [96, 72, 52], 30, 11); q.fillStyle = '#3a2b20'; for (let y = 0; y < h; y += 64) q.fillRect(0, y, w, 5); q.fillStyle = '#6e5440';
+ for (let x = 0; x < w; x += 128) q.fillRect(x + 60, 0, 8, h); rivets(q, [12, 116, 140, 244], [14, 50, 78, 114, 142, 178, 206, 242], '#b29470'); q.fillStyle = 'rgba(40,24,12,.35)'; q.fillRect(0, h - 40, w, 40); },
+ crate(q, w, h) { noiseFill(q, w, h, [72, 82, 58], 22, 21); q.strokeStyle = '#3a4430'; q.lineWidth = 10; q.strokeRect(5, 5, w - 10, h - 10); q.lineWidth = 8; q.beginPath(); q.moveTo(10, 10); q.lineTo(w - 10, h - 10); q.moveTo(w - 10, 10); q.lineTo(10, h - 10); q.stroke();
+ q.fillStyle = '#c9b34a'; q.font = 'bold 34px monospace'; q.fillText('S-7', w * 0.36, h * 0.56); },
+ pylon(q, w, h) { noiseFill(q, w, h, [104, 100, 92], 24, 31); for (let x = -h; x < w; x += 40) { q.fillStyle = '#d9a722'; q.beginPath(); q.moveTo(x, h); q.lineTo(x + 20, h); q.lineTo(x + 60, h - 40); q.lineTo(x + 40, h - 40); q.fill(); }
+ q.fillStyle = '#2a2826'; q.fillRect(0, h - 44, w, 4); q.fillStyle = '#5b5852'; for (let y = 16; y < h - 50; y += 48) q.fillRect(0, y, w, 4); },
+ tech(q, w, h) { noiseFill(q, w, h, [46, 52, 58], 18, 41); q.fillStyle = '#1a1f24'; q.fillRect(20, 30, w - 40, 90); q.fillRect(20, 150, w - 40, 70);
+ for (let k = 0; k < 9; k++) { q.fillStyle = k % 3 ? '#2fa36b' : '#7be0a8'; q.fillRect(30 + k * 22, 44 + (k * 37 % 50), 14, 8); } q.fillStyle = '#d9a722'; q.fillRect(0, 0, w, 8); },
+ techGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); for (let k = 0; k < 9; k++) { q.fillStyle = k % 3 ? '#1c7a4c' : '#5ce9a0'; q.fillRect(30 + k * 22, 44 + (k * 37 % 50), 14, 8); } q.fillStyle = '#123'; q.fillRect(20, 150, w - 40, 70); },
+ hangar(q, w, h) { noiseFill(q, w, h, [78, 86, 94], 20, 51); q.fillStyle = '#2f353b'; for (let y = 0; y < h; y += 128) q.fillRect(0, y, w, 6); for (let x = 0; x < w; x += 128) q.fillRect(x, 0, 6, h);
+ q.fillStyle = '#c99a2a'; q.fillRect(0, h - 26, w, 10); rivets(q, [16, 112, 144, 240], [16, 112, 144, 240], '#a9b3bb'); },
+ cargo(q, w, h) { noiseFill(q, w, h, [150, 78, 34], 22, 61); for (let x = 0; x < w; x += 16) { q.fillStyle = x % 32 ? 'rgba(0,0,0,.18)' : 'rgba(255,220,180,.08)'; q.fillRect(x, 0, 8, h); }
+ q.strokeStyle = '#4a2a14'; q.lineWidth = 8; q.strokeRect(4, 4, w - 8, h - 8); q.fillStyle = '#efe3c8'; q.font = 'bold 26px monospace'; q.fillText('CRG 4410', 40, 70); },
+ strogg(q, w, h) { noiseFill(q, w, h, [104, 66, 58], 30, 71); q.fillStyle = '#3e2420'; for (let y = 24; y < h; y += 64) q.fillRect(0, y, w, 10); q.fillStyle = '#a06a58';
+ for (let x = 16; x < w; x += 64) { q.fillRect(x, 0, 6, h); q.fillRect(x + 12, 0, 3, h); } rivets(q, [40, 104, 168, 232], [8, 72, 136, 200], '#b5806a'); },
+ pillar(q, w, h) { noiseFill(q, w, h, [92, 80, 78], 24, 81); q.fillStyle = '#3a3032'; for (let x = 0; x < w; x += 64) q.fillRect(x, 0, 10, h); q.fillStyle = '#ff7a1a'; for (let y = 40; y < h; y += 96) q.fillRect(0, y, w, 6); },
+ pillarGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); q.fillStyle = '#ff6a10'; for (let y = 40; y < h; y += 96) q.fillRect(0, y, w, 6); },
+ dais(q, w, h) { noiseFill(q, w, h, [66, 58, 56], 22, 91); q.strokeStyle = '#a3241a'; q.lineWidth = 6; q.beginPath(); q.arc(w / 2, h / 2, w * 0.4, 0, Math.PI * 2); q.stroke(); q.lineWidth = 3; q.beginPath(); q.arc(w / 2, h / 2, w * 0.28, 0, Math.PI * 2); q.stroke();
+ for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; q.beginPath(); q.moveTo(w / 2 + Math.cos(a) * w * 0.28, h / 2 + Math.sin(a) * w * 0.28); q.lineTo(w / 2 + Math.cos(a) * w * 0.4, h / 2 + Math.sin(a) * w * 0.4); q.stroke(); } },
+ roof(q, w, h) { noiseFill(q, w, h, [40, 40, 44], 16, 101); q.fillStyle = '#1b1b1e'; for (let k = 0; k < w; k += 128) { q.fillRect(k, 0, 8, h); q.fillRect(0, k, w, 8); } q.fillStyle = '#e8dcb0'; q.fillRect(48, 48, 32, 32); q.fillRect(176, 176, 32, 32); },
+ roofGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); q.fillStyle = '#c9b98a'; q.fillRect(48, 48, 32, 32); q.fillRect(176, 176, 32, 32); },
+ metal(q, w, h) { noiseFill(q, w, h, [92, 92, 96], 22, 111); q.fillStyle = '#3c3c40'; q.fillRect(0, h / 2 - 3, w, 6); rivets(q, [10, w - 10], [10, h - 10], '#b8b8bc'); },
+ factory(q, w, h) { noiseFill(q, w, h, [96, 92, 84], 24, 131); q.fillStyle = '#4a4640'; for (let y = 0; y < h; y += 64) q.fillRect(0, y, w, 6);
+ for (let x = 0; x < w; x += 128) { q.fillStyle = '#d9a722'; q.fillRect(x + 8, h - 30, 48, 10); q.fillStyle = '#2a2826'; q.fillRect(x + 56, h - 30, 48, 10); } rivets(q, [24, 104, 152, 232], [24, 88, 152, 216], '#c0b8a6'); },
+ machine(q, w, h) { noiseFill(q, w, h, [70, 84, 92], 20, 141); q.fillStyle = '#1e262c'; q.fillRect(24, 24, w - 48, h - 48); q.fillStyle = '#ff8a2a';
+ for (let k = 0; k < 6; k++) q.fillRect(40 + k * 30, 40, 18, 6); q.fillStyle = '#5ad0ff'; q.fillRect(40, h - 70, w - 80, 8); q.strokeStyle = '#9aa8b0'; q.lineWidth = 4; q.strokeRect(8, 8, w - 16, h - 16); },
+ machineGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); q.fillStyle = '#ff8a2a'; for (let k = 0; k < 6; k++) q.fillRect(40 + k * 30, 40, 18, 6); q.fillStyle = '#5ad0ff'; q.fillRect(40, h - 70, w - 80, 8); },
+ arena(q, w, h) { noiseFill(q, w, h, [124, 104, 80], 26, 151); q.fillStyle = '#6a5440'; for (let y = 0; y < h; y += 48) { const o = (y / 48 % 2) * 64; for (let x = -64 + o; x < w; x += 128) q.fillRect(x, y, 4, 48); q.fillRect(0, y, w, 4); } },
+ column(q, w, h) { noiseFill(q, w, h, [150, 138, 120], 20, 161); q.fillStyle = 'rgba(60,44,30,.35)'; for (let x = 0; x < w; x += 32) q.fillRect(x, 0, 8, h); q.fillStyle = '#7a3020'; q.fillRect(0, 16, w, 10); q.fillRect(0, h - 26, w, 10); },
+ lab(q, w, h) { noiseFill(q, w, h, [176, 184, 176], 14, 171); q.fillStyle = '#7a8a86'; for (let y = 0; y < h; y += 64) q.fillRect(0, y, w, 3); for (let x = 0; x < w; x += 64) q.fillRect(x, 0, 3, h);
+ q.fillStyle = '#3a8a5a'; q.fillRect(0, h - 40, w, 14); q.fillStyle = '#d8d040'; for (let x = 0; x < w; x += 32) q.fillRect(x, h - 44, 16, 4); },
+ bench(q, w, h) { noiseFill(q, w, h, [130, 140, 146], 16, 181); q.fillStyle = '#3c464c'; q.fillRect(0, 0, w, 10); q.fillStyle = '#60c890'; for (let k = 0; k < 4; k++) q.fillRect(20 + k * 56, 30, 34, 20); },
+ flesh(q, w, h) { noiseFill(q, w, h, [120, 62, 58], 36, 121, 2); q.strokeStyle = 'rgba(60,20,20,.6)'; q.lineWidth = 3; for (let k = 0; k < 10; k++) { q.beginPath(); q.moveTo(hash(k, 1, 9) * w, 0); q.bezierCurveTo(hash(k, 2, 9) * w, h * 0.3, hash(k, 3, 9) * w, h * 0.7, hash(k, 4, 9) * w, h); q.stroke(); } },
+ };
+
+ // Box geometry with world-scaled UVs (one texture tile = 128 Quake units) so walls never stretch.
+ function brushGeometry(b) {
+ const [x0, y0, z0] = b.mins, [x1, y1, z1] = b.maxs, pos = [], uv = [], nor = [], idx = [];
+ const face = (corners, n, ua, va) => {
+ const base = pos.length / 3;
+ for (const c of corners) { const p = qv(c[0], c[1], c[2]); pos.push(p.x, p.y, p.z); uv.push(c[ua] / 128, c[va] / 128); nor.push(n.x, n.y, n.z); }
+ idx.push(base, base + 1, base + 2, base, base + 2, base + 3);
+ };
+ const N = (x, y, z) => qv(x / S, y / S, z / S).normalize();
+ face([[x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]], N(0, 0, 1), 0, 1); // top
+ face([[x0, y1, z0], [x1, y1, z0], [x1, y0, z0], [x0, y0, z0]], N(0, 0, -1), 0, 1); // bottom
+ face([[x0, y0, z0], [x1, y0, z0], [x1, y0, z1], [x0, y0, z1]], N(0, -1, 0), 0, 2); // -y
+ face([[x1, y1, z0], [x0, y1, z0], [x0, y1, z1], [x1, y1, z1]], N(0, 1, 0), 0, 2); // +y
+ face([[x0, y1, z0], [x0, y0, z0], [x0, y0, z1], [x0, y1, z1]], N(-1, 0, 0), 1, 2); // -x
+ face([[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], N(1, 0, 0), 1, 2); // +x
+ const geo = new T.BufferGeometry();
+ geo.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); geo.setAttribute('uv', new T.Float32BufferAttribute(uv, 2));
+ geo.setAttribute('normal', new T.Float32BufferAttribute(nor, 3)); geo.setIndex(idx);
+ // Inward faces of the arena shell are what the camera sees; render both sides.
+ return geo;
+ }
+
+ // ---------------- the scene ----------------
+ const ARENA_STYLE = {
+ supertank: { fog: 0x2c2420, near: 900, far: 3400, hemi: [0xffd2a6, 0x3a2a20, 1.35], sun: [0xffb070, 1.6, [-0.5, 1, 0.35]], sky: ['#1c1424', '#5a2e3a', '#d0773a'], lamps: [] },
+ hornet: { fog: 0x161b20, near: 700, far: 3000, hemi: [0xb9cde0, 0x282624, 1.15], sun: null, sky: null, lamps: [[896, 900, 470, 0xfff2d2, 1.6, 2400], [300, 300, 300, 0xffb050, 1.0, 1200], [1500, 1500, 300, 0x9fd0ff, 1.0, 1200]] },
+ makron: { fog: 0x2a1a16, near: 1100, far: 3600, hemi: [0xffd0c0, 0x4a3028, 2.3], sun: null, sky: null, lamps: [[960, 960, 420, 0xff7a4a, 2.4, 2600], [560, 560, 300, 0xff9a50, 1.4, 1300], [1360, 1360, 300, 0xff9a50, 1.4, 1300], [560, 1360, 300, 0xffc890, 1.2, 1300], [1360, 560, 300, 0xffc890, 1.2, 1300]] },
+ tank_commander: { fog: 0x24201c, near: 1000, far: 3400, hemi: [0xffe2c0, 0x3a342c, 2.0], sun: null, sky: null, lamps: [[896, 896, 420, 0xffd8a0, 2.0, 2600], [480, 620, 300, 0xff9a40, 1.2, 1200], [1312, 620, 300, 0xff9a40, 1.2, 1200], [480, 1170, 300, 0x9ad0ff, 1.2, 1200], [1312, 1170, 300, 0x9ad0ff, 1.2, 1200]] },
+ gladiator: { fog: 0x3a2a22, near: 1200, far: 3400, hemi: [0xffd8b0, 0x4a3426, 1.5], sun: [0xffb070, 1.6, [0.4, 1, -0.3]], sky: ['#241828', '#6a3a3a', '#e08a4a'], lamps: [] },
+ mutant: { fog: 0x1e2624, near: 1100, far: 3400, hemi: [0xe0fff0, 0x2a3430, 1.9], sun: null, sky: null, lamps: [[960, 800, 360, 0xd8fff0, 2.0, 2400], [480, 400, 300, 0x8affc0, 1.0, 1200], [1440, 400, 300, 0x8affc0, 1.0, 1200], [480, 1200, 300, 0xfff0c0, 1.0, 1200], [1440, 1200, 300, 0xfff0c0, 1.0, 1200]] },
+ };
+ class Scene {
+ constructor(key, canvas) {
+ this.key = key; this.canvas = canvas; this.resources = []; this.times = []; this.ready = false; this.error = null; this.closed = false;
+ this.view = document.createElement('canvas'); this.view.width = 854; this.view.height = 480;
+ this.renderer = new T.WebGLRenderer({ canvas: this.view, antialias: true, preserveDrawingBuffer: true, powerPreference: 'low-power' });
+ this.renderer.setPixelRatio(1); this.renderer.setSize(854, 480, false); this.renderer.outputColorSpace = T.SRGBColorSpace;
+ this.renderer.toneMapping = T.ACESFilmicToneMapping; this.renderer.toneMappingExposure = 1.15; this.renderer.autoClear = false; this.renderer.info.autoReset = false;
+ this.view.addEventListener('webglcontextlost', e => { e.preventDefault(); this.ready = false; this.error = 'WebGL context lost'; });
+ const st = ARENA_STYLE[key];
+ this.world = new T.Scene(); this.world.fog = new T.Fog(st.fog, st.near * S, st.far * S);
+ this.world.background = st.sky ? this.keep(canvasTex(8, 256, (q, w, h) => { const gr = q.createLinearGradient(0, 0, 0, h); gr.addColorStop(0, st.sky[0]); gr.addColorStop(0.55, st.sky[1]); gr.addColorStop(1, st.sky[2]); q.fillStyle = gr; q.fillRect(0, 0, w, h); })) : new T.Color(st.fog);
+ // Quake II fov 90 is horizontal: vertical = 2*atan(tan(45)*480/854) = 58.7 degrees.
+ this.camera = new T.PerspectiveCamera(2 * Math.atan(Math.tan(45 * DEG) * 480 / 854) / DEG, 854 / 480, 2 * S, 6000 * S);
+ this.world.add(new T.HemisphereLight(st.hemi[0], st.hemi[1], st.hemi[2]));
+ if (st.sun) { const sun = new T.DirectionalLight(st.sun[0], st.sun[1]); sun.position.set(st.sun[2][0], st.sun[2][1], st.sun[2][2]); this.world.add(sun); }
+ for (const [x, y, z, c, i, d] of st.lamps) { const l = new T.PointLight(c, i, d * S, 1.2); qv(x, y, z, l.position); this.world.add(l); }
+ this.flashLight = new T.PointLight(0xffc070, 0, 500 * S, 1.5); this.world.add(this.flashLight);
+ this.boomLight = new T.PointLight(0xff8a30, 0, 600 * S, 1.4); this.world.add(this.boomLight);
+ this.tex = {}; this.mat = {};
+ const tex = name => this.tex[name] || (this.tex[name] = this.keep(canvasTex(256, 256, PAINT[name])));
+ const lam = (name, color = 0xffffff, glow) => { const m = new T.MeshLambertMaterial({ map: tex(name), color, side: T.DoubleSide }); if (glow) { m.emissive = new T.Color(0xffffff); m.emissiveMap = tex(glow); m.emissiveIntensity = 1.3; } return this.keep(m); };
+ this.mat.brush = { floor: lam('floor'), wall: lam('wall'), crate: lam('crate'), pylon: lam('pylon'), tech: lam('tech', 0xffffff, 'techGlow'), hangar: lam('hangar'), cargo: lam('cargo'),
+ strogg: lam('strogg'), pillar: lam('pillar', 0xffffff, 'pillarGlow'), dais: lam('dais'), roof: lam('roof', 0xffffff, 'roofGlow'), barrier: lam('pylon', 0xc8c4bc),
+ factory: lam('factory'), machine: lam('machine', 0xffffff, 'machineGlow'), arena: lam('arena'), column: lam('column'), lab: lam('lab'), bench: lam('bench') };
+ for (const b of Q.worlds[key].brushes) {
+ if (b.sky) continue;
+ const mesh = new T.Mesh(this.keep(brushGeometry(b)), this.mat.brush[b.mat] || this.mat.brush.wall);
+ this.world.add(mesh);
+ }
+ this.buildShared(); this.buildBosses(); this.buildWeapons();
+ }
+ keep(r) { this.resources.push(r); return r; }
+ std(color, opts = {}) { return this.keep(new T.MeshLambertMaterial(Object.assign({ color }, opts))); }
+ glow(color, opacity = 1) { return this.keep(new T.MeshBasicMaterial({ color, transparent: opacity < 1, opacity, depthWrite: opacity >= 1, blending: opacity < 1 ? T.AdditiveBlending : T.NormalBlending, fog: false })); }
+ buildShared() {
+ const G = this.geo = {
+ box: this.keep(new T.BoxGeometry(1, 1, 1)), sphere: this.keep(new T.SphereGeometry(1, 14, 10)), lowSphere: this.keep(new T.SphereGeometry(1, 8, 6)),
+ cyl: this.keep(new T.CylinderGeometry(1, 1, 1, 12)), cyl6: this.keep(new T.CylinderGeometry(1, 1, 1, 6)), cone: this.keep(new T.ConeGeometry(1, 1, 10)),
+ ico: this.keep(new T.IcosahedronGeometry(1, 0)), ring: this.keep(new T.TorusGeometry(1, 0.06, 6, 24)), plane: this.keep(new T.PlaneGeometry(1, 1)),
+ };
+ const pool = (n, make) => { const out = []; for (let k = 0; k < n; k++) { const o = make(); o.visible = false; this.world.add(o); out.push(o); } return out; };
+ this.mats = {
+ rocketBody: this.std(0x5b5f58), flame: this.glow(0xffa040, 0.9), smoke: this.keep(new T.MeshBasicMaterial({ color: 0x8a8580, transparent: true, opacity: 0.32, depthWrite: false })),
+ bolt: this.glow(0xffe060, 0.95), boltCore: this.glow(0xfff8d0), bfg: this.glow(0x5cff6a, 0.85), bfgCore: this.glow(0xe8ffe0), bfgHalo: this.keep(new T.MeshBasicMaterial({ color: 0x40ff60, transparent: true, opacity: 0.08, depthWrite: false, wireframe: true })),
+ boom: this.glow(0xff8a30, 0.8), boomCore: this.glow(0xfff0b0, 0.9), blood: this.keep(new T.MeshBasicMaterial({ color: 0x8a0d08, transparent: true, opacity: 0.8, depthWrite: false })),
+ puff: this.keep(new T.MeshBasicMaterial({ color: 0x9a948a, transparent: true, opacity: 0.6, depthWrite: false })), spark: this.glow(0xffd070, 0.9),
+ meat: this.std(0x7a1c16), gibMetal: this.std(0x6a6a70), debris: this.std(0x4a4440), mflash: this.glow(0xffd890, 0.95), warn: this.glow(0xff2a20, 0.65),
+ tracer: this.keep(new T.LineBasicMaterial({ color: 0xffe0a0, transparent: true, opacity: 0.55 })), railCore: this.keep(new T.LineBasicMaterial({ color: 0xe8f4ff, transparent: true, opacity: 0.9 })),
+ railSpiral: this.keep(new T.LineBasicMaterial({ color: 0x3a7cff, transparent: true, opacity: 0.9 })), laser: this.keep(new T.LineBasicMaterial({ color: 0x6aff70, transparent: true, opacity: 0.85 })),
+ aimLine: this.keep(new T.LineBasicMaterial({ color: 0xff3020, transparent: true, opacity: 0.85 })),
+ };
+ this.rockets = pool(24, () => { const g = new T.Group(); const body = new T.Mesh(G.cyl, this.mats.rocketBody); body.scale.set(2.2 * S, 18 * S, 2.2 * S); body.rotation.z = Math.PI / 2; g.add(body);
+ const fl = new T.Mesh(G.cone, this.mats.flame); fl.scale.set(3.4 * S, 14 * S, 3.4 * S); fl.rotation.z = Math.PI / 2; fl.position.x = -15 * S; g.add(fl);
+ for (let k = 0; k < 4; k++) { const sm = new T.Mesh(G.lowSphere, this.mats.smoke); sm.position.x = -(28 + k * 16) * S; sm.scale.setScalar((4 + k * 2.2) * S); g.add(sm); } return g; });
+ this.bolts = pool(48, () => { const g = new T.Group(); const a = new T.Mesh(G.sphere, this.mats.bolt); a.scale.set(16 * S, 3.2 * S, 3.2 * S); g.add(a); const c = new T.Mesh(G.sphere, this.mats.boltCore); c.scale.set(9 * S, 1.6 * S, 1.6 * S); g.add(c); return g; });
+ this.bfgs = pool(4, () => { const g = new T.Group(); const a = new T.Mesh(G.sphere, this.mats.bfg); a.scale.setScalar(14 * S); g.add(a); const c = new T.Mesh(G.sphere, this.mats.bfgCore); c.scale.setScalar(7 * S); g.add(c);
+ const h = new T.Mesh(G.lowSphere, this.mats.bfgHalo); h.scale.setScalar(256 * S); g.add(h); return g; });
+ this.booms = pool(24, () => { const g = new T.Group(); const a = new T.Mesh(G.ico, this.mats.boom); g.add(a); const c = new T.Mesh(G.sphere, this.mats.boomCore); c.scale.setScalar(0.5); g.add(c); return g; });
+ this.puffs = pool(64, () => new T.Mesh(G.lowSphere, this.mats.puff));
+ this.gibs = pool(40, () => new T.Mesh(G.ico, this.mats.meat));
+ this.flashes = pool(12, () => new T.Mesh(G.sphere, this.mats.mflash));
+ const lines = (n, mat, pts) => pool(n, () => { const geo = this.keep(new T.BufferGeometry()); geo.setAttribute('position', new T.BufferAttribute(new Float32Array(pts * 3), 3)); return new T.Line(geo, mat); });
+ this.tracers = lines(40, this.mats.tracer, 2); this.railCores = lines(6, this.mats.railCore, 2); this.railSpirals = lines(6, this.mats.railSpiral, 96);
+ this.lasers = lines(12, this.mats.laser, 2); this.aimLines = lines(2, this.mats.aimLine, 2);
+ this.items = {};
+ const itemMat = { health: this.std(0xe8e4dc), health_large: this.std(0xf2eee6), stimpack: this.std(0xd0f0ff), armor_shard: this.glow(0x4ae07a, 0.95), armor_jacket: this.std(0x6e7b4a),
+ armor_combat: this.std(0x8a8f96), armor_body: this.std(0xc0a246), ammo_shells: this.std(0xa0382a), ammo_bullets: this.std(0xb89a34), ammo_rockets: this.std(0x3c5a34), ammo_cells: this.std(0x3a6aa8), ammo_slugs: this.std(0x5a6a5a) };
+ this.itemMat = itemMat; this.crossMat = this.glow(0xd01818);
+ }
+ // ---------------- boss models (original silhouettes after the Quake II designs) ----------------
+ // Quake-local position (fwd, left, up) and sizes in units; rx rolls about forward, ry turns a vertical cylinder to
+ // point forward (three z), rz yaws about up.
+ part(parent, geo, mat, x, y, z, sx, sy, sz, rx = 0, ry = 0, rz = 0) {
+ const m = new T.Mesh(geo, mat); qv(x, y, z, m.position); m.scale.set(sx * S, sz * S, sy * S); m.rotation.set(rx, rz, ry); parent.add(m); return m;
+ }
+ group(parent, x = 0, y = 0, z = 0) { const g = new T.Group(); qv(x, y, z, g.position); parent.add(g); return g; }
+ buildBosses() {
+ const G = this.geo, P = this.part.bind(this);
+ const steel = this.std(0x9a9ea6), dark = this.std(0x4a4d52), rust = this.std(0xa06a44), olive = this.std(0x76844f), flesh = this.std(0xc07a62, { map: this.keep(canvasTex(128, 128, PAINT.flesh)) });
+ const red = this.glow(0xff3010), amber = this.glow(0xffa030), green = this.glow(0x60ff70), cyan = this.glow(0x60c8ff), purple = this.std(0x7a5a88);
+ this.bossMats = { steel, dark, rust, olive, flesh, red, amber, green, cyan };
+ this.models = {};
+ // Super Tank (boss1): tracked base, armoured hull, chaingun arm on the right, triple rocket pod on the left.
+ { const root = new T.Group(), m = { root }; this.world.add(root);
+ for (const s of [1, -1]) { const tr = this.group(root, 0, s * 44, 0); P(tr, G.box, dark, 0, 0, 22, 132, 34, 44); for (let k = -2; k <= 2; k++) P(tr, G.cyl, steel, k * 26, 0, 18, 13, 13, 37, Math.PI / 2, 0, 0); m['tread' + (s > 0 ? 'L' : 'R')] = tr; }
+ const hull = this.group(root, 0, 0, 44); P(hull, G.box, olive, 0, 0, 16, 104, 80, 32); P(hull, G.box, steel, 46, 0, 10, 16, 70, 18); m.hull = hull;
+ const torso = this.group(hull, -6, 0, 32); P(torso, G.box, olive, 0, 0, 20, 66, 62, 40); P(torso, G.box, dark, 0, 0, 42, 40, 40, 8); P(torso, G.box, rust, 18, 0, 34, 20, 24, 18);
+ m.eye = P(torso, G.box, red, 29, 0, 36, 3, 14, 4); m.torso = torso;
+ const gun = this.group(torso, 30, -30, 12); P(gun, G.cyl, dark, 0, 0, 0, 16, 16, 30, 0, Math.PI / 2, 0); for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; P(gun, G.cyl6, steel, 26, Math.cos(a) * 4.5, Math.sin(a) * 4.5, 2.6, 2.6, 34, 0, Math.PI / 2, 0); } m.gun = gun;
+ const pod = this.group(torso, 12, 32, 18); P(pod, G.box, rust, 0, 0, 0, 30, 30, 22); for (let k = 0; k < 3; k++) P(pod, G.cyl, dark, 12, -10 + k * 10, 2, 6, 6, 20, 0, Math.PI / 2, 0); m.podGlow = P(pod, G.box, amber, 16, 0, 2, 2, 28, 10); m.pod = pod;
+ this.models.monster_supertank = m; }
+ // Hornet (boss2): flying insectoid gunship, two wing pairs, twin machinegun pods, rocket rack under the nose.
+ { const root = new T.Group(), m = { root }; this.world.add(root);
+ const body = this.group(root, 0, 0, 40); P(body, G.sphere, rust, 0, 0, 0, 62, 34, 24); P(body, G.sphere, flesh, -40, 0, -4, 46, 26, 22); P(body, G.sphere, dark, 34, 0, 4, 26, 22, 18);
+ m.eyes = [P(body, G.sphere, red, 52, 8, 8, 4, 4, 4), P(body, G.sphere, red, 52, -8, 8, 4, 4, 4)];
+ for (const s of [1, -1]) { P(body, G.cyl, steel, 22, s * 40, 30, 7, 7, 34, 0, Math.PI / 2, 0); P(body, G.box, dark, 6, s * 30, 22, 24, 20, 10); }
+ for (let k = 0; k < 4; k++) P(body, G.cyl, dark, 22, [16, 8, -8, -16][k], -24, 4, 4, 22, 0, Math.PI / 2, 0);
+ m.wings = []; const wingMat = this.keep(new T.MeshLambertMaterial({ color: 0x9fb2a0, transparent: true, opacity: 0.55, side: T.DoubleSide }));
+ for (const s of [1, -1]) for (const f of [12, -18]) { const w = this.group(body, f, s * 22, 18); const blade = P(w, G.box, wingMat, 0, s * 44, 0, 34, 88, 1.5); m.wings.push({ w, s, f }); }
+ for (const s of [1, -1]) for (const f of [20, 0, -20]) P(body, G.cyl6, dark, f, s * 18, -26, 2.5, 2.5, 22, s * 0.4, 0, 0);
+ m.body = body; this.models.monster_boss2 = m; }
+ // Jorg (boss3 walker): huge bipedal mech with twin chainguns and the Makron rider on top.
+ { const root = new T.Group(), m = { root }; this.world.add(root);
+ m.legs = [];
+ for (const s of [1, -1]) { const hip = this.group(root, -6, s * 46, 78); const thigh = P(hip, G.box, steel, 0, 0, -18, 34, 30, 44); const knee = this.group(hip, 0, 0, -38);
+ P(knee, G.box, dark, 8, 0, -16, 30, 26, 40); const foot = P(knee, G.box, steel, 14, 0, -38, 56, 36, 10); m.legs.push({ hip, knee, s }); }
+ const body = this.group(root, 0, 0, 84); P(body, G.box, steel, 0, 0, 22, 112, 104, 44); P(body, G.box, dark, 0, 0, 48, 80, 72, 12); P(body, G.box, rust, 50, 0, 18, 18, 60, 30);
+ m.vents = P(body, G.box, amber, 58, 0, 24, 2, 40, 6);
+ for (const s of [1, -1]) { const arm = this.group(body, 40, s * 47, 12); P(arm, G.box, dark, 0, 0, 0, 40, 26, 30); for (let k = 0; k < 4; k++) { const a = k * Math.PI / 2 + 0.785; P(arm, G.cyl6, steel, 34, Math.cos(a) * 7, Math.sin(a) * 7, 4, 4, 44, 0, Math.PI / 2, 0); } m['arm' + (s > 0 ? 'L' : 'R')] = arm; }
+ m.bfg = P(body, G.sphere, green, 6, -9, 27, 9, 9, 9);
+ const rider = this.group(body, -10, 0, 54); P(rider, G.box, purple, 0, 0, 14, 22, 30, 30); P(rider, G.sphere, flesh, 0, 0, 36, 10, 10, 12); P(rider, G.box, dark, 6, 18, 18, 14, 10, 26); m.rider = rider;
+ m.body = body; this.models.monster_jorg = m; }
+ // Makron: armoured cyborg; railgun on the right arm, BFG / hyperblaster cannon on the left.
+ { const root = new T.Group(), m = { root }; this.world.add(root);
+ m.legs = [];
+ for (const s of [1, -1]) { const hip = this.group(root, 0, s * 12, 46); P(hip, G.box, dark, 0, 0, -10, 16, 14, 26); const knee = this.group(hip, 0, 0, -24); P(knee, G.box, steel, 2, 0, -10, 14, 12, 24); P(knee, G.box, dark, 6, 0, -22, 24, 16, 6); m.legs.push({ hip, knee, s }); }
+ const torso = this.group(root, 0, 0, 48); P(torso, G.box, purple, 0, 0, 14, 28, 38, 30); P(torso, G.box, steel, 2, 0, 30, 22, 30, 10); P(torso, G.sphere, flesh, 4, 0, 42, 9, 9, 11); m.eyes = P(torso, G.box, red, 12, 0, 43, 2, 10, 3);
+ const rail = this.group(torso, -6, -8, 24); P(rail, G.box, dark, 0, 0, 0, 22, 12, 12); P(rail, G.cyl, steel, 22, 0, 0, 5, 5, 34, 0, Math.PI / 2, 0); m.railGlow = P(rail, G.cyl, cyan, 22, 0, 0, 2.5, 2.5, 36, 0, Math.PI / 2, 0); m.rail = rail;
+ const cannon = this.group(torso, 8, 20, 14); P(cannon, G.box, rust, 0, 0, 0, 26, 14, 16); P(cannon, G.cyl, dark, 16, 0, 0, 9, 9, 16, 0, Math.PI / 2, 0); m.cannonGlow = P(cannon, G.sphere, green, 25, 0, 0, 6, 6, 6); m.cannon = cannon;
+ m.torso = torso; this.models.monster_makron = m; }
+ // Tank Commander: a heavy biped (box -32..32 x -16..72), blaster on the right forearm, chaingun on the left, a
+ // rocket pack on the shoulder; skin 2 is the commander's darker red plating.
+ { const root = new T.Group(), m = { root }; this.world.add(root); const plate = this.std(0x8a3a2c), plateD = this.std(0x5a2a22);
+ m.legs = [];
+ for (const s of [1, -1]) { const hip = this.group(root, 0, s * 16, 22); P(hip, G.box, plateD, 0, 0, -10, 22, 18, 26); const knee = this.group(hip, 0, 0, -22); P(knee, G.box, steel, 4, 0, -8, 18, 16, 20); P(knee, G.box, dark, 10, 0, -16, 34, 22, 8); m.legs.push({ hip, knee, s }); }
+ const torso = this.group(root, 0, 0, 26); P(torso, G.box, plate, 0, 0, 18, 46, 56, 38); P(torso, G.box, plateD, -8, 0, 40, 34, 44, 12); P(torso, G.sphere, flesh, 14, 0, 44, 8, 9, 9); m.eye = P(torso, G.box, red, 22, 0, 46, 2, 10, 3);
+ const mgArm = this.group(torso, 8, 34, 14); P(mgArm, G.box, dark, 0, 0, 0, 30, 14, 14); const mg = this.group(mgArm, 22, 0, 0); for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; P(mg, G.cyl6, steel, 14, Math.cos(a) * 3.5, Math.sin(a) * 3.5, 2.2, 2.2, 26, 0, Math.PI / 2, 0); } m.mg = mg; m.mgArm = mgArm;
+ const blast = this.group(torso, 10, -32, 12); P(blast, G.box, steel, 0, 0, 0, 34, 14, 14); m.blastGlow = P(blast, G.sphere, amber, 18, 0, 0, 5, 5, 5);
+ const pod = this.group(torso, -14, 20, 46); P(pod, G.box, plateD, 0, 0, 0, 24, 20, 18); for (let k = 0; k < 3; k++) P(pod, G.cyl, dark, 8, -6 + k * 6, 2, 3.5, 3.5, 14, 0, Math.PI / 2, 0); m.podGlow = P(pod, G.box, amber, 14, 0, 2, 2, 18, 8); m.pod = pod;
+ m.torso = torso; this.models.monster_tank_commander = m; }
+ // Gladiator: a lanky biped (box -32..32 x -24..64) with a cleaver on the right arm and a railgun on the left.
+ { const root = new T.Group(), m = { root }; this.world.add(root); const hide = this.std(0x8a7a5a), armour = this.std(0x5a6a74);
+ m.legs = [];
+ for (const s of [1, -1]) { const hip = this.group(root, 0, s * 12, 6); P(hip, G.box, armour, 0, 0, -14, 12, 12, 28); const knee = this.group(hip, 0, 0, -26); P(knee, G.box, dark, 4, 0, -2, 12, 10, 10); m.legs.push({ hip, knee, s }); }
+ const torso = this.group(root, 0, 0, 8); P(torso, G.box, hide, 0, 0, 22, 26, 34, 34); P(torso, G.box, armour, 4, 0, 34, 22, 40, 12); P(torso, G.sphere, flesh, 6, 0, 48, 8, 8, 10); P(torso, G.box, red, 13, 0, 50, 2, 8, 2);
+ const cleaver = this.group(torso, 6, -26, 30); P(cleaver, G.box, armour, 0, 0, -8, 10, 10, 22); P(cleaver, G.box, steel, 14, 0, -18, 30, 3, 18); m.cleaver = cleaver;
+ const rail = this.group(torso, 8, 24, 26); P(rail, G.box, dark, 0, 0, 0, 22, 10, 10); P(rail, G.cyl, steel, 18, 0, 0, 3.5, 3.5, 26, 0, Math.PI / 2, 0); m.railGlow = P(rail, G.cyl, cyan, 18, 0, 0, 2.5, 2.5, 28, 0, Math.PI / 2, 0);
+ m.torso = torso; this.models.monster_gladiator = m; }
+ // Mutant: a hunched quadruped-ish brute (box -32..32 x -24..48), long clawed arms, no weapon.
+ { const root = new T.Group(), m = { root }; this.world.add(root); const skin = this.std(0xd8a882), bone = this.std(0xf4ead0);
+ m.legs = [];
+ for (const s of [1, -1]) { const hip = this.group(root, -10, s * 16, -2); P(hip, G.box, skin, 0, 0, -10, 14, 14, 24); P(hip, G.box, bone, 6, 0, -22, 18, 12, 4); m.legs.push({ hip, s }); }
+ const body = this.group(root, 0, 0, 4); P(body, G.sphere, skin, 0, 0, 18, 30, 26, 20); P(body, G.sphere, skin, 18, 0, 30, 16, 16, 14); P(body, G.sphere, flesh, 30, 0, 34, 9, 10, 9); P(body, G.box, red, 38, 4, 36, 2, 3, 2); P(body, G.box, red, 38, -4, 36, 2, 3, 2);
+ for (let k = 0; k < 5; k++) P(body, G.cone, bone, -10 + k * 7, 0, 36 - k * 1.5, 3, 3, 8);
+ for (const s of [1, -1]) { const arm = this.group(body, 16, s * 24, 28); P(arm, G.box, skin, 6, 0, -12, 10, 10, 28); for (let k = -1; k <= 1; k++) P(arm, G.cone, bone, 12, k * 3, -28, 2, 2, 10, Math.PI, 0, 0); m[s > 0 ? 'armL' : 'armR'] = arm; }
+ m.body = body; this.models.monster_mutant = m; }
+ for (const m of Object.values(this.models)) m.root.visible = false;
+ }
+ buildWeapons() { // first-person view models, drawn in their own pass over the world
+ this.vscene = new T.Scene(); this.vcam = new T.PerspectiveCamera(52, 854 / 480, 0.01, 10);
+ this.vscene.add(new T.HemisphereLight(0xfff0e0, 0x302820, 1.5)); const key = new T.DirectionalLight(0xffffff, 1.2); key.position.set(-0.4, 1, 0.6); this.vscene.add(key);
+ const G = this.geo, dark = this.std(0x2a2b2e), steel = this.std(0x7a7d82), brass = this.std(0x9a7a3a), wood = this.std(0x5a3c24), blue = this.glow(0x6ab8ff), orange = this.glow(0xffa040);
+ const box = (g, x, y, z, sx, sy, sz, m) => { const o = new T.Mesh(G.box, m); o.position.set(x, y, z); o.scale.set(sx, sy, sz); g.add(o); return o; };
+ const tube = (g, x, y, z, r, l, m) => { const o = new T.Mesh(G.cyl, m); o.position.set(x, y, z); o.scale.set(r, l, r); o.rotation.x = Math.PI / 2; g.add(o); return o; };
+ const W = this.vweapons = {};
+ const mk = (name, build) => { const g = new T.Group(), inner = new T.Group(); build(inner); inner.scale.setScalar(0.62); g.add(inner); g.userData.spin = inner.userData.spin; g.visible = false; this.vscene.add(g); W[name] = g; };
+ mk('blaster', g => { box(g, 0, 0, 0, 0.07, 0.09, 0.26, dark); tube(g, 0, 0.02, -0.17, 0.022, 0.12, steel); box(g, 0, -0.08, 0.06, 0.05, 0.12, 0.07, wood); box(g, 0, 0.055, -0.02, 0.03, 0.02, 0.12, orange); });
+ mk('shotgun', g => { tube(g, 0, 0.02, -0.12, 0.022, 0.5, steel); box(g, 0, -0.01, 0.1, 0.06, 0.07, 0.24, wood); box(g, 0, -0.025, -0.12, 0.05, 0.035, 0.18, wood); });
+ mk('supershotgun', g => { tube(g, -0.022, 0.02, -0.12, 0.022, 0.5, steel); tube(g, 0.022, 0.02, -0.12, 0.022, 0.5, steel); box(g, 0, -0.01, 0.12, 0.08, 0.08, 0.22, wood); });
+ mk('machinegun', g => { box(g, 0, 0, 0, 0.07, 0.08, 0.34, dark); tube(g, 0, 0.01, -0.24, 0.018, 0.16, steel); box(g, 0, -0.09, -0.02, 0.04, 0.12, 0.05, brass); });
+ mk('chaingun', g => { const spin = new T.Group(); for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; tube(spin, Math.cos(a) * 0.035, Math.sin(a) * 0.035, -0.18, 0.012, 0.42, steel); } g.add(spin); g.userData.spin = spin; box(g, 0, -0.02, 0.1, 0.12, 0.12, 0.2, dark); });
+ mk('rocketlauncher', g => { tube(g, 0, 0.03, -0.08, 0.055, 0.6, this.std(0x44523a)); box(g, 0, -0.06, 0.08, 0.06, 0.1, 0.12, dark); tube(g, 0, 0.03, -0.39, 0.06, 0.03, steel); });
+ mk('hyperblaster', g => { const spin = new T.Group(); for (let k = 0; k < 4; k++) { const a = k * Math.PI / 2; tube(spin, Math.cos(a) * 0.03, Math.sin(a) * 0.03, -0.2, 0.012, 0.38, steel); } g.add(spin); g.userData.spin = spin; box(g, 0, -0.03, 0.08, 0.1, 0.1, 0.2, dark); box(g, 0, 0.06, 0.06, 0.04, 0.02, 0.16, orange); });
+ mk('railgun', g => { box(g, 0, 0, -0.06, 0.07, 0.07, 0.6, dark); tube(g, 0, 0.0, -0.06, 0.03, 0.62, blue); box(g, 0, -0.07, 0.12, 0.05, 0.1, 0.1, steel); });
+ this.vflash = new T.Mesh(G.sphere, this.glow(0xffd890, 0.9)); this.vflash.scale.setScalar(0.045); this.vflash.visible = false; this.vscene.add(this.vflash);
+ }
+ // ---------------- per-frame update ----------------
+ render(g, ctx) {
+ if (this.closed || this.renderer.getContext().isContextLost()) { this.ready = false; this.error = this.closed ? '3D renderer is closed' : 'WebGL context lost'; throw Error(this.error); }
+ const t0 = performance.now();
+ try {
+ const p = g.ents[1], time = g.ms / 1000;
+ const eye = [p.origin[0], p.origin[1], p.origin[2] + (p.viewheight || 22)];
+ const ang = p.health > 0 ? p.v_angle : [-15, p.v_angle[1], 40];
+ qv(eye[0], eye[1], eye[2] - (p.health > 0 ? 0 : 16), this.camera.position);
+ const cp = Math.cos(ang[0] * DEG), sp = Math.sin(ang[0] * DEG), cy = Math.cos(ang[1] * DEG), sy = Math.sin(ang[1] * DEG);
+ const look = qv(eye[0] + cp * cy * 100, eye[1] + cp * sy * 100, eye[2] - sp * 100);
+ this.camera.up.set(0, 1, 0); this.camera.lookAt(look);
+ this.camera.rotateZ(-(ang[2] || 0) * DEG);
+ this.updateBosses(g, time); this.updateMissiles(g, time); this.updateFx(g, time); this.updateItems(g, time);
+ this.renderer.info.reset(); this.renderer.clear(); this.renderer.render(this.world, this.camera);
+ this.updateViewWeapon(g, p, time);
+ this.renderer.clearDepth(); this.renderer.render(this.vscene, this.vcam);
+ ctx.drawImage(this.view, 0, 0, 854, 480);
+ this.times.push(performance.now() - t0); if (this.times.length > 120) this.times.shift();
+ this.ready = true; this.error = null;
+ } catch (e) { this.ready = false; this.error = String(e && e.stack || e); throw e; }
+ }
+ updateBosses(g, time) {
+ for (const m of Object.values(this.models)) m.root.visible = false;
+ for (let i = 2; i < g.ents.length; i++) {
+ const e = g.ents[i];
+ if (!e.inuse || !this.models[e.classname] || e.gibbed) continue;
+ const m = this.models[e.classname], def = Q.MONSTERS[e.classname], mi = e.monsterinfo || {}, mv = def.moves[mi.currentmove] || def.moves.stand;
+ const f = Math.max(0, e.frame - mv.first), n = mv.last - mv.first + 1, ph = f / n, move = mi.currentmove || 'stand';
+ // A monster moves its ai_run distance on its 100 ms think; the original client spreads that step over the next
+ // server frame (cl_ents.c lerpfrac). The state keeps the step as e.lerp, read-only here.
+ const lf = e.lerp ? Math.max(0, 1 - (g.ms - e.lerp[3]) / Q.FRAMETIME_MS) : 0, lo = lf ? e.lerp : [0, 0, 0];
+ m.root.visible = true; qv(e.origin[0] + lo[0] * lf, e.origin[1] + lo[1] * lf, e.origin[2] + lo[2] * lf, m.root.position); m.root.rotation.set(0, e.angles[1] * DEG, 0);
+ const dying = e.deadflag === Q.DEAD_DEAD, hurt = e.skinnum === 1;
+ if (e.classname === 'monster_supertank') {
+ const walk = move === 'run' || move === 'forward';
+ m.treadL.position.y = (walk ? Math.sin(ph * Math.PI * 4) * 1.2 : 0) * S; m.treadR.position.y = (walk ? -Math.sin(ph * Math.PI * 4) * 1.2 : 0) * S;
+ m.torso.rotation.y = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.18 : 0;
+ m.gun.rotation.x = move === 'attack1' ? time * 9 : 0;
+ const charging = move === 'attack2' && e.frame >= 20 && e.frame < 34;
+ m.pod.rotation.z = charging ? -0.25 : 0; m.podGlow.visible = charging; m.podGlow.material.opacity = 1;
+ m.hull.rotation.z = dying ? Math.min(1, ph * 1.3) * 0.3 : 0; m.root.position.y -= dying ? ph * 22 * S : 0;
+ m.eye.visible = !dying;
+ } else if (e.classname === 'monster_boss2') {
+ for (const w of m.wings) w.w.rotation.x = w.s * (Math.sin(time * 38 + w.f) * 0.5 + 0.2);
+ const pitch = move === 'attack_rocket' ? -0.12 : move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.3 : 0;
+ m.body.rotation.z = pitch + (dying ? -ph * 0.8 : 0); m.body.rotation.x = Math.sin(time * 2.1) * 0.05 + (dying ? ph * 0.6 : 0);
+ m.body.position.y = (40 + Math.sin(time * 3) * 2) * S;
+ } else if (e.classname === 'monster_jorg') {
+ const walk = move === 'run' || move === 'walk';
+ for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.35; L.knee.rotation.z = -Math.max(0, a) * 0.5; }
+ const fire = move === 'attack1' || move === 'start_attack1';
+ m.armL.rotation.x = fire ? time * 6 : 0; m.armR.rotation.x = fire ? -time * 6 : 0;
+ m.bfg.visible = !dying; m.bfg.scale.setScalar((move === 'attack2' && e.frame < 25 ? 9 + (e.frame - 18) * 1.6 : 6) * S);
+ m.body.rotation.z = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.12 : dying ? Math.min(1, ph * 1.2) * 0.35 : 0;
+ m.root.position.y -= dying ? Math.max(0, ph - 0.5) * 50 * S : 0;
+ m.rider.visible = !(dying && e.frame >= 79);
+ } else if (e.classname === 'monster_makron') {
+ const walk = move === 'run' || move === 'walk';
+ for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.5; L.knee.rotation.z = -Math.max(0, a) * 0.6; }
+ const railCharge = move === 'attack5' && e.frame <= 243, sweep = move === 'attack4' && e.frame >= 213 && e.frame <= 229, bfgCharge = move === 'attack3' && e.frame <= 204;
+ m.railGlow.visible = railCharge; m.railGlow.scale.set(2.5 * S * (1 + (e.frame - 235) * 0.12), 36 * S, 2.5 * S * (1 + (e.frame - 235) * 0.12));
+ m.rail.rotation.z = railCharge ? 0.1 : 0;
+ m.cannon.rotation.y = sweep ? (e.frame <= 221 ? -(221 - e.frame) * 10 : (229 - e.frame) * 10) * DEG : 0;
+ m.cannonGlow.visible = bfgCharge || sweep; m.cannonGlow.scale.setScalar((bfgCharge ? 6 + (e.frame - 201) * 2 : 4) * S);
+ m.torso.rotation.z = move === 'sight' ? Math.sin(ph * Math.PI) * -0.2 : move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.25 : dying ? Math.min(1, ph * 1.4) * 1.2 : 0;
+ m.root.position.y -= dying ? Math.max(0, ph - 0.6) * 40 * S : 0;
+ } else if (e.classname === 'monster_tank_commander') {
+ const walk = move === 'run' || move === 'start_run' || move === 'walk';
+ for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.4; L.knee.rotation.z = -Math.max(0, a) * 0.5; }
+ m.mg.rotation.x = move === 'attack_chain' ? time * 12 : 0;
+ m.mgArm.rotation.y = move === 'attack_chain' && e.frame >= 173 && e.frame <= 191 ? (e.frame <= 182 ? -(e.frame - 178) * 8 : (e.frame - 186) * 8) * DEG : 0;
+ m.blastGlow.visible = move === 'attack_blast' || move === 'reattack_blast';
+ const pre = move === 'attack_pre_rocket' || move === 'attack_fire_rocket'; m.podGlow.visible = pre; m.pod.rotation.z = pre ? -0.3 : 0;
+ m.torso.rotation.z = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.2 : dying ? Math.min(1, ph * 1.3) * 0.9 : 0;
+ m.root.position.y -= dying ? Math.max(0, ph - 0.5) * 30 * S : 0;
+ } else if (e.classname === 'monster_gladiator') {
+ const walk = move === 'run' || move === 'walk';
+ for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.6; L.knee.rotation.z = -Math.max(0, a) * 0.7; }
+ const swing = move === 'attack_melee', railing = move === 'attack_gun' && e.frame <= 49;
+ m.cleaver.rotation.z = swing ? Math.sin(ph * Math.PI * 4) * 1.1 : 0.2;
+ const charge = 1 + Math.max(0, Math.min(3, e.frame - 46)) * 0.35; m.railGlow.visible = railing; m.railGlow.scale.set(2.5 * S * charge, 30 * S, 2.5 * S * charge);
+ m.torso.rotation.z = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.3 : dying ? Math.min(1, ph * 1.4) * 1.3 : 0;
+ m.root.position.y -= dying ? Math.max(0, ph - 0.6) * 40 * S : 0;
+ } else if (e.classname === 'monster_mutant') {
+ const walk = move === 'run' || move === 'walk' || move === 'start_walk';
+ for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.7; }
+ const claw = move === 'attack', leap = move === 'jump';
+ m.armL.rotation.z = claw ? Math.sin(ph * Math.PI * 2) * 1.2 : leap ? -1.2 : 0.3; m.armR.rotation.z = claw ? -Math.sin(ph * Math.PI * 2 + 1) * 1.2 : leap ? -1.2 : 0.3;
+ m.body.rotation.z = leap ? -0.5 : move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.4 : dying ? Math.min(1, ph * 1.5) * 1.4 : 0;
+ m.root.position.y -= dying ? Math.max(0, ph - 0.5) * 30 * S : 0;
+ }
+ for (const mat of [this.bossMats.red]) mat.color.setHex(hurt ? 0xff8040 : 0xff3010);
+ }
+ // Railgun aim lines once the target point is locked (Makron: MakronSaveloc on frame 242, fires on 243; Gladiator:
+ // gladiator_attack saves pos1 in the tick it picks attack_gun, still on the previous move's frame, and fires on frame
+ // 49, four ticks later). The line is the exact shot line.
+ for (const l of this.aimLines) l.visible = false;
+ let ai = 0;
+ for (let i = 2; i < g.ents.length && ai < this.aimLines.length; i++) {
+ const e = g.ents[i];
+ if (!e.inuse || e.deadflag || !e.monsterinfo) continue;
+ let ofs = null;
+ if (e.classname === 'monster_makron' && e.monsterinfo.currentmove === 'attack5' && e.frame === 242) ofs = [-17.3, 7.8, 72.4];
+ else if (e.classname === 'monster_gladiator' && e.monsterinfo.currentmove === 'attack_gun' && e.frame <= 48) ofs = [30.0, 18.0, 28.0];
+ if (!ofs) continue;
+ const av = Q.angleVectors(e.angles), start = Q.projectSource(e.origin, ofs, av.forward, av.right), dir = Q.norm(Q.sub(e.pos1, start)), end = Q.ma(start, 2400, dir);
+ this.setLine(this.aimLines[ai++], start, end);
+ }
+ }
+ setLine(line, a, b) {
+ const arr = line.geometry.attributes.position.array, A = qv(a[0], a[1], a[2]), Bv = qv(b[0], b[1], b[2]);
+ arr[0] = A.x; arr[1] = A.y; arr[2] = A.z; arr[3] = Bv.x; arr[4] = Bv.y; arr[5] = Bv.z;
+ line.geometry.attributes.position.needsUpdate = true; line.geometry.computeBoundingSphere(); line.visible = true;
+ }
+ orient(obj, origin, vel) {
+ qv(origin[0], origin[1], origin[2], obj.position);
+ const yaw = Math.atan2(vel[1], vel[0]), pitch = Math.atan2(vel[2], Math.hypot(vel[0], vel[1]));
+ obj.rotation.set(0, yaw, pitch, 'YZX');
+ }
+ updateMissiles(g, time) {
+ let r = 0, b = 0, f = 0, l = 0;
+ for (const o of [...this.rockets, ...this.bolts, ...this.bfgs, ...this.lasers]) o.visible = false;
+ for (let i = 2; i < g.ents.length; i++) {
+ const e = g.ents[i];
+ if (!e.inuse) continue;
+ if (e.classname === 'rocket' && r < this.rockets.length) { const o = this.rockets[r++]; this.orient(o, e.origin, e.velocity); o.visible = true; }
+ else if (e.classname === 'bolt' && b < this.bolts.length) { const o = this.bolts[b++]; this.orient(o, e.origin, e.velocity); o.visible = true; }
+ else if (e.classname === 'bfg blast' && f < this.bfgs.length) {
+ const o = this.bfgs[f++]; qv(e.origin[0], e.origin[1], e.origin[2], o.position); o.visible = true;
+ const exploding = e.think === 'bfg_explode' || e.effect === 'bfgexplode';
+ o.children[0].scale.setScalar((exploding ? 40 + (e.frame || 0) * 30 : 14 + Math.sin(time * 20) * 2) * S); o.children[2].visible = !exploding;
+ for (const end of e.lasers || []) if (l < this.lasers.length) this.setLine(this.lasers[l++], e.origin, end);
+ }
+ }
+ }
+ updateFx(g, time) {
+ let bo = 0, pu = 0, tr = 0, rc = 0, gi = 0, fl = 0;
+ for (const o of [...this.booms, ...this.puffs, ...this.tracers, ...this.railCores, ...this.railSpirals, ...this.gibs, ...this.flashes]) o.visible = false;
+ let flash = 0, boom = 0, flashPos = null, boomPos = null;
+ for (const fx of g.fx) {
+ const age = (g.ms - fx.t0) / fx.life;
+ if (age < 0 || age > 1) continue;
+ if (fx.kind === 'explosion' && bo < this.booms.length) {
+ const o = this.booms[bo++], s = (fx.big ? 70 : 48) * (0.35 + age * 0.8);
+ qv(fx.o[0], fx.o[1], fx.o[2], o.position); o.scale.setScalar(s * S); o.rotation.set(fx.id, fx.id * 1.3, 0); o.visible = true;
+ o.children[0].material.opacity = 0.85 * (1 - age); if (1 - age > boom) { boom = 1 - age; boomPos = fx.o; }
+ } else if ((fx.kind === 'blood' || fx.kind === 'puff' || fx.kind === 'spark' || fx.kind === 'blasterhit') && pu < this.puffs.length) {
+ const o = this.puffs[pu++]; qv(fx.o[0], fx.o[1], fx.o[2] + age * 10, o.position); o.scale.setScalar((fx.kind === 'blood' ? 5 : 3.5) * (1 + age) * S);
+ o.material = fx.kind === 'blood' ? this.mats.blood : fx.kind === 'puff' ? this.mats.puff : this.mats.spark; o.visible = true;
+ } else if (fx.kind === 'tracer' && fx.from === 'monster' && tr < this.tracers.length) {
+ this.setLine(this.tracers[tr++], fx.o, fx.to);
+ } else if (fx.kind === 'rail' && rc < this.railCores.length) {
+ this.setLine(this.railCores[rc], fx.o, fx.to);
+ const sp = this.railSpirals[rc++], arr = sp.geometry.attributes.position.array, d = Q.sub(fx.to, fx.o), L = Q.len(d), dir = Q.norm(d);
+ const side = Q.norm(Q.cross(dir, Math.abs(dir[2]) < 0.9 ? [0, 0, 1] : [1, 0, 0])), up = Q.cross(side, dir), n = arr.length / 3, v = new T.Vector3();
+ for (let k = 0; k < n; k++) { const t = k / (n - 1), a = t * L / 18, rr = 5 + age * 6, p = Q.ma(Q.ma(Q.ma(fx.o, t * L, dir), Math.cos(a) * rr, side), Math.sin(a) * rr, up); qv(p[0], p[1], p[2], v); arr[k * 3] = v.x; arr[k * 3 + 1] = v.y; arr[k * 3 + 2] = v.z; }
+ sp.geometry.attributes.position.needsUpdate = true; sp.geometry.computeBoundingSphere(); sp.visible = true;
+ sp.material.opacity = 0.9 * (1 - age); this.railCores[rc - 1].material.opacity = 0.9 * (1 - age);
+ } else if (fx.kind === 'mflash' && fl < this.flashes.length) {
+ const o = this.flashes[fl++]; qv(fx.o[0], fx.o[1], fx.o[2], o.position); o.scale.setScalar((fx.weapon === 'bfg' ? 14 : fx.weapon === 'rocket' ? 9 : 6) * S); o.visible = true;
+ flash = 1; flashPos = fx.o;
+ } else if (fx.kind === 'railcharge' && fl < this.flashes.length) {
+ const e = g.ents[fx.owner]; if (!e || !e.inuse) continue;
+ }
+ }
+ for (let i = 2; i < g.ents.length && gi < this.gibs.length; i++) {
+ const e = g.ents[i];
+ if (!e.inuse || (e.classname !== 'gib' && e.classname !== 'debris')) continue;
+ const o = this.gibs[gi++]; qv(e.origin[0], e.origin[1], e.origin[2], o.position); o.rotation.set(e.angles[0] * DEG, e.angles[1] * DEG, e.angles[2] * DEG);
+ o.scale.setScalar((e.classname === 'debris' ? 3 : e.head ? 9 : e.gib === 'chest' ? 8 : 5) * S);
+ o.material = e.classname === 'debris' ? this.mats.debris : e.gib === 'metal' || e.gib === 'gear' ? this.mats.gibMetal : this.mats.meat; o.visible = true;
+ }
+ this.flashLight.intensity = flash ? 2.2 : 0; if (flashPos) qv(flashPos[0], flashPos[1], flashPos[2], this.flashLight.position);
+ this.boomLight.intensity = boom * 3.2; if (boomPos) qv(boomPos[0], boomPos[1], boomPos[2] + 24, this.boomLight.position);
+ }
+ updateItems(g, time) {
+ const seen = new Set();
+ for (let i = 2; i < g.ents.length; i++) {
+ const e = g.ents[i];
+ if (!e.inuse || e.solid !== Q.SOLID_TRIGGER || !e.item) continue;
+ let o = this.items[i];
+ if (!o || o.userData.item !== e.item) { if (o) this.world.remove(o); o = this.items[i] = this.itemModel(e.item); this.world.add(o); }
+ seen.add(String(i)); o.visible = true;
+ qv(e.origin[0], e.origin[1], e.origin[2] - 6 + Math.sin(time * 2.4 + i) * 3, o.position); o.rotation.y = time * 1.6 + i;
+ }
+ for (const k of Object.keys(this.items)) if (!seen.has(k)) this.items[k].visible = false;
+ }
+ itemModel(item) {
+ const g = new T.Group(); g.userData.item = item; const G = this.geo, m = this.itemMat[item] || this.itemMat.health;
+ const add = (geo, mat, x, y, z, sx, sy, sz) => { const o = new T.Mesh(geo, mat); o.position.set(x * S, z * S, -y * S); o.scale.set(sx * S, sz * S, sy * S); g.add(o); return o; };
+ if (item.startsWith('health') || item === 'stimpack') {
+ const s = item === 'health_large' ? 1.3 : item === 'stimpack' ? 0.55 : 1;
+ add(G.box, m, 0, 0, 0, 22 * s, 16 * s, 14 * s); add(G.box, this.crossMat, 0, 0, 7.5 * s, 14 * s, 4 * s, 1); add(G.box, this.crossMat, 0, 0, 7.5 * s, 4 * s, 14 * s, 1);
+ } else if (item === 'armor_shard') { add(G.ico, m, 0, 0, 2, 7, 7, 10); }
+ else if (item.startsWith('armor')) { add(G.box, m, 0, 0, 0, 10, 26, 24); add(G.box, m, 4, 0, 10, 8, 30, 6); }
+ else { add(G.box, m, 0, 0, 0, 18, 14, 12); add(G.box, this.std(0xd8d0b0), 0, 0, 6.5, 12, 10, 1); }
+ return g;
+ }
+ updateViewWeapon(g, p, time) {
+ for (const w of Object.values(this.vweapons)) w.visible = false;
+ this.vflash.visible = false;
+ if (p.health <= 0 || !p.weapon) return;
+ const w = this.vweapons[p.weapon]; if (!w) return;
+ const def = Q.WDEF[p.weapon], [act, fireLast, idleLast, deact] = def.frames;
+ let drop = 0;
+ if (p.weaponstate === 2) drop = (p.gunframe - idleLast) / Math.max(1, deact - idleLast);
+ else if (p.weaponstate === 1) drop = 1 - p.gunframe / Math.max(1, act);
+ const speed = Math.hypot(p.velocity[0], p.velocity[1]), bob = p.groundentity >= 0 ? Math.min(1, speed / 300) : 0;
+ const since = g.ms - (p.fired || -9999), recoil = since >= 0 && since < 200 ? (1 - since / 200) : 0;
+ w.visible = true;
+ w.position.set(0.15 + Math.cos(time * 7.5) * 0.008 * bob, -0.13 - drop * 0.25 + Math.abs(Math.sin(time * 7.5)) * 0.008 * bob, -0.34 + recoil * 0.035);
+ w.rotation.set(recoil * 0.12, 0, 0);
+ if (w.userData.spin && p.weaponstate === 3) w.userData.spin.rotation.z = time * 14;
+ if (since >= 0 && since < 100) { this.vflash.visible = true; this.vflash.position.set(0.15, -0.11 - drop * 0.25, -0.55); this.vflash.scale.setScalar(0.03); }
+ }
+ metrics() {
+ const sorted = [...this.times].sort((a, b) => a - b), info = this.renderer.info;
+ return { renderer: 'webgl-quake2', drawCalls: info.render.calls, triangles: info.render.triangles, samples: sorted.length,
+ cpuRenderMsP50: sorted.length ? sorted[Math.floor((sorted.length - 1) * 0.5)] : null, cpuRenderMsP95: sorted.length ? sorted[Math.floor((sorted.length - 1) * 0.95)] : null };
+ }
+ close() { if (this.closed) return; this.closed = true; this.ready = false; for (const r of this.resources) r.dispose && r.dispose(); this.renderer.dispose(); this.renderer.forceContextLoss(); this.resources = []; }
+ }
+ R.render = (g, ctx) => {
+ let m = byCanvas.get(ctx.canvas); if (!m) { m = new Map(); byCanvas.set(ctx.canvas, m); }
+ let s = m.get(g.key); if (!s || s.closed) { s = new Scene(g.key, ctx.canvas); m.set(g.key, s); }
+ s.render(g, ctx); m.last = s; return s;
+ };
+ R.status = ctx => {
+ const m = ctx && byCanvas.get(ctx.canvas); let ready = false, error = null;
+ if (m) for (const s of m.values()) { if (!s.closed && s.renderer.getContext().isContextLost()) { s.ready = false; s.error = 'WebGL context lost'; } ready = ready || (s.ready && !s.closed); error = error || s.error; }
+ return { renderer: 'webgl-quake2', kind: 'perspective', ready, error };
+ };
+ R.metrics = ctx => { const m = ctx && byCanvas.get(ctx.canvas); return m && m.last && !m.last.closed ? m.last.metrics() : null; };
+ R.close = ctx => { const m = ctx && byCanvas.get(ctx.canvas); if (!m) return; for (const s of m.values()) s.close(); byCanvas.delete(ctx.canvas); };
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/quake2_remake/scripted.js b/environments/games/web/games/quake2_remake/scripted.js
new file mode 100644
index 0000000000000000000000000000000000000000..0c1eeeae75349a99dc7a2dde5e32b6d82914e73b
--- /dev/null
+++ b/environments/games/web/games/quake2_remake/scripted.js
@@ -0,0 +1,308 @@
+/* Quake II boss arenas - the standard scripted reference controller (BossBench, not part of the original game).
+ Quake2Game.scripted(game) is called once per 200 ms packet with the live simulation. It reads privileged state,
+ looks ahead on deep copies (M.copyGame never touches the live RNG or state), and returns only legal packets:
+ six hold sets of at most four keys and one mouse delta. Deterministic: no Math.random, no clock.
+ At 60 Hz (q2-arena@3) a packet is twelve ticks, two per hold set; the controller holds its move keys in all six
+ sets and taps weapon keys in sets 1-3 so the press lands on the first tick and is released after 100 ms. */
+(function (root) {
+ 'use strict';
+ const N = root.NativeBench, M = root.Quake2Game, Q = M.Q;
+ const MOUSE_DEG = Q.CL.m_yaw * Q.CL.sensitivity; // 0.066 degrees per mouse count
+ const memory = new WeakMap();
+ const angleDiff = a => ((a % 360) + 540) % 360 - 180;
+ const MOVES = [[], ['W'], ['S'], ['A'], ['D'], ['W', 'A'], ['W', 'D'], ['S', 'A'], ['S', 'D']];
+ const SPEED = { rocketlauncher: 650, hyperblaster: 1000, blaster: 1000 };
+ const LOOK = Math.round(1.4 * M.hz); // look-ahead per candidate move: 1.4 s (14 ticks at @2)
+ M.LOOK_K = 1; // blinded futures per candidate move (see M.scripted)
+
+ // The copies get their own rand() state, so the controller plans with the rules but without knowing the live dice
+ // (bullet spread, the boss's next attack choice): it cannot dodge by reading the future RNG. Since q2-arena@3 the
+ // copy's state is a function of the tick only, not of the live holdrand: with it derived from the live value the
+ // packet still depended on the real dice (leak probe: decision invariance 0.63-0.75, tools/leak60.js).
+ function simulate(g, keys, mouseTicks, ticks, k = 0) {
+ const h = M.copyGame(g), ks = new Set(keys), none = new Set();
+ let x = Math.imul((g.t + 0x9e3779b9 + Math.imul(k, 0x632be5ab)) >>> 0, 0x85ebca6b) >>> 0; x ^= x >>> 13; x = Math.imul(x, 0xc2b2ae35) >>> 0; x ^= x >>> 16;
+ h.rnd = x >>> 0;
+ // At 60 Hz the shared per-tick quantize (a walk over the whole state) was 87 % of the controller's time; the copy is
+ // a plan, not a replay, so it is quantized once at the end (still deterministic; off by micro-units at most).
+ for (let t = 0; t < ticks && !h.outcome; t++) {
+ h.events = [];
+ h.update(ks, none, mouseTicks[t] || [0, 0, 0]); // the turn happens in the first packet only
+ h.t++;
+ }
+ N.quantize(h);
+ return h;
+ }
+ const center = e => Q.center(e);
+ const eyeOf = p => [p.origin[0], p.origin[1], p.origin[2] + p.viewheight];
+ function lineOfFire(g, from, to, boss) {
+ const tr = Q.trace(g, from, null, null, to, 1, Q.MASK_SHOT);
+ return tr.ent === boss || tr.fraction === 1;
+ }
+ // Weapon wanted for this target: highest-value weapon with ammo whose range rule holds.
+ function wantWeapon(g, p, b, dist) {
+ const has = (w, ammo, n = 1) => p.inv[w] && (!ammo || p.inv[ammo] >= n);
+ const surface = dist - (b.maxs[0] || 0);
+ const order = [];
+ if (b.classname === 'monster_supertank') {
+ // Rockets from RANGE_MID, then the machinegun from mid range; the shotguns are the last resort: their range puts
+ // the player in RANGE_NEAR (attack checks 5x as often) or inside 160 units (always the chaingun).
+ if (surface > 150) order.push(['rocketlauncher', 'rockets']);
+ order.push(['machinegun', 'bullets'], ['supershotgun', 'shells', 2], ['shotgun', 'shells']);
+ } else if (b.classname === 'monster_boss2') {
+ // Railgun first: hitscan 150 suits peek-shoot-hide against a flier (rockets and bolts miss it often).
+ order.push(['railgun', 'slugs'], ['chaingun', 'bullets'], ['hyperblaster', 'cells']);
+ } else if (b.classname === 'monster_jorg') {
+ if (dist < 800) order.push(['chaingun', 'bullets', 20]);
+ order.push(['hyperblaster', 'cells'], ['railgun', 'slugs']);
+ if (surface > 190) order.push(['rocketlauncher', 'rockets']);
+ } else if (b.classname === 'monster_tank_commander') {
+ // Rockets from range (750 health per hit-set is a lot of 8-damage bullets); the chaingun when it is close.
+ if (surface > 150) order.push(['rocketlauncher', 'rockets']);
+ order.push(['chaingun', 'bullets', 20], ['supershotgun', 'shells', 2], ['machinegun', 'bullets']);
+ } else if (b.classname === 'monster_gladiator') {
+ // Keep outside the cleaver: rockets and the hyperblaster from mid range.
+ if (surface > 150) order.push(['rocketlauncher', 'rockets']);
+ order.push(['hyperblaster', 'cells'], ['chaingun', 'bullets', 20], ['supershotgun', 'shells', 2]);
+ } else if (b.classname === 'monster_mutant') {
+ // No ranged attack to answer: shotguns at close range, the chaingun while kiting.
+ if (dist < 420) order.push(['supershotgun', 'shells', 2]);
+ order.push(['chaingun', 'bullets', 20], ['machinegun', 'bullets'], ['supershotgun', 'shells', 2]);
+ } else {
+ order.push(['railgun', 'slugs'], ['hyperblaster', 'cells'], ['chaingun', 'bullets']);
+ if (surface > 190) order.push(['rocketlauncher', 'rockets']);
+ }
+ order.push(['machinegun', 'bullets'], ['shotgun', 'shells'], ['supershotgun', 'shells', 2], ['blaster', null]);
+ for (const [w, ammo, n] of order) if (has(w, ammo, n || 1)) return w;
+ return 'blaster';
+ }
+ // Hitscan streams that keep firing while the boss can see the player: the counter is to break line of sight. The
+ // Hornet's 0.9 s pre-mg windup deals no damage, so the controller keeps shooting through it and hides on attack_mg.
+ const STREAM = { monster_supertank: ['attack1'], monster_boss2: ['attack_mg'], monster_jorg: ['start_attack1', 'attack1'],
+ monster_tank_commander: ['attack_chain'] };
+ const PREFERRED = {
+ monster_supertank: [['rocketlauncher', 'rockets'], ['machinegun', 'bullets']],
+ monster_boss2: [['railgun', 'slugs'], ['chaingun', 'bullets'], ['hyperblaster', 'cells']],
+ monster_jorg: [['chaingun', 'bullets'], ['hyperblaster', 'cells'], ['railgun', 'slugs'], ['rocketlauncher', 'rockets']],
+ monster_makron: [['railgun', 'slugs'], ['hyperblaster', 'cells'], ['chaingun', 'bullets'], ['rocketlauncher', 'rockets']],
+ monster_tank_commander: [['rocketlauncher', 'rockets'], ['chaingun', 'bullets']],
+ monster_gladiator: [['rocketlauncher', 'rockets'], ['hyperblaster', 'cells'], ['chaingun', 'bullets']],
+ monster_mutant: [['supershotgun', 'shells'], ['chaingun', 'bullets']],
+ };
+ // Cover spots: points beside the arena's cover brushes (not the shell) that the boss's eye cannot see.
+ function hiddenSpots(g, b) {
+ const be = [b.origin[0], b.origin[1], b.origin[2] + b.viewheight], out = [], brushes = Q.worlds[g.key].brushes;
+ for (let k = 6; k < brushes.length; k++) {
+ const br = brushes[k];
+ if (br.maxs[2] < 64) continue; // too low to hide behind
+ const cx = (br.mins[0] + br.maxs[0]) / 2, cy = (br.mins[1] + br.maxs[1]) / 2;
+ for (const [px, py] of [[br.mins[0] - 40, cy], [br.maxs[0] + 40, cy], [cx, br.mins[1] - 40], [cx, br.maxs[1] + 40],
+ [br.mins[0] - 40, br.mins[1] - 40], [br.maxs[0] + 40, br.mins[1] - 40], [br.mins[0] - 40, br.maxs[1] + 40], [br.maxs[0] + 40, br.maxs[1] + 40]]) {
+ const pt = [px, py, br.mins[2] + 24];
+ if (Q.pointcontents(g, pt) & Q.CONTENTS_SOLID) continue;
+ if (Q.trace(g, be, null, null, [px, py, pt[2] + 22], -1, Q.MASK_OPAQUE).fraction < 1) out.push(pt);
+ }
+ }
+ return out;
+ }
+ // Stalemate breaker (5 s without sight, while the normal seek after 1 s has not found the boss): the nearest point the
+ // player can walk to in a straight line from which the boss's eye is visible now. Without it, player and boss can
+ // mirror each other on the two sides of a full-height pillar (each one's distance term only matches the other's
+ // position along the pillar, and a 1.4 s straight look-ahead never comes out of it).
+ function sightSpot(g, b, p) {
+ const be = [b.origin[0], b.origin[1], b.origin[2] + b.viewheight];
+ let best = null, bestD = 1e9;
+ for (const r of [96, 192, 288, 384]) {
+ for (let k = 0; k < 16; k++) {
+ const a = k * Math.PI / 8, pt = [p.origin[0] + Q.cos(a) * r, p.origin[1] + Q.sin(a) * r, p.origin[2]];
+ if (r >= bestD) continue;
+ if (Q.trace(g, p.origin, [-16, -16, -24], [16, 16, 32], pt, 1, Q.MASK_SOLID).fraction < 1) continue;
+ if (Q.trace(g, [pt[0], pt[1], pt[2] + p.viewheight], null, null, be, -1, Q.MASK_OPAQUE).fraction < 1) continue;
+ best = pt; bestD = r;
+ }
+ if (best) break;
+ }
+ return best;
+ }
+ // The boss's view of a candidate player position: eye-to-eye trace through the world only.
+ const seenBy = (g, b, q) => Q.trace(g, [b.origin[0], b.origin[1], b.origin[2] + b.viewheight], null, null, [q.origin[0], q.origin[1], q.origin[2] + q.viewheight], -1, Q.MASK_OPAQUE).fraction === 1;
+ function threats(h) { // enemy projectiles and BFG orbs near the player at the end of a look-ahead
+ const p = h.ents[1]; let s = 0;
+ for (const e of h.ents) {
+ if (!e.inuse || e.owner === 1 || e.owner < 0) continue;
+ if (e.classname === 'rocket') {
+ const v = Q.norm(e.velocity), rel = Q.sub(p.origin, e.origin), along = Q.dot(rel, v);
+ if (along > 0) { const off = Q.len(Q.sub(rel, Q.scale(v, along))); s += Math.max(0, 110 - off) * (along < 700 ? 1 : 0.3); }
+ } else if (e.classname === 'bfg blast') {
+ const dd = Q.len(Q.sub(p.origin, e.origin)); s += Math.max(0, 420 - dd) * 2.5;
+ } else if (e.classname === 'bolt') {
+ const v = Q.norm(e.velocity), rel = Q.sub(p.origin, e.origin), along = Q.dot(rel, v);
+ if (along > 0) { const off = Q.len(Q.sub(rel, Q.scale(v, along))); s += Math.max(0, 60 - off) * 0.5; }
+ }
+ }
+ return s;
+ }
+ M.scripted = function (g) {
+ const noop = { holds: Array.from({ length: 6 }, () => []), mouse: [0, 0, 0] };
+ const p = g.ents[1];
+ if (g.outcome || p.health <= 0) return noop;
+ // Memory across packets (hysteresis, time out of sight) is rolled once per tick, so asking twice about the same
+ // state gives the same packet; a new episode (tick 0) starts fresh.
+ let mem = memory.get(g);
+ if (!mem || (g.t === 0 && mem.t !== 0)) { mem = { t: -1, move: 0, unseen: 0, base: null }; memory.set(g, mem); }
+ if (mem.t !== g.t) { mem.base = { move: mem.move, unseen: mem.unseen }; mem.t = g.t; }
+ const bi = g.bossEnt(), b = g.ents[bi];
+ const alive = b && b.inuse && (b.svflags & Q.SVF_MONSTER) && b.deadflag !== Q.DEAD_DEAD && b.health > 0;
+ const eye = eyeOf(p);
+ let dx = 0, dy = 0, fire = false, want = p.weapon, dist = 1e9;
+ if (alive) {
+ const c = center(b);
+ dist = Q.len(Q.sub(c, p.origin));
+ want = wantWeapon(g, p, b, dist);
+ // Aim: the centre of the body, led by the boss's last-frame motion for projectile weapons.
+ let aim = [c[0], c[1], b.origin[2] + (b.maxs[2] - b.mins[2]) * 0.45];
+ const speed = SPEED[p.weapon];
+ if (speed) { const vel = Q.scale(Q.sub(b.origin, b.old_origin), 10), tf = Q.len(Q.sub(aim, eye)) / speed; aim = Q.ma(aim, tf, vel); }
+ const dvec = Q.sub(aim, eye), yaw = Q.atan2(dvec[1], dvec[0]) * 180 / Math.PI;
+ // Machinegun climb: each held shot adds machinegun_shots * -1.5 degrees of pitch kick; pull down to match.
+ const climb = p.weapon === 'machinegun' && (p.buttons & 1) ? Math.min(9, p.machinegun_shots + 0.5) * 1.5 : 0;
+ const pitch = -Q.atan2(dvec[2], Math.sqrt(dvec[0] * dvec[0] + dvec[1] * dvec[1])) * 180 / Math.PI + climb;
+ const dyaw = angleDiff(yaw - p.viewangles[1]), dpitch = pitch - p.viewangles[0];
+ dx = Math.max(-1000, Math.min(1000, Math.round(-dyaw / MOUSE_DEG)));
+ dy = Math.max(-1000, Math.min(1000, Math.round(dpitch / MOUSE_DEG)));
+ const residual = Math.abs(dyaw + dx * MOUSE_DEG) + Math.abs(dpitch - dy * MOUSE_DEG);
+ const radius = Math.max(b.maxs[0], 24), tol = Q.atan2(radius * 0.8, Math.max(1, dist)) * 180 / Math.PI;
+ const clear = lineOfFire(g, eye, aim, bi);
+ const selfSplash = p.weapon === 'rocketlauncher' && dist - b.maxs[0] < 170;
+ // Pellet spread is +-hspread/8192 radians (shotgun 500, super shotgun 1000 plus +-5 degrees per barrel): against
+ // the 128-unit Super Tank or 160-unit Jorg most pellets still land at 900 units, against Makron (60) they do not.
+ const outOfRange = /shotgun/.test(p.weapon) && dist > (b.maxs[0] >= 60 ? 1000 : 640);
+ fire = clear && residual < tol + 2 && !selfSplash && !outOfRange && Math.abs(dyaw) < 60;
+ }
+ // Weapon switch: tap weapnext / weapprev toward the wanted weapon when idle.
+ let tap = null;
+ const switching = !!p.newweapon || p.weaponstate === 1 || p.weaponstate === 2;
+ if (!switching && want && want !== p.weapon && p.weaponstate !== 3) {
+ const owned = Q.WEAPON_ORDER.filter(w => p.inv[w]), cur = owned.indexOf(p.weapon), tgt = owned.indexOf(want);
+ if (tgt >= 0) tap = ((tgt - cur + owned.length) % owned.length) <= owned.length / 2 ? 'K' : 'R';
+ }
+ // Movement: one-second look-ahead per candidate move on copies; score survival, damage, range and threats.
+ const fireKeys = fire ? ['J'] : [];
+ const PT = M.hz / 5, mouseTicks = Array.from({ length: PT }, () => [dx / PT, dy / PT, 0]); // the packet's split
+ const hp0 = p.health + armor(p) * 0.6, boss0 = g.health()[2];
+ // Super Tank: rockets from the edge of RANGE_FAR. M_CheckAttack never attacks at >= 1000 units and only at 0.02
+ // per frame (x2 on hard) in RANGE_MID, against 0.1 (x2) in RANGE_NEAR; the tank walks 120 u/s, the player runs 300.
+ const stBand = p.weapon === 'rocketlauncher' ? [880, 1250] : [650, 1000];
+ const band = !alive ? [400, 900] : b.classname === 'monster_supertank' ? stBand : /shotgun/.test(p.weapon) ? [170, 380]
+ : b.classname === 'monster_boss2' ? [260, 620] : b.classname === 'monster_jorg' ? [360, 760]
+ : b.classname === 'monster_tank_commander' ? (p.weapon === 'rocketlauncher' ? [560, 900] : [300, 600])
+ : b.classname === 'monster_gladiator' ? [420, 780] : b.classname === 'monster_mutant' ? [200, 420] : [320, 700];
+ let best = 0, bestScore = -Infinity;
+ const stream = alive && (STREAM[b.classname] || []).includes(b.monsterinfo.currentmove);
+ const fragile = p.health + armor(p) * 0.6 < 70;
+ // Hiding is a tactic, not a plan: after 1 s without line of sight (and no burst in progress) the controller goes
+ // looking for the boss; cover is only taken while a hitscan burst is actually running.
+ const visNow = alive && Q.visible(g, bi, 1);
+ mem.unseen = visNow ? 0 : mem.base.unseen + 1;
+ const seek = alive && mem.unseen >= 5 && !fragile && !(STREAM[b.classname] || []).includes(b.monsterinfo.currentmove);
+ const spot = seek && mem.unseen >= 25 ? sightSpot(g, b, p) : null;
+ // Against hitscan bosses stay within a short dash of cover at all times (peek, shoot, step back): the burst only
+ // continues while the boss can see the player at its reattack check.
+ const hitscanBoss = alive && STREAM[b.classname];
+ const spots = alive && (stream || fragile || hitscanBoss) ? hiddenSpots(g, b) : [];
+ // Ammo the preferred weapons of this fight are short of (below half of the carry limit); the main weapon first.
+ const needAmmo = [];
+ if (alive) for (const [w, ammo] of PREFERRED[b.classname] || []) if (p.inv[w] && p.inv[ammo] < Q.AMMO_MAX[ammo] / 2) needAmmo.push('ammo_' + ammo);
+ const main = alive && (PREFERRED[b.classname] || []).find(([w]) => p.inv[w]);
+ const lowMain = !!main && p.inv[main[1]] < Q.AMMO_MAX[main[1]] * 0.5;
+ // Out of the preferred weapons' ammo (while owning one of them): only the close-range fallbacks are left, so
+ // restocking comes first. The easy kit owns none of them and is never starving.
+ const owned = alive ? (PREFERRED[b.classname] || []).filter(([w]) => p.inv[w]) : [];
+ const starving = owned.length > 0 && !owned.some(([w, ammo]) => p.inv[ammo] >= 6);
+ for (let m = 0; m < MOVES.length; m++) {
+ const keys = ['Shift', ...MOVES[m], ...fireKeys];
+ const scores = [];
+ for (let k = 0; k < M.LOOK_K; k++) {
+ const h = simulate(g, keys, mouseTicks, LOOK, k), q = h.ents[1];
+ let score = -(hp0 - (q.health + armor(q) * 0.6)) * 25 + (boss0 - h.health()[2]) * 0.4;
+ if (h.outcome === 'loss' || q.health <= 0) score -= 1e6;
+ if (h.outcome === 'win') score += 1e5;
+ if (alive) {
+ const hb = h.ents[h.bossEnt()], nd = Q.len(Q.sub(Q.center(hb), q.origin));
+ const seen = hb.inuse && hb.health > 0 && Q.visible(h, 1, h.bossEnt());
+ if (!starving) score -= Math.max(0, band[0] - nd) * 0.5 + Math.max(0, nd - band[1]) * 0.25;
+ else score -= Math.max(0, 480 - nd) * 1.0; // restocking: stay out of RANGE_NEAR / the chaingun
+ if (seen) score += stream ? -90 : fragile ? 5 : (/shotgun/.test(p.weapon) && b.maxs[0] < 60 && nd > 640 ? -30 : 20);
+ if (seek) { if (seen) score += 80; score -= nd * 0.04; if (spot) score -= Math.sqrt((spot[0] - q.origin[0]) ** 2 + (spot[1] - q.origin[1]) ** 2) * 0.25; }
+ // During a hitscan stream the live boss does not move (attack1 is ai_charge 0): judge cover against it too.
+ if (stream && !seenBy(h, b, q)) score += 60;
+ if (spots.length) {
+ let near = 1e9; for (const s of spots) near = Math.min(near, Math.sqrt((s[0] - q.origin[0]) ** 2 + (s[1] - q.origin[1]) ** 2));
+ score -= stream || fragile ? near * (stream ? 0.4 : 0.08) : seek ? 0 : Math.max(0, near - 140) * 0.06;
+ }
+ }
+ score -= threats(h) * 1.5;
+ // Room to manoeuvre: free distance in eight directions (corners trap the player in a hitscan stream).
+ let room = 0;
+ for (let k = 0; k < 8; k++) {
+ const a = k * Math.PI / 4, to = [q.origin[0] + Q.cos(a) * 200, q.origin[1] + Q.sin(a) * 200, q.origin[2]];
+ room += Q.trace(h, q.origin, [-16, -16, -24], [16, 16, 32], to, 1, Q.MASK_SOLID).fraction;
+ }
+ score -= (8 - room) * 14;
+ if (m === mem.base.move) score += 6;
+ if (q.health < 90 || armor(q) < 40) {
+ // Health and armor pickups (and the ones about to respawn): strong pull when hurt, a mild one otherwise.
+ let near = 1e9;
+ for (const e of h.ents) {
+ if (!e.inuse || !e.item) continue;
+ const useful = /health/.test(e.item) ? q.health < 100 : e.item === 'stimpack' || (e.item === 'armor_shard' && armor(q) < 100);
+ if (!useful) continue;
+ const soon = e.solid !== Q.SOLID_TRIGGER && e.think === 'DoRespawn' && e.nextthink - h.ms < 3000;
+ if (e.solid === Q.SOLID_TRIGGER || soon) near = Math.min(near, Q.len(Q.sub(e.origin, q.origin)) + (soon ? 60 : 0));
+ }
+ // Like the ammo boxes below: a health or armor item taken inside the look-ahead is gone from the floor (q2-arena@4
+ // frees it), so "nearest item" would measure the next one and punish the move that heals. Taking one counts as
+ // distance 0 plus a bonus that grows with the damage taken.
+ let healed = 0;
+ for (let k = 0; k < h.ents.length && k < g.ents.length; k++) {
+ const ge = g.ents[k], he = h.ents[k];
+ if (ge.inuse && ge.solid === Q.SOLID_TRIGGER && /^(health|stimpack|armor)/.test(ge.item || '') && !(he.inuse && he.item === ge.item && he.solid === Q.SOLID_TRIGGER)) healed++;
+ }
+ if (healed) score += (q.health < 50 ? 160 : q.health < 80 ? 60 : 20) * healed;
+ else if (near < 1e9) score -= near * (q.health < 50 ? 0.2 : q.health < 80 ? 0.08 : 0.03);
+ }
+ if (needAmmo.length) {
+ // Boxes on the floor, and boxes that respawn within the next 3 s (waiting next to them is the restock).
+ let near = 1e9;
+ for (const e of h.ents) {
+ if (!e.inuse || !needAmmo.includes(e.item)) continue;
+ const soon = e.solid !== Q.SOLID_TRIGGER && e.think === 'DoRespawn' && e.nextthink - h.ms < 3000;
+ if (e.solid === Q.SOLID_TRIGGER || soon) near = Math.min(near, Q.len(Q.sub(e.origin, q.origin)) + (soon ? 60 : 0));
+ }
+ // A box taken inside the look-ahead has left the floor, so "nearest box" would then measure the next one and
+ // punish the very move that restocks: taking a needed box counts as distance 0 plus a bonus.
+ let taken = 0;
+ for (let k = 0; k < h.ents.length && k < g.ents.length; k++) if (needAmmo.includes(h.ents[k].item) && h.ents[k].solid !== Q.SOLID_TRIGGER && g.ents[k].solid === Q.SOLID_TRIGGER) taken++;
+ // During a hitscan burst cover beats restocking (the burst stops at the first reattack check without sight).
+ if (taken) score += stream ? 30 : starving ? 200 : lowMain ? 120 : 40;
+ else if (near < 1e9) score -= near * (stream ? 0.03 : starving ? 0.5 : lowMain ? 0.22 : 0.07);
+ }
+ scores.push(score);
+ }
+ // Several blinded futures per move (M.LOOK_K): half the worst, half the mean, so one lucky draw cannot pick a move.
+ const score = scores.length > 1 ? 0.5 * Math.min(...scores) + 0.5 * scores.reduce((x, y) => x + y, 0) / scores.length : scores[0];
+ if (score > bestScore) { bestScore = score; best = m; }
+ }
+ mem.move = best;
+ const holds = Array.from({ length: 6 }, (_, k) => {
+ const ks = ['Shift', ...MOVES[best]];
+ // A new press fires at once inside ClientThink while the packet's turn is still under way (60 Hz); start it on hold
+ // set 5 (turn 2/3 done), close to the 10 Hz packet whose first sample came half-way. Held fire stays in every set.
+ if (tap && k < 3) ks.push(tap); else if (fire && (k >= 4 || (p.buttons & 1))) ks.push('J');
+ return ks.slice(0, 4);
+ });
+ return { holds, mouse: [dx, dy, 0] };
+ };
+ const armor = p => p.inv.jacket + p.inv.combat + p.inv.body;
+ M.oracle = M.scripted;
+})(typeof window === 'undefined' ? globalThis : window);
diff --git a/environments/games/web/games/sekiro_remake/app3d.js b/environments/games/web/games/sekiro_remake/app3d.js
new file mode 100644
index 0000000000000000000000000000000000000000..c64424a0a24d601db0647f4097e14145a10863e2
--- /dev/null
+++ b/environments/games/web/games/sekiro_remake/app3d.js
@@ -0,0 +1,78 @@
+/* Human play and exact native-input recording. Game state is owned by each module. */
+(function () {
+ 'use strict';
+ const N=NativeBench, M=window.GAME_MODULE, $=s=>document.querySelector(s), canvas=$('canvas'), context=canvas.getContext('2d');
+ let session=new N.Session(M,M.cases[0].id,1,.5),running=false,last=0,accumulator=0;
+ // A key pressed and released between two ticks stays latched until one tick has sampled it (same rule as
+ // _native/shell.js since 2026-11-01), so fast taps, macro keys and Playwright press() are never lost. Until 2026-11-09 this
+ // page released the key on a setTimeout(0), which can run before the next tick and drop the tap; now it is the tick that releases it.
+ const held=new Set(),pending=new Set(),releaseAfterTick=new Set(),pointerHeld=new Map(),touchHeld=new Map(); let mouse=[0,0,0],replay=null,replayIndex=0,automatic=false,script=null,scriptTick=0;
+ const keys={KeyW:'W',KeyA:'A',KeyS:'S',KeyD:'D',Space:'Space',ShiftLeft:'Shift',ShiftRight:'Shift',KeyJ:'J',KeyK:'K',KeyL:'L',KeyQ:'Q',KeyE:'E',KeyR:'R',ArrowUp:'W',ArrowDown:'S',ArrowLeft:'A',ArrowRight:'D'};
+ document.body.dataset.game=M.id;
+ // Public difficulty = three tiers (2026-11-02): rebuilt from Module.tiers when the game declares it.
+ if(M.tiers&&$('#difficulty')){const sel=$('#difficulty'),names={easy:'Easy',normal:'Normal',hard:'Hard'};sel.textContent='';
+ for(const t of ['easy','normal','hard']){const op=document.createElement('option');op.value=String(M.tiers[t]);op.textContent=names[t]+'(d='+M.tiers[t]+')';if(t==='normal')op.selected=true;sel.append(op);}}
+ for(const def of M.cases){const option=document.createElement('option');option.value=def.id;option.textContent=def.name;$('#case').append(option);}
+ const controls=Array.isArray(M.controls)?M.controls.map(value=>['',value]):Object.entries(M.controls);
+ for(const [key,value]of controls){const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=key;dd.textContent=value;$('dl').append(dt,dd);}
+ function status(value){$('#status').textContent=value;}
+ function clear(){held.clear();pending.clear();releaseAfterTick.clear();pointerHeld.clear();touchHeld.clear();mouse=[0,0,0];accumulator=0;}
+ function inputKeys(){return [...new Set([...held,...[...pointerHeld.values()].flatMap(keys=>[...keys]),...touchHeld.values()])].filter(key=>N.keys.includes(key)).slice(0,4);}
+ function draw(){
+ M.draw(session.game,context);
+ $('#pause').textContent=running?'Pause':'Resume';
+ $('#overlay').hidden=running&&!session.game.outcome;
+ $('#overlay strong').textContent=session.game.outcome?{win:'Challenge Complete',loss:'Challenge Failed',timeout:'Time up'}[session.game.outcome]:replay?'Replay · Paused':session.game.t?'Paused':'Are You Ready?';
+ $('#overlay span').textContent=session.game.outcome?'Restart the challenge or export this replay':session.game.t?'Click the screen or press Resume to return to battle':'Click Start Challenge, then click the screen to lock the mouse and turn the camera';
+ }
+ function reset(id,seed,difficulty){running=false;automatic=false;replay=null;script=null;scriptTick=0;clear();session=new N.Session(M,id,seed,difficulty);draw();return session.snapshot();}
+ window.nativeAPI={reset,packet(packet){if(running)throw Error('Pause before a scripted packet');const value=session.packet(packet);draw();return value;},
+ state(){return session.snapshot();},recording(){return session.export();},
+ render(){draw();return canvas.toDataURL('image/png');},
+ renderMetrics(){return M.renderMetrics?M.renderMetrics(context):{};},
+ module(){return {id:M.id,hz:M.hz,version:M.version,cases:M.cases};}};
+ // PC-style mouse look (2026-11-09): the first click on the canvas during a fight locks the pointer, after which plain mouse
+ // movement turns the camera and the buttons stay attack / guard. Not on the start / resume buttons: while the pointer is
+ // locked every click goes to the canvas, so the toolbar would be unreachable until Esc. Dragging still works without a lock.
+ function lockPointer(){if(document.pointerLockElement===canvas||!canvas.requestPointerLock)return;try{const r=canvas.requestPointerLock();if(r&&r.catch)r.catch(()=>{});}catch(error){}}
+ document.addEventListener('pointerlockchange',()=>{if(document.pointerLockElement===canvas)status('Mouse locked · Press Esc to unlock');else if(running&&!automatic&&!replay){running=false;clear();status('Paused (mouse unlocked) · Click the screen to resume and lock the mouse');draw();}
+ else if(!running&&!automatic&&!replay&&!session.game.outcome&&session.game.t>0)status('Paused (Esc) · Click the screen to resume and lock the mouse');});
+ function start(useScript){try{reset($('#case').value,Number($('#seed').value),Number($('#difficulty').value));automatic=useScript;running=true;status(useScript?'Verification script running':'Battle started · Recording this match · Click the screen to lock the mouse; move it to turn the camera');canvas.focus();draw();}catch(error){status(error.message);}}
+ $('#start').onclick=()=>start(false);$('#demo').onclick=()=>start(true);
+ $('#pause').onclick=()=>{if(session.game.outcome)return;running=!running;clear();if(running)canvas.focus();draw();};
+ $('#step').onclick=()=>{running=false;if(replay)replayTick();else session.tick();draw();};
+ function openReplay(data){N.Session.import(M,data);reset(data.case,data.seed,data.difficulty);replay=data;replayIndex=0;running=true;$('#case').value=data.case;status('Replay verified · Starting playback');draw();}
+ $('#sample').onclick=()=>{try{const data=M.example?.[$('#case').value];if(!data)throw Error('No built-in replay for this challenge yet. Try Verify Script first.');openReplay(data);}catch(error){status(error.message);}};
+ function replayTick(){if(replayIndex{const data=session.export(),url=URL.createObjectURL(new Blob([JSON.stringify(data)],{type:'application/json'}));const link=document.createElement('a');link.href=url;link.download=M.id+'-'+session.seed+'.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);status('Current replay exported');};
+ $('#import').onclick=()=>$('#file').click();$('#file').onchange=async event=>{const file=event.target.files[0];if(!file)return;try{if(file.size>12e6)throw Error('Replay file is too large');openReplay(JSON.parse(await file.text()));}catch(error){status('Import failed: '+error.message);}event.target.value='';};
+ function release(){clear();if(running){running=false;status('Window lost focus · Battle paused');}draw();}
+ window.addEventListener('blur',release);document.addEventListener('visibilitychange',()=>{if(document.hidden)release();});
+ window.addEventListener('keydown',event=>{if(['INPUT','SELECT','BUTTON'].includes(document.activeElement.tagName))return;if(keys[event.code]){event.preventDefault();held.add(keys[event.code]);pending.add(keys[event.code]);releaseAfterTick.delete(keys[event.code]);}if(event.code==='Escape'){const wasRunning=running;running=false;clear();if(document.pointerLockElement===canvas)document.exitPointerLock?.();if(wasRunning&&!automatic&&!replay&&!session.game.outcome)status('Paused (Esc) · Click the screen to resume and lock the mouse');draw();}});
+ window.addEventListener('keyup',event=>{const key=keys[event.code];if(key){event.preventDefault();if(pending.has(key))releaseAfterTick.add(key);else held.delete(key);}});
+ canvas.oncontextmenu=event=>event.preventDefault();canvas.onpointerdown=event=>{if(event.button!==0&&event.button!==2)return;canvas.focus();
+ // A click on the canvas while the pointer is free re-locks it and resumes a paused fight; that click is not an attack.
+ if(document.pointerLockElement!==canvas&&!automatic&&!replay&&!session.game.outcome&&session.game.t>0&&!running){lockPointer();running=true;clear();draw();return;}
+ if(document.pointerLockElement!==canvas&&running&&!automatic&&!replay)lockPointer();const keys=pointerHeld.get(event.pointerId)||new Set();keys.add(event.button===2?'RMB':'LMB');pointerHeld.set(event.pointerId,keys);};
+ // Pointer Events emits pointerup only after the final mouse button is released.
+ // pointermove carries changes to the button mask for chorded mouse presses.
+ function syncMouse(event){if(event.pointerType==='mouse'&&pointerHeld.has(event.pointerId)){const keys=new Set();if(event.buttons&1)keys.add('LMB');if(event.buttons&2)keys.add('RMB');if(keys.size)pointerHeld.set(event.pointerId,keys);else pointerHeld.delete(event.pointerId);}}
+ window.addEventListener('pointermove',syncMouse);
+ window.addEventListener('pointerup',event=>{if(event.pointerType==='mouse')syncMouse(event);else pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);});
+ window.addEventListener('pointercancel',event=>{pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);});
+ canvas.onpointermove=event=>{if(event.buttons||document.pointerLockElement===canvas){mouse[0]+=event.movementX;mouse[1]+=event.movementY;}};
+ canvas.onwheel=event=>{event.preventDefault();mouse[2]+=Math.sign(event.deltaY);};
+ canvas.ondblclick=()=>canvas.requestPointerLock?.();
+ document.querySelectorAll('[data-key]').forEach(button=>{button.onpointerdown=event=>{event.preventDefault();button.setPointerCapture(event.pointerId);touchHeld.set(event.pointerId,button.dataset.key);};button.onpointerup=button.onpointercancel=event=>touchHeld.delete(event.pointerId);});
+ function frame(now){const delta=Math.min(.1,(now-last)/1000||0);last=now;const beforeTick=session.game.t,wasRunning=running;try{
+ if(running&&!session.game.outcome){accumulator+=delta;while(accumulator>=1/M.hz&&running&&!session.game.outcome){accumulator-=1/M.hz;
+ if(replay)replayTick();else if(automatic){const count=M.hz/5;if(scriptTick===0)script=(M.scripted||M.oracle).call(M,session.game);const sub=Math.ceil((scriptTick+1)*6/count)-1;session.tick(script.holds[sub],script.mouse.map(value=>value/count));scriptTick=(scriptTick+1)%count;}
+ else{session.tick(inputKeys(),mouse.map((value,index)=>N.clamp(value,index===2?-5:-1000,index===2?5:1000)));mouse=[0,0,0];pending.clear();for(const key of releaseAfterTick)held.delete(key);releaseAfterTick.clear();}}
+ if(session.game.outcome){running=false;status({win:'Challenge Complete',loss:'Challenge Failed',timeout:'Challenge Timed Out'}[session.game.outcome]+' · You can export or replay this match');}}
+ if(session.game.t!==beforeTick||running!==wasRunning)draw();
+ }catch(error){running=false;clear();status('Runtime error: '+error.message);$('#overlay').hidden=false;$('#overlay strong').textContent='Unable to resume right now';$('#overlay span').textContent=error.message;}
+ requestAnimationFrame(frame);
+ }
+ window.addEventListener('pagehide',()=>M.closeRenderer?.(context));
+ draw();requestAnimationFrame(frame);
+})();
diff --git a/environments/games/web/games/sekiro_remake/compact_actions.json b/environments/games/web/games/sekiro_remake/compact_actions.json
new file mode 100644
index 0000000000000000000000000000000000000000..13d86ba2c536855ddacfcdd53c2e68c6a2f5dbf1
--- /dev/null
+++ b/environments/games/web/games/sekiro_remake/compact_actions.json
@@ -0,0 +1,1135 @@
+{
+ "schema": "bossbench/compact-actions@1",
+ "game": "sekiro_remake",
+ "version": "sekiro-compact@1",
+ "heads": [
+ {
+ "name": "move",
+ "options": [
+ {
+ "label": "none"
+ },
+ {
+ "label": "forward",
+ "keys": [
+ "W"
+ ]
+ },
+ {
+ "label": "forward_start",
+ "subs": [
+ [
+ "W"
+ ],
+ [
+ "W"
+ ],
+ [
+ "W"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "forward_end",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "W"
+ ],
+ [
+ "W"
+ ],
+ [
+ "W"
+ ]
+ ]
+ },
+ {
+ "label": "forward_tap",
+ "subs": [
+ [
+ "W"
+ ],
+ [],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "back",
+ "keys": [
+ "S"
+ ]
+ },
+ {
+ "label": "left",
+ "keys": [
+ "A"
+ ]
+ },
+ {
+ "label": "right",
+ "keys": [
+ "D"
+ ]
+ },
+ {
+ "label": "back_left",
+ "keys": [
+ "S",
+ "A"
+ ]
+ },
+ {
+ "label": "back_right",
+ "keys": [
+ "S",
+ "D"
+ ]
+ },
+ {
+ "label": "turn_left_30",
+ "dx": -175
+ },
+ {
+ "label": "turn_right_30",
+ "dx": 175
+ }
+ ]
+ },
+ {
+ "name": "act",
+ "options": [
+ {
+ "label": "none"
+ },
+ {
+ "label": "attack_0",
+ "subs": [
+ [
+ "J"
+ ],
+ [],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "attack_1",
+ "subs": [
+ [],
+ [
+ "J"
+ ],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "attack_2",
+ "subs": [
+ [],
+ [],
+ [
+ "J"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "attack_3",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "J"
+ ],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "attack_4",
+ "subs": [
+ [],
+ [],
+ [],
+ [],
+ [
+ "J"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "attack_5",
+ "subs": [
+ [],
+ [],
+ [],
+ [],
+ [],
+ [
+ "J"
+ ]
+ ]
+ },
+ {
+ "label": "deflect_0",
+ "subs": [
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "deflect_1",
+ "subs": [
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "deflect_2",
+ "subs": [
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "deflect_3",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "deflect_4",
+ "subs": [
+ [],
+ [],
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "deflect_5",
+ "subs": [
+ [],
+ [],
+ [],
+ [],
+ [],
+ [
+ "RMB"
+ ]
+ ]
+ },
+ {
+ "label": "deflect_attack_0_1",
+ "subs": [
+ [
+ "RMB"
+ ],
+ [
+ "J"
+ ],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "deflect_attack_0_2",
+ "subs": [
+ [
+ "RMB"
+ ],
+ [],
+ [
+ "J"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "deflect_attack_0_3",
+ "subs": [
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [
+ "J"
+ ],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "deflect_attack_0_4",
+ "subs": [
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [],
+ [
+ "J"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "deflect_attack_0_5",
+ "subs": [
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [],
+ [],
+ [
+ "J"
+ ]
+ ]
+ },
+ {
+ "label": "deflect_attack_1_2",
+ "subs": [
+ [],
+ [
+ "RMB"
+ ],
+ [
+ "J"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "deflect_attack_1_3",
+ "subs": [
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [
+ "J"
+ ],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "deflect_attack_1_4",
+ "subs": [
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [
+ "J"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "deflect_attack_1_5",
+ "subs": [
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [],
+ [
+ "J"
+ ]
+ ]
+ },
+ {
+ "label": "deflect_attack_2_3",
+ "subs": [
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [
+ "J"
+ ],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "deflect_attack_2_4",
+ "subs": [
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [
+ "J"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "deflect_attack_2_5",
+ "subs": [
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [
+ "J"
+ ]
+ ]
+ },
+ {
+ "label": "deflect_attack_3_4",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [
+ "J"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "deflect_attack_3_5",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [
+ "J"
+ ]
+ ]
+ },
+ {
+ "label": "deflect_attack_4_5",
+ "subs": [
+ [],
+ [],
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [
+ "J"
+ ]
+ ]
+ },
+ {
+ "label": "deflect_0_4",
+ "subs": [
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "deflect_0_5",
+ "subs": [
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [],
+ [],
+ [
+ "RMB"
+ ]
+ ]
+ },
+ {
+ "label": "deflect_2_4",
+ "subs": [
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [
+ "RMB"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "deflect_2_5",
+ "subs": [
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [
+ "RMB"
+ ]
+ ]
+ },
+ {
+ "label": "deflect_3_5",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [
+ "RMB"
+ ]
+ ]
+ },
+ {
+ "label": "step_alt_0",
+ "subs": [
+ [
+ "Shift"
+ ],
+ [],
+ [
+ "Shift"
+ ],
+ [],
+ [
+ "Shift"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "step_alt_1",
+ "subs": [
+ [],
+ [
+ "Shift"
+ ],
+ [],
+ [
+ "Shift"
+ ],
+ [],
+ [
+ "Shift"
+ ]
+ ]
+ },
+ {
+ "label": "deflect_2_4_5",
+ "subs": [
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [],
+ [
+ "RMB"
+ ],
+ [
+ "RMB"
+ ]
+ ]
+ },
+ {
+ "label": "step_0",
+ "subs": [
+ [
+ "Shift"
+ ],
+ [],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "step_1",
+ "subs": [
+ [],
+ [
+ "Shift"
+ ],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "step_2",
+ "subs": [
+ [],
+ [],
+ [
+ "Shift"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "step_3",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "Shift"
+ ],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "step_4",
+ "subs": [
+ [],
+ [],
+ [],
+ [],
+ [
+ "Shift"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "jump_0",
+ "subs": [
+ [
+ "Space"
+ ],
+ [],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_1",
+ "subs": [
+ [],
+ [
+ "Space"
+ ],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_2",
+ "subs": [
+ [],
+ [],
+ [
+ "Space"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_3",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "Space"
+ ],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_4",
+ "subs": [
+ [],
+ [],
+ [],
+ [],
+ [
+ "Space"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "jump_5",
+ "subs": [
+ [],
+ [],
+ [],
+ [],
+ [],
+ [
+ "Space"
+ ]
+ ]
+ },
+ {
+ "label": "jump_kick_0",
+ "subs": [
+ [
+ "Space"
+ ],
+ [],
+ [
+ "Space"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_kick_1",
+ "subs": [
+ [],
+ [
+ "Space"
+ ],
+ [],
+ [
+ "Space"
+ ],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_kick_2",
+ "subs": [
+ [],
+ [],
+ [
+ "Space"
+ ],
+ [],
+ [
+ "Space"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "jump_kick_3",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "Space"
+ ],
+ [],
+ [
+ "Space"
+ ]
+ ]
+ },
+ {
+ "label": "jump_attack_0_1",
+ "subs": [
+ [
+ "Space"
+ ],
+ [
+ "J"
+ ],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_attack_0_2",
+ "subs": [
+ [
+ "Space"
+ ],
+ [],
+ [
+ "J"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_attack_0_3",
+ "subs": [
+ [
+ "Space"
+ ],
+ [],
+ [],
+ [
+ "J"
+ ],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_attack_1_2",
+ "subs": [
+ [],
+ [
+ "Space"
+ ],
+ [
+ "J"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_attack_1_3",
+ "subs": [
+ [],
+ [
+ "Space"
+ ],
+ [],
+ [
+ "J"
+ ],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_attack_1_4",
+ "subs": [
+ [],
+ [
+ "Space"
+ ],
+ [],
+ [],
+ [
+ "J"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "jump_attack_2_3",
+ "subs": [
+ [],
+ [],
+ [
+ "Space"
+ ],
+ [
+ "J"
+ ],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "jump_attack_2_4",
+ "subs": [
+ [],
+ [],
+ [
+ "Space"
+ ],
+ [],
+ [
+ "J"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "jump_attack_2_5",
+ "subs": [
+ [],
+ [],
+ [
+ "Space"
+ ],
+ [],
+ [],
+ [
+ "J"
+ ]
+ ]
+ },
+ {
+ "label": "jump_attack_3_4",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "Space"
+ ],
+ [
+ "J"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "jump_attack_3_5",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "Space"
+ ],
+ [],
+ [
+ "J"
+ ]
+ ]
+ },
+ {
+ "label": "jump_attack_4_5",
+ "subs": [
+ [],
+ [],
+ [],
+ [],
+ [
+ "Space"
+ ],
+ [
+ "J"
+ ]
+ ]
+ },
+ {
+ "label": "guard_hold_2",
+ "subs": [
+ [
+ "RMB"
+ ],
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "guard_hold_3",
+ "subs": [
+ [
+ "RMB"
+ ],
+ [
+ "RMB"
+ ],
+ [
+ "RMB"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "guard_hold_6",
+ "subs": [
+ [
+ "RMB"
+ ],
+ [
+ "RMB"
+ ],
+ [
+ "RMB"
+ ],
+ [
+ "RMB"
+ ],
+ [
+ "RMB"
+ ],
+ [
+ "RMB"
+ ]
+ ]
+ },
+ {
+ "label": "guard_hold_late",
+ "subs": [
+ [],
+ [],
+ [],
+ [
+ "RMB"
+ ],
+ [
+ "RMB"
+ ],
+ [
+ "RMB"
+ ]
+ ]
+ },
+ {
+ "label": "run",
+ "keys": [
+ "Shift"
+ ]
+ },
+ {
+ "label": "heal_0",
+ "subs": [
+ [
+ "Q"
+ ],
+ [],
+ [],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "heal_2",
+ "subs": [
+ [],
+ [],
+ [
+ "Q"
+ ],
+ [],
+ [],
+ []
+ ]
+ },
+ {
+ "label": "heal_4",
+ "subs": [
+ [],
+ [],
+ [],
+ [],
+ [
+ "Q"
+ ],
+ []
+ ]
+ },
+ {
+ "label": "revive",
+ "tap": [
+ "R"
+ ]
+ },
+ {
+ "label": "lock_toggle",
+ "tap": [
+ "E"
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/environments/games/web/games/sekiro_remake/draw.js b/environments/games/web/games/sekiro_remake/draw.js
new file mode 100644
index 0000000000000000000000000000000000000000..79e2772e37593cb5bd20356ab26a1bef3c932e9e
--- /dev/null
+++ b/environments/games/web/games/sekiro_remake/draw.js
@@ -0,0 +1,70 @@
+/* Sekiro HUD drawn over the WebGL frame: boss name, deathblow markers and vitality at the top left, posture gauges
+ * growing from the centre (boss at the top, Sekiro at the bottom), Sekiro's vitality, resurrection nodes, gourd and
+ * ailment gauges at the bottom left, the red perilous kanji above Sekiro, the deathblow mark on the target, the blue lock-on
+ * reticle (only while locked) and an edge arrow toward an off-screen boss, native Hz. */
+(function(root){
+ 'use strict';const M=root.SekiroGame,B=root.Boss3D,clamp=(x,a,b)=>Math.max(a,Math.min(b,x));
+ const TIER_NAMES={easy:'Easy',normal:'Normal',hard:'Hard'};
+ function font(c,size,weight='',serif=false){c.font=`${weight} ${size}px ${serif?'"Noto Serif SC","Songti SC","SimSun","Microsoft YaHei",serif':'"Segoe UI","Microsoft YaHei",sans-serif'}`;}
+ function text(c,s,x,y,size,color,align='left',o={}){font(c,size,o.weight||'',o.serif);c.textAlign=align;c.textBaseline='alphabetic';
+ if(o.glow){c.shadowColor=o.glow;c.shadowBlur=o.blur||12;}c.fillStyle='rgba(6,8,10,.75)';c.fillText(s,x+1,y+1.5);c.fillStyle=color;c.fillText(s,x,y);c.shadowBlur=0;}
+ function bar(c,x,y,w,h,v,fill,back='rgba(10,12,14,.72)'){c.fillStyle=back;c.fillRect(x,y,w,h);c.fillStyle=fill;c.fillRect(x+1,y+1,Math.max(0,(w-2)*clamp(v,0,1)),h-2);
+ c.strokeStyle='rgba(220,205,170,.55)';c.lineWidth=1;c.strokeRect(x+.5,y+.5,w-1,h-1);}
+ // Posture grows outward from the middle; it turns hotter as it nears a break and darker while low vitality slows recovery.
+ function posture(c,cx,y,w,h,v,slow,flash){if(v<=0.002)return;const half=w/2*clamp(v,0,1);c.fillStyle='rgba(10,10,12,.7)';c.fillRect(cx-w/2,y,w,h);
+ const hot=v>.85&&flash,col=hot?'#ff4f1f':v>.6?'#f08a2a':'#e6b143';const g=c.createLinearGradient(cx-half,0,cx+half,0);g.addColorStop(0,col);g.addColorStop(.5,'#ffe5a0');g.addColorStop(1,col);
+ c.fillStyle=g;c.fillRect(cx-half,y+1,half*2,h-2);if(slow){c.fillStyle='rgba(120,20,10,.35)';c.fillRect(cx-half,y+1,half*2,h-2);}
+ c.fillStyle='rgba(255,240,200,.9)';c.fillRect(cx-1,y-2,2,h+4);c.strokeStyle='rgba(230,200,150,.5)';c.strokeRect(cx-w/2+.5,y+.5,w-1,h-1);}
+ function dot(c,x,y,r,full,color){c.beginPath();c.arc(x,y,r,0,Math.PI*2);c.fillStyle=full?color:'rgba(30,26,26,.85)';c.fill();c.lineWidth=1.5;c.strokeStyle=full?'rgba(255,190,170,.9)':'rgba(140,120,118,.8)';c.stroke();}
+ // Lock-on aids, drawn in 2D over the frame so walls and pillars never hide them (as zelda_oot_remake/draw.js reticle / edgeArrow).
+ // Cool blue, so the lock never reads as the red deathblow dot or the red perilous kanji; the ring sits at the deathblow height and circles that dot.
+ const LOCK='#8fdcff',PI2=Math.PI*2;
+ function reticle(c,x,y,r,a,dot){c.save();c.translate(x,y);c.lineWidth=4;c.strokeStyle='rgba(8,12,20,.85)';c.beginPath();c.arc(0,0,r,0,PI2);c.stroke();
+ c.lineWidth=2;c.strokeStyle=LOCK;c.beginPath();c.arc(0,0,r,0,PI2);c.stroke();
+ for(let i=0;i<4;i++){c.save();c.rotate(a+i*PI2/4);c.beginPath();c.moveTo(0,-r-2);c.lineTo(-5,-r-11);c.lineTo(5,-r-11);c.closePath();c.fillStyle=LOCK;c.fill();c.lineWidth=1.2;c.strokeStyle='rgba(8,12,20,.85)';c.stroke();c.restore();}
+ if(dot){c.beginPath();c.arc(0,0,3,0,PI2);c.fillStyle=LOCK;c.fill();c.lineWidth=1.2;c.strokeStyle='rgba(8,12,20,.85)';c.stroke();}c.restore();}
+ function edgeArrow(c,ax,ay,col,label){const m=36,k=Math.min((427-m)/Math.max(1e-6,Math.abs(ax)),(240-m)/Math.max(1e-6,Math.abs(ay))),x=427+ax*k,y=240+ay*k,a=Math.atan2(ay,ax);
+ c.save();c.translate(x,y);c.rotate(a);c.beginPath();c.moveTo(18,0);c.lineTo(-10,-13);c.lineTo(-4,0);c.lineTo(-10,13);c.closePath();c.fillStyle=col;c.fill();c.lineWidth=2.5;c.strokeStyle='rgba(8,12,20,.92)';c.stroke();c.restore();
+ text(c,label,x-Math.cos(a)*30,y-Math.sin(a)*30+5,12,col,'center');}
+ function gourd(c,x,y){c.fillStyle='#9a5a28';c.beginPath();c.arc(x,y+5,6.5,0,Math.PI*2);c.arc(x,y-4,4.5,0,Math.PI*2);c.fill();c.fillStyle='#d9b56a';c.fillRect(x-1.5,y-12,3,4);c.fillStyle='rgba(255,240,200,.3)';c.beginPath();c.arc(x-2,y+3,2,0,Math.PI*2);c.fill();}
+ M.draw=function(g,c){const scene=B.render('sekiro',g,c),p=g.player,b=g.boss,kind=g.kind||'genichiro',K=M.bosses[kind],tm=g.t/M.hz;
+ // ---- boss: deathblow markers, name and vitality (top left)
+ const [shown,left]=K.markers(b),name=K.names[Math.min(K.names.length-1,(b.phase||1)-1)];
+ for(let i=0;i0){c.strokeStyle='#1a1214';c.lineWidth=3;c.beginPath();c.moveTo(30,414);c.lineTo(62,405);c.stroke();text(c,'Resurrection sealed',70,414,11,'#c9b0bb');}
+ bar(c,30,422,236,8,(p.hp||0)/(p.maxHp||1),p.poisoned>0?'#7d9a3a':'#c7392f');
+ let gy=416;for(const [v,label,col] of [[p.poison||0,'Poison',p.poisoned>0?'#a8d050':'#7da040'],[p.terror||0,'Terror','#9b1a2a'],...(p.burn!==undefined?[[p.burning>0?100:p.burn,'Burn',p.burning>0?'#ff7a2a':'#d4602a']]:[])]){if(v<=0.5&&!(label==='Poison'&&p.poisoned>0))continue;gy-=13;text(c,label,272,gy+8,11,col);bar(c,286,gy,70,6,label==='Poison'&&p.poisoned>0?1:v/100,col);}
+ gourd(c,40,452);text(c,'× '+(p.gourds??0),52,458,14,'#e8d9b8');
+ posture(c,427,446,300,7,(p.posture||0)/(p.maxPosture||100),(p.hp||0)/(p.maxHp||1)<.5,Math.floor(g.t/6)%2===0);
+ // ---- perilous kanji above Sekiro, deathblow mark on the target
+ if(scene&&b.perilous&&b.telegraph&&!p.dead){const s=scene.project(p.x,(p.y||0)+2.05,p.z),pulse=1+.08*Math.sin(g.t*.5);
+ c.save();c.globalAlpha=.85;const rg=c.createRadialGradient(s.x,s.y-14,2,s.x,s.y-14,36*pulse);rg.addColorStop(0,'rgba(255,40,20,.55)');rg.addColorStop(1,'rgba(255,40,20,0)');c.fillStyle=rg;c.fillRect(s.x-40,s.y-56,80,84);c.restore();
+ text(c,'PERIL',s.x,s.y,Math.round(40*pulse),'#ff3b26','center',{weight:'bold',serif:true,glow:'rgba(255,40,10,.9)',blur:14});}
+ // Lock reticle while locked; when the boss is out of the picture (behind the camera, or past an edge) an arrow at the edge points to it.
+ if(scene&&b.state!=='dead'&&!g.outcome&&!p.dead){const h=kind==='ape'?2.1:kind==='gyoubu'?2.7:kind==='demon'?3.6:1.2,s=scene.project(b.x,(b.y||0)+h,b.z),on=s.visible&&s.x>8&&s.x<846&&s.y>8&&s.y<472;
+ if(on&&g.lockOn)reticle(c,s.x,s.y,20,g.t*.04,!b.deathblowAvailable);
+ else if(!on){const yaw=g.cameraYaw||0,dx=b.x-p.x,dz=b.z-p.z,right=-dx*Math.cos(yaw)+dz*Math.sin(yaw),ahead=dx*Math.sin(yaw)+dz*Math.cos(yaw);
+ // In front: the projected direction; behind the camera the projection flips, so use the camera frame (screen-right, and down for behind).
+ const [ax,ay]=s.visible&&ahead>0?[s.x-427,s.y-240]:[right,-ahead];edgeArrow(c,ax,ay,g.lockOn?LOCK:'#ffcf8a',g.lockOn?'Lock':'Boss');}}
+ if(scene&&b.deathblowAvailable){const h=kind==='ape'?2.1:kind==='gyoubu'?2.7:kind==='demon'?3.6:1.2,s=scene.project(b.x,(b.y||0)+h,b.z),r=7+Math.sin(g.t*.25)*1.5;
+ c.beginPath();c.arc(s.x,s.y,r+7,0,Math.PI*2);c.strokeStyle='rgba(255,60,40,.5)';c.lineWidth=2;c.stroke();c.beginPath();c.arc(s.x,s.y,r,0,Math.PI*2);c.fillStyle='#e0261c';c.shadowColor='#ff3020';c.shadowBlur=12;c.fill();c.shadowBlur=0;}
+ if(p.lightning>0&&!p.dead){const s=scene?scene.project(p.x,(p.y||0)+2.2,p.z):{x:427,y:200};text(c,'Lightning strike',s.x,s.y,20,'#ffe39a','center',{weight:'bold',glow:'rgba(255,220,120,.9)'});}
+ // ---- Shinobi Execution banner (the guardian ape's first one is a deception, S14)
+ const banner=(b.executing>0&&(b.phase===b.bars||kind==='ape'))||g.outcome==='win'||(b.state==='dead'&&(b.deadTicks||0)>110);
+ if(banner){const u=g.outcome==='win'?1:clamp(b.state==='dead'?((b.deadTicks||0)-110)/40:(58-(b.executing||0))/14,0,1);c.save();c.globalAlpha=u;
+ c.fillStyle='rgba(0,0,0,.35)';c.fillRect(0,196,854,92);text(c,'DEATHBLOW',427,262,62,'#e9e2d2','center',{weight:'bold',serif:true,glow:'rgba(180,20,20,.9)',blur:18});
+ text(c,kind==='isshin'?'FINAL EXECUTION':'EXECUTION',427,282,12,'#c9b9a0','center');c.restore();}
+ if(p.dead&&!g.outcome){c.fillStyle='rgba(30,0,0,.28)';c.fillRect(0,0,854,480);text(c,'DEAD',427,252,92,'#c7261e','center',{weight:'bold',serif:true,glow:'rgba(200,0,0,.8)',blur:20});
+ text(c,p.terrorDeath?'Killed by terror · Cannot resurrect':lives>0&&!p.resurrectionLocked?'Press R to resurrect':'Cannot resurrect',427,296,17,'#efe0d1','center');}
+ // ---- clock, tier and native rate (bottom right)
+ const tierName=Object.entries(M.tiers).find(([,v])=>Math.abs(v-g.d)<1e-9)?.[0];
+ text(c,`${M.hz}Hz`,826,442,13,'#e8c983','right',{weight:'bold'});text(c,(tierName?TIER_NAMES[tierName]+' · ':'d='+(+g.d).toFixed(2)+' · ')+tm.toFixed(1)+'s',826,460,12,'#d6d2c6','right');
+ };
+ M.renderStatus=ctx=>B.status('sekiro',ctx);M.renderMetrics=ctx=>B.metrics('sekiro',ctx);M.closeRenderer=ctx=>B.close('sekiro',ctx);
+})(window);
diff --git a/environments/games/web/games/sekiro_remake/game.js b/environments/games/web/games/sekiro_remake/game.js
new file mode 100644
index 0000000000000000000000000000000000000000..cb4aa2d4abdaa34ed332a0c1193703d8955e1f48
--- /dev/null
+++ b/environments/games/web/games/sekiro_remake/game.js
@@ -0,0 +1,1167 @@
+/* Sekiro: Shadows Die Twice - six boss duels in one deterministic 60 Hz engine (rules sekiro@10).
+ * sekiro/genichiro Ashina Castle top: two armored bars, then Way of Tomoe (three deathblows)
+ * sekiro/guardian_ape Sunken Valley watering hole: the white beast, a false Shinobi Execution, the headless apparition
+ * sekiro/lady_butterfly Hirata Estate audience chamber: threads and kunai, then illusions and spirit butterflies
+ * sekiro/isshin Silvergrass field: Way of Tomoe Genichiro, then Isshin with sword, spear and matchlock, lightning (four deathblows)
+ * sekiro/gyoubu Ashina Castle Gate: the mounted Gyoubu, charges past and away, rope spear, hind-leg kick (two deathblows)
+ * sekiro/demon The burning gate: the Demon of Hatred, fire arms, fireballs, the fire ring and Burn (three deathblows)
+ * Mechanics follow public guides (Fextralife, BWIKI parameter pages, GameWith/VGR guides).
+ * The hard tier's vitality / posture / recovery anchors are BWIKI base parameters; move timings, reaches, speeds and the
+ * player's numbers are calibration values, not extracted FromSoftware data. See SOURCES.md. */
+(function(root){
+ 'use strict';
+ const N=root.NativeBench,A=(x,z)=>Math.atan2(x,z),dist=(a,b)=>Math.hypot(a.x-b.x,a.z-b.z);
+ // Public tiers (2026-11-02). Boss magnitudes run geometrically through the easy / normal / hard anchors.
+ const TIERS={easy:.2,normal:.5,hard:.8};
+ function tier(d,[e,n,h]){return d>=TIERS.normal?n*Math.pow(h/n,(d-TIERS.normal)/(TIERS.hard-TIERS.normal)):n*Math.pow(e/n,(TIERS.normal-d)/(TIERS.normal-TIERS.easy));}
+ const C={playerHP:100,posture:100,move:.075,run:.125,dodge:.2,dodgeFrames:16,dodgeInv:6,
+ deflectFrames:12,spamFloor:3,spamInterval:24,spamReset:60,
+ // Sekiro waits about a second before posture recovers; enemy posture has no delay (S04).
+ playerPostureDelay:60,postureRate:.26,guardRecovery:2.7,deflectChainWindow:40,deflectChainBonus:.06,deflectChainMax:.3,
+ jumpSpeed:.215,gravity:.0115,sweepHeight:.55,grabJumpHeight:.6,
+ slashWind:7,slashEnd:25,thrustCharge:25,thrustWind:10,thrustEnd:34,
+ // Kusabimaru normal cut at Attack Power 1 deals 80 vitality (S13: 80 at AP 1, +20 per point). Posture numbers are
+ // percent units of Genichiro's armored posture (660, S22): postureUnit converts them to absolute posture.
+ slashDamage:80,thrustDamage:120,slashPosture:9,thrustPosture:12,blockPosture:7,thrustBlockPosture:9,postureUnit:3.3,
+ mikiriPosture:25,mikiriStun:30,stompPosture:22,hitStun:20,
+ deathblowWindow:180,deathblowMissFraction:.75,executionFrames:58,deathblowReach:2.15,
+ guardBreakStagger:58,safetyRollAfter:14,safetyRollRemain:12,
+ gourdStock:7,gourdHeal:45,gourdFrames:66,gourdApply:26,resurrectionNodes:2,reviveFrames:50,reviveFraction:.5,
+ // Status ailments: buildup gauges decay when not fed; a full poison gauge drains vitality for a while, a full
+ // terror gauge kills outright (S20/S21; rates are calibration).
+ poisonDecay:.08,poisonTicks:360,poisonDrain:.06,terrorDecay:.12};
+ // Posture recovery cut by remaining vitality. Bosses: BWIKI per-boss tables (S22, S16, S18); Sekiro: S04 quartiles.
+ const REGEN={gen12:[[.8,1],[.6,.5],[.4,.167],[0,.083]],std:[[.8,1],[.6,.6],[.4,.3],[0,.1]],player:[[.75,1],[.5,.66],[.25,.33],[0,.01]]};
+ // Small seeds give nearly identical first xorshift draws; scramble the seed so seeds 1..8 differ from the start.
+ function mixSeed(seed){let x=(seed>>>0)^0x9e3779b9;x=Math.imul(x^(x>>>16),0x85ebca6b);x=Math.imul(x^(x>>>13),0xc2b2ae35);x^=x>>>16;return (x>>>0)||0x6d2b79f5;}
+ function regenFactor(table,h){for(const [at,f] of REGEN[table])if(h>at||at===0)return f;return 0;}
+ const H=(t,o={})=>Object.assign({t,type:'slash',reach:2.8,hp:12,posture:15},o);
+ // One draw per choice; entries listed in w get that relative weight (all 1 = the plain uniform pick).
+ function pickW(g,list,w={}){const ws=list.map(n=>w[n]??1),total=ws.reduce((a,b)=>a+b,0);let r=N.rand(g)*total;for(let i=0;iH(t,{reach:2.9,hp:i===8?18:10,posture:i===8?25:11,parry:i===8?14:6,push:i===8?.7:0,final:i===8}))},
+ jump_slam:{duration:57,hits:[{t:42,type:'slam',reach:2.65,hp:19,posture:23}],whiff:[[42,57]]},
+ tomoe_slash:{duration:44,hits:[H(16,{reach:3.0,hp:14,posture:17})]},
+ swipe5:{duration:100,hits:[16,30,44,58,74].map(t=>H(t,{reach:2.9,hp:10,posture:12,parry:9})),open:[[86,100]]},
+ thrust:{duration:58,perilous:'thrust',hits:[{t:33,type:'thrust',reach:3.4,hp:25,posture:27}],open:[[46,58]]},
+ sweep:{duration:61,perilous:'sweep',hits:[{t:34,type:'sweep',reach:3.5,hp:25,posture:29}],open:[[42,61]]},
+ grab:{duration:68,perilous:'grab',hits:[{t:34,type:'grab',dodge:true,reach:1.95,hp:34,posture:20}],whiff:[[40,68]]},
+ running_grab:{duration:78,perilous:'grab',hits:[{t:48,type:'grab',dodge:true,reach:2.05,hp:36,posture:25}],whiff:[[54,78]]},
+ leap_thrust:{duration:67,perilous:'thrust',hits:[{t:40,type:'thrust',reach:3.1,hp:28,posture:30}],whiff:[[48,67]]},
+ dive_ready:{duration:G.diveReady,hits:[],next:'leap_thrust'},
+ bow:{duration:53,hits:[],shots:[22],open:[[0,53]]},
+ bow_roll:{duration:96,hits:[H(70,{hp:14,posture:16})],shots:[20],open:[[0,46]]},
+ quick_bow:{duration:36,hits:[],shots:[10],open:[[0,36]]},
+ charged_bow:{duration:96,hits:[],shots:[70],heavy:[70],open:[[0,96]]},
+ volley:{duration:88,hits:[],shots:[30,38,46,65],open:[[0,88]]},
+ lightning_slash:{duration:125,perilous:'lightning',hits:[{t:100,type:'lightning',reach:10,hp:0,posture:0,arc:.42}],open:[[0,100],[104,125]]},
+ lightning_sweep:{duration:125,perilous:'lightning',hits:[{t:100,type:'lightning',reach:8.5,hp:0,posture:0,arc:1.7}],open:[[0,100],[104,125]]},
+ lightning_bow:{duration:125,perilous:'lightning',hits:[],shots:[96],open:[[0,125]]},
+ tomoe_awaken:{duration:72,hits:[],invulnerable:true,next:'leap_thrust'}
+ };
+ const GENICHIRO={moves:GEN_MOVES,radius:.5,height:1.95,kickRange:2.15,names:['Bow-and-Blade Swordsman','Bow-and-Blade Swordsman','Lightning Swordsman'],forms:['genichiro','genichiro','tomoe'],
+ // [easy, normal, hard] pools, calibrated to the meeting's tier windows with the reference controller. BWIKI base (S22)
+ // fixes the shape: bars 1-2 HP 1598 / posture 660 / 60 per s (full recovery 11 s), bar 3 x1.6 HP, x1.36 posture, 22.5 s.
+ anchors:{hp:[170,1129,3768],posture:[371,903,1556],recover:11,tomoeHP:1.6,tomoePosture:1.36,tomoeRecover:22.5,rest:[70,32,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.15]},
+ tune(d){const a=this.anchors,hp=tier(d,a.hp),posture=tier(d,a.posture);
+ const armored={hp:Math.round(hp),posture:Math.round(posture),regen:Math.round(posture)/(a.recover*60),table:'gen12'},tp=Math.round(posture*a.tomoePosture);
+ return {bars:[armored,{...armored},{hp:Math.round(hp*a.tomoeHP),posture:tp,regen:tp/(a.tomoeRecover*60),table:'std'}],
+ rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};},
+ extra:()=>({lightning:false,lastLightningAt:-999,extraShot:0}),
+ start(g){g.startMove('opening');},
+ idle(g){const b=g.boss,p=g.player;g.face(b,p);if(dist(b,p)>2.25)g.advance(.058*g.tune.chase,2.2);
+ if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));},
+ choose(g){const b=g.boss,p=g.player,d=dist(b,p),tomoe=b.form_id==='tomoe';
+ // If idle, he always answers healing: a charged shot (armored) or a sword-dive thrust (Way of Tomoe) (S01).
+ if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return tomoe?'dive_ready':'charged_bow';}
+ const r=N.rand(g);
+ // Way of Tomoe keeps returning to lightning; the pacing rule is an engineering calibration, not a measured rate.
+ if(tomoe&&r<(g.t-b.lastLightningAt>G.lightningDue?G.lightningDueChance:G.lightningChance))return ['lightning_slash','lightning_sweep','lightning_bow'][Math.floor(N.rand(g)*3)];
+ if(g.t-b.attackedAt<90){const q=N.rand(g);if(q<.3)return 'jump_slam';if(q<.45&&!tomoe)return 'volley';}
+ if(d>5)return tomoe?(r<.6?'leap_thrust':'volley'):b.healthbar_phase===2?(r<.4?'charged_bow':r<.7?'volley':r<.85?'bow':'bow_roll'):(r<.45?'charged_bow':r<.75?'volley':'bow_roll');
+ const list=b.healthbar_phase===1?['slash','double','kick_arrow','passage','jump_slam','grab','thrust','bow_roll','volley']:
+ b.healthbar_phase===2?['slash','double','kick_arrow','passage','jump_slam','sweep','grab','thrust','bow_roll','volley','bow_roll','bow']:
+ ['double','passage','swipe5','jump_slam','leap_thrust','running_grab','sweep','thrust','kick_arrow','bow_roll'];
+ return list[Math.floor(r*list.length)];},
+ onStart(g,name){const b=g.boss;b.lightning=name.startsWith('lightning');if(b.lightning)b.lastLightningAt=g.t;b.extraShot=name==='bow_roll'&&N.rand(g)<.5?36:0;},
+ followUp(g,move){const b=g.boss;
+ if(b.chainNext==='thrust_followup')return dist(b,g.player)>G.thrustFollowRange?'quick_bow':'running_grab';
+ if(b.chainNext)return b.chainNext;
+ if(GEN_MOVES[move].next)return GEN_MOVES[move].next;
+ if(move==='jump_slam')return b.healthbar_phase===1?'thrust':b.healthbar_phase===2?(N.rand(g)=18&&t<80)g.advance(.025*ch,1.6);
+ if(move==='opening'&&t>=32&&t<58)g.advance(.17,1.9);
+ if(move==='bow_roll'&&t>=46&&t<62)g.advance(.16,1.8);
+ if(move==='jump_slam'){b.y=t<42?Math.max(0,Math.sin(Math.PI*N.clamp((t-12)/30,0,1))*2.1):0;if(t>=15&&t<38)g.advance(.17,1.7);}
+ if(move==='leap_thrust'){b.y=t<40?Math.max(0,Math.sin(Math.PI*N.clamp((t-13)/27,0,1))*1.5):0;if(t>=19&&t<40)g.advanceCommitted(.32,1.1);}
+ if(move==='running_grab'&&t<46){if(t<35)g.advance(.13*ch,1.1);else g.advanceCommitted(.13,1.1);}
+ if((move==='grab'||move==='sweep')&&t<18){const side=move==='grab'?-1:1;g.move(b,Math.cos(b.yaw)*.035*side,-Math.sin(b.yaw)*.035*side);}
+ if(move==='thrust'&&t>=25&&t<=33)g.advanceCommitted(.17,1.15);
+ if(move==='volley'){b.y=Math.max(0,Math.sin(Math.PI*N.clamp((t-12)/66,0,1))*1.8);if(t<20)g.move(b,-Math.sin(b.yaw)*.05,-Math.cos(b.yaw)*.05);}
+ // Lightning of Tomoe: grip and crouch, leap, the bolt meets the blade, then the strike ~1.4 s after takeoff (S05).
+ if(move.startsWith('lightning'))b.y=Math.max(0,Math.sin(Math.PI*N.clamp((t-16)/90,0,1))*2.6);
+ },
+ afterHits(g,move,m,t){const b=g.boss,p=g.player;
+ for(const hit of m.hits)if(t===hit.t&&hit.type==='lightning')g.hazards.push({type:move==='lightning_sweep'?'lightning_arc':'lightning_line',x:b.x,y:.3,z:b.z,yaw:b.yaw,radius:hit.reach,age:0,life:14});
+ for(const shot of m.shots||[])if(t===shot)g.arrow(!!m.heavy?.includes(shot),move==='lightning_bow');
+ if(move==='bow_roll'&&b.extraShot&&t===b.extraShot)g.arrow(false,false);
+ // Floating Passage cancel: a distant player gets a fast bow shot, usually only after he lost a bar (S01).
+ if(move==='passage'&&t===92&&b.healthbar_phase>=2&&dist(b,p)>4.5){g.stats.passageCancels++;g.emit('passage_cancel');g.startMove('quick_bow');}
+ },
+ // His guard: two blocks, then a perfect parry that starts the Floating Passage string (S01) or a quick counter.
+ playerHit(g,kind,open){const b=g.boss,p=g.player,busy=b.state==='attack';
+ if(open){g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);g.interruptBoss(C.hitStun);g.fx('cut',b);return;}
+ b.guardCount++;
+ if(b.guardCount>=3){b.guardCount=0;g.stats.bossDeflects++;p.posture=Math.min(p.maxPosture,p.posture+4);p.postureDelay=C.playerPostureDelay;g.fx('boss_deflect',b);g.emit('boss_deflect');
+ if(!busy||b.moveTick<9)g.startMove(N.rand(g)b.phase<3?[2,3-b.phase]:[1,1]
+ };
+
+ /* ---------------------------------------------------------------- Guardian Ape (Sunken Valley watering hole) */
+ const P={fakeDeath:330,flinchSmall:44,flinchBig:118,flinchRoll:46,poiseReset:1500,poiseSlash:50,poiseThrust:75,headPosture:2,
+ smallFlinchPosture:6,bigFlinchPosture:4.5,neckBonus:2,turn:.07,turnHeadless:.055,screamDeflectChance:.45};
+ const APE_MOVES={
+ // Phase 1: the white beast roams on all fours; nearly all its blows can be guarded, the grabs cannot (S14/S15).
+ slam_combo:{duration:100,hits:[30,44,58,74].map(t=>H(t,{type:'slam',reach:3.4,arc:1.3,hp:13,posture:16,parry:7})),open:[[84,100]]},
+ swipe_leap:{duration:110,hits:[H(26,{reach:3.5,arc:1.5,hp:14,posture:17}),H(42,{reach:3.5,arc:1.5,hp:14,posture:17}),H(84,{type:'slam',reach:3.2,arc:3.2,hp:22,posture:26})],open:[[88,110]]},
+ swipe_grab:{duration:86,perilous:'grab',hits:[{t:42,type:'grab',reach:3.8,arc:1.7,hp:34,posture:20}],whiff:[[46,86]]},
+ belly_flop:{duration:102,perilous:'grab',hits:[{t:58,type:'grab',noJump:true,reach:2.2,arc:3.2,hp:36,posture:24}],whiff:[[62,102]]},
+ back_thrash:{duration:118,hits:[26,38,50,62,74].map(t=>H(t,{type:'slam',reach:3.1,arc:3.2,hp:11,posture:14,parry:6})),open:[[98,118]],head:[[14,98]]},
+ fart:{duration:52,hits:[],gas:[22],next:'flee_poo'},
+ flee_poo:{duration:134,hits:[],poo:[66],open:[[88,134]]},
+ roar:{duration:86,hits:[],open:[[26,86]]},
+ bound:{duration:58,hits:[]},
+ roll_away:{duration:46,hits:[]},
+ // Phase 2: the headless apparition, sword in the right hand and its head in the left (S14, S15).
+ sword4:{duration:114,hits:[28,46,62,82].map((t,i)=>H(t,{reach:4.6,arc:1.6,hp:15,posture:18,parry:12,window:4,ltr:i===1})),open:[[96,114]]},
+ diving_lunge:{duration:126,hits:[H(36,{reach:4.1,arc:1.1,hp:22,posture:24,parry:14,window:4})],open:[[46,114]],neck:[[46,114]]},
+ jump_sweep:{duration:74,perilous:'sweep',hits:[{t:54,type:'sweep',reach:4.9,arc:1.8,hp:26,posture:28}],next:'overhead_slam'},
+ overhead_slam:{duration:82,hits:[H(56,{type:'slam',reach:4.3,arc:.8,hp:28,posture:30,parry:30,window:8,stun:96})],whiff:[[62,82]]},
+ scream_long:{duration:226,perilous:'terror',hits:[],scream:{from:62,to:206,radius:8.5,rate:1.3,drain:.11},open:[[206,226]]},
+ scream_short:{duration:102,perilous:'terror',hits:[],scream:{from:20,to:72,radius:6.2,rate:1.6,drain:.12},open:[[74,102]]},
+ headless_rise:{duration:140,hits:[],invulnerable:true}
+ };
+ APE_MOVES.rising=APE_MOVES.headless_rise;
+ const APE={moves:APE_MOVES,radius:1.2,height:3.0,kickRange:2.9,kickAnyHeight:true,names:['Valley Giant Ape','Valley Giant Ape'],forms:['ape','headless'],
+ // [easy, normal, hard] pools, calibrated like Genichiro's. BWIKI base (S16): HP 3520, posture 1140, 60 per s (19 s), poise
+ // 400 then 520; the risen apparition gets x1.1 HP and posture.
+ anchors:{hp:[480,2327,10012],posture:[860,1810,3242],recover:19,poise:[220,300,400],poise2:1.3,rise:1.1,pressure:[.4,1,1],rest:[120,34,22],restStun:[20,12,6],dmg:[.6,.85,1],chase:[.85,1,1.12]},
+ tune(d){const a=this.anchors,hp=Math.round(tier(d,a.hp)),posture=Math.round(tier(d,a.posture)),poise=Math.round(tier(d,a.poise)),p2=Math.round(posture*a.rise);
+ return {bars:[{hp,posture,regen:posture/(a.recover*60),table:'std',poise},{hp:Math.round(hp*a.rise),posture:p2,regen:p2/(a.recover*60),table:'std',poise:Math.round(poise*a.poise2)}],pressure:tier(d,a.pressure),
+ rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};},
+ extra:()=>({poise:0,poiseMax:0,poiseAt:-9999,flinch:0,deadTicks:0,roam:1}),
+ start(g){const b=g.boss;b.poise=b.poiseMax=g.tune.bars[0].poise;b.state='idle';b.action='idle';b.cooldown=40;},
+ // The beast roams around Sekiro on all fours at a middle distance and answers anyone who closes in (S14); the
+ // headless apparition walks in to sword range.
+ idle(g){const b=g.boss,p=g.player,d=dist(b,p),head=b.form_id==='headless',to=A(p.x-b.x,p.z-b.z),ch=g.tune.chase;
+ g.turn(b,to,head?P.turnHeadless:P.turn);
+ if(head){if(d>3.4)g.advance(.062*ch,3.2);}
+ else{if(d>5)g.advance(.1*ch,4.6);else{const out=d<3.8?-.05:0,side=b.roam*.06*ch;g.move(b,Math.sin(to)*out+Math.cos(to)*side,Math.cos(to)*out-Math.sin(to)*side);if(room(g,b.x,b.z)a[Math.floor(N.rand(g)*a.length)];
+ // An easier tier screams less often (the long blood scream is its deadliest and longest move).
+ if(b.form_id==='headless'){const w={scream_long:g.tune.pressure};
+ if(d>9)return r<.55?'jump_sweep':'diving_lunge';
+ if(d>5)return pickW(g,['diving_lunge','jump_sweep','scream_long','sword4'],w);
+ return pickW(g,['sword4','sword4','overhead_slam','scream_long','jump_sweep','diving_lunge'],w);}
+ // The fart is often used when Sekiro is behind it, and is always followed by the flight and the poo throw (S14).
+ const behind=Math.abs(N.angle(A(p.x-b.x,p.z-b.z)-b.yaw))>1.9;
+ if(behind&&d<5&&r<.6)return 'fart';
+ if(d>9)return r<.6?'bound':'belly_flop';
+ if(d>6)return pick(['belly_flop','swipe_leap','roar','bound','flee_poo']);
+ if(d>3.2)return pick(['slam_combo','swipe_leap','belly_flop','swipe_grab','slam_combo','roar']);
+ return pick(['slam_combo','swipe_leap','swipe_grab','back_thrash','slam_combo','swipe_grab','fart']);},
+ onStart(g,name){const b=g.boss,p=g.player;b.aimX=p.x;b.aimZ=p.z;},
+ followUp(g,move){const b=g.boss;if(b.chainNext)return b.chainNext;return APE_MOVES[move].next||null;},
+ step(g,move,m,t){const b=g.boss,p=g.player,to=A(p.x-b.x,p.z-b.z),ch=g.tune.chase;
+ const track=(until,rate=.09)=>{if(t=56&&t<84?Math.sin(Math.PI*(t-56)/28)*2.6:0;if(t>=56&&t<84)g.advanceCommitted(.2,1.6);}
+ if(move==='swipe_grab'){track(30,.08);}
+ if(move==='belly_flop'){track(20,.12);b.y=t>=20&&t<58?Math.sin(Math.PI*(t-20)/38)*3.6:0;if(t>=20&&t<58)g.toward(b,b.aimX,b.aimZ,.26,.4);}
+ if(move==='back_thrash'){track(10,.1);}
+ if(move==='flee_poo'){if(t<40){g.turn(b,to+Math.PI,.2);g.move(b,-Math.sin(to)*.2,-Math.cos(to)*.2);}
+ else{track(66,.2);b.y=t>=44&&t<80?Math.sin(Math.PI*(t-44)/36)*4.2:0;}}
+ if(move==='roar'){if(t<20)g.move(b,-Math.sin(to)*.12,-Math.cos(to)*.12);track(26,.1);}
+ if(move==='roll_away'){if(t<30){const away=A(b.x-p.x,b.z-p.z);g.move(b,Math.sin(away)*.2,Math.cos(away)*.2);}b.y=t<30?Math.abs(Math.sin(Math.PI*t/15))*.8:0;}
+ if(move==='bound'){track(14,.15);b.y=t>=14&&t<50?Math.sin(Math.PI*(t-14)/36)*3.2:0;if(t>=14&&t<50)g.toward(b,b.aimX,b.aimZ,.28,3.2);}
+ if(move==='sword4'){track(76,.05);if(t<84)g.advance(.03*ch,3.0);}
+ if(move==='diving_lunge'){track(18,.1);if(t>=18&&t<40)g.advanceCommitted(.3,1.3);}
+ if(move==='jump_sweep'){track(10,.12);b.y=t>=6&&t<54?Math.sin(Math.PI*(t-6)/48)*3.6:0;if(t>=6&&t<50)g.toward(b,b.aimX,b.aimZ,.22,2.6);}
+ if(move==='overhead_slam'){track(40,.06);}
+ if(m.scream&&t>=m.scream.from&&tb.moveTick>=w[0]&&b.moveTick0||(b.state==='attack'&&(m?.neck||[]).some(w=>b.moveTick>=w[0]&&b.moveTick0)b.neckExposed--;
+ // A big flinch that ends unbroken resets the ladder; a recorded small flinch lasts until the poise resets (S16).
+ if(b.flinch===2&&b.state!=='stunned')b.flinch=0;
+ if(b.flinch&&g.t-b.poiseAt>P.poiseReset)b.flinch=0;
+ if(g.t-b.poiseAt>P.poiseReset)b.poise=b.poiseMax;
+ if(b.state!=='dead')return false;
+ if(--b.deadTicks<=0){g.nextBar();b.form_id='headless';b.source_phase=2;b.poise=b.poiseMax=g.tune.bars[1].poise;b.flinch=0;g.emit('form:headless');g.startMove('headless_rise');}
+ return true;},
+ // The first deathblow decapitates it and shows SHINOBI EXECUTION, a deception: it rises with a hidden bar (S14).
+ finish(g){const b=g.boss;if(b.phase===2){g.win();return;}
+ b.state='dead';b.action='fake_death';b.actionTick=0;b.deadTicks=P.fakeDeath;b.hp=0;b.posture=0;g.hazards=[];g.stats.falseExecutions++;g.emit('false_execution');},
+ markers:b=>[1,b.state==='dead'?0:1]
+ };
+
+ /* ---------------------------------------------------------------- Lady Butterfly (Hirata Estate) */
+ const L={hover:3.8,guardReset:90,spell:720,interrupted:240,respawn:24,cooldown:900,runDispel:150,illusions:4,kick:34,hitFlinch:14,
+ illusionSpeed:.032,butterflySpeed:.105,butterflyTurn:.05,butterflyLaunch:26,butterflyHoming:110,butterflyLife:260,dartSpeed:.2,dartTurn:.03,dartLaunch:12,dartHoming:24,kunaiSpeed:.42};
+ const BUT_MOVES={
+ // Phase 1: kunai, threads strung between the pillars and an aerial grab (S17, S19).
+ kunai_throw:{duration:66,hits:[],kunai:[[24,3],[40,3]],open:[[48,66]]},
+ three_strike:{duration:84,hits:[H(16,{reach:2.5,hp:9,posture:12}),H(28,{reach:2.5,hp:9,posture:12}),H(54,{type:'slam',reach:2.3,arc:1.6,hp:14,posture:18})],open:[[58,84]]},
+ leg_drop:{duration:80,hits:[H(50,{type:'slam',reach:2.1,arc:3.2,hp:16,posture:20})],open:[[56,80]]},
+ kunai_dash:{duration:124,hits:[H(54,{reach:2.4,hp:10,posture:13}),H(80,{reach:2.4,hp:10,posture:13})],kunai:[[14,3],[30,3]],whiff:[[86,124]]},
+ sweep:{duration:76,perilous:'sweep',hits:[{t:34,type:'sweep',reach:3.0,arc:1.5,hp:20,posture:22},{t:46,type:'sweep',reach:3.0,arc:1.5,hp:20,posture:22}],open:[[52,76]]},
+ thread_up:{duration:46,hits:[],air:true},
+ thread_hover:{duration:100,hits:[],air:true,kunai:[[22,3],[50,3],[78,3]]},
+ thread_dive:{duration:76,hits:[H(26,{reach:2.4,hp:9,posture:12}),H(34,{reach:2.4,hp:9,posture:12}),H(42,{reach:2.4,hp:10,posture:13})],open:[[56,76]]},
+ drop_grab:{duration:84,perilous:'grab',hits:[{t:42,type:'grab',noJump:true,reach:2.3,arc:1.5,hp:30,posture:20}],whiff:[[46,84]]},
+ counter2:{duration:44,hits:[H(10,{reach:2.5,hp:8,posture:11}),H(22,{reach:2.5,hp:8,posture:11})]},
+ deflect_kick:{duration:40,hits:[{t:12,type:'kick',reach:2.2,hp:6,posture:16,push:1.1}]},
+ hop_back:{duration:30,hits:[]},
+ // Phase 2: illusions of villagers, spirit butterflies and a flurry that ends in a perilous sweep (S17, S19).
+ illusion:{duration:64,hits:[],summon:[32],open:[[0,16]]},
+ dispel:{duration:56,hits:[],dispel:[30],open:[[34,56]],invulnerableUntil:32},
+ flurry:{duration:156,perilous:'sweep',perilousFrom:96,hits:[{t:12,type:'kick',reach:2.2,hp:6,posture:14,push:1.3},...[56,66,76,86,96].map(t=>H(t,{reach:2.5,hp:8,posture:10})),{t:122,type:'sweep',reach:3.0,arc:1.6,hp:22,posture:24}],butterflies:[[26,4]],open:[[128,156]]},
+ kunai_butterfly:{duration:84,hits:[],butterflies:[[16,4]],kunai:[[32,3],[40,3],[48,3]],open:[[60,84]]},
+ waltz:{duration:104,hits:[],air:true,butterflies:[[22,3],[62,3]],kunai:[[42,3],[80,3]]},
+ // "Lose yourself in my illusions": she rises from the first deathblow and opens the illusion phase (S17).
+ rising:{duration:78,hits:[],summon:[60],open:[[62,78]],invulnerableUntil:62}
+ };
+ const BUTTERFLY={moves:BUT_MOVES,radius:.42,height:1.6,kickRange:2.15,names:['Thread Kunoichi','Thread Kunoichi'],forms:['butterfly','illusionist'],
+ // [easy, normal, hard] pools, calibrated like Genichiro's. BWIKI base (S18): HP 2073, posture 600, 60 per s (10 s),
+ // recovery cuts 0/40/70/90 %.
+ anchors:{hp:[340,1201,3593],posture:[380,675,1040],recover:10,spell:[300,540,720],pressure:[.45,1,1],rest:[44,30,18],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.12]},
+ tune(d){const a=this.anchors,posture=Math.round(tier(d,a.posture)),bar={hp:Math.round(tier(d,a.hp)),posture,regen:posture/(a.recover*60),table:'std'};
+ return {bars:[bar,{...bar}],spell:Math.round(tier(d,a.spell)),pressure:tier(d,a.pressure),rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};},
+ extra:()=>({hoverX:0,hoverZ:0,guardAt:-999,counterNext:false,spell:0,dispelDue:false,illusionCooldown:0,spawnTimer:0}),
+ start(g){const b=g.boss;b.state='idle';b.action='idle';b.cooldown=30;},
+ idle(g){const b=g.boss,p=g.player,d=dist(b,p);g.face(b,p);if(b.y>0)b.y=Math.max(0,b.y-.2);
+ if(d>2.4)g.advance(.07*g.tune.chase,2.3);else if(d<1.6)g.move(b,-Math.sin(b.yaw)*.04,-Math.cos(b.yaw)*.04);
+ if(b.counterNext){b.counterNext=false;g.startMove('counter2');return;}
+ if(--b.cooldown<=0)g.startMove(this.choose(g));},
+ // An easier tier spends less time on the threads and in the flurry.
+ choose(g){const b=g.boss,p=g.player,d=dist(b,p),w={thread_up:g.tune.pressure,flurry:g.tune.pressure},pick=a=>pickW(g,a,w);
+ if(b.form_id==='illusionist'){
+ // Kept running, or left alone long enough, she turns the illusions into homing butterflies (S17, S18).
+ if(b.dispelDue||(b.spell>0&&p.runTicks>=L.runDispel))return 'dispel';
+ if(b.spell<=0&&b.illusionCooldown<=0&&!g.minions.some(q=>q.alive))return 'illusion';
+ if(d>6)return pick(['kunai_butterfly','thread_up','kunai_dash','leg_drop']);
+ return pick(['flurry','three_strike','sweep','kunai_butterfly','thread_up','flurry']);}
+ if(d>6)return pick(['kunai_throw','kunai_dash','thread_up','leg_drop']);
+ if(d>3)return pick(['kunai_dash','leg_drop','thread_up','sweep','three_strike']);
+ return pick(['three_strike','sweep','three_strike','kunai_throw','thread_up','leg_drop']);},
+ onStart(g,name){const b=g.boss,p=g.player;b.aimX=p.x;b.aimZ=p.z;
+ if(name==='thread_up'){// a hover point on the threads, away from the pillars, about five units from Sekiro
+ const a=A(b.x-p.x,b.z-p.z)+(N.rand(g)-.5)*1.2,ar=g.arena;b.hoverX=N.clamp(p.x+Math.sin(a)*5,-ar.halfWidth+2,ar.halfWidth-2);b.hoverZ=N.clamp(p.z+Math.cos(a)*5,-ar.halfDepth+2,ar.halfDepth-2);}},
+ followUp(g,move){const b=g.boss;
+ if(move==='thread_up')return b.form_id==='illusionist'?'waltz':'thread_hover';
+ if(move==='thread_hover'||move==='waltz')return N.rand(g)<.6?'thread_dive':'drop_grab';
+ return null;},
+ step(g,move,m,t){const b=g.boss,p=g.player,ch=g.tune.chase;
+ const track=until=>{if(t=34&&t<52?Math.sin(Math.PI*(t-34)/18)*1.6:0;}
+ if(move==='leg_drop'){track(30);b.y=t>=8&&t<50?Math.sin(Math.PI*(t-8)/84)*3.0*(t<29?1:1):0;if(t>=29)b.y=Math.max(0,3.0*(50-t)/21);if(t>=8&&t<50)g.toward(b,b.aimX,b.aimZ,.12,.3);}
+ if(move==='kunai_dash'){track(40);if((t>=40&&t<52)||(t>=66&&t<78))g.advanceCommitted(.3,1.2);if(t===60){b.aim=A(p.x-b.x,p.z-b.z);b.yaw=b.aim;b.commitDistance=dist(b,p);}}
+ if(move==='sweep'){track(20);if(t<26)g.advance(.04*ch,1.8);}
+ if(move==='thread_up'){g.face(b,p);b.y=Math.min(L.hover,L.hover*Math.sin(Math.PI/2*N.clamp((t-6)/30,0,1)));g.toward(b,b.hoverX,b.hoverZ,.16,0);}
+ if(move==='thread_hover'||move==='waltz'){g.face(b,p);b.y=L.hover;}
+ if(move==='thread_dive'){track(10);b.y=t<24?L.hover*(1-t/24):0;if(t<26)g.toward(b,b.aimX,b.aimZ,.24,1.2);}
+ // she tracks Sekiro until she drops (S19: a side step is caught, a retreat straight back as she falls is not)
+ if(move==='drop_grab'){track(34);b.y=t<26?L.hover:t<40?L.hover*(40-t)/14:0;if(t>=26&&t<42)g.toward(b,b.aimX,b.aimZ,.3,.9);}
+ if(move==='counter2'){track(16);if(t<20)g.advance(.05,1.6);}
+ if(move==='deflect_kick'){track(8);}
+ if(move==='hop_back'){track(4);if(t<20)g.move(b,-Math.sin(b.yaw)*.13,-Math.cos(b.yaw)*.13);b.y=Math.sin(Math.PI*N.clamp(t/20,0,1))*.7;}
+ if(move==='illusion'||move==='dispel'){g.face(b,p);}
+ if(move==='rising'){g.face(b,p);b.y=t<52?Math.sin(Math.PI*t/52)*2.4:0;if(t<52)g.toward(b,b.aimX,b.aimZ,.12,0);}
+ if(move==='flurry'){track(50);if(t>=40&&t<100)g.advance(.06*ch,1.6);}
+ if(move==='kunai_butterfly'){track(48);}
+ },
+ afterHits(g,move,m,t){const b=g.boss;
+ for(const [at,n] of m.kunai||[])if(t===at)g.kunai(n);
+ for(const [at,n] of m.butterflies||[])if(t===at)for(let i=0;i1.2)return;
+ if(open){if(b.action==='illusion'&&b.state==='attack'){b.illusionCooldown=L.interrupted;g.emit('spell_interrupted');}
+ g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);if(!b.deathblowAvailable){g.interruptBoss(L.hitFlinch);b.counterNext=true;}g.fx('cut',b);return;}
+ if(g.t-b.guardAt>L.guardReset)b.guardCount=0;b.guardAt=g.t;b.guardCount++;
+ if(b.guardCount>=3){b.guardCount=0;g.stats.bossDeflects++;p.posture=Math.min(p.maxPosture,p.posture+6);p.postureDelay=C.playerPostureDelay;g.fx('boss_deflect',b);g.emit('boss_deflect');
+ if(b.state!=='attack'||b.moveTick<8)g.startMove(N.rand(g)<.5?'deflect_kick':'hop_back');}
+ else{g.stats.bossBlocks++;g.fx('boss_block',b);g.emit('boss_block');g.bossPosture((kind==='thrust'?C.thrustBlockPosture:C.blockPosture)*C.postureUnit);}},
+ onDeflect(){},
+ special(g){const b=g.boss;if(b.illusionCooldown>0)b.illusionCooldown--;
+ if(b.spell>0){if(--b.spell===0)b.dispelDue=true;if(g.minions.filter(q=>q.alive).length[1,1]
+ };
+ /* ---------------------------------------------------------------- Isshin, the Sword Saint (silvergrass field) */
+ // Way of Tomoe Genichiro (one bar, no Lightning of Tomoe, S29), then Isshin: sword, spear and matchlock, then lightning (S27, S28).
+ const I={tomoeHP:2556/2240,tomoePosture:750/660,tomoeRecover:25,spearHP:1.27,waveSpeed:.42,bulletSpeed:.6,waveLeak:.35,stompPush:2.2,stompReach:5.5,
+ mortalChance:.16,passageThrust:.8,lightningChance:.2,lightningDue:420,lightningDueChance:.55,counterThrust:.5,ichimonjiWave:.75,leapThrust:.6,retreatChop:.5,quadThrust:.7};
+ const ISSHIN_MOVES={
+ // Genichiro's own table (his third phase minus the lightning, S29) plus the black Mortal Blade: run or step through it (S27, S30).
+ ...Object.fromEntries(['double','passage','swipe5','jump_slam','tomoe_slash','leap_thrust','dive_ready','running_grab','sweep','thrust','kick_arrow','bow_roll','volley','quick_bow','counter','lightning_slash','lightning_sweep'].map(n=>[n,GEN_MOVES[n]])),
+ mortal_blade:{duration:132,track:50,hits:[{t:62,type:'mortal',reach:7.2,arc:1.5,hp:32,posture:30},{t:96,type:'mortal',reach:7.2,arc:1.5,hp:32,posture:30}],rings:[62,96],open:[[66,90],[108,132]]},
+ isshin_emerge:{duration:96,hits:[],invulnerable:true,cinematic:true,next:'cross'},
+ // Sword: Ashina Cross, its close-range cancel into a perilous sweep, Ichimonji (a deflect chains the vertical wave), Dragon Flash, the spiral (S27, S28, S30).
+ cross:{duration:70,hits:[H(36,{reach:3.4,hp:16,posture:18,parry:12}),H(44,{reach:3.4,hp:16,posture:18,parry:12})],adv:[[20,36,.22,1.6]],open:[[56,70]]},
+ smack_sweep:{duration:78,perilous:'sweep',perilousFrom:22,hits:[H(14,{reach:2.8,hp:10,posture:14}),{t:46,type:'sweep',reach:4,arc:2,hp:24,posture:26}],open:[[56,78]]},
+ ichimonji:{duration:58,hits:[H(26,{type:'slam',reach:3,arc:.9,hp:20,posture:26,parry:15})],open:[[44,58]]},
+ dragon_flash:{duration:82,hits:[],waves:[[40,'v'],[54,'v']],open:[[0,24],[64,82]]},
+ wind_v:{duration:56,hits:[],waves:[[24,'v']],open:[[34,56]]},
+ spiral:{duration:80,hits:[H(40,{ring:true,reach:6.4,arc:3.2,hp:18,posture:22})],rings:[40],open:[[52,80]]},
+ combo:{duration:108,hits:[24,42,58,84].map(t=>H(t,{reach:3,hp:12,posture:14,parry:9})),adv:[[0,80,.03,1.7,true]],open:[[96,108]]},
+ overhead:{duration:64,hits:[H(30,{type:'slam',reach:3,arc:.9,hp:18,posture:24}),H(46,{reach:2.8})],open:[[54,64]]},
+ pose_thrust:{duration:74,perilous:'thrust',track:30,hits:[{t:44,type:'thrust',reach:3.8,hp:26,posture:28}],adv:[[36,44,.2,1.15]],open:[[56,74]]},
+ dash_slash:{duration:60,hits:[H(30,{reach:3.2,hp:18,posture:20})],adv:[[10,30,.34,1.6]],open:[[44,60]]},
+ // Spear and matchlock: the stomp, Double Projected Force, the leap, the retreating sweep, four shots (the last delayed) into a perilous (S27, S30).
+ stomp:{duration:82,hits:[H(62,{reach:3.4,arc:3.2,hp:12,posture:14})],stomp:[30],open:[[72,82]]},
+ double_disc:{duration:74,hits:[],waves:[[26,'h'],[44,'h']],open:[[54,74]]},
+ leap_slam:{duration:66,hits:[H(42,{type:'slam',reach:3.1,hp:22,posture:26})],leap:[14,42,2.4],adv:[[14,42,.2,1.7,true]],whiff:[[46,66]]},
+ retreat_sweep:{duration:62,hits:[H(30,{reach:5,arc:1.8,hp:18,posture:20,window:-4})],back:[0,14,.16],open:[[44,62]]},
+ quad_shot:{duration:116,track:96,hits:[],gun:[26,40,54,92],back:[0,14,.2],open:[[100,116]]},
+ quick_gun:{duration:36,hits:[],gun:[12],open:[[20,36]]},
+ spear_thrust:{duration:66,perilous:'thrust',track:24,hits:[{t:36,type:'thrust',reach:4.7,hp:26,posture:28}],adv:[[22,36,.24,1.4]],open:[[48,66]]},
+ spear_sweep:{duration:70,perilous:'sweep',hits:[{t:36,type:'sweep',reach:5,arc:2,hp:26,posture:28}],open:[[46,70]]},
+ spear_spiral:{duration:90,hits:[H(46,{ring:true,reach:8.5,arc:3.2,hp:20,posture:22})],rings:[46],open:[[58,90]]},
+ three_thrust:{duration:92,hits:[22,40,56,74].map(t=>H(t,{reach:3.6,hp:12,posture:14,parry:9})),adv:[[0,70,.03,2,true]],next:'spear_thrust'},
+ heavy_chops:{duration:96,hits:[30,60].map(t=>H(t,{type:'slam',reach:3.6,arc:.9,hp:20,posture:30,parry:14})),adv:[[0,40,.03,2,true]],open:[[80,96]]},
+ // Lightning: Tomoe's bolt and the double slanted flash join the spear arsenal (S27, S28, S30); the reversal stuns him.
+ double_flash:{duration:76,hits:[],waves:[[30,'h'],[44,'h']],open:[[54,76]]},
+ thunder_chop:{duration:72,hits:[H(42,{type:'slam',reach:3.6,arc:.9,hp:24,posture:30,parry:20,window:-4})],adv:[[0,30,.04,2,true]],open:[[58,72]]}
+ };
+ const ISSHIN={moves:ISSHIN_MOVES,radius:.5,height:1.95,kickRange:2.15,names:['Lightning Swordsman','Old Sword-and-Spear Master','Old Sword-and-Spear Master','Old Sword-and-Spear Master'],forms:['tomoe','isshin_sword','isshin_spear','isshin_lightning'],
+ // [easy, normal, hard] pools for Isshin's sword bar. BWIKI base (S28, S29): Genichiro 2556 / 750 / 30 per s (25 s), Isshin 2240 / 660 / 60 per s
+ // (11 s); his spear and lightning bars carry HP x1.27 each. The page leaves stacking open: read as not stacked (engineering choice).
+ anchors:{hp:[148,700,2500],posture:[330,800,1560],recover:11,rest:[70,32,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.15]},
+ tune(d){const a=this.anchors,hp=tier(d,a.hp),posture=tier(d,a.posture),bar=(h,x,s,table)=>{const px=Math.round(x);return {hp:Math.round(h),posture:px,regen:px/(s*60),table};};
+ return {bars:[bar(hp*I.tomoeHP,posture*I.tomoePosture,I.tomoeRecover,'std'),bar(hp,posture,a.recover,'gen12'),bar(hp*I.spearHP,posture,a.recover,'gen12'),bar(hp*I.spearHP,posture,a.recover,'gen12')],
+ rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};},
+ extra:()=>({lightning:false,lastLightningAt:-999,extraShot:0}),
+ start(g){g.startMove('mortal_blade');},
+ idle(g){const b=g.boss,p=g.player;g.face(b,p);if(dist(b,p)>2.25)g.advance(.058*g.tune.chase,2.2);
+ if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));},
+ choose(g){const b=g.boss,p=g.player,d=dist(b,p),r=N.rand(g),phase=b.phase,pick=a=>a[Math.floor(N.rand(g)*a.length)];
+ // Items and distance both draw the dash or the leap (S27); Genichiro answers healing with his sword dive (S01).
+ if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return phase===1?'dive_ready':phase===2?'dash_slash':'leap_slam';}
+ if(phase===1){if(N.rand(g)5)return r<.6?'leap_thrust':'volley';
+ return pick(['double','passage','swipe5','jump_slam','leap_thrust','running_grab','sweep','thrust','kick_arrow','bow_roll']);}
+ if(phase===4&&N.rand(g)<(g.t-b.lastLightningAt>I.lightningDue?I.lightningDueChance:I.lightningChance))return N.rand(g)<.5?'lightning_slash':'lightning_sweep';
+ if(phase===2){if(d>6)return pick(['dash_slash','dragon_flash','wind_v','cross']);
+ if(d<2.6&&r<.3)return 'smack_sweep';
+ return pick(['cross','ichimonji','dragon_flash','spiral','combo','overhead','pose_thrust','smack_sweep','dash_slash']);}
+ if(d>7)return pick(phase===4?['quad_shot','double_flash','leap_slam','spear_spiral']:['quad_shot','double_disc','leap_slam','spear_spiral']);
+ const list=['double_disc','leap_slam','quad_shot','spear_thrust','spear_sweep','spear_spiral','three_thrust','heavy_chops','wind_v'];
+ return pick(phase===4?[...list,'double_flash','thunder_chop']:list);},
+ onStart(g,name){GENICHIRO.onStart(g,name);},
+ followUp(g,move){const b=g.boss;
+ if(b.chainNext==='thrust_followup')return dist(b,g.player)>G.thrustFollowRange?'quick_bow':'running_grab';
+ if(b.chainNext)return b.chainNext;
+ const next=ISSHIN_MOVES[move].next;if(next)return next;
+ if(move==='jump_slam')return 'tomoe_slash';
+ if(move==='tomoe_slash')return 'thrust';
+ if(move==='passage'&&N.rand(g)=from&&t=m.back[0]&&t=m.leap[0]&&t4.5){g.stats.passageCancels++;g.emit('passage_cancel');g.startMove('quick_bow');}
+ return;}
+ for(const [at,kind] of m.waves||[])if(t===at)g.airWave(kind);
+ for(const at of m.gun||[])if(t===at)g.bullet();
+ for(const at of m.rings||[])if(t===at){const reach=m.hits.find(h=>h.t===at)?.reach||6;g.hazards.push({type:move==='mortal_blade'?'mortal_arc':'ring',x:b.x,y:.3,z:b.z,yaw:b.yaw,radius:reach,age:0,life:18});g.emit(move==='mortal_blade'?'mortal_blade':'ring');}},
+ // Genichiro: as on the castle top. Isshin's middle stance turns the third cut: two guards, then a plain counter or a pose and a perilous thrust (S28, S30).
+ playerHit(g,kind,open){const b=g.boss,p=g.player,busy=b.state==='attack';
+ if(b.phase===1){GENICHIRO.playerHit(g,kind,open);return;}
+ // Engineering choice, extrapolated from S28's general note on hyper armor: a cut lands on the gathering bolt but does not stop the leap, so the reversal stays the answer (S27, S30).
+ if(open){const armored=busy&&b.lightning&&b.moveTick<100;g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);if(!armored)g.interruptBoss(C.hitStun);g.fx('cut',b);return;}
+ b.guardCount++;
+ if(b.guardCount>=3){b.guardCount=0;g.stats.bossDeflects++;p.posture=Math.min(p.maxPosture,p.posture+4);p.postureDelay=C.playerPostureDelay;g.fx('boss_deflect',b);g.emit('boss_deflect');
+ // Repeated cuts against the spear draw the retreating sweep (S27).
+ if(!busy||b.moveTick<9)g.startMove(b.phase>=3?(N.rand(g)b.phase===1?[1,1]:[3,5-b.phase]
+ };
+ /* ---------------------------------------------------------------- Gyoubu Masataka Oniwa (Ashina Castle Gate) */
+ // The only mounted boss: no guard, hyper armor until his poise breaks, the horse carries him past and away (S31, S32). There is no
+ // grappling hook here: after riding off he always wheels and charges back, and his rope spear punishes standing far away.
+ const O={poiseSlash:50,poiseThrust:75,poiseReset:1500,flinch:44,sharp:.6,upper:3,lower:.7,upperFrom:.6,walk:.09,turn:.05,turnRide:.2,rideOffNext:.6,tripleSweep:.6,flickRide:.7,comboRide:.35,rearAngle:2.4,sideAngle:.6};
+ const GYOUBU_MOVES={
+ // He talks first and can be cut during it (S31).
+ intro:{duration:150,hits:[],open:[[0,150]],next:'charge_sweep'},
+ // On foot-pace: three cuts, the third staggers him when deflected (S31); the flick from his right flank usually rides off (S31, S32).
+ combo3:{duration:112,track:20,hits:[H(28,{reach:3.8,arc:1.5,hp:14,posture:16,parry:10}),H(46,{reach:3.8,arc:1.5,hp:12,posture:20}),H(84,{type:'slam',reach:4,arc:1.3,hp:18,posture:22,parry:22,stun:54})],open:[[96,112]]},
+ flick:{duration:52,track:10,hits:[H(20,{reach:3.4,arc:1.6,hp:12,posture:16})],open:[[34,52]]},
+ thrust_near:{duration:70,perilous:'thrust',track:28,hits:[{t:40,type:'thrust',reach:4.6,hp:24,posture:26}],open:[[52,70]]},
+ horse_kick:{duration:54,track:0,hits:[{t:22,type:'kick',rear:true,reach:3.2,arc:1.2,hp:16,posture:18,stagger:20}],open:[[34,54]]},
+ // Charges ride through: speed is set when the horse commits so it arrives at the contact tick, then carries on past (S31).
+ charge_sweep:{duration:96,perilous:'sweep',track:20,ride:[20,76,.3],arrive:52,hits:[{t:52,type:'sweep',reach:4.4,arc:2.2,hp:24,posture:26}],next:'wheel'},
+ figure8:{duration:100,track:18,ride:[18,80,.28],arrive:50,hits:[42,50,58].map(t=>H(t,{reach:4,arc:1.8,hp:11,posture:14,parry:8,window:-3})),next:'wheel'},
+ triple_charge:{duration:96,track:18,ride:[18,76,.28],arrive:54,hits:[44,54,64].map(t=>H(t,{reach:4,arc:1.8,hp:12,posture:22,parry:9}))},
+ late_charge:{duration:92,track:18,ride:[18,72,.28],arrive:46,hits:[H(58,{reach:4.2,arc:3.2,hp:14,posture:18,parry:12})],next:'wheel'},
+ // The horse turns round after a pass: this is the opening that closing in with the hook gives in the original.
+ wheel:{duration:64,track:64,trot:[18,64,.06],hits:[],open:[[0,64]]},
+ turn_about:{duration:26,track:26,hits:[]},
+ ride_off:{duration:50,track:0,away:[0,44,.3],hits:[]},
+ gallop:{duration:40,track:40,chaseAt:.32,chaseTo:9,hits:[]},
+ jump_attack:{duration:96,track:12,leap:[12,50,3.2],hits:[H(50,{type:'slam',reach:3.6,arc:1.6,hp:18,posture:22,parry:24}),H(68,{type:'slam',reach:3.6,arc:1.6,hp:18,posture:22,parry:24})],open:[[82,96]]},
+ // The spearhead on its rope: three wide circles that can be guarded or deflected, and a line that can only be deflected (S31, S34).
+ rope_sweep:{duration:122,track:100,hits:[40,68,96].map(t=>H(t,{reach:9.5,arc:3.2,hp:12,posture:16,parry:11})),rings:[40,68,96],open:[[106,122]]},
+ rope_thrust:{duration:78,perilous:'thrust',track:36,hits:[{t:44,type:'rope',noBlock:true,reach:12,arc:.3,hp:22,posture:24,parry:18}],line:[44],open:[[56,78]]},
+ rising:{duration:1,hits:[]}
+ };
+ const GYOUBU={moves:GYOUBU_MOVES,radius:1,height:2.9,kickRange:2.6,kickAnyHeight:true,names:['Mounted Spear General','Mounted Spear General'],forms:['gyoubu','gyoubu'],
+ // [easy, normal, hard] pools, calibrated to the windows. BWIKI base (S32): HP 2552, posture 660, 30 per s (22 s), total poise 360, reset 25 s. No source gives a difference between his two bars.
+ anchors:{hp:[650,1800,6500],posture:[1200,2000,2400],recover:22,poise:[220,300,360],rest:[90,32,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.15]},
+ tune(d){const a=this.anchors,hp=Math.round(tier(d,a.hp)),posture=Math.round(tier(d,a.posture)),poise=Math.round(tier(d,a.poise)),bar={hp,posture,regen:posture/(a.recover*60),table:'std',poise};
+ return {bars:[bar,{...bar}],rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};},
+ extra:()=>({poise:0,poiseMax:0,poiseAt:-9999,rideX:0,rideZ:0}),
+ start(g){const b=g.boss;b.poise=b.poiseMax=g.tune.bars[0].poise;g.startMove('intro');},
+ idle(g){const b=g.boss,p=g.player;g.turn(b,A(p.x-b.x,p.z-b.z),O.turn);if(dist(b,p)>3.4)g.advance(O.walk*g.tune.chase,3.2);
+ if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));},
+ // Right flank: the spear hand; left flank: he prefers to turn; directly behind: the hind legs (S32).
+ choose(g){const b=g.boss,p=g.player,d=dist(b,p),rel=N.angle(A(p.x-b.x,p.z-b.z)-b.yaw),pick=a=>a[Math.floor(N.rand(g)*a.length)];
+ if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return d>6?'rope_thrust':'triple_charge';}
+ if(d>9)return pick(['rope_sweep','rope_thrust','gallop']);
+ if(d>5)return pick(['triple_charge','figure8','late_charge','jump_attack','rope_sweep','rope_thrust','charge_sweep']);
+ if(Math.abs(rel)>O.rearAngle)return 'horse_kick';
+ if(rel>O.sideAngle)return 'turn_about';
+ return pick(rel<-O.sideAngle?['combo3','flick','thrust_near','flick','ride_off']:['combo3','thrust_near','jump_attack','ride_off','ride_off']);},
+ onStart(g,name){g.boss.lightning=false;},
+ followUp(g,move){const b=g.boss;if(b.chainNext)return b.chainNext;const next=GYOUBU_MOVES[move].next;if(next)return next;
+ if(move==='triple_charge')return N.rand(g){const r=N.rand(g);return r<.4?'charge_sweep':r<.7?'triple_charge':r<.85?'figure8':'late_charge';};
+ if(move==='ride_off'){if(N.rand(g)>=O.rideOffNext)return N.rand(g)<.5?'rope_sweep':'rope_thrust';return dist(b,g.player)>12?'gallop':charge();}
+ if(move==='gallop')return dist(b,g.player)>12?'gallop':charge();
+ if(move==='turn_about'){const r=N.rand(g);return r<.4?'combo3':r<.7?'thrust_near':'flick';}
+ if(move==='combo3'&&N.rand(g)=from&&t=from)g.turn(b,b.aim,O.turnRide);}
+ if(m.away&&t>=m.away[0]&&t=m.trot[0]&&t=a&&t=a&&t=32&&t<40)g.advanceCommitted(.2,2);},
+ afterHits(g,move,m,t){const b=g.boss;
+ for(const at of m.rings||[])if(t===at){g.hazards.push({type:'ring',x:b.x,y:.3,z:b.z,yaw:b.yaw,radius:9.5,age:0,life:18});g.emit('rope_sweep');}
+ for(const at of m.line||[])if(t===at){g.hazards.push({type:'rope_line',x:b.x,y:1.9,z:b.z,yaw:b.aim,radius:12,age:0,life:12});g.emit('rope_thrust');}},
+ // He cannot guard and hyper armor carries his attacks through; only a broken poise staggers him (S32). Cuts above the waist
+ // take x3 posture, the horse and his legs x0.7, and the blade takes x0.6 vitality (S32).
+ playerHit(g,kind){const b=g.boss,p=g.player,part=p.y>O.upperFrom?O.upper:O.lower;
+ g.damageBoss((kind==='thrust'?C.thrustDamage:C.slashDamage)*O.sharp,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit*part);g.fx('cut',b);if(b.deathblowAvailable||b.hp<=0)return;
+ if(b.action==='intro'&&b.state==='attack'){g.emit('intro_interrupted');g.startMove('charge_sweep');return;}
+ b.poise-=kind==='thrust'?O.poiseThrust:O.poiseSlash;b.poiseAt=g.t;
+ if(b.poise<=0){b.poise=b.poiseMax;g.stats.flinches++;g.stagger('stagger',O.flinch);g.emit('flinch_small');}},
+ onDeflect(g,hit){const b=g.boss;if(hit.stun&&b.state==='attack'){g.stagger('stagger',hit.stun);g.emit('combo_staggered');}},
+ special(g){const b=g.boss;if(g.t-b.poiseAt>O.poiseReset)b.poise=b.poiseMax;return false;},
+ finish(g){const b=g.boss;if(b.phase===2){g.win();return;}
+ g.nextBar();b.poise=b.poiseMax=g.tune.bars[1].poise;b.source_phase=2;b.state='stunned';b.stun=G.riseOpen;b.action='rising';b.actionTick=0;},
+ markers:b=>[2,3-b.phase]
+ };
+ /* ---------------------------------------------------------------- Demon of Hatred (Ashina Castle Gate, in flames) */
+ // Three bars, no guard, hyper armor until its poise breaks; most blows miss the space under its belly (S37, S39). Fire arms cannot be
+ // deflected and guarding them still builds Burn, which drains vitality and stops posture recovery (S38, S39). Timings are calibration values.
+ const D={poiseSlash:50,poiseThrust:75,poiseReset:1500,flinch:40,turn:.045,walk:.06,belly:2.05,rise3:80,
+ burnDecay:.15,burnTicks:300,burnDrain:.05,fireLeak:.3,fireRate:1.4,ringRadius:7.5,ringWidth:.55,ringLife:480,ringBurn:30,ringPush:1.4,
+ lobFlight:52,lobGravity:.012,lobBlast:1.5,homingSpeed:.2,homingTurn:.075,homingClimb:.07,homingFor:66,homingFall:.006,shotSpeed:.34,waveSpeed:.36,
+ doubleCharge:.75,fireSweep:.5,secondVolley:.35,headbutt2:.3,chargeRanged:.55,burstRadius:5,burstPush:2.5};
+ const FIRE=o=>H(o.t,Object.assign({noDeflect:true,burn:24,leak:D.fireLeak,reach:4.3,arc:1.5,inner:D.belly,hp:15,posture:14},o));
+ const DEMON_MOVES={
+ arm_swing:{duration:72,track:24,hits:[H(32,{reach:4.3,arc:1.5,inner:D.belly,hp:14,posture:16,parry:12})],open:[[52,72]]},
+ // Right foot held up about a second (S36); both feet on his left (S36), weaker than the single stomp (S39).
+ stomp:{duration:84,track:30,hits:[H(50,{type:'slam',reach:3.2,arc:2.2,hp:18,posture:20,parry:16})],open:[[64,84]]},
+ double_stomp:{duration:100,track:24,hits:[40,66].map(t=>H(t,{type:'slam',reach:3.2,arc:2.4,hp:13,posture:15,parry:12})),open:[[80,100]]},
+ headbutt:{duration:76,track:30,hits:[H(42,{type:'slam',reach:4.6,arc:.75,inner:D.belly,hp:20,posture:22,parry:16})],open:[[56,76]]},
+ // Fire arm twice, a stomp, the fire arm again (S39).
+ fire_combo:{duration:154,track:20,hits:[FIRE({t:30}),FIRE({t:52}),H(90,{type:'slam',reach:3.2,arc:2.2,hp:15,posture:17,parry:13}),FIRE({t:124,hp:17})],open:[[138,154]]},
+ fire_throw:{duration:92,track:30,shots:[34,58],hits:[],open:[[70,92]]},
+ // Fireballs lobbed with each wave of the hands, the last with the last wave (S36).
+ fireballs:{duration:124,track:96,lobs:[40,52,64,76,98],hits:[],open:[[0,30],[104,124]]},
+ whip_slam:{duration:104,track:40,hits:[FIRE({t:58,type:'slam',reach:12.5,arc:.15,inner:0,hp:18,posture:18,burn:30})],trail:58,open:[[70,104]]},
+ // Unblockable: run, or be in the air as it lands; about a second open after landing, in place of the grappling hook (S36, S39).
+ blast_leap:{duration:154,track:50,leap:[50,82,3.6],hits:[{t:82,type:'blast',reach:6,arc:Math.PI,hp:28,posture:30,burn:45,push:2.4}],open:[[96,154]]},
+ charge:{duration:88,perilous:'sweep',track:30,ride:[30,78,.3],arrive:54,hits:[{t:54,type:'sweep',reach:3.6,arc:1.4,hp:24,posture:24}]},
+ charge_back:{duration:76,perilous:'sweep',track:18,ride:[18,66,.3],arrive:42,hits:[{t:42,type:'sweep',reach:3.6,arc:1.4,hp:24,posture:24}]},
+ fire_sweep:{duration:74,perilous:'sweep',track:26,hits:[{t:38,type:'sweep',reach:4.4,arc:1.7,hp:18,posture:20,burn:30}],open:[[52,74]]},
+ kick_wave:{duration:92,track:36,waves:[46],hits:[],open:[[60,92]]},
+ // Homing fireballs; the stomp and pose at the end is the opening (S36).
+ homing:{duration:164,track:90,homing:[34,44,54,64,74,84],hits:[],open:[[124,164]]},
+ // Phase 3 opens with the fire ring, then three whip swings: jump the low one, stay down under the high one, get behind the last (S36, S39).
+ fire_ring:{duration:196,perilous:'sweep',track:150,ringAt:40,hits:[FIRE({t:84,type:'sweep',reach:6,arc:Math.PI,inner:0,burn:26,hp:16,posture:18}),FIRE({t:128,onlyAir:true,reach:6,arc:Math.PI,inner:0,burn:26,hp:16,posture:18}),FIRE({t:166,type:'slam',reach:5.5,arc:1.0,inner:0,burn:26,hp:18,posture:20})],open:[[178,196]]},
+ turn_about:{duration:30,track:30,hits:[]},
+ // After the first deathblow: crouched and immune, a small blast that pushes without damage, then a leap back (S36).
+ crouch:{duration:150,invulnerable:true,hits:[],burst:140,next:'leap_back'},
+ leap_back:{duration:56,track:0,back:[24,48,.18],hits:[],open:[[0,26]]},
+ rising:{duration:1,hits:[]}
+ };
+ const DEMON={moves:DEMON_MOVES,radius:1.1,height:4.4,kickRange:3.0,kickAnyHeight:true,names:['Flame Behemoth','Flame Behemoth','Flame Behemoth'],forms:['demon','demon','demon'],
+ // [easy, normal, hard] per-bar pools, calibrated to the windows. BWIKI base (S37): HP 3195, posture 1050, 30 per s (35 s), poise 640, reset 25 s.
+ // No source gives a per-bar difference, so the three bars are equal.
+ anchors:{hp:[600,1600,4200],posture:[1200,2000,3200],recover:35,poise:[400,520,640],rest:[80,34,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.1]},
+ tune(d){const a=this.anchors,hp=Math.round(tier(d,a.hp)),posture=Math.round(tier(d,a.posture)),poise=Math.round(tier(d,a.poise)),bar={hp,posture,regen:posture/(a.recover*60),table:'std',poise};
+ return {bars:[bar,{...bar},{...bar}],rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};},
+ extra:()=>({poise:0,poiseMax:0,poiseAt:-9999,rideX:0,rideZ:0,leapSpeed:0,ringDue:false,waveDue:false,repeat:0,lastMove:''}),
+ playerExtra:()=>({burn:0,burning:0,burnFed:false}),statsExtra:()=>({burns:0}),
+ start(g){const b=g.boss;b.poise=b.poiseMax=g.tune.bars[0].poise;b.state='idle';b.action='idle';b.cooldown=40;},
+ idle(g){const b=g.boss,p=g.player;g.turn(b,A(p.x-b.x,p.z-b.z),D.turn);if(dist(b,p)>3.6)g.advance(D.walk*g.tune.chase,3.4);
+ if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));},
+ // Negative relative angle = his right flank (same sign as Gyoubu's).
+ choose(g){const b=g.boss,p=g.player,d=dist(b,p),rel=N.angle(A(p.x-b.x,p.z-b.z)-b.yaw),ph=b.phase,pick=a=>a[Math.floor(N.rand(g)*a.length)];
+ if(b.ringDue)return 'fire_ring';
+ if(b.waveDue){b.waveDue=false;if(d>6)return 'kick_wave';}
+ if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return d>6?'fireballs':'charge';}
+ if(d>9)return pick(ph>=2?['fireballs','whip_slam','charge','kick_wave','homing']:['fireballs','whip_slam','charge']);
+ if(d>5)return pick(ph>=2?['fire_throw','charge','whip_slam','blast_leap','homing','kick_wave']:['fire_throw','charge','whip_slam','blast_leap']);
+ if(Math.abs(rel)>2.3)return N.rand(g)<.5?'turn_about':'blast_leap';
+ if(d.6)return pick(['double_stomp','arm_swing','fire_combo']);
+ return pick(['headbutt','arm_swing','fire_combo','charge']);},
+ onStart(g,name){const b=g.boss;b.lightning=false;b.repeat=name===b.lastMove?b.repeat+1:1;b.lastMove=name;},
+ followUp(g,move){const b=g.boss,d=dist(b,g.player),next=DEMON_MOVES[move].next,pick=a=>a[Math.floor(N.rand(g)*a.length)];if(next)return next;
+ if(move==='charge'&&b.phase===3&&N.rand(g)=2?['fireballs','whip_slam','fire_throw','homing','kick_wave']:['fireballs','whip_slam','fire_throw']);return null;}
+ if(move==='fireballs'&&b.repeat<2&&d>6&&N.rand(g)=from&&t=a&&t=a&&t=m.back[0]&&t=2;
+ for(let r=2.5;r<=12.5;r+=2)for(const s of wide?[-1.6,0,1.6]:[0])g.hazards.push({type:'fire',x:b.x+Math.sin(a)*r+Math.cos(a)*s,y:0,z:b.z+Math.cos(a)*r-Math.sin(a)*s,radius:1,age:0,life:150,rate:D.fireRate});g.emit('fire_trail');},
+ playerHit(g,kind){const b=g.boss;
+ g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);g.fx('cut',b);if(b.deathblowAvailable||b.hp<=0)return;
+ b.poise-=kind==='thrust'?D.poiseThrust:D.poiseSlash;b.poiseAt=g.t;
+ if(b.poise<=0){b.poise=b.poiseMax;g.stats.flinches++;g.stagger('stagger',D.flinch);g.emit('flinch_small');}},
+ onDeflect(){},
+ special(g){const b=g.boss;if(g.t-b.poiseAt>D.poiseReset)b.poise=b.poiseMax;return false;},
+ finish(g){const b=g.boss;if(b.phase===3){g.win();return;}
+ g.nextBar();b.poise=b.poiseMax=g.tune.bars[b.phase-1].poise;b.source_phase=b.phase;
+ if(b.phase===2){b.waveDue=true;g.startMove('crouch');}
+ else{b.ringDue=true;b.state='stunned';b.stun=D.rise3;b.action='rising';b.actionTick=0;}},
+ markers:b=>[3,4-b.phase]
+ };
+ const KINDS={genichiro:GENICHIRO,ape:APE,butterfly:BUTTERFLY,isshin:ISSHIN,gyoubu:GYOUBU,demon:DEMON};
+ const CASES={
+ 'sekiro/genichiro':{kind:'genichiro',name:'Bow-and-Blade Swordsman · Castle rooftop (three deathblows)',arena:{shape:'rect',halfWidth:8,halfDepth:6,pillars:[]},player:[0,4.2],boss:[0,-3.6]},
+ 'sekiro/guardian_ape':{kind:'ape',name:'Guardian Ape · Valley pool (feigned death and second phase)',arena:{shape:'circle',radius:14.5,pillars:[]},player:[0,6.5],boss:[0,-5]},
+ 'sekiro/lady_butterfly':{kind:'butterfly',name:'Thread-Wielding Shinobi · Old estate courtyard (threads and illusions)',arena:{shape:'rect',halfWidth:9.5,halfDepth:7.5,pillars:[-6.6,-2.2,2.2,6.6].flatMap(x=>[{x,z:-4.6,r:.42},{x,z:4.6,r:.42}])},player:[0,3.2],boss:[0,-3.2]},
+ 'sekiro/isshin':{kind:'isshin',name:'Old Sword-and-Spear Master · Pampas field (Lightning Swordsman and three master phases)',arena:{shape:'circle',radius:13,pillars:[]},player:[0,4.5],boss:[0,-4.5]},
+ 'sekiro/gyoubu':{kind:'gyoubu',name:'Mounted Spear General · Castle gate (charges and rope spear)',arena:{shape:'circle',radius:19,pillars:[]},player:[0,6],boss:[0,-6]},
+ 'sekiro/demon':{kind:'demon',name:'Flame Behemoth · Burning castle gate (fire and burn)',arena:{shape:'circle',radius:17,pillars:[]},player:[0,6.5],boss:[0,-6.5]}
+ };
+
+ const M=root.SekiroGame={id:'sekiro_remake',version:'sekiro@12',hz:60,maxSeconds:300,dimension:'3d',renderer:'webgl-boss3d',
+ title:'Sekiro · Shadows Die Twice',tiers:TIERS,cases:Object.entries(CASES).map(([id,c])=>({id,name:c.name})),
+ tuning:C,genichiro:G,ape:P,butterfly:L,moves:GEN_MOVES,isshin:I,gyoubu:O,demon:D,bosses:{genichiro:GENICHIRO,ape:APE,butterfly:BUTTERFLY,isshin:ISSHIN,gyoubu:GYOUBU,demon:DEMON},caseKinds:Object.fromEntries(Object.entries(CASES).map(([id,c])=>[id,c.kind])),
+ controls:{'W A S D':'Move relative to the camera; there is no stamina bar. Hold Shift to sprint','mouse dx':'Turn the free camera with horizontal mouse movement. After pressing E to lock on, the camera tracks the boss and horizontal mouse movement no longer turns it',
+ 'J / LMB':'Tap to slash or hold to charge a thrust. When the red marker appears nearby, press attack again for a deathblow','K / RMB':'Hold to block; press just before impact to deflect. Repeated presses shorten the deflect window',
+ 'Shift':'Press to dodge. Dodge toward a perilous thrust to counter it; dodge sideways or backward to escape a perilous grab','Space':'Jump over a perilous low sweep, then press jump again near the enemy to kick off them',
+ 'Q':'Healing gourd (the Bow-and-Blade Swordsman always punishes healing while idle)','E':'Toggle lock-on (off at the start)','R':'Resurrect after death (subject to resurrection nodes and seals; terror deaths cannot be reversed)',
+ 'Airborne J / LMB':'Lightning reversal: catch lightning in the air, then attack again before landing to send it back','Posture broken':'Press Shift or Space during stagger to recover sooner',
+ 'Status':'Poison builds from gas and dung, then drains health. Terror builds from the ape’s phase-two scream and kills at full gauge; move away to avoid it','Illusions':'The shinobi’s summoned illusions vanish after one hit. Homing butterflies pursue you; pillars can block them','Mounted Spear General':'The mounted general does not block. Hits land but interrupt him only when his poise breaks. Jumping slashes to his upper body deal more posture damage. He turns and charges back after riding away (there is no grappling rope); standing directly behind the horse risks a kick','Flame Behemoth':'The behemoth does not block and staggers only when its poise breaks. Staying under its belly avoids most moves. Its flaming arm cannot be deflected; blocking reduces damage but builds burn. Full burn drains health and prevents posture recovery. Jump over perilous charges and fire-ring sweeps. Run from the explosive leap or be airborne at impact. The phase-three fire ring knocks you back and burns you','Old Sword-and-Spear Master':'Red-blade ranged slashes cannot be blocked; dodge or run away. Spirit blades chip through blocks, while deflecting avoids posture damage; jumping and sidestepping also work. Blocking bullets from the spear phase costs heavy posture. A four-shot volley is always followed by a perilous attack'}};
+ function newBody(x,z,hp,r){return {x,y:0,z,yaw:Math.PI,hp,maxHp:hp,r,posture:0,maxPosture:C.posture,postureDelay:0,action:'idle',actionTick:0,flash:0,hurt:0};}
+ function openAt(m,tick,connected=true){const inside=w=>tick>=w[0]&&ticks+b.hp,0);this.nextMinion=1;
+ this.stats={moves:{},deflects:0,blocks:0,guardBreaks:0,safetyRolls:0,mikiri:0,sweepJumps:0,stomps:0,grabEscapes:0,
+ lightningReversals:0,lightningCatches:0,lightningFailures:0,deathblows:0,resurrections:0,deaths:0,gourdsUsed:0,healsApplied:0,
+ healPunishes:0,passageOpenings:0,passageCancels:0,healthHits:0,bossDeflects:0,bossBlocks:0,playerAttacks:0,perilousFailures:0,playerHits:0,
+ postureBreaks:0,vitalityBreaks:0,poisoned:0,terrorDeaths:0,flinches:0,apeRolls:0,neckOpenings:0,falseExecutions:0,illusionsSummoned:0,illusionsKilled:0,butterflies:0,butterflyHits:0,pillarBlocks:0,...K.statsExtra?.()};
+ K.start(this);
+ }
+ get K(){return KINDS[this.kind];}
+ get moves(){return KINDS[this.kind].moves;}
+ state(){return N.copy(this);}
+ emit(name){this.events.push(name);}
+ fx(type,at,life=15){this.effects.push({type,x:at.x,y:(at.y||0)+.9,z:at.z,life,maxLife:life});}
+ face(o,target){o.yaw=A(target.x-o.x,target.z-o.z);}
+ turn(o,yaw,rate){o.yaw=N.angle(o.yaw+N.clamp(N.angle(yaw-o.yaw),-rate,rate));}
+ confine(o){const a=this.arena;
+ if(a.shape==='circle'){const r=Math.hypot(o.x,o.z),lim=a.radius-o.r;if(r>lim){o.x*=lim/r;o.z*=lim/r;}}
+ else{o.x=N.clamp(o.x,-a.halfWidth+o.r,a.halfWidth-o.r);o.z=N.clamp(o.z,-a.halfDepth+o.r,a.halfDepth-o.r);}
+ for(const q of a.pillars){const dx=o.x-q.x,dz=o.z-q.z,d=Math.hypot(dx,dz),min=q.r+o.r;if(d1e-9?dx/d:1,nz=d>1e-9?dz/d:0;o.x=q.x+nx*min;o.z=q.z+nz*min;}}}
+ move(o,dx,dz){o.x+=dx;o.z+=dz;this.confine(o);}
+ // Steer around a pillar standing in the straight line to the target, so no boss can stall behind one.
+ heading(o,tx,tz){let a=A(tx-o.x,tz-o.z);const far=Math.hypot(tx-o.x,tz-o.z);
+ for(const q of this.arena.pillars){const qx=q.x-o.x,qz=q.z-o.z,along=qx*Math.sin(a)+qz*Math.cos(a),side=qx*Math.cos(a)-qz*Math.sin(a);
+ if(along>0&&along1e-3?-1:1,tx2=-k*vz/len,tz2=k*vx/len;a=A(tx2*.8+Math.sin(a)*.4,tz2*.8+Math.cos(a)*.4);break;}}
+ return a;}
+ toward(o,tx,tz,speed,min){const d=Math.hypot(tx-o.x,tz-o.z);if(d<=min)return;const a=this.heading(o,tx,tz),s=Math.min(speed,d-min);this.move(o,Math.sin(a)*s,Math.cos(a)*s);}
+ advance(speed,min=.9){const b=this.boss,p=this.player;this.toward(b,p.x,p.z,speed,min+(b.r-.5));}
+ advanceCommitted(speed,min=.9){const b=this.boss,travel=Math.min(speed,Math.max(0,b.commitDistance-min-(b.r-.5)));
+ this.move(b,Math.sin(b.aim)*travel,Math.cos(b.aim)*travel);b.commitDistance=Math.max(0,b.commitDistance-travel);}
+ postureFactor(o){const h=o.hp/o.maxHp;return o===this.boss?regenFactor(this.tune.bars[this.boss.phase-1].table,h):regenFactor('player',h);}
+ recoverPosture(o,boost=1){if(o.postureDelay>0||o.burning>0)return;const rate=o===this.boss?this.tune.bars[this.boss.phase-1].regen:C.postureRate;o.posture=Math.max(0,o.posture-rate*this.postureFactor(o)*boost);}
+ setPlayerAction(action){const p=this.player;if(p.action!==action){p.action=action;p.actionTick=0;}}
+ dodgeToward(){const p=this.player,b=this.boss,a=A(b.x-p.x,b.z-p.z);return p.dodgeX*Math.sin(a)+p.dodgeZ*Math.cos(a);}
+ startMove(name){
+ const b=this.boss,m=this.moves[name],p=this.player;if(!m)throw Error('Unknown move '+name);
+ b.state='attack';b.action=name;b.actionTick=0;b.moveTick=0;b.moveDuration=m.duration;b.perilous=m.perilous||null;b.chainNext=null;b.connected=false;
+ b.telegraph=m.perilousFrom?null:b.perilous;b.aim=A(p.x-b.x,p.z-b.z);if(this.kind!=='ape'&&this.kind!=='gyoubu'&&this.kind!=='demon')b.yaw=b.aim;b.commitDistance=dist(p,b);
+ this.K.onStart?.(this,name);this.stats.moves[name]=(this.stats.moves[name]||0)+1;this.emit('move:'+name);
+ }
+ stagger(action,ticks){const b=this.boss;b.state='stunned';b.stun=ticks;b.action=action;b.actionTick=0;b.perilous=null;b.telegraph=null;b.lightning=false;b.chainNext=null;b.y=0;}
+ interruptBoss(ticks){const b=this.boss;if(b.deathblowAvailable||b.executing||b.state==='dead')return;b.state='stunned';b.stun=Math.max(b.stun,ticks);b.action='stagger';b.actionTick=0;b.perilous=null;b.telegraph=null;b.lightning=false;b.chainNext=null;}
+ // Apparent posture cap: the beast's posture cannot be broken by deflection alone in its first life (S16).
+ bossPosture(amount,deflect=false){const b=this.boss;if(b.deathblowAvailable||b.executing||b.state==='dead')return;
+ b.posture=Math.min(b.maxPosture,b.posture+amount);b.postureDelay=0;
+ if(deflect&&this.kind==='ape'&&b.form_id==='ape'&&b.posture>=b.maxPosture){b.posture=b.maxPosture-1;return;}
+ if(b.posture>=b.maxPosture)this.breakBoss();}
+ damageBoss(amount,posture=0){const b=this.boss;if(b.deathblowAvailable||b.executing||b.state==='dead')return;b.hp=Math.max(0,b.hp-amount);b.flash=8;this.stats.healthHits++;this.emit('boss_health_hit');
+ if(b.hp<=0)this.breakBoss();else this.bossPosture(posture);}
+ breakBoss(){const b=this.boss;if(b.executing||b.deathblowAvailable)return;if(b.hp<=0)this.stats.vitalityBreaks++;else this.stats.postureBreaks++;b.deathblowAvailable=true;b.deathblow=b.hp===0?-1:C.deathblowWindow;b.state='deathblow';b.action='posture_break';b.actionTick=0;b.perilous=null;b.telegraph=null;b.lightning=false;b.chainNext=null;b.neckExposed=0;this.emit('deathblow_available');}
+ execute(){
+ const b=this.boss,p=this.player;if(!b.deathblowAvailable||dist(p,b)>C.deathblowReach+b.r||p.y>.2||p.dead)return false;
+ b.deathblowAvailable=false;b.executing=C.executionFrames;b.state='execution';b.action='deathblow';b.actionTick=0;b.hp=0;b.y=0;
+ p.inv=C.executionFrames+8;p.stagger=0;p.postureBroken=false;p.lightning=0;p.attackTick=-1;p.charge=0;p.healTick=0;p.dodgeTicks=0;this.setPlayerAction('deathblow');
+ this.hazards=[];this.minions=[];this.stats.deathblows++;p.resurrectionLocked=false;this.emit('deathblow');return true;
+ }
+ finishExecution(){this.K.finish(this);}
+ win(){this.outcome='win';this.emit('shinobi_execution');}
+ nextBar(){const b=this.boss,bar=this.tune.bars[b.phase];b.phase++;b.healthbar_phase=b.phase;
+ b.hp=b.maxHp=bar.hp;b.maxPosture=bar.posture;b.posture=0;b.postureDelay=0;b.guardCount=0;b.y=0;b.stun=0;b.perilous=null;b.telegraph=null;b.neckExposed=0;
+ const p=this.player;p.posture=0;p.postureDelay=0;p.inv=25;p.lightning=0;this.setPlayerAction('idle');
+ this.hazards=[];this.minions=[];this.emit('phase:'+b.phase);}
+ breakPlayer(){const p=this.player;p.stagger=C.guardBreakStagger;p.posture=35;p.postureBroken=true;p.attackTick=-1;p.charge=0;p.healTick=0;this.stats.guardBreaks++;this.setPlayerAction('posture_break');this.emit('guard_break');}
+ die(terror=false){const p=this.player;p.dead=true;p.deathTimer=180;p.vy=0;p.guarding=false;p.lightning=0;p.postureBroken=false;p.terrorDeath=terror;this.stats.deaths++;if(terror)this.stats.terrorDeaths++;this.setPlayerAction('dead');this.emit(terror?'terror_death':'player_dead');}
+ hurtPlayer(hp,posture=0,stagger=16,bypass=false,scaled=true){
+ const p=this.player;if(p.dead||(!bypass&&p.inv>0))return;
+ p.hp=Math.max(0,p.hp-hp*(scaled?this.tune.dmg:1));p.posture=Math.min(p.maxPosture,p.posture+posture);p.postureDelay=C.playerPostureDelay;
+ p.hurt=12;p.inv=bypass?0:5;p.stagger=Math.max(p.stagger,stagger);p.attackTick=-1;p.charge=0;p.healTick=0;p.dodgeTicks=0;this.stats.playerHits++;
+ this.setPlayerAction('hurt');this.emit('player_hit');
+ if(p.hp<=0){this.die();return;}
+ if(p.posture>=p.maxPosture)this.breakPlayer();
+ }
+ revive(){const p=this.player;if(!p.dead||p.nodes<=0||p.resurrectionLocked||p.terrorDeath)return false;
+ p.nodes--;p.resurrections=p.nodes;p.resurrectionLocked=true;p.dead=false;p.hp=p.maxHp*C.reviveFraction;p.posture=0;p.stagger=0;p.y=0;p.vy=0;p.terror=0;
+ p.revive=C.reviveFrames;p.inv=C.reviveFrames+10;if(p.burning!==undefined){p.burn=0;p.burning=0;}p.attackTick=-1;p.healTick=0;this.setPlayerAction('revive');
+ this.interruptBoss(45);this.hazards=this.hazards.filter(q=>q.type==='gas');this.stats.resurrections++;this.emit('resurrection');return true;
+ }
+ guardFacing(source){return Math.abs(N.angle(A(source.x-this.player.x,source.z-this.player.z)-this.player.yaw))<1.55;}
+ blockOrDeflect(hit,source,kind='melee',move=null){
+ const p=this.player,b=this.boss;if(!p.guarding||p.stagger>0||!this.guardFacing(source))return false;
+ // A fire arm cannot be deflected: a fresh press takes the blow in full (S39).
+ if(hit.noDeflect&&p.guardAge=p.maxPosture)this.breakPlayer();
+ // Guarding fire still builds Burn (S38) and lets some of it through (S36, S39).
+ if(hit.burn&&!p.dead){this.burnUp(hit.burn);if(hit.leak){p.hp=Math.max(0,p.hp-hit.hp*hit.leak*this.tune.dmg);if(p.hp<=0)this.die();}}
+ }
+ p.postureDelay=C.playerPostureDelay;if(hit.push){const a=A(p.x-source.x,p.z-source.z);this.move(p,Math.sin(a)*hit.push,Math.cos(a)*hit.push);}return true;
+ }
+ reaches(hit,src){const p=this.player,d=dist(src,p),angle=Math.abs(N.angle(A(p.x-src.x,p.z-src.z)-src.yaw));return d<=hit.reach&&d>=(hit.inner||0)&&(hit.rear?Math.PI-angle:angle)<=(hit.arc||1.13);}
+ strike(hit,move,src){
+ const b=this.boss,p=this.player,fromBoss=src===b;if(p.dead||p.revive||b.executing||(fromBoss&&b.deathblowAvailable))return;
+ // onlyAir: a high swing that passes over a grounded Sekiro (S36).
+ const reach=this.reaches(hit,src)&&!(hit.onlyAir&&p.y<=C.sweepHeight);
+ if(this.probe)this.probe.push({i:this.probeTick,kind:'melee',type:hit.type,move,reach,src:fromBoss?'boss':'minion',noJump:!!hit.noJump,dodge:!!hit.dodge,noDeflect:!!hit.noDeflect,facing:this.guardFacing(src)});
+ if(!reach)return;
+ if(hit.type==='sweep'){
+ if(p.y>C.sweepHeight){this.stats.sweepJumps++;this.emit('sweep_avoided');return;}
+ b.connected=true;this.stats.perilousFailures++;this.hurtPlayer(hit.hp,hit.posture,25,true);if(hit.burn)this.burnUp(hit.burn);return;
+ }
+ // The Demon's explosive landing: no guard; be out of reach or in the air (S36, S39).
+ if(hit.type==='blast'){if(p.y>.9){this.emit('blast_avoided');return;}b.connected=true;this.stats.perilousFailures++;this.hurtPlayer(hit.hp,hit.posture,30,true);
+ if(!p.dead){const a=A(p.x-src.x,p.z-src.z);this.move(p,Math.sin(a)*hit.push,Math.cos(a)*hit.push);this.burnUp(hit.burn);}return;}
+ if(hit.type==='grab'){
+ // No deflect or guard. Genichiro: jump or step aside; a forward (Mikiri) step is still caught. The ape's floor
+ // swipe is jumped; its belly flop and Lady Butterfly's aerial grab are escaped only by distance (S05, S14, S19).
+ if((!hit.noJump&&p.y>C.grabJumpHeight)||(hit.dodge&&p.dodgeTicks>=C.dodgeFrames-C.dodgeInv&&this.dodgeToward()<=.55)){this.stats.grabEscapes++;this.emit('grab_avoided');return;}
+ b.connected=true;this.stats.perilousFailures++;this.emit('grabbed');this.hurtPlayer(hit.hp,hit.posture,40,true);return;
+ }
+ if(hit.type==='lightning'){this.catchLightning();return;}
+ // Isshin's circular force wave: jump it, deflect it as his arm moves, or be elsewhere (S27).
+ if(hit.ring&&p.y>C.sweepHeight){this.emit('ring_jumped');return;}
+ if(hit.type==='mortal'){if(p.dodgeTicks>=C.dodgeFrames-C.dodgeInv){this.emit('mortal_avoided');return;}b.connected=true;this.stats.perilousFailures++;this.hurtPlayer(hit.hp,hit.posture,30,true);return;}
+ if(p.y>1.9&&hit.type!=='slam')return;
+ if(hit.type==='thrust'&&p.dodgeTicks>0&&p.y<.3&&this.dodgeToward()>.55){
+ this.stats.mikiri++;this.fx('mikiri',b,25);this.emit('mikiri');this.bossPosture(C.mikiriPosture*C.postureUnit);this.interruptBoss(C.mikiriStun);p.dodgeTicks=0;p.inv=12;return;
+ }
+ if(this.blockOrDeflect(hit,src,'melee',move)){if(fromBoss)b.connected=true;return;}
+ if(hit.type!=='thrust'&&p.dodgeTicks>=C.dodgeFrames-C.dodgeInv)return;
+ if(fromBoss){b.connected=true;if(hit.type==='thrust')this.stats.perilousFailures++;this.K.onLanded?.(this,hit);}
+ this.hurtPlayer(hit.hp,hit.posture,hit.stagger??(hit.type==='slam'?24:16));if(hit.burn)this.burnUp(hit.burn);
+ }
+ // Burn (S38): fire fills the gauge, guarded or not; full, it drains vitality and stops posture recovery for a while.
+ burnUp(x){const p=this.player;if(p.burn===undefined||p.dead)return;p.burnFed=true;if(p.burning>0)return;
+ p.burn=Math.min(100,p.burn+x*this.tune.dmg);if(p.burn>=100){p.burn=0;p.burning=D.burnTicks;this.stats.burns++;this.emit('burning');}}
+ catchLightning(){const p=this.player;if(p.dead)return;
+ if(p.y>.2){p.hp=Math.max(0,p.hp-G.lightningChip);p.lightning=G.lightningCarry;p.lightningCaughtAt=this.t;this.stats.lightningCatches++;this.fx('lightning_catch',p,20);this.emit('lightning_caught');
+ if(p.hp<=0)this.hurtPlayer(1,0,0,true);
+ }else{this.stats.lightningFailures++;this.fx('shock',p,35);this.emit('grounded_lightning');this.hurtPlayer(G.lightningDamage,G.lightningPosture,G.lightningShock,true);}
+ }
+ reverseLightning(){const p=this.player,b=this.boss;if(!p.lightning||p.y<=.1||this.t===p.lightningCaughtAt)return false;
+ p.lightning=0;this.stats.lightningReversals++;this.emit('lightning_reversal');this.fx('lightning_return',b,30);
+ if(dist(p,b)<=G.reversalRange&&Math.abs(N.angle(A(b.x-p.x,b.z-p.z)-p.yaw))<1.6){this.damageBoss(Math.round(b.maxHp*G.lightningBossDamage),G.lightningBossPosture*C.postureUnit);this.interruptBoss(G.lightningStun);}
+ else this.emit('reversal_out_of_range');
+ this.hazards=this.hazards.filter(q=>q.type!=='lightning_arrow');return true;
+ }
+ // Area terror: the headless ape's blood scream fills the gauge with distance falloff; guarding does not stop it (S20).
+ terrorWave(s){const p=this.player,b=this.boss;if(p.dead||p.revive||b.executing)return;const d=dist(p,b);
+ if(this.probe&&d<=s.radius)this.probe.push({i:this.probeTick,kind:'aoe',type:'terror',reach:true});
+ if(d>s.radius)return;const fall=Math.sqrt(1-d/s.radius);p.terror=Math.min(100,p.terror+s.rate*fall*this.tune.dmg);p.terrorFed=true;
+ p.hp=Math.max(0,p.hp-s.drain*fall*this.tune.dmg);if(p.terror>=100){this.emit('terror_full');this.die(true);}else if(p.hp<=0)this.die();}
+ playerAttack(kind){const p=this.player;if(p.attackTick<0)return;
+ const wind=kind==='thrust'?C.thrustWind:C.slashWind;if(p.attackTick!==wind||p.attackHit)return;p.attackHit=true;
+ const b=this.boss,range=kind==='thrust'?3.05:2.55,facing=o=>Math.abs(N.angle(A(o.x-p.x,o.z-p.z)-p.yaw));
+ for(const q of this.minions)if(q.alive&&dist(p,q)<=range+q.r-.3&&facing(q)<=1.2){q.alive=false;q.fade=24;this.stats.illusionsKilled++;this.fx('illusion_cut',q);this.emit('illusion_cut');}
+ if(dist(p,b)>range+b.r-.5||facing(b)>1.2||Math.abs((b.y||0)-(p.y||0))>1.5||b.executing||b.deathblowAvailable||b.state==='dead')return;
+ const m=this.moves[b.action],busy=b.state==='attack';if(busy&&(m?.invulnerable||b.moveTick<(m?.invulnerableUntil||0)))return;
+ b.attackedAt=this.t;this.K.playerHit(this,kind,b.state==='stunned'||(busy&&openAt(m,b.moveTick,b.connected)),b.action);
+ }
+ arrow(heavy=false,lightning=false){const b=this.boss,p=this.player;
+ const sy=b.y+1.35,dy=p.y+.9-sy,dx=p.x-b.x,dz=p.z-b.z,len=Math.hypot(dx,dy,dz)||1,speed=lightning?.42:.4;
+ this.hazards.push({type:lightning?'lightning_arrow':'arrow',x:b.x,y:sy,z:b.z,vx:dx/len*speed,vy:dy/len*speed,vz:dz/len*speed,
+ sourceX:b.x,sourceZ:b.z,owner:'boss',age:0,life:120,radius:.2,charged:heavy,damage:heavy?24:12,posture:heavy?27:12});this.emit(lightning?'lightning_arrow':'arrow');
+ }
+ // Matchlock shot: fast, and guarding one costs heavy posture, so deflect it (S27).
+ bullet(){const b=this.boss,p=this.player,sy=b.y+1.3,dy=p.y+.9-sy,dx=p.x-b.x,dz=p.z-b.z,len=Math.hypot(dx,dy,dz)||1,speed=I.bulletSpeed;
+ this.hazards.push({type:'bullet',x:b.x,y:sy,z:b.z,vx:dx/len*speed,vy:dy/len*speed,vz:dz/len*speed,sourceX:b.x,sourceZ:b.z,age:0,life:60,radius:.14,damage:10,posture:24});this.emit('gunshot');}
+ // Force waves run along the ground: step aside from a vertical one, jump a flat one; guarding leaks vitality, deflecting does no posture damage (S27).
+ airWave(kind){const b=this.boss,p=this.player,a=A(p.x-b.x,p.z-b.z),speed=I.waveSpeed;
+ this.hazards.push({type:'wave',wide:kind==='h',x:b.x,y:.9,z:b.z,yaw:a,vx:Math.sin(a)*speed,vy:0,vz:Math.cos(a)*speed,sourceX:b.x,sourceZ:b.z,age:0,life:60,radius:kind==='h'?.95:.5,damage:kind==='h'?18:16,posture:kind==='h'?22:20});this.emit('force_wave');}
+ // The poo flies in a straight line at about 60 m/s and lasts three seconds (S16); a hit poisons at once (S14).
+ throwPoo(){const b=this.boss,p=this.player,sy=b.y+2.2,dx=p.x-b.x,dy=p.y+.9-sy,dz=p.z-b.z,len=Math.hypot(dx,dy,dz)||1,speed=1;
+ this.hazards.push({type:'poo',x:b.x,y:sy,z:b.z,vx:dx/len*speed,vy:dy/len*speed,vz:dz/len*speed,sourceX:b.x,sourceZ:b.z,age:0,life:180,radius:.42,damage:30,posture:20});this.emit('poo');}
+ kunai(n){const b=this.boss,p=this.player,sy=b.y+1.25;
+ for(let i=0;i=4&&a.pillars.every(q=>Math.hypot(x-q.x,z-q.z)>1)){this.minions.push({id:this.nextMinion++,x,y:0,z,yaw:A(p.x-x,p.z-z),r:.36,alive:true,state:'walk',t:0,fade:0,age:0});this.stats.illusionsSummoned++;return;}}}
+ summonIllusions(){const b=this.boss;b.spell=this.tune.spell||L.spell;b.dispelDue=false;while(this.minions.filter(q=>q.alive).length1.7&&!p.dead)this.toward(q,p.x,p.z,L.illusionSpeed,1.6);else if(!p.dead){q.state='attack';q.t=0;}}
+ else if(q.state==='attack'){if(++q.t<20)q.yaw=to;if(q.t===34)this.strike({type:'slash',reach:2.1,arc:1.1,hp:7,posture:11,stagger:8},'illusion',q);if(q.t>=40){q.state='recover';q.t=0;}}
+ else if(++q.t>=50){q.state='walk';q.t=0;}}
+ this.minions=this.minions.filter(q=>q.alive||q.fade>0);}
+ projectiles(){const p=this.player,a=this.arena;
+ for(const q of this.hazards){q.age++;q.life--;
+ if(q.type==='gas'){if(!p.dead&&p.y<1.6&&dist(q,p)0)q.cool--;const d=dist(q,p);
+ if(!p.dead&&!p.revive&&p.y<1&&q.cool<=0&&Math.abs(d-q.radius)a.radius+1:Math.abs(q.x)>a.halfWidth+1||Math.abs(q.z)>a.halfDepth+1;
+ if(out||q.y<-.2){q.life=0;continue;}
+ if(a.pillars.some(c=>Math.hypot(q.x-c.x,q.z-c.z)2&&!(q.type==='butterfly'&&q.age<(q.swarm?L.butterflyLaunch:L.dartLaunch))&&!p.dead&&!p.revive&&Math.hypot(p.x-old.x-u*dx,q.type==='wave'&&!q.wide?0:p.y+.9-old.y-u*dy,p.z-old.z-u*dz)0||p.dodgeTicks>=C.dodgeFrames-C.dodgeInv)continue;
+ q.life=0;
+ const src={x:q.sourceX,z:q.sourceZ};if(q.type==='butterfly'){src.x=old.x;src.z=old.z;this.stats.butterflyHits++;}
+ const blocks=this.stats.blocks;if(this.blockOrDeflect({type:q.type,hp:q.damage,posture:q.posture,push:q.charged?.55:0,burn:q.burn,leak:q.leak},src,q.swarm?'butterfly':'arrow')){if(q.type==='wave'&&this.stats.blocks>blocks){p.hp=Math.max(0,p.hp-q.damage*I.waveLeak*this.tune.dmg);if(p.hp<=0)this.die();}continue;}
+ this.hurtPlayer(q.damage,q.posture,18);if(q.burn&&!p.dead)this.burnUp(q.burn);
+ if(q.type==='poo'&&!p.dead){p.poisoned=C.poisonTicks;p.poison=0;this.stats.poisoned++;this.emit('poisoned');}
+ }
+ }
+ this.hazards=this.hazards.filter(q=>q.life>0);
+ }
+ // Lobbed fireballs burst where they land and leave a fire; homing ones steer with a limited turn and sink to the ground (S36, S39).
+ fireball(q){const p=this.player;
+ if(q.lob)q.vy-=D.lobGravity;else{if(q.age>12&&q.age<12+D.homingFor){const want=A(p.x-q.x,p.z-q.z),now=A(q.vx,q.vz),yaw=N.angle(now+N.clamp(N.angle(want-now),-D.homingTurn,D.homingTurn));q.vx=Math.sin(yaw)*D.homingSpeed;q.vz=Math.cos(yaw)*D.homingSpeed;q.vy=N.clamp((p.y+.9-q.y)*.08,-D.homingClimb,D.homingClimb);}else if(q.age<=12)q.vy*=.9;else q.vy-=D.homingFall;}
+ const old={x:q.x,y:q.y,z:q.z};q.x+=q.vx;q.y+=q.vy;q.z+=q.vz;
+ const hitP=()=>{if(this.probe)this.probe.push({i:this.probeTick,kind:'projectile',type:'fireball',reach:true});if(p.inv>0||p.dodgeTicks>=C.dodgeFrames-C.dodgeInv)return;
+ if(!this.blockOrDeflect({type:'fireball',hp:q.damage,posture:q.posture,burn:q.burn,leak:D.fireLeak,noDeflect:true},{x:q.sourceX,z:q.sourceZ},'arrow')){this.hurtPlayer(q.damage,q.posture,18);this.burnUp(q.burn);}};
+ if(q.y<=0){q.life=0;this.hazards.push({type:'fire',x:q.x,y:0,z:q.z,radius:1.1,age:0,life:q.lob?100:60,rate:D.fireRate});this.emit('fireball_burst');
+ if(!p.dead&&!p.revive&&p.y<.8&&Math.hypot(p.x-q.x,p.z-q.z)2&&!p.dead&&!p.revive){const dx=q.x-old.x,dy=q.y-old.y,dz=q.z-old.z,len=dx*dx+dy*dy+dz*dz,u=N.clamp(((p.x-old.x)*dx+(p.y+.9-old.y)*dy+(p.z-old.z)*dz)/(len||1),0,1);
+ if(Math.hypot(p.x-old.x-u*dx,p.y+.9-old.y-u*dy,p.z-old.z-u*dz)0||p.dodgeTicks>=C.dodgeFrames-C.dodgeInv){if(this.probe)this.probe.push({i:this.probeTick,kind:'projectile',type:'fireball',reach:true});return;}q.life=0;hitP();}}}
+ statuses(){const p=this.player;if(p.dead){p.poisonFed=p.terrorFed=false;if(p.burnFed!==undefined)p.burnFed=false;return;}
+ if(p.poison>=100){p.poison=0;p.poisoned=C.poisonTicks;this.stats.poisoned++;this.emit('poisoned');}
+ if(p.poisoned>0){p.poisoned--;p.hp=Math.max(0,p.hp-C.poisonDrain);if(p.hp<=0)this.die();}
+ if(!p.poisonFed)p.poison=Math.max(0,p.poison-C.poisonDecay);if(!p.terrorFed)p.terror=Math.max(0,p.terror-C.terrorDecay);p.poisonFed=p.terrorFed=false;
+ if(p.burning!==undefined){if(p.burning>0&&!p.dead){p.burning--;p.hp=Math.max(0,p.hp-D.burnDrain*this.tune.dmg);if(p.hp<=0)this.die();}if(!p.burnFed)p.burn=Math.max(0,p.burn-D.burnDecay);p.burnFed=false;}}
+ bossUpdate(){const b=this.boss,p=this.player,K=this.K;
+ b.actionTick++;if(b.flash>0)b.flash--;
+ if(b.executing){b.executing--;if(!b.executing)this.finishExecution();return;}
+ if(b.deathblowAvailable){b.y=Math.max(0,b.y-.15);if(b.deathblow>0&&--b.deathblow===0){b.deathblowAvailable=false;b.posture=b.maxPosture*C.deathblowMissFraction;b.state='idle';b.action='idle';b.cooldown=25;this.emit('deathblow_missed');}return;}
+ if(K.special&&K.special(this))return;
+ if(p.dead)return;
+ if(b.state==='stunned'){if(b.action!=='flinch_big')b.y=Math.max(0,b.y-.15);if(--b.stun<=0){b.state='idle';b.action='idle';b.cooldown=this.tune.restStun;}return;}
+ // Enemy posture has no recovery delay (S04) and keeps recovering during his own attacks; it pauses while he is
+ // staggered (returned above, by analogy with the S04 clause for Sekiro) and while a deathblow is open.
+ this.recoverPosture(b);
+ if(b.state==='idle'){K.idle(this);return;}
+ const move=b.action,m=this.moves[move],t=b.moveTick++;
+ if(m.perilousFrom&&t===m.perilousFrom)b.telegraph=b.perilous;
+ K.step(this,move,m,t);if(b.state!=='attack'||b.action!==move)return;
+ for(const hit of m.hits)if(t===hit.t)this.strike(hit,move,b);
+ if(b.state!=='attack'||b.action!==move)return;
+ K.afterHits(this,move,m,t);if(b.state!=='attack'||b.action!==move)return;
+ if(t>=m.duration-1){if(!m.air)b.y=0;const next=K.followUp(this,move);
+ if(next){this.startMove(next);return;}
+ b.state='idle';b.action='idle';b.perilous=null;b.telegraph=null;b.lightning=false;b.cooldown=this.tune.rest;
+ }
+ }
+ vertical(){const p=this.player;
+ if(p.y>0||p.vy>0){p.y+=p.vy;p.vy-=C.gravity;if(p.y<=0){p.y=0;p.vy=0;p.stomped=false;if(p.lightning){p.lightning=0;this.stats.lightningFailures++;this.emit('lightning_grounded');this.hurtPlayer(G.lightningDamage,G.lightningPosture,G.lightningShock,true);}}}
+ if(p.lightning>0)p.lightning--;
+ }
+ kick(){const p=this.player,b=this.boss,K=this.K;if(p.stomped||p.y<=.5||b.executing||b.state==='dead'||b.deathblowAvailable||dist(p,b)>=K.kickRange+b.r-.5)return false;
+ if(!K.kickAnyHeight&&p.y<=b.y+.5)return false;
+ p.stomped=true;p.vy=C.jumpSpeed*.8;this.stats.stomps++;const perilousSweep=b.state==='attack'&&b.perilous==='sweep';
+ this.bossPosture((this.kind==='butterfly'&&perilousSweep?L.kick:C.stompPosture)*C.postureUnit);this.fx('stomp',b,22);this.emit('head_stomp');K.onKick?.(this);return true;}
+ playerUpdate(keys,pressed,mouse){const p=this.player,b=this.boss;
+ if(pressed.has('E'))this.lockOn=!this.lockOn;
+ if(this.lockOn){this.face(p,b);this.cameraYaw=p.yaw;}else{this.cameraYaw=N.angle(this.cameraYaw-mouse[0]*.003);p.yaw=this.cameraYaw;}p.actionTick++;
+ // Physical holds continue through death/cinematics; returning to play must
+ // never synthesize a fresh deflect, charged attack or dodge press.
+ const guard=keys.has('K')||keys.has('RMB'),attack=keys.has('J')||keys.has('LMB'),dodge=keys.has('Shift');
+ const guardPress=guard&&!p.guardHeld,attackPress=attack&&!p.attackHeld,dodgePress=dodge&&!p.dodgeHeld;
+ p.guardHeld=guard;p.attackHeld=attack;p.dodgeHeld=dodge;p.running=false;
+ for(const name of ['inv','stagger','hurt','flash','revive'])if(p[name]>0)p[name]--;
+ if(p.stagger===0)p.postureBroken=false;
+ if(p.dead){p.guarding=false;p.guardAge=999;p.runTicks=0;if(pressed.has('R'))this.revive();if(p.dead&&--p.deathTimer<=0)this.outcome='loss';return;}
+ if(b.executing||p.revive||(b.state==='attack'&&(b.action==='tomoe_awaken'||this.moves[b.action]?.cinematic))){p.guarding=false;p.guardAge=999;this.vertical();return;}
+ if(this.t-p.lastGuardPress>C.spamReset)p.spam=0;
+ if(guardPress){p.spam=this.t-p.lastGuardPress>p.spam);p.guardAge=0;
+ }else p.guardAge++;
+ p.guarding=guard&&p.stagger===0&&p.healTick===0&&(p.attackTick<0||p.attackTick>13);
+ if(guardPress&&p.charge){p.charge=0;p.attackTick=-1;this.setPlayerAction('guard');}
+ if(p.lightning&&attackPress&&this.reverseLightning())return;
+ if(attackPress&&b.deathblowAvailable&&this.execute())return;
+ if(p.stagger>0){p.guarding=false;p.dodgeTicks=0;
+ // Safety roll: Step Dodge or Jump makes a posture-break stun much shorter (S04).
+ if(p.postureBroken&&(dodgePress||pressed.has('Space'))&&C.guardBreakStagger-p.stagger>=C.safetyRollAfter&&p.stagger>C.safetyRollRemain){p.stagger=C.safetyRollRemain;this.stats.safetyRolls++;this.setPlayerAction('safety_roll');this.emit('safety_roll');}
+ this.vertical();return;}
+ if(pressed.has('Q')&&p.gourds>0&&p.hpC.gourdFrames){p.healTick=0;this.setPlayerAction('idle');}this.recoverPosture(p);p.runTicks=0;return;}
+ if(pressed.has('Space')){
+ if(p.y===0){p.vy=C.jumpSpeed;p.stomped=false;this.setPlayerAction('jump');this.emit('jump');}
+ else this.kick();
+ }
+ this.vertical();
+ const f=(keys.has('W')?1:0)-(keys.has('S')?1:0),side=(keys.has('D')?1:0)-(keys.has('A')?1:0),a=this.cameraYaw;
+ let dx=Math.sin(a)*f-Math.cos(a)*side,dz=Math.cos(a)*f+Math.sin(a)*side,len=Math.hypot(dx,dz);if(len){dx/=len;dz/=len;}
+ if(dodgePress&&p.y===0&&!p.charge&&p.attackTick<0){if(!len){dx=Math.sin(p.yaw);dz=Math.cos(p.yaw);}p.dodgeX=dx;p.dodgeZ=dz;p.dodgeTicks=C.dodgeFrames;this.setPlayerAction('dodge');this.emit('step');}
+ const stepping=p.dodgeTicks>0;
+ if(stepping){this.move(p,p.dodgeX*C.dodge,p.dodgeZ*C.dodge);p.dodgeTicks--;}
+ else if(len){p.running=dodge&&!p.guarding;const speed=p.guarding?C.move*.55:p.running?C.run:C.move;this.move(p,dx*speed,dz*speed);if(p.attackTick<0&&!p.charge&&p.y===0)this.setPlayerAction(p.running?'run':'walk');}
+ p.runTicks=p.running?p.runTicks+1:0;
+ if(attackPress&&p.attackTick<0&&!p.guarding&&p.dodgeTicks===0){p.charge=1;this.setPlayerAction('charge');}
+ if(p.charge){if(!attack||p.charge>=C.thrustCharge){p.attackKind=attack?'thrust':'slash';p.attackTick=0;p.attackHit=false;p.charge=0;this.stats.playerAttacks++;this.setPlayerAction(p.attackKind);}else p.charge++;}
+ if(p.attackTick>=0){this.playerAttack(p.attackKind);p.attackTick++;if(p.attackTick>(p.attackKind==='thrust'?C.thrustEnd:C.slashEnd)){p.attackTick=-1;this.setPlayerAction('idle');}}
+ // No posture recovery while attacking, sprinting, dodging, airborne or staggered; guarding speeds it up (S04).
+ if(p.attackTick<0&&!p.charge&&!stepping&&p.y===0&&!p.running){if(!len)this.setPlayerAction(p.guarding?'guard':'idle');this.recoverPosture(p,p.guarding?C.guardRecovery:1);}
+ }
+ separate(o,q,heightO,heightQ){const d=dist(o,q),min=o.r+q.r;if(!(o.y=min)return;
+ const nx=d>1e-8?(o.x-q.x)/d:Math.sin(o.yaw),nz=d>1e-8?(o.z-q.z)/d:Math.cos(o.yaw),push=(min-d)*.5;
+ this.move(o,nx*push,nz*push);this.move(q,-nx*push,-nz*push);
+ const residual=min-dist(o,q);if(residual>1e-6){this.move(o,nx*residual,nz*residual);const remain=min-dist(o,q);if(remain>1e-6)this.move(q,-nx*remain,-nz*remain);}}
+ update(keys,pressed,mouse){if(this.outcome)return;
+ for(const body of [this.player,this.boss])if(body.postureDelay>0)body.postureDelay--;
+ this.playerUpdate(keys,pressed,mouse);if(!this.outcome)this.bossUpdate();if(this.outcome)return;
+ this.minionUpdate();if(!this.player.dead)this.projectiles();this.statuses();
+ const p=this.player,b=this.boss;
+ // A horse at the gallop rides through: without this it pushes Sekiro along in front of it and can never pass him.
+ if(!b.executing&&b.state!=='dead'&&!(b.state==='attack'&&this.moves[b.action]?.ride))this.separate(p,b,1.75,b.height);
+ for(const q of this.minions)if(q.alive)this.separate(p,q,1.75,1.7);
+ if(this.lockOn){this.face(p,b);this.cameraYaw=p.yaw;}
+ this.effects=this.effects.filter(fx=>--fx.life>0);this.lastKeys=[...keys].sort();
+ }
+ health(){const b=this.boss,later=this.tune.bars.slice(b.phase).reduce((s,x)=>s+x.hp,0);
+ return [this.player.hp,C.playerHP,this.outcome==='win'?0:(b.state==='dead'?0:b.hp)+later,this.totalBossHP];}
+ }
+ M.Game=Game;M.openAt=openAt;M.regenFactor=regenFactor;M.tier=tier;
+
+ /* Standard scripted reference controller (bossbench scripted hook). Called once per 200 ms packet with the live
+ * game; it reads privileged state on a deep copy, predicts the next contacts by simulating that copy with no input,
+ * and returns only legal holds (<= 4 keys each). Deterministic; never touches the live game or its RNG. */
+ function cloneGame(g){return Object.assign(Object.create(Game.prototype),N.copy(g));}
+ function simTick(h,keys,mouse){const prev=new Set(h.lastKeys);h.events=[];h.update(new Set(keys),new Set(keys.filter(k=>!prev.has(k))),mouse);N.quantize(h);h.t++;}
+ function contacts(h,horizon){const s=cloneGame(h);s.probe=[];
+ let first=-1;for(let i=0;ic.reach))first=i;if(first>=0&&i>=first+8)break;}
+ return s.probe.filter(c=>c.reach);
+ }
+ function room(h,x,z){const a=h.arena;/* free distance to the arena edge or a pillar */let r=a.shape==='circle'?a.radius-Math.hypot(x,z):Math.min(a.halfWidth-Math.abs(x),a.halfDepth-Math.abs(z));
+ for(const q of a.pillars)r=Math.min(r,Math.hypot(x-q.x,z-q.z)-q.r);return r;}
+ function sideKey(h,reach=3.2){const p=h.player,a=h.cameraYaw,rx=-Math.cos(a),rz=Math.sin(a);
+ // Step toward the side with more room.
+ return room(h,p.x+rx*reach,p.z+rz*reach)>=room(h,p.x-rx*reach,p.z-rz*reach)?'D':'A';}
+ // Best of eight run directions away from a point, keeping room to keep running (walls, pillars).
+ function escape(h,x,z){const p=h.player,a=h.cameraYaw,f=[Math.sin(a),Math.cos(a)],r=[-Math.cos(a),Math.sin(a)];let best=null,score=-1e9;
+ for(const [keys,u,v] of [[['S'],-1,0],[['S','A'],-1,-1],[['S','D'],-1,1],[['A'],0,-1],[['D'],0,1],[['W','A'],1,-1],[['W','D'],1,1],[['W'],1,0]]){
+ const len=Math.hypot(u,v),dx=(f[0]*u+r[0]*v)/len,dz=(f[1]*u+r[1]*v)/len;let px=p.x,pz=p.z,stuck=0;
+ for(let k=1;k<=6;k++){const nx=px+dx*.6,nz=pz+dz*.6;if(room(h,nx,nz)score){score=sc;best=keys;}}
+ return [...best,'Shift'];}
+ // Drinking takes 66 ticks: simulate the whole animation on a copy and heal only if nothing lands meanwhile.
+ function safeHeal(h){const s=cloneGame(h),hits=s.stats.playerHits;simTick(s,['Q'],[0,0,0]);
+ for(let i=0;ih.stats.healsApplied;}
+ function swarmCenter(list,p){if(!list.length)return [p.x,p.z];let x=0,z=0;for(const q of list){x+=q.x;z+=q.z;}return [x/list.length,z/list.length];}
+ function plan(h){
+ const p=h.player,b=h.boss,prev=new Set(h.lastKeys),d=dist(p,b),tap=k=>prev.has(k)?[]:[k],kind=h.kind,head=b.form_id==='headless';
+ if(h.outcome)return [];
+ if(p.dead)return p.nodes>0&&!p.resurrectionLocked&&!p.terrorDeath?tap('R'):[];
+ if(b.executing||p.revive||(b.state==='attack'&&(b.action==='tomoe_awaken'||h.moves[b.action]?.cinematic)))return [];
+ if(p.stagger>0)return p.postureBroken&&C.guardBreakStagger-p.stagger>=C.safetyRollAfter?tap('Shift'):[];
+ if(p.lightning>0&&p.y>.1)return tap('J');
+ if(p.healTick>0)return [];
+ if(b.deathblowAvailable)return d>C.deathblowReach+b.r-.15?['W']:tap('J');
+ const grounded=p.y===0&&p.vy===0,free=grounded&&!p.charge&&p.attackTick<0&&p.dodgeTicks===0;
+ if(!grounded&&!p.stomped&&p.y>.55&&db.y+.5)&&b.perilous==='sweep'&&b.state==='attack')return tap('Space');
+ const swarm=h.hazards.filter(q=>q.type==='butterfly'&&q.swarm&&dist(q,p)<7.5&&q.agec.kind==='melee'&&!['sweep','grab','lightning','mortal'].includes(c.type));
+ let threat=all[0];
+ // A projectile followed closely by a guardable blow: guard (deflect) the blow instead of stepping into it.
+ if(threat&&(threat.type==='butterfly'||threat.type==='poo')&&melee&&melee.i<=threat.i+6)threat=melee;
+ const eta=threat?threat.i:99;
+ if(threat&&threat.src==='minion'&&!threat.facing){const q=h.minions.filter(m=>m.alive&&m.state==='attack').sort((a,c)=>dist(a,p)-dist(c,p))[0];
+ if(free&&eta<=3&&!prev.has('Shift'))return escape(h,q?q.x:p.x,q?q.z:p.z);if(eta<=3)return [];}
+ if(threat){
+ const type=threat.type;
+ if(type==='terror')return escape(h,b.x,b.z);
+ if(type==='gas'){const q=h.hazards.find(z=>z.type==='gas');return escape(h,q?q.x:b.x,q?q.z:b.z);}
+ if(type==='fire'&&!all.some(c=>c.kind!=='aoe'&&c.i<=6))return escape(h,threat.x,threat.z);
+ if(type==='fire_ring'&&eta<=6)return escape(h,b.x,b.z);
+ if(type==='blast'){if(grounded&&eta>=4&&eta<=14)return tap('Space');if(eta<=14)return [];}
+ // Fire arms and fireballs cannot be deflected: be guarding well before they land.
+ // A fire arm cannot be deflected and guarding it builds Burn: walk in under the belly, where it misses (S36, S37), else hold the guard early.
+ if(threat.noDeflect&&threat.kind==='melee'&&grounded&&free&&d>D.belly-.1&&(d-D.belly+.1)/C.move=4&&d>D.belly&&p.attackTick<0&&!p.charge)return ['W','Shift'];
+ if(type==='fireball'&&free&&eta<=2&&!prev.has('Shift'))return [sideKey(h,1.6),'Shift'];
+ if(type==='fireball'&&eta<=2&&prev.has('Shift'))return [];
+ if(threat.noDeflect||type==='fireball'){if(eta<=29)return ['RMB'];}
+ if(type==='lightning'||type==='lightning_arrow'){
+ if(grounded&&eta<=1+(type==='lightning'?3:0))return tap('Space');
+ if(grounded&&eta>8&&d>7)return ['W'];
+ if(eta<=8)return [];
+ }else if(type==='mortal'){
+ if(free&&eta<=5&&!prev.has('Shift'))return [sideKey(h),'Shift'];
+ if(eta<=5)return [];
+ }else if(type==='sweep'){
+ if(grounded&&eta>=3&&eta<=8)return tap('Space');
+ if(eta<=8)return [];
+ }else if(type==='grab'){
+ if(threat.noJump){// distance only: retreat straight back as it commits (the aerial grab tracks a side step, S19)
+ const away=escape(h,b.x,b.z);if(free&&eta<=16&&!prev.has('Shift'))return away;
+ return eta<=18?(prev.has('Shift')?away.filter(k=>k!=='Shift'):away):[];}
+ if(threat.dodge&&free&&eta<=3&&!prev.has('Shift'))return [sideKey(h),'Shift'];
+ if(grounded&&eta>=3&&eta<=8&&!prev.has('Space'))return ['Space'];
+ if(eta<=8)return prev.has('Shift')||prev.has('Space')?[]:threat.dodge?[sideKey(h)]:[];
+ }else if(type==='thrust'){
+ if(free&&eta>=1&&eta<=6&&!prev.has('Shift'))return ['W','Shift'];
+ if(eta<=1)return ['RMB'];
+ if(eta<=6)return prev.has('Shift')?[]:['W'];
+ }else if(type==='poo'||type==='butterfly'){
+ if(type==='butterfly'&&!swarm.length){if(eta<=1)return ['RMB'];if(eta<=4)return [];}
+ else{if(free&&eta<=2&&!prev.has('Shift'))return type==='butterfly'?escape(h,...swarmCenter(swarm,p)):[sideKey(h,1.6),'Shift'];
+ if(eta<=2)return [];}
+ }else{
+ if(eta<=1)return ['RMB'];
+ if(eta<=4&&!swarm.length)return [];
+ }
+ }
+ // Spirit butterflies outrun a walk but not a sprint: kite them (pillars break them), and back away from the
+ // flurry instead of guarding it, coming back after its perilous finisher (S17, S19).
+ if(swarm.length&&grounded)return escape(h,...swarmCenter(swarm,p));
+ if(b.state==='attack'&&b.action==='flurry'&&b.moveTick>=6&&b.moveTick<100&&grounded)return d<5.5?escape(h,b.x,b.z):[];
+ if(b.state==='attack'&&b.action==='flurry'&&b.moveTick>=100&&b.moveTick<124&&grounded)return d>3.4?['W']:[];
+ const ms=b.state==='attack'&&h.moves[b.action]?.scream;if(ms&&b.moveTick['arrow','lightning_arrow','kunai','poo','butterfly','bullet','wave'].includes(q.type));
+ const calm=eta>=30&&!arrowsInFlight&&(b.state==='idle'||b.state==='stunned'||b.state==='dead')&&h.minions.every(q=>!q.alive||dist(q,p)>3);
+ if(p.hp<=50&&p.gourds>0&&free&&!prev.has('Q')&&calm&&(kind!=='genichiro'||b.state!=='idle'||d>=2)&&safeHeal(h))return ['Q'];
+ if(b.state==='dead'){if(p.hp<=75&&p.gourds>0&&free&&!prev.has('Q')&&safeHeal(h))return ['Q'];return d<6?['S']:[];}
+ // Lightning: wait for the airborne catch and reversal (heavier payoff) instead of cutting him out of the leap.
+ const lightningMove=b.state==='attack'&&b.lightning&&b.moveTick<100;
+ const m=h.moves[b.action],open=!lightningMove&&(b.state==='stunned'||b.state==='idle'||(b.state==='attack'&&openAt(m,b.moveTick+9,b.connected)));
+ if(lightningMove&&grounded&&d>6.5)return ['W'];
+ // Illusions: cut one that has closed in when nothing else is coming.
+ const near=h.minions.find(q=>q.alive&&dist(q,p)<2.3&&Math.abs(N.angle(A(q.x-p.x,q.z-p.z)-p.yaw))<1.1);
+ if(near&&free&&eta>=14)return tap('J');
+ const reach=2.45+b.r-.5,safe=eta>=19&&!(b.state==='attack'&&m?.invulnerable);
+ if(free&&safe&&open&&d<=reach&&b.y<1.2)return tap('J');
+ // The headless ape outranges Sekiro: keep a middle distance unless it is open (S14).
+ // Its delayed overhead chop is the opening: step in and deflect it to stun it with the neck exposed (S14, S15).
+ if(head&&b.state==='attack'&&(b.action==='overhead_slam'||b.action==='jump_sweep'&&b.moveTick>40)&&!open){return d>3.5&&b.moveTick<44?['W']:[];}
+ if(head&&!open&&b.state!=='stunned'){if(b.state==='attack'&&d<4.8)return [];if(d<4.6)return ['S'];if(d>7.5)return ['W'];return [];}
+ if(kind==='ape'&&b.state==='attack'&&!open&&d<3.6)return [];
+ if(kind==='gyoubu'&&d>5&&p.attackTick<0&&!p.charge&&grounded)return ['W','Shift'];
+ if(d>reach-.15&&p.attackTick<0&&!p.charge)return ['W'];
+ return [];
+ }
+ // The fight opens unlocked (free camera, sekiro@11): the script locks on in its first sub-step and never toggles again,
+ // so from then on it plays exactly as it did when the fight opened locked (camera already faces the boss at tick 0).
+ M.scripted=function(game){
+ const h=cloneGame(game),p=h.player,b=h.boss,holds=[],lock=!h.lockOn;
+ const mouse=[h.lockOn?0:N.clamp(Math.round(-N.angle(A(b.x-p.x,b.z-p.z)-h.cameraYaw)/.003),-1000,1000),0,0];
+ for(let j=0;j<6;j++){
+ const keys=j===0&&lock?['E',...plan(h)].slice(0,4):plan(h).slice(0,4);holds.push(keys);
+ for(let n=0;n<2&&!h.outcome;n++)simTick(h,keys,mouse.map(v=>v/12));
+ }
+ return {holds,mouse};
+ };
+ M.oracle=M.scripted; // legacy tool name
+ M.debug={plan:g=>plan(cloneGame(g)),contacts:(g,n=30)=>contacts(cloneGame(g),n)};
+})(typeof window==='undefined'?globalThis:window);
diff --git a/environments/games/web/games/sekiro_remake/index.html b/environments/games/web/games/sekiro_remake/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..85ae9c8faee4988b98952044c86279378d3361f5
--- /dev/null
+++ b/environments/games/web/games/sekiro_remake/index.html
@@ -0,0 +1,7 @@
+Sekiro · Six Bosses
+
Sekiro · Shadows Die Twice
Sekiro · Six Bosses
Face six foes: a bow-and-blade swordsman, a deceptive guardian ape, an illusion-wielding shinobi, a sword-and-spear master, a mounted general, and a flame behemoth. Read their attacks and break their posture.
The gunner has 6 health, 5 armor, and 180 energy. Armor regenerates by 1 per second after 3 seconds without damage. Bosses enrage at half health. The blade can cut ordinary bullets, turrets, star turrets, and vortex shots, but not shockwaves, meteors, laser orbs, explosive shots, or beams. Hold the left mouse button and drag to aim manually, or double-click the screen to lock the pointer for free aim (Esc unlocks it). When the mouse is idle, auto-aim targets a visible boss. Replays save inputs and the seed for deterministic verification. The scripted demo reads internal state and emits only valid keyboard and mouse actions; it does not start RL training.
+
+
+
diff --git a/environments/games/web/games/soulknight_remake/manifest.json b/environments/games/web/games/soulknight_remake/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..964f24342d5a48df2b8b698fb09c56cbb6a09e29
--- /dev/null
+++ b/environments/games/web/games/soulknight_remake/manifest.json
@@ -0,0 +1,31 @@
+{
+ "schema": "bossbench/game-manifest@1",
+ "engine": "independent",
+ "game": "soulknight_remake",
+ "module": "SoulKnightGame",
+ "title": "Soul Knight: Dungeon Bosses",
+ "dimension": "2d",
+ "native_hz": 60,
+ "max_seconds": 300,
+ "renderer": "canvas-native",
+ "rules": "knight-arena@6",
+ "cases": [
+ "soulknight/goblin_priest",
+ "soulknight/christmas_treant",
+ "soulknight/devils_snare",
+ "soulknight/grand_slime",
+ "soulknight/varkolyn_leader",
+ "soulknight/volcanic_sandworm"
+ ],
+ "scripts": [
+ "_native/runtime.js",
+ "soulknight_remake/game.js",
+ "soulknight_remake/draw.js"
+ ],
+ "sim_scripts": [
+ "_native/runtime.js",
+ "soulknight_remake/game.js"
+ ],
+ "play_page": "web/games/soulknight_remake/index.html",
+ "scripted_controller": "SoulKnightGame.scripted(game) -> {holds:[6 key arrays], mouse:[dx,dy,dz]} (falls back to .oracle)"
+}
diff --git a/environments/games/web/games/terraria_remake/arena.js b/environments/games/web/games/terraria_remake/arena.js
new file mode 100644
index 0000000000000000000000000000000000000000..c56f491f5f3d7f75018ed0191004eed57e3607ac
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/arena.js
@@ -0,0 +1,9 @@
+// Arena geometry, in game units (u). Origin = left wall surface / floor surface, y up.
+// Scale: 1 u = 2 tiles = 32 px of the source game (a tile is 16 px); its 60 Hz tick is kept, so
+// speed px/tick x 1.875 = u/s acceleration px/tick^2 x 112.5 = u/s^2
+// 27 x 15 u = a 54 x 30 tile arena (engine/renderer.js: 30 px per u on screen, keep W <= 28).
+// Platforms (one-way, like wooden platforms) are per case: BB.CASES[id].platforms = [[x0, x1, y], ...].
+(function (g) {
+ var BB = g.BB;
+ BB.ARENA = { W: 27, H: 15 };
+})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/environments/games/web/games/terraria_remake/art/scenes.js b/environments/games/web/games/terraria_remake/art/scenes.js
new file mode 100644
index 0000000000000000000000000000000000000000..6c42e6d8c0fa3dcac326bcb6455d37d074fe3950
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/art/scenes.js
@@ -0,0 +1,119 @@
+(function(g){
+ var BB=g.BB,ART=BB.ART;
+ // Original procedural backdrops, cached once per case (bg + fg) plus a cached day/night alternate.
+ // Seeded by a fixed hash (ART.hash), never by the game RNG.
+ var H=ART.hash;
+ function sky(x,top,bottom){var gr=x.createLinearGradient(0,0,0,466);gr.addColorStop(0,top);gr.addColorStop(1,bottom);x.fillStyle=gr;x.fillRect(0,0,854,480);}
+ function hills(x,base,amp,col,seed,step){x.fillStyle=col;x.beginPath();x.moveTo(0,480);for(var px=0;px<=854;px+=step){x.lineTo(px,base-amp*(.5+.5*Math.sin(px*.011+seed))-amp*.35*H(seed+px));}x.lineTo(854,480);x.closePath();x.fill();}
+ function tree(x,px,base,h,trunk,leaf,leaf2){
+ x.fillStyle=trunk;x.fillRect(px-4,base-h,8,h);x.fillRect(px-9,base-6,18,6);
+ x.fillStyle=leaf;x.beginPath();x.arc(px,base-h,h*.32,0,Math.PI*2);x.arc(px-h*.22,base-h*.82,h*.24,0,Math.PI*2);x.arc(px+h*.22,base-h*.82,h*.24,0,Math.PI*2);x.fill();
+ x.fillStyle=leaf2;x.beginPath();x.arc(px-h*.08,base-h*1.06,h*.17,0,Math.PI*2);x.fill();
+ }
+ function stars(x,n,seed){for(var i=0;i.5?'rgba(0,0,0,.12)':'rgba(255,255,255,.05)';x.fillRect(px,y+5,15,10);}
+ x.fillStyle=top;x.fillRect(0,y-2,854,6);
+ if(kind!=='dungeon'&&kind!=='hive')for(px=0;px<854;px+=6){var gh=2+Math.floor(H(px*3.1)*5);x.fillRect(px,y-2-gh,2,gh);}
+ }
+ // Honeycomb wall for the underground hive (original procedural pattern).
+ function honeycomb(x,top){
+ var r=19,hx=r*1.5,hy=r*Math.sqrt(3);
+ for(var col=0,cx=-r;cx<880;col++,cx+=hx)for(var cy=top+(col%2)*hy/2;cy<480;cy+=hy){
+ var s=H(col*13.7+cy);x.beginPath();
+ for(var k=0;k<6;k++){var a=k*Math.PI/3;x.lineTo(cx+Math.cos(a)*(r-1.5),cy+Math.sin(a)*(r-1.5));}
+ x.closePath();x.fillStyle=s>.86?'#6a4818':s>.5?'#3e2a10':'#35230c';x.fill();
+ x.strokeStyle='rgba(18,10,2,.7)';x.lineWidth=2;x.stroke();
+ if(s>.86){x.fillStyle='rgba(255,200,90,.12)';x.beginPath();x.arc(cx-4,cy-4,5,0,Math.PI*2);x.fill();}
+ }
+ }
+ ART.scene=function(doc,id){
+ var bg=doc.createElement('canvas'),fg=doc.createElement('canvas');bg.width=fg.width=854;bg.height=fg.height=480;
+ var x=bg.getContext('2d'),V=BB.VIEW,kind=BB.CASES[id].arena;
+ var night=kind==='night',cave=kind==='dungeon'||kind==='hive',evil=kind==='corruption',crimson=kind==='crimson';
+ function paint(x,isNight){
+ if(kind==='hive'){
+ // underground hive: warm gradient, honeycomb wall, dripping honey and jungle vines (no day/night)
+ sky(x,'#140c04','#24170a');honeycomb(x,70);
+ x.fillStyle='rgba(10,6,2,.35)';x.fillRect(0,0,854,480);
+ for(var d=0;d<14;d++){var hx=30+d*62+H(d)*30,len=30+H(d+3)*90;x.fillStyle='rgba(190,120,30,.6)';x.fillRect(hx-2,60,4,len);x.beginPath();x.arc(hx,60+len,4,0,Math.PI*2);x.fill();}
+ for(d=0;d<9;d++){var vx=H(d+20)*854;x.strokeStyle='#2c4a1e';x.lineWidth=3;x.beginPath();x.moveTo(vx,40);x.quadraticCurveTo(vx+18,140,vx-6,180+H(d)*120);x.stroke();
+ x.fillStyle='#365f24';for(var l=0;l<5;l++){x.beginPath();x.ellipse(vx+6-l*2,70+l*28,6,3,.6,0,Math.PI*2);x.fill();}}
+ [[150,250],[700,250]].forEach(function(p){ART.glow(x,p[0],p[1],70,'255,170,60',.12);});
+ return;
+ }
+ if(crimson){
+ // crimson: blood-red sky, flesh hills, vertebra spires and veiny ground growths
+ sky(x,isNight?'#200a10':'#5a1f26',isNight?'#4a1820':'#8a3a3a');
+ if(isNight){stars(x,40,5);moon(x,690,84,20);}else sun(x,700,90,20);
+ hills(x,320,60,isNight?'#3a121a':'#6a2a30',2.7,6);
+ for(var i=0;i<8;i++){var sx=50+i*110+H(i+11)*40,sh=100+H(i+2)*120;
+ for(var v=0;v.7?'#33415a':s>.35?'#2d3a50':'#283447';x.fillRect(a,y,50,20);
+ x.fillStyle='rgba(255,255,255,.04)';x.fillRect(a,y,50,2);}
+ [110,330,524,744].forEach(function(px){x.fillStyle='#1a2230';x.fillRect(px-20,96,40,370);x.fillStyle='#3d4c63';x.fillRect(px-26,90,52,10);x.fillRect(px-26,450,52,16);});
+ [220,634].forEach(function(px){x.fillStyle='#0b0f17';x.beginPath();x.moveTo(px-26,250);x.lineTo(px-26,170);x.arc(px,170,26,Math.PI,0);x.lineTo(px+26,250);x.closePath();x.fill();
+ ART.glow(x,px,190,40,'90,140,255',.18);});
+ for(var k=0;k<6;k++){var cx=70+k*150+H(k)*30;x.strokeStyle='#4b525c';x.lineWidth=2;x.setLineDash([3,2]);x.beginPath();x.moveTo(cx,96);x.lineTo(cx,96+40+H(k+9)*60);x.stroke();x.setLineDash([]);}
+ [[180,300],[680,300]].forEach(function(p){ART.glow(x,p[0],p[1],46,'255,170,80',.35);x.fillStyle='#ffcc6a';x.fillRect(p[0]-3,p[1]-6,6,9);x.fillStyle='#5a4632';x.fillRect(p[0]-5,p[1]+3,10,4);});
+ return;
+ }
+ if(evil){
+ sky(x,isNight?'#1d1426':'#4a3a5c',isNight?'#3a2a44':'#7a6585');
+ if(isNight){stars(x,50,3);moon(x,120,78,18);}else sun(x,700,90,20);
+ hills(x,320,60,isNight?'#2c2036':'#4f3f5e',1.3,6);
+ // ebonstone spires and thorny dead trees
+ for(var i=0;i<9;i++){var px=40+i*100+H(i)*40,hgt=90+H(i+3)*120;x.fillStyle=isNight?'#231a2c':'#3d2f4a';x.beginPath();x.moveTo(px-26,466);x.lineTo(px-8,466-hgt);x.lineTo(px+4,466-hgt*.82);x.lineTo(px+26,466);x.closePath();x.fill();}
+ hills(x,380,40,isNight?'#2a1f33':'#46385a',4.1,5);
+ for(i=0;i<7;i++){var tx=60+i*125+H(i*2)*30,th=60+H(i+8)*40;x.strokeStyle=isNight?'#1a1220':'#2c2235';x.lineWidth=5;x.beginPath();x.moveTo(tx,466);x.lineTo(tx,466-th);x.stroke();
+ x.lineWidth=2;x.beginPath();x.moveTo(tx,466-th*.6);x.lineTo(tx-16,466-th*.85);x.moveTo(tx,466-th*.75);x.lineTo(tx+14,466-th);x.stroke();}
+ for(i=0;i<16;i++){x.fillStyle='rgba(180,140,220,.35)';x.fillRect(H(i+40)*854,140+H(i+60)*300,2,2);}
+ return;
+ }
+ if(isNight){sky(x,'#0e1830','#2c4468');stars(x,90,1);moon(x,700,90,22);}
+ else{sky(x,'#6fb6e6','#cfe8f2');sun(x,700,92,24);
+ for(var cl=0;cl<5;cl++){var ccx=60+cl*190+H(cl)*40,ccy=60+H(cl+4)*60;x.fillStyle='rgba(255,255,255,.75)';x.beginPath();x.ellipse(ccx,ccy,46,14,0,0,Math.PI*2);x.ellipse(ccx+24,ccy-8,30,12,0,0,Math.PI*2);x.fill();}}
+ hills(x,300,70,isNight?'#1d3042':'#8fb9b0',.4,6);
+ hills(x,350,50,isNight?'#1b3a35':'#5f9670',2.2,5);
+ for(var j=0;j<12;j++)tree(x,20+j*76+H(j)*30,466,90+H(j+5)*60,isNight?'#2a2620':'#5c3d27',isNight?'#1e4436':'#3f8a4a',isNight?'#2a5a46':'#5aa85c');
+ }
+ paint(x,night);
+ ground(x,kind,V);
+ var f=fg.getContext('2d');
+ (BB.CASES[id].platforms||[]).forEach(function(p){var x0=Math.round(V.sx(p[0])),w=Math.round((p[1]-p[0])*V.S),y=Math.round(V.sy(p[2]));
+ f.fillStyle='#4c3423';f.fillRect(x0,y,w,7);f.fillStyle='#c9925a';f.fillRect(x0,y,w,3);
+ for(var n=0;n0?4:0);return this.status.broken_armor>0?Math.floor(d/2):d;};
+ // r7 (2026-11-07): no natural health regeneration. The source regenerates over time (RT/eRT formula), which in a
+ // single-boss arena let a controller stand and trade hits. Life comes back only from dropped hearts.
+ // Poisoned: 2 life per second for players (Debuffs Wiki), applied as one point every 30 ticks.
+ P.updateLifeDrain=function(c){
+ if(this.status.poisoned>0&&this.hp>0){this.poisonCounter++;if(this.poisonCounter>=30){this.poisonCounter=0;this.hp=Math.max(0,this.hp-1);c.emit('poison_tick',this.x,this.y+K.H);}}
+ else this.poisonCounter=0;
+ };
+ P.update=function(c,i){
+ var dt=BB.DT,pv=this.prev,oldY=this.y;
+ function decay(v){return v<=dt+1e-9?0:v-dt;}
+ this.invul=decay(this.invul);this.atkCd=decay(this.atkCd);this.atkT=decay(this.atkT);this.dropT=decay(this.dropT);
+ for(var name in this.status)this.status[name]=decay(this.status[name]);
+ // Confused swaps the movement controls (left with right, jump/up with drop/down); attacks are unchanged.
+ if(this.status.confused>0)i=Object.assign({},i,{left:i.right,right:i.left,jump:i.drop,drop:i.jump});
+ if(this.status.cursed>0)i=Object.assign({},i,{attack:false,bow:false,sword:false});
+ if(this.atkT>0){
+ this.slashPreviousAngle=this.slashAngle;
+ var arc=2.2-3.3*(1-this.atkT/K.SWORD_CD);this.slashAngle=this.slashFacing>0?arc:Math.PI-arc;
+ }
+ this.knock*=0.89;
+ var dir=(i.right?1:0)-(i.left?1:0),slow=(this.status.slow>0?0.5:1)*(this.status.weak>0?0.9:1);
+ // Weak also lowers melee damage and melee speed by 5.1 %; the instance NAIL is what the engine deals per slash.
+ this.NAIL=this.status.weak>0?K.SWORD*0.949:K.SWORD;
+ this.vx=TR.playerHorizontal(this.vx,dir,K.BASE_RUN*slow,K.RUN*slow,K.ACC,K.DEC,true);
+ if(dir&&this.atkT<=0)this.facing=dir;
+ if(i.switchWeapon&&!pv.switchWeapon)this.weapon=this.weapon==='bow'?'sword':'bow';
+ if(i.drop&&this.y>0&&this.grounded){this.dropT=0.18;this.grounded=false;this.y=Math.max(0,this.y-0.06);this.jumpTicks=0;}
+ if(i.jump&&!pv.jump&&this.grounded&&!i.drop){this.jumpTicks=K.JUMP_TICKS;this.grounded=false;c.emit('jump',this.x,this.y);}
+ if(!i.jump)this.jumpTicks=0;
+ this.flying=false;this.gliding=false;
+ if(this.jumpTicks>0){this.vy=K.JUMP-K.GRAV*dt;this.jumpTicks--;}
+ else{
+ this.vy=Math.max(-K.FALL,this.vy-K.GRAV*dt);
+ if(i.jump&&!this.grounded&&this.flight>0){
+ this.flying=true;this.vy=Math.min(K.FLY,this.vy+60*dt);this.flight=decay(this.flight);
+ }else if(i.jump&&!this.grounded&&this.vy<0){this.gliding=true;this.vy=Math.max(this.vy,-K.FALL/3);}
+ }
+ this.x=BB.clamp(this.x+this.vx*dt,K.W/2,BB.ARENA.W-K.W/2);
+ this.y=Math.min(BB.ARENA.H-K.H,this.y+this.vy*dt);this.grounded=false;
+ if(this.y<=0){this.y=0;this.vy=0;this.grounded=true;}
+ if(this.vy<=0&&this.dropT<=0){
+ var landing=-Infinity;
+ TR.platforms(c).forEach(function(p){
+ if(this.x+K.W/2>p[0]&&this.x-K.W/2
=p[2]-0.001&&this.y<=p[2])landing=Math.max(landing,p[2]);
+ },this);
+ if(landing>-Infinity){this.y=landing;this.vy=0;this.grounded=true;}
+ }
+ if(this.grounded){this.flight=K.WINGS;this.jumpTicks=0;this.flying=false;this.gliding=false;}
+ if(this.y>=BB.ARENA.H-K.H&&this.vy>0){this.vy=0;this.jumpTicks=0;}
+ if((i.attack||i.bow||i.sword)&&this.atkCd<=0){
+ var weapon=i.bow?'bow':i.sword?'sword':this.weapon;
+ var b=this.centre(),a=Math.atan2(this.aimY-b.y,this.aimX-b.x);
+ this.facing=Math.cos(a)>=0?1:-1;
+ if(weapon==='bow'){
+ this.atkCd=K.BOW_CD;
+ this.arrows.push({id:++this.nextId,x:b.x,y:b.y,vx:Math.cos(a)*K.ARROW_SPEED,vy:Math.sin(a)*K.ARROW_SPEED,age:0,life:K.ARROW_LIFE});c.emit('arrow',b.x,b.y);
+ }else{
+ this.atkCd=K.SWORD_CD/(this.status.weak>0?0.949:1);this.atkT=K.SWORD_CD;this.slashFacing=this.facing;
+ this.slashAngle=this.facing>0?2.2:Math.PI-2.2;this.slashPreviousAngle=this.slashAngle;this.slashHits={};c.emit('slash',b.x,b.y);
+ }
+ }
+ this.arrows=this.arrows.filter(function(p){
+ var ox=p.x,oy=p.y;
+ p.age=(p.age||0)+1;if(p.age>=K.ARROW_GRAV_DELAY)p.vy=Math.max(-K.FALL,p.vy-K.ARROW_GRAV*dt);
+ p.x+=p.vx*dt;p.y+=p.vy*dt;p.life-=dt;
+ var shape={x0:ox,y0:oy,x1:p.x,y1:p.y,r:0.08};
+ if(TR.resolveArrow(c.boss,c,K.BOW,shape,p.vx>=0?1:-1))return false;
+ return p.life>0&&p.x>=0&&p.x<=BB.ARENA.W&&p.y>=0&&p.y<=BB.ARENA.H;
+ },this);
+ var slash=this.slashBox();
+ if(slash)TR.slashExtras(c.boss,c,this.NAIL,slash.pts,this.slashHits);
+ this.updateLifeDrain(c);
+ if(typeof TR.updatePickups==='function')TR.updatePickups(c);
+ this.prev={jump:!!i.jump,switchWeapon:!!i.switchWeapon};
+ };
+ P.onSlashContact=function () {};
+ P.hurt=function(c,base,fromX,hazard){
+ if(this.invul>0||this.hp<=0)return false;
+ var damage=TR.playerDamage(c,base,this.defense(),TR.defFactor(c));
+ this.hp=Math.max(0,this.hp-damage);this.invul=damage===1?K.INVUL/2:K.INVUL;
+ this.knock=this.x>fromX?4.5*TR.PX:-4.5*TR.PX;this.vx=this.knock;this.vy=3.5*TR.PX;this.grounded=false;this.jumpTicks=0;
+ if(hazard&&hazard.debuff&&c.rng.chance(hazard.debuffChance==null?1:hazard.debuffChance)){
+ var duration=hazard.debuffDuration;
+ if(Array.isArray(duration))duration=c.rng.uniform(duration[0],duration[1]);
+ this.applyStatus(hazard.debuff,+duration||0);
+ }
+ // A weighted debuff pool (Brain of Cthulhu Expert contacts): one roll picks one debuff and its duration range.
+ if(hazard&&hazard.debuffPool&&c.rng.chance(hazard.debuffChance==null?1:hazard.debuffChance)){
+ var pool=hazard.debuffPool,pick=pool[c.rng.pick(pool.map(function(e){return e[1];}))];
+ this.applyStatus(pick[0],c.rng.uniform(pick[2][0],pick[2][1]));
+ }
+ TR.emitHit(c,'player_hit',this.x,this.y+K.H,damage);return true;
+ };
+ P.state=function(){return TR.snapshot(this,{attacking:this.atkT>0,flight_max:K.WINGS});};
+ BB.Adventurer=Adventurer;BB.TR.BODY=K;
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/bosses/brain_of_cthulhu.js b/environments/games/web/games/terraria_remake/bosses/brain_of_cthulhu.js
new file mode 100644
index 0000000000000000000000000000000000000000..f7af56b828467a4afda75c81bd264c7f460978ec
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/bosses/brain_of_cthulhu.js
@@ -0,0 +1,131 @@
+(function(g){
+ var BB=g.BB,TR=BB.TR,S=BB.SPECS.brain_of_cthulhu;
+ // Desktop 1.4.5.8 ordinary single-player Classic / Expert Brain of Cthulhu (aiStyle 54) and its Creepers.
+ // Published: brain 1250/2125 life, 30/54 damage, defense 14; 20 Creepers 100/170 life, 20/36 damage, defense 10,
+ // never respawn; the brain cannot be damaged until every Creeper is dead; a Creeper drops a heart 1/2 when the
+ // player is hurt; Expert contacts roll one debuff from a nine-entry pool (Creepers always, phase-2 brain 1/3);
+ // Expert phase 2 adds three mirror illusions around the player whose opacity rises as health drops.
+ // Unpublished (estimates): teleport and charge timing, speeds, orbit radius, the 1.4.4
+ // phase-1 safe radius.
+ var W=110/32,H=86/32;
+ // Expert contact debuff pool: [name, weight out of 81, duration range s] (Creeper / Brain of Cthulhu pages).
+ var POOL=[['poisoned',11,[5.23,10.4]],['darkness',11,[3,5.93]],['cursed',2,[.73,1.47]],['bleeding',11,[15,29.8]],
+ ['confused',2,[1.5,2.97]],['slow',11,[5.23,10.4]],['weak',11,[11.23,22.33]],['silenced',11,[1.5,2.97]],['broken_armor',11,[9.73,19.37]]];
+ function Brain(){}
+ var P=Brain.prototype;TR.boss(P,S);
+ P.reset=function(c){
+ this.setup(c,20,9,W,H);this.expert=this.k.expert>=.5;
+ // Boss health is the published combined total (brain + 20 Creepers, 3250 / 5525), like the Eater's segment sum,
+ // so the HUD, verifier and reward count Creeper kills. The brain's own health is brainHp.
+ this.brainHp=this.brainMax=TR.paceHp(this,this.expert?2125:1250,10,this.pace.brainHp);this.dmg=TR.paceDmg(this,this.expert?54:30);this.defense=14;
+ this.creeperHp=TR.paceHp(this,this.expert?170:100);this.creeperDmg=TR.paceDmg(this,this.expert?36:20);
+ this.sourceProfile=this.expert?'desktop-expert':'desktop-classic';this.phase=1;this.fade=1;this.tpTimer=0;this.chargeTimer=1.2/this.pace.aggr;
+ this.knockbackResist=this.expert?.6:.55;
+ this.orbitAngle=0;this.illusions=[];this.illusionAlpha=0;
+ for(var i=0;i<20;i++){
+ // The 20 Creepers spawn on three rings around the brain, evenly spread (no cluster a single sword arc clears).
+ var a=i/20*Math.PI*2,r=2.2+(i%3)*.55;
+ this.minions.push({id:++this.nextId,kind:'creeper',x:this.x+TR.cos(a)*r,y:this.y+TR.sin(a)*r,vx:0,vy:0,w:34/32,h:34/32,
+ hp:this.creeperHp,max_hp:this.creeperHp,dmg:this.creeperDmg,defense:10,knockbackResist:this.expert?.28:.2,floating:true,
+ drop:'creeper_heart',slot:a,ring:r,st:'orbit',t:0,debuffPool:this.expert?POOL:null,debuffChance:1});
+ }
+ this.max_hp=this.brainMax+20*this.creeperHp;this.sync();
+ this.go(c,'idle',0,'creeper_charge');
+ };
+ P.sync=function(){this.hp=this.brainHp+this.minions.reduce(function(a,m){return a+(m.kind==='creeper'?Math.max(0,m.hp):0);},0);};
+ P.alive=function(){return this.minions.filter(function(m){return m.kind==='creeper'&&m.hp>0;});};
+ // Phase 1: invulnerable; a teleporting brain is not solid until it has mostly faded in.
+ P.hitTargets=function(){return this.phase===1||this.fade<.5||this.st==='dead'?[]:[{id:'brain',box:this.bodyBox()}];};
+ P.onNailHit=function(c,base,dir,f,id){
+ if(this.phase===1||this.fade<.5||this.brainHp<=0)return null;
+ var hit=TR.rollDetails(c,base,this.defense,.5,.04);this.brainHp=Math.max(0,this.brainHp-hit.damage);this.hitFlash=.12;
+ TR.emitHit(c,'boss_hit',this.x,this.y,hit.damage,hit.critical);this.sync();
+ if(!this.brainHp){this.hp=0;this.st='dead';this.minions=[];this.shots=[];c.emit('boss_dead',this.x,this.y);return 'flesh';}
+ // "The only boss that is affected by knockback" (Wiki trivia): phase-2 knockback resistance 55 % / 60 %
+ // (1.4.4). Arrow KB 2, sword KB 5; the push uses the shared NPC knockback rule on the brain's own velocity.
+ TR.enemyKnockback(c,this,hit.damage,hit.critical,{facing:f<0?-1:1,knockback:dir==='arrow'?TR.BODY.BOW_KB:TR.BODY.SWORD_KB});
+ return 'flesh';
+ };
+ P.teleport=function(c,near){
+ // A random spot around the player, away from the player and inside the arena (phase 1 keeps the safe radius).
+ var b=c.body.centre(),best=null;
+ for(var k=0;k<12;k++){
+ var a=c.rng.uniform(0,Math.PI*2),r=near?c.rng.uniform(5,8):c.rng.uniform(7,11),x=b.x+TR.cos(a)*r,y=b.y+Math.abs(TR.sin(a))*r*.8+1;
+ if(x>this.w/2&&xthis.h/2+.5&&y.9||m.xBB.ARENA.W-m.w/2||m.yBB.ARENA.H-m.h/2){m.st='return';m.t=0;}
+ m.x=BB.clamp(m.x,m.w/2,BB.ARENA.W-m.w/2);m.y=BB.clamp(m.y,m.h/2,BB.ARENA.H-m.h/2);
+ }else{
+ // Irregular circles around the brain: each Creeper has its own ring radius and a wobble.
+ var a=m.slot+self.orbitAngle,r=m.ring+TR.sin(self.orbitAngle*1.7+m.id)*.5;
+ var tx=self.x+TR.cos(a)*r,ty=self.y+TR.sin(a)*r;
+ TR.moveToward(m,tx,ty,(m.st==='return'?9:12)*self.pace.speed,m.st==='return'?30:60);
+ if(m.st==='return'&&Math.hypot(m.x-tx,m.y-ty)<.6)m.st='orbit';
+ }
+ return true;
+ });
+ };
+ P.update=function(c){
+ if(this.st==='dead')return;this.clock(c);var dt=BB.DT,b=c.body.centre();this.sync();
+ this.fade=Math.min(1,this.fade+dt/(this.phase===1?.6:.35));
+ if(this.phase===1){
+ // Translucent and invulnerable: drift toward the player, then teleport away in a random direction. The drift
+ // stops short of the player so the orbiting ring cannot simply sit on them: Creepers reach the player by
+ // charging (the source behaviour), not by the ring overlapping a player the brain is parked next to.
+ var bx=b.x,by=b.y+1.5,dd=Math.hypot(this.x-bx,this.y-by),keep=4.5;
+ if(dd>keep)TR.moveToward(this,bx,by,2.4*TR.PX*this.pace.speed,4);
+ else{this.vx*=.9;this.vy*=.9;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2);this.y=BB.clamp(this.y+this.vy*dt,this.h/2,BB.ARENA.H-this.h/2);}
+ this.tpTimer+=dt;
+ if(this.tpTimer>=(this.expert?4:5.5)/this.pace.aggr){this.tpTimer=0;this.teleport(c,false);}
+ this.updateCreepers(c,b);this.sync();
+ if(!this.alive().length){this.phase=2;this.tpTimer=0;this.go(c,'transform',.8,'teleport');c.emit('boss_escalate',this.x,this.y);}
+ return;
+ }
+ if(this.st==='transform'){this.vx=this.vy=0;if(this.timer<=0)this.go(c,'attack',0,'teleport');}
+ else{
+ // Phase 2: visible heart. It closes in "at a steady pace" (Wiki tip) and its illusions "spread away from the
+ // real Brain if the player is walking away" -- so a walking player outpaces it; its threat is the rapid
+ // teleports around the player. Chase 3 px/tick (Expert 4) is below the 3 px/tick-plus run speed once tier
+ // aggression is applied (r6 round 2: at 4.5 px/tick a movement-only beam search died by 33 s on hard).
+ if(this.fade>=1)TR.moveToward(this,b.x,b.y,(this.expert?4:3)*TR.PX*this.pace.speed,this.expert?12:8);
+ this.tpTimer+=dt;
+ if(this.tpTimer>=(this.expert?2.4:3.2)/this.pace.aggr){this.tpTimer=0;this.teleport(c,true);}
+ }
+ // Expert illusions mirror the brain through the player; opacity rises as the brain's own health drops.
+ if(this.expert){var dx=this.x-b.x,dy=this.y-b.y;
+ this.illusions=[{x:b.x-dx,y:b.y+dy},{x:b.x+dx,y:b.y-dy},{x:b.x-dx,y:b.y-dy}].map(function(p){
+ return {x:BB.clamp(p.x,.5,BB.ARENA.W-.5),y:BB.clamp(p.y,.5,BB.ARENA.H-.5)};});
+ this.illusionAlpha=.25+.75*(1-this.brainHp/this.brainMax);}
+ this.minions=this.minions.filter(function(m){return m.hp>0;});this.sync();
+ };
+ P.hazards=function(){
+ if(this.st==='dead')return [];
+ var out=[];
+ // A fading brain cannot touch the player; it becomes solid as it finishes appearing.
+ if(this.fade>=.5){var h={kind:this.phase===1?'brain':'brain_heart',box:this.bodyBox(),dmg:this.dmg,fromX:this.x};
+ if(this.expert&&this.phase===2){h.debuffPool=POOL;h.debuffChance=1/3;}out.push(h);}
+ return out.concat(TR.extraHazards(this));
+ };
+ BB.CASES['terraria/brain_of_cthulhu'] = TR.register('brain_of_cthulhu','Teleporting Flesh Brain',Brain,'crimson');
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/bosses/eater_of_worlds.js b/environments/games/web/games/terraria_remake/bosses/eater_of_worlds.js
new file mode 100644
index 0000000000000000000000000000000000000000..af96ae65ebe8fe46fca9d82311d9f21ecbba2a00
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/bosses/eater_of_worlds.js
@@ -0,0 +1,170 @@
+(function(g){
+ var BB=g.BB,TR=BB.TR,S=BB.SPECS.eater_of_worlds;
+ var EXPLOSIVES={grenade:1,sticky_grenade:1,bouncy_grenade:1,bomb:1,sticky_bomb:1,bouncy_bomb:1,
+ dynamite:1,sticky_dynamite:1,bouncy_dynamite:1,power_bomb:1,sticky_power_bomb:1,explosives:1,
+ explosive_bunny:1,confetti_grenade:1,bomb_fish:1,scarab_bomb:1,beenade:1,bee:1,giant_bee:1,tnt_barrel:1};
+ var EXPLOSIVE_IDS={30:1,397:1,517:1,28:1,37:1,516:1,29:1,470:1,637:1,1086:1,1087:1,
+ 108:1,281:1,588:1,519:1,773:1,183:1,181:1,566:1,1002:1};
+ function snap(v){return Math.floor(v/TR.TILE)*TR.TILE;}
+ function Eater(){}
+ var P=Eater.prototype;TR.boss(P,S);
+ P.stats=function(type){
+ return {hp:TR.paceHp(this,this.expert?210:150,1),dmg:TR.paceDmg(this,this.expert?(type==='head'?48:type==='body'?21:18):(type==='head'?22:type==='body'?13:11)),
+ defense:(type==='head'?2:type==='body'?4:8)+(this.expert?2:0)};
+ };
+ P.reset=function(c){
+ this.setup(c,20,-1,1.375,1.375);this.expert=this.k.expert>=.5;this.segments=[];this.chains=[];
+ this.sourceProfile=this.expert?'desktop-expert':'desktop-classic';this.spacing=46/32;
+ // Tier aggression (tiers.js) scales top speed by sqrt(aggr) and steering by aggr; 1 at normal.
+ this.maxSpeed=16*(this.expert?1.2:1)*this.pace.speed;this.acceleration=(this.expert?16.875:7.875)*this.pace.aggr;
+ // The available reference gives ballistic peak heights (~31/44 tiles), rather than raw AI gravity.
+ // This approximation is constrained to those peaks; exact continuous steering remains documented.
+ this.airGravity=16*16/(31*TR.TILE*2);this.max_hp=0;
+ var n=Math.max(8,Math.round((this.expert?72:67)*this.pace.segments)),size=this.expert?1.2:1;
+ for(var i=0;i1){
+ var first=run[0],prev=old.find(function(ch){return ch.ids[0]===first.id;}),newHead=first.type!=='head';
+ run.forEach(function(s,n){self.retype(s,n===0?'head':n===run.length-1?'tail':'body');});
+ // A surviving head keeps its momentum. Every new split head must fall and reach material first.
+ chains.push({ids:run.map(function(s){return s.id;}),st:prev?prev.st:'burrow',timer:0,digTimer:prev?prev.digTimer:0,
+ target:prev?prev.target:c.body.centre(),vx:prev?prev.vx:0,vy:prev?prev.vy:0,
+ forceFall:newHead||(!prev&&old.length>0)});
+ }run=[];
+ }
+ this.segments.forEach(function(s){if(s.hp>0)run.push(s);else finish();});finish();this.chains=chains;
+ this.hp=this.segments.reduce(function(a,s){return a+s.hp;},0);
+ if(!this.hp){this.st='dead';this.shots=[];c.emit('boss_dead',this.x,this.y);}
+ };
+ P.hitTargets=function(){
+ // Initial coiled segments are invisible but remain hittable, as in the source game.
+ return this.segments.filter(function(s){return s.hp>0&&s.y>-s.h/2;}).map(function(s){return {id:s.id,box:TR.box(s)};});
+ };
+ P.damageMultiplier=function(attack){
+ var kind=typeof attack==='string'?attack:attack&&(attack.kind||attack.projectileKind),
+ id=attack&&typeof attack==='object'?attack.projectileId:null;
+ if(kind==='molotov_fire'||kind==='obsidian_swordfish_fire')return .65;
+ return this.expert&&(EXPLOSIVES[kind]||EXPLOSIVE_IDS[id])?.2:1;
+ };
+ P.onNailHit=function(c,base,dir,f,id){
+ var s=this.segments.find(function(v){return v.id===id;});if(!s||s.hp<=0)return null;
+ var hit=TR.rollDetails(c,base*this.damageMultiplier(dir),s.defense,0.5,0.04),damage=hit.damage;
+ s.hp=Math.max(0,s.hp-damage);this.hitFlash=.12;TR.emitHit(c,'boss_hit',s.x,s.y,damage,hit.critical);
+ if(!s.hp){if(TR.dropSegment)TR.dropSegment(c,this,s);c.emit('worm_split',s.x,s.y);this.rebuild(c);}
+ else this.hp=this.segments.reduce(function(a,v){return a+v.hp;},0);
+ return 'flesh';
+ };
+ P.inMaterial=function(c,s){
+ var solid=function(x,y){return TR.solidAt?TR.solidAt(c,x,y,{platforms:true}):y<=0;};
+ return solid(s.x,s.y)||solid(s.x,s.y-s.h/2)||solid(s.x-s.w/2,s.y)||solid(s.x+s.w/2,s.y);
+ };
+ // Source worm steering (vanilla aiStyle 6, as mirrored by tModLoader ExampleMod WormHead): per-axis steps
+ // of `acceleration` toward the target direction, plus the source's anti-stall terms. When the head moves
+ // away from a nearly level/vertical target it curves along the other axis (x2 step); when it is slower than
+ // half its top speed it keeps pushing along its current sign. Without those terms a head below a target
+ // that is higher than its standing hop hovers at the surface forever (r4 bug).
+ // y is up here and down in the source, so a zero vertical velocity breaks toward "up" in both.
+ function toward(v,t,a){return vt?v-a:v;}
+ P.steerToward=function(ch,dirX,dirY){
+ var speed=this.maxSpeed,acc=this.acceleration*BB.DT,len=Math.hypot(dirX,dirY),absX=Math.abs(dirX),absY=Math.abs(dirY),vx=ch.vx,vy=ch.vy;
+ if(len>0){dirX*=speed/len;dirY*=speed/len;}
+ if(len>0&&((vx>0&&dirX>0)||(vx<0&&dirX<0)||(vy>0&&dirY>0)||(vy<0&&dirY<0))){
+ vx=toward(vx,dirX,acc);vy=toward(vy,dirY,acc);
+ if(Math.abs(dirY)0&&dirX<0)||(vx<0&&dirX>0)))vy+=vy<0?-acc*2:acc*2;
+ if(Math.abs(dirX)0&&dirY<0)||(vy<0&&dirY>0)))vx+=vx>0?acc*2:-acc*2;
+ }else if(absX>absY){
+ vx=toward(vx,dirX,acc*1.1);
+ if(Math.abs(vx)+Math.abs(vy)0)vy=toward(vy,dirY,acc*1.1);
+ if(Math.abs(vx)+Math.abs(vy)0?acc:-acc;
+ }
+ ch.vx=vx;ch.vy=vy;
+ };
+ // Out of material: constant gravity (fitted to the published peaks, EOW-05) and the source's horizontal
+ // terms: a slow head keeps accelerating along its sign, a head at terminal fall turns toward the target,
+ // a fast-falling head loses horizontal speed. dirX is the raw tile-snapped distance, compared in source px.
+ P.fall=function(ch,dirX){
+ var speed=this.maxSpeed,acc=this.acceleration*BB.DT;
+ ch.vy=Math.max(-speed,ch.vy-this.airGravity*BB.DT);
+ if(Math.abs(ch.vx)+Math.abs(ch.vy)dpx)ch.vx-=acc;}
+ else if(ch.vy<-4*TR.PX)ch.vx+=ch.vx<0?acc*.9:-acc*.9;
+ };
+ P.spitChance=function(s){return s.type==='head'?1/390+(1-s.hp/s.max_hp)*(1/90-1/390):s.type==='body'?1/900:0;};
+ P.spitAllowed=function(c,s){
+ if(s.hp<=0||s.type==='tail')return false;
+ var b=c.body.centre();
+ if(TR.lineOfSight&&!TR.lineOfSight(c,s.x,s.y,b.x,b.y))return false;
+ if(s.type==='body'&&(s.y<=0||(TR.backgroundWallAt&&TR.backgroundWallAt(c,s.x,s.y))))return false;
+ return true;
+ };
+ P.spit=function(c,s){
+ TR.shoot(this,c,s.x,s.y,7*TR.PX,'vile_spit',false);
+ var shot=this.shots[this.shots.length-1];shot.sourceSegment=s.id;shot.dmg=TR.paceDmg(this,64);shot.destructible=true;shot.solidCollision=true;shot.collidePlatforms=true;
+ // Eater-specific Vile Spit is an NPC attack and has no Weak debuff since Desktop 1.4.2.
+ // Its 7 px/tick motion corresponds to the Wiki's rounded 36 mph.
+ c.emit('vile_spit',s.x,s.y);
+ };
+ P.update=function(c){
+ if(this.st==='dead')return;this.clock(c);var dt=BB.DT,b=c.body.centre(),lookup={},self=this;
+ this.segments.forEach(function(s){lookup[s.id]=s;});
+ this.chains.forEach(function(ch){
+ var head=lookup[ch.ids[0]],material=self.inMaterial(c,head),distance=Math.hypot(head.x-b.x,head.y-b.y),
+ far=Math.abs(head.x-b.x)>62.5*TR.TILE||Math.abs(head.y-b.y)>62.5*TR.TILE;
+ ch.digTimer-=dt;
+ if(material&&distance<25&&ch.digTimer<=0){
+ c.emit('burrow_dig',head.x,head.y);ch.digTimer=BB.clamp(.1+distance*.026,.1,.75);
+ }
+ ch.target={x:b.x,y:b.y};
+ if(material)ch.forceFall=false;
+ // The source compares tile-snapped centres (16 px = TR.TILE).
+ var dirX=snap(b.x)-snap(head.x),dirY=snap(b.y)-snap(head.y);
+ if((material||far)&&!ch.forceFall){self.steerToward(ch,dirX,dirY);ch.st='burrow';}
+ // No artificial pause or telegraph: outside tiles a worm follows a ballistic fall.
+ else{self.fall(ch,dirX);ch.st='lunge';}
+ head.vx=ch.vx;head.vy=ch.vy;head.x+=ch.vx*dt;head.y+=ch.vy*dt;
+ // Finite benchmark world margins allow a long chain to turn underground off-screen.
+ if(head.x< -4){head.x=-4;ch.vx=Math.abs(ch.vx);}if(head.x>BB.ARENA.W+4){head.x=BB.ARENA.W+4;ch.vx=-Math.abs(ch.vx);}
+ if(head.y< -20){head.y=-20;ch.vy=Math.abs(ch.vy);}if(head.y>BB.ARENA.H+10){head.y=BB.ARENA.H+10;ch.vy=-Math.abs(ch.vy);}
+ for(var n=1;nself.spacing){
+ s.x=prev.x-sx/dist*self.spacing;s.y=prev.y-sy/dist*self.spacing;s.visible=true;
+ }else if(s.visible&&dist>1e-9){s.x=prev.x-sx/dist*self.spacing;s.y=prev.y-sy/dist*self.spacing;}
+ s.vx=(s.x-ox)/dt;s.vy=(s.y-oy)/dt;
+ }
+ });
+ var leader=this.chains[0];
+ if(leader){var head=lookup[leader.ids[0]];this.x=head.x;this.y=head.y;this.vx=head.vx;this.vy=head.vy;
+ this.st=leader.st==='burrow'?'recover':'attack';this.timer=0;this.target=leader.target;}
+ if(this.expert)this.segments.forEach(function(s){
+ if(!self.spitAllowed(c,s))return;s.shotAttempts++;
+ if(c.rng.chance(self.spitChance(s)))self.spit(c,s);
+ });
+ };
+ P.hazards=function(){
+ return this.st==='dead'?[]:this.segments.filter(function(s){return s.hp>0&&s.y>-s.h/2;}).map(function(s){
+ return {kind:'worm_'+s.type,box:TR.box(s),dmg:s.dmg,fromX:s.x};
+ }).concat(TR.extraHazards(this));
+ };
+ BB.CASES['terraria/eater_of_worlds'] = TR.register('eater_of_worlds','Burrowing Great Worm',Eater,'corruption');
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/bosses/eye_of_cthulhu.js b/environments/games/web/games/terraria_remake/bosses/eye_of_cthulhu.js
new file mode 100644
index 0000000000000000000000000000000000000000..1e5bfa79114c85e7151db706e90a5d2c43f975fb
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/bosses/eye_of_cthulhu.js
@@ -0,0 +1,125 @@
+(function(g){
+ var BB=g.BB,TR=BB.TR,S=BB.SPECS.eye_of_cthulhu;
+ function Eye(){}
+ var P=Eye.prototype;TR.boss(P,S);
+ P.reset=function(c){
+ this.setup(c,20,10,110/32,110/32);
+ this.expert=this.k.expert>=0.5;this.easyScale=1;
+ this.hp=this.max_hp=TR.paceHp(this,this.expert?3640:2800);
+ this.dmg=TR.paceDmg(this,this.expert?30:15);this.defense=12;this.phaseAt=this.expert?0.65:0.5;
+ this.k.hp=this.max_hp;this.k.dmg=this.dmg;this.k.phase_at=this.phaseAt;
+ this.k.def_factor=this.expert?0.75:0.5;
+ this.cycleIndex=0;this.dashesLeft=0;this.spawnTimer=0;this.servantsThisHover=0;
+ this.servantsPerHover=this.expert?5:4;this.pendingChain=false;
+ this.transformFrames=0;this.rotation=0;this.dashAge=0;this.dashFrames=0;this.dashFramesTotal=0;this.chainLevel=0;
+ this.recoverFrames=0;this.despawned=false;this.dawnDeparting=false;
+ this.startHover(c);
+ };
+ P.startHover=function(c){
+ this.move=null;this.dashesLeft=0;this.pendingChain=false;
+ this.servantsThisHover=0;this.spawnTimer=1.8/this.pace.aggr;this.hoverFrames=0;
+ this.go(c,'idle',this.hoverLimit()/60);
+ };
+ // Tier aggression stretches hover and summon cadences and scales dash/hover speeds (tiers.js).
+ P.hoverLimit=function(){return Math.round((this.phase===1?600:this.expert?120:200)/this.pace.aggr);};
+ P.spawnServant=function(c,angle){
+ var b=c.body.centre(),dx=b.x-this.x,dy=b.y-this.y,l=Math.hypot(dx,dy)||1;
+ var vx=dx/l,vy=dy/l;
+ if(angle){var co=Math.cos(angle),si=Math.sin(angle),ox=vx;vx=ox*co-vy*si;vy=ox*si+vy*co;}
+ this.minions.push({id:++this.nextId,kind:'servant',x:this.x+vx*this.w/2,y:this.y+vy*this.h/2,
+ vx:vx*5*TR.PX*this.pace.speed,vy:vy*5*TR.PX*this.pace.speed,w:20/32,h:20/32,hp:this.expert?12:8,max_hp:this.expert?12:8,
+ dmg:TR.paceDmg(this,this.expert?24:12),defense:0,drop:'heart_star',floating:true,knockbackResist:this.expert?0.1:0});
+ c.emit('servant_spawn',this.x,this.y);
+ };
+ P.startDashes=function(c,chain){
+ this.move=chain?'chain_dash':'dash';this.dashesLeft=chain?5:3;
+ this.chainLevel=this.expert&&this.phase===2?(this.hp/this.max_hp<0.04?2:this.hp/this.max_hp<0.12?1:0):0;
+ this.launch(c);
+ };
+ P.launch=function(c){
+ var b=c.body.centre(),chain=this.move==='chain_dash';
+ if(chain)this.chainLevel=this.hp/this.max_hp<0.04?2:this.hp/this.max_hp<0.12?1:0;
+ // A charge commits to one vector. Only rapid charges lead the moving target.
+ var lead=chain?(this.chainLevel===2?0.25:0.12):0;
+ this.target={x:b.x+(c.body.vx||0)*lead,y:b.y+(c.body.vy||0)*lead};
+ var dx=this.target.x-this.x,dy=this.target.y-this.y,l=Math.hypot(dx,dy)||1;
+ var speed=(chain?(this.chainLevel===2?20:16):this.phase===2?6.8:6)*TR.PX*this.pace.speed;
+ if(!chain&&this.expert)speed*=1.15;
+ this.vx=dx/l*speed;this.vy=dy/l*speed;this.dashAge=0;this.dashFrames=0;
+ this.dashFramesTotal=chain?(this.chainLevel===2?21:this.chainLevel===1?29:39):150;
+ this.go(c,'attack',this.dashFramesTotal/60,this.move);
+ c.emit(chain?'eye_chain_roar':'eye_roar',this.x,this.y);
+ };
+ P.pauseCharges=function(c,frames){frames=Math.round(frames/this.pace.aggr);this.recoverFrames=frames;this.go(c,'recover',frames/60);};
+ P.updateServants=function(c,b){
+ this.minions=this.minions.filter(function(m){
+ if(m.hp<=0){if(TR.dropMinion)TR.dropMinion(c,this,m);return false;}
+ TR.moveToward(m,b.x,b.y,(this.expert?7:6)*TR.PX*this.pace.speed,12);return true;
+ },this);
+ };
+ P.updateArmor=function(){
+ if(this.phase===1){this.defense=12;this.dmg=TR.paceDmg(this,this.expert?30:15);return;}
+ var frac=this.hp/this.max_hp;
+ this.defense=this.expert&&frac<0.04?-30:this.expert&&frac<0.12?-15:0;
+ this.dmg=TR.paceDmg(this,this.expert?(frac<0.04?40:36):23);
+ };
+ P.onNailHit=function(c,base,dir,f,id){this.updateArmor();return TR.damageBoss(this,c,base,id);};
+ P.update=function(c){
+ if(this.st==='dead'||this.despawned)return;this.clock(c);var dt=BB.DT,b=c.body.centre();
+ if(TR.isDaytime&&TR.isDaytime(c)&&!this.dawnDeparting){
+ this.dawnDeparting=true;this.st='despawn';this.timer=1e9;this.stT=0;this.move=null;
+ this.vy=Math.max(4*TR.PX,this.vy);c.emit('eye_dawn_flee',this.x,this.y);
+ }
+ if(this.dawnDeparting){
+ // Night-only bosses depart upward rather than vanishing in place when dawn arrives.
+ this.vx*=0.98;this.vy=Math.min(10*TR.PX,this.vy+0.2*TR.PG*dt);
+ this.x+=this.vx*dt;this.y+=this.vy*dt;this.updateServants(c,b);
+ if(this.y-this.h/2>BB.ARENA.H){this.despawned=true;this.minions=[];this.shots=[];c.emit('eye_dawn_despawn',this.x,this.y);}
+ return;
+ }
+ // Mode gates are discrete. At exactly the threshold the original first form remains active.
+ if(this.phase===1&&this.hp/this.max_hp=this.hoverLimit())this.startDashes(c,this.expert&&this.phase===2&&this.hp/this.max_hp<0.12);
+ }else if(this.st==='transform'){
+ this.vx=this.vy=0;this.transformFrames++;this.rotation+=Math.max(0,100-Math.abs(100-this.transformFrames))*0.005;
+ // The original Eye remains vulnerable during the transformation.
+ if(this.transformFrames>=200)this.startDashes(c,false);
+ }else if(this.st==='attack'){
+ this.dashFrames++;this.dashAge=this.dashFrames/60;
+ if(this.move==='dash'&&this.dashFrames>40){this.vx*=0.98;this.vy*=0.98;}
+ this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2);
+ this.y=BB.clamp(this.y+this.vy*dt,this.h/2,BB.ARENA.H-this.h/2);
+ if(this.dashFrames>=this.dashFramesTotal){
+ this.dashesLeft--;
+ if(this.dashesLeft>0)this.pauseCharges(c,this.move==='chain_dash'?(this.chainLevel===2?1:this.chainLevel===1?5:12):1);
+ else if(this.expert&&this.phase===2){
+ if(this.move==='dash'){this.pendingChain=true;this.pauseCharges(c,21);}
+ else if(this.hp/this.max_hp<0.12){this.pendingChain=true;this.pauseCharges(c,this.hp/this.max_hp<0.04?1:7);}
+ else this.startHover(c);
+ }else this.startHover(c);
+ }
+ }else if(this.st==='recover'){
+ this.vx*=0.98;this.vy*=0.98;
+ this.recoverFrames--;
+ if(this.recoverFrames<=0){if(this.pendingChain){this.pendingChain=false;this.startDashes(c,true);}else this.launch(c);}
+ }
+ this.updateServants(c,b);
+ };
+ P.hazards=function(){return this.st==='dead'||this.despawned?[]:[{kind:this.phase===2?'maw':'eye',box:this.bodyBox(),dmg:this.dmg,fromX:this.x}].concat(TR.extraHazards(this));};
+ BB.CASES['terraria/eye_of_cthulhu'] = TR.register('eye_of_cthulhu','Charging Giant Eye',Eye,'night');
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/bosses/king_slime.js b/environments/games/web/games/terraria_remake/bosses/king_slime.js
new file mode 100644
index 0000000000000000000000000000000000000000..57e6fe6aed13ef4e7d439ec910c783c6269e3b4e
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/bosses/king_slime.js
@@ -0,0 +1,132 @@
+(function(g){
+ var BB=g.BB,TR=BB.TR,S=BB.SPECS.king_slime;
+ // Desktop 1.4.5.8, ordinary single-player Classic / Expert, without secret seeds.
+ // Units retain the common 32 source pixels per world unit and 60 simulation ticks per second.
+ var W=122.5/32,H=115/32,GRAVITY=0.3*TR.PG;
+ function KingSlime(){}
+ var P=KingSlime.prototype;TR.boss(P,S);
+ P.reset=function(c){
+ this.setup(c,21,H/2,W,H);this.expert=this.k.expert>=0.5;
+ this.hp=this.max_hp=TR.paceHp(this,this.expert?2800:2000);this.dmg=TR.paceDmg(this,this.expert?64:40);this.defense=10;
+ this.jumpIndex=0;this.floor=0;this.groundTicks=0;this.teleportWait=0;
+ this.spawnMark=this.max_hp;this.teleportScale=1;this.hidden=false;this.invulnerable=false;
+ this.go(c,'idle',1);this.sourceProfile=this.expert?'desktop-expert':'desktop-classic';
+ };
+ P.jumpCooldown=function(){
+ var f=this.hp/this.max_hp,i=f>=.8?0:f>=.6?1:f>=.4?2:f>=.2?3:f>=.1?4:5;
+ // Tier aggression stretches the source cooldown frames (tiers.js); 1 at normal and above.
+ return Math.round((this.move==='high_jump'?[100,67,50,34,23,16]:[60,40,30,20,14,10])[i]/this.pace.aggr);
+ };
+ P.resize=function(){
+ var bottom=this.y-this.h/2,size=(.6+.4*this.hp/this.max_hp)*this.teleportScale;
+ this.w=W*size;this.h=H*size;this.y=bottom+this.h/2;
+ };
+ P.slime=function(c,blueOnly){
+ var spike=!blueOnly&&this.expert&&c.rng.chance(.25),kind=spike?'spiked_slime':'slime';
+ // Sourced ordinary pre-Hardmode NPC statistics; volley timing remains provisional.
+ var m={id:++this.nextId,kind:kind,x:this.x+c.rng.uniform(-this.w*.35,this.w*.35),
+ y:Math.max(.3,this.y-this.h*.25),vx:c.rng.uniform(-2,2),vy:c.rng.uniform(3,5),
+ w:.75,h:.5,hp:spike?100:this.expert?50:25,max_hp:spike?100:this.expert?50:25,
+ defense:spike?5:2,dmg:TR.paceDmg(this,spike?28:this.expert?14:7),knockbackResist:spike||this.expert?.1:0,
+ aggressive:spike,face:c.rng.chance(.5)?1:-1,drop:'heart_star',timer:c.rng.uniform(.1,.6),spikeTimer:c.rng.uniform(.8,1.5)};
+ this.minions.push(m);c.emit(spike?'spiked_slime_spawn':'slime_spawn',m.x,m.y);
+ };
+ P.onNailHit=function(c,base,dir,f,part){
+ if(this.invulnerable||this.hidden||this.st==='dead')return null;
+ var old=this.hp,result=TR.damageBoss(this,c,base,part);
+ if(this.hp===old)return result;
+ if(!this.hp){var deathCount=4+c.rng.int(4);for(var j=0;j125*TR.TILE)return {x:b.x,y:c.body.y};
+ var surfaces=[[0,BB.ARENA.W,0]].concat(TR.platforms(c));
+ function candidates(lo,hi){
+ var result=[];surfaces.forEach(function(p){
+ for(var x=Math.max(.5,p[0]);x<=Math.min(BB.ARENA.W-.5,p[1]);x+=TR.TILE){
+ var d=Math.max(Math.abs(x-b.x),Math.abs(p[2]-b.y));
+ if(d>=lo*TR.TILE&&d<=hi*TR.TILE&&los(x,p[2]+self.h/2)&&
+ (!TR.solidAt||!TR.solidAt(c,x,p[2]+TR.TILE,{platforms:true})))result.push({x:x,y:p[2]});
+ }
+ });return result;
+ }
+ var spots=candidates(7,10);if(!spots.length)spots=candidates(2,6);
+ return spots.length?spots[c.rng.int(spots.length)]:{x:b.x,y:c.body.y};
+ };
+ P.startTeleport=function(c){
+ this.target=this.teleportSpot(c);this.move='teleport';this.teleportWait=0;this.vx=this.vy=0;
+ this.go(c,'antic',1,'teleport');c.emit('teleport_disappear',this.x,this.y);
+ };
+ P.jump=function(c){
+ this.move=['jump','jump','low_jump','high_jump'][this.jumpIndex++%4];
+ this.f=c.body.x>=this.x?1:-1;this.target=c.body.centre();
+ this.vx=this.f*(this.move==='low_jump'?4.5:this.move==='high_jump'?3.5:4)*TR.PX;
+ this.vy=(this.move==='low_jump'?6:this.move==='high_jump'?13:8)*TR.PX;
+ this.go(c,'attack',0,this.move);
+ };
+ P.updateMinions=function(c){
+ var dt=BB.DT,b=c.body.centre(),self=this;
+ this.minions=this.minions.filter(function(m){
+ if(m.hp<=0)return false;var oldFeet=m.y-m.h/2;m.timer-=dt;m.spikeTimer-=dt;
+ m.vy=Math.max(-10*TR.PX,m.vy-GRAVITY*dt);m.x=BB.clamp(m.x+m.vx*dt,m.w/2,BB.ARENA.W-m.w/2);m.y+=m.vy*dt;
+ var ground=0;TR.platforms(c).forEach(function(p){if(m.x>=p[0]&&m.x<=p[1]&&oldFeet>=p[2]&&m.y-m.h/2<=p[2]&&m.vy<=0&&c.body.y>=p[2])ground=Math.max(ground,p[2]);});
+ if(m.y-m.h/2<=ground){
+ m.y=ground+m.h/2;m.vy=0;m.vx*=.8;
+ if(m.kind==='spiked_slime'&&Math.hypot(b.x-m.x,b.y-m.y)<7&&m.spikeTimer<=0){
+ for(var k=-1;k<=1;k++){var dx=b.x-m.x,dy=b.y-m.y,a=Math.atan2(dy,dx)+k*.22;
+ self.shots.push({id:++self.nextId,kind:'slime_spike',x:m.x,y:m.y,vx:Math.cos(a)*9,vy:Math.sin(a)*9,
+ r:.12,life:5,dmg:TR.paceDmg(self,36),gravity:9,solidCollision:true,collidePlatforms:false,sourceMinion:m.id});}
+ m.spikeTimer=1.5;c.emit('slime_spikes',m.x,m.y);
+ }
+ if(m.timer<=0){
+ if(m.aggressive||m.hp=m.x?1:-1;
+ m.vy=6*TR.PX;m.vx=m.face*2*TR.PX;m.timer=1;
+ }
+ }
+ return true;
+ });
+ };
+ P.update=function(c){
+ if(this.st==='dead')return;this.clock(c);var dt=BB.DT;
+ var obstructed=TR.lineOfSight&&!TR.lineOfSight(c,this.x,this.y,c.body.x,c.body.y+.65);
+ var teleporting=this.move==='teleport'&&(this.st==='antic'||this.st==='recover');
+ if(!teleporting&&(obstructed||Math.abs(c.body.y-(this.y+this.h/2))>10*TR.TILE))this.teleportWait+=dt;
+ // Timer pauses when reachable and is consumed only once King Slime is grounded.
+ if(teleporting){
+ if(this.st==='antic'){
+ this.teleportScale=Math.max(.02,Math.max(0,this.timer));this.resize();
+ this.hidden=this.timer<=1e-9;this.invulnerable=this.hidden;
+ if(this.timer<=1e-9){this.x=this.target.x;this.floor=this.target.y;this.y=this.floor+this.h/2;
+ this.go(c,'recover',.5,'teleport');c.emit('teleport',this.x,this.floor);}
+ }else{
+ this.hidden=false;this.invulnerable=false;this.teleportScale=BB.clamp(1-this.timer/.5,.02,1);this.resize();
+ if(this.timer<=1e-9){this.teleportScale=1;this.resize();this.jumpIndex=0;this.groundTicks=0;this.move=null;this.go(c,'idle',1);}
+ }
+ }else if(this.st==='attack'){
+ var feet=this.y-this.h/2;this.vy=Math.max(-10*TR.PX,this.vy-GRAVITY*dt);
+ this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2);this.y+=this.vy*dt;
+ var floor=0;TR.platforms(c).forEach(function(p){
+ if(this.vy<=0&&this.x+this.w/2>p[0]&&this.x-this.w/2
=p[2]&&this.y-this.h/2<=p[2]&&c.body.y>=p[2]-.1)floor=Math.max(floor,p[2]);
+ },this);
+ if(this.y-this.h/2<=floor){this.floor=floor;this.y=floor+this.h/2;this.vx=this.vy=0;this.groundTicks=0;
+ this.go(c,'recover',this.jumpCooldown()/60);c.emit('boss_land_hard',this.x,this.floor);}
+ }else{
+ this.y=this.floor+this.h/2;this.groundTicks++;this.timer=Math.max(0,(this.jumpCooldown()-this.groundTicks)/60);
+ if(this.floor>0&&c.body.y=5/this.pace.aggr-1e-9)this.startTeleport(c);else if(!this.timer)this.jump(c);
+ }
+ this.updateMinions(c);
+ };
+ P.hazards=function(){
+ if(this.st==='dead')return [];
+ var contact=this.hidden?[]:[{kind:'king_slime',box:this.bodyBox(),dmg:this.dmg,fromX:this.x}];
+ return contact.concat(TR.extraHazards(this));
+ };
+ BB.CASES['terraria/king_slime'] = TR.register('king_slime','Bouncing Gel Giant',KingSlime,'forest');
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/bosses/kit.js b/environments/games/web/games/terraria_remake/bosses/kit.js
new file mode 100644
index 0000000000000000000000000000000000000000..334bee8f1fdce39bada8a2906ddf515749fd6f48
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/bosses/kit.js
@@ -0,0 +1,24 @@
+(function(g){
+ var BB=g.BB,TR=BB.TR;BB.CASES=BB.CASES||{};
+ TR.boss=function(P,spec){
+ BB.bossKit(P,spec,{idle:'idle',antic:'telegraph',attack:'active',recover:'recovery',transform:'telegraph',dead:'recovery'});
+ P.setup=function(c,x,y,w,h){
+ this.k=BB.knobs(spec.difficulty,c.d>=.75?1:.5);this.pace=TR.pace(c,spec.id);this.hp=this.max_hp=Math.round(this.k.hp);this.dmg=Math.round(this.k.dmg);this.defense=this.k.defense||0;
+ this.x=x;this.y=y;this.w=w;this.h=h;this.vx=0;this.vy=0;this.f=-1;
+ this.st='idle';this.timer=0.8;this.stT=0;this.move=null;this.phase=1;this.hitFlash=0;this.track={};this.cycle={};this.stamp=0;this.lastActive=null;
+ this.minions=[];this.shots=[];this.pickups=[];this.nextId=0;this.target={x:x,y:y};
+ var dawn=c.options&&c.options.dawn_in_seconds;
+ this.nightTicks=Number.isFinite(dawn)?32400-BB.clamp(dawn,0,540)*60:0;
+ };
+ P.bodyBox=function(){return TR.box(this);};
+ P.onNailHit=function(c,base,dir,f,part){return TR.damageBoss(this,c,base,part);};
+ P.state=function(){var role=this.role();return TR.snapshot(this,{fsm:this.st,role:role,telegraph_left:role==='telegraph'?BB.r4(Math.max(0,this.timer)):0,hazards:this.hazards()});};
+ P.begin=function(c,move,target){this.target=target||c.body.centre();this.move=move;this.go(c,'antic',this.k.telegraph,move);};
+ P.recover=function(c,scale){this.vx=this.vy=0;this.go(c,'recover',this.k.recovery*(scale||1));};
+ P.clock=function(c){this.flash(BB.DT);this.timer-=BB.DT;this.stT+=BB.DT;this.nightTicks++;TR.updateShots(this,c);};
+ };
+ TR.register=function(id,title,Boss,arena,platforms){
+ BB.CASES=BB.CASES||{};
+ return {title:title,Body:BB.Adventurer,Boss:Boss,arena:arena,platforms:platforms||[[2,25,2.4],[4,23,5.3]]};
+ };
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/bosses/queen_bee.js b/environments/games/web/games/terraria_remake/bosses/queen_bee.js
new file mode 100644
index 0000000000000000000000000000000000000000..5d706368deac2fd99bdd20b23cde8e618c0bbfb7
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/bosses/queen_bee.js
@@ -0,0 +1,135 @@
+(function(g){
+ var BB=g.BB,TR=BB.TR,S=BB.SPECS.queen_bee;
+ // Desktop 1.4.5.8 ordinary single-player Classic / Expert Queen Bee (aiStyle 43).
+ // Published: life 3400/4760, contact 30/54, stinger 22/44, defense 8 (Expert 8-28 with lost health), knockback
+ // immune, 120 % scale, the opening attack is always the triple charge, 6/12/18 bees, Poisoned on stingers 1/3 10 s
+ // (Expert 100 % 2-20 s, contact 2-8 s). Unpublished (estimates): charge/stinger speeds,
+ // intervals, stinger count, hover offsets and the Expert speed-up curve.
+ var W=66/32*1.2,H=66/32*1.2;
+ function QueenBee(){}
+ var P=QueenBee.prototype;TR.boss(P,S);
+ P.reset=function(c){
+ this.setup(c,21,10,W,H);this.expert=this.k.expert>=.5;
+ this.hp=this.max_hp=TR.paceHp(this,this.expert?4760:3400);this.dmg=TR.paceDmg(this,this.expert?54:30);
+ this.stingerDmg=TR.paceDmg(this,this.expert?44:22);this.defense=8;
+ this.knockbackResist=1;this.sourceProfile=this.expert?'desktop-expert':'desktop-classic';
+ this.chargesLeft=0;this.side=1;this.cycleIndex=0;this.volleyLeft=0;this.volleyTimer=0;this.beeBatch=0;this.beesLeft=0;
+ this.hoverT=0;this.lockY=null;this.charge=null;this.hold=0;this.align=0;this.spawnTimer=0;
+ // The source opening attack: always the horizontal charge first.
+ this.startCharges(c);
+ };
+ // Expert grows faster and more relentless as health drops (published qualitatively; this 0..1 curve is ours).
+ P.rage=function(){return this.expert?BB.clamp(1-this.hp/this.max_hp,0,1):0;};
+ P.updateArmor=function(){this.defense=this.expert?8+Math.round(20*this.rage()):8;};
+ P.startCharges=function(c){
+ var r=this.rage();this.chargesLeft=this.expert?(r>=.9?6:r>=.75?5:r>=.5?4:3):3;
+ this.side=c.body.x>=this.x?-1:1;this.move='charge';this.go(c,'antic',0,'charge');this.align=0;
+ };
+ // Charge speed px/tick: 18 Classic (3x the player's 6 px/tick sprint cap), Expert 18 -> 27 as health drops.
+ // Unlike chase speeds, the committed charge does not scale with tier aggression: a charge is a dodge test
+ // decided by its height lock, and at 20.5 px/tick (hard x sqrt(1.3)) a movement-only beam search kept only
+ // 75/200 HP over the opening 20 s versus 164 at normal (r6 round 1, qb_charge_beam.js). Hard raises cadence
+ // (shorter alignment and recovery), damage and health instead.
+ P.chargeSpeed=function(){return (18+9*this.rage())*TR.PX;};
+ // How long she holds the lined-up pose before a charge (estimate; the source game shows a brief pause while she
+ // lines up). Expert shortens it as health drops; tier aggression shortens it, never below 0.15 s.
+ P.windup=function(){return Math.max(.15,(this.expert?.32-.14*this.rage():.32)/this.pace.aggr);};
+ P.nextAttack=function(c){
+ // After the opening charges the source cycles through its three patterns; ours: summon, stingers, charge.
+ var order=['summon','stingers','charge'],next=order[this.cycleIndex++%3];
+ if(next==='charge')this.startCharges(c);
+ else if(next==='summon'){
+ this.move='summon';this.beeBatch=[6,12,18][c.rng.int(3)];this.beesLeft=this.beeBatch;this.spawnTimer=.35/this.pace.aggr;
+ this.hoverT=0;this.go(c,'idle',0,'summon');c.emit('queen_bee_buzz',this.x,this.y);
+ }else{
+ this.move='stingers';this.volleyLeft=this.expert?12:8;this.volleyTimer=.7/this.pace.aggr;this.hoverT=0;
+ this.go(c,'recover',0,'stingers');
+ }
+ };
+ P.spawnBee=function(c){
+ var big=this.expert&&c.rng.chance(.3),hp=big?24:this.expert?12:10,dmg=TR.paceDmg(this,big?24:this.expert?18:15);
+ var a=c.rng.uniform(0,Math.PI*2);
+ this.minions.push({id:++this.nextId,kind:big?'big_bee':'bee',x:this.x,y:this.y-H*.3,vx:TR.cos(a)*3,vy:TR.sin(a)*3,
+ w:big?.6:.45,h:big?.6:.45,hp:hp,max_hp:hp,dmg:dmg,defense:big?5:2,knockbackResist:.5,floating:true,drop:'heart_star',
+ debuff:this.expert?'poisoned':null,debuffChance:1,debuffDuration:[2,6],life:12});
+ c.emit('bee_spawn',this.x,this.y);
+ };
+ P.fireStinger=function(c){
+ var b=c.body.centre(),dx=b.x-this.x,dy=b.y-(this.y-H*.35),u=TR.dir(dx,dy,c.rng.uniform(-.06,.06)),speed=(this.expert?15:12)*TR.PX*this.pace.speed;
+ this.shots.push({id:++this.nextId,kind:'bee_stinger',x:this.x,y:this.y-H*.35,vx:u.x*speed,vy:u.y*speed,speed:speed,
+ r:.16,life:4,dmg:this.stingerDmg,solidCollision:true,collidePlatforms:false,
+ debuff:'poisoned',debuffChance:this.expert?1:1/3,debuffDuration:this.expert?[2,20]:[10,10]});
+ c.emit('bee_stinger',this.x,this.y);
+ };
+ P.updateBees=function(c,b){
+ var dt=BB.DT,self=this;
+ this.minions=this.minions.filter(function(m){
+ if(m.hp<=0){if(TR.dropMinion)TR.dropMinion(c,self,m);return false;}
+ m.life-=dt;if(m.life<=0)return false;
+ // Bees home in with a little wobble; they stay inside the arena.
+ var wob=TR.sin((c.t+m.id*17)*.15)*.8;
+ TR.moveToward(m,b.x+wob,b.y+.3,(m.kind==='big_bee'?6:7.5)*self.pace.speed,14);return true;
+ });
+ };
+ P.update=function(c){
+ if(this.st==='dead')return;this.clock(c);var dt=BB.DT,b=c.body.centre(),self=this;
+ this.updateArmor();
+ if(this.move==='charge'){
+ var sp=this.chargeSpeed(),edge=BB.ARENA.W-this.w/2;
+ if(this.st==='antic'){
+ // Line up beside the player at the player's height, then commit to a horizontal dash. Once lined up she
+ // locks that height and hangs for a beat (the readable windup) before charging along exactly that lane, so
+ // the pause shows the lane the hitbox will travel (r6 round 3: re-tracking a flying player during the hold
+ // kept resetting it, the charge came on the 2.56 s timeout instead and easy fights spread over 22-34 s).
+ var tx=BB.clamp(b.x+this.side*9,this.w/2,edge),ty=BB.clamp(b.y,this.h/2,BB.ARENA.H-this.h/2);
+ if(this.hold>0){
+ this.vx*=.8;this.vy=0;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,edge);this.y=this.lockY;this.hold+=dt;
+ }else{
+ TR.moveToward(this,tx,ty,(16+6*this.rage())*TR.PX*this.pace.speed,60*this.pace.aggr);
+ this.align+=dt;
+ if(Math.abs(this.y-ty)<.45&&Math.abs(this.x-tx)<2.2){this.hold=dt;this.lockY=this.y;this.vy=0;}
+ }
+ if(this.hold>=this.windup()||this.align>1.6/this.pace.aggr+this.windup()){
+ this.hold=0;this.f=b.x>=this.x?1:-1;this.vx=this.f*sp;this.vy=0;this.lockY=this.y;this.go(c,'attack',0,'charge');c.emit('queen_bee_charge',this.x,this.y);
+ }
+ }else if(this.st==='attack'){
+ this.x+=this.vx*dt;this.y=this.lockY;
+ // A charge ends past the player (or at the wall); she brakes and turns for the next one.
+ var past=this.f>0?this.x>b.x+6:this.x=edge){
+ this.x=BB.clamp(this.x,this.w/2,edge);this.chargesLeft--;this.vx*=.3;
+ if(this.chargesLeft>0){this.side=this.f;this.go(c,'recover',(this.expert?.18:.3)/this.pace.aggr,'charge');}
+ else{this.go(c,'recover',.5/this.pace.aggr,'charge_end');}
+ }
+ }else if(this.st==='recover'){
+ this.vx*=.85;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,edge);
+ if(this.timer<=0){if(this.move==='charge'){this.f=b.x>=this.x?1:-1;this.go(c,'antic',0,'charge');this.align=0;}}
+ }
+ }else if(this.move==='charge_end'){
+ this.vx*=.85;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2);
+ if(this.timer<=0)this.nextAttack(c);
+ }else if(this.move==='summon'){
+ // Hover above the player and release the batch over time.
+ TR.moveToward(this,b.x,Math.min(BB.ARENA.H-this.h/2,b.y+6),7*TR.PX*this.pace.speed,8);
+ this.hoverT+=dt;this.spawnTimer-=dt;
+ if(this.beesLeft>0&&this.spawnTimer<=0){this.spawnBee(c);this.beesLeft--;this.spawnTimer=(this.expert?.16:.22)/this.pace.aggr;}
+ if(this.beesLeft<=0&&this.hoverT>.6)this.nextAttack(c);
+ }else if(this.move==='stingers'){
+ // Hornet-like: drift above and to the side of the player and fire stingers down at them.
+ this.hoverT+=dt;var sway=TR.sin(this.hoverT*1.4)*6;
+ TR.moveToward(this,BB.clamp(b.x+sway,this.w/2,BB.ARENA.W-this.w/2),Math.min(BB.ARENA.H-this.h/2,b.y+5.5),9*TR.PX*this.pace.speed,10);
+ this.volleyTimer-=dt;
+ if(this.volleyTimer<=0&&this.volleyLeft>0){this.fireStinger(c);this.volleyLeft--;this.volleyTimer=(this.expert?.32-.12*this.rage():.45)/this.pace.aggr;}
+ if(this.volleyLeft<=0&&this.volleyTimer<=-.4)this.nextAttack(c);
+ }
+ this.updateBees(c,b);
+ };
+ P.onNailHit=function(c,base,dir,f,id){this.updateArmor();return TR.damageBoss(this,c,base,id);};
+ P.hazards=function(){
+ if(this.st==='dead')return [];
+ var body={kind:this.move==='charge'&&this.st==='attack'?'queen_bee_charge':'queen_bee',box:this.bodyBox(),dmg:this.dmg,fromX:this.x};
+ if(this.expert){body.debuff='poisoned';body.debuffChance=1;body.debuffDuration=[2,8];}
+ return [body].concat(TR.extraHazards(this));
+ };
+ BB.CASES['terraria/queen_bee'] = TR.register('queen_bee','Charging Giant Bee',QueenBee,'hive');
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/bosses/skeletron.js b/environments/games/web/games/terraria_remake/bosses/skeletron.js
new file mode 100644
index 0000000000000000000000000000000000000000..e8724b06a2948ac71a77fd9e9b1e60d3f76d0680
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/bosses/skeletron.js
@@ -0,0 +1,110 @@
+(function(g){
+ var BB=g.BB,TR=BB.TR,S=BB.SPECS.skeletron;
+ function Skeletron(){}
+ var P=Skeletron.prototype;TR.boss(P,S);
+ P.reset=function(c){
+ this.setup(c,18,10.5,80/32,102/32);this.expert=this.k.expert>=0.5;this.easyScale=1;
+ this.hp=this.max_hp=TR.paceHp(this,this.expert?8800:4400);this.dmg=TR.paceDmg(this,this.expert?70:32);
+ this.k.hp=this.max_hp;this.k.dmg=this.dmg;this.k.def_factor=this.expert?0.75:0.5;
+ this.k.hand_hp=TR.paceHp(this,this.expert?1560:600);this.skullTimer=80/60;this.skullFrames=0;this.headFrames=0;
+ this.handIndex=0;this.enraged=false;this.spinSpeed=0;
+ // Tier aggression stretches the hover / hand cadences and scales chase and hand speeds (tiers.js).
+ this.hoverFrames=Math.round(800/this.pace.aggr);this.handGap=Math.round((this.expert?200:300)/this.pace.aggr);
+ var offset=Math.round((this.expert?100:150)/this.pace.aggr);
+ this.hands=[-1,1].map(function(side,n){return {id:'hand'+n,side:side,x:18+side*3,y:7.8,vx:0,vy:0,
+ w:52/32,h:52/32,hp:this.k.hand_hp,max_hp:this.k.hand_hp,defense:14,st:'idle',timer:0,
+ wait:n*offset/60,waitFrames:n*offset,attackIndex:n,target:{x:0,y:0}};},this);
+ this.go(c,'idle',this.hoverFrames/60);this.defense=this.armor();
+ };
+ P.hitTargets=function(){return [{id:'head',box:this.bodyBox()}].concat(this.hands.filter(function(h){return h.hp>0;})
+ .map(function(h){return {id:h.id,box:TR.box(h)};}));};
+ P.armor=function(){return this.enraged?9999:(this.st==='attack'?0:10)+
+ (this.expert?this.hands.filter(function(h){return h.hp>0;}).length*25:0);};
+ P.onNailHit=function(c,base,dir,f,id){
+ if(this.hp<=0)return null;var hand=this.hands.find(function(h){return h.id===id;});
+ if(hand){
+ if(hand.hp<=0)return null;
+ var hit=TR.rollDetails(c,base,14,0.5,0.04);hand.hp=Math.max(0,hand.hp-hit.damage);TR.emitHit(c,'boss_hit',hand.x,hand.y,hit.damage,hit.critical);
+ if(!hand.hp)c.emit('hand_destroyed',hand.x,hand.y);this.defense=this.armor();return 'flesh';
+ }
+ this.defense=this.armor();return TR.damageBoss(this,c,base,id);
+ };
+ P.chaseSpeed=function(b){
+ var alive=this.hands.filter(function(h){return h.hp>0;}).length,speed=2*TR.PX*this.pace.speed;
+ if(this.expert){
+ speed*=10/3;speed*=1+(2-alive)*0.05;
+ var tiles=Math.hypot(this.x-b.x,this.y-b.y)/TR.TILE;
+ if(tiles>=9.375)speed*=Math.min(2.6,Math.pow(1.1,Math.floor((tiles-9.375)/3.125)+1));
+ }return speed;
+ };
+ P.spawnSkull=function(c){
+ TR.shoot(this,c,this.x,this.y,3*TR.PX,'homing_skull',true);
+ var p=this.shots[this.shots.length-1];p.dmg=TR.paceDmg(this,68);p.solidCollision=true;p.collidePlatforms=false;p.life=10;
+ };
+ P.beginHand=function(c,h,b){
+ h.attackIndex++;h.attackAxis=h.attackIndex%2?'vertical':'horizontal';
+ h.target={x:b.x,y:b.y};h.st='antic';h.timer=0;
+ c.emit(h.attackAxis==='vertical'?'hand_vertical_antic':'hand_horizontal_antic',h.x,h.y);
+ };
+ P.updateHand=function(c,h,b){
+ if(h.hp<=0)return;var dt=BB.DT,speedMul=(this.expert?1.16:1)*this.pace.speed;h.timer-=dt;
+ if(this.st==='attack'){
+ h.st='idle';TR.moveToward(h,this.x+h.side*3.2,this.y-2.8,(this.expert?8:5)*TR.PX*this.pace.speed,35);return;
+ }
+ if(h.st==='idle'){
+ h.waitFrames++;h.wait=h.waitFrames/60;TR.moveToward(h,this.x+h.side*3.2,this.y-2.8,(this.expert?8:5)*TR.PX*this.pace.speed,25);
+ if(h.waitFrames>=this.handGap){h.wait=0;h.waitFrames=0;this.beginHand(c,h,b);}
+ }else if(h.st==='antic'){
+ // Preparation is physical alignment, not an added stationary telegraph timer.
+ var ax=h.attackAxis==='vertical'?b.x:BB.clamp(this.x+h.side*6,h.w/2,BB.ARENA.W-h.w/2);
+ var ay=h.attackAxis==='vertical'?Math.min(BB.ARENA.H-h.h/2,this.y+2):b.y;
+ TR.moveToward(h,ax,ay,9*TR.PX*speedMul,40);
+ if(Math.hypot(ax-h.x,ay-h.y)<0.6){
+ h.target={x:b.x,y:b.y};h.st='attack';h.timer=0.7;
+ if(h.attackAxis==='vertical'){
+ h.vx=BB.clamp((b.x-h.x)/Math.max(0.15,Math.abs(b.y-h.y)/(15*TR.PX*speedMul)),-16*TR.PX*speedMul,16*TR.PX*speedMul);
+ h.vy=-15*TR.PX*speedMul;
+ }else{h.vx=(b.x=BB.ARENA.W-h.w/2))h.st='return';
+ }else if(h.st==='return'){
+ var rx=BB.clamp(this.x+h.side*3.2,h.w/2,BB.ARENA.W-h.w/2),ry=BB.clamp(this.y-2.8,h.h/2,BB.ARENA.H-h.h/2);
+ TR.moveToward(h,rx,ry,(this.expert?12:8)*TR.PX*this.pace.speed,40);
+ if(Math.hypot(h.x-rx,h.y-ry)<1)h.st='idle';
+ }
+ };
+ P.update=function(c){
+ if(this.st==='dead')return;this.clock(c);var b=c.body.centre(),alive=this.hands.filter(function(h){return h.hp>0;});
+ // Starting at 19:30, dawn is nine real-time minutes later. The finite benchmark may end first.
+ if((TR.isDaytime?TR.isDaytime(c):c.t>=9*60*60)&&!this.enraged){this.enraged=true;this.go(c,'attack',1e9,'spin');c.emit('skeletron_day_enrage',this.x,this.y);}
+ if(this.st==='idle'){
+ this.headFrames++;
+ TR.moveToward(this,b.x,Math.min(BB.ARENA.H-this.h/2,b.y+250/32),(this.expert?4:2)*TR.PX*this.pace.speed,this.expert?15:6);
+ if(this.expert&&(alive.length<2||this.hp/this.max_hp<0.75)){
+ this.skullFrames++;this.skullTimer=((alive.length===0?40:80)-this.skullFrames)/60;
+ if(this.skullFrames>=(alive.length===0?40:80)){this.spawnSkull(c);this.skullFrames=0;this.skullTimer=(alive.length===0?40:80)/60;}
+ }
+ if(this.headFrames>=this.hoverFrames){this.headFrames=0;this.go(c,'attack',400/60,'spin');c.emit('skeletron_roar',this.x,this.y);}
+ }else if(this.st==='attack'){
+ this.headFrames++;
+ this.spinSpeed=this.enraged?20*TR.PX:this.chaseSpeed(b);
+ TR.moveToward(this,b.x,b.y,this.spinSpeed,this.enraged?100:60);
+ if(!this.enraged&&this.headFrames>=400){this.headFrames=0;this.go(c,'idle',this.hoverFrames/60);this.move=null;}
+ }
+ this.hands.forEach(function(h){this.updateHand(c,h,b);},this);this.defense=this.armor();
+ };
+ P.hazards=function(){
+ if(this.st==='dead')return [];
+ var head={kind:this.st==='attack'?'skull_spin':'skull',box:this.bodyBox(),fromX:this.x,
+ dmg:this.enraged?9999:TR.paceDmg(this,this.expert?(this.st==='attack'?91:70):32)};
+ if(this.expert){head.debuff='bleeding';head.debuffChance=1;head.debuffDuration=[12,20];}
+ return [head].concat(this.hands.filter(function(h){return h.hp>0;}).map(function(h){
+ var hit={kind:'hand',box:TR.box(h),dmg:TR.paceDmg(this,this.expert?44:20),fromX:h.x};
+ if(this.expert){hit.debuff='slow';hit.debuffChance=0.5;hit.debuffDuration=[1,2];}return hit;
+ },this),TR.extraHazards(this));
+ };
+ BB.CASES['terraria/skeletron'] = TR.register('skeletron','Twin-Handed Giant Skull',Skeletron,'dungeon');
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/draw/adventurer.js b/environments/games/web/games/terraria_remake/draw/adventurer.js
new file mode 100644
index 0000000000000000000000000000000000000000..c5a70146be97f360b5c53da592cf8229117208ec
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/draw/adventurer.js
@@ -0,0 +1,133 @@
+(function(g){
+ var BB=g.BB,D=BB.TR.DRAW,TAU=Math.PI*2;
+ // Original procedural adventurer: hair, tunic, belt, boots; legs follow the simulated run speed, the cape
+ // follows velocity, wings appear only while flying/gliding (the simulated state), the sword arc is the hitbox.
+ function limb(x,ax,ay,bx,by,w,col){x.lineCap='round';x.lineWidth=w;x.strokeStyle=col;x.beginPath();x.moveTo(ax,ay);x.lineTo(bx,by);x.stroke();}
+ function figure(x,b,V,t){
+ var f=b.facing<0?-1:1,s=V.S,run=Math.abs(b.vx)/11.25,air=!b.grounded;
+ var cx=V.sx(b.x),fy=V.sy(b.y),H=1.3125*s,ph=b.x*2.2;
+ x.save();x.translate(cx,fy);x.scale(f,1);
+ var hip=-H*.42,sw=air?.5:Math.sin(ph)*Math.min(1,run*1.4)*.75;
+ // cape
+ x.fillStyle='#5a2f63';x.beginPath();x.moveTo(-s*.12,-H*.78);x.quadraticCurveTo(-s*.4-run*s*.2,-H*.5,-s*.32-run*s*.35,-H*.22+(air?-s*.1:0));x.lineTo(-s*.05,-H*.3);x.closePath();x.fill();
+ // legs
+ limb(x,-s*.05,hip,-s*.05+Math.sin(sw)*s*.22,-s*.04,s*.15,'#3a4e66');
+ limb(x,s*.06,hip,s*.06-Math.sin(sw)*s*.22,-s*.04,s*.15,'#455d79');
+ x.fillStyle='#3a2a20';x.fillRect(-s*.05+Math.sin(sw)*s*.22-s*.08,-s*.08,s*.2,s*.08);x.fillRect(s*.06-Math.sin(sw)*s*.22-s*.08,-s*.08,s*.2,s*.08);
+ // torso
+ x.fillStyle='#b5482f';x.beginPath();x.moveTo(-s*.17,-H*.78);x.lineTo(s*.17,-H*.78);x.lineTo(s*.2,hip);x.lineTo(-s*.2,hip);x.closePath();x.fill();
+ x.fillStyle='#e8c25e';x.fillRect(-s*.2,hip-s*.06,s*.4,s*.06);
+ x.strokeStyle='#4a1d12';x.lineWidth=1.2;x.strokeRect(-s*.17,-H*.78,s*.34,H*.36);
+ // head
+ x.fillStyle='#efc39b';x.beginPath();x.arc(s*.02,-H*.88,s*.17,0,TAU);x.fill();
+ x.fillStyle='#5b3a24';x.beginPath();x.arc(-s*.02,-H*.93,s*.18,Math.PI*.9,Math.PI*2.05);x.fill();x.fillRect(-s*.2,-H*.93,s*.1,s*.16);
+ x.fillStyle='#1c2430';x.fillRect(s*.09,-H*.9,s*.05,s*.05);
+ x.restore();
+ }
+ function wings(x,b,V,t){
+ var cx=V.sx(b.x),cy=V.sy(b.y+.9),flap=b.flying?Math.sin(t*28)*.5:.25;
+ [-1,1].forEach(function(k){x.save();x.translate(cx,cy);x.scale(k,1);x.rotate(-.3-flap);
+ for(var i=0;i<4;i++){x.fillStyle=i%2?'#d9e6ee':'#b9cbd8';x.beginPath();x.ellipse(-12-i*5,-4+i*3,12-i*1.5,4,-.5+i*.18,0,TAU);x.fill();}
+ x.restore();});
+ }
+ function weapon(x,b,V,center){
+ var a=b.atkT>0?b.slashAngle:Math.atan2(b.aimY-center.y,b.aimX-center.x);
+ x.save();x.translate(V.sx(b.x),V.sy(center.y));x.rotate(-a);
+ if(b.atkT>0||b.weapon==='sword'){
+ x.fillStyle='#8b6a3e';x.fillRect(2,-2,8,4);x.fillStyle='#e9c35a';x.fillRect(9,-7,4,14);
+ x.fillStyle='#d6ecf0';x.beginPath();x.moveTo(13,-3);x.lineTo(13+V.S*2.0,-2);x.lineTo(16+V.S*2.05,0);x.lineTo(13+V.S*2.0,2);x.lineTo(13,3);x.closePath();x.fill();
+ x.strokeStyle='#5d7a86';x.lineWidth=1;x.stroke();
+ }else{
+ x.strokeStyle='#7b4f2c';x.lineWidth=3;x.beginPath();x.arc(4,0,13,-1.15,1.15);x.stroke();
+ x.strokeStyle='#efe6cf';x.lineWidth=1;x.beginPath();x.moveTo(4+13*Math.cos(-1.15),13*Math.sin(-1.15));x.lineTo(4+13*Math.cos(1.15),13*Math.sin(1.15));x.stroke();
+ }
+ x.restore();
+ }
+ function crosshair(x,V,b){
+ var ax=V.sx(b.aimX),ay=V.sy(b.aimY);x.save();x.strokeStyle='rgba(20,20,20,.6)';x.lineWidth=3;
+ x.beginPath();x.arc(ax,ay,6,0,TAU);x.stroke();x.strokeStyle='#fff0b8';x.lineWidth=1.5;x.beginPath();x.arc(ax,ay,6,0,TAU);x.moveTo(ax-11,ay);x.lineTo(ax-7,ay);x.moveTo(ax+7,ay);x.lineTo(ax+11,ay);x.moveTo(ax,ay-11);x.lineTo(ax,ay-7);x.moveTo(ax,ay+7);x.lineTo(ax,ay+11);x.stroke();x.restore();
+ }
+ // Floating combat text from the case's own events (amounts are presentation-only payloads); stateless.
+ function combatText(x,c,V){
+ var ev=c.events;x.save();x.textAlign='center';x.font='bold 13px "Segoe UI",sans-serif';
+ for(var i=ev.length-1,n=0;i>=0&&n<24;i--){var e=ev[i];if(e.t=12;
+ return (h%12||12)+':'+(m<10?'0':'')+m+(pm?' PM':' AM');
+ }
+ BB.BODY_DRAW.terraria_adventurer={
+ draw:function(x,c,t,V){
+ var b=c.body,center=b.centre();
+ D.shadow(x,V,b.x,b.y,.7,c);
+ if(b.hp<=0){ // Terraria leaves a tombstone where the player died
+ var gx=V.sx(b.x),gy=V.sy(b.y);x.save();x.fillStyle='#8d949a';x.strokeStyle='#2c3036';x.lineWidth=2;
+ x.beginPath();x.moveTo(gx-11,gy);x.lineTo(gx-11,gy-22);x.arc(gx,gy-22,11,Math.PI,0);x.lineTo(gx+11,gy);x.closePath();x.fill();x.stroke();
+ x.fillStyle='#3b4148';x.fillRect(gx-1.5,gy-26,3,14);x.fillRect(gx-6,gy-22,12,3);x.restore();combatText(x,c,V);return;}
+ x.save();if(b.invul>0&&Math.floor(t*18)%2)x.globalAlpha=0.45;
+ if(b.flying||b.gliding)wings(x,b,V,t);
+ figure(x,b,V,t);weapon(x,b,V,center);x.restore();
+ b.arrows.forEach(function(p){
+ x.save();x.translate(V.sx(p.x),V.sy(p.y));x.rotate(-Math.atan2(p.vy,p.vx));x.fillStyle='rgba(255,240,200,.25)';x.fillRect(-20,-1,12,2);
+ x.fillStyle='#d9c08a';x.fillRect(-9,-1,16,2);x.fillStyle='#e9f7ee';x.beginPath();x.moveTo(11,0);x.lineTo(6,-3);x.lineTo(6,3);x.fill();x.fillStyle='#c0644a';x.fillRect(-10,-3,4,2);x.fillRect(-10,1,4,2);x.restore();
+ });
+ var slash=b.slashBox();
+ if(slash){x.save();x.globalCompositeOperation='lighter';x.fillStyle='rgba(255,226,150,.35)';x.beginPath();
+ slash.pts.forEach(function(p,n){if(n)x.lineTo(V.sx(p[0]),V.sy(p[1]));else x.moveTo(V.sx(p[0]),V.sy(p[1]));});x.closePath();x.fill();x.restore();}
+ crosshair(x,V,b);
+ combatText(x,c,V);
+ },
+ fullHud:function(x,c,V,extra){
+ var b=c.body,w=c.boss,dr=BB.BOSS_DRAW[c.id]||{},W=V.W;
+ x.save();x.textBaseline='alphabetic';
+ // player panel (top left)
+ panel(x,10,8,250,62);
+ x.font='bold 12px "Segoe UI",sans-serif';x.fillStyle='#ffd7cf';x.fillText('Health '+b.hp+' / '+b.max_hp,18,24);
+ bar(x,18,29,150,8,b.hp/b.max_hp,b.hp/b.max_hp<.3?'#ff4a4a':'#e2453b','#3b1518');
+ x.fillStyle='#bfe6f5';x.font='11px "Segoe UI",sans-serif';x.fillText('Flight',18,52);bar(x,46,45,122,5,b.flight/1.5,'#7fd0ec','#173040');
+ x.fillStyle='#c9c4ff';x.fillText('Mana '+b.mana,18,65);bar(x,66,59,102,4,b.mana/b.max_mana,'#6f7cff','#1c1c46');
+ x.fillStyle='#f3e2b2';x.font='bold 12px "Segoe UI",sans-serif';x.fillText(b.weapon==='bow'?'Bow':'Sword',180,24);
+ x.font='10px "Segoe UI",sans-serif';x.fillStyle='#b8c6cc';x.fillText(b.flying?'Flying':b.gliding?'Gliding':b.grounded?'Grounded':'Airborne',180,38);
+ var st=[],NAMES={slow:'Slow',bleeding:'Bleeding',poisoned:'Poisoned',confused:'Confused',weak:'Weak',broken_armor:'Armor broken',cursed:'Cursed',darkness:'Darkness',silenced:'Silenced'};
+ Object.keys(NAMES).forEach(function(k){if(b.status[k]>0)st.push(NAMES[k]+' '+b.status[k].toFixed(1)+'s');});
+ if(st.length){x.fillStyle='#ffb36b';x.fillText(st.slice(0,2).join(' '),180,52);if(st.length>2)x.fillText(st.slice(2,4).join(' '),180,64);}
+ // boss panel (top right)
+ var bw=330,bx=W-bw-10;panel(x,bx,8,bw,48);
+ var title=String(c.def&&c.def.title||'Boss'),f=Math.max(0,w.hp/w.max_hp),col=dr.bar?dr.bar(w):'#d8c27a';
+ x.font='bold 13px Georgia,"Microsoft YaHei",serif';x.fillStyle='#f6e7c4';x.textAlign='left';x.fillText(title,bx+8,24);
+ x.textAlign='right';x.font='bold 12px "Segoe UI",sans-serif';x.fillStyle='#fff';x.fillText(w.hp+' / '+w.max_hp,bx+bw-8,24);
+ bar(x,bx+8,29,bw-16,9,f,col,'#26161a','rgba(240,220,170,.8)');
+ if(w.hands){var hx=bx+8;w.hands.forEach(function(h,i){bar(x,hx+i*((bw-16)/2+2),40,(bw-16)/2-2,3,h.hp/h.max_hp,'#cdbf9a','#2a2622');});}
+ x.textAlign='left';x.font='11px "Segoe UI","Microsoft YaHei",sans-serif';x.fillStyle='#d9e4e8';
+ x.fillText(dr.phase?dr.phase(w,!!BB.TR.showCues):'',bx+8,w.hands?54:52);
+ // centre column, between the two panels: public tier (or the source mode for a custom d) + timer, then the
+ // rules, native tick rate and in-game clock, then the label
+ var secs=c.t/BB.FPS,mm=Math.floor(secs/60),ss=Math.floor(secs%60),tier=w.pace&&w.pace.tier,cx=(260+bx)/2,
+ level=tier?BB.TR.TIER_NAMES[tier]:w.expert?'Expert Expert':'Custom d='+(+c.d).toFixed(2);
+ x.textAlign='center';x.font='bold 12px "Segoe UI","Microsoft YaHei",sans-serif';
+ x.fillStyle=w.expert?'#ff9d6b':tier==='hard'?'#ffc46b':tier==='easy'?'#a8e6b0':'#bfe3c6';
+ x.fillText(level+' · '+mm+':'+(ss<10?'0':'')+ss,cx,22);
+ x.font='11px "Segoe UI","Microsoft YaHei",sans-serif';x.fillStyle=BB.TR.isDaytime(c)?'#ffe48a':'#a9c1e8';
+ x.fillText((w.expert?'Expert rules':'Classic rules')+' · '+BB.FPS+' Hz · '+(BB.TR.isDaytime(c)?'Day ':'Night ')+clock(c),cx,37);
+ if(extra){x.font='bold 12px "Segoe UI","Microsoft YaHei",sans-serif';x.fillStyle='#ffe7a3';x.fillText(extra,cx,54);}
+ // The play page draws the final live frame once before its HTML result panel opens; that frame skips the
+ // banner so the two never overlap. Off-page renderers (RGB observations, harness video) keep it.
+ var onPage=!!(x.canvas&&x.canvas.id==='view'&&g.document&&g.document.getElementById('result'));
+ if(c.result&&!onPage){x.font='bold 30px Georgia,serif';x.fillStyle=c.result==='win'?'#ffe08a':'#ff8a7a';x.strokeStyle='rgba(0,0,0,.7)';x.lineWidth=4;
+ var word=c.result==='win'?'VICTORY':c.result==='loss'?'DEFEATED':'TIME UP';x.strokeText(word,W/2,V.H/2-40);x.fillText(word,W/2,V.H/2-40);}
+ x.restore();
+ }
+ };
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/draw/brain_of_cthulhu.js b/environments/games/web/games/terraria_remake/draw/brain_of_cthulhu.js
new file mode 100644
index 0000000000000000000000000000000000000000..b040ade5f283011f5db334f64e7e30d78c20de53
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/draw/brain_of_cthulhu.js
@@ -0,0 +1,64 @@
+(function(g){
+ var BB=g.BB,D=BB.TR.DRAW,TAU=Math.PI*2;
+ // Original art: a pink, folded brain with a dangling brain stem and a single eye; translucent and invulnerable
+ // in phase 1, it reveals a beating heart in phase 2. Creepers are veiny eyeballs with flesh tendrils.
+ // Expert illusions are the same drawing at the illusion opacity; only the real brain flashes when hit.
+ function brain(x,V,w,cx,cy,t,alpha,flash,phase){
+ var s=w.w*V.S,pulse=1+Math.sin(t*(phase===2?9:3))*.03;
+ x.save();x.globalAlpha=alpha;x.translate(cx,cy);x.scale(pulse,pulse);
+ // stem
+ x.strokeStyle='#8a3040';x.lineWidth=s*.08;x.beginPath();x.moveTo(0,s*.25);x.quadraticCurveTo(s*.08+Math.sin(t*2)*s*.05,s*.42,-s*.04,s*.55);x.stroke();
+ // lobes
+ x.fillStyle=D.lit(flash,phase===2?'#e58c98':'#d98a9c');x.beginPath();x.ellipse(0,0,s*.5,s*.36,0,0,TAU);x.fill();
+ x.strokeStyle='#6a1f2c';x.lineWidth=2;x.stroke();
+ x.strokeStyle='rgba(120,30,50,.7)';x.lineWidth=1.6;
+ for(var k=0;k<6;k++){var yy=-s*.28+k*s*.11;x.beginPath();x.moveTo(-s*.45,yy);
+ for(var j=0;j<6;j++)x.quadraticCurveTo(-s*.4+j*s*.16,yy+((j+k)%2?-1:1)*s*.06,-s*.32+j*s*.16,yy);x.stroke();}
+ x.strokeStyle='#6a1f2c';x.lineWidth=2;x.beginPath();x.moveTo(0,-s*.35);x.quadraticCurveTo(s*.04,0,0,s*.3);x.stroke();
+ if(phase===2){
+ // the exposed heart
+ var hb=1+Math.max(0,Math.sin(t*9))*.18;x.save();x.translate(0,s*.12);x.scale(hb,hb);
+ x.fillStyle='#b8202e';x.beginPath();x.moveTo(0,s*.12);x.bezierCurveTo(-s*.2,-s*.02,-s*.1,-s*.18,0,-s*.07);x.bezierCurveTo(s*.1,-s*.18,s*.2,-s*.02,0,s*.12);x.fill();
+ x.strokeStyle='#4a0810';x.lineWidth=1.5;x.stroke();x.restore();
+ }else{
+ x.fillStyle='#f2e4d6';x.beginPath();x.arc(s*.18,-s*.02,s*.11,0,TAU);x.fill();
+ x.fillStyle='#7a1a2a';x.beginPath();x.arc(s*.21,-s*.02,s*.05,0,TAU);x.fill();
+ }
+ x.restore();
+ }
+ function creeper(x,V,m,t){
+ var cx=V.sx(m.x),cy=V.sy(m.y),r=m.w*V.S*.5,a=m.st==='charge'?Math.atan2(-m.vy,m.vx):Math.sin(t*2+m.id);
+ x.save();x.translate(cx,cy);x.rotate(a);
+ x.strokeStyle='#7a2232';x.lineWidth=2;
+ for(var k=-1;k<=1;k++){x.beginPath();x.moveTo(-r*.7,k*r*.3);x.quadraticCurveTo(-r*1.5,k*r*.6+Math.sin(t*12+k+m.id)*3,-r*2,k*r*.9);x.stroke();}
+ x.fillStyle=m.hitT>0?'#fff':'#c9505e';x.beginPath();x.arc(0,0,r,0,TAU);x.fill();x.strokeStyle='#4a1020';x.lineWidth=1.5;x.stroke();
+ // health ring: a Creeper the player has hit shows how much is left (the source game draws per-NPC bars)
+ if(m.hp0)creeper(x,V,m,t);});
+ (w.pickups||[]).length&&D.extras(x,{boss:{minions:[],shots:[],pickups:w.pickups}},t,V);
+ },body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return;
+ // Expert illusions first (behind), the real brain on top. A fading (teleporting) brain is drawn at its fade.
+ if(w.phase===2&&w.illusions&&w.illusions.length){
+ w.illusions.forEach(function(p){brain(x,V,w,V.sx(p.x),V.sy(p.y),t,w.illusionAlpha*w.fade,false,2);});
+ }
+ var alpha=(w.phase===1?.55:1)*Math.max(.15,w.fade);
+ brain(x,V,w,V.sx(w.x),V.sy(w.y),t,alpha,w.hitFlash>0,w.phase);
+ },bar:function(w){return w.phase===2?'#d0454f':'#d98a9c';},
+ phase:function(w){
+ var alive=w.minions.filter(function(m){return m.kind==='creeper'&&m.hp>0;});
+ if(w.phase===1){
+ // The HUD bar is the brain + Creeper total; spell out where the remaining health sits.
+ var creepers=alive.reduce(function(a,m){return a+m.hp;},0);
+ return 'Phase 1 · core invulnerable · guard eyes '+alive.length+'/20 ('+creepers+')· core '+w.brainHp;
+ }
+ return 'Phase 2 · core '+w.brainHp+'/'+w.brainMax+(w.expert?' · clones':'');
+ }};
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/draw/eater_of_worlds.js b/environments/games/web/games/terraria_remake/draw/eater_of_worlds.js
new file mode 100644
index 0000000000000000000000000000000000000000..1803f53cdcf1b9b0e0a7447e5b30cc582e3bb48d
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/draw/eater_of_worlds.js
@@ -0,0 +1,47 @@
+(function(g){
+ var BB=g.BB,D=BB.TR.DRAW;
+ var TAU=Math.PI*2;
+ // Original art: armoured corrupt segments, a head with mandibles and a spiked tail. Each segment faces the
+ // segment in front of it; coiled (not yet visible) and underground segments are not drawn.
+ function segment(x,s,len,flash,t){
+ var r=len*.5;
+ if(s.type==='tail'){
+ x.beginPath();x.moveTo(r*.9,-r*.75);x.quadraticCurveTo(-r*.2,-r*.7,-r*1.3,0);x.quadraticCurveTo(-r*.2,r*.7,r*.9,r*.75);x.closePath();
+ x.fillStyle=D.lit(flash,'#6d4f7d');x.fill();x.lineWidth=2;x.strokeStyle='#22162b';x.stroke();
+ x.strokeStyle='#a27fb3';x.lineWidth=1.5;x.beginPath();x.moveTo(r*.5,-r*.45);x.quadraticCurveTo(-r*.1,0,r*.5,r*.45);x.stroke();return;
+ }
+ x.beginPath();x.ellipse(0,0,r*1.02,r*.92,0,0,TAU);x.fillStyle=D.lit(flash,s.type==='head'?'#7a5a8c':'#6d4f7d');x.fill();
+ x.lineWidth=2;x.strokeStyle='#22162b';x.stroke();
+ x.fillStyle='rgba(190,160,205,.55)';x.beginPath();x.ellipse(0,-r*.35,r*.75,r*.3,0,0,TAU);x.fill();
+ x.strokeStyle='#3a2647';x.lineWidth=1.5;x.beginPath();x.moveTo(-r*.25,-r*.88);x.quadraticCurveTo(-r*.45,0,-r*.25,r*.88);x.stroke();
+ x.beginPath();x.moveTo(r*.3,-r*.86);x.quadraticCurveTo(r*.1,0,r*.3,r*.86);x.stroke();
+ if(s.type==='head'){
+ var bite=Math.sin(t*9)*.18;
+ [-1,1].forEach(function(k){
+ x.save();x.translate(r*.75,k*r*.45);x.rotate(k*(.35+bite));
+ x.beginPath();x.moveTo(0,-r*.16*k);x.quadraticCurveTo(r*.75,-r*.1*k,r*.95,r*.25*k);x.quadraticCurveTo(r*.55,r*.08*k,0,r*.18*k);x.closePath();
+ x.fillStyle='#d9cc9b';x.fill();x.lineWidth=1.5;x.strokeStyle='#2a1f12';x.stroke();x.restore();
+ });
+ x.fillStyle='#f2e27a';[-1,1].forEach(function(k){x.beginPath();x.arc(r*.42,k*r*.42,r*.11,0,TAU);x.fill();});
+ x.fillStyle='#2a1030';x.beginPath();x.ellipse(r*.86,0,r*.14,r*.22,0,0,TAU);x.fill();
+ }
+ }
+ BB.BOSS_DRAW['terraria/eater_of_worlds']={hazards:D.extras,body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return;
+ var lookup={},fronts={};w.segments.forEach(function(s){lookup[s.id]=s;});
+ w.chains.forEach(function(ch){for(var i=1;i0;
+ w.segments.slice().reverse().forEach(function(s){if(s.hp<=0||s.visible===false||s.y<=-s.h/2)return;
+ var front=fronts[s.id],dx=front?front.x-s.x:s.vx||0,dy=front?front.y-s.y:s.vy||0;
+ x.save();x.translate(V.sx(s.x),V.sy(s.y));x.rotate(-Math.atan2(dy,dx||1e-6));
+ segment(x,s,s.w*V.S,flash,t);x.restore();
+ });
+ // dirt bursts where a head is digging just below the surface (presentation only)
+ w.chains.forEach(function(ch){var h=lookup[ch.ids[0]];if(!h||h.y>.4||h.y<-2.5)return;
+ x.fillStyle='rgba(98,71,53,.8)';for(var k=0;k<5;k++){var px=V.sx(h.x)+Math.sin(t*13+k*2.3)*14,py=V.sy(0)-Math.abs(Math.sin(t*9+k))*10;x.fillRect(px,py,3,3);}});
+ },bar:function(){return '#b07fc4';},
+ phase:function(w){
+ var alive=w.segments.filter(function(s){return s.hp>0;}).length;
+ return w.chains.length+' worms · '+alive+' segments alive';
+ }};
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/draw/eye_of_cthulhu.js b/environments/games/web/games/terraria_remake/draw/eye_of_cthulhu.js
new file mode 100644
index 0000000000000000000000000000000000000000..0b2d27e95aa12615958d93ca305531f61a3dd700
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/draw/eye_of_cthulhu.js
@@ -0,0 +1,52 @@
+(function(g){
+ var BB=g.BB,D=BB.TR.DRAW;
+ var TAU=Math.PI*2;
+ // Original art: an eyeball with trailing nerve tendrils; the second form shows a toothed maw.
+ // Orientation follows the simulated charge velocity, the transform spin, or the player while hovering.
+ BB.BOSS_DRAW['terraria/eye_of_cthulhu']={hazards:function(x,c,t,V){
+ var w=c.boss;if(w.st==='antic')D.cue(x,V,w,w.target,'#f39783');D.extras(x,c,t,V);
+ },body:function(x,c,t,V){var w=c.boss;if(w.st==='dead'||w.despawned)return;
+ var b=c.body.centre(),a;
+ if(w.st==='transform')a=w.rotation;
+ else if(w.st==='attack'||w.dawnDeparting)a=Math.atan2(-(w.vy||0),w.vx||1e-6);
+ else a=Math.atan2(-(b.y-w.y),b.x-w.x);
+ var r=w.w*V.S*.5,flash=w.hitFlash>0,phase2=w.phase===2;
+ x.save();x.translate(V.sx(w.x),V.sy(w.y));x.rotate(a);
+ // tendrils trail behind the eye
+ var wig=w.st==='attack'?2:5;
+ for(var k=0;k<5;k++){
+ var off=(k-2)*r*.22,len=r*(1.25+.18*(k%3)),ph=t*(w.st==='attack'?16:7)+k*1.7;
+ x.beginPath();x.moveTo(-r*.8,off*.8);
+ x.bezierCurveTo(-r-len*.35,off+Math.sin(ph)*wig,-r-len*.7,off*1.3-Math.sin(ph+1)*wig*1.5,-r-len,off*1.6+Math.sin(ph+2)*wig*2);
+ x.lineWidth=Math.max(2,r*.13)*(1-k%2*.3);x.strokeStyle='#7c1f2c';x.stroke();
+ x.lineWidth=Math.max(1,r*.05);x.strokeStyle='#c4485a';x.stroke();
+ }
+ // sclera
+ x.beginPath();x.arc(0,0,r,0,TAU);x.fillStyle=D.lit(flash,phase2?'#e2c3b2':'#efe3d3');x.fill();
+ x.lineWidth=2.5;x.strokeStyle='#4a1a22';x.stroke();
+ // veins
+ x.strokeStyle='rgba(184,40,58,.75)';x.lineWidth=1.3;
+ for(var v=0;v<7;v++){var va=Math.PI*.55+v*.27,vx=Math.cos(va)*r*.95,vy=Math.sin(va)*r*.95;
+ x.beginPath();x.moveTo(vx,vy);x.quadraticCurveTo(vx*.65+Math.sin(v*3.1)*4,vy*.65,vx*.42,vy*.42+Math.cos(v)*3);x.stroke();}
+ if(!phase2){
+ x.beginPath();x.arc(r*.42,0,r*.46,0,TAU);x.fillStyle='#3b7f8a';x.fill();x.strokeStyle='#18363b';x.lineWidth=2;x.stroke();
+ x.beginPath();x.arc(r*.5,0,r*.24,0,TAU);x.fillStyle='#0b0b10';x.fill();
+ x.fillStyle='rgba(255,255,255,.75)';x.beginPath();x.arc(r*.36,-r*.16,r*.08,0,TAU);x.fill();
+ }else{
+ // maw: dark opening with two rows of teeth facing forward
+ x.beginPath();x.ellipse(r*.38,0,r*.5,r*.62,0,0,TAU);x.fillStyle='#3a0d16';x.fill();x.strokeStyle='#1b0408';x.lineWidth=2;x.stroke();
+ x.fillStyle='#f2ead2';
+ for(var i=0;i<6;i++){var ty=-r*.5+i*r*.2;x.beginPath();x.moveTo(r*.85,ty);x.lineTo(r*.55,ty+r*.07);x.lineTo(r*.85,ty+r*.14);x.fill();
+ x.beginPath();x.moveTo(r*.0,ty+r*.02);x.lineTo(r*.22,ty+r*.09);x.lineTo(r*.0,ty+r*.16);x.fill();}
+ x.fillStyle='rgba(220,60,70,.6)';x.beginPath();x.ellipse(r*.38,0,r*.18,r*.3,0,0,TAU);x.fill();
+ }
+ x.restore();
+ },bar:function(w){return w.phase===2?'#d8545e':'#db927e';},
+ phase:function(w,assist){
+ if(w.dawnDeparting)return 'Dawn departure · Dawn';
+ if(w.st==='transform')return 'Transforming · Transforming';
+ var form=w.phase===1?'Phase 1':'Phase 2';
+ if(w.st==='attack'||w.st==='recover')return form+' · '+(w.move==='chain_dash'?'Rapid charges':'Dash')+(assist?' remaining '+w.dashesLeft:'');
+ return form+' · Hovering';
+ }};
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/draw/king_slime.js b/environments/games/web/games/terraria_remake/draw/king_slime.js
new file mode 100644
index 0000000000000000000000000000000000000000..03e6ce6227bab67726896450888ade9310d22dd8
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/draw/king_slime.js
@@ -0,0 +1,51 @@
+(function(g){
+ var BB=g.BB,D=BB.TR.DRAW,TR=BB.TR;
+ // Original art: a translucent gel dome with a crown and a dark core. Squash/stretch follows the simulated
+ // jump velocity and landing recovery; the teleport shrink is the simulated hitbox size itself.
+ BB.BOSS_DRAW['terraria/king_slime']={
+ hazards:function(x,c,t,V){
+ var w=c.boss;
+ if(w.st==='antic'&&w.move==='teleport')D.cue(x,V,{x:w.x,y:w.y},{x:w.target.x,y:w.target.y+0.2},'#88e9d4');
+ if(w.st!=='dead'&&!w.hidden)D.shadow(x,V,w.x,w.y-w.h/2,w.w,c);
+ D.extras(x,c,t,V);
+ },
+ body:function(x,c,t,V){var w=c.boss;
+ if(w.st==='dead'||w.hidden)return;
+ var sq=1;
+ if(w.st==='attack')sq=1+BB.clamp(w.vy/(13*TR.PX),-1,1)*.16;
+ else if(w.st==='recover'&&w.move!=='teleport')sq=1-.16*Math.max(0,1-w.stT/.22);
+ else sq=1+Math.sin(t*5)*.025;
+ var W=w.w*V.S/Math.sqrt(sq),H=w.h*V.S*sq,cx=V.sx(w.x),by=V.sy(w.y-w.h/2),flash=w.hitFlash>0;
+ var fade=w.move==='teleport'&&(w.st==='antic'||w.st==='recover')?.55:1;
+ x.save();x.translate(cx,by);x.globalAlpha=fade;
+ // gel dome
+ x.beginPath();x.moveTo(-W/2,0);x.bezierCurveTo(-W*.56,-H*.62,-W*.3,-H,0,-H);x.bezierCurveTo(W*.3,-H,W*.56,-H*.62,W/2,0);x.closePath();
+ x.globalAlpha=fade*.86;x.fillStyle=D.lit(flash,'#3d86d6');x.fill();x.globalAlpha=fade;
+ x.lineWidth=2.5;x.strokeStyle='#123563';x.stroke();
+ // darker inner core and lower gel
+ x.fillStyle='rgba(14,40,92,.45)';x.beginPath();x.ellipse(0,-H*.38,W*.2,H*.22,0,0,Math.PI*2);x.fill();
+ x.fillStyle='rgba(20,60,120,.35)';x.beginPath();x.ellipse(0,-H*.08,W*.44,H*.1,0,0,Math.PI*2);x.fill();
+ // highlights
+ x.fillStyle='rgba(255,255,255,.55)';x.beginPath();x.ellipse(-W*.25,-H*.72,W*.08,H*.14,-.6,0,Math.PI*2);x.fill();
+ x.fillStyle='rgba(255,255,255,.3)';x.beginPath();x.ellipse(-W*.12,-H*.86,W*.05,H*.05,0,0,Math.PI*2);x.fill();
+ // crown (dropped visually while vanishing)
+ if(!(w.move==='teleport'&&w.st==='antic')){
+ var cw=W*.36,ch=H*.2,top=-H*1.0;
+ x.beginPath();x.moveTo(-cw/2,top+ch*.15);x.lineTo(-cw/2,top-ch*.55);x.lineTo(-cw/4,top-ch*.15);x.lineTo(0,top-ch*.75);x.lineTo(cw/4,top-ch*.15);x.lineTo(cw/2,top-ch*.55);x.lineTo(cw/2,top+ch*.15);x.closePath();
+ x.fillStyle=D.lit(flash,'#f0c445');x.fill();x.lineWidth=1.5;x.strokeStyle='#6d4b0c';x.stroke();
+ x.fillStyle='#d8324a';x.beginPath();x.arc(0,top-ch*.12,ch*.17,0,Math.PI*2);x.fill();
+ x.fillStyle='#7fd4f0';x.fillRect(-cw/2+2,top-ch*.2,3,3);x.fillRect(cw/2-5,top-ch*.2,3,3);
+ }
+ x.restore();
+ if(w.st==='antic'&&w.move!=='teleport')D.cue(x,V,{x:w.x,y:w.y},{x:w.target.x,y:0.2},'#f7d377');
+ },
+ bar:function(){return '#4f9de0';},
+ // Only what the original shows on screen; hidden counters appear only with the explicit assist toggle.
+ phase:function(w,assist){
+ if(w.move==='teleport'&&(w.st==='antic'||w.st==='recover'))return 'Teleport · Teleport';
+ var text=w.st==='attack'?'Jump · Jump':'Landed · Landed';
+ if(assist)text+=' · next jump '+['normal','normal','low','high'][w.jumpIndex%4]+(w.teleportWait>0?' · TeleportTimer '+(5-w.teleportWait).toFixed(1)+'s':'');
+ return text;
+ }
+ };
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/draw/palette.js b/environments/games/web/games/terraria_remake/draw/palette.js
new file mode 100644
index 0000000000000000000000000000000000000000..a5ae00f1467497da6d6db35d268ea2c190d03593
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/draw/palette.js
@@ -0,0 +1,80 @@
+(function(g){
+ var BB=g.BB;
+ BB.VIEW.PAL={sky:'#83b9c6',forest:'#35694d',earth:'#624735',gold:'#efc96e',ink:'#e8eddd',dark:'#172b32'};
+ var D=BB.TR.DRAW={};
+ // Hand-authored original procedural art; no downloaded images, fonts or source-game sprites.
+ // Every function here only reads the case; noise comes from a hash of ids/time, never from the game RNG.
+ D.sprite=function(ctx,V,e,rows,pal,w,h,flip){
+ var sx=V.sx(e.x),sy=V.sy(e.y),cw=w*V.S/rows[0].length,ch=h*V.S/rows.length;
+ ctx.save();ctx.translate(Math.round(sx),Math.round(sy));if(flip)ctx.scale(-1,1);
+ for(var y=0;y=p[0]&&ex<=p[1]&&ey>=p[2]-.05&&p[2]>floor)floor=p[2];});
+ var gap=Math.max(0,ey-floor),k=Math.max(0,1-gap/8);if(k<=0)return;
+ BB.ART.shade(x,V.sx(ex),V.sy(floor)+2,width*V.S*.55*(0.6+0.4*k),5,0.35*k);
+ };
+ function slime(x,V,m,t,spiked){
+ var cx=V.sx(m.x),by=V.sy(m.y-m.h/2),w=m.w*V.S,h=m.h*V.S*(1+Math.sin(t*7+m.id)*.05),flash=m.hitT>0;
+ x.save();x.translate(cx,by);
+ if(spiked){x.fillStyle='#d9d3c4';for(var k=-2;k<=2;k++){x.beginPath();x.moveTo(k*w*.18-3,-h*.55);x.lineTo(k*w*.2,-h*1.15+Math.abs(k)*3);x.lineTo(k*w*.18+3,-h*.55);x.fill();}}
+ x.beginPath();x.moveTo(-w/2,0);x.quadraticCurveTo(-w/2,-h*1.05,0,-h*1.05);x.quadraticCurveTo(w/2,-h*1.05,w/2,0);x.closePath();
+ x.globalAlpha=.88;x.fillStyle=D.lit(flash,spiked?'#4c78c9':'#3f8ee0');x.fill();x.globalAlpha=1;
+ x.lineWidth=1.5;x.strokeStyle='#14305a';x.stroke();
+ x.fillStyle='rgba(255,255,255,.55)';x.beginPath();x.ellipse(-w*.2,-h*.72,w*.11,h*.12,-.5,0,Math.PI*2);x.fill();
+ x.fillStyle='#0d1f38';var f=m.face||1;x.fillRect(f*w*.08-3,-h*.55,2,3);x.fillRect(f*w*.08+3,-h*.55,2,3);
+ x.restore();
+ }
+ function servant(x,V,m,t){
+ var cx=V.sx(m.x),cy=V.sy(m.y),r=m.w*V.S*.5,a=Math.atan2(-(m.vy||0),m.vx||1);
+ x.save();x.translate(cx,cy);x.rotate(a);
+ x.strokeStyle='#8e2b3a';x.lineWidth=2;
+ for(var k=-1;k<=1;k++){x.beginPath();x.moveTo(-r*.6,k*r*.3);x.quadraticCurveTo(-r*1.5,k*r*.5+Math.sin(t*14+k+m.id)*3,-r*2.1,k*r*.7);x.stroke();}
+ x.fillStyle='#ece0d0';x.beginPath();x.arc(0,0,r,0,Math.PI*2);x.fill();x.strokeStyle='#4a1820';x.lineWidth=1.5;x.stroke();
+ x.fillStyle='#a8343f';x.beginPath();x.arc(r*.35,0,r*.5,0,Math.PI*2);x.fill();
+ x.fillStyle='#120608';x.beginPath();x.arc(r*.45,0,r*.22,0,Math.PI*2);x.fill();
+ x.restore();
+ }
+ function shot(x,V,p,t){
+ var cx=V.sx(p.x),cy=V.sy(p.y),a=Math.atan2(-p.vy,p.vx),r=Math.max(4,p.r*V.S);
+ x.save();x.translate(cx,cy);
+ if(p.kind==='slime_spike'){x.rotate(a);x.fillStyle='#e7e1cf';x.beginPath();x.moveTo(r*1.6,0);x.lineTo(-r*1.2,-2.2);x.lineTo(-r*1.2,2.2);x.closePath();x.fill();x.strokeStyle='#5a5246';x.lineWidth=1;x.stroke();}
+ else if(p.kind==='vile_spit'){
+ x.rotate(a);x.fillStyle='rgba(126,170,52,.45)';x.beginPath();x.ellipse(-r*.9,0,r*1.1,r*.55,0,0,Math.PI*2);x.fill();
+ x.fillStyle='#a7c94a';x.beginPath();x.arc(0,0,r,0,Math.PI*2);x.fill();x.strokeStyle='#3d4f17';x.lineWidth=1.5;x.stroke();
+ x.fillStyle='#e3f3a0';x.beginPath();x.arc(r*.3,-r*.3,r*.3,0,Math.PI*2);x.fill();
+ }else{ // homing skull with a cold flame trail
+ x.save();x.rotate(a);x.fillStyle='rgba(110,170,255,.35)';x.beginPath();x.moveTo(-r*.4,-r*.7);x.quadraticCurveTo(-r*2.6,Math.sin(t*20+p.id)*3,-r*.4,r*.7);x.fill();x.restore();
+ x.fillStyle='#ece3c9';x.beginPath();x.arc(0,-1,r*.85,0,Math.PI*2);x.fill();x.fillRect(-r*.5,r*.3,r,r*.5);
+ x.strokeStyle='#4d463c';x.lineWidth=1;x.stroke();x.fillStyle='#2a2430';x.fillRect(-r*.45,-r*.35,r*.35,r*.35);x.fillRect(r*.1,-r*.35,r*.35,r*.35);
+ }
+ x.restore();
+ }
+ function pickup(x,V,p,t){
+ var cx=V.sx(p.x),cy=V.sy(p.y)+Math.sin(t*5+p.x)*1.5;x.save();x.translate(cx,cy);
+ if(p.kind==='heart'){x.fillStyle='#e9465a';x.beginPath();x.moveTo(0,5);x.bezierCurveTo(-9,-1,-5,-8,0,-3);x.bezierCurveTo(5,-8,9,-1,0,5);x.fill();x.strokeStyle='#5c0f1c';x.lineWidth=1;x.stroke();}
+ else{BB.ART.glow(x,0,0,12,'150,190,255',.5);x.fillStyle='#ffe78a';x.beginPath();for(var i=0;i<10;i++){var rr=i%2?3:7,a=-Math.PI/2+i*Math.PI/5;x.lineTo(Math.cos(a)*rr,Math.sin(a)*rr);}x.closePath();x.fill();x.strokeStyle='#7a5a12';x.lineWidth=1;x.stroke();}
+ x.restore();
+ }
+ D.extras=function(x,c,t,V){
+ var boss=c.boss;
+ (boss.minions||[]).forEach(function(m){if(m.hp<=0)return;
+ if(m.kind==='slime'||m.kind==='spiked_slime'){D.shadow(x,V,m.x,m.y-m.h/2,m.w,c);slime(x,V,m,t,m.kind==='spiked_slime');}else servant(x,V,m,t);
+ });
+ (boss.shots||[]).forEach(function(p){shot(x,V,p,t);});
+ (boss.pickups||[]).forEach(function(p){pickup(x,V,p,t);});
+ };
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/draw/queen_bee.js b/environments/games/web/games/terraria_remake/draw/queen_bee.js
new file mode 100644
index 0000000000000000000000000000000000000000..5cb4b3f0199cf6851f843aa51d35ec3e8ddff032
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/draw/queen_bee.js
@@ -0,0 +1,71 @@
+(function(g){
+ var BB=g.BB,D=BB.TR.DRAW,TAU=Math.PI*2;
+ // Original art: a crowned queen bee with striped abdomen, stinger, translucent beating wings and a royal ruff.
+ // She faces her velocity while charging and the player otherwise; bees and stingers are drawn here too.
+ function bee(x,V,m,t){
+ var cx=V.sx(m.x),cy=V.sy(m.y),r=m.w*V.S*.5,f=(m.vx||0)>=0?1:-1,flap=Math.sin(t*60+m.id)*.6;
+ x.save();x.translate(cx,cy);x.scale(f,1);
+ x.fillStyle='rgba(230,240,255,.65)';x.beginPath();x.ellipse(-r*.1,-r*.75,r*.55,r*.3*(1+flap*.4),-.5,0,TAU);x.fill();
+ x.fillStyle='#f2c23a';x.beginPath();x.ellipse(0,0,r,r*.75,0,0,TAU);x.fill();
+ x.fillStyle='#2a1c08';x.fillRect(-r*.35,-r*.72,r*.22,r*1.44);x.fillRect(r*.1,-r*.72,r*.2,r*1.44);
+ x.beginPath();x.moveTo(-r,0);x.lineTo(-r*1.45,r*.12);x.lineTo(-r,r*.25);x.fill();
+ x.fillStyle='#1a1205';x.beginPath();x.arc(r*.72,-r*.15,r*.2,0,TAU);x.fill();
+ if(m.kind==='big_bee'){x.strokeStyle='#8a5a12';x.lineWidth=1.5;x.beginPath();x.ellipse(0,0,r,r*.75,0,0,TAU);x.stroke();}
+ x.restore();
+ }
+ function stinger(x,V,p){
+ var a=Math.atan2(-p.vy,p.vx),r=Math.max(5,p.r*V.S*1.4);x.save();x.translate(V.sx(p.x),V.sy(p.y));x.rotate(a);
+ x.fillStyle='rgba(255,220,90,.35)';x.beginPath();x.ellipse(-r*1.2,0,r*1.3,r*.45,0,0,TAU);x.fill();
+ x.fillStyle='#f6d34a';x.beginPath();x.moveTo(r*1.4,0);x.lineTo(-r,-r*.42);x.lineTo(-r*.6,0);x.lineTo(-r,r*.42);x.closePath();x.fill();
+ x.strokeStyle='#6a4a08';x.lineWidth=1;x.stroke();x.restore();
+ }
+ BB.BOSS_DRAW['terraria/queen_bee']={hazards:function(x,c,t,V){
+ var w=c.boss;
+ // Readable windup: while she hangs at the charge height a faint (18 %) streak marks that lane. It is drawn only
+ // during the pause, the period the source shows her holding level with the player; the explicit target box
+ // stays behind the assist cues switch.
+ if(w.move==='charge'&&w.st==='antic'&&w.hold>0){
+ var y=V.sy(w.y),k=Math.min(1,w.hold/w.windup());x.save();x.globalAlpha=.18*k;x.fillStyle='#ffe28a';
+ x.fillRect(Math.min(V.sx(w.x),V.sx(c.body.x))-20,y-3,Math.abs(V.sx(c.body.x)-V.sx(w.x))+40,6);x.restore();
+ }
+ if(w.move==='charge'&&w.st==='antic'&&BB.TR.showCues)D.cue(x,V,w,{x:c.body.centre().x,y:w.y},'#f5d26a');
+ w.minions.forEach(function(m){if(m.hp>0)bee(x,V,m,t);});
+ w.shots.forEach(function(p){stinger(x,V,p);});
+ (w.pickups||[]).length&&D.extras(x,{boss:{minions:[],shots:[],pickups:w.pickups}},t,V);
+ },body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return;
+ var charging=w.move==='charge'&&w.st==='attack',b=c.body.centre(),f=charging?(w.vx>=0?1:-1):(b.x>=w.x?1:-1);
+ var s=w.w*V.S,flash=w.hitFlash>0,flap=Math.sin(t*(charging?70:48))*.5,tilt=charging?.12:Math.sin(t*3)*.05;
+ // the windup crouch: she pulls back slightly before the dash
+ var crouch=w.move==='charge'&&w.st==='antic'&&w.hold>0?Math.min(1,w.hold/w.windup()):0;
+ x.save();x.translate(V.sx(w.x)-f*crouch*6,V.sy(w.y));x.scale(f,1);x.rotate(-tilt+crouch*.18);
+ // speed lines while charging
+ if(charging){x.strokeStyle='rgba(255,240,190,.35)';x.lineWidth=2;for(var k=0;k<4;k++){x.beginPath();x.moveTo(-s*.6,-s*.25+k*s*.16);x.lineTo(-s*(1.1+k%2*.25),-s*.25+k*s*.16);x.stroke();}}
+ // back wings
+ x.fillStyle='rgba(210,230,255,.5)';x.beginPath();x.ellipse(-s*.05,-s*.42,s*.42,s*.2*(1+flap*.5),-.6,0,TAU);x.fill();
+ // abdomen with stripes and stinger
+ x.fillStyle=D.lit(flash,'#f0b62e');x.beginPath();x.ellipse(-s*.18,s*.06,s*.36,s*.28,.15,0,TAU);x.fill();
+ x.save();x.beginPath();x.ellipse(-s*.18,s*.06,s*.36,s*.28,.15,0,TAU);x.clip();x.fillStyle='#3a2508';
+ for(k=0;k<3;k++)x.fillRect(-s*.42+k*s*.17,-s*.3,s*.07,s*.7);x.restore();
+ x.strokeStyle='#4a2f08';x.lineWidth=2;x.beginPath();x.ellipse(-s*.18,s*.06,s*.36,s*.28,.15,0,TAU);x.stroke();
+ x.fillStyle='#2a1a06';x.beginPath();x.moveTo(-s*.5,s*.1);x.lineTo(-s*.72,s*.2);x.lineTo(-s*.48,s*.22);x.fill();
+ // thorax with royal ruff
+ x.fillStyle=D.lit(flash,'#7a4a12');x.beginPath();x.arc(s*.17,-s*.02,s*.2,0,TAU);x.fill();
+ x.fillStyle='#f5e6c2';for(k=0;k<6;k++){var a=-1.2+k*.48;x.beginPath();x.arc(s*.17+Math.cos(a)*s*.2,-s*.02+Math.sin(a)*s*.2,s*.07,0,TAU);x.fill();}
+ // head, eyes, antennae and crown
+ x.fillStyle=D.lit(flash,'#e8a82a');x.beginPath();x.arc(s*.38,-s*.13,s*.15,0,TAU);x.fill();x.strokeStyle='#4a2f08';x.lineWidth=1.5;x.stroke();
+ x.fillStyle='#2a1408';x.beginPath();x.ellipse(s*.45,-s*.15,s*.05,s*.075,0,0,TAU);x.fill();
+ x.strokeStyle='#2a1408';x.lineWidth=1.5;x.beginPath();x.moveTo(s*.4,-s*.27);x.quadraticCurveTo(s*.47,-s*.42,s*.56,-s*.4);x.stroke();
+ x.fillStyle='#f6cf46';x.beginPath();x.moveTo(s*.26,-s*.26);for(var p=0;p<5;p++){x.lineTo(s*.28+p*s*.045,-s*(p%2?.32:.4));}x.lineTo(s*.48,-s*.26);x.closePath();x.fill();
+ x.fillStyle='#e24a5a';x.beginPath();x.arc(s*.37,-s*.33,s*.022,0,TAU);x.fill();
+ // front wings
+ x.fillStyle='rgba(235,245,255,.6)';x.beginPath();x.ellipse(s*.02,-s*.4,s*.38,s*.17*(1-flap*.5),-.85,0,TAU);x.fill();
+ x.strokeStyle='rgba(120,150,190,.6)';x.lineWidth=1;x.stroke();
+ x.restore();
+ },bar:function(){return '#e6b23a';},
+ phase:function(w,assist){
+ if(w.move==='charge'||w.move==='charge_end')return 'Lane charge'+(assist?' remaining '+w.chargesLeft:'');
+ if(w.move==='summon')return 'Summon bees'+(assist?' remaining '+w.beesLeft:'');
+ if(w.move==='stingers')return 'Stinger volley'+(assist?' remaining '+w.volleyLeft:'');
+ return '';
+ }};
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/draw/skeletron.js b/environments/games/web/games/terraria_remake/draw/skeletron.js
new file mode 100644
index 0000000000000000000000000000000000000000..aca054ed323b0506450c8472ede5691f65650427
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/draw/skeletron.js
@@ -0,0 +1,58 @@
+(function(g){
+ var BB=g.BB,D=BB.TR.DRAW;
+ var TAU=Math.PI*2;
+ function bone(x,ax,ay,bx,by,wd){
+ x.lineCap='round';x.lineWidth=wd+3;x.strokeStyle='#3d362f';x.beginPath();x.moveTo(ax,ay);x.lineTo(bx,by);x.stroke();
+ x.lineWidth=wd;x.strokeStyle='#ddd1b3';x.stroke();
+ x.fillStyle='#e9dfc4';[[ax,ay],[bx,by]].forEach(function(p){x.beginPath();x.arc(p[0],p[1],wd*.75,0,TAU);x.fill();});
+ }
+ function hand(x,V,h,flash,t){
+ var cx=V.sx(h.x),cy=V.sy(h.y),s=h.w*V.S*.5,a=h.st==='attack'?Math.atan2(-h.vy,h.vx):Math.PI/2*(h.side<0?1:1)+.0;
+ if(h.st!=='attack')a=-Math.PI/2+h.side*.35;
+ x.save();x.translate(cx,cy);x.rotate(a);
+ x.fillStyle=D.lit(flash,'#e2d6b8');x.strokeStyle='#3d362f';x.lineWidth=2;
+ x.beginPath();x.ellipse(0,0,s*.62,s*.55,0,0,TAU);x.fill();x.stroke();
+ for(var f=-1.5;f<=1.5;f++){
+ var fy=f*s*.28;x.beginPath();x.moveTo(s*.4,fy);x.lineTo(s*1.05,fy*1.15);x.lineWidth=s*.22+2;x.strokeStyle='#3d362f';x.stroke();
+ x.lineWidth=s*.22;x.strokeStyle=D.lit(flash,'#e2d6b8');x.stroke();
+ x.fillStyle='#3d362f';x.beginPath();x.arc(s*1.08,fy*1.15,s*.1,0,TAU);x.fill();
+ }
+ x.beginPath();x.moveTo(-s*.1,-s*.55);x.lineTo(-s*.55,-s*1.0);x.lineWidth=s*.22+2;x.strokeStyle='#3d362f';x.stroke();x.lineWidth=s*.22;x.strokeStyle=D.lit(flash,'#e2d6b8');x.stroke();
+ x.restore();
+ }
+ function skull(x,w,W,H,flash,glow){
+ // cranium + cheek + jaw, original silhouette
+ x.beginPath();x.moveTo(-W*.48,-H*.05);x.bezierCurveTo(-W*.55,-H*.6,-W*.3,-H*.52,0,-H*.52);x.bezierCurveTo(W*.3,-H*.52,W*.55,-H*.6,W*.48,-H*.05);
+ x.bezierCurveTo(W*.46,H*.16,W*.3,H*.22,W*.26,H*.28);x.lineTo(-W*.26,H*.28);x.bezierCurveTo(-W*.3,H*.22,-W*.46,H*.16,-W*.48,-H*.05);x.closePath();
+ x.fillStyle=D.lit(flash,'#e6dbc0');x.fill();x.lineWidth=2.5;x.strokeStyle='#3d362f';x.stroke();
+ x.beginPath();x.rect(-W*.22,H*.28,W*.44,H*.17);x.fillStyle=D.lit(flash,'#d8ccae');x.fill();x.stroke();
+ x.strokeStyle='#3d362f';x.lineWidth=1.5;for(var i=-2;i<=2;i++){x.beginPath();x.moveTo(i*W*.085,H*.28);x.lineTo(i*W*.085,H*.42);x.stroke();}
+ [-1,1].forEach(function(s){x.beginPath();x.ellipse(s*W*.2,-H*.04,W*.14,H*.13,s*.2,0,TAU);x.fillStyle='#15121a';x.fill();
+ if(glow){BB.ART.glow(x,s*W*.2,-H*.04,W*.2,'255,70,60',.8);x.fillStyle='#ff6a4d';x.beginPath();x.arc(s*W*.2,-H*.04,W*.04,0,TAU);x.fill();}});
+ x.beginPath();x.moveTo(0,H*.1);x.lineTo(-W*.06,H*.2);x.lineTo(W*.06,H*.2);x.closePath();x.fillStyle='#15121a';x.fill();
+ x.strokeStyle='rgba(61,54,47,.6)';x.lineWidth=1.2;x.beginPath();x.moveTo(W*.1,-H*.5);x.lineTo(W*.16,-H*.36);x.lineTo(W*.1,-H*.28);x.stroke();
+ }
+ BB.BOSS_DRAW['terraria/skeletron']={hazards:D.extras,body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return;
+ var flash=w.hitFlash>0,hx=V.sx(w.x),hy=V.sy(w.y);
+ w.hands.forEach(function(h){if(h.hp<=0)return;
+ var sx=V.sx(w.x+h.side*.85),sy=V.sy(w.y-.75),ex=V.sx(h.x),ey=V.sy(h.y),mx=(sx+ex)/2,my=(sy+ey)/2,dx=ex-sx,dy=ey-sy,l=Math.hypot(dx,dy)||1;
+ var bend=Math.max(0,95-l)*.55+12,elx=mx+(-dy/l)*bend*h.side*-1,ely=my+(dx/l)*bend*h.side*-1;
+ if(ely0;}).length;
+ if(w.enraged)return 'Daytime enraged · Enraged';
+ return (w.st==='attack'?'Spinning pursuit · Spin':'Hovering hand strikes · Hands')+' · hands '+hands+'/2'+(assist?' · Armor '+w.defense:'');
+ }};
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/game.js b/environments/games/web/games/terraria_remake/game.js
new file mode 100644
index 0000000000000000000000000000000000000000..93b5e9ebb8d3a2335b3f646e8b21f886dfdb22b0
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/game.js
@@ -0,0 +1,14 @@
+(function(g){
+ g.BB.GAME={id:'terraria_remake',title:'Terraria · Arena Trials',rules:'terraria-1458-arena-r7',defaultCase:'terraria/king_slime',roster:[
+ {id:'terraria/king_slime',name:'Bouncing Gel Giant',arch:'Jumps, teleports, and slime minions'},
+ {id:'terraria/eye_of_cthulhu',name:'Charging Giant Eye',arch:'Read the charge lane and adapt to phase-two rapid charges'},
+ {id:'terraria/skeletron',name:'Twin-Handed Giant Skull',arch:'Independent hands, spinning pursuit, and armor windows'},
+ {id:'terraria/eater_of_worlds',name:'Burrowing Great Worm',arch:'Burrowing, segmented targets, and real splitting'},
+ {id:'terraria/queen_bee',name:'Charging Giant Bee',arch:'Align with lane charges, bee summons, and stinger volleys'},
+ {id:'terraria/brain_of_cthulhu',name:'Teleporting Flesh Brain',arch:'Clear the guard eyes, then chase the teleporting core'}
+ ]};
+ // Public three tiers (tiers.js): the shared page builds its difficulty buttons from this declaration.
+ g.BB.GAME.tiers=g.BB.TR.TIER_D;
+ g.BB.GAME.resetOptions=function(){var el=g.document&&g.document.getElementById('world-start');return {dawn_in_seconds:el?+el.value:540};};
+ if(g.document){var cue=g.document.getElementById('show-cues');if(cue)cue.addEventListener('change',function(){g.BB.TR.showCues=cue.checked;});}
+})(typeof window!=='undefined'?window:globalThis);
diff --git a/environments/games/web/games/terraria_remake/index.html b/environments/games/web/games/terraria_remake/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..fcb605800d6475a35669dc1130a034e6b7f01714
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/index.html
@@ -0,0 +1,68 @@
+
+
+
+
+Terraria · Arena Trials | BossBench
+
+
+
+
Terraria ARENA TRIALS
One loadout, six challenges. Read attacks and master your positioning.
A/D Move; hold Space to jump higher and continue flying; S drops through platforms.
+
Move the mouse to aim; J/left mouse button uses the current weapon; Q switches between sword and bow.
+
E equips the bow; right mouse button equips the sword. Bow is the default with unlimited standard arrows.
+
The blue bar shows remaining flight time and refills on landing; hold Space to glide after it runs out. The sword sweeps an arc in the facing direction and can hit several worm segments at once.
+
The charging giant eye leaves at dawn; the twin-handed skull enrages by day. Target lines are off by default because the original game has none; enable assist cues if needed.
+
All three difficulty tiers use Classic rules: Easy lasts about 25 seconds, Normal about one minute, and Hard about three minutes. Boss health, attack frequency, and damage increase by tier.
+
Move list
+
Recording and Replay
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/environments/games/web/games/terraria_remake/presentation.js b/environments/games/web/games/terraria_remake/presentation.js
new file mode 100644
index 0000000000000000000000000000000000000000..737e8a33c65a78c7a67227def0de22f664a66dc7
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/presentation.js
@@ -0,0 +1,32 @@
+// Original synthesized cues; presentation never changes the simulation or its RNG.
+(function(g){
+ var BB=g.BB,ctx=null;
+ function unlock(){
+ var Audio=g.AudioContext||g.webkitAudioContext;if(!Audio)return;
+ if(!ctx)ctx=new Audio();if(ctx.state==='suspended')ctx.resume().catch(function(){});
+ }
+ if(g.document){g.document.addEventListener('pointerdown',unlock,{once:true});g.document.addEventListener('keydown',unlock,{once:true});}
+ function tone(hz,duration,volume,type,end){
+ if(!ctx||ctx.state!=='running')return;
+ var o=ctx.createOscillator(),a=ctx.createGain(),t=ctx.currentTime;
+ o.type=type||'triangle';o.frequency.setValueAtTime(hz,t);if(end)o.frequency.exponentialRampToValueAtTime(end,t+duration);
+ a.gain.setValueAtTime(volume,t);a.gain.exponentialRampToValueAtTime(.0001,t+duration);
+ o.connect(a);a.connect(ctx.destination);o.start(t);o.stop(t+duration);
+ }
+ var consume=BB.Juice.prototype.consume;
+ BB.Juice.prototype.consume=function(c,R){
+ var start=this.caseRef===c&&c.events.length>=this.seen?this.seen:c.events.length;
+ consume.call(this,c,R);
+ if(!c.id.startsWith('terraria/'))return;
+ // Terraria has no artificial hit-stop. Keep the shared visual particles.
+ this.hitstop=0;
+ if(!R.canvas||R.canvas.id!=='view'||!g.document.getElementById('select').classList.contains('hidden'))return;
+ var count=0;
+ for(var i=start;i one legal 200 ms packet.
+// It reads the live BB.Case (privileged state) and evaluates candidate key sets on isolated deep copies
+// (their own RNG copy, no shared objects except the immutable case definition), so the live simulation and
+// its RNG are never touched. Deterministic: no Math.random, no clock, no memory between calls.
+// It is a reference/demo controller, never shown to a policy; its wins are not model or human results.
+(function (g) {
+ var BB = g.BB, SC = BB.TR.SCRIPTED = {};
+ function copy(v) {
+ if (!v || typeof v !== 'object') return v;
+ if (Array.isArray(v)) return v.map(copy);
+ var o = Object.create(Object.getPrototypeOf(v));
+ Object.keys(v).forEach(function (k) { o[k] = k === 'def' ? v[k] : k === 'events' ? [] : copy(v[k]); });
+ return o;
+ }
+ function dist(a, b) { return Math.hypot(a.x - b.x, a.y - b.y); }
+ // Aim point: the nearest live target part (Eater segments above ground, Expert Skeletron hands first,
+ // close minions), led by its velocity over the arrow flight time.
+ function aimTarget(c) {
+ var w = c.boss, b = c.body.centre(), parts = [];
+ if (w.segments) parts = w.segments.filter(function (s) { return s.hp > 0 && s.y > 0.1; });
+ else if (w.hands && w.k.expert >= .5) parts = w.hands.filter(function (h) { return h.hp > 0; });
+ if (!parts.length) parts = [w];
+ parts = parts.concat((w.minions || []).filter(function (m) { return m.hp > 0 && dist(m, b) < 4; }));
+ parts.sort(function (a, z) { return dist(a, b) - dist(z, b); });
+ var p = parts[0], flight = dist(p, b) / 31;
+ var lead = (w.st === 'antic' || w.st === 'recover') ? 0 : Math.min(.35, flight);
+ return { x: BB.clamp(p.x + (p.vx || 0) * lead, .1, 26.9), y: BB.clamp(p.y + (p.vy || 0) * lead + 1.5 * flight * flight, .1, 14.9) };
+ }
+ // Same keys held for all six sub-steps; Space is released for one packet when a fresh press is needed.
+ function packet(c, keys) {
+ var t = aimTarget(c); keys = Object.assign({}, keys);
+ if (keys.Space && c.body.grounded && c.body.prev.jump) delete keys.Space;
+ var held = []; for (var i = 0; i < BB.SUBSTEPS; i++) held.push(keys);
+ return BB.formatPacket(held, [BB.clamp(Math.round((t.x - c.body.aimX) * 30), -1000, 1000), BB.clamp(Math.round((c.body.aimY - t.y) * 30), -1000, 1000), 0]);
+ }
+ function runPacket(s, text) {
+ var p = BB.parsePacket(text), m = p.mouse.map(function (v) { return v / 12; });
+ for (var j = 0; j < 12 && !s.result; j++) s.tick(p.subs[Math.floor(j / 2)], m);
+ }
+ function bossHealth(w) { return w.hp + (w.hands ? w.hands.reduce(function (a, h) { return a + h.hp; }, 0) : 0); }
+ function candidates(c, expertEye) {
+ var a = [{ E: true }, { E: true, A: true }, { E: true, D: true }, { E: true, Space: true }, { E: true, A: true, Space: true },
+ { E: true, D: true, Space: true }, { E: true, S: true }, { E: true, A: true, S: true }, { E: true, D: true, S: true }];
+ // The sword is offered where melee arcs pay: Eater segments, Expert Eye, Queen Bee's bee swarms and the Brain's
+ // Creeper ring (one arc clears several; r6 round 1: hard Queen Bee 6/8 -> 8/8, hard Brain 2/8 -> 8/8 with the
+ // sword and a 9-packet look-ahead that sees a returning Creeper coming).
+ if (c.boss.segments || expertEye || c.id === 'terraria/queen_bee' || c.id === 'terraria/brain_of_cthulhu') a = a.concat([{ RMB: true }, { RMB: true, A: true }, { RMB: true, D: true }, { RMB: true, Space: true },
+ { RMB: true, A: true, Space: true }, { RMB: true, D: true, Space: true }]);
+ return a;
+ }
+ // Score of holding `keys` for `horizon` packets on a copy: health kept, Boss damage dealt, distance from
+ // hazards, remaining wing time, and a small penalty for being pinned at a side wall.
+ // Expert Eye chain dashes change direction every ~0.35-0.65 s, so holding one key set for 10 packets is a poor
+ // model of the future. There, each candidate first packet is scored by its best follow-up among a few
+ // continuations (round 3: Expert Eye seeds 1-8 went from 4/8 to 6/8 wins in the Node stress).
+ var CONTINUATIONS = [null, { E: true }, { E: true, A: true }, { E: true, D: true }];
+ function evaluate(c, keys, horizon, expertEye, cont) {
+ var s = copy(c), initial = s.body.hp, before = bossHealth(s.boss);
+ for (var n = 0; n < horizon && !s.result; n++) runPacket(s, packet(s, n === 0 || !cont ? keys : cont));
+ return score(s, initial, before, expertEye);
+ }
+ function score(s, initial, before, expertEye) {
+ var b = s.body.centre(), near = 0;
+ s.boss.hazards().forEach(function (h) {
+ var q = h.box || { x: h.circle[0], y: h.circle[1] }; near += Math.max(0, 3 - Math.hypot(q.x - b.x, q.y - b.y));
+ });
+ // Eater: health counts 22 per point, not 14. With the r5 worm AI the chain keeps sweeping back through the
+ // player, so trading sword hits inside it pays over 1.2 s but drains 200 HP over a long fight (r5 round 3:
+ // hard tier 3/24 losses at 58-81 s with 14; 8/8 with 22, including those three seeds). r7 (no natural regen):
+ // 26. Over seeds 1-32 hard, 22 lost seed 25 at 88 s; 26, 30 and 34 all win 32/32 (in window 29, 29, 28; normal
+ // 28, 28, 29). 26 and 30 tie on counts; 26 is used because the recorded seed 1 finishes in the hard window with it
+ // (204 s vs 142 s). A look-ahead of 9 instead of 6 also saved seed 25 but finished 4 hard seeds under 150 s.
+ var score = (s.body.hp - initial) * (expertEye ? 16 : s.boss.segments ? 26 : 14) + (before - bossHealth(s.boss)) * (expertEye ? 1.6 : .6) - near * 8 + s.body.flight * 2;
+ if (s.result === 'loss') score -= 10000; if (s.result === 'win') score += 10000;
+ return score - Math.max(0, 2 - s.body.x) - Math.max(0, s.body.x - 25);
+ }
+ // Classic hard Skeletron: hand swipes come between spins at 1.15x cadence, so a single key set held for the whole
+ // look-ahead cannot both dodge the swipe and line up the next shot. Two plies: every first packet is scored by its
+ // best follow-up key set held for the rest of the 1.8 s horizon (r6 round 1: hard 7/16 with one ply, 16/16 on the
+ // 8 failing seeds with two; ~40 ms per 200 ms packet).
+ function twoPly(c, horizon) {
+ var initial = c.body.hp, before = bossHealth(c.boss), list = candidates(c, false), best = null, bestScore = -Infinity;
+ list.forEach(function (k1) {
+ var s1 = copy(c); runPacket(s1, packet(s1, k1)); var top = -Infinity;
+ list.forEach(function (k2) {
+ var s2 = copy(s1); for (var n = 1; n < horizon && !s2.result; n++) runPacket(s2, packet(s2, k2));
+ top = Math.max(top, score(s2, initial, before, false));
+ });
+ if (top > bestScore) { bestScore = top; best = k1; }
+ });
+ return packet(c, best);
+ }
+ function decide(c) {
+ var expertEye = c.id === 'terraria/eye_of_cthulhu' && !!c.boss.expert;
+ if (c.boss.hands && !c.boss.expert && c.boss.pace.aggr > 1) return twoPly(c, 9);
+ // Skeletron's spin chases for 6.7 s: Expert needs a 2.4 s look-ahead to plan the escape past the head.
+ var horizon = expertEye ? 10 : c.id === 'terraria/brain_of_cthulhu' ? 9 : c.boss.hands && c.boss.expert ? 12 : 6, best = null, bestScore = -Infinity;
+ candidates(c, expertEye).forEach(function (keys) {
+ var score = -Infinity;
+ (expertEye ? CONTINUATIONS : [null]).forEach(function (cont) { score = Math.max(score, evaluate(c, keys, horizon, expertEye, cont)); });
+ if (score > bestScore) { bestScore = score; best = keys; }
+ });
+ return packet(c, best);
+ }
+ SC.copy = copy; SC.packet = packet; SC.decide = decide; SC.aimTarget = aimTarget;
+ BB.GAME.scripted = function (c) { return decide(c); };
+})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/environments/games/web/games/terraria_remake/semantic_ppo_v1/__init__.py b/environments/games/web/games/terraria_remake/semantic_ppo_v1/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..13ef4b83bfd63fbbe6e09c5b6c36021e8017f4b7
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/semantic_ppo_v1/__init__.py
@@ -0,0 +1,4 @@
+from .env import SemanticEnv, make_semantic_env
+from .actions import to_named, to_indices
+
+__all__ = ['SemanticEnv', 'make_semantic_env', 'to_named', 'to_indices']
diff --git a/environments/games/web/games/terraria_remake/semantic_ppo_v1/actions.py b/environments/games/web/games/terraria_remake/semantic_ppo_v1/actions.py
new file mode 100644
index 0000000000000000000000000000000000000000..1282a25b9ae72f963936af73dfbed579e4897440
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/semantic_ppo_v1/actions.py
@@ -0,0 +1,42 @@
+"""The named action vocabulary shown to an LLM; integer IDs stay inside PPO."""
+from numbers import Integral
+import gymnasium as gym
+import numpy as np
+
+FIELDS = ('move', 'vert', 'attack')
+LABELS = (('none', 'left', 'right'), ('none', 'jump', 'drop'),
+ ('none',) + tuple(f'shoot {i*22.5:g}' for i in range(16)) + ('slash left', 'slash right'))
+
+
+def to_named(indices):
+ if len(indices) != 3 or any(isinstance(v, (bool, np.bool_)) or not isinstance(v, Integral)
+ or not 0 <= v < len(labels) for v, labels in zip(indices, LABELS)):
+ raise ValueError('expected three categorical integer IDs in [3,3,19]')
+ return {field: labels[int(i)] for field, labels, i in zip(FIELDS, LABELS, indices)}
+
+
+def to_indices(action):
+ """Decode canonical named fields; the environment additionally accepts text envelopes."""
+ if not isinstance(action, dict) or set(action) != set(FIELDS):
+ raise ValueError('expected move, vert, attack fields')
+ return tuple(labels.index(action[field]) for field, labels in zip(FIELDS, LABELS))
+
+
+class NamedActions(gym.Space):
+ def __init__(self, seed=None):
+ super().__init__(None, None, seed)
+
+ def sample(self, mask=None, probability=None):
+ if mask is not None or probability is not None:
+ raise ValueError('named action masking is not supported')
+ return to_named([int(self.np_random.integers(len(labels))) for labels in LABELS])
+
+ def contains(self, action):
+ try:
+ to_indices(action)
+ return True
+ except (TypeError, ValueError, KeyError):
+ return False
+
+ def __repr__(self):
+ return 'NamedActions(move=3, vert=3, attack=19)'
diff --git a/environments/games/web/games/terraria_remake/semantic_ppo_v1/env.py b/environments/games/web/games/terraria_remake/semantic_ppo_v1/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..76339c0c1d0f2ca030a4da586215284afa05eff4
--- /dev/null
+++ b/environments/games/web/games/terraria_remake/semantic_ppo_v1/env.py
@@ -0,0 +1,252 @@
+"""Experimental RGB / 100 ms semantic Gym environment, independent of policy-gym@2."""
+from __future__ import annotations
+
+import base64
+import copy
+import hashlib
+import json
+import math
+from numbers import Integral
+from pathlib import Path
+import re
+import shutil
+import subprocess
+
+import gymnasium as gym
+import numpy as np
+
+from bossbench.unified import _finite_number, _plain, _reset_options
+from bossbench.tiers import resolve_options
+from bossbench.webenv import BrowserTransport
+from .actions import NamedActions, FIELDS, LABELS
+
+HERE = Path(__file__).resolve().parent
+GAME = HERE.parent
+ROOT = HERE.parents[3]
+PROTOCOL = ('Output a JSON object with explicit action meanings, for example '
+ '{"move":"left","vert":"jump","attack":"shoot 135"}. '
+ 'All three fields execute concurrently in one 100 ms window; use "none" for no action. '
+ '0 degrees points right, 90 up. The 16 shoot directions are multiples of 22.5 degrees. '
+ 'Text envelopes such as <|semantic_start|> left ; jump ; shoot 135 <|semantic_end|> are also accepted. '
+ 'Invalid input executes a no-op; never output categorical integer IDs in the LLM response.')
+
+
+def source_manifest():
+ """Fingerprint precisely the frozen page plus the experimental adapter."""
+ page = (GAME / 'index.html').read_text(encoding='utf-8')
+ frozen = hashlib.sha256()
+ for name in re.findall(r'