Prompt specification
Build or customize the Three.js 3D scene "Replanning After a Corridor Closes" 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: Replanning After a Corridor Closes
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/replanning-after-a-corridor-closes-x3460
Scene Description Prompt:
Use Three.js from cdnjs to create a playable grid puzzle with two routes and a triggered blockage. Preserve the goal, expose changed adjacency, and allow reset without regenerating the level. Deliver one self-contained HTML file with visible voxel blocks.
Technical checks: After the trigger, close the upper corridor and open the lower connection. In the adjacency list, give each neighbor a single consistent accessibility state. Reset to the original graph.
Return one complete HTML document that works with the cdnjs Three.js r160 module inside a sandbox with scripts allowed. Make the requested subject visible at the default camera. Use procedural assets and local button handlers. Do not use native form submission, pointer lock, external assets or runtime requests other than Three.js.
Working Three.js Starter (replanning-after-a-corridor-closes-x3460):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#07131f">
<link rel="icon" href="data:,">
<title>Labirinto Voxel — Adjacência em Tempo Real</title>
<style>
:root {
color-scheme: dark;
--bg: #07131f;
--panel: #0b1725;
--panel-2: #101f2f;
--line: #23364a;
--text: #edf5ff;
--muted: #91a6ba;
--upper: #ffb454;
--lower: #43c8ff;
--open: #58e6ad;
--closed: #ff5c70;
--trigger: #ff526b;
--gold: #ffe16a;
}
* { 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, summary { font: inherit; }
button:focus-visible,
summary:focus-visible {
outline: 2px solid #72d9ff;
outline-offset: 3px;
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
width: 100%;
height: 100vh;
height: 100dvh;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 30%, rgba(47, 93, 125, 0.18), transparent 52%),
var(--bg);
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage::after {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
background: radial-gradient(circle at center, transparent 55%, rgba(1, 7, 13, 0.46));
}
.stage-top {
position: absolute;
z-index: 3;
top: 20px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
pointer-events: none;
}
.brand-card,
.state-pill {
border: 1px solid rgba(133, 170, 202, 0.25);
background: rgba(7, 18, 30, 0.78);
box-shadow: 0 14px 35px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(12px);
}
.brand-card {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 13px;
border-radius: 14px;
}
.level-code {
display: grid;
place-items: center;
min-width: 49px;
height: 38px;
border-radius: 9px;
color: #06101a;
background: linear-gradient(135deg, #ffe16a, #ffae4d);
font-size: 12px;
font-weight: 900;
letter-spacing: 0.06em;
}
.brand-card b {
display: block;
font-size: 13px;
letter-spacing: 0.13em;
}
.brand-card small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.1em;
}
.state-pill {
display: flex;
align-items: center;
gap: 8px;
padding: 11px 14px;
border-radius: 999px;
color: #b9c9d8;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
}
.state-pill::before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: #7f95a9;
box-shadow: 0 0 0 4px rgba(127, 149, 169, 0.12);
}
.state-pill[data-mode="triggered"]::before {
background: var(--trigger);
box-shadow: 0 0 0 4px rgba(255, 82, 107, 0.14);
}
.state-pill[data-mode="success"]::before {
background: var(--gold);
box-shadow: 0 0 0 4px rgba(255, 225, 106, 0.16);
}
.stage-bottom {
position: absolute;
z-index: 3;
right: 20px;
bottom: 18px;
left: 20px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 18px;
pointer-events: none;
}
.position-card,
.control-hint {
border: 1px solid rgba(133, 170, 202, 0.22);
border-radius: 12px;
background: rgba(7, 18, 30, 0.82);
backdrop-filter: blur(10px);
}
.position-card {
padding: 9px 12px;
color: #dbe9f5;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.06em;
}
.control-hint {
max-width: 420px;
padding: 9px 12px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
text-align: right;
}
#panel {
min-width: 0;
height: 100%;
padding: 24px 22px 30px;
overflow-y: auto;
border-left: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(16, 31, 47, 0.96), rgba(8, 20, 32, 0.98));
scrollbar-color: #30485f transparent;
scrollbar-width: thin;
}
.eyebrow {
color: #6fd9ff;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.18em;
}
h1 {
margin: 7px 0 8px;
font-size: 28px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.intro {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.objective-card {
position: relative;
margin: 19px 0 14px;
padding: 15px 15px 14px;
overflow: hidden;
border: 1px solid #294157;
border-radius: 15px;
background: linear-gradient(135deg, rgba(39, 72, 99, 0.55), rgba(16, 33, 49, 0.8));
}
.objective-card::after {
content: "";
position: absolute;
top: -34px;
right: -34px;
width: 92px;
height: 92px;
border: 18px solid rgba(255, 180, 84, 0.07);
border-radius: 22px;
transform: rotate(18deg);
}
.objective-card strong {
display: block;
margin-bottom: 5px;
font-size: 12px;
letter-spacing: 0.06em;
}
.objective-card p {
position: relative;
z-index: 1;
margin: 0;
color: #c6d7e6;
font-size: 12px;
line-height: 1.5;
}
.route-cards {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-bottom: 19px;
}
.route-card {
--route: var(--upper);
padding: 12px;
border: 1px solid color-mix(in srgb, var(--route) 32%, #26384a);
border-radius: 13px;
background: color-mix(in srgb, var(--route) 6%, #0d1b29);
}
.route-card.lower { --route: var(--lower); }
.route-card > span {
display: block;
color: var(--route);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.08em;
}
.route-card strong {
display: block;
margin: 5px 0 3px;
font-size: 15px;
letter-spacing: 0.03em;
}
.route-card strong[data-status="open"] { color: var(--open); }
.route-card strong[data-status="closed"] { color: var(--closed); }
.route-card small {
color: var(--muted);
font-size: 10px;
}
.panel-section {
margin: 0 0 18px;
padding-top: 17px;
border-top: 1px solid var(--line);
}
.section-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 11px;
}
.section-head h2 {
margin: 0 0 4px;
font-size: 13px;
letter-spacing: 0.04em;
}
.section-head p {
margin: 0;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.coord-chip {
flex: 0 0 auto;
padding: 5px 7px;
border: 1px solid #2b4258;
border-radius: 7px;
color: #a9bfd2;
background: #0a1623;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
#adjacencySummary {
color: var(--muted);
font-size: 10px;
}
#adjacencyList {
display: grid;
gap: 7px;
}
.adj-row {
display: grid;
grid-template-columns: 10px minmax(0, 1fr) auto;
align-items: center;
gap: 9px;
width: 100%;
padding: 10px 11px;
border: 1px solid #263a4e;
border-radius: 10px;
color: var(--text);
background: #0b1927;
text-align: left;
cursor: pointer;
transition: border-color 150ms ease, background 150ms ease, transform 150ms ease;
}
.adj-row:hover {
border-color: #3f607c;
background: #102235;
transform: translateX(2px);
}
.node-dot {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--node-color);
box-shadow: 0 0 9px color-mix(in srgb, var(--node-color) 45%, transparent);
}
.adj-name {
min-width: 0;
}
.adj-name b {
display: block;
overflow: hidden;
font-size: 11px;
text-overflow: ellipsis;
white-space: nowrap;
}
.adj-name small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
font-variant-numeric: tabular-nums;
}
.status {
min-width: 63px;
padding: 5px 7px;
border-radius: 999px;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.06em;
text-align: center;
}
.status.open {
color: var(--open);
background: rgba(88, 230, 173, 0.11);
border: 1px solid rgba(88, 230, 173, 0.25);
}
.status.closed {
color: var(--closed);
background: rgba(255, 92, 112, 0.1);
border: 1px solid rgba(255, 92, 112, 0.25);
}
.empty-state {
padding: 13px;
border: 1px dashed #2b4055;
border-radius: 10px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
text-align: center;
}
#changesList {
display: grid;
gap: 8px;
}
.change-row {
padding: 10px 11px;
border: 1px solid rgba(255, 180, 84, 0.24);
border-radius: 10px;
background: rgba(255, 180, 84, 0.055);
}
.change-row b {
font-size: 10px;
}
.change-row small {
color: var(--muted);
font-size: 9px;
}
.change-delta {
display: flex;
align-items: center;
gap: 7px;
margin-top: 7px;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.05em;
}
.before.open { color: var(--open); }
.before.closed { color: var(--closed); }
.after.open { color: var(--open); }
.after.closed { color: var(--closed); }
.change-delta i { color: #70869a; font-style: normal; }
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 3px 0 17px;
}
.controls button {
min-height: 42px;
padding: 10px 11px;
border: 1px solid #314b63;
border-radius: 10px;
color: #d9e7f2;
background: #102234;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.05em;
cursor: pointer;
transition: transform 120ms ease, border-color 120ms ease, background 120ms ease;
}
.controls button:hover:not(:disabled) {
border-color: #5b809f;
background: #142b40;
transform: translateY(-1px);
}
.controls button.primary {
grid-column: 1 / -1;
color: #18070b;
border-color: #ff7c8f;
background: linear-gradient(135deg, #ff7186, #ff4d69);
box-shadow: 0 9px 24px rgba(255, 77, 105, 0.18);
}
.controls button.primary:disabled {
color: #9eabb7;
border-color: #304050;
background: #172533;
box-shadow: none;
cursor: default;
}
.audit-card {
padding: 12px;
border: 1px solid #294054;
border-radius: 12px;
background: #091522;
}
.audit-badge {
display: inline-flex;
align-items: center;
padding: 6px 8px;
border-radius: 7px;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.06em;
}
.audit-badge.ok {
color: var(--open);
border: 1px solid rgba(88, 230, 173, 0.26);
background: rgba(88, 230, 173, 0.08);
}
.audit-badge.bad {
color: var(--closed);
border: 1px solid rgba(255, 92, 112, 0.3);
background: rgba(255, 92, 112, 0.09);
}
#auditDetail {
margin: 8px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
font-variant-numeric: tabular-nums;
}
details {
margin-top: 13px;
border: 1px solid #24384c;
border-radius: 11px;
background: #091522;
}
summary {
padding: 11px 12px;
color: #b8cad9;
font-size: 10px;
font-weight: 800;
cursor: pointer;
}
#topologyList {
display: grid;
gap: 1px;
padding: 0 8px 8px;
}
.topology-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
padding: 7px 5px;
border-top: 1px solid #182a3b;
color: #9db1c3;
font-size: 9px;
}
.topology-row .status {
min-width: 58px;
padding: 3px 5px;
font-size: 8px;
}
.panel-footer {
margin: 16px 2px 0;
color: #6f8498;
font-size: 9px;
line-height: 1.5;
}
#toast {
position: absolute;
z-index: 8;
left: 50%;
bottom: 82px;
max-width: min(520px, calc(100% - 40px));
padding: 11px 15px;
border: 1px solid #38536c;
border-radius: 10px;
color: #e5f1fa;
background: rgba(8, 19, 30, 0.94);
box-shadow: 0 14px 38px rgba(0, 0, 0, 0.35);
font-size: 11px;
line-height: 1.4;
text-align: center;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 10px);
transition: opacity 180ms ease, transform 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast[data-kind="success"] {
border-color: rgba(255, 225, 106, 0.45);
color: #fff3b2;
}
#toast[data-kind="warning"] {
border-color: rgba(255, 92, 112, 0.48);
}
#loading {
position: absolute;
z-index: 20;
inset: 0;
display: grid;
place-items: center;
color: #a9c1d4;
background: #07131f;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.1em;
transition: opacity 300ms ease;
}
#loading.is-hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 900px) {
html, body {
height: auto;
min-height: 100%;
overflow: auto;
}
#app {
display: flex;
flex-direction: column;
height: auto;
min-height: 100dvh;
}
#stage {
flex: 0 0 66dvh;
min-height: 460px;
}
#panel {
width: 100%;
height: auto;
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.stage-top {
top: 12px;
right: 12px;
left: 12px;
}
.stage-bottom {
right: 12px;
bottom: 12px;
left: 12px;
}
.control-hint {
display: none;
}
}
@media (max-width: 520px) {
#panel { padding: 20px 15px 26px; }
h1 { font-size: 25px; }
.brand-card small { display: none; }
.state-pill { padding: 10px; font-size: 9px; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
scroll-behavior: auto !important;
transition-duration: 0.01ms !important;
animation-duration: 0.01ms !important;
}
}
</style>
</head>
<body>
<div id="app">
<main id="stage" aria-label="Puzzle tridimensional de rotas voxel">
<canvas id="scene" aria-label="Tabuleiro voxel interativo"></canvas>
<div class="stage-top">
<div class="brand-card">
<span class="level-code">R//07</span>
<div>
<b>ROTA VOXEL</b>
<small>ADJACÊNCIA EM TEMPO REAL</small>
</div>
</div>
<div id="statePill" class="state-pill" data-mode="initial">
<span id="stateText">ESTADO INICIAL</span>
</div>
</div>
<div class="stage-bottom">
<div id="currentPosition" class="position-card">CUBO · INÍCIO (0, 2)</div>
<div class="control-hint">
Clique em uma peça vizinha e aberta para mover · Arraste para girar ·
Use a roda para zoom · Teclado: setas, Espaço e R
</div>
</div>
<div id="toast" role="status" aria-live="polite"></div>
<div id="loading">CARREGANDO O LABORATÓRIO VOXEL…</div>
</main>
<aside id="panel" aria-label="Dados e controles do puzzle">
<header>
<div class="eyebrow">PUZZLE DE ROTAS VOXEL</div>
<h1>Escolha o caminho.</h1>
<p class="intro">
Uma única ligação superior, uma ligação inferior e um gatilho que troca
a topologia sem mover a meta.
</p>
</header>
<section class="objective-card">
<strong>OBJETIVO</strong>
<p>
Dispare o gatilho, observe a adjacência mudar e leve o cubo à
<b>META (6, 2)</b>. Depois do disparo, o corredor superior fecha e a
ligação inferior abre.
</p>
</section>
<div class="route-cards">
<div class="route-card upper">
<span>ROTA SUPERIOR</span>
<strong id="upperState" data-status="open">ABERTA</strong>
<small>Upper 02 → Upper 03</small>
</div>
<div class="route-card lower">
<span>LIGAÇÃO INFERIOR</span>
<strong id="lowerState" data-status="closed">FECHADA</strong>
<small>Upper 02 → Lower 01</small>
</div>
</div>
<section class="panel-section">
<div class="section-head">
<div>
<h2>ADJACÊNCIA INSPECIONADA</h2>
<p>Cada vizinho aparece uma única vez, com um único estado.</p>
</div>
<span id="selectedCoord" class="coord-chip">(3, 2)</span>
</div>
<div class="section-head">
<strong id="selectedName">Upper 02</strong>
<span id="adjacencySummary">3 conexões</span>
</div>
<div id="adjacencyList"></div>
</section>
<section class="panel-section">
<div class="section-head">
<div>
<h2>MUDANÇAS DO GATILHO</h2>
<p>Antes e depois, usando a mesma fonte de dados.</p>
</div>
</div>
<div id="changesList"></div>
</section>
<div class="controls">
<button id="triggerBtn" class="primary" type="button">DISPARAR GATILHO</button>
<button id="resetBtn" type="button">REINICIAR R-07</button>
<button id="auditBtn" type="button">VERIFICAR DADOS + 3D</button>
<button id="homeBtn" type="button">RESTAURAR CÂMERA</button>
</div>
<section class="audit-card" aria-label="Resultado da auditoria">
<span id="auditBadge" class="audit-badge ok">TESTE REAL: OK · INICIAL</span>
<p id="auditDetail">Preparando auditoria de dados e geometria…</p>
</section>
<details>
<summary>VER TOPOLOGIA COMPLETA</summary>
<div id="topologyList"></div>
</details>
<p class="panel-footer">
O nível R-07, seus nós e suas arestas persistem em memória.
<b>REINICIAR</b> restaura apenas os estados, sem regenerar o tabuleiro.
</p>
</aside>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const ui = {
stage: document.getElementById("stage"),
canvas: document.getElementById("scene"),
loading: document.getElementById("loading"),
statePill: document.getElementById("statePill"),
stateText: document.getElementById("stateText"),
currentPosition: document.getElementById("currentPosition"),
upperState: document.getElementById("upperState"),
lowerState: document.getElementById("lowerState"),
goalLockText: document.getElementById("goalLockText"),
selectedName: document.getElementById("selectedName"),
selectedCoord: document.getElementById("selectedCoord"),
adjacencySummary: document.getElementById("adjacencySummary"),
adjacencyList: document.getElementById("adjacencyList"),
changesList: document.getElementById("changesList"),
triggerBtn: document.getElementById("triggerBtn"),
resetBtn: document.getElementById("resetBtn"),
auditBtn: document.getElementById("auditBtn"),
homeBtn: document.getElementById("homeBtn"),
auditBadge: document.getElementById("auditBadge"),
auditDetail: document.getElementById("auditDetail"),
topologyList: document.getElementById("topologyList"),
toast: document.getElementById("toast")
};
const LEVEL = Object.freeze({
id: "R-07",
title: "Duas rotas, um gatilho",
signature: 1707
});
const NODES = {
START: { id: "START", label: "Início", coord: [0, 2], kind: "start", color: 0x42d7b3 },
GATE: { id: "GATE", label: "Gatilho", coord: [1, 2], kind: "trigger", color: 0xff526b },
U1: { id: "U1", label: "Upper 01", coord: [2, 2], kind: "upper", color: 0xffb454 },
U2: { id: "U2", label: "Upper 02", coord: [3, 2], kind: "upper", color: 0xffb454 },
U3: { id: "U3", label: "Upper 03", coord: [4, 2], kind: "upper", color: 0xffb454 },
U4: { id: "U4", label: "Upper 04", coord: [5, 2], kind: "upper", color: 0xffb454 },
GOAL: { id: "GOAL", label: "Meta", coord: [6, 2], kind: "goal", color: 0xffe16a },
L1: { id: "L1", label: "Lower 01", coord: [3, 3], kind: "lower", color: 0x43c8ff },
L2: { id: "L2", label: "Lower 02", coord: [4, 3], kind: "lower", color: 0x43c8ff },
L3: { id: "L3", label: "Lower 03", coord: [5, 3], kind: "lower", color: 0x43c8ff },
L4: { id: "L4", label: "Lower 04", coord: [6, 3], kind: "lower", color: 0x43c8ff }
};
const EDGE_DEFS = [
{ id: "s-gate", a: "START", b: "GATE", initialOpen: true, kind: "common", routeColor: 0x58dfbb },
{ id: "gate-u1", a: "GATE", b: "U1", initialOpen: true, kind: "upper", routeColor: 0xffb454 },
{ id: "u1-u2", a: "U1", b: "U2", initialOpen: true, kind: "upper", routeColor: 0xffb454 },
{ id: "u2-u3", a: "U2", b: "U3", initialOpen: true, kind: "upper", routeColor: 0xffb454 },
{ id: "u3-u4", a: "U3", b: "U4", initialOpen: true, kind: "upper", routeColor: 0xffb454 },
{ id: "u4-goal", a: "U4", b: "GOAL", initialOpen: true, kind: "upper", routeColor: 0xffd06b },
{ id: "u2-l1", a: "U2", b: "L1", initialOpen: false, kind: "lower", routeColor: 0x43c8ff },
{ id: "l1-l2", a: "L1", b: "L2", initialOpen: true, kind: "lower", routeColor: 0x43c8ff },
{ id: "l2-l3", a: "L2", b: "L3", initialOpen: true, kind: "lower", routeColor: 0x43c8ff },
{ id: "l3-l4", a: "L3", b: "L4", initialOpen: true, kind: "lower", routeColor: 0x43c8ff },
{ id: "l4-goal", a: "L4", b: "GOAL", initialOpen: true, kind: "lower", routeColor: 0x75dcff }
];
function canonicalEdgeKey(a, b) {
return [a, b].sort().join("|");
}
const edges = new Map();
const edgeById = new Map();
const definitionKeys = new Set();
for (const def of EDGE_DEFS) {
const key = canonicalEdgeKey(def.a, def.b);
if (definitionKeys.has(key)) {
throw new Error(`Aresta duplicada na definição: ${key}`);
}
definitionKeys.add(key);
const edge = {
...def,
open: def.initialOpen,
visual: null
};
edges.set(key, edge);
edgeById.set(edge.id, edge);
}
function findEdge(a, b) {
return edges.get(canonicalEdgeKey(a, b)) || null;
}
/*
Fonte única de verdade:
- O estado de uma ligação pertence à aresta canônica.
- A UI, o movimento, o caminho e a malha 3D leem esse mesmo booleano.
- Não existem listas independentes "abertos" e "fechados".
*/
function getAdjacency(nodeId) {
const rows = [];
for (const edge of edges.values()) {
if (edge.a !== nodeId && edge.b !== nodeId) continue;
const other = edge.a === nodeId ? edge.b : edge.a;
rows.push({
from: nodeId,
to: other,
edgeId: edge.id,
open: edge.open,
edge
});
}
return rows;
}
function topologySignature() {
return JSON.stringify({
level: LEVEL.id,
nodes: Object.values(NODES)
.map(node => [node.id, ...node.coord, node.kind])
.sort((a, b) => a[0].localeCompare(b[0])),
edges: Array.from(edgeById.values())
.map(edge => [edge.id, edge.a, edge.b, edge.initialOpen, edge.kind])
.sort((a, b) => a[0].localeCompare(b[0]))
});
}
const LEVEL_SIGNATURE = topologySignature();
const GRID_SPACING = 1.45;
function gridToWorld(coord) {
return new THREE.Vector3(
(coord[0] - 3) * GRID_SPACING,
0,
(coord[1] - 2.5) * GRID_SPACING
);
}
function hexCss(hex) {
return `#${hex.toString(16).padStart(6, "0")}`;
}
function coordinateText(node) {
return `(${node.coord[0]}, ${node.coord[1]})`;
}
const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
const renderer = new THREE.WebGLRenderer({
canvas: ui.canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131f);
scene.fog = new THREE.Fog(0x07131f, 22, 42);
const camera = new THREE.OrthographicCamera(-8, 8, 5, -5, 0.1, 60);
const cameraTarget = new THREE.Vector3(0, 0.22, 0);
const homeCamera = { theta: 0.48, phi: 0.82, zoom: 1 };
let cameraTheta = homeCamera.theta;
let cameraPhi = homeCamera.phi;
let cameraZoom = homeCamera.zoom;
function updateCamera() {
const radius = 18;
camera.position.set(
cameraTarget.x + radius * Math.sin(cameraPhi) * Math.sin(cameraTheta),
cameraTarget.y + radius * Math.cos(cameraPhi),
cameraTarget.z + radius * Math.sin(cameraPhi) * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}
function resizeRenderer() {
const width = Math.max(1, ui.stage.clientWidth);
const height = Math.max(1, ui.stage.clientHeight);
const aspect = width / height;
const frustumHeight = Math.max(9.3, 14.6 / aspect);
camera.left = -frustumHeight * aspect / 2;
camera.right = frustumHeight * aspect / 2;
camera.top = frustumHeight / 2;
camera.bottom = -frustumHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
updateCamera();
}
const hemisphere = new THREE.HemisphereLight(0xc9ecff, 0x152137, 1.9);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff0d7, 3.4);
keyLight.position.set(-6, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -11;
keyLight.shadow.camera.right = 11;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.00035;
scene.add(keyLight);
scene.add(keyLight.target);
const rimLight = new THREE.DirectionalLight(0x4fc8ff, 1.7);
rimLight.position.set(9, 6, -8);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffa04b, 18, 12, 2);
warmLight.position.set(4, 4, 1);
scene.add(warmLight);
const root = new THREE.Group();
scene.add(root);
function standardMaterial(hex, options = {}) {
return new THREE.MeshStandardMaterial({
color: hex,
roughness: options.roughness ?? 0.72,
metalness: options.metalness ?? 0.04,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
}
function addBox(parent, size, position, material, options = {}) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), material);
mesh.position.set(...position);
mesh.castShadow = options.cast !== false;
mesh.receiveShadow = options.receive !== false;
parent.add(mesh);
return mesh;
}
function roundedRectPath(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function makeLabelSprite(title, subtitle, accent) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 176;
const ctx = canvas.getContext("2d");
roundedRectPath(ctx, 5, 5, 502, 166, 26);
ctx.fillStyle = "rgba(5, 13, 22, 0.90)";
ctx.fill();
ctx.strokeStyle = accent;
ctx.lineWidth = 5;
ctx.stroke();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#f2f8ff";
ctx.font = "800 61px system-ui, sans-serif";
ctx.fillText(title, 256, 70, 465);
ctx.fillStyle = accent;
ctx.font = "700 35px system-ui, sans-serif";
ctx.fillText(subtitle, 256, 126, 440);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.34, 0.461, 1);
sprite.renderOrder = 20;
return sprite;
}
const boardBaseMaterial = standardMaterial(0x101c29, { roughness: 0.9 });
const boardInsetMaterial = standardMaterial(0x172838, { roughness: 0.84 });
addBox(root, [12.9, 0.48, 5.95], [0, -0.28, 0], boardBaseMaterial);
addBox(root, [12.5, 0.15, 5.55], [0, -0.035, 0], boardInsetMaterial);
const floorPalette = [0x172838, 0x1a2c3d, 0x1c3042, 0x152638];
for (let x = -1; x <= 7; x++) {
for (let z = 1; z <= 4; z++) {
const position = gridToWorld([x, z]);
let tileColor = floorPalette[(x + z * 3 + 9) % floorPalette.length];
if (z === 2 && x >= 0 && x <= 6) tileColor = 0x342b2b;
if (z === 3 && x >= 3 && x <= 6) tileColor = 0x193544;
const material = standardMaterial(tileColor, { roughness: 0.91 });
addBox(
root,
[1.22, 0.16, 1.22],
[position.x, 0.08, position.z],
material,
{ cast: false }
);
}
}
const trimMaterial = standardMaterial(0x294054, {
roughness: 0.65,
metalness: 0.12
});
addBox(root, [12.75, 0.12, 0.13], [0, -0.03, -2.82], trimMaterial);
addBox(root, [12.75, 0.12, 0.13], [0, -0.03, 2.82], trimMaterial);
addBox(root, [0.13, 0.12, 5.55], [-6.32, -0.03, 0], trimMaterial);
addBox(root, [0.13, 0.12, 5.55], [6.32, -0.03, 0], trimMaterial);
const nodeGroups = new Map();
const interactiveMeshes = [];
const invisiblePickMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
});
let triggerVisual = null;
let goalBeacon = null;
function createNode(node) {
const group = new THREE.Group();
group.position.copy(gridToWorld(node.coord));
root.add(group);
const baseColor = new THREE.Color(node.color);
const capColor = baseColor.clone().lerp(new THREE.Color(0xffffff), 0.14);
const baseMaterial = standardMaterial(baseColor, { roughness: 0.76 });
const capMaterial = standardMaterial(capColor, {
roughness: 0.58,
metalness: 0.08
});
addBox(group, [1.08, 0.34, 1.08], [0, 0.34, 0], baseMaterial);
addBox(group, [0.86, 0.22, 0.86], [0, 0.60, 0], capMaterial);
const studMaterial = standardMaterial(capColor, {
roughness: 0.5,
emissive: node.color,
emissiveIntensity: node.kind === "trigger" ? 0.14 : 0.04
});
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
addBox(group, [0.13, 0.12, 0.13], [sx * 0.36, 0.76, sz * 0.36], studMaterial);
}
}
if (node.kind === "trigger") {
const buttonMaterial = standardMaterial(0xff526b, {
roughness: 0.38,
metalness: 0.12,
emissive: 0x7a1024,
emissiveIntensity: 0.26
});
const button = addBox(group, [0.46, 0.16, 0.46], [0, 0.82, 0], buttonMaterial);
const triggerRingMaterial = new THREE.MeshBasicMaterial({
color: 0xff526b,
transparent: true,
opacity: 0.75
});
const triggerRing = new THREE.Mesh(
new THREE.TorusGeometry(0.43, 0.035, 8, 32),
triggerRingMaterial
);
triggerRing.rotation.x = Math.PI / 2;
triggerRing.position.y = 0.78;
group.add(triggerRing);
triggerVisual = { group, button, buttonMaterial, triggerRing };
} else if (node.kind === "goal") {
const goldMaterial = standardMaterial(0xffe16a, {
roughness: 0.28,
metalness: 0.18,
emissive: 0xffb91f,
emissiveIntensity: 0.45
});
const poleMaterial = standardMaterial(0xffed9b, {
roughness: 0.35,
metalness: 0.22
});
addBox(group, [0.08, 1.25, 0.08], [0.38, 1.30, 0], poleMaterial);
addBox(group, [0.55, 0.34, 0.07], [0.62, 1.76, 0], goldMaterial);
goalBeacon = addBox(group, [0.30, 0.30, 0.30], [-0.34, 1.36, 0], goldMaterial);
const goalLight = new THREE.PointLight(0xffdc62, 9, 4.5, 2);
goalLight.position.set(0, 1.1, 0);
group.add(goalLight);
} else if (node.kind === "start") {
const arrowMaterial = standardMaterial(0xb9ffec, {
emissive: 0x42d7b3,
emissiveIntensity: 0.18
});
addBox(group, [0.12, 0.08, 0.32], [0, 0.76, -0.18], arrowMaterial);
addBox(group, [0.12, 0.08, 0.32], [0, 0.76, 0], arrowMaterial);
addBox(group, [0.12, 0.08, 0.32], [0, 0.76, 0.18], arrowMaterial);
} else {
const centerMaterial = standardMaterial(node.color, {
roughness: 0.46,
emissive: node.color,
emissiveIntensity: 0.09
});
addBox(group, [0.38, 0.08, 0.38], [0, 0.76, 0], centerMaterial);
}
const label = makeLabelSprite(
node.label.toUpperCase(),
coordinateText(node),
hexCss(node.color)
);
label.position.set(0, node.kind === "goal" ? 1.76 : 1.14, 0);
group.add(label);
const pickMesh = new THREE.Mesh(
new THREE.BoxGeometry(1.20, 1.45, 1.20),
invisiblePickMaterial
);
pickMesh.position.y = 0.72;
pickMesh.userData.nodeId = node.id;
group.add(pickMesh);
interactiveMeshes.push(pickMesh);
nodeGroups.set(node.id, group);
}
Object.values(NODES).forEach(createNode);
function buildEdgeVisual(edge) {
const group = new THREE.Group();
root.add(group);
const a = gridToWorld(NODES[edge.a].coord);
const b = gridToWorld(NODES[edge.b].coord);
const delta = b.clone().sub(a);
const length = delta.length();
const midpoint = a.clone().add(b).multiplyScalar(0.5);
const segmentCount = Math.max(3, Math.round(length / 0.31));
const pathMaterial = standardMaterial(edge.routeColor, {
roughness: 0.48,
metalness: 0.08,
emissive: edge.routeColor,
emissiveIntensity: 0.16
});
const pavers = new THREE.Group();
group.add(pavers);
for (let i = 1; i < segmentCount; i++) {
const t = i / segmentCount;
const position = a.clone().lerp(b, t);
addBox(
pavers,
[0.27, 0.12, 0.27],
[position.x, 0.235, position.z],
pathMaterial,
{ cast: false }
);
}
const openMarker = new THREE.Group();
openMarker.position.copy(midpoint);
group.add(openMarker);
const openMaterial = standardMaterial(0x58e6ad, {
roughness: 0.42,
emissive: 0x35d995,
emissiveIntensity: 0.4
});
const openLightMaterial = standardMaterial(0xbaffdf, {
roughness: 0.25,
emissive: 0x62efb6,
emissiveIntensity: 0.7
});
addBox(openMarker, [0.46, 0.09, 0.46], [0, 0.31, 0], openMaterial);
addBox(openMarker, [0.12, 0.05, 0.31], [0, 0.38, 0], openLightMaterial);
const closedWall = new THREE.Group();
closedWall.position.copy(midpoint);
group.add(closedWall);
const blockedMaterial = standardMaterial(0xff526b, {
roughness: 0.43,
metalness: 0.08,
emissive: 0x8c1028,
emissiveIntensity: 0.24
});
const blockedDarkMaterial = standardMaterial(0x7c2639, {
roughness: 0.65
});
const horizontal = Math.abs(delta.x) > Math.abs(delta.z);
if (horizontal) {
addBox(closedWall, [0.18, 0.68, 0.86], [0, 0.52, 0], blockedMaterial);
addBox(closedWall, [0.27, 0.12, 0.96], [0, 0.23, 0], blockedDarkMaterial);
addBox(closedWall, [0.13, 0.82, 0.13], [0, 0.54, 0.34], blockedDarkMaterial);
addBox(closedWall, [0.13, 0.82, 0.13], [0, 0.54, -0.34], blockedDarkMaterial);
} else {
addBox(closedWall, [0.86, 0.68, 0.18], [0, 0.52, 0], blockedMaterial);
addBox(closedWall, [0.96, 0.12, 0.27], [0, 0.23, 0], blockedDarkMaterial);
addBox(closedWall, [0.13, 0.82, 0.13], [0.34, 0.54, 0], blockedDarkMaterial);
addBox(closedWall, [0.13, 0.82, 0.13], [-0.34, 0.54, 0], blockedDarkMaterial);
}
return {
group,
pavers,
pathMaterial,
openMarker,
closedWall,
stateOpen: null,
transitionToken: 0
};
}
for (const edge of edges.values()) {
edge.visual = buildEdgeVisual(edge);
}
const robot = new THREE.Group();
root.add(robot);
const robotWhite = standardMaterial(0xeaf7ff, { roughness: 0.48, metalness: 0.12 });
const robotBlue = standardMaterial(0x2c9fce, {
roughness: 0.4,
metalness: 0.16,
emissive: 0x123d55,
emissiveIntensity: 0.25
});
const robotDark = standardMaterial(0x10202e, { roughness: 0.55 });
addBox(robot, [0.18, 0.14, 0.25], [-0.15, 0.08, 0.02], robotDark);
addBox(robot, [0.18, 0.14, 0.25], [0.15, 0.08, 0.02], robotDark);
addBox(robot, [0.52, 0.44, 0.44], [0, 0.35, 0], robotWhite);
addBox(robot, [0.34, 0.12, 0.46], [0, 0.35, 0], robotBlue);
addBox(robot, [0.43, 0.34, 0.40], [0, 0.72, 0], robotWhite);
addBox(robot, [0.31, 0.15, 0.025], [0, 0.74, 0.208], robotDark);
addBox(robot, [0.07, 0.07, 0.035], [-0.09, 0.75, 0.226], robotBlue);
addBox(robot, [0.07, 0.07, 0.035], [0.09, 0.75, 0.226], robotBlue);
addBox(robot, [0.035, 0.22, 0.035], [0, 0.98, 0], robotBlue);
addBox(robot, [0.09, 0.09, 0.09], [0, 1.10, 0], robotBlue);
const robotShadow = new THREE.Mesh(
new THREE.CircleGeometry(0.39, 28),
new THREE.MeshBasicMaterial({
color: 0x02070c,
transparent: true,
opacity: 0.32,
depthWrite: false
})
);
robotShadow.rotation.x = -Math.PI / 2;
robotShadow.position.y = 0.012;
robot.add(robotShadow);
const selectionMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.86
});
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.68, 0.035, 8, 44),
selectionMaterial
);
selectionRing.rotation.x = Math.PI / 2;
root.add(selectionRing);
const state = {
triggered: false,
current: "START",
selected: "U2",
changes: [],
success: false,
auditContext: "INICIAL"
};
const robotTarget = gridToWorld(NODES.START.coord);
robotTarget.y = 0.72;
robot.position.copy(robotTarget);
const selectionTarget = gridToWorld(NODES.U2.coord);
selectionTarget.y = 0.79;
selectionRing.position.copy(selectionTarget);
let robotYawTarget = 0;
const tweens = new Set();
const pulses = [];
const particles = [];
const particleGroup = new THREE.Group();
root.add(particleGroup);
function startTween(duration, update, complete = null) {
const tween = { elapsed: 0, duration, update, complete };
tweens.add(tween);
}
function updateTweens(dt) {
for (const tween of [...tweens]) {
tween.elapsed += dt;
const t = Math.min(1, tween.elapsed / tween.duration);
tween.update(t);
if (t >= 1) {
tweens.delete(tween);
if (tween.complete) tween.complete();
}
}
}
function applyEdgeState(edge, open, animate = true) {
const visual = edge.visual;
const previous = visual.stateOpen;
const next = Boolean(open);
edge.open = next;
visual.stateOpen = next;
visual.openMarker.visible = next;
visual.closedWall.visible = !next;
visual.pathMaterial.color.setHex(next ? edge.routeColor : 0x293647);
visual.pathMaterial.emissive.setHex(next ? edge.routeColor : 0x0a111a);
visual.pathMaterial.emissiveIntensity = next ? 0.16 : 0.03;
visual.transitionToken += 1;
const token = visual.transitionToken;
if (animate && previous !== null && previous !== next) {
if (next) {
visual.openMarker.scale.setScalar(0.06);
startTween(0.34, t => {
if (token !== visual.transitionToken) return;
const scale = 0.06 + 0.94 * (1 - Math.pow(1 - t, 3));
visual.openMarker.scale.setScalar(scale);
}, () => {
if (token === visual.transitionToken) visual.openMarker.scale.setScalar(1);
});
} else {
visual.closedWall.scale.set(1, 0.03, 1);
startTween(0.34, t => {
if (token !== visual.transitionToken) return;
const eased = 1 - Math.pow(1 - t, 3);
visual.closedWall.scale.set(1, 0.03 + 0.97 * eased, 1);
}, () => {
if (token === visual.transitionToken) visual.closedWall.scale.set(1, 1, 1);
});
}
} else {
visual.openMarker.scale.setScalar(1);
visual.closedWall.scale.set(1, 1, 1);
}
}
function spawnPulse(nodeId, color) {
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.8,
depthWrite: false
});
const mesh = new THREE.Mesh(
new THREE.TorusGeometry(0.65, 0.045, 8, 40),
material
);
mesh.rotation.x = Math.PI / 2;
const position = gridToWorld(NODES[nodeId].coord);
mesh.position.set(position.x, 0.83, position.z);
root.add(mesh);
pulses.push({ mesh, life: 1, duration: 0.9 });
}
function removePulses() {
for (const pulse of pulses) {
root.remove(pulse.mesh);
pulse.mesh.geometry.dispose();
pulse.mesh.material.dispose();
}
pulses.length = 0;
}
function spawnGoalBurst() {
const origin = gridToWorld(NODES.GOAL.coord);
const colors = [0xffe16a, 0x43c8ff, 0xffb454, 0x58e6ad];
for (let i = 0; i < 26; i++) {
const material = new THREE.MeshBasicMaterial({
color: colors[i % colors.length],
transparent: true,
opacity: 0.95
});
const mesh = new THREE.Mesh(new THREE.BoxGeometry(0.10, 0.10, 0.10), material);
mesh.position.set(origin.x, 1.05, origin.z);
particleGroup.add(mesh);
particles.push({
mesh,
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 3.4,
2.3 + Math.random() * 3.1,
(Math.random() - 0.5) * 3.4
),
spin: new THREE.Vector3(
(Math.random() - 0.5) * 8,
(Math.random() - 0.5) * 8,
(Math.random() - 0.5) * 8
),
life: 1.7,
duration: 1.7
});
}
}
function clearParticles() {
for (const particle of particles) {
particleGroup.remove(particle.mesh);
particle.mesh.geometry.dispose();
particle.mesh.material.dispose();
}
particles.length = 0;
}
let toastTimer = 0;
function showToast(message, kind = "info") {
ui.toast.textContent = message;
ui.toast.dataset.kind = kind;
ui.toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => ui.toast.classList.remove("show"), 3300);
}
function renderAdjacency() {
const selected = NODES[state.selected];
const rows = getAdjacency(state.selected);
const openCount = rows.filter(row => row.open).length;
const closedCount = rows.length - openCount;
ui.selectedName.textContent = selected.label;
ui.selectedCoord.textContent = coordinateText(selected);
ui.adjacencySummary.textContent =
`${rows.length} conexões · ${openCount} abertas · ${closedCount} fechadas`;
ui.adjacencyList.replaceChildren();
for (const row of rows) {
const target = NODES[row.to];
const button = document.createElement("button");
button.type = "button";
button.className = "adj-row";
button.dataset.neighbor = row.to;
button.dataset.status = row.open ? "open" : "closed";
button.setAttribute(
"aria-label",
`${target.label}, ${coordinateText(target)}, ligação ${row.open ? "aberta" : "fechada"}`
);
button.innerHTML = `
<span class="node-dot" style="--node-color:${hexCss(target.color)}"></span>
<span class="adj-name">
<b>${target.label}</b>
<small>${coordinateText(target)}</small>
</span>
<span class="status ${row.open ? "open" : "closed"}">
${row.open ? "ABERTO" : "FECHADO"}
</span>
`;
button.addEventListener("click", () => inspectNode(row.to));
ui.adjacencyList.appendChild(button);
}
}
function renderChanges() {
ui.changesList.replaceChildren();
if (state.changes.length === 0) {
const empty = document.createElement("div");
empty.className = "empty-state";
empty.textContent =
"Nenhuma mudança ainda. Dispare o gatilho para atualizar as duas ligações.";
ui.changesList.appendChild(empty);
return;
}
for (const change of state.changes) {
const from = NODES[change.from];
const to = NODES[change.to];
const row = document.createElement("div");
row.className = "change-row";
row.dataset.edgeId = change.edgeId;
row.innerHTML = `
<b>${from.label} → ${to.label}</b>
<small> ${coordinateText(from)} → ${coordinateText(to)}</small>
<div class="change-delta">
<span class="before ${change.before ? "open" : "closed"}">
${change.before ? "ABERTO" : "FECHADO"}
</span>
<i>→</i>
<span class="after ${change.after ? "open" : "closed"}">
${change.after ? "ABERTO" : "FECHADO"}
</span>
</div>
`;
ui.changesList.appendChild(row);
}
}
function renderStatus() {
const current = NODES[state.current];
const upper = edgeById.get("u2-u3");
const lower = edgeById.get("u2-l1");
ui.currentPosition.textContent =
`CUBO · ${current.label.toUpperCase()} ${coordinateText(current)}`;
ui.upperState.textContent = upper.open ? "ABERTA" : "BLOQUEADA";
ui.upperState.dataset.status = upper.open ? "open" : "closed";
ui.lowerState.textContent = lower.open ? "ABERTA" : "FECHADA";
ui.lowerState.dataset.status = lower.open ? "open" : "closed";
ui.triggerBtn.disabled = state.triggered;
ui.triggerBtn.textContent = state.triggered
? "GATILHO DISPARADO"
: "DISPARAR GATILHO";
if (state.success) {
ui.stateText.textContent = "META ATINGIDA";
ui.statePill.dataset.mode = "success";
} else if (state.triggered) {
ui.stateText.textContent = "GATILHO ATIVO";
ui.statePill.dataset.mode = "triggered";
} else {
ui.stateText.textContent = "ESTADO INICIAL";
ui.statePill.dataset.mode = "initial";
}
}
function renderTopologyAudit() {
ui.topologyList.replaceChildren();
for (const edge of edgeById.values()) {
const a = NODES[edge.a];
const b = NODES[edge.b];
const row = document.createElement("div");
row.className = "topology-row";
row.dataset.edgeId = edge.id;
row.innerHTML = `
<span>${a.label} ↔ ${b.label}</span>
<span class="status ${edge.open ? "open" : "closed"}">
${edge.open ? "ABERTO" : "FECHADO"}
</span>
`;
ui.topologyList.appendChild(row);
}
}
function findOpenPath(startId, endId) {
const queue = [startId];
const previous = new Map([[startId, null]]);
while (queue.length > 0) {
const current = queue.shift();
if (current === endId) break;
for (const row of getAdjacency(current)) {
if (!row.open || previous.has(row.to)) continue;
previous.set(row.to, current);
queue.push(row.to);
}
}
if (!previous.has(endId)) return null;
const path = [];
let cursor = endId;
while (cursor !== null) {
path.unshift(cursor);
cursor = previous.get(cursor);
}
return path;
}
function auditAssert(condition, message) {
if (!condition) throw new Error(message);
}
function validateCurrentState() {
const directedPairs = new Set();
const canonicalPairs = new Set();
let directedCount = 0;
for (const edge of edges.values()) {
const visual = edge.visual;
auditAssert(Boolean(visual), `Geometria ausente: ${edge.id}`);
auditAssert(
visual.stateOpen === edge.open,
`Estado e malha divergem: ${edge.id}`
);
auditAssert(
visual.openMarker.visible === edge.open,
`Marcador aberto incorreto: ${edge.id}`
);
auditAssert(
visual.closedWall.visible === !edge.open,
`Parede de bloqueio incorreta: ${edge.id}`
);
auditAssert(
visual.pavers.children.length > 0,
`Pavimentos ausentes: ${edge.id}`
);
const canonicalKey = canonicalEdgeKey(edge.a, edge.b);
auditAssert(
!canonicalPairs.has(canonicalKey),
`Aresta canônica duplicada: ${canonicalKey}`
);
canonicalPairs.add(canonicalKey);
for (const [from, to] of [[edge.a, edge.b], [edge.b, edge.a]]) {
const directedKey = `${from}|${to}`;
auditAssert(
!directedPairs.has(directedKey),
`Relação dirigida duplicada: ${directedKey}`
);
directedPairs.add(directedKey);
directedCount++;
}
}
for (const node of Object.values(NODES)) {
const rows = getAdjacency(node.id);
const targets = new Set();
for (const row of rows) {
auditAssert(
!targets.has(row.to),
`Vizinho duplicado em ${node.label}: ${row.to}`
);
targets.add(row.to);
const sourceEdge = findEdge(node.id, row.to);
auditAssert(Boolean(sourceEdge), `Aresta não encontrada: ${node.id}-${row.to}`);
auditAssert(
row.open === sourceEdge.open,
`Adjacência divergente: ${node.id}-${row.to}`
);
}
}
const expectedRows = getAdjacency(state.selected);
const domRows = [...ui.adjacencyList.querySelectorAll(".adj-row")];
auditAssert(
domRows.length === expectedRows.length,
`A lista visual tem ${domRows.length} linhas; esperado ${expectedRows.length}`
);
for (const expected of expectedRows) {
const domRow = domRows.find(row => row.dataset.neighbor === expected.to);
auditAssert(Boolean(domRow), `Vizinho ausente no DOM: ${expected.to}`);
auditAssert(
domRow.dataset.status === (expected.open ? "open" : "closed"),
`Estado visual duplicado ou incorreto: ${expected.to}`
);
}
const topologyRows = [...ui.topologyList.querySelectorAll(".topology-row")];
auditAssert(
topologyRows.length === edges.size,
"A topologia visual não contém exatamente uma linha por aresta"
);
auditAssert(
new Set(topologyRows.map(row => row.dataset.edgeId)).size === edges.size,
"A topologia visual contém arestas duplicadas"
);
const upper = edgeById.get("u2-u3");
const lower = edgeById.get("u2-l1");
if (state.triggered) {
auditAssert(upper.open === false, "O corredor superior deveria estar fechado");
auditAssert(lower.open === true, "A ligação inferior deveria estar aberta");
auditAssert(
upper.visual.closedWall.visible && !upper.visual.openMarker.visible,
"A geometria do bloqueio superior está incorreta"
);
auditAssert(
lower.visual.openMarker.visible && !lower.visual.closedWall.visible,
"A geometria da abertura inferior está incorreta"
);
auditAssert(state.changes.length === 2, "O gatilho deveria gerar exatamente duas mudanças");
} else {
auditAssert(upper.open === true, "O corredor superior deveria estar aberto");
auditAssert(lower.open === false, "A ligação inferior deveria estar fechada");
auditAssert(
upper.visual.openMarker.visible && !upper.visual.closedWall.visible,
"A geometria superior inicial está incorreta"
);
auditAssert(
lower.visual.closedWall.visible && !lower.visual.openMarker.visible,
"A geometria inferior inicial está incorreta"
);
auditAssert(state.changes.length === 0, "Não deveria haver mudanças antes do gatilho");
}
const path = findOpenPath("START", "GOAL");
auditAssert(Boolean(path), "Não existe caminho aberto até a meta");
if (state.triggered) {
auditAssert(path.includes("L1"), "Após o gatilho, o caminho deve usar Lower 01");
auditAssert(!path.includes("U3"), "Após o gatilho, Upper 03 não pode fazer parte do caminho");
} else {
auditAssert(path.includes("U3"), "No estado inicial, o caminho superior deve existir");
}
for (const node of Object.values(NODES)) {
const group = nodeGroups.get(node.id);
auditAssert(Boolean(group), `Nó visual ausente: ${node.id}`);
const expected = gridToWorld(node.coord);
auditAssert(
Math.abs(group.position.x - expected.x) < 0.0001 &&
Math.abs(group.position.z - expected.z) < 0.0001,
`Geometria do nó deslocada: ${node.id}`
);
}
auditAssert(
topologySignature() === LEVEL_SIGNATURE,
"A topologia do nível foi regenerada ou alterada"
);
auditAssert(
nodeGroups.get("GOAL") === nodeGroups.get("GOAL"),
"A referência da meta não é persistente"
);
return {
directedCount,
edgeCount: edges.size,
path
};
}
function runAudit(verbose = false) {
try {
const result = validateCurrentState();
ui.auditBadge.className = "audit-badge ok";
ui.auditBadge.textContent = `TESTE REAL: OK · ${state.auditContext}`;
ui.auditDetail.textContent =
`${result.directedCount} relações únicas · ` +
`${result.edgeCount}/${result.edgeCount} geometrias coerentes · ` +
`0 conflitos · caminho ${result.path.map(id => NODES[id].label).join(" → ")}`;
console.info(
`[${LEVEL.id}] Auditoria ${state.auditContext}:`,
result.directedCount,
"relações únicas;",
result.edgeCount,
"malhas coerentes; caminho:",
result.path.join(" → ")
);
if (verbose) {
showToast(
`Auditoria OK: ${result.directedCount} relações únicas, nenhuma分類ação duplicada e malha 3D sincronizada.`,
"success"
);
}
return true;
} catch (error) {
ui.auditBadge.className = "audit-badge bad";
ui.auditBadge.textContent = "TESTE REAL: FALHOU";
ui.auditDetail.textContent = error.message;
console.error(`[${LEVEL.id}] Falha na auditoria:`, error);
if (verbose) showToast(`Falha na auditoria: ${error.message}`, "warning");
return false;
}
}
function refreshUI() {
renderAdjacency();
renderChanges();
renderStatus();
renderTopologyAudit();
runAudit(false);
}
function inspectNode(nodeId) {
if (!NODES[nodeId]) return;
state.selected = nodeId;
const position = gridToWorld(NODES[nodeId].coord);
selectionTarget.set(position.x, 0.79, position.z);
refreshUI();
}
function moveRobot(targetId) {
const from = gridToWorld(NODES[state.current].coord);
const to = gridToWorld(NODES[targetId].coord);
const direction = to.clone().sub(from);
state.current = targetId;
state.selected = targetId;
state.success = targetId === "GOAL";
robotTarget.set(to.x, 0.72, to.z);
selectionTarget.set(to.x, 0.79, to.z);
robotYawTarget = Math.atan2(direction.x, direction.z);
refreshUI();
if (targetId === "GATE") {
showToast("Gatilho alcançado. Dispare o controle vermelho no painel ou pressione Espaço.");
} else if (targetId === "GOAL") {
spawnGoalBurst();
showToast("Meta atingida! O gatilho trocou a rota e preservou o destino.", "success");
}
}
function tryMove(targetId) {
if (!NODES[targetId]) return;
if (targetId === state.current) {
state.selected = targetId;
if (targetId === "GATE" && !state.triggered) {
activateTrigger();
} else {
refreshUI();
}
return;
}
const edge = findEdge(state.current, targetId);
if (!edge) {
inspectNode(targetId);
showToast(`${NODES[targetId].label} foi inspecionado. Não há ligação direta com o cubo.`);
return;
}
if (!edge.open) {
inspectNode(targetId);
showToast(
`${NODES[targetId].label}: ligação FECHADA. O cubo não atravessa esta aresta.`,
"warning"
);
return;
}
if (targetId === "GOAL" && !state.triggered) {
inspectNode(targetId);
showToast("Meta protegida: dispare o gatilho antes de concluir a rota.", "warning");
return;
}
moveRobot(targetId);
}
function activateTrigger() {
if (state.triggered) {
showToast("O gatilho já foi disparado. Use a rota inferior.");
return;
}
const upper = edgeById.get("u2-u3");
const lower = edgeById.get("u2-l1");
const upperBefore = upper.open;
const lowerBefore = lower.open;
applyEdgeState(upper, false, true);
applyEdgeState(lower, true, true);
state.changes = [
{
edgeId: upper.id,
from: upper.a,
to: upper.b,
before: upperBefore,
after: false
},
{
edgeId: lower.id,
from: lower.a,
to: lower.b,
before: lowerBefore,
after: true
}
];
state.triggered = true;
state.auditContext = "APÓS GATILHO";
triggerVisual.buttonMaterial.color.setHex(0x7d2b3d);
triggerVisual.buttonMaterial.emissive.setHex(0x37101b);
triggerVisual.buttonMaterial.emissiveIntensity = 0.18;
triggerVisual.triggerRing.material.color.setHex(0x7d2b3d);
spawnPulse("GATE", 0xff526b);
refreshUI();
showToast(
"Gatilho acionado: Upper 03 ficou FECHADO e Lower 01 ficou ABERTO. A meta não mudou.",
"success"
);
}
function restoreLevel(announce = true) {
for (const edge of edges.values()) {
applyEdgeState(edge, edge.initialOpen, false);
}
state.triggered = false;
state.changes = [];
state.current = "START";
state.selected = "U2";
state.success = false;
state.auditContext = announce ? "APÓS RESET" : "INICIAL";
const start = gridToWorld(NODES.START.coord);
const selected = gridToWorld(NODES.U2.coord);
robotTarget.set(start.x, 0.72, start.z);
robot.position.copy(robotTarget);
robot.rotation.set(0, 0, 0);
robotYawTarget = 0;
selectionTarget.set(selected.x, 0.79, selected.z);
selectionRing.position.copy(selectionTarget);
triggerVisual.buttonMaterial.color.setHex(0xff526b);
triggerVisual.buttonMaterial.emissive.setHex(0x7a1024);
triggerVisual.buttonMaterial.emissiveIntensity = 0.26;
triggerVisual.button.position.y = 0.82;
triggerVisual.triggerRing.material.color.setHex(0xff526b);
clearParticles();
removePulses();
refreshUI();
if (announce) {
showToast(
"Nível R-07 restaurado: a mesma topologia e a mesma META foram preservadas; dados e malha foram revalidados.",
"success"
);
}
}
ui.triggerBtn.addEventListener("click", activateTrigger);
ui.resetBtn.addEventListener("click", () => restoreLevel(true));
ui.auditBtn.addEventListener("click", () => runAudit(true));
ui.homeBtn.addEventListener("click", () => {
cameraTheta = homeCamera.theta;
cameraPhi = homeCamera.phi;
cameraZoom = homeCamera.zoom;
updateCamera();
showToast("Câmera restaurada.");
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let gesture = null;
function pickNodeAt(clientX, clientY) {
const rect = ui.canvas.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(interactiveMeshes, false);
return hits.length > 0 ? hits[0].object.userData.nodeId : null;
}
ui.canvas.addEventListener("pointerdown", event => {
if (event.pointerType === "mouse" && event.button !== 0) return;
gesture = {
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: 0
};
ui.canvas.setPointerCapture(event.pointerId);
ui.canvas.style.cursor = "grabbing";
});
ui.canvas.addEventListener("pointermove", event => {
if (gesture && gesture.pointerId === event.pointerId) {
const dx = event.clientX - gesture.lastX;
const dy = event.clientY - gesture.lastY;
gesture.moved += Math.abs(dx) + Math.abs(dy);
gesture.lastX = event.clientX;
gesture.lastY = event.clientY;
if (gesture.moved > 4) {
cameraTheta -= dx * 0.005;
cameraPhi = THREE.MathUtils.clamp(cameraPhi + dy * 0.004, 0.42, 1.25);
updateCamera();
}
} else {
const nodeId = pickNodeAt(event.clientX, event.clientY);
ui.canvas.style.cursor = nodeId ? "pointer" : "grab";
}
});
ui.canvas.addEventListener("pointerup", event => {
if (!gesture || gesture.pointerId !== event.pointerId) return;
const wasClick = gesture.moved < 8;
gesture = null;
if (ui.canvas.hasPointerCapture(event.pointerId)) {
ui.canvas.releasePointerCapture(event.pointerId);
}
ui.canvas.style.cursor = "grab";
if (wasClick) {
const nodeId = pickNodeAt(event.clientX, event.clientY);
if (nodeId) tryMove(nodeId);
}
});
ui.canvas.addEventListener("pointercancel", () => {
gesture = null;
ui.canvas.style.cursor = "grab";
});
ui.canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(
cameraZoom * Math.exp(-event.deltaY * 0.001),
0.75,
1.75
);
updateCamera();
}, { passive: false });
ui.canvas.addEventListener("contextmenu", event => event.preventDefault());
document.addEventListener("keydown", event => {
if (event.ctrlKey || event.metaKey || event.altKey) return;
if (["INPUT", "TEXTAREA", "SELECT"].includes(event.target.tagName)) return;
if (event.code === "Space") {
if (event.target.tagName === "BUTTON") return;
event.preventDefault();
activateTrigger();
return;
}
if (event.key.toLowerCase() === "r") {
event.preventDefault();
restoreLevel(true);
return;
}
const directionByKey = {
ArrowLeft: [-1, 0],
ArrowRight: [1, 0],
ArrowUp: [0, -1],
ArrowDown: [0, 1]
};
const direction = directionByKey[event.key];
if (!direction) return;
event.preventDefault();
const current = NODES[state.current];
const rows = getAdjacency(state.current);
const match = rows.find(row => {
const target = NODES[row.to];
return (
target.coord[0] - current.coord[0] === direction[0] &&
target.coord[1] - current.coord[1] === direction[1]
);
});
if (!match) {
showToast("Não há uma ligação nessa direção.");
} else if (!match.open) {
inspectNode(match.to);
showToast(
`${NODES[match.to].label}: ligação FECHADA na direção selecionada.`,
"warning"
);
} else {
tryMove(match.to);
}
});
if ("ResizeObserver" in window) {
new ResizeObserver(resizeRenderer).observe(ui.stage);
}
window.addEventListener("resize", resizeRenderer);
restoreLevel(false);
resizeRenderer();
renderer.render(scene, camera);
ui.loading.classList.add("is-hidden");
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
updateTweens(dt);
const damping = 1 - Math.exp(-dt * 10);
robot.position.lerp(robotTarget, damping);
robot.position.y = 0.72 + (reducedMotion ? 0 : Math.sin(elapsed * 3.1) * 0.018);
const yawDifference = Math.atan2(
Math.sin(robotYawTarget - robot.rotation.y),
Math.cos(robotYawTarget - robot.rotation.y)
);
robot.rotation.y += yawDifference * damping;
selectionRing.position.lerp(selectionTarget, damping);
selectionRing.position.y = 0.79;
const ringScale = reducedMotion ? 1 : 1 + Math.sin(elapsed * 3.4) * 0.035;
selectionRing.scale.setScalar(ringScale);
if (goalBeacon) {
goalBeacon.rotation.y += dt * 1.15;
goalBeacon.rotation.x = reducedMotion ? 0 : Math.sin(elapsed * 0.9) * 0.18;
}
if (triggerVisual) {
const targetY = state.triggered ? 0.76 : 0.82;
triggerVisual.button.position.y += (targetY - triggerVisual.button.position.y) * damping;
triggerVisual.triggerRing.material.opacity = state.triggered
? 0.24
: 0.62 + (reducedMotion ? 0 : Math.sin(elapsed * 3.2) * 0.15);
}
for (let i = pulses.length - 1; i >= 0; i--) {
const pulse = pulses[i];
pulse.life -= dt;
const progress = 1 - Math.max(0, pulse.life) / pulse.duration;
pulse.mesh.scale.setScalar(1 + progress * 2.6);
pulse.mesh.material.opacity = Math.max(0, 0.8 * (1 - progress));
if (pulse.life <= 0) {
root.remove(pulse.mesh);
pulse.mesh.geometry.dispose();
pulse.mesh.material.dispose();
pulses.splice(i, 1);
}
}
for (let i = particles.length - 1; i >= 0; i--) {
const particle = particles[i];
particle.life -= dt;
particle.velocity.y -= 4.2 * dt;
particle.mesh.position.addScaledVector(particle.velocity, dt);
particle.mesh.rotation.x += particle.spin.x * dt;
particle.mesh.rotation.y += particle.spin.y * dt;
particle.mesh.rotation.z += particle.spin.z * dt;
particle.mesh.material.opacity = Math.max(0, particle.life / particle.duration);
if (particle.life <= 0) {
particleGroup.remove(particle.mesh);
particle.mesh.geometry.dispose();
particle.mesh.material.dispose();
particles.splice(i, 1);
}
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```