Prompt specification
Build or customize the Three.js 3D scene "Pause Resume and Replay Consistency Test" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Pause Resume and Replay Consistency Test
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/pause-resume-and-replay-consistency-test-x3576
Scene Description Prompt:
Build a voxel strategy simulation with pause, adjustable playback speed, and deterministic seeded replay. Use Three.js from cdnjs in one HTML file.
Working Three.js Starter (pause-resume-and-replay-consistency-test-x3576):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Command — Deterministic Strategy Simulator</title>
<style>
:root {
--bg: #071018;
--panel: rgba(10, 20, 29, 0.88);
--panel-light: rgba(19, 34, 45, 0.92);
--line: rgba(137, 199, 221, 0.18);
--text: #d9edf4;
--muted: #7895a3;
--cyan: #45d9e8;
--cyan-dark: #1b8998;
--orange: #ff8a48;
--green: #6ee7a4;
--yellow: #ffd166;
--red: #ff6577;
--shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: var(--text);
background: rgba(31, 54, 68, 0.9);
border: 1px solid var(--line);
border-radius: 8px;
padding: 9px 12px;
cursor: pointer;
transition: 140ms ease;
}
button:hover:not(:disabled) {
border-color: rgba(69, 217, 232, 0.55);
background: rgba(42, 78, 91, 0.95);
transform: translateY(-1px);
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:disabled {
opacity: 0.38;
cursor: not-allowed;
}
button.primary {
color: #031317;
background: var(--cyan);
border-color: var(--cyan);
font-weight: 800;
}
button.primary:hover:not(:disabled) {
background: #79e9f2;
}
button.danger {
border-color: rgba(255, 101, 119, 0.4);
color: #ffacb5;
}
canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
}
#ui {
position: fixed;
inset: 0;
pointer-events: none;
user-select: none;
}
.panel {
pointer-events: auto;
background: var(--panel);
border: 1px solid var(--line);
box-shadow: var(--shadow);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.muted {
color: var(--muted);
}
.mono {
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
}
#brand {
position: absolute;
top: 18px;
left: 18px;
width: 230px;
padding: 16px;
border-radius: 12px;
}
#brand h1 {
margin: 5px 0 3px;
font-size: 20px;
letter-spacing: -0.03em;
}
#brand p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
#resourceBar {
position: absolute;
top: 18px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 20px;
padding: 12px 18px;
border-radius: 12px;
}
.resource {
display: flex;
align-items: center;
gap: 9px;
min-width: 88px;
}
.resource-icon {
display: grid;
width: 29px;
height: 29px;
place-items: center;
color: var(--cyan);
background: rgba(69, 217, 232, 0.1);
border: 1px solid rgba(69, 217, 232, 0.22);
border-radius: 7px;
font-size: 13px;
}
.resource-value {
font-size: 15px;
font-weight: 800;
}
.resource-label {
margin-top: 1px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#transport {
position: absolute;
top: 18px;
right: 18px;
width: 292px;
padding: 14px;
border-radius: 12px;
}
.transport-row {
display: flex;
align-items: center;
gap: 8px;
}
.transport-row + .transport-row {
margin-top: 11px;
}
#playButton {
min-width: 84px;
}
#stepButton {
width: 44px;
padding-right: 0;
padding-left: 0;
}
.speed-wrap {
flex: 1;
min-width: 0;
}
.speed-label {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#speed {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.status-pill {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 8px;
color: var(--green);
background: rgba(110, 231, 164, 0.08);
border: 1px solid rgba(110, 231, 164, 0.22);
border-radius: 999px;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.status-pill::before {
width: 6px;
height: 6px;
content: "";
background: currentColor;
border-radius: 50%;
box-shadow: 0 0 9px currentColor;
}
.status-pill.replay {
color: var(--yellow);
background: rgba(255, 209, 102, 0.08);
border-color: rgba(255, 209, 102, 0.25);
}
.status-pill.paused {
color: var(--muted);
background: rgba(120, 149, 163, 0.08);
border-color: rgba(120, 149, 163, 0.2);
}
#leftPanel {
position: absolute;
bottom: 18px;
left: 18px;
width: 230px;
padding: 15px;
border-radius: 12px;
}
#selectionTitle {
margin: 7px 0 3px;
font-size: 15px;
font-weight: 800;
}
#selectionMeta {
min-height: 34px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.hp-track {
height: 5px;
margin: 10px 0 13px;
overflow: hidden;
background: rgba(255, 255, 255, 0.08);
border-radius: 99px;
}
#hpFill {
width: 100%;
height: 100%;
background: var(--green);
border-radius: inherit;
transition: width 120ms linear;
}
.action-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.action-grid button {
padding: 9px 5px;
font-size: 10px;
font-weight: 700;
}
#buildButton.active {
color: #061719;
background: var(--cyan);
border-color: var(--cyan);
}
.help {
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
kbd {
padding: 1px 4px;
color: #b8d1dc;
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 3px;
font-size: 9px;
}
#replayPanel {
position: absolute;
right: 18px;
bottom: 18px;
width: 292px;
padding: 15px;
border-radius: 12px;
}
#seedInput {
width: 100%;
margin: 9px 0 8px;
padding: 10px 11px;
color: var(--text);
background: rgba(3, 10, 15, 0.6);
border: 1px solid var(--line);
border-radius: 8px;
outline: none;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 12px;
}
#seedInput:focus {
border-color: rgba(69, 217, 232, 0.55);
}
.replay-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.replay-actions button {
font-size: 10px;
font-weight: 800;
}
.replay-meta {
display: flex;
justify-content: space-between;
margin: 11px 0 8px;
color: var(--muted);
font-size: 9px;
}
#commandLog {
max-height: 102px;
overflow: hidden;
color: #90aab6;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 9px;
line-height: 1.75;
}
.log-line {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.log-tick {
display: inline-block;
width: 42px;
color: #527581;
}
#bottomBar {
position: absolute;
bottom: 18px;
left: 50%;
width: min(460px, calc(100vw - 560px));
min-width: 320px;
transform: translateX(-50%);
padding: 12px 14px;
border-radius: 12px;
}
.timeline-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
#clock {
color: var(--text);
font-size: 10px;
font-weight: 800;
}
.timeline-track {
height: 4px;
overflow: hidden;
background: rgba(255, 255, 255, 0.07);
border-radius: 99px;
}
#timelineFill {
width: 0;
height: 100%;
background: linear-gradient(90deg, var(--cyan-dark), var(--cyan));
border-radius: inherit;
transition: width 80ms linear;
}
#toast {
position: absolute;
top: 96px;
left: 50%;
max-width: 420px;
padding: 10px 14px;
color: #d9edf4;
background: rgba(7, 16, 24, 0.9);
border: 1px solid var(--line);
border-radius: 8px;
box-shadow: var(--shadow);
opacity: 0;
transform: translate(-50%, -8px);
transition: 180ms ease;
font-size: 11px;
text-align: center;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#outcome {
position: absolute;
top: 50%;
left: 50%;
display: none;
width: 340px;
padding: 26px;
border-radius: 15px;
text-align: center;
transform: translate(-50%, -50%);
}
#outcome h2 {
margin: 8px 0;
font-size: 26px;
}
#outcome p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.6;
}
@media (max-width: 1050px) {
#bottomBar {
width: 320px;
min-width: 320px;
bottom: 182px;
}
#replayPanel {
width: 255px;
}
#transport {
width: 255px;
}
}
@media (max-width: 760px) {
#brand,
#leftPanel,
#replayPanel {
display: none;
}
#resourceBar {
top: 12px;
left: 12px;
transform: none;
padding: 9px 11px;
}
#transport {
top: 12px;
right: 12px;
width: 218px;
padding: 10px;
}
#bottomBar {
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
min-width: 0;
transform: none;
}
}
</style>
</head>
<body>
<div id="ui">
<section id="brand" class="panel">
<div class="eyebrow">Tactical Systems / 07</div>
<h1>VOXEL COMMAND</h1>
<p>Deterministic battlefield simulation<br>Seed-driven strategy sandbox</p>
</section>
<section id="resourceBar" class="panel">
<div class="resource">
<div class="resource-icon">◆</div>
<div>
<div id="credits" class="resource-value mono">180</div>
<div class="resource-label">Credits</div>
</div>
</div>
<div class="resource">
<div class="resource-icon">▲</div>
<div>
<div id="supply" class="resource-value mono">10 / 20</div>
<div class="resource-label">Units</div>
</div>
</div>
<div class="resource">
<div class="resource-icon">✦</div>
<div>
<div id="kills" class="resource-value mono">0</div>
<div class="resource-label">Eliminations</div>
</div>
</div>
</section>
<section id="transport" class="panel">
<div class="transport-row">
<button id="playButton" class="primary">Ⅱ Pause</button>
<button id="stepButton" title="Advance one fixed simulation tick">▶|</button>
<div class="speed-wrap">
<div class="speed-label">
<span>Playback</span>
<span id="speedValue" class="mono">1.00×</span>
</div>
<input id="speed" type="range" min="0.25" max="4" step="0.25" value="1">
</div>
</div>
<div class="transport-row">
<span id="runStatus" class="status-pill">Live</span>
<span id="tickLabel" class="mono muted" style="margin-left:auto">T+ 00:00.0</span>
</div>
</section>
<section id="leftPanel" class="panel">
<div class="eyebrow">Selected Entity</div>
<div id="selectionTitle">No unit selected</div>
<div id="selectionMeta">Select a friendly unit or structure.</div>
<div class="hp-track"><div id="hpFill"></div></div>
<div class="action-grid">
<button id="buildButton">Build Turret · 60</button>
<button id="repairButton">Repair · 25</button>
</div>
<div class="help">
<kbd>LMB</kbd> select / move / attack<br>
<kbd>RMB</kbd> drag to orbit · wheel to zoom<br>
<kbd>WASD</kbd> pan · <kbd>Q/E</kbd> rotate<br>
<kbd>Space</kbd> pause · <kbd>B</kbd> build<br>
<kbd>R</kbd> deterministic replay
</div>
</section>
<section id="replayPanel" class="panel">
<div class="eyebrow">Replay Lab</div>
<input id="seedInput" value="1337" aria-label="Scenario seed" spellcheck="false">
<div class="replay-actions">
<button id="newButton">New Scenario</button>
<button id="replayButton" class="primary">Replay Run</button>
</div>
<div class="replay-meta">
<span id="commandCount">0 recorded commands</span>
<span id="seedLabel" class="mono">SEED 1337</span>
</div>
<div id="commandLog"></div>
</section>
<section id="bottomBar" class="panel">
<div class="timeline-row">
<span id="timelineLabel">Fixed-step simulation / 10 Hz</span>
<span id="clock" class="mono">00:00.0</span>
</div>
<div class="timeline-track"><div id="timelineFill"></div></div>
</section>
<div id="toast"></div>
<section id="outcome" class="panel">
<div class="eyebrow">Simulation Complete</div>
<h2 id="outcomeTitle">Victory</h2>
<p id="outcomeText"></p>
</section>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
const GRID = 18;
const FIXED_DT = 0.1;
const TEAM_PLAYER = "player";
const TEAM_ENEMY = "enemy";
const PLAYER_BASE = { x: 4, z: 13 };
const ENEMY_BASE = { x: 13, z: 4 };
const ui = {
brand: document.querySelector("#brand"),
credits: document.querySelector("#credits"),
supply: document.querySelector("#supply"),
kills: document.querySelector("#kills"),
play: document.querySelector("#playButton"),
step: document.querySelector("#stepButton"),
speed: document.querySelector("#speed"),
speedValue: document.querySelector("#speedValue"),
status: document.querySelector("#runStatus"),
tickLabel: document.querySelector("#tickLabel"),
timeline: document.querySelector("#timelineFill"),
timelineLabel: document.querySelector("#timelineLabel"),
clock: document.querySelector("#clock"),
selectionTitle: document.querySelector("#selectionTitle"),
selectionMeta: document.querySelector("#selectionMeta"),
hpFill: document.querySelector("#hpFill"),
build: document.querySelector("#buildButton"),
repair: document.querySelector("#repairButton"),
seed: document.querySelector("#seedInput"),
newButton: document.querySelector("#newButton"),
replay: document.querySelector("#replayButton"),
commandCount: document.querySelector("#commandCount"),
seedLabel: document.querySelector("#seedLabel"),
commandLog: document.querySelector("#commandLog"),
toast: document.querySelector("#toast"),
outcome: document.querySelector("#outcome"),
outcomeTitle: document.querySelector("#outcomeTitle"),
outcomeText: document.querySelector("#outcomeText")
};
const state = {
tick: 0,
elapsed: 0,
paused: false,
speed: 1,
credits: 180,
kills: 0,
selected: null,
buildMode: false,
commands: [],
events: [],
replaying: false,
replayEndTick: 0,
outcome: null
};
const world = {
heights: new Float32Array(GRID * GRID),
staticBlocked: new Set(),
units: [],
buildings: [],
resources: [],
visible: new Set(),
explored: new Set()
};
let currentSeed = "1337";
let simulationRandom;
let replayCursor = 0;
let accumulator = 0;
let nextUnitId = 1;
let nextBuildingId = 1;
let toastTimer = 0;
// -------------------------------------------------------------------------
// Seeded random functions. Simulation randomness is separate from map visuals.
// -------------------------------------------------------------------------
function hashSeed(value) {
const text = String(value);
let hash = 2166136261 >>> 0;
for (let i = 0; i < text.length; i++) {
hash ^= text.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
function mulberry32(seed) {
let value = seed >>> 0;
return function () {
value += 0x6D2B79F5;
let result = value;
result = Math.imul(result ^ (result >>> 15), result | 1);
result ^= result + Math.imul(result ^ (result >>> 7), result | 61);
return ((result ^ (result >>> 14)) >>> 0) / 4294967296;
};
}
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071018);
scene.fog = new THREE.FogExp2(0x071018, 0.009);
const camera = new THREE.OrthographicCamera(-16, 16, 11, -11, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
document.body.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0x9ee9ff, 0x18201b, 2.2);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffe4bc, 3.2);
sun.position.set(-12, 24, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 18;
sun.shadow.camera.bottom = -18;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 60;
sun.shadow.bias = -0.0008;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x39c9ff, 1.3);
rim.position.set(15, 9, -14);
scene.add(rim);
const mapGroup = new THREE.Group();
const dynamicGroup = new THREE.Group();
const effectsGroup = new THREE.Group();
scene.add(mapGroup, dynamicGroup, effectsGroup);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const healthPlane = new THREE.PlaneGeometry(1, 0.1);
const materials = {
player: new THREE.MeshStandardMaterial({
color: 0x3ec7d6,
roughness: 0.48,
metalness: 0.2
}),
playerDark: new THREE.MeshStandardMaterial({
color: 0x174c5a,
roughness: 0.62,
metalness: 0.18
}),
enemy: new THREE.MeshStandardMaterial({
color: 0xf27643,
roughness: 0.52,
metalness: 0.18
}),
enemyDark: new THREE.MeshStandardMaterial({
color: 0x612c1e,
roughness: 0.65,
metalness: 0.15
}),
metal: new THREE.MeshStandardMaterial({
color: 0x263945,
roughness: 0.45,
metalness: 0.65
}),
dark: new THREE.MeshStandardMaterial({
color: 0x101b23,
roughness: 0.74,
metalness: 0.2
}),
rock: new THREE.MeshStandardMaterial({
color: 0x46515a,
roughness: 0.92
}),
crystal: new THREE.MeshStandardMaterial({
color: 0x52ddff,
emissive: 0x087d9c,
emissiveIntensity: 1.4,
roughness: 0.28,
metalness: 0.25
}),
yellow: new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0x6b4d00,
emissiveIntensity: 0.45
}),
healthBack: new THREE.MeshBasicMaterial({
color: 0x35151c,
transparent: true,
opacity: 0.9,
depthTest: false
}),
health: new THREE.MeshBasicMaterial({
color: 0x6ee7a4,
depthTest: false
}),
hoverValid: new THREE.MeshBasicMaterial({
color: 0x45d9e8,
transparent: true,
opacity: 0.52,
depthWrite: false
}),
hoverInvalid: new THREE.MeshBasicMaterial({
color: 0xff6577,
transparent: true,
opacity: 0.52,
depthWrite: false
})
};
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x081219,
roughness: 1
});
const ground = new THREE.Mesh(new THREE.PlaneGeometry(180, 180), groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.58;
ground.receiveShadow = true;
scene.add(ground);
const hoverMesh = new THREE.Mesh(unitBox, materials.hoverValid);
hoverMesh.scale.set(0.88, 0.08, 0.88);
hoverMesh.visible = false;
hoverMesh.renderOrder = 4;
scene.add(hoverMesh);
// -------------------------------------------------------------------------
// Coordinate helpers
// -------------------------------------------------------------------------
function gridKey(x, z) {
return `${x},${z}`;
}
function worldX(x) {
return x - (GRID - 1) / 2;
}
function worldZ(z) {
return z - (GRID - 1) / 2;
}
function tileIndex(x, z) {
return z * GRID + x;
}
function inBounds(x, z) {
return x >= 0 && z >= 0 && x < GRID && z < GRID;
}
function terrainHeight(x, z) {
if (!inBounds(x, z)) return 0;
return world.heights[tileIndex(x, z)];
}
function tileKeyForPosition(position) {
return gridKey(Math.round(position.x), Math.round(position.z));
}
function distanceBetween(a, b) {
return Math.hypot(a.x - b.x, a.z - b.z);
}
// -------------------------------------------------------------------------
// Mesh helpers
// -------------------------------------------------------------------------
function clearGroup(group) {
while (group.children.length) {
group.remove(group.children[group.children.length - 1]);
}
}
function addBox(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(size[0], size[1], size[2]);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function createHealthBar() {
const group = new THREE.Group();
const back = new THREE.Mesh(healthPlane, materials.healthBack);
back.renderOrder = 20;
group.add(back);
const fill = new THREE.Mesh(healthPlane, materials.health);
fill.position.z = 0.01;
fill.renderOrder = 21;
group.add(fill);
group.userData.fill = fill;
scene.add(group);
return group;
}
function updateHealthBar(bar, x, y, z, ratio, color) {
const clamped = Math.max(0, Math.min(1, ratio));
bar.visible = true;
bar.position.set(x, y, z);
bar.quaternion.copy(camera.quaternion);
bar.scale.set(0.72, 1, 1);
const fill = bar.userData.fill;
fill.scale.x = clamped;
fill.position.x = -(1 - clamped) * 0.5;
fill.material = color === "enemy" ? materials.healthBack : materials.health;
if (color === "enemy") {
fill.material = new THREE.MeshBasicMaterial({
color: 0xff6577,
depthTest: false
});
}
}
// -------------------------------------------------------------------------
// Scenario construction
// -------------------------------------------------------------------------
function initializeScenario(seed, clearCommands = true) {
currentSeed = String(seed);
const seedHash = hashSeed(currentSeed);
const mapRandom = mulberry32(seedHash);
simulationRandom = mulberry32(seedHash ^ 0x9e3779b9);
state.tick = 0;
state.elapsed = 0;
state.paused = false;
state.speed = Number(ui.speed.value);
state.credits = 180;
state.kills = 0;
state.selected = null;
state.buildMode = false;
state.replaying = false;
state.replayEndTick = 0;
state.outcome = null;
state.events = [];
if (clearCommands) {
state.commands = [];
}
replayCursor = 0;
accumulator = 0;
nextUnitId = 1;
nextBuildingId = 1;
world.units.length = 0;
world.buildings.length = 0;
world.resources.length = 0;
world.staticBlocked.clear();
world.visible.clear();
world.explored.clear();
clearGroup(mapGroup);
clearGroup(dynamicGroup);
clearGroup(effectsGroup);
buildTerrain(mapRandom);
buildResources(mapRandom);
buildStructures();
buildUnits();
updateVision();
ui.seed.value = currentSeed;
ui.seedLabel.textContent = `SEED ${currentSeed}`;
ui.outcome.style.display = "none";
ui.build.classList.remove("active");
addEvent(`Scenario ${currentSeed} initialized.`);
updateUI();
}
function buildTerrain(random) {
for (let z = 0; z < GRID; z++) {
for (let x = 0; x < GRID; x++) {
const index = tileIndex(x, z);
world.heights[index] = 0.52 + random() * 0.42;
const nearPlayer =
Math.abs(x - PLAYER_BASE.x) < 3 &&
Math.abs(z - PLAYER_BASE.z) < 3;
const nearEnemy =
Math.abs(x - ENEMY_BASE.x) < 3 &&
Math.abs(z - ENEMY_BASE.z) < 3;
if (!nearPlayer && !nearEnemy && random() < 0.075) {
world.staticBlocked.add(gridKey(x, z));
}
}
}
const terrain = new THREE.InstancedMesh(
unitBox,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.94,
metalness: 0.02
}),
GRID * GRID
);
terrain.castShadow = false;
terrain.receiveShadow = true;
const dummy = new THREE.Object3D();
const color = new THREE.Color();
for (let z = 0; z < GRID; z++) {
for (let x = 0; x < GRID; x++) {
const index = tileIndex(x, z);
const height = world.heights[index];
const variation = (random() - 0.5) * 0.045;
dummy.position.set(worldX(x), height / 2, worldZ(z));
dummy.scale.set(0.985, height, 0.985);
dummy.updateMatrix();
terrain.setMatrixAt(index, dummy.matrix);
color.setHSL(
0.37 + variation,
0.17 + random() * 0.06,
0.235 + random() * 0.045
);
terrain.setColorAt(index, color);
}
}
terrain.instanceMatrix.needsUpdate = true;
terrain.instanceColor.needsUpdate = true;
terrain.userData.terrain = true;
mapGroup.add(terrain);
const slab = new THREE.Mesh(
new THREE.BoxGeometry(GRID + 0.6, 1, GRID + 0.6),
materials.dark
);
slab.position.y = -0.62;
slab.receiveShadow = true;
mapGroup.add(slab);
const linePoints = [];
for (let z = 0; z <= GRID; z++) {
for (let x = 0; x < GRID; x++) {
const y = world.heights[tileIndex(x, z)] + 0.012;
linePoints.push(
new THREE.Vector3(worldX(x) - 0.5, y, worldZ(z) - 0.5),
new THREE.Vector3(worldX(x) + 0.5, y, worldZ(z) - 0.5)
);
}
}
for (let x = 0; x <= GRID; x++) {
for (let z = 0; z < GRID; z++) {
const y = world.heights[tileIndex(x, z)] + 0.012;
linePoints.push(
new THREE.Vector3(worldX(x) - 0.5, y, worldZ(z) - 0.5),
new THREE.Vector3(worldX(x) - 0.5, y, worldZ(z) + 0.5)
);
}
}
const gridGeometry = new THREE.BufferGeometry().setFromPoints(linePoints);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x9dd8e7,
transparent: true,
opacity: 0.105
})
);
mapGroup.add(grid);
for (const key of world.staticBlocked) {
const [x, z] = key.split(",").map(Number);
const rockGroup = new THREE.Group();
const height = terrainHeight(x, z);
addBox(
rockGroup,
[0.62, 0.64, 0.66],
[0, 0.32, 0],
materials.rock
);
addBox(
rockGroup,
[0.44, 0.32, 0.48],
[0.08, 0.72, -0.04],
materials.rock
);
rockGroup.position.set(worldX(x), height, worldZ(z));
rockGroup.rotation.y = (x * 13 + z * 7) % 5;
mapGroup.add(rockGroup);
}
}
function buildResources(random) {
const count = 22;
for (let i = 0; i < count; i++) {
let x = 0;
let z = 0;
do {
x = Math.floor(random() * GRID);
z = Math.floor(random() * GRID);
} while (
world.staticBlocked.has(gridKey(x, z)) ||
(x === PLAYER_BASE.x && z === PLAYER_BASE.z) ||
(x === ENEMY_BASE.x && z === ENEMY_BASE.z)
);
const group = new THREE.Group();
const crystal = new THREE.Mesh(
new THREE.OctahedronGeometry(0.24, 0),
materials.crystal
);
crystal.scale.y = 1.45;
crystal.position.y = 0.36;
crystal.rotation.y = random() * Math.PI;
crystal.castShadow = true;
group.add(crystal);
const base = addBox(
group,
[0.55, 0.12, 0.55],
[0, 0.06, 0],
materials.metal
);
base.rotation.y = 0.25;
group.position.set(worldX(x), terrainHeight(x, z), worldZ(z));
mapGroup.add(group);
world.resources.push({ x, z, group });
}
}
function buildStructures() {
createBuilding("base", TEAM_PLAYER, PLAYER_BASE.x, PLAYER_BASE.z);
createBuilding("base", TEAM_ENEMY, ENEMY_BASE.x, ENEMY_BASE.z);
createBuilding("turret", TEAM_PLAYER, PLAYER_BASE.x + 2, PLAYER_BASE.z - 1);
createBuilding("turret", TEAM_ENEMY, ENEMY_BASE.x - 2, ENEMY_BASE.z + 1);
}
function createBuilding(type, team, x, z) {
const isBase = type === "base";
const maxHp = isBase ? 520 : 170;
const building = {
id: `b${nextBuildingId++}`,
type,
team,
x,
z,
hp: maxHp,
maxHp,
alive: true,
group: new THREE.Group(),
healthBar: createHealthBar(),
head: null
};
building.group.userData.buildingId = building.id;
const mainMaterial = team === TEAM_PLAYER ? materials.player : materials.enemy;
const darkMaterial = team === TEAM_PLAYER ? materials.playerDark : materials.enemyDark;
if (isBase) {
addBox(building.group, [0.86, 0.46, 0.86], [0, 0.23, 0], darkMaterial);
addBox(building.group, [0.68, 0.58, 0.68], [0, 0.74, 0], mainMaterial);
addBox(building.group, [0.82, 0.14, 0.82], [0, 1.08, 0], darkMaterial);
addBox(building.group, [0.18, 0.54, 0.18], [0, 1.37, 0], mainMaterial);
const beacon = addBox(
building.group,
[0.26, 0.26, 0.26],
[0, 1.79, 0],
materials.crystal
);
beacon.rotation.y = Math.PI / 4;
} else {
addBox(building.group, [0.72, 0.28, 0.72], [0, 0.14, 0], darkMaterial);
addBox(building.group, [0.36, 0.42, 0.36], [0, 0.45, 0], mainMaterial);
const head = new THREE.Group();
addBox(head, [0.56, 0.28, 0.56], [0, 0, 0], darkMaterial);
addBox(head, [0.18, 0.18, 0.78], [0, 0.03, 0.28], mainMaterial);
head.position.y = 0.79;
building.group.add(head);
building.head = head;
}
building.group.position.set(
worldX(x),
terrainHeight(x, z),
worldZ(z)
);
dynamicGroup.add(building.group);
world.buildings.push(building);
return building;
}
function buildUnits() {
const playerPositions = [
[4, 11], [3, 11], [2, 12], [5, 14], [2, 14],
[6, 14], [4, 15], [7, 13], [1, 13], [6, 11]
];
const enemyPositions = [
[13, 3], [14, 3], [12, 2], [13, 5], [14, 5],
[11, 3], [15, 4], [12, 6]
];
for (const [x, z] of playerPositions) {
createUnit(TEAM_PLAYER, x, z);
}
for (const [x, z] of enemyPositions) {
createUnit(TEAM_ENEMY, x, z);
}
}
function createUnit(team, x, z) {
const isScout = nextUnitId % 4 === 0;
const maxHp = isScout ? 62 : 88;
const unit = {
id: `u${nextUnitId++}`,
team,
type: isScout ? "Scout" : "Rifle",
x,
z,
hp: maxHp,
maxHp,
alive: true,
cooldown: 0,
order: null,
path: [],
repathTimer: 0,
group: new THREE.Group(),
model: new THREE.Group(),
healthBar: createHealthBar(),
selectionRing: null
};
const mainMaterial = team === TEAM_PLAYER ? materials.player : materials.enemy;
const darkMaterial = team === TEAM_PLAYER ? materials.playerDark : materials.enemyDark;
addBox(unit.model, [0.44, 0.52, 0.38], [0, 0.39, 0], darkMaterial);
addBox(unit.model, [0.37, 0.34, 0.34], [0, 0.82, 0], mainMaterial);
addBox(unit.model, [0.16, 0.12, 0.06], [0, 0.84, -0.2], materials.dark);
addBox(unit.model, [0.12, 0.12, 0.56], [0.19, 0.51, -0.2], materials.metal);
addBox(unit.model, [0.1, 0.35, 0.12], [-0.12, 0.35, 0.2], darkMaterial);
addBox(unit.model, [0.1, 0.35, 0.12], [0.12, 0.35, 0.2], darkMaterial);
if (isScout) {
unit.model.scale.setScalar(0.86);
}
unit.group.userData.unitId = unit.id;
unit.group.add(unit.model);
unit.group.position.set(worldX(x), terrainHeight(x, z), worldZ(z));
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.43, 0.045, 5, 18),
materials.yellow
);
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.05;
ring.visible = false;
unit.group.add(ring);
unit.selectionRing = ring;
dynamicGroup.add(unit.group);
world.units.push(unit);
return unit;
}
// -------------------------------------------------------------------------
// Visibility
// -------------------------------------------------------------------------
function updateVision() {
world.visible.clear();
const reveal = (x, z, radius) => {
for (let dz = -radius; dz <= radius; dz++) {
for (let dx = -radius; dx <= radius; dx++) {
if (dx * dx + dz * dz > radius * radius) continue;
const tx = Math.round(x) + dx;
const tz = Math.round(z) + dz;
if (!inBounds(tx, tz)) continue;
const key = gridKey(tx, tz);
world.visible.add(key);
world.explored.add(key);
}
}
};
for (const unit of world.units) {
if (unit.team === TEAM_PLAYER && unit.alive) {
reveal(unit.x, unit.z, 4.2);
}
}
for (const building of world.buildings) {
if (building.team === TEAM_PLAYER && building.alive) {
reveal(building.x, building.z, 4.8);
}
}
}
// -------------------------------------------------------------------------
// Pathfinding
// -------------------------------------------------------------------------
function isBuildingAt(x, z, ignoreId = null) {
return world.buildings.some(
(building) =>
building.alive &&
building.x === x &&
building.z === z &&
building.id !== ignoreId
);
}
function isBlocked(x, z, ignoreId = null) {
if (!inBounds(x, z)) return true;
if (world.staticBlocked.has(gridKey(x, z))) return true;
if (isBuildingAt(x, z, ignoreId)) return true;
return false;
}
function nearestOpenTile(x, z) {
if (!isBlocked(x, z)) return { x, z };
const candidates = [];
for (let radius = 1; radius <= 3; radius++) {
for (let dz = -radius; dz <= radius; dz++) {
for (let dx = -radius; dx <= radius; dx++) {
if (Math.max(Math.abs(dx), Math.abs(dz)) !== radius) continue;
const tx = x + dx;
const tz = z + dz;
if (!isBlocked(tx, tz)) {
candidates.push({ x: tx, z: tz });
}
}
}
if (candidates.length) {
candidates.sort(
(a, b) =>
Math.abs(a.x - x) + Math.abs(a.z - z) -
(Math.abs(b.x - x) + Math.abs(b.z - z))
);
return candidates[0];
}
}
return null;
}
function findPath(startX, startZ, goalX, goalZ) {
const goal = nearestOpenTile(goalX, goalZ);
if (!goal) return [];
const startKey = gridKey(startX, startZ);
const goalKey = gridKey(goal.x, goal.z);
if (startKey === goalKey) return [];
const open = [{
x: startX,
z: startZ,
g: 0,
h: Math.abs(startX - goal.x) + Math.abs(startZ - goal.z),
key: startKey
}];
const cameFrom = new Map();
const closed = new Set();
const directions = [
[0, -1], [1, 0], [0, 1], [-1, 0]
];
while (open.length) {
open.sort((a, b) => {
const fDiff = (a.g + a.h) - (b.g + b.h);
if (fDiff !== 0) return fDiff;
const hDiff = a.h - b.h;
if (hDiff !== 0) return hDiff;
return a.key.localeCompare(b.key);
});
const current = open.shift();
if (current.key === goalKey) {
const path = [];
let key = goalKey;
let node = { x: goal.x, z: goal.z };
while (key !== startKey) {
path.push(node);
const previous = cameFrom.get(key);
if (!previous) break;
node = previous;
key = previous.key;
}
path.reverse();
return path;
}
if (closed.has(current.key)) continue;
closed.add(current.key);
for (const [dx, dz] of directions) {
const nx = current.x + dx;
const nz = current.z + dz;
if (!inBounds(nx, nz) || isBlocked(nx, nz)) continue;
const key = gridKey(nx, nz);
if (closed.has(key)) continue;
const g = current.g + 1;
const old = open.find((entry) => entry.key === key);
if (!old || g < old.g) {
const node = {
x: nx,
z: nz,
g,
h: Math.abs(nx - goal.x) + Math.abs(nz - goal.z),
key
};
cameFrom.set(key, current);
if (old) {
open.splice(open.indexOf(old), 1);
}
open.push(node);
}
}
}
return [];
}
// -------------------------------------------------------------------------
// Commands and deterministic recording
// -------------------------------------------------------------------------
function submitCommand(command) {
if (state.replaying) return;
command.tick = state.tick;
state.commands.push(command);
executeCommand(command);
updateUI();
}
function executeCommand(command) {
if (command.type === "select") {
const unit = getUnit(command.id);
if (unit) state.selected = unit.id;
return;
}
if (command.type === "move") {
const unit = getUnit(command.id);
if (!unit || !unit.alive || unit.team !== TEAM_PLAYER) return;
const path = findPath(
Math.round(unit.x),
Math.round(unit.z),
command.x,
command.z
);
unit.order = { kind: "move" };
unit.path = path;
unit.repathTimer = 0;
return;
}
if (command.type === "attack") {
const unit = getUnit(command.id);
const target = getUnit(command.targetId);
if (
!unit ||
!target ||
!unit.alive ||
!target.alive ||
unit.team !== TEAM_PLAYER
) return;
unit.order = { kind: "attack", targetId: target.id };
unit.path = [];
unit.repathTimer = 0;
return;
}
if (command.type === "build") {
if (state.credits < 60) {
addEvent("Build rejected: insufficient credits.");
return;
}
if (!canBuildAt(command.x, command.z)) {
addEvent("Build rejected: location occupied.");
return;
}
state.credits -= 60;
createBuilding("turret", TEAM_PLAYER, command.x, command.z);
addEvent(`Turret deployed at ${command.x}, ${command.z}.`);
return;
}
if (command.type === "repair") {
const building = getBuilding(command.id);
if (
!building ||
!building.alive ||
building.team !== TEAM_PLAYER ||
building.hp >= building.maxHp ||
state.credits < 25
) return;
state.credits -= 25;
building.hp = Math.min(building.maxHp, building.hp + 75);
addEvent("Structure integrity restored.");
}
}
function canBuildAt(x, z) {
if (!inBounds(x, z) || isBlocked(x, z)) return false;
return !world.units.some(
(unit) =>
unit.alive &&
Math.round(unit.x) === x &&
Math.round(unit.z) === z
);
}
function getUnit(id) {
return world.units.find((unit) => unit.id === id);
}
function getBuilding(id) {
return world.buildings.find((building) => building.id === id);
}
// -------------------------------------------------------------------------
// Simulation
// -------------------------------------------------------------------------
function simulationStep() {
if (state.replaying) {
while (
replayCursor < state.commands.length &&
state.commands[replayCursor].tick <= state.tick
) {
executeCommand(state.commands[replayCursor]);
replayCursor++;
}
}
if (state.tick % 10 === 0) {
state.credits += 2;
}
for (const unit of world.units) {
if (!unit.alive) continue;
updateUnit(unit);
}
for (const building of world.buildings) {
if (!building.alive) continue;
updateBuilding(building);
}
updateVision();
state.tick++;
state.elapsed = state.tick * FIXED_DT;
const playerBase = world.buildings.find(
(building) => building.type === "base" && building.team === TEAM_PLAYER
);
const enemyBase = world.buildings.find(
(building) => building.type === "base" && building.team === TEAM_ENEMY
);
if (enemyBase && !enemyBase.alive) {
state.outcome = "victory";
} else if (playerBase && !playerBase.alive) {
state.outcome = "defeat";
}
if (state.outcome) {
state.paused = true;
showOutcome();
}
}
function updateUnit(unit) {
unit.cooldown = Math.max(0, unit.cooldown - FIXED_DT);
unit.repathTimer--;
if (unit.order?.kind === "attack") {
const target = getUnit(unit.order.targetId);
if (!target || !target.alive) {
unit.order = null;
unit.path = [];
} else {
const distance = distanceBetween(unit, target);
if (distance <= 1.45) {
unit.path = [];
attackUnit(unit, target);
} else {
if (!unit.path.length || unit.repathTimer <= 0) {
unit.path = findPath(
Math.round(unit.x),
Math.round(unit.z),
Math.round(target.x),
Math.round(target.z)
);
unit.repathTimer = 14;
}
moveAlongPath(unit);
}
}
} else if (unit.order?.kind === "move") {
const arrived = moveAlongPath(unit);
if (arrived) unit.order = null;
}
if (unit.team === TEAM_PLAYER) {
const visibleEnemy = world.units.find(
(enemy) =>
enemy.alive &&
enemy.team === TEAM_ENEMY &&
world.visible.has(tileKeyForPosition(enemy)) &&
distanceBetween(unit, enemy) <= 1.45
);
if (visibleEnemy) attackUnit(unit, visibleEnemy);
} else {
updateEnemyAI(unit);
}
}
function updateEnemyAI(unit) {
if (unit.order) return;
const targets = [];
for (const candidate of world.units) {
if (
candidate.alive &&
candidate.team === TEAM_PLAYER &&
distanceBetween(unit, candidate) <= 7
) {
targets.push(candidate);
}
}
for (const building of world.buildings) {
if (
building.alive &&
building.team === TEAM_PLAYER &&
distanceBetween(unit, building) <= 6.5
) {
targets.push(building);
}
}
if (!targets.length) return;
targets.sort(
(a, b) =>
distanceBetween(unit, a) - distanceBetween(unit, b) ||
a.id.localeCompare(b.id)
);
const target = targets[0];
const distance = distanceBetween(unit, target);
if (distance <= 1.45) {
attackUnit(unit, target);
} else {
unit.path = findPath(
Math.round(unit.x),
Math.round(unit.z),
Math.round(target.x),
Math.round(target.z)
);
unit.order = { kind: "move" };
unit.repathTimer = 12;
}
}
function moveAlongPath(unit) {
if (!unit.path.length) return true;
const speed = unit.type === "Scout" ? 2.8 : 2.15;
let remaining = speed * FIXED_DT;
while (remaining > 0 && unit.path.length) {
const next = unit.path[0];
const dx = next.x - unit.x;
const dz = next.z - unit.z;
const distance = Math.hypot(dx, dz);
if (distance <= remaining || distance < 0.0001) {
unit.x = next.x;
unit.z = next.z;
unit.path.shift();
remaining -= distance;
} else {
unit.x += (dx / distance) * remaining;
unit.z += (dz / distance) * remaining;
remaining = 0;
}
}
return unit.path.length === 0;
}
function attackUnit(attacker, target) {
if (attacker.cooldown > 0 || !target.alive) return;
const damage = 9 + Math.floor(simulationRandom() * 7);
attacker.cooldown = 0.72 + simulationRandom() * 0.28;
target.hp -= damage;
createTracer(attacker, target);
if (target.hp <= 0) {
target.alive = false;
target.hp = 0;
target.group.visible = false;
target.healthBar.visible = false;
if (attacker.team === TEAM_PLAYER) {
state.credits += 12;
state.kills++;
addEvent(`${target.type} eliminated by ${attacker.type}.`);
}
}
}
function updateBuilding(building) {
const range = building.type === "turret" ? 4.4 : 3.1;
const target = world.units.find(
(unit) =>
unit.alive &&
unit.team !== building.team &&
distanceBetween(building, unit) <= range
);
if (!target) return;
if (building.head) {
const targetAngle = Math.atan2(
target.x - building.x,
target.z - building.z
);
building.head.rotation.y +=
Math.atan2(
Math.sin(targetAngle - building.head.rotation.y),
Math.cos(targetAngle - building.head.rotation.y)
) * 0.28;
}
if (building.cooldown > 0) {
building.cooldown -= FIXED_DT;
return;
}
building.cooldown = building.type === "turret" ? 1.05 : 1.4;
const damage = building.type === "turret"
? 17 + Math.floor(simulationRandom() * 5)
: 10 + Math.floor(simulationRandom() * 4);
target.hp -= damage;
createTracer(building, target);
if (target.hp <= 0) {
target.alive = false;
target.group.visible = false;
target.healthBar.visible = false;
if (building.team === TEAM_PLAYER) {
state.credits += 12;
state.kills++;
addEvent(`${target.type} destroyed by friendly structure.`);
}
}
}
// -------------------------------------------------------------------------
// Visual effects
// -------------------------------------------------------------------------
function createTracer(source, target) {
const start = new THREE.Vector3(
worldX(source.x),
terrainHeight(Math.round(source.x), Math.round(source.z)) + 0.75,
worldZ(source.z)
);
const end = new THREE.Vector3(
worldX(target.x),
terrainHeight(Math.round(target.x), Math.round(target.z)) + 0.65,
worldZ(target.z)
);
const geometry = new THREE.BufferGeometry().setFromPoints([start, end]);
const material = new THREE.LineBasicMaterial({
color: source.team === TEAM_PLAYER ? 0x8ff6ff : 0xffa35f,
transparent: true,
opacity: 0.95
});
const line = new THREE.Line(geometry, material);
effectsGroup.add(line);
world.resources.tracers = world.resources.tracers || [];
world.resources.tracers.push({ line, life: 0.18 });
}
function updateEffects(dt) {
const tracers = world.resources.tracers || [];
for (let i = tracers.length - 1; i >= 0; i--) {
const tracer = tracers[i];
tracer.life -= dt;
tracer.line.material.opacity = Math.max(0, tracer.life / 0.18);
if (tracer.life <= 0) {
effectsGroup.remove(tracer.line);
tracer.line.geometry.dispose();
tracer.line.material.dispose();
tracers.splice(i, 1);
}
}
}
function updateVisuals(time) {
for (const unit of world.units) {
if (!unit.alive) continue;
const visible =
unit.team === TEAM_PLAYER ||
world.visible.has(tileKeyForPosition(unit));
unit.group.visible = visible;
const x = Math.round(unit.x);
const z = Math.round(unit.z);
const height = terrainHeight(x, z);
const bob = Math.sin(time * 7 + unit.id.length + unit.x) * 0.018;
unit.group.position.set(worldX(unit.x), height + bob, worldZ(unit.z));
unit.model.rotation.y = Math.atan2(
unit.path[0]?.x - unit.x || 0,
unit.path[0]?.z - unit.z || 0
);
unit.selectionRing.visible =
state.selected === unit.id &&
unit.team === TEAM_PLAYER;
if (visible) {
updateHealthBar(
unit.healthBar,
worldX(unit.x),
height + 1.35,
worldZ(unit.z),
unit.hp / unit.maxHp,
unit.team
);
} else {
unit.healthBar.visible = false;
}
}
for (const building of world.buildings) {
if (!building.alive) continue;
const visible =
building.team === TEAM_PLAYER ||
world.explored.has(gridKey(building.x, building.z));
building.group.visible = visible;
if (visible) {
updateHealthBar(
building.healthBar,
worldX(building.x),
terrainHeight(building.x, building.z) + 1.95,
worldZ(building.z),
building.hp / building.maxHp,
building.team
);
} else {
building.healthBar.visible = false;
}
}
for (const resource of world.resources) {
resource.group.visible = world.explored.has(gridKey(resource.x, resource.z));
resource.group.rotation.y = time * 0.45;
resource.group.children[0].position.y = 0.36 + Math.sin(time * 2 + resource.x) * 0.04;
}
}
// -------------------------------------------------------------------------
// Camera controls implemented without addons
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0, 0),
yaw: Math.PI / 4,
pitch: 0.82,
zoom: 1
};
const keys = new Set();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragging = false;
let pointerDownX = 0;
let pointerDownY = 0;
let lastPointerX = 0;
let lastPointerY = 0;
function updateCamera(dt) {
const forward = new THREE.Vector3(
-Math.sin(cameraState.yaw),
0,
-Math.cos(cameraState.yaw)
);
const right = new THREE.Vector3(
Math.cos(cameraState.yaw),
0,
-Math.sin(cameraState.yaw)
);
const panSpeed = 8 * dt / cameraState.zoom;
if (keys.has("KeyW") || keys.has("ArrowUp")) {
cameraState.target.addScaledVector(forward, panSpeed);
}
if (keys.has("KeyS") || keys.has("ArrowDown")) {
cameraState.target.addScaledVector(forward, -panSpeed);
}
if (keys.has("KeyD") || keys.has("ArrowRight")) {
cameraState.target.addScaledVector(right, panSpeed);
}
if (keys.has("KeyA") || keys.has("ArrowLeft")) {
cameraState.target.addScaledVector(right, -panSpeed);
}
if (keys.has("KeyQ")) cameraState.yaw += dt * 0.9;
if (keys.has("KeyE")) cameraState.yaw -= dt * 0.9;
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -9, 9);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -9, 9);
const radius = 30;
camera.position.set(
cameraState.target.x + Math.sin(cameraState.yaw) * Math.cos(cameraState.pitch) * radius,
cameraState.target.y + Math.sin(cameraState.pitch) * radius,
cameraState.target.z + Math.cos(cameraState.yaw) * Math.cos(cameraState.pitch) * radius
);
camera.lookAt(cameraState.target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const halfHeight = 11;
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
window.addEventListener("resize", resize);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDownX = event.clientX;
pointerDownY = event.clientY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (event.button === 2 || event.button === 1) {
dragging = true;
renderer.domElement.setPointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (dragging) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.004,
0.35,
1.35
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
} else {
updateHover(event);
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (dragging) {
dragging = false;
try {
renderer.domElement.releasePointerCapture(event.pointerId);
} catch {}
return;
}
const moved = Math.hypot(
event.clientX - pointerDownX,
event.clientY - pointerDownY
);
if (event.button === 0 && moved < 5) {
handleWorldClick(event);
}
});
renderer.domElement.addEventListener("pointerleave", () => {
hoverMesh.visible = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * (event.deltaY > 0 ? 0.9 : 1.1),
0.62,
2.5
);
},
{ passive: false }
);
function setPointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function getVisibleUnitHit(event) {
setPointerFromEvent(event);
const groups = world.units
.filter((unit) => unit.alive && unit.group.visible)
.map((unit) => unit.group);
const hits = raycaster.intersectObjects(groups, true);
for (const hit of hits) {
let object = hit.object;
while (object) {
if (object.userData.unitId) {
return { unit: getUnit(object.userData.unitId), point: hit.point };
}
object = object.parent;
}
}
return null;
}
function getBuildingHit(event) {
setPointerFromEvent(event);
const groups = world.buildings
.filter((building) => building.alive && building.group.visible)
.map((building) => building.group);
const hits = raycaster.intersectObjects(groups, true);
for (const hit of hits) {
let object = hit.object;
while (object) {
if (object.userData.buildingId) {
return {
building: getBuilding(object.userData.buildingId),
point: hit.point
};
}
object = object.parent;
}
}
return null;
}
function getTerrainHit(event) {
setPointerFromEvent(event);
const terrain = mapGroup.children.find(
(child) => child.userData?.terrain
);
if (!terrain) return null;
const hits = raycaster.intersectObject(terrain, false);
if (!hits.length) return null;
const index = hits[0].instanceId;
if (index === undefined) return null;
return {
x: index % GRID,
z: Math.floor(index / GRID),
point: hits[0].point
};
}
function updateHover(event) {
const tile = getTerrainHit(event);
if (!tile) {
hoverMesh.visible = false;
return;
}
hoverMesh.visible = true;
hoverMesh.position.set(
worldX(tile.x),
terrainHeight(tile.x, tile.z) + 0.08,
worldZ(tile.z)
);
if (state.buildMode) {
hoverMesh.material = canBuildAt(tile.x, tile.z) && state.credits >= 60
? materials.hoverValid
: materials.hoverInvalid;
} else {
hoverMesh.material = materials.hoverValid;
}
}
function handleWorldClick(event) {
if (state.outcome || state.replaying) return;
const unitHit = getVisibleUnitHit(event);
if (unitHit) {
const clicked = unitHit.unit;
const selected = getUnit(state.selected);
if (
selected &&
selected.alive &&
selected.team === TEAM_PLAYER &&
clicked.team === TEAM_ENEMY
) {
submitCommand({
type: "attack",
id: selected.id,
targetId: clicked.id
});
} else {
submitCommand({ type: "select", id: clicked.id });
}
return;
}
const buildingHit = getBuildingHit(event);
if (buildingHit) {
submitCommand({
type: "select",
id: buildingHit.building.id
});
return;
}
const tile = getTerrainHit(event);
if (!tile) return;
if (state.buildMode) {
submitCommand({
type: "build",
x: tile.x,
z: tile.z
});
state.buildMode = false;
ui.build.classList.remove("active");
showToast("Turret construction command issued.");
return;
}
const selected = getUnit(state.selected);
if (
selected &&
selected.alive &&
selected.team === TEAM_PLAYER
) {
submitCommand({
type: "move",
id: selected.id,
x: tile.x,
z: tile.z
});
}
}
// -------------------------------------------------------------------------
// Keyboard controls
// -------------------------------------------------------------------------
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
keys.add(event.code);
if (event.code === "Space") {
event.preventDefault();
togglePause();
}
if (event.code === "KeyB") {
toggleBuild();
}
if (event.code === "KeyR") {
startReplay();
}
if (event.code === "Escape") {
state.buildMode = false;
ui.build.classList.remove("active");
hoverMesh.visible = false;
}
if (event.code === "KeyF") {
const selected = getUnit(state.selected);
if (selected) {
cameraState.target.set(worldX(selected.x), 0, worldZ(selected.z));
}
}
});
window.addEventListener("keyup", (event) => {
keys.delete(event.code);
});
// -------------------------------------------------------------------------
// UI and replay
// -------------------------------------------------------------------------
function togglePause() {
if (state.outcome) return;
state.paused = !state.paused;
updateUI();
}
function toggleBuild() {
if (state.credits < 60) {
showToast("Insufficient credits for a turret.");
return;
}
state.buildMode = !state.buildMode;
ui.build.classList.toggle("active", state.buildMode);
showToast(
state.buildMode
? "Select an open tile to deploy a turret."
: "Construction mode cancelled."
);
}
function startReplay() {
if (state.tick <= 0) {
showToast("Run the simulation before starting a replay.");
return;
}
const duration = state.tick;
const commands = state.commands.map((command) => ({ ...command }));
initializeScenario(currentSeed, false);
state.commands = commands;
state.replaying = true;
state.replayEndTick = duration;
state.paused = false;
replayCursor = 0;
addEvent(`Deterministic replay started from seed ${currentSeed}.`);
showToast("Replaying the recorded command stream.");
updateUI();
}
function addEvent(message) {
state.events.push({
tick: state.tick,
message
});
if (state.events.length > 30) state.events.shift();
}
function showToast(message) {
ui.toast.textContent = message;
ui.toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
ui.toast.classList.remove("show");
}, 2200);
}
function showOutcome() {
ui.outcome.style.display = "block";
if (state.outcome === "victory") {
ui.outcomeTitle.textContent = "Enemy Core Eliminated";
ui.outcomeTitle.style.color = "var(--cyan)";
ui.outcomeText.textContent =
`Scenario ${currentSeed} completed in ${state.elapsed.toFixed(1)} seconds with ${state.kills} eliminations.`;
} else {
ui.outcomeTitle.textContent = "Command Lost";
ui.outcomeTitle.style.color = "var(--red)";
ui.outcomeText.textContent =
`Your core was destroyed after ${state.elapsed.toFixed(1)} seconds. Change the seed or issue different commands.`;
}
}
function formatTime(seconds) {
const minutes = Math.floor(seconds / 60);
const remainder = (seconds % 60).toFixed(1).padStart(4, "0");
return `${String(minutes).padStart(2, "0")}:${remainder}`;
}
function updateUI() {
const playerUnits = world.units.filter(
(unit) => unit.alive && unit.team === TEAM_PLAYER
).length;
const capacity = 20;
ui.credits.textContent = Math.floor(state.credits);
ui.supply.textContent = `${playerUnits} / ${capacity}`;
ui.kills.textContent = state.kills;
ui.speedValue.textContent = `${state.speed.toFixed(2)}×`;
ui.clock.textContent = formatTime(state.elapsed);
ui.tickLabel.textContent = `T+ ${state.elapsed.toFixed(1)}s`;
const progress = state.replaying
? state.tick / Math.max(1, state.replayEndTick)
: Math.min(1, state.tick / 3000);
ui.timeline.style.width = `${Math.max(0, Math.min(1, progress)) * 100}%`;
if (state.replaying) {
ui.status.textContent = "Replay";
ui.status.className = "status-pill replay";
ui.timelineLabel.textContent = "Deterministic command replay";
} else if (state.paused) {
ui.status.textContent = "Paused";
ui.status.className = "status-pill paused";
ui.timelineLabel.textContent = "Fixed-step simulation / 10 Hz";
} else {
ui.status.textContent = "Live";
ui.status.className = "status-pill";
ui.timelineLabel.textContent = "Fixed-step simulation / 10 Hz";
}
ui.play.textContent = state.paused ? "▶ Play" : "Ⅱ Pause";
ui.play.disabled = Boolean(state.outcome);
ui.step.disabled = !state.paused || Boolean(state.outcome);
ui.replay.disabled = state.tick <= 0 || state.replaying;
ui.build.disabled = state.credits < 60 || Boolean(state.replaying) || Boolean(state.outcome);
const selectedUnit = getUnit(state.selected);
const selectedBuilding = getBuilding(state.selected);
if (selectedUnit && selectedUnit.alive) {
const ratio = selectedUnit.hp / selectedUnit.maxHp;
ui.selectionTitle.textContent = `${selectedUnit.type} ${selectedUnit.id.toUpperCase()}`;
ui.selectionMeta.textContent =
`${selectedUnit.team === TEAM_PLAYER ? "Friendly" : "Hostile"} · ` +
`HP ${Math.ceil(selectedUnit.hp)}/${selectedUnit.maxHp} · ` +
`Position ${Math.round(selectedUnit.x)}, ${Math.round(selectedUnit.z)}`;
ui.hpFill.style.width = `${ratio * 100}%`;
ui.hpFill.style.background = ratio > 0.55 ? "var(--green)" : ratio > 0.25 ? "var(--yellow)" : "var(--red)";
ui.repair.disabled = true;
} else if (selectedBuilding && selectedBuilding.alive) {
const ratio = selectedBuilding.hp / selectedBuilding.maxHp;
ui.selectionTitle.textContent = selectedBuilding.type === "base"
? "Command Core"
: "Defense Turret";
ui.selectionMeta.textContent =
`${selectedBuilding.team === TEAM_PLAYER ? "Friendly" : "Hostile"} · ` +
`HP ${Math.ceil(selectedBuilding.hp)}/${selectedBuilding.maxHp} · ` +
`Position ${selectedBuilding.x}, ${selectedBuilding.z}`;
ui.hpFill.style.width = `${ratio * 100}%`;
ui.hpFill.style.background = ratio > 0.55 ? "var(--green)" : ratio > 0.25 ? "var(--yellow)" : "var(--red)";
ui.repair.disabled =
selectedBuilding.team !== TEAM_PLAYER ||
selectedBuilding.hp >= selectedBuilding.maxHp ||
state.credits < 25 ||
state.replaying;
} else {
ui.selectionTitle.textContent = "No entity selected";
ui.selectionMeta.textContent = "Select a friendly unit or structure.";
ui.hpFill.style.width = "0%";
ui.repair.disabled = true;
}
ui.commandCount.textContent = `${state.commands.length} recorded command${state.commands.length === 1 ? "" : "s"}`;
const recent = state.commands.slice(-5).reverse();
ui.commandLog.innerHTML = recent.length
? recent.map((command) => {
const label = command.type === "select"
? `select ${command.id}`
: command.type === "move"
? `move ${command.id} → ${command.x},${command.z}`
: command.type === "attack"
? `attack ${command.id} → ${command.targetId}`
: command.type === "build"
? `build turret ${command.x},${command.z}`
: `repair ${command.id}`;
return `<div class="log-line"><span class="log-tick">${String(command.tick).padStart(4, "0")}</span>${label}</div>`;
}).join("")
: '<div class="muted">No commands recorded yet.</div>';
}
ui.play.addEventListener("click", togglePause);
ui.step.addEventListener("click", () => {
if (!state.paused || state.outcome || state.replaying) return;
simulationStep();
updateUI();
});
ui.speed.addEventListener("input", () => {
state.speed = Number(ui.speed.value);
updateUI();
});
ui.build.addEventListener("click", toggleBuild);
ui.repair.addEventListener("click", () => {
if (!state.selected) return;
submitCommand({
type: "repair",
id: state.selected
});
});
ui.newButton.addEventListener("click", () => {
const seed = ui.seed.value.trim() || "1337";
initializeScenario(seed, true);
showToast(`New deterministic scenario: ${seed}`);
});
ui.seed.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
event.preventDefault();
ui.newButton.click();
}
});
ui.replay.addEventListener("click", startReplay);
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let uiAccumulator = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.1);
const time = clock.elapsedTime;
if (!state.paused && !state.outcome) {
accumulator += dt * state.speed;
let steps = 0;
while (accumulator >= FIXED_DT && steps < 16) {
if (state.replaying && state.tick >= state.replayEndTick) {
state.replaying = false;
state.paused = true;
addEvent("Replay complete. Deterministic state restored.");
break;
}
simulationStep();
accumulator -= FIXED_DT;
steps++;
if (state.replaying && state.tick >= state.replayEndTick) {
state.replaying = false;
state.paused = true;
addEvent("Replay complete. Deterministic state restored.");
break;
}
}
} else {
accumulator = 0;
}
updateCamera(dt);
updateEffects(dt);
updateVisuals(time);
uiAccumulator += dt;
if (uiAccumulator >= 0.1) {
uiAccumulator = 0;
updateUI();
}
renderer.render(scene, camera);
}
resize();
initializeScenario(currentSeed, true);
animate();
</script>
</body>
</html>
```