Prompt specification
Build or customize the Three.js 3D scene "Echo-based corridor exploration game" 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: Echo-based corridor exploration game
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/echo-based-corridor-exploration-game-x0648
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts bat echolocation. Create a bounded cave maze where users reveal nearby surfaces through timed symbolic echoes; navigation uses measured path distances while the interface distinguishes the game from biological sonar accuracy. Low-poly.
Working Three.js Starter (echo-based-corridor-exploration-game-x0648):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
/>
<title>Echo Cave — Stylized Echolocation</title>
<style>
:root {
--bg: #05080a;
--panel: rgba(8, 13, 16, 0.82);
--panel-border: rgba(142, 226, 231, 0.18);
--text: #e2f0ef;
--muted: #8fa3a5;
--cyan: #73f3ef;
--cyan-dim: #2d8f91;
--amber: #e4b86d;
--violet: #b7a0ff;
}
* {
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 {
color: inherit;
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
cursor: crosshair;
touch-action: none;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
user-select: none;
}
.glass {
border: 1px solid var(--panel-border);
background: var(--panel);
backdrop-filter: blur(13px);
box-shadow:
0 16px 44px rgba(0, 0, 0, 0.28),
inset 0 1px rgba(255, 255, 255, 0.035);
}
#brand {
position: absolute;
top: 20px;
left: 20px;
padding: 14px 17px;
min-width: 235px;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.19em;
text-transform: uppercase;
}
#brand h1 {
margin: 4px 0 2px;
font-size: 22px;
font-weight: 660;
letter-spacing: 0.08em;
}
#brand .sub {
color: var(--muted);
font-size: 11px;
letter-spacing: 0.035em;
}
#readouts {
position: absolute;
top: 20px;
left: 50%;
display: flex;
gap: 1px;
overflow: hidden;
transform: translateX(-50%);
border-radius: 3px;
}
.readout {
min-width: 102px;
padding: 12px 15px;
background: rgba(8, 13, 16, 0.78);
border-top: 1px solid var(--panel-border);
border-bottom: 1px solid var(--panel-border);
}
.readout:first-child {
border-left: 1px solid var(--panel-border);
}
.readout:last-child {
border-right: 1px solid var(--panel-border);
}
.readout label {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.readout strong {
color: var(--text);
font-size: 14px;
font-weight: 620;
font-variant-numeric: tabular-nums;
}
#map-panel {
position: absolute;
top: 20px;
right: 20px;
width: 286px;
padding: 13px;
border-radius: 3px;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
}
.panel-heading h2 {
margin: 0;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.panel-heading span {
color: var(--cyan-dim);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
#map {
display: block;
width: 260px;
height: 260px;
border: 1px solid rgba(115, 243, 239, 0.1);
background: #070b0d;
}
#map-legend {
display: flex;
justify-content: space-between;
margin-top: 8px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.05em;
}
#map-legend i {
display: inline-block;
width: 6px;
height: 6px;
margin-right: 4px;
border-radius: 50%;
background: var(--cyan);
vertical-align: 0;
box-shadow: 0 0 8px var(--cyan);
}
#targets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 5px;
margin-top: 11px;
}
.target-button {
position: relative;
min-height: 53px;
padding: 7px 5px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 2px;
background: rgba(255, 255, 255, 0.025);
cursor: pointer;
pointer-events: auto;
transition: 140ms ease;
}
.target-button:hover,
.target-button.active {
border-color: rgba(115, 243, 239, 0.55);
background: rgba(115, 243, 239, 0.08);
}
.target-button.active::after {
position: absolute;
right: 4px;
bottom: 3px;
left: 4px;
height: 2px;
background: var(--cyan);
content: "";
box-shadow: 0 0 8px var(--cyan);
}
.target-button b {
display: block;
margin-bottom: 2px;
font-size: 10px;
letter-spacing: 0.12em;
}
.target-button span {
display: block;
color: var(--muted);
font-size: 9px;
font-variant-numeric: tabular-nums;
}
#route-panel {
position: absolute;
right: 20px;
bottom: 20px;
width: 286px;
padding: 14px;
border-radius: 3px;
}
#route-top {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
}
#route-target {
color: var(--cyan);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#route-distance {
font-size: 27px;
font-weight: 520;
font-variant-numeric: tabular-nums;
letter-spacing: -0.04em;
}
#route-distance small {
color: var(--muted);
font-size: 11px;
font-weight: 500;
letter-spacing: 0;
}
#route-note {
margin-top: 7px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
#model-note {
position: absolute;
bottom: 20px;
left: 20px;
width: min(420px, calc(100vw - 350px));
padding: 13px 15px;
border-radius: 3px;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
#model-note strong {
display: block;
margin-bottom: 4px;
color: var(--amber);
font-size: 9px;
letter-spacing: 0.16em;
text-transform: uppercase;
}
#echo-panel {
position: absolute;
bottom: 22px;
left: 50%;
width: min(380px, calc(100vw - 40px));
padding: 12px 14px 13px;
border-radius: 3px;
transform: translateX(-50%);
}
#echo-row {
display: flex;
align-items: center;
gap: 13px;
}
#echo-button {
flex: 0 0 auto;
min-width: 112px;
padding: 10px 13px;
border: 1px solid rgba(115, 243, 239, 0.46);
border-radius: 2px;
background: rgba(115, 243, 239, 0.08);
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
cursor: pointer;
pointer-events: auto;
transition: 140ms ease;
}
#echo-button:hover:not(:disabled) {
background: rgba(115, 243, 239, 0.16);
box-shadow: 0 0 24px rgba(115, 243, 239, 0.12);
}
#echo-button:disabled {
border-color: rgba(115, 243, 239, 0.2);
color: #89aaa9;
cursor: default;
}
#echo-button.active {
color: #061112;
background: var(--cyan);
box-shadow: 0 0 28px rgba(115, 243, 239, 0.3);
}
#echo-copy {
min-width: 0;
flex: 1;
}
#echo-status {
margin-bottom: 6px;
color: var(--text);
font-size: 11px;
font-weight: 620;
letter-spacing: 0.07em;
}
#echo-track {
height: 3px;
overflow: hidden;
background: rgba(255, 255, 255, 0.08);
}
#echo-progress {
width: 0;
height: 100%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
#echo-hint {
margin-top: 5px;
color: var(--muted);
font-size: 9px;
}
#controls-hint {
position: absolute;
bottom: 8px;
left: 50%;
color: rgba(202, 225, 224, 0.48);
font-size: 9px;
letter-spacing: 0.06em;
transform: translateX(-50%);
white-space: nowrap;
}
#curtain {
position: fixed;
inset: 0;
z-index: 10;
display: grid;
place-items: center;
padding: 20px;
background:
radial-gradient(circle at 50% 40%, rgba(18, 56, 58, 0.3), transparent 38%),
rgba(2, 5, 7, 0.88);
backdrop-filter: blur(8px);
transition: opacity 300ms ease, visibility 300ms ease;
}
#curtain.hidden {
visibility: hidden;
opacity: 0;
pointer-events: none;
}
#intro {
width: min(570px, 100%);
padding: 34px;
border: 1px solid rgba(115, 243, 239, 0.22);
background: rgba(7, 12, 15, 0.88);
box-shadow: 0 35px 100px rgba(0, 0, 0, 0.65);
}
#intro .eyebrow {
margin-bottom: 10px;
}
#intro h2 {
margin: 0 0 12px;
font-size: clamp(36px, 8vw, 64px);
font-weight: 520;
line-height: 0.95;
letter-spacing: -0.055em;
}
#intro p {
margin: 0 0 22px;
color: #aebfc0;
font-size: 13px;
line-height: 1.65;
}
.intro-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-bottom: 20px;
}
.intro-grid div {
padding: 10px 11px;
border: 1px solid rgba(255, 255, 255, 0.08);
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.intro-grid b {
display: block;
color: var(--text);
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#enter {
width: 100%;
padding: 13px 18px;
border: 0;
border-radius: 2px;
background: var(--cyan);
color: #051011;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.14em;
cursor: pointer;
text-transform: uppercase;
transition: 140ms ease;
}
#enter:hover {
background: #a4fffa;
box-shadow: 0 0 32px rgba(115, 243, 239, 0.24);
}
#intro-note {
margin-top: 14px;
color: #788c8e;
font-size: 9px;
line-height: 1.55;
text-align: center;
}
#sound-button {
position: absolute;
top: 20px;
right: 320px;
padding: 9px 11px;
border-radius: 2px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.1em;
cursor: pointer;
pointer-events: auto;
}
#touch-controls {
position: absolute;
right: 18px;
bottom: 20px;
display: none;
grid-template-columns: repeat(3, 48px);
grid-template-rows: repeat(2, 48px);
gap: 5px;
pointer-events: auto;
}
#touch-controls button {
border: 1px solid rgba(115, 243, 239, 0.35);
border-radius: 3px;
background: rgba(8, 13, 16, 0.78);
color: var(--cyan);
font-size: 17px;
touch-action: none;
}
#touch-controls .forward {
grid-column: 2;
}
#touch-controls .left {
grid-column: 1;
grid-row: 2;
}
#touch-controls .back {
grid-column: 2;
grid-row: 2;
}
#touch-controls .right {
grid-column: 3;
grid-row: 2;
}
#touch-echo {
position: absolute;
right: 18px;
bottom: 132px;
display: none;
width: 74px;
height: 74px;
border: 1px solid rgba(115, 243, 239, 0.4);
border-radius: 50%;
background: rgba(8, 13, 16, 0.82);
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
pointer-events: auto;
}
@media (max-width: 920px) {
#readouts {
top: 96px;
left: 20px;
transform: none;
}
#brand {
min-width: 210px;
}
#sound-button {
top: 78px;
right: 20px;
}
#model-note {
display: none;
}
#route-panel {
bottom: 118px;
}
#echo-panel {
bottom: 20px;
}
}
@media (max-width: 650px) {
#map-panel {
top: 146px;
right: 12px;
width: 208px;
padding: 8px;
}
#map {
width: 190px;
height: 190px;
}
#map-legend {
display: none;
}
#targets {
margin-top: 6px;
}
.target-button {
min-height: 42px;
}
#route-panel {
right: 12px;
bottom: 118px;
width: 208px;
}
#route-distance {
font-size: 22px;
}
#echo-panel {
left: 12px;
bottom: 14px;
width: calc(100vw - 24px);
transform: none;
}
#controls-hint {
display: none;
}
#brand {
top: 12px;
left: 12px;
}
#readouts {
top: 91px;
left: 12px;
}
.readout {
min-width: 84px;
padding: 9px 10px;
}
#sound-button {
top: 12px;
right: 12px;
}
#intro {
padding: 24px;
}
.intro-grid {
grid-template-columns: 1fr;
}
}
@media (pointer: coarse) {
#touch-controls {
display: grid;
}
#touch-echo {
display: block;
}
#route-panel {
bottom: 132px;
}
#echo-panel {
left: 12px;
bottom: 12px;
width: calc(100vw - 196px);
transform: none;
}
#echo-button {
min-width: 86px;
padding: 9px;
}
#echo-hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div id="hud">
<section id="brand" class="glass">
<div class="eyebrow">Field Study 07</div>
<h1>ECHO CAVE</h1>
<div class="sub">A stylized echolocation maze</div>
</section>
<section id="readouts" class="glass">
<div class="readout">
<label>Heading</label>
<strong id="heading">000° N</strong>
</div>
<div class="readout">
<label>Walked</label>
<strong id="walked">0.0 m</strong>
</div>
<div class="readout">
<label>Memory</label>
<strong id="memory">1%</strong>
</div>
<div class="readout">
<label>Mode</label>
<strong>Symbolic</strong>
</div>
</section>
<button id="sound-button" class="glass">SOUND ON · M</button>
<section id="map-panel" class="glass">
<div class="panel-heading">
<h2>Passage Memory</h2>
<span id="map-scale">11 × 11 cells</span>
</div>
<canvas id="map" width="560" height="560"></canvas>
<div id="map-legend">
<span><i></i> Measured route</span>
<span>Revealed walls brighten</span>
</div>
<div id="targets"></div>
</section>
<section id="route-panel" class="glass">
<div id="route-top">
<div>
<div id="route-target">Select a beacon</div>
<div class="eyebrow" style="margin-top: 5px; color: var(--muted)">
Computed passage path
</div>
</div>
<div id="route-distance">— <small>m</small></div>
</div>
<div id="route-note">
Distance follows open corridor centerlines. It is not an acoustic range estimate.
</div>
</section>
<section id="model-note" class="glass">
<strong>Model note · not biological sonar</strong>
Echo rings, range, surface highlights, and memory are game abstractions.
Real bats emit ultrasonic calls and infer structure from returning sound;
this scene does not simulate that resolution or behavior.
</section>
<section id="echo-panel" class="glass">
<div id="echo-row">
<button id="echo-button">EMIT ECHO</button>
<div id="echo-copy">
<div id="echo-status">READY · 7.2 m symbolic range</div>
<div id="echo-track"><div id="echo-progress"></div></div>
<div id="echo-hint">Space emits a temporary surface reveal.</div>
</div>
</div>
</section>
<div id="controls-hint">
WASD MOVE · MOUSE LOOK · SPACE ECHO · 1–3 TARGET · ESC PAUSE
</div>
<div id="touch-controls">
<button class="forward" data-code="KeyW" aria-label="Move forward">↑</button>
<button class="left" data-code="KeyA" aria-label="Move left">←</button>
<button class="back" data-code="KeyS" aria-label="Move backward">↓</button>
<button class="right" data-code="KeyD" aria-label="Move right">→</button>
</div>
<button id="touch-echo">ECHO</button>
</div>
<div id="curtain">
<div id="intro">
<div class="eyebrow">Stylized echolocation experiment</div>
<h2>Navigate by<br />remembered echoes.</h2>
<p>
Explore a bounded low-poly cave. Emit a timed echo to reveal nearby
surfaces and passage memory, then use the measured route to a beacon.
</p>
<div class="intro-grid">
<div><b>Move</b>WASD / arrow keys</div>
<div><b>Look</b>Mouse, or drag to look</div>
<div><b>Reveal</b>Space or the Echo button</div>
<div><b>Navigate</b>Choose beacons with 1–3</div>
</div>
<button id="enter">Enter the cave</button>
<div id="intro-note">
The sound is an audible game proxy, not a bat ultrasound simulation.
Path distances are computed geometrically along the maze.
</div>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and renderer
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const curtain = document.querySelector("#curtain");
const enterButton = document.querySelector("#enter");
const echoButton = document.querySelector("#echo-button");
const touchEchoButton = document.querySelector("#touch-echo");
const soundButton = document.querySelector("#sound-button");
const headingEl = document.querySelector("#heading");
const walkedEl = document.querySelector("#walked");
const memoryEl = document.querySelector("#memory");
const echoStatusEl = document.querySelector("#echo-status");
const echoProgressEl = document.querySelector("#echo-progress");
const routeTargetEl = document.querySelector("#route-target");
const routeDistanceEl = document.querySelector("#route-distance");
const targetsEl = document.querySelector("#targets");
const mapCanvas = document.querySelector("#map");
const mapContext = mapCanvas.getContext("2d");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.16;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x05080a);
scene.fog = new THREE.FogExp2(0x05080a, 0.047);
const camera = new THREE.PerspectiveCamera(
68,
window.innerWidth / window.innerHeight,
0.06,
100
);
camera.rotation.order = "YXZ";
scene.add(camera);
const clock = new THREE.Clock();
// -------------------------------------------------------------------------
// Deterministic utilities
// -------------------------------------------------------------------------
let seed = 0x7a11c0de;
function random() {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function easeOutCubic(value) {
return 1 - Math.pow(1 - value, 3);
}
function keyFor(row, column) {
return `${row},${column}`;
}
// -------------------------------------------------------------------------
// Maze generation: one connected perfect maze
// -------------------------------------------------------------------------
const GRID_SIZE = 11;
const CELL_SIZE = 3.25;
const HALF_MAZE = (GRID_SIZE * CELL_SIZE) / 2;
const PLAYER_RADIUS = 0.56;
const ECHO_RANGE = 7.2;
const ECHO_DURATION = 3.65;
const ECHO_WAVE_TIME = 1.25;
const DIRECTIONS = [
{ row: -1, column: 0 },
{ row: 0, column: 1 },
{ row: 1, column: 0 },
{ row: 0, column: -1 }
];
const maze = Array.from({ length: GRID_SIZE }, () =>
Array.from({ length: GRID_SIZE }, () => ({
visited: false,
walls: [true, true, true, true]
}))
);
const stack = [[0, 0]];
maze[0][0].visited = true;
while (stack.length) {
const [row, column] = stack[stack.length - 1];
const candidates = [];
for (let direction = 0; direction < DIRECTIONS.length; direction++) {
const nextRow = row + DIRECTIONS[direction].row;
const nextColumn = column + DIRECTIONS[direction].column;
if (
nextRow >= 0 &&
nextRow < GRID_SIZE &&
nextColumn >= 0 &&
nextColumn < GRID_SIZE &&
!maze[nextRow][nextColumn].visited
) {
candidates.push(direction);
}
}
if (!candidates.length) {
stack.pop();
continue;
}
const direction = candidates[Math.floor(random() * candidates.length)];
const nextRow = row + DIRECTIONS[direction].row;
const nextColumn = column + DIRECTIONS[direction].column;
const opposite = (direction + 2) % 4;
maze[row][column].walls[direction] = false;
maze[nextRow][nextColumn].walls[opposite] = false;
maze[nextRow][nextColumn].visited = true;
stack.push([nextRow, nextColumn]);
}
function cellCenter(row, column) {
return new THREE.Vector2(
-HALF_MAZE + (column + 0.5) * CELL_SIZE,
-HALF_MAZE + (row + 0.5) * CELL_SIZE
);
}
function cellAt(x, z) {
const column = clamp(
Math.floor((x + HALF_MAZE) / CELL_SIZE),
0,
GRID_SIZE - 1
);
const row = clamp(
Math.floor((z + HALF_MAZE) / CELL_SIZE),
0,
GRID_SIZE - 1
);
return { row, column };
}
// Unique wall segments. North and west are used internally to avoid
// duplicating the same shared boundary.
const wallSegments = [];
function addWallSegment(x1, z1, x2, z2, cells) {
wallSegments.push({ x1, z1, x2, z2, cells });
}
for (let row = 0; row < GRID_SIZE; row++) {
for (let column = 0; column < GRID_SIZE; column++) {
const x1 = -HALF_MAZE + column * CELL_SIZE;
const x2 = x1 + CELL_SIZE;
const z1 = -HALF_MAZE + row * CELL_SIZE;
const z2 = z1 + CELL_SIZE;
if (maze[row][column].walls[0]) {
addWallSegment(x1, z1, x2, z1, [
[row, column],
row > 0 ? [row - 1, column] : null
]);
}
if (maze[row][column].walls[3]) {
addWallSegment(x1, z1, x1, z2, [
[row, column],
column > 0 ? [row, column - 1] : null
]);
}
if (row === GRID_SIZE - 1 && maze[row][column].walls[2]) {
addWallSegment(x1, z2, x2, z2, [[row, column]]);
}
if (column === GRID_SIZE - 1 && maze[row][column].walls[1]) {
addWallSegment(x2, z1, x2, z2, [[row, column]]);
}
}
}
// -------------------------------------------------------------------------
// Cave shell and low-poly wall instances
// -------------------------------------------------------------------------
const caveSize = GRID_SIZE * CELL_SIZE + 9;
const floorGeometry = new THREE.PlaneGeometry(
caveSize,
caveSize,
GRID_SIZE * 2,
GRID_SIZE * 2
);
floorGeometry.rotateX(-Math.PI / 2);
const floorPositions = floorGeometry.attributes.position;
const floorColors = new Float32Array(floorPositions.count * 3);
const floorColor = new THREE.Color();
for (let index = 0; index < floorPositions.count; index++) {
floorPositions.setY(
index,
-0.055 + (random() - 0.5) * 0.075
);
const shade = 0.045 + random() * 0.025;
floorColor.setRGB(shade * 0.86, shade, shade * 1.03);
floorColors[index * 3] = floorColor.r;
floorColors[index * 3 + 1] = floorColor.g;
floorColors[index * 3 + 2] = floorColor.b;
}
floorGeometry.setAttribute(
"color",
new THREE.BufferAttribute(floorColors, 3)
);
const floor = new THREE.Mesh(
floorGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
metalness: 0.02,
flatShading: true
})
);
floor.receiveShadow = true;
scene.add(floor);
const ceiling = new THREE.Mesh(
new THREE.PlaneGeometry(caveSize, caveSize),
new THREE.MeshStandardMaterial({
color: 0x0b0e11,
roughness: 1,
side: THREE.DoubleSide,
flatShading: true
})
);
ceiling.geometry.rotateX(Math.PI / 2);
ceiling.position.y = 5.1;
scene.add(ceiling);
const wallRockGeometry = new THREE.DodecahedronGeometry(1, 0);
const wallRockMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.96,
metalness: 0.02,
flatShading: true,
emissive: 0x071012,
emissiveIntensity: 0.24
});
const wallInstanceData = [];
const dummy = new THREE.Object3D();
const wallPalette = [
0x293034,
0x252c30,
0x303438,
0x22292d,
0x34383a
];
for (const segment of wallSegments) {
const horizontal = Math.abs(segment.x2 - segment.x1) > 0.001;
for (let rockIndex = 0; rockIndex < 3; rockIndex++) {
const fraction = 0.16 + rockIndex * 0.34 + (random() - 0.5) * 0.045;
const x = THREE.MathUtils.lerp(segment.x1, segment.x2, fraction);
const z = THREE.MathUtils.lerp(segment.z1, segment.z2, fraction);
const y = 0.94 + random() * 0.24;
dummy.position.set(x, y, z);
dummy.rotation.set(
(random() - 0.5) * 0.32,
random() * Math.PI,
(random() - 0.5) * 0.24
);
if (horizontal) {
dummy.scale.set(
CELL_SIZE * (0.5 + random() * 0.055),
1.35 + random() * 0.62,
0.68 + random() * 0.08
);
} else {
dummy.scale.set(
0.68 + random() * 0.08,
1.35 + random() * 0.62,
CELL_SIZE * (0.5 + random() * 0.055)
);
}
dummy.updateMatrix();
const baseColor = new THREE.Color(
wallPalette[Math.floor(random() * wallPalette.length)]
);
baseColor.offsetHSL(
(random() - 0.5) * 0.015,
(random() - 0.5) * 0.04,
(random() - 0.5) * 0.035
);
wallInstanceData.push({
x,
z,
baseColor,
touched: false
});
}
}
const wallMesh = new THREE.InstancedMesh(
wallRockGeometry,
wallRockMaterial,
wallInstanceData.length
);
for (let index = 0; index < wallInstanceData.length; index++) {
const data = wallInstanceData[index];
dummy.position.set(data.x, 0, data.z);
// The instance matrices were populated above in wallInstanceData order.
// Recompute them from the stored segment geometry for reliability.
const segmentIndex = Math.floor(index / 3);
const rockIndex = index % 3;
const segment = wallSegments[segmentIndex];
const horizontal = Math.abs(segment.x2 - segment.x1) > 0.001;
const fraction = 0.16 + rockIndex * 0.34;
dummy.position.set(
THREE.MathUtils.lerp(segment.x1, segment.x2, fraction),
0.94 + ((index * 17) % 23) / 100,
THREE.MathUtils.lerp(segment.z1, segment.z2, fraction)
);
dummy.rotation.set(
((index * 13) % 31) / 100,
((index * 29) % 100) / 100 * Math.PI,
((index * 7) % 17) / 100
);
if (horizontal) {
dummy.scale.set(
CELL_SIZE * 0.525,
1.45 + ((index * 11) % 45) / 100,
0.71
);
} else {
dummy.scale.set(
0.71,
1.45 + ((index * 11) % 45) / 100,
CELL_SIZE * 0.525
);
}
dummy.updateMatrix();
wallMesh.setMatrixAt(index, dummy.matrix);
wallMesh.setColorAt(index, data.baseColor);
}
wallMesh.instanceMatrix.needsUpdate = true;
wallMesh.instanceColor.needsUpdate = true;
wallMesh.castShadow = true;
wallMesh.receiveShadow = true;
scene.add(wallMesh);
// Stalactites add a low-poly cave silhouette without extra logic.
const stalactiteData = [];
for (let index = 0; index < wallSegments.length; index += 2) {
const segment = wallSegments[index];
const fraction = 0.25 + random() * 0.5;
stalactiteData.push({
x: THREE.MathUtils.lerp(segment.x1, segment.x2, fraction),
z: THREE.MathUtils.lerp(segment.z1, segment.z2, fraction),
scale: 0.55 + random() * 0.75,
rotation: random() * Math.PI
});
}
const stalactiteMesh = new THREE.InstancedMesh(
new THREE.ConeGeometry(0.48, 1.55, 5, 1),
new THREE.MeshStandardMaterial({
color: 0x171c20,
roughness: 1,
flatShading: true
}),
stalactiteData.length
);
for (let index = 0; index < stalactiteData.length; index++) {
const data = stalactiteData[index];
dummy.position.set(data.x, 4.35, data.z);
dummy.rotation.set(0, data.rotation, Math.PI);
dummy.scale.set(data.scale, data.scale, data.scale);
dummy.updateMatrix();
stalactiteMesh.setMatrixAt(index, dummy.matrix);
}
stalactiteMesh.instanceMatrix.needsUpdate = true;
scene.add(stalactiteMesh);
// -------------------------------------------------------------------------
// Lighting
// -------------------------------------------------------------------------
scene.add(new THREE.AmbientLight(0x8ba0a8, 0.32));
const hemisphere = new THREE.HemisphereLight(
0x72939b,
0x241c17,
0.8
);
scene.add(hemisphere);
const lamp = new THREE.SpotLight(
0xc4e4e7,
34,
16,
Math.PI * 0.19,
0.66,
1.35
);
lamp.position.set(0.12, -0.08, 0);
lamp.castShadow = true;
lamp.shadow.mapSize.set(1024, 1024);
lamp.shadow.bias = -0.0004;
const lampTarget = new THREE.Object3D();
lampTarget.position.set(0, -0.05, -1);
camera.add(lamp);
camera.add(lampTarget);
lamp.target = lampTarget;
const echoLight = new THREE.PointLight(0x61f4f0, 0, 11, 1.5);
scene.add(echoLight);
// -------------------------------------------------------------------------
// Graph pathfinding and beacon selection
// -------------------------------------------------------------------------
function bfsPath(startRow, startColumn, endRow, endColumn) {
const startKey = keyFor(startRow, startColumn);
const endKey = keyFor(endRow, endColumn);
const queue = [startKey];
const parent = new Map([[startKey, null]]);
for (let queueIndex = 0; queueIndex < queue.length; queueIndex++) {
const currentKey = queue[queueIndex];
if (currentKey === endKey) break;
const [row, column] = currentKey.split(",").map(Number);
for (let direction = 0; direction < DIRECTIONS.length; direction++) {
if (maze[row][column].walls[direction]) continue;
const nextRow = row + DIRECTIONS[direction].row;
const nextColumn = column + DIRECTIONS[direction].column;
if (
nextRow < 0 ||
nextRow >= GRID_SIZE ||
nextColumn < 0 ||
nextColumn >= GRID_SIZE
) {
continue;
}
const nextKey = keyFor(nextRow, nextColumn);
if (!parent.has(nextKey)) {
parent.set(nextKey, currentKey);
queue.push(nextKey);
}
}
}
if (!parent.has(endKey)) return [];
const path = [];
let current = endKey;
while (current !== null) {
const [row, column] = current.split(",").map(Number);
path.push({ row, column });
current = parent.get(current);
}
path.reverse();
return path;
}
function graphDistances(startRow, startColumn) {
const distances = new Map();
const queue = [[startRow, startColumn]];
distances.set(keyFor(startRow, startColumn), 0);
for (let index = 0; index < queue.length; index++) {
const [row, column] = queue[index];
const distance = distances.get(keyFor(row, column));
for (let direction = 0; direction < DIRECTIONS.length; direction++) {
if (maze[row][column].walls[direction]) continue;
const nextRow = row + DIRECTIONS[direction].row;
const nextColumn = column + DIRECTIONS[direction].column;
if (
nextRow < 0 ||
nextRow >= GRID_SIZE ||
nextColumn < 0 ||
nextColumn >= GRID_SIZE
) {
continue;
}
const nextKey = keyFor(nextRow, nextColumn);
if (!distances.has(nextKey)) {
distances.set(nextKey, distance + 1);
queue.push([nextRow, nextColumn]);
}
}
}
return distances;
}
const startRow = Math.floor(GRID_SIZE / 2);
const startColumn = Math.floor(GRID_SIZE / 2);
const startCenter = cellCenter(startRow, startColumn);
const distancesFromStart = graphDistances(startRow, startColumn);
const leaves = [];
for (let row = 0; row < GRID_SIZE; row++) {
for (let column = 0; column < GRID_SIZE; column++) {
const openWalls = maze[row][column].walls.filter((closed) => !closed).length;
if (openWalls === 1) leaves.push({ row, column });
}
}
leaves.sort(
(a, b) =>
distancesFromStart.get(keyFor(b.row, b.column)) -
distancesFromStart.get(keyFor(a.row, a.column))
);
const selectedBeaconCells = [];
for (const candidate of leaves) {
const candidateCenter = cellCenter(candidate.row, candidate.column);
const separated = selectedBeaconCells.every((existing) => {
const existingCenter = cellCenter(existing.row, existing.column);
return candidateCenter.distanceTo(existingCenter) > CELL_SIZE * 4;
});
if (separated) selectedBeaconCells.push(candidate);
if (selectedBeaconCells.length === 3) break;
}
while (selectedBeaconCells.length < 3) {
selectedBeaconCells.push(leaves[selectedBeaconCells.length]);
}
const beaconDefinitions = [
{ name: "Cyan Chime", color: 0x70f2ec },
{ name: "Amber Chime", color: 0xe4b86d },
{ name: "Violet Chime", color: 0xb7a0ff }
];
const beacons = selectedBeaconCells.map((cell, index) => {
const definition = beaconDefinitions[index];
const center = cellCenter(cell.row, cell.column);
const material = new THREE.MeshStandardMaterial({
color: definition.color,
emissive: definition.color,
emissiveIntensity: 1.8,
roughness: 0.35,
flatShading: true
});
const mesh = new THREE.Mesh(
new THREE.OctahedronGeometry(0.38, 0),
material
);
mesh.position.set(center.x, 1.03, center.y);
mesh.castShadow = true;
scene.add(mesh);
const light = new THREE.PointLight(definition.color, 3.2, 5, 1.8);
light.position.set(center.x, 1.35, center.y);
scene.add(light);
return {
...cell,
...definition,
center,
mesh,
light
};
});
let selectedBeacon = 0;
const targetButtons = beacons.map((beacon, index) => {
const button = document.createElement("button");
button.className = "target-button";
button.innerHTML = `
<b>${index + 1} · ${beacon.name.split(" ")[0].toUpperCase()}</b>
<span data-distance>— m</span>
`;
button.addEventListener("click", () => selectBeacon(index));
targetsEl.appendChild(button);
return button;
});
function selectBeacon(index) {
selectedBeacon = (index + beacons.length) % beacons.length;
targetButtons.forEach((button, buttonIndex) => {
button.classList.toggle("active", buttonIndex === selectedBeacon);
});
routeTargetEl.textContent = beacons[selectedBeacon].name;
updateRoute();
}
// -------------------------------------------------------------------------
// Player state and direct first-person camera controls
// -------------------------------------------------------------------------
const player = new THREE.Vector3(startCenter.x, 0, startCenter.y);
const keys = Object.create(null);
const discoveredCells = new Set([keyFor(startRow, startColumn)]);
let yaw = 0;
let pitch = 0;
let walkedDistance = 0;
let started = false;
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
camera.position.set(player.x, 1.64, player.z);
function constrainPlayer(x, z) {
for (const segment of wallSegments) {
const segmentX = segment.x2 - segment.x1;
const segmentZ = segment.z2 - segment.z1;
const lengthSquared = segmentX * segmentX + segmentZ * segmentZ;
const projection = clamp(
((x - segment.x1) * segmentX + (z - segment.z1) * segmentZ) /
lengthSquared,
0,
1
);
const nearestX = segment.x1 + segmentX * projection;
const nearestZ = segment.z1 + segmentZ * projection;
let differenceX = x - nearestX;
let differenceZ = z - nearestZ;
const distanceSquared =
differenceX * differenceX + differenceZ * differenceZ;
if (distanceSquared < PLAYER_RADIUS * PLAYER_RADIUS) {
const distance = Math.sqrt(distanceSquared);
if (distance > 0.00001) {
const push = PLAYER_RADIUS - distance + 0.002;
x += (differenceX / distance) * push;
z += (differenceZ / distance) * push;
} else {
const length = Math.sqrt(lengthSquared);
const normalX = -segmentZ / length;
const normalZ = segmentX / length;
x += normalX * (PLAYER_RADIUS + 0.002);
z += normalZ * (PLAYER_RADIUS + 0.002);
}
}
}
return { x, z };
}
function updatePlayer(deltaTime, elapsedTime) {
const forwardInput =
(keys.KeyW || keys.ArrowUp ? 1 : 0) -
(keys.KeyS || keys.ArrowDown ? 1 : 0);
const sideInput =
(keys.KeyD || keys.ArrowRight ? 1 : 0) -
(keys.KeyA || keys.ArrowLeft ? 1 : 0);
if (forwardInput || sideInput) {
const forward = new THREE.Vector3(
-Math.sin(yaw),
0,
-Math.cos(yaw)
);
const right = new THREE.Vector3(
Math.cos(yaw),
0,
-Math.sin(yaw)
);
const movement = new THREE.Vector3()
.addScaledVector(forward, forwardInput)
.addScaledVector(right, sideInput)
.normalize()
.multiplyScalar(3.15 * deltaTime);
const constrainedX = constrainPlayer(
player.x + movement.x,
player.z
);
player.x = constrainedX.x;
const constrainedZ = constrainPlayer(
player.x,
player.z + movement.z
);
player.z = constrainedZ.z;
walkedDistance += Math.hypot(movement.x, movement.z);
}
const bob = forwardInput
? Math.sin(elapsedTime * 10.5) * 0.026
: 0;
camera.position.set(player.x, 1.64 + bob, player.z);
camera.rotation.set(pitch, yaw, 0, "YXZ");
}
// -------------------------------------------------------------------------
// Timed symbolic echo
// -------------------------------------------------------------------------
const echoShell = new THREE.Mesh(
new THREE.IcosahedronGeometry(1, 1),
new THREE.MeshBasicMaterial({
color: 0x70f4ef,
wireframe: true,
transparent: true,
opacity: 0,
depthWrite: false
})
);
echoShell.visible = false;
scene.add(echoShell);
const echoRing = new THREE.Mesh(
new THREE.TorusGeometry(1, 0.018, 5, 80),
new THREE.MeshBasicMaterial({
color: 0x70f4ef,
transparent: true,
opacity: 0,
depthWrite: false
})
);
echoRing.rotation.x = Math.PI / 2;
echoRing.visible = false;
scene.add(echoRing);
const echo = {
active: false,
elapsed: 0,
origin: new THREE.Vector3()
};
const revealColor = new THREE.Color(0x70f4ef);
function emitEcho() {
if (!started || echo.active) return;
echo.active = true;
echo.elapsed = 0;
echo.origin.set(player.x, 1.25, player.z);
echoShell.visible = true;
echoRing.visible = true;
echoButton.disabled = true;
echoButton.classList.add("active");
echoButton.textContent = "ECHOING";
for (const instance of wallInstanceData) {
instance.touched = false;
}
playEchoSound();
}
function updateEcho(deltaTime) {
if (!echo.active) return;
echo.elapsed += deltaTime;
const waveProgress = clamp(echo.elapsed / ECHO_WAVE_TIME, 0, 1);
const radius = easeOutCubic(waveProgress) * ECHO_RANGE;
const fade = clamp((ECHO_DURATION - echo.elapsed) / 1.05, 0, 1);
for (const instance of wallInstanceData) {
const distance = Math.hypot(
instance.x - echo.origin.x,
instance.z - echo.origin.z
);
if (!instance.touched && distance <= radius) {
instance.touched = true;
}
}
for (let index = 0; index < wallInstanceData.length; index++) {
const instance = wallInstanceData[index];
const strength = instance.touched ? fade : 0;
const color = instance.baseColor.clone().lerp(revealColor, strength * 0.88);
wallMesh.setColorAt(index, color);
}
wallMesh.instanceColor.needsUpdate = true;
for (let row = 0; row < GRID_SIZE; row++) {
for (let column = 0; column < GRID_SIZE; column++) {
const key = keyFor(row, column);
if (discoveredCells.has(key)) continue;
const center = cellCenter(row, column);
const distance = Math.hypot(
center.x - echo.origin.x,
center.y - echo.origin.z
);
if (distance <= radius) discoveredCells.add(key);
}
}
echoShell.position.copy(echo.origin);
echoShell.scale.setScalar(Math.max(radius, 0.01));
echoShell.material.opacity = 0.36 * fade;
echoRing.position.set(echo.origin.x, 0.09, echo.origin.z);
echoRing.scale.setScalar(Math.max(radius, 0.01));
echoRing.material.opacity = 0.82 * fade;
echoLight.position.set(echo.origin.x, 1.55, echo.origin.z);
echoLight.intensity = 58 * fade;
const remaining = Math.max(0, ECHO_DURATION - echo.elapsed);
echoStatusEl.textContent = `ACTIVE · ${remaining.toFixed(1)} s remain`;
echoProgressEl.style.width = `${(1 - echo.elapsed / ECHO_DURATION) * 100}%`;
if (echo.elapsed >= ECHO_DURATION) {
endEcho();
}
}
function endEcho() {
echo.active = false;
echoShell.visible = false;
echoRing.visible = false;
echoLight.intensity = 0;
for (let index = 0; index < wallInstanceData.length; index++) {
wallInstanceData[index].touched = false;
wallMesh.setColorAt(index, wallInstanceData[index].baseColor);
}
wallMesh.instanceColor.needsUpdate = true;
echoButton.disabled = false;
echoButton.classList.remove("active");
echoButton.textContent = "EMIT ECHO";
echoStatusEl.textContent = `READY · ${ECHO_RANGE.toFixed(1)} m symbolic range`;
echoProgressEl.style.width = "0%";
}
// -------------------------------------------------------------------------
// Audible proxy sound
// -------------------------------------------------------------------------
let audioContext = null;
let muted = false;
function ensureAudio() {
if (!audioContext) {
const AudioContextClass =
window.AudioContext || window.webkitAudioContext;
if (AudioContextClass) audioContext = new AudioContextClass();
}
if (audioContext?.state === "suspended") {
audioContext.resume().catch(() => {});
}
}
function chirp(startTime, startFrequency, endFrequency, duration, volume) {
if (!audioContext) return;
const oscillator = audioContext.createOscillator();
const gain = audioContext.createGain();
oscillator.type = "sine";
oscillator.frequency.setValueAtTime(startFrequency, startTime);
oscillator.frequency.exponentialRampToValueAtTime(
endFrequency,
startTime + duration
);
gain.gain.setValueAtTime(0.0001, startTime);
gain.gain.exponentialRampToValueAtTime(volume, startTime + 0.014);
gain.gain.exponentialRampToValueAtTime(0.0001, startTime + duration);
oscillator.connect(gain);
gain.connect(audioContext.destination);
oscillator.start(startTime);
oscillator.stop(startTime + duration + 0.03);
}
function playEchoSound() {
if (muted || !audioContext) return;
const now = audioContext.currentTime;
chirp(now, 620, 1380, 0.13, 0.045);
chirp(now + 0.25, 760, 420, 0.19, 0.027);
}
function toggleMute() {
muted = !muted;
soundButton.textContent = muted ? "SOUND OFF · M" : "SOUND ON · M";
}
// -------------------------------------------------------------------------
// Route measurement and minimap
// -------------------------------------------------------------------------
let routePoints = [];
let currentRouteDistance = 0;
function updateRoute() {
const cell = cellAt(player.x, player.z);
const beacon = beacons[selectedBeacon];
const path = bfsPath(cell.row, cell.column, beacon.row, beacon.column);
const points = [new THREE.Vector2(player.x, player.z)];
if (path.length) {
points.push(cellCenter(path[0].row, path[0].column));
for (const pathCell of path) {
points.push(cellCenter(pathCell.row, pathCell.column));
}
} else {
points.push(beacon.center);
}
let distance = 0;
for (let index = 1; index < points.length; index++) {
distance += points[index].distanceTo(points[index - 1]);
}
routePoints = points;
currentRouteDistance = distance;
routeDistanceEl.innerHTML = `${distance.toFixed(1)} <small>m</small>`;
targetButtons.forEach((button, index) => {
const distanceElement = button.querySelector("[data-distance]");
distanceElement.textContent =
index === selectedBeacon ? `${distance.toFixed(1)} m` : "select";
});
}
const mapSize = 280;
const mapMargin = 14;
const mapScale =
(mapSize - mapMargin * 2) / (GRID_SIZE * CELL_SIZE);
function mapPoint(x, z) {
return {
x: mapMargin + (x + HALF_MAZE) * mapScale,
y: mapMargin + (z + HALF_MAZE) * mapScale
};
}
function drawMap() {
const context = mapContext;
context.setTransform(2, 0, 0, 2, 0, 0);
context.clearRect(0, 0, mapSize, mapSize);
context.fillStyle = "#070b0d";
context.fillRect(0, 0, mapSize, mapSize);
context.strokeStyle = "rgba(115,243,239,0.055)";
context.lineWidth = 1;
for (let row = 0; row < GRID_SIZE; row++) {
for (let column = 0; column < GRID_SIZE; column++) {
if (!discoveredCells.has(keyFor(row, column))) continue;
const center = cellCenter(row, column);
const point = mapPoint(center.x, center.y);
const size = CELL_SIZE * mapScale;
context.fillStyle = "rgba(70,115,118,0.1)";
context.fillRect(
point.x - size / 2,
point.y - size / 2,
size,
size
);
}
}
// Faint complete layout.
context.strokeStyle = "rgba(150,190,190,0.065)";
context.lineWidth = 1;
context.beginPath();
for (const segment of wallSegments) {
const a = mapPoint(segment.x1, segment.z1);
const b = mapPoint(segment.x2, segment.z2);
context.moveTo(a.x, a.y);
context.lineTo(b.x, b.y);
}
context.stroke();
// Revealed wall segments.
context.strokeStyle = "rgba(128,184,184,0.55)";
context.lineWidth = 2;
context.beginPath();
for (const segment of wallSegments) {
const visible = segment.cells.some(
(cell) =>
cell && discoveredCells.has(keyFor(cell[0], cell[1]))
);
if (!visible) continue;
const a = mapPoint(segment.x1, segment.z1);
const b = mapPoint(segment.x2, segment.z2);
context.moveTo(a.x, a.y);
context.lineTo(b.x, b.y);
}
context.stroke();
// Measured route.
if (routePoints.length > 1) {
context.strokeStyle = "rgba(115,243,239,0.9)";
context.lineWidth = 2;
context.setLineDash([4, 4]);
context.beginPath();
routePoints.forEach((point, index) => {
const mapped = mapPoint(point.x, point.y);
if (index === 0) context.moveTo(mapped.x, mapped.y);
else context.lineTo(mapped.x, mapped.y);
});
context.stroke();
context.setLineDash([]);
}
// Beacons.
for (const beacon of beacons) {
const point = mapPoint(beacon.center.x, beacon.center.y);
const color = `#${beacon.color.toString(16).padStart(6, "0")}`;
context.save();
context.translate(point.x, point.y);
context.rotate(Math.PI / 4);
context.fillStyle = color;
context.shadowColor = color;
context.shadowBlur = beacon === beacons[selectedBeacon] ? 11 : 4;
context.fillRect(-3, -3, 6, 6);
context.restore();
}
// Player heading.
const playerPoint = mapPoint(player.x, player.z);
context.save();
context.translate(playerPoint.x, playerPoint.y);
context.rotate((-yaw * 180) / Math.PI);
context.beginPath();
context.moveTo(0, -7);
context.lineTo(5, 5);
context.lineTo(0, 2.5);
context.lineTo(-5, 5);
context.closePath();
context.fillStyle = "#d9fffa";
context.shadowColor = "#70f4ef";
context.shadowBlur = 10;
context.fill();
context.restore();
context.strokeStyle = "rgba(115,243,239,0.16)";
context.lineWidth = 1;
context.strokeRect(0.5, 0.5, mapSize - 1, mapSize - 1);
context.fillStyle = "rgba(143,163,165,0.72)";
context.font = "8px ui-monospace, monospace";
context.fillText("N", mapSize / 2 - 3, 10);
}
// -------------------------------------------------------------------------
// Input
// -------------------------------------------------------------------------
function requestPointerLock() {
if (!canvas.requestPointerLock) return;
try {
const result = canvas.requestPointerLock();
if (result?.catch) result.catch(() => {});
} catch (_) {
// Drag-to-look remains available.
}
}
enterButton.addEventListener("click", () => {
ensureAudio();
started = true;
curtain.classList.add("hidden");
requestPointerLock();
});
canvas.addEventListener("click", () => {
if (started && document.pointerLockElement !== canvas) {
requestPointerLock();
}
});
document.addEventListener("pointerlockchange", () => {
if (document.pointerLockElement === canvas) {
curtain.classList.add("hidden");
} else if (started) {
enterButton.textContent = "Resume the cave";
curtain.classList.remove("hidden");
}
});
document.addEventListener("mousemove", (event) => {
if (document.pointerLockElement === canvas) {
yaw -= event.movementX * 0.0022;
pitch -= event.movementY * 0.0018;
pitch = clamp(pitch, -Math.PI * 0.44, Math.PI * 0.44);
}
});
canvas.addEventListener("pointerdown", (event) => {
if (event.pointerType === "mouse") return;
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging || document.pointerLockElement === canvas) return;
yaw -= (event.clientX - lastPointerX) * 0.004;
pitch -= (event.clientY - lastPointerY) * 0.0035;
pitch = clamp(pitch, -Math.PI * 0.44, Math.PI * 0.44);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
});
canvas.addEventListener("pointerup", () => {
dragging = false;
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
});
document.addEventListener("keydown", (event) => {
if (
[
"Space",
"ArrowUp",
"ArrowDown",
"ArrowLeft",
"ArrowRight"
].includes(event.code)
) {
event.preventDefault();
}
keys[event.code] = true;
if (event.code === "Space" && !event.repeat) emitEcho();
if (["Digit1", "Digit2", "Digit3"].includes(event.code)) {
selectBeacon(Number(event.code.slice(-1)) - 1);
}
if (event.code === "KeyM" && !event.repeat) toggleMute();
});
document.addEventListener("keyup", (event) => {
keys[event.code] = false;
});
window.addEventListener("blur", () => {
for (const code in keys) keys[code] = false;
});
echoButton.addEventListener("click", emitEcho);
touchEchoButton.addEventListener("click", emitEcho);
soundButton.addEventListener("click", toggleMute);
document.querySelectorAll("#touch-controls button").forEach((button) => {
const code = button.dataset.code;
button.addEventListener("pointerdown", (event) => {
event.preventDefault();
keys[code] = true;
button.setPointerCapture(event.pointerId);
});
const release = () => {
keys[code] = false;
};
button.addEventListener("pointerup", release);
button.addEventListener("pointercancel", release);
button.addEventListener("lostpointercapture", release);
});
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
const compassLabels = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
selectBeacon(0);
renderer.setAnimationLoop(() => {
const deltaTime = Math.min(clock.getDelta(), 0.05);
const elapsedTime = clock.elapsedTime;
updatePlayer(deltaTime, elapsedTime);
updateEcho(deltaTime);
updateRoute();
for (let index = 0; index < beacons.length; index++) {
const beacon = beacons[index];
beacon.mesh.rotation.y += deltaTime * 0.75;
beacon.mesh.rotation.x = Math.sin(elapsedTime * 0.8 + index) * 0.16;
beacon.mesh.position.y =
1.03 + Math.sin(elapsedTime * 1.7 + index * 2) * 0.11;
const selected = index === selectedBeacon;
beacon.mesh.material.emissiveIntensity = selected ? 3.1 : 1.65;
beacon.light.intensity = selected ? 4.5 : 2.6;
}
const heading = ((-yaw * 180) / Math.PI + 360) % 360;
const compassIndex = Math.round(heading / 45) % 8;
headingEl.textContent =
`${String(Math.round(heading)).padStart(3, "0")}° ${compassLabels[compassIndex]}`;
walkedEl.textContent = `${walkedDistance.toFixed(1)} m`;
memoryEl.textContent = `${Math.round(
(discoveredCells.size / (GRID_SIZE * GRID_SIZE)) * 100
)}%`;
drawMap();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```