Prompt specification
Build or customize the Three.js 3D scene "Modular Dungeon With Verified Exit" 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: Modular Dungeon With Verified Exit
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/modular-dungeon-with-verified-exit-x3491
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts generated levels with guaranteed connected routes. Build an original voxel dungeon from a small module set using deterministic seeds. Check connectivity and door alignment before showing the completed bounded level. Voxel style.
Working Three.js Starter (modular-dungeon-with-verified-exit-x3491):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vowel Vault — Deterministic Voxel Dungeon</title>
<style>
:root {
color-scheme: dark;
--ink: #eef5ff;
--muted: #91a0b8;
--panel: rgba(12, 17, 28, 0.82);
--line: rgba(159, 190, 231, 0.16);
--cyan: #70e6db;
--gold: #e7c86a;
--green: #84d17a;
--red: #ff7185;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #080b12;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 44%, transparent 42%, rgba(2, 5, 10, 0.42) 100%),
linear-gradient(180deg, rgba(5, 8, 14, 0.28), transparent 24%);
z-index: 1;
}
.brand {
position: fixed;
z-index: 3;
top: 24px;
left: 26px;
pointer-events: none;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.65);
}
.brand-mark {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 7px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.brand-mark::before {
content: "";
width: 9px;
height: 9px;
background: var(--cyan);
box-shadow: 0 0 18px var(--cyan);
transform: rotate(45deg);
}
h1 {
margin: 0;
font-size: clamp(25px, 3.4vw, 42px);
line-height: 0.98;
letter-spacing: -0.045em;
}
.brand p {
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
}
.panel {
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel);
box-shadow:
0 18px 55px rgba(0, 0, 0, 0.34),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(15px);
}
#generator {
position: fixed;
z-index: 4;
top: 24px;
right: 24px;
width: min(350px, calc(100vw - 48px));
padding: 18px 18px 16px;
}
.generator-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.eyebrow {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.status-pill {
display: inline-flex;
align-items: center;
gap: 7px;
color: var(--gold);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status-pill::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
animation: pulse 1.1s ease-in-out infinite;
}
#generator.verified .status-pill {
color: var(--green);
}
#generator.failed .status-pill {
color: var(--red);
}
#genTitle {
margin: 0 0 5px;
font-size: 18px;
letter-spacing: -0.02em;
}
#genText {
min-height: 34px;
margin: 0 0 14px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
#checks {
display: grid;
gap: 7px;
margin: 0;
padding: 0;
list-style: none;
}
#checks li {
position: relative;
padding-left: 25px;
color: #66738a;
font-size: 11px;
line-height: 1.35;
transition: color 180ms ease;
}
#checks li::before {
content: "";
position: absolute;
left: 0;
top: 2px;
width: 14px;
height: 14px;
border: 1px solid #3b4558;
border-radius: 4px;
background: rgba(255, 255, 255, 0.02);
}
#checks li.active {
color: var(--ink);
}
#checks li.active::before {
border-color: var(--gold);
background: rgba(231, 200, 106, 0.12);
box-shadow: 0 0 12px rgba(231, 200, 106, 0.12);
}
#checks li.done {
color: #a8b6c8;
}
#checks li.done::before {
content: "✓";
display: grid;
place-items: center;
border-color: var(--green);
color: var(--green);
background: rgba(132, 209, 122, 0.1);
font-size: 9px;
font-weight: 900;
}
#generator.failed #checks li.done::before {
border-color: var(--red);
color: var(--red);
background: rgba(255, 113, 133, 0.1);
}
#summary {
display: none;
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid var(--line);
color: #b8c7da;
font-size: 11px;
line-height: 1.6;
}
#generator.verified #summary {
display: block;
}
#controls {
position: fixed;
z-index: 5;
left: 24px;
bottom: 24px;
width: min(570px, calc(100vw - 48px));
padding: 14px;
}
.control-row {
display: flex;
align-items: end;
gap: 8px;
}
.seed-field {
flex: 1;
min-width: 140px;
}
.seed-field span {
display: block;
margin: 0 0 6px 2px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.15em;
}
input,
button {
height: 38px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.045);
}
input {
width: 100%;
padding: 0 12px;
color: var(--ink);
outline: none;
font-size: 13px;
font-weight: 650;
letter-spacing: 0.04em;
}
input:focus {
border-color: rgba(112, 230, 219, 0.55);
box-shadow: 0 0 0 3px rgba(112, 230, 219, 0.07);
}
button {
padding: 0 13px;
cursor: pointer;
font-size: 11px;
font-weight: 750;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
button:hover {
border-color: rgba(159, 190, 231, 0.38);
background: rgba(255, 255, 255, 0.075);
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
button.primary {
border-color: rgba(112, 230, 219, 0.4);
color: #071414;
background: var(--cyan);
}
button.primary:hover {
background: #91f2e8;
}
button.active {
border-color: rgba(112, 230, 219, 0.38);
color: var(--cyan);
background: rgba(112, 230, 219, 0.08);
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 10px;
}
.chip {
padding: 5px 8px;
border: 1px solid rgba(159, 190, 231, 0.11);
border-radius: 999px;
color: #718097;
background: rgba(255, 255, 255, 0.025);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#hint {
position: fixed;
z-index: 3;
right: 24px;
bottom: 24px;
color: #75839a;
font-size: 10px;
line-height: 1.6;
text-align: right;
pointer-events: none;
text-shadow: 0 2px 10px #000;
}
#hint strong {
color: #b7c5d8;
font-weight: 700;
}
#toast {
position: fixed;
z-index: 10;
left: 50%;
top: 24px;
max-width: min(460px, calc(100vw - 40px));
padding: 10px 14px;
border: 1px solid rgba(255, 113, 133, 0.32);
border-radius: 9px;
color: #ffd8de;
background: rgba(55, 16, 26, 0.9);
font-size: 12px;
transform: translate(-50%, -150%);
opacity: 0;
pointer-events: none;
transition:
transform 220ms ease,
opacity 220ms ease;
}
#toast.visible {
transform: translate(-50%, 0);
opacity: 1;
}
@keyframes pulse {
0%,
100% {
opacity: 0.45;
transform: scale(0.85);
}
50% {
opacity: 1;
transform: scale(1.08);
}
}
@media (max-width: 760px) {
.brand {
top: 17px;
left: 17px;
}
.brand p {
display: none;
}
#generator {
top: auto;
right: 14px;
bottom: 156px;
width: min(330px, calc(100vw - 28px));
padding: 13px;
}
#genText {
min-height: 0;
margin-bottom: 10px;
}
#checks {
gap: 5px;
}
#summary {
display: none !important;
}
#controls {
left: 14px;
bottom: 14px;
width: calc(100vw - 28px);
}
.control-row {
flex-wrap: wrap;
}
.seed-field {
flex-basis: 100%;
}
.control-row button {
flex: 1;
}
#hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel dungeon"></canvas>
<div class="vignette"></div>
<header class="brand">
<div class="brand-mark">Procedural Architecture</div>
<h1>Vowel Vault</h1>
<p>Seeded rooms, aligned gates, verified routes.</p>
</header>
<section id="generator" class="panel" aria-live="polite">
<div class="generator-head">
<div class="eyebrow">Generation Console</div>
<div class="status-pill" id="statusText">Working</div>
</div>
<h2 id="genTitle">Preparing the vault…</h2>
<p id="genText">
The level remains hidden until its door and connectivity checks pass.
</p>
<ol id="checks">
<li data-step="0">Resolve deterministic seed</li>
<li data-step="1">Sample five room modules</li>
<li data-step="2">Carve the connected route graph</li>
<li data-step="3">Validate door alignment</li>
<li data-step="4">Flood-fill every walkable cell</li>
</ol>
<div id="summary"></div>
</section>
<section id="controls" class="panel" aria-label="Dungeon controls">
<div class="control-row">
<label class="seed-field">
<span>World seed</span>
<input
id="seedInput"
value="VOWEL-17"
maxlength="32"
autocomplete="off"
spellcheck="false"
/>
</label>
<button id="regenerate" class="primary">Build level</button>
<button id="randomize">Random</button>
<button id="routeToggle" class="active" aria-pressed="true">Routes</button>
</div>
<div class="chips">
<span class="chip">5 rooms</span>
<span class="chip">5 linked edges</span>
<span class="chip">8 framed doors</span>
<span class="chip">Bounded perimeter</span>
<span class="chip">Deterministic</span>
</div>
</section>
<div id="hint">
<strong>Drag</strong> orbit · <strong>Wheel</strong> zoom<br />
<strong>Right-drag / Shift-drag</strong> pan · <strong>WASD</strong> move
</div>
<div id="toast"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Renderer and scene
// ---------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x080c14);
scene.fog = new THREE.Fog(0x080c14, 34, 68);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
120
);
const hemisphere = new THREE.HemisphereLight(0x9ec5ff, 0x17121d, 1.35);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffe2b5, 2.45);
keyLight.position.set(-11, 19, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -18;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 18;
keyLight.shadow.camera.bottom = -18;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 48;
keyLight.shadow.bias = -0.0006;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x78a8ff, 0.8);
fillLight.position.set(15, 9, -13);
scene.add(fillLight);
// ---------------------------------------------------------------------
// Custom camera controls. No addons are used.
// ---------------------------------------------------------------------
class CameraRig {
constructor(cameraObject, element) {
this.camera = cameraObject;
this.element = element;
this.target = new THREE.Vector3(0, 0.25, 0);
this.yaw = 0.68;
this.pitch = 0.86;
this.radius = 31;
this.minRadius = 15;
this.maxRadius = 48;
this.pointers = new Map();
this.keys = new Set();
this.lastPinchDistance = 0;
this.dragMode = "orbit";
element.addEventListener("contextmenu", (event) => event.preventDefault());
element.addEventListener("pointerdown", (event) => {
element.setPointerCapture(event.pointerId);
this.pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (this.pointers.size === 2) {
this.dragMode = "pinch";
this.lastPinchDistance = this.getPinchDistance();
} else {
this.dragMode =
event.button === 2 || event.shiftKey ? "pan" : "orbit";
}
});
element.addEventListener("pointermove", (event) => {
const previous = this.pointers.get(event.pointerId);
if (!previous) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
previous.x = event.clientX;
previous.y = event.clientY;
if (this.pointers.size >= 2) {
const distance = this.getPinchDistance();
if (distance > 0 && this.lastPinchDistance > 0) {
this.radius = THREE.MathUtils.clamp(
this.radius * (this.lastPinchDistance / distance),
this.minRadius,
this.maxRadius
);
}
this.lastPinchDistance = distance;
return;
}
if (this.dragMode === "orbit") {
this.yaw -= dx * 0.006;
this.pitch = THREE.MathUtils.clamp(
this.pitch + dy * 0.005,
0.38,
1.36
);
} else {
const right = new THREE.Vector3(
Math.cos(this.yaw),
0,
-Math.sin(this.yaw)
);
const forward = new THREE.Vector3(
-Math.sin(this.yaw),
0,
-Math.cos(this.yaw)
);
this.target.addScaledVector(
right,
dx * this.radius * 0.00125
);
this.target.addScaledVector(
forward,
-dy * this.radius * 0.00125
);
this.target.x = THREE.MathUtils.clamp(this.target.x, -9, 9);
this.target.z = THREE.MathUtils.clamp(this.target.z, -8, 8);
}
});
const releasePointer = (event) => {
this.pointers.delete(event.pointerId);
if (this.pointers.size === 1) this.dragMode = "orbit";
if (this.pointers.size === 0) this.lastPinchDistance = 0;
};
element.addEventListener("pointerup", releasePointer);
element.addEventListener("pointercancel", releasePointer);
element.addEventListener("lostpointercapture", releasePointer);
element.addEventListener(
"wheel",
(event) => {
event.preventDefault();
this.radius = THREE.MathUtils.clamp(
this.radius * Math.exp(event.deltaY * 0.001),
this.minRadius,
this.maxRadius
);
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement
) {
return;
}
const key = event.key.toLowerCase();
this.keys.add(key);
if (key === "r") this.reset();
});
window.addEventListener("keyup", (event) => {
this.keys.delete(event.key.toLowerCase());
});
window.addEventListener("blur", () => this.keys.clear());
}
getPinchDistance() {
const values = [...this.pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
reset() {
this.target.set(0, 0.25, 0);
this.yaw = 0.68;
this.pitch = 0.86;
this.radius = 31;
}
update(delta) {
const right = new THREE.Vector3(
Math.cos(this.yaw),
0,
-Math.sin(this.yaw)
);
const forward = new THREE.Vector3(
-Math.sin(this.yaw),
0,
-Math.cos(this.yaw)
);
const movement = new THREE.Vector3();
const speed = this.radius * 0.72 * delta;
if (this.keys.has("w") || this.keys.has("arrowup")) {
movement.addScaledVector(forward, speed);
}
if (this.keys.has("s") || this.keys.has("arrowdown")) {
movement.addScaledVector(forward, -speed);
}
if (this.keys.has("d") || this.keys.has("arrowright")) {
movement.addScaledVector(right, speed);
}
if (this.keys.has("a") || this.keys.has("arrowleft")) {
movement.addScaledVector(right, -speed);
}
this.target.add(movement);
this.target.x = THREE.MathUtils.clamp(this.target.x, -9, 9);
this.target.z = THREE.MathUtils.clamp(this.target.z, -8, 8);
const cosinePitch = Math.cos(this.pitch);
this.camera.position.set(
this.target.x + this.radius * cosinePitch * Math.sin(this.yaw),
this.target.y + this.radius * Math.sin(this.pitch),
this.target.z + this.radius * cosinePitch * Math.cos(this.yaw)
);
this.camera.lookAt(this.target);
}
}
const cameraRig = new CameraRig(camera, canvas);
// ---------------------------------------------------------------------
// Deterministic dungeon description
// ---------------------------------------------------------------------
const GRID = { width: 25, height: 19 };
const ORIGIN_X = (GRID.width - 1) / 2;
const ORIGIN_Z = (GRID.height - 1) / 2;
// Each module is a 5×5 room. Blocked cells are deliberately kept away
// from door approach cells so every module remains traversable in any
// room slot.
const MODULES = [
{
id: "pillar",
name: "Pillar Hall",
accent: 0x77b7ff,
blocked: [[1, 1], [3, 1], [1, 3]],
prop: "pillar",
motif: "cross"
},
{
id: "kiln",
name: "Twin Kilns",
accent: 0xff8a4c,
blocked: [[0, 0], [4, 4]],
prop: "kiln",
motif: "diagonal"
},
{
id: "crown",
name: "Crown Vault",
accent: 0xe7c86a,
blocked: [[1, 1], [3, 1]],
prop: "pillar",
motif: "ring"
},
{
id: "crystal",
name: "Crystal Court",
accent: 0x70e6db,
blocked: [[1, 3], [3, 1]],
prop: "crystal",
motif: "cross"
},
{
id: "fountain",
name: "Quiet Fountain",
accent: 0x9d8cff,
blocked: [[0, 4], [4, 0], [2, 0]],
prop: "fountain",
motif: "ring"
},
{
id: "archive",
name: "Archive Nook",
accent: 0x84d17a,
blocked: [[0, 0], [0, 4], [4, 4]],
prop: "shelf",
motif: "diagonal"
}
];
const ROOM_SLOTS = [
{ id: "A", x: 2, y: 2 },
{ id: "B", x: 11, y: 2 },
{ id: "C", x: 19, y: 2 },
{ id: "D", x: 5, y: 8 },
{ id: "E", x: 15, y: 8 }
];
// The topology is always connected. A-D and B-E share a doorway wall,
// while the other links have short straight corridors.
const EDGES = [
{
a: "A",
b: "B",
aSide: "east",
bSide: "west",
aDoor: { x: 7, y: 4 },
bDoor: { x: 10, y: 4 },
axis: "x"
},
{
a: "B",
b: "C",
aSide: "east",
bSide: "west",
aDoor: { x: 16, y: 4 },
bDoor: { x: 18, y: 4 },
axis: "x"
},
{
a: "A",
b: "D",
aSide: "south",
bSide: "north",
aDoor: { x: 5, y: 7 },
bDoor: { x: 5, y: 7 },
axis: "y"
},
{
a: "B",
b: "E",
aSide: "south",
bSide: "north",
aDoor: { x: 15, y: 7 },
bDoor: { x: 15, y: 7 },
axis: "y"
},
{
a: "D",
b: "E",
aSide: "east",
bSide: "west",
aDoor: { x: 10, y: 10 },
bDoor: { x: 14, y: 10 },
axis: "x"
}
];
function hashString(value) {
let hash = 2166136261;
for (let i = 0; i < value.length; i++) {
hash ^= value.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
function mulberry32(seed) {
return function random() {
let t = (seed += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function shuffled(values, random) {
const result = [...values];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
function keyOf(x, y) {
return `${x},${y}`;
}
function inBounds(x, y) {
return (
x >= 0 &&
y >= 0 &&
x < GRID.width &&
y < GRID.height
);
}
function straightPath(a, b, axis) {
const path = [];
if (axis === "x") {
if (a.y !== b.y) return [];
const start = Math.min(a.x, b.x);
const end = Math.max(a.x, b.x);
for (let x = start; x <= end; x++) path.push({ x, y: a.y });
} else {
if (a.x !== b.x) return [];
const start = Math.min(a.y, b.y);
const end = Math.max(a.y, b.y);
for (let y = start; y <= end; y++) path.push({ x: a.x, y });
}
return path;
}
function sideMatches(room, side, point) {
if (side === "east") {
return (
point.x === room.x + 5 &&
point.y >= room.y &&
point.y <= room.y + 4
);
}
if (side === "west") {
return (
point.x === room.x - 1 &&
point.y >= room.y &&
point.y <= room.y + 4
);
}
if (side === "north") {
return (
point.y === room.y - 1 &&
point.x >= room.x &&
point.x <= room.x + 4
);
}
if (side === "south") {
return (
point.y === room.y + 5 &&
point.x >= room.x &&
point.x <= room.x + 4
);
}
return false;
}
function inwardCell(room, side, point) {
if (side === "east") return { x: point.x - 1, y: point.y };
if (side === "west") return { x: point.x + 1, y: point.y };
if (side === "north") return { x: point.x, y: point.y + 1 };
if (side === "south") return { x: point.x, y: point.y - 1 };
return null;
}
function sideAxis(side) {
return side === "east" || side === "west" ? "x" : "y";
}
function makeDungeonData(seed, attempt) {
const random = mulberry32(
hashString(`${seed.trim()}::module-sequence::${attempt}`)
);
const selectedModules = shuffled(MODULES, random).slice(
0,
ROOM_SLOTS.length
);
const rooms = ROOM_SLOTS.map((slot, index) => ({
...slot,
module: selectedModules[index]
}));
const floors = new Set();
const blocked = new Set();
const floorOwners = new Map();
const walls = new Map();
const corridors = [];
const doors = new Map();
const roomDoors = new Map();
const wallPriority = {
corridor: 1,
room: 2,
border: 3
};
function addFloor(x, y, owner) {
if (!inBounds(x, y)) return;
floors.add(keyOf(x, y));
floorOwners.set(keyOf(x, y), owner);
}
function addWall(x, y, type) {
if (!inBounds(x, y) || floors.has(keyOf(x, y))) return;
const key = keyOf(x, y);
const previous = walls.get(key);
if (
!previous ||
wallPriority[type] > wallPriority[previous]
) {
walls.set(key, type);
}
}
for (const room of rooms) {
for (let y = 0; y < 5; y++) {
for (let x = 0; x < 5; x++) {
addFloor(room.x + x, room.y + y, room.id);
}
}
}
for (const edge of EDGES) {
const path = straightPath(edge.aDoor, edge.bDoor, edge.axis);
corridors.push({ ...edge, path });
for (const point of path) {
addFloor(point.x, point.y, "corridor");
}
const doorPairs = [
[edge.a, edge.aSide, edge.aDoor],
[edge.b, edge.bSide, edge.bDoor]
];
for (const [roomId, side, point] of doorPairs) {
const key = keyOf(point.x, point.y);
if (!roomDoors.has(roomId)) roomDoors.set(roomId, new Set());
roomDoors.get(roomId).add(key);
if (!doors.has(key)) {
doors.set(key, {
x: point.x,
y: point.y,
axis: edge.axis,
references: []
});
}
doors.get(key).references.push({ roomId, side });
}
}
// Explicit room perimeter walls. Door cells are omitted.
for (const room of rooms) {
const openings = roomDoors.get(room.id) || new Set();
const candidates = [];
for (let x = room.x - 1; x <= room.x + 5; x++) {
candidates.push({ x, y: room.y - 1 });
candidates.push({ x, y: room.y + 5 });
}
for (let y = room.y; y <= room.y + 4; y++) {
candidates.push({ x: room.x - 1, y });
candidates.push({ x: room.x + 5, y });
}
candidates.push(
{ x: room.x - 1, y: room.y - 1 },
{ x: room.x + 5, y: room.y - 1 },
{ x: room.x - 1, y: room.y + 5 },
{ x: room.x + 5, y: room.y + 5 }
);
for (const point of candidates) {
if (!openings.has(keyOf(point.x, point.y))) {
addWall(point.x, point.y, "room");
}
}
}
// Corridor side walls are derived from the actual carved path.
for (const corridor of corridors) {
for (const point of corridor.path) {
const neighbors = [
{ x: point.x + 1, y: point.y },
{ x: point.x - 1, y: point.y },
{ x: point.x, y: point.y + 1 },
{ x: point.x, y: point.y - 1 }
];
for (const neighbor of neighbors) {
if (!floors.has(keyOf(neighbor.x, neighbor.y))) {
addWall(neighbor.x, neighbor.y, "corridor");
}
}
}
}
// Continuous outer perimeter makes the finished level bounded.
for (let x = 0; x < GRID.width; x++) {
addWall(x, 0, "border");
addWall(x, GRID.height - 1, "border");
}
for (let y = 0; y < GRID.height; y++) {
addWall(0, y, "border");
addWall(GRID.width - 1, y, "border");
}
for (const room of rooms) {
for (const [localX, localY] of room.module.blocked) {
blocked.add(
keyOf(room.x + localX, room.y + localY)
);
}
}
return {
seed,
attempt,
rooms,
corridors,
doors,
floors,
blocked,
walls,
floorOwners
};
}
// ---------------------------------------------------------------------
// Validation: alignment first, then full connectivity
// ---------------------------------------------------------------------
function validateAlignment(data) {
const errors = [];
const roomMap = new Map(
data.rooms.map((room) => [room.id, room])
);
for (const room of data.rooms) {
for (let y = 0; y < 5; y++) {
for (let x = 0; x < 5; x++) {
const key = keyOf(room.x + x, room.y + y);
if (!data.floors.has(key)) {
errors.push(`Room ${room.id} has a missing floor at ${key}.`);
}
}
}
}
for (const edge of data.corridors) {
if (!edge.path.length) {
errors.push(`Link ${edge.a}-${edge.b} is not a straight path.`);
continue;
}
const first = edge.path[0];
const last = edge.path[edge.path.length - 1];
if (
first.x !== edge.aDoor.x ||
first.y !== edge.aDoor.y
) {
errors.push(`Link ${edge.a}-${edge.b} misses its first door.`);
}
if (
last.x !== edge.bDoor.x ||
last.y !== edge.bDoor.y
) {
errors.push(`Link ${edge.a}-${edge.b} misses its final door.`);
}
for (const point of edge.path) {
const key = keyOf(point.x, point.y);
if (!data.floors.has(key)) {
errors.push(`Corridor cell ${key} is not carved.`);
}
if (data.blocked.has(key)) {
errors.push(`Corridor cell ${key} is obstructed.`);
}
}
const endpoints = [
{
roomId: edge.a,
side: edge.aSide,
point: edge.aDoor
},
{
roomId: edge.b,
side: edge.bSide,
point: edge.bDoor
}
];
for (const endpoint of endpoints) {
const room = roomMap.get(endpoint.roomId);
const key = keyOf(endpoint.point.x, endpoint.point.y);
if (!room) {
errors.push(`Unknown room ${endpoint.roomId}.`);
continue;
}
if (!data.floors.has(key)) {
errors.push(`Door ${key} is not walkable.`);
}
if (!sideMatches(room, endpoint.side, endpoint.point)) {
errors.push(
`Door ${key} does not align with room ${room.id}'s ${endpoint.side} wall.`
);
}
if (sideAxis(endpoint.side) !== edge.axis) {
errors.push(
`Door ${key} faces across its corridor instead of along it.`
);
}
const inward = inwardCell(
room,
endpoint.side,
endpoint.point
);
if (!inward) {
errors.push(`Door ${key} has no inward approach.`);
} else {
const inwardKey = keyOf(inward.x, inward.y);
if (!data.floors.has(inwardKey)) {
errors.push(
`Door ${key} has no floor on its room-facing side.`
);
}
if (data.blocked.has(inwardKey)) {
errors.push(
`Door ${key} is blocked immediately inside room ${room.id}.`
);
}
}
}
}
for (const key of data.floors) {
const [x, y] = key.split(",").map(Number);
if (!inBounds(x, y)) {
errors.push(`Floor ${key} lies outside the bounded grid.`);
}
}
return {
ok: errors.length === 0,
errors: errors.slice(0, 12),
references: EDGES.length * 2
};
}
function validateConnectivity(data) {
const walkable = [...data.floors].filter(
(key) => !data.blocked.has(key)
);
if (!walkable.length) {
return {
ok: false,
errors: ["The dungeon contains no walkable cells."],
count: 0
};
}
const adjacency = (key) => {
const [x, y] = key.split(",").map(Number);
return [
`${x + 1},${y}`,
`${x - 1},${y}`,
`${x},${y + 1}`,
`${x},${y - 1}`
].filter((candidate) => walkable.includes(candidate));
};
const visited = new Set([walkable[0]]);
const queue = [walkable[0]];
while (queue.length) {
const current = queue.shift();
for (const neighbor of adjacency(current)) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
const unreachable = walkable.filter((key) => !visited.has(key));
const errors = unreachable
.slice(0, 12)
.map((key) => `Walkable cell ${key} is disconnected.`);
return {
ok: unreachable.length === 0,
errors,
count: 1,
walkableCount: walkable.length
};
}
function findValidDungeon(seed) {
let lastErrors = ["No candidate could be generated."];
for (let attempt = 0; attempt < 32; attempt++) {
const data = makeDungeonData(seed, attempt);
const alignment = validateAlignment(data);
if (!alignment.ok) {
lastErrors = alignment.errors;
continue;
}
const connectivity = validateConnectivity(data);
if (connectivity.ok) {
return {
data,
alignment,
connectivity
};
}
lastErrors = connectivity.errors;
}
return {
data: null,
alignment: { ok: false, errors: lastErrors },
connectivity: { ok: false, errors: lastErrors }
};
}
// ---------------------------------------------------------------------
// Level rendering
// ---------------------------------------------------------------------
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const floorGeometry = new THREE.BoxGeometry(0.98, 0.18, 0.98);
const wallGeometry = new THREE.BoxGeometry(0.98, 1, 0.98);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.9,
metalness: 0.04
});
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.84,
metalness: 0.06
});
const borderMaterial = new THREE.MeshStandardMaterial({
color: 0x30394b,
roughness: 0.92,
metalness: 0.04
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x171e2b,
roughness: 0.82,
metalness: 0.12
});
const plinthMaterial = new THREE.MeshStandardMaterial({
color: 0x111824,
roughness: 0.92,
metalness: 0.06
});
const goldMaterial = new THREE.MeshStandardMaterial({
color: 0xd6b75f,
emissive: 0x6e4d13,
emissiveIntensity: 0.35,
roughness: 0.45,
metalness: 0.58
});
const routeMaterial = new THREE.MeshStandardMaterial({
color: 0x70e6db,
emissive: 0x35d9cf,
emissiveIntensity: 0.85,
roughness: 0.4,
metalness: 0.1
});
const flameMaterial = new THREE.MeshStandardMaterial({
color: 0xffbd63,
emissive: 0xff6a24,
emissiveIntensity: 2.2,
roughness: 0.35
});
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x8d83ff,
emissive: 0x473bbd,
emissiveIntensity: 0.75,
roughness: 0.24,
metalness: 0.25
});
const accentMaterials = new Map();
function accentMaterial(color) {
if (!accentMaterials.has(color)) {
accentMaterials.set(
color,
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.48,
roughness: 0.48,
metalness: 0.18
})
);
}
return accentMaterials.get(color);
}
function worldPosition(x, y, elevation = 0) {
return new THREE.Vector3(
x - ORIGIN_X,
elevation,
y - ORIGIN_Z
);
}
function addVoxel(parent, material, position, scale) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.position.copy(position);
mesh.scale.copy(scale);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function coordinateHash(x, y, salt = 0) {
let hash = hashString(`${x}:${y}:${salt}`);
hash ^= hash << 13;
hash ^= hash >>> 17;
hash ^= hash << 5;
return (hash >>> 0) / 4294967295;
}
let levelRoot = null;
let routeGroup = null;
let routesVisible = true;
let animatedFlames = [];
let animatedCrystals = [];
let animatedLights = [];
let revealStartedAt = 0;
function clearLevel() {
if (!levelRoot) return;
levelRoot.traverse((object) => {
if (object.isInstancedMesh && object.dispose) {
object.dispose();
}
});
scene.remove(levelRoot);
levelRoot = null;
routeGroup = null;
animatedFlames = [];
animatedCrystals = [];
animatedLights = [];
}
function addModuleProp(parent, room, localX, localY) {
const module = room.module;
const position = worldPosition(
room.x + localX,
room.y + localY,
0
);
const group = new THREE.Group();
group.position.copy(position);
parent.add(group);
const accent = accentMaterial(module.accent);
if (module.prop === "pillar") {
addVoxel(
group,
darkMaterial,
new THREE.Vector3(0, 0.15, 0),
new THREE.Vector3(0.74, 0.3, 0.74)
);
addVoxel(
group,
accent,
new THREE.Vector3(0, 0.78, 0),
new THREE.Vector3(0.5, 0.96, 0.5)
);
addVoxel(
group,
goldMaterial,
new THREE.Vector3(0, 1.34, 0),
new THREE.Vector3(0.68, 0.16, 0.68)
);
} else if (module.prop === "kiln") {
addVoxel(
group,
darkMaterial,
new THREE.Vector3(0, 0.17, 0),
new THREE.Vector3(0.78, 0.34, 0.78)
);
addVoxel(
group,
accent,
new THREE.Vector3(0, 0.62, 0),
new THREE.Vector3(0.62, 0.56, 0.62)
);
addVoxel(
group,
flameMaterial,
new THREE.Vector3(0, 1.0, 0),
new THREE.Vector3(0.38, 0.2, 0.38)
);
} else if (module.prop === "crystal") {
addVoxel(
group,
darkMaterial,
new THREE.Vector3(0, 0.13, 0),
new THREE.Vector3(0.72, 0.26, 0.72)
);
addVoxel(
group,
accent,
new THREE.Vector3(0, 0.51, 0),
new THREE.Vector3(0.46, 0.48, 0.46)
);
addVoxel(
group,
accent,
new THREE.Vector3(0, 0.88, 0),
new THREE.Vector3(0.28, 0.3, 0.28)
);
animatedCrystals.push({
group,
phase: coordinateHash(room.x, room.y) * Math.PI * 2
});
} else if (module.prop === "fountain") {
addVoxel(
group,
darkMaterial,
new THREE.Vector3(0, 0.14, 0),
new THREE.Vector3(0.76, 0.28, 0.76)
);
addVoxel(
group,
waterMaterial,
new THREE.Vector3(0, 0.32, 0),
new THREE.Vector3(0.54, 0.08, 0.54)
);
} else if (module.prop === "shelf") {
addVoxel(
group,
darkMaterial,
new THREE.Vector3(-0.22, 0.72, 0),
new THREE.Vector3(0.18, 1.44, 0.62)
);
addVoxel(
group,
darkMaterial,
new THREE.Vector3(0.22, 0.72, 0),
new THREE.Vector3(0.18, 1.44, 0.62)
);
addVoxel(
group,
accent,
new THREE.Vector3(0, 1.12, 0),
new THREE.Vector3(0.62, 0.16, 0.7)
);
addVoxel(
group,
accent,
new THREE.Vector3(0, 0.62, 0),
new THREE.Vector3(0.62, 0.16, 0.7)
);
}
}
function addWallTorch(parent, room, wallX, wallY, face) {
const group = new THREE.Group();
const position = worldPosition(wallX, wallY, 0);
group.position.copy(position);
parent.add(group);
const inward = new THREE.Vector3(
face === "east" ? -0.43 : 0,
0,
face === "north" ? 0.43 : 0
);
addVoxel(
group,
darkMaterial,
inward.clone().add(new THREE.Vector3(0, 0.78, 0)),
new THREE.Vector3(0.18, 0.38, 0.18)
);
const flame = addVoxel(
group,
flameMaterial,
inward.clone().add(new THREE.Vector3(0, 1.04, 0)),
new THREE.Vector3(0.19, 0.28, 0.19)
);
animatedFlames.push({
mesh: flame,
baseScale: flame.scale.clone(),
phase:
coordinateHash(wallX, wallY, 91) * Math.PI * 2
});
}
function addDoorFrame(parent, door) {
const group = new THREE.Group();
const position = worldPosition(door.x, door.y, 0);
group.position.copy(position);
parent.add(group);
addVoxel(
group,
goldMaterial,
new THREE.Vector3(0, 0.025, 0),
new THREE.Vector3(0.82, 0.05, 0.82)
);
if (door.axis === "x") {
addVoxel(
group,
goldMaterial,
new THREE.Vector3(0, 0.62, -0.44),
new THREE.Vector3(0.15, 1.24, 0.15)
);
addVoxel(
group,
goldMaterial,
new THREE.Vector3(0, 0.62, 0.44),
new THREE.Vector3(0.15, 1.24, 0.15)
);
addVoxel(
group,
goldMaterial,
new THREE.Vector3(0, 1.24, 0),
new THREE.Vector3(0.17, 0.16, 0.98)
);
} else {
addVoxel(
group,
goldMaterial,
new THREE.Vector3(-0.44, 0.62, 0),
new THREE.Vector3(0.15, 1.24, 0.15)
);
addVoxel(
group,
goldMaterial,
new THREE.Vector3(0.44, 0.62, 0),
new THREE.Vector3(0.15, 1.24, 0.15)
);
addVoxel(
group,
goldMaterial,
new THREE.Vector3(0, 1.24, 0),
new THREE.Vector3(0.98, 0.16, 0.17)
);
}
}
function buildLevel(data) {
clearLevel();
levelRoot = new THREE.Group();
levelRoot.visible = false;
scene.add(levelRoot);
routeGroup = new THREE.Group();
routeGroup.visible = routesVisible;
levelRoot.add(routeGroup);
// Bounded stone plinth and ground.
addVoxel(
levelRoot,
plinthMaterial,
new THREE.Vector3(0, -0.47, 0),
new THREE.Vector3(GRID.width + 1.1, 0.56, GRID.height + 1.1)
);
addVoxel(
levelRoot,
darkMaterial,
new THREE.Vector3(0, -0.8, 0),
new THREE.Vector3(GRID.width + 2.3, 0.22, GRID.height + 2.3)
);
const floorCells = [...data.floors];
const floorMesh = new THREE.InstancedMesh(
floorGeometry,
floorMaterial,
floorCells.length
);
floorMesh.receiveShadow = true;
floorMesh.castShadow = false;
const roomById = new Map(
data.rooms.map((room) => [room.id, room])
);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
const roomStone = new THREE.Color(0x354158);
const corridorStone = new THREE.Color(0x34445b);
floorCells.forEach((key, index) => {
const [x, y] = key.split(",").map(Number);
const position = worldPosition(x, y, -0.09);
const owner = data.floorOwners.get(key);
dummy.position.copy(position);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
floorMesh.setMatrixAt(index, dummy.matrix);
if (owner === "corridor") {
color.copy(corridorStone);
} else {
const room = roomById.get(owner);
const localX = x - room.x;
const localY = y - room.y;
color.copy(roomStone).lerp(
new THREE.Color(room.module.accent),
0.16
);
const motif = room.module.motif;
const motifCell =
(motif === "cross" &&
(localX === 2 || localY === 2)) ||
(motif === "ring" &&
Math.abs(localX - 2) + Math.abs(localY - 2) <= 2) ||
(motif === "diagonal" && localX === localY);
if (motifCell) {
color.lerp(
new THREE.Color(room.module.accent),
0.26
);
}
}
const variation = coordinateHash(x, y, 17) - 0.5;
color.offsetHSL(0, 0, variation * 0.045);
floorMesh.setColorAt(index, color);
});
floorMesh.instanceMatrix.needsUpdate = true;
if (floorMesh.instanceColor) {
floorMesh.instanceColor.needsUpdate = true;
}
levelRoot.add(floorMesh);
// Standard room and corridor walls.
const regularWalls = [...data.walls.entries()].filter(
([, type]) => type !== "border"
);
const wallMesh = new THREE.InstancedMesh(
wallGeometry,
wallMaterial,
regularWalls.length
);
wallMesh.castShadow = true;
wallMesh.receiveShadow = true;
regularWalls.forEach(([key], index) => {
const [x, y] = key.split(",").map(Number);
const height = 1.28 + coordinateHash(x, y, 31) * 0.24;
dummy.position.copy(worldPosition(x, y, height / 2));
dummy.scale.set(1, height, 1);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
wallMesh.setMatrixAt(index, dummy.matrix);
color.set(0x56637a);
color.lerp(
new THREE.Color(0x303a4e),
coordinateHash(x, y, 49) * 0.5
);
wallMesh.setColorAt(index, color);
});
wallMesh.instanceMatrix.needsUpdate = true;
if (wallMesh.instanceColor) {
wallMesh.instanceColor.needsUpdate = true;
}
levelRoot.add(wallMesh);
// Lower continuous outer boundary.
const boundaryWalls = [...data.walls.entries()].filter(
([, type]) => type === "border"
);
const boundaryMesh = new THREE.InstancedMesh(
wallGeometry,
borderMaterial,
boundaryWalls.length
);
boundaryMesh.castShadow = true;
boundaryMesh.receiveShadow = true;
boundaryWalls.forEach(([key], index) => {
const [x, y] = key.split(",").map(Number);
dummy.position.copy(worldPosition(x, y, 0.4));
dummy.scale.set(1, 0.8, 1);
dummy.updateMatrix();
boundaryMesh.setMatrixAt(index, dummy.matrix);
});
boundaryMesh.instanceMatrix.needsUpdate = true;
levelRoot.add(boundaryMesh);
// Corner towers.
for (const [x, z] of [
[0, 0],
[GRID.width - 1, 0],
[0, GRID.height - 1],
[GRID.width - 1, GRID.height - 1]
]) {
addVoxel(
levelRoot,
darkMaterial,
worldPosition(x, z, 0.7),
new THREE.Vector3(1.16, 1.4, 1.16)
);
addVoxel(
levelRoot,
goldMaterial,
worldPosition(x, z, 1.44),
new THREE.Vector3(0.75, 0.12, 0.75)
);
}
// Room medallions, module props, torches, and local lights.
for (const room of data.rooms) {
const center = worldPosition(
room.x + 2,
room.y + 2,
0.035
);
addVoxel(
levelRoot,
accentMaterial(room.module.accent),
center,
new THREE.Vector3(0.72, 0.035, 0.72)
);
for (const [localX, localY] of room.module.blocked) {
addModuleProp(levelRoot, room, localX, localY);
}
// These positions are deliberately away from every door.
addWallTorch(
levelRoot,
room,
room.x + 4,
room.y - 1,
"north"
);
addWallTorch(
levelRoot,
room,
room.x + 5,
room.y,
"east"
);
const lightPosition = worldPosition(
room.x + 2,
room.y + 2,
1.65
);
const light = new THREE.PointLight(
room.module.accent,
7.5,
5.3,
2
);
light.position.copy(lightPosition);
levelRoot.add(light);
animatedLights.push({
light,
phase: coordinateHash(room.x, room.y, 73) * Math.PI * 2
});
}
// Door frames are generated only after alignment validation.
for (const door of data.doors.values()) {
addDoorFrame(levelRoot, door);
}
// Glowing route ribbons make the verified topology visible.
for (const corridor of data.corridors) {
for (const point of corridor.path) {
const position = worldPosition(point.x, point.y, 0.043);
const scale =
corridor.axis === "x"
? new THREE.Vector3(0.96, 0.035, 0.14)
: new THREE.Vector3(0.14, 0.035, 0.96);
addVoxel(
routeGroup,
routeMaterial,
position,
scale
);
}
}
levelRoot.scale.setScalar(0.96);
levelRoot.position.y = -0.12;
}
// ---------------------------------------------------------------------
// UI and generation workflow
// ---------------------------------------------------------------------
const generatorPanel = document.querySelector("#generator");
const generatorTitle = document.querySelector("#genTitle");
const generatorText = document.querySelector("#genText");
const statusText = document.querySelector("#statusText");
const summary = document.querySelector("#summary");
const checkItems = [...document.querySelectorAll("#checks li")];
const seedInput = document.querySelector("#seedInput");
const regenerateButton = document.querySelector("#regenerate");
const randomizeButton = document.querySelector("#randomize");
const routeToggle = document.querySelector("#routeToggle");
const toast = document.querySelector("#toast");
let generationToken = 0;
let toastTimer = 0;
function setCheck(index, state, text) {
const item = checkItems[index];
item.className = state;
if (text) item.textContent = text;
}
function resetChecks() {
checkItems.forEach((item, index) => {
item.className = "";
item.textContent = [
"Resolve deterministic seed",
"Sample five room modules",
"Carve the connected route graph",
"Validate door alignment",
"Flood-fill every walkable cell"
][index];
});
}
function pause(milliseconds) {
return new Promise((resolve) =>
setTimeout(resolve, milliseconds)
);
}
function showToast(message) {
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("visible");
}, 5000);
}
function updateSeedInURL(seed) {
try {
const url = new URL(window.location.href);
url.searchParams.set("seed", seed);
window.history.replaceState(null, "", url);
} catch {
// The scene still works when opened from restricted local contexts.
}
}
async function generateLevel(rawSeed) {
const token = ++generationToken;
const seed = rawSeed.trim() || "VOWEL-17";
seedInput.value = seed;
updateSeedInURL(seed);
if (levelRoot) levelRoot.visible = false;
generatorPanel.className = "panel";
statusText.textContent = "Working";
generatorTitle.textContent = "Preparing the vault…";
generatorText.textContent =
"The level remains hidden until its door and connectivity checks pass.";
summary.style.display = "none";
resetChecks();
setCheck(0, "active", "Resolve deterministic seed");
await pause(180);
if (token !== generationToken) return;
setCheck(0, "done", `Seed resolved: ${seed}`);
setCheck(1, "active", "Sample five room modules");
await pause(180);
if (token !== generationToken) return;
setCheck(1, "done", "Five unique modules sampled from six");
setCheck(2, "active", "Carve the connected route graph");
await pause(180);
if (token !== generationToken) return;
setCheck(2, "done", "Five links carved with eight unique doorways");
setCheck(3, "active", "Validate door alignment");
await pause(160);
if (token !== generationToken) return;
const result = findValidDungeon(seed);
if (!result.alignment.ok) {
setCheck(3, "done", "Door alignment failed");
generatorPanel.className = "panel failed";
statusText.textContent = "Rejected";
generatorTitle.textContent = "Level withheld";
generatorText.textContent =
result.alignment.errors.join(" ") ||
"The generated topology failed validation.";
showToast("Generation failed validation; no level was shown.");
return;
}
setCheck(3, "done", "10 of 10 door references aligned");
setCheck(4, "active", "Flood-fill every walkable cell");
await pause(160);
if (token !== generationToken) return;
if (!result.connectivity.ok) {
setCheck(4, "done", "Connectivity check failed");
generatorPanel.className = "panel failed";
statusText.textContent = "Rejected";
generatorTitle.textContent = "Level withheld";
generatorText.textContent =
result.connectivity.errors.join(" ") ||
"The generated dungeon was not fully connected.";
showToast("Generation failed validation; no level was shown.");
return;
}
setCheck(
4,
"done",
`Flood-fill passed: 1 component, ${result.connectivity.walkableCount} cells`
);
buildLevel(result.data);
// The completed level is revealed only after both validation stages.
levelRoot.visible = true;
revealStartedAt = performance.now();
generatorPanel.className = "panel verified";
statusText.textContent = "Verified";
generatorTitle.textContent = "Level verified";
generatorText.textContent =
"Every room and corridor belongs to one connected walkable component.";
summary.textContent =
`${result.data.rooms.length} rooms · ` +
`${result.data.corridors.length} connected links · ` +
`${result.data.doors.size} framed doors · ` +
`${result.connectivity.walkableCount} validated cells`;
summary.style.display = "block";
}
regenerateButton.addEventListener("click", () => {
generateLevel(seedInput.value);
});
seedInput.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
generateLevel(seedInput.value);
}
});
randomizeButton.addEventListener("click", () => {
let randomPart;
if (window.crypto && window.crypto.getRandomValues) {
const values = new Uint32Array(1);
window.crypto.getRandomValues(values);
randomPart = values[0].toString(36).toUpperCase();
} else {
randomPart = Date.now().toString(36).toUpperCase();
}
generateLevel(`RUNE-${randomPart}`);
});
routeToggle.addEventListener("click", () => {
routesVisible = !routesVisible;
if (routeGroup) routeGroup.visible = routesVisible;
routeToggle.classList.toggle("active", routesVisible);
routeToggle.setAttribute("aria-pressed", String(routesVisible));
routeToggle.textContent = routesVisible ? "Routes" : "Routes off";
});
// ---------------------------------------------------------------------
// Resize and render loop
// ---------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(
Math.min(window.devicePixelRatio || 1, 2)
);
renderer.setSize(window.innerWidth, window.innerHeight);
});
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(160, 160),
new THREE.MeshStandardMaterial({
color: 0x080b12,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.93;
ground.receiveShadow = true;
scene.add(ground);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
cameraRig.update(delta);
if (levelRoot && levelRoot.visible) {
const revealProgress = THREE.MathUtils.clamp(
(performance.now() - revealStartedAt) / 720,
0,
1
);
const eased = 1 - Math.pow(1 - revealProgress, 3);
levelRoot.scale.setScalar(0.96 + eased * 0.04);
levelRoot.position.y = -0.12 * (1 - eased);
for (const flame of animatedFlames) {
const pulse = Math.sin(elapsed * 5.2 + flame.phase);
flame.mesh.scale.y =
flame.baseScale.y * (1 + pulse * 0.08);
flame.mesh.scale.x =
flame.baseScale.x * (1 - pulse * 0.035);
flame.mesh.scale.z =
flame.baseScale.z * (1 - pulse * 0.035);
}
for (const crystal of animatedCrystals) {
crystal.group.rotation.y =
elapsed * 0.34 + crystal.phase;
}
for (const item of animatedLights) {
item.light.intensity =
7.5 + Math.sin(elapsed * 2.1 + item.phase) * 0.7;
}
routeMaterial.emissiveIntensity =
0.78 + Math.sin(elapsed * 2.3) * 0.16;
}
renderer.render(scene, camera);
}
animate();
const initialSeed =
new URLSearchParams(window.location.search).get("seed") ||
"VOWEL-17";
generateLevel(initialSeed);
</script>
</body>
</html>
```