Prompt specification
Build or customize the Three.js 3D scene "Carrying a Bench Around a Corner" 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: Carrying a Bench Around a Corner
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/carrying-a-bench-around-a-corner-x3710
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing cooperative carrying poses around obstacles. Animate two characters rotating a bench through a bounded corridor. Coordinate their paths and prevent the bench from cutting through walls or bodies. Voxel style.
Technical checks: Find and animate a collision-free path that carries the bench through the turn from A to B. Check the bench and both carriers throughout the traversal.
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 (carrying-a-bench-around-a-corner-x3710):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Coop Carry — Travessia Segura</title>
<style>
:root {
--ink: #172a2c;
--muted: #607274;
--panel: rgba(250, 252, 247, 0.93);
--line: rgba(23, 42, 44, 0.13);
--teal: #147d78;
--teal-dark: #0d5f5b;
--coral: #df6c4f;
--gold: #e4ad3d;
--green: #32885b;
--shadow: 0 12px 35px rgba(22, 48, 48, 0.14);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce6df;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene.dragging { cursor: grabbing; }
.ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel, button {
pointer-events: auto;
}
.topbar {
position: absolute;
top: 18px;
left: 20px;
display: flex;
align-items: center;
gap: 13px;
padding: 12px 15px;
border: 1px solid var(--line);
border-radius: 15px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.brand-mark {
width: 38px;
height: 38px;
display: grid;
place-items: center;
border-radius: 10px;
background: var(--ink);
color: #f8fbf5;
font-weight: 900;
letter-spacing: -1px;
}
.brand-title {
font-size: 14px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.brand-sub {
margin-top: 3px;
color: var(--muted);
font-size: 11px;
font-weight: 650;
}
.panel {
position: absolute;
border: 1px solid var(--line);
border-radius: 17px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.controls {
top: 94px;
left: 20px;
width: 300px;
padding: 16px;
}
.eyebrow {
color: var(--muted);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.status-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 7px;
}
#status {
font-size: 17px;
font-weight: 850;
letter-spacing: -0.02em;
}
.status-dot {
width: 11px;
height: 11px;
flex: 0 0 auto;
border-radius: 3px;
background: var(--gold);
box-shadow: 0 0 0 5px rgba(228, 173, 61, 0.16);
}
.status-dot.safe {
background: var(--green);
box-shadow: 0 0 0 5px rgba(50, 136, 91, 0.14);
}
#phase {
margin: 5px 0 14px;
color: var(--muted);
font-size: 12px;
line-height: 1.35;
}
.button-row {
display: flex;
gap: 8px;
}
button {
border: 0;
border-radius: 10px;
padding: 10px 12px;
background: #e8eeea;
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 800;
cursor: pointer;
transition: transform 120ms ease, background 120ms ease, color 120ms ease;
}
button:hover { transform: translateY(-1px); }
button:active { transform: translateY(0); }
button.primary {
flex: 1;
background: var(--teal);
color: white;
}
button.primary:hover { background: var(--teal-dark); }
.speed-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
.speed-buttons {
display: flex;
gap: 5px;
}
.speed-buttons button {
min-width: 42px;
padding: 7px 9px;
background: #e8eeea;
font-size: 11px;
}
.speed-buttons button.active {
background: var(--ink);
color: white;
}
.safety {
top: 20px;
right: 20px;
width: 280px;
padding: 16px;
}
.safe-banner {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 12px;
color: var(--green);
font-size: 13px;
font-weight: 850;
}
.check {
width: 25px;
height: 25px;
display: grid;
place-items: center;
border-radius: 8px;
background: rgba(50, 136, 91, 0.12);
font-size: 14px;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 58px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.52);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 5px;
font-size: 18px;
letter-spacing: -0.03em;
}
.metric strong.good { color: var(--green); }
.metric strong.alert { color: #b34836; }
.validation-note {
margin: 11px 1px 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.objective {
left: 20px;
bottom: 20px;
width: 300px;
padding: 14px 16px;
}
.objective p {
margin: 6px 0 0;
color: #42585a;
font-size: 11px;
line-height: 1.5;
}
.timeline {
position: absolute;
left: 50%;
bottom: 20px;
width: min(560px, calc(100vw - 680px));
min-width: 370px;
transform: translateX(-50%);
padding: 13px 16px 14px;
}
.timeline-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#progressText { color: var(--teal); }
.track {
position: relative;
height: 7px;
margin-top: 10px;
overflow: hidden;
border-radius: 5px;
background: #dfe7e2;
}
#progressFill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--teal), #55a874);
}
.phase-labels {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 4px;
margin-top: 7px;
color: #738385;
font-size: 8px;
font-weight: 750;
text-align: center;
text-transform: uppercase;
}
.camera-tools {
position: absolute;
right: 20px;
bottom: 20px;
display: flex;
gap: 7px;
padding: 8px;
}
.camera-tools button {
min-width: 40px;
padding: 9px 11px;
background: var(--panel);
}
#success {
position: absolute;
top: 88px;
left: 50%;
min-width: 310px;
padding: 15px 20px;
border: 1px solid rgba(50, 136, 91, 0.24);
border-radius: 15px;
background: rgba(239, 249, 240, 0.96);
box-shadow: var(--shadow);
color: #236944;
text-align: center;
opacity: 0;
transform: translate(-50%, -12px);
transition: opacity 250ms ease, transform 250ms ease;
}
#success.show {
opacity: 1;
transform: translate(-50%, 0);
}
#success strong {
display: block;
font-size: 15px;
}
#success span {
display: block;
margin-top: 3px;
font-size: 11px;
}
#toast {
position: absolute;
left: 50%;
top: 24px;
padding: 10px 14px;
border-radius: 10px;
background: var(--ink);
color: white;
font-size: 11px;
font-weight: 750;
opacity: 0;
transform: translate(-50%, -8px);
transition: opacity 180ms ease, transform 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
background: #dce6df;
color: var(--ink);
font-size: 13px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
transition: opacity 250ms ease;
}
#loading.hidden { opacity: 0; pointer-events: none; }
@media (max-width: 980px) {
.safety { width: 245px; }
.controls { width: 265px; }
.timeline { width: 350px; min-width: 0; }
.objective { display: none; }
}
@media (max-width: 700px) {
.topbar { top: 10px; left: 10px; padding: 9px 11px; }
.brand-sub { display: none; }
.controls { top: 72px; left: 10px; width: 225px; padding: 12px; }
.safety { top: 10px; right: 10px; width: 190px; padding: 11px; }
.safe-banner { font-size: 11px; }
.metric { min-height: 49px; padding: 8px; }
.metric strong { font-size: 15px; }
.metric-grid { grid-template-columns: 1fr; }
.metric:nth-child(3), .metric:nth-child(4) { display: none; }
.timeline { left: 10px; right: 10px; bottom: 66px; width: auto; transform: none; }
.camera-tools { right: 10px; bottom: 10px; }
.phase-labels { font-size: 7px; }
#success { top: 205px; min-width: 270px; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Simulação tridimensional de dois caracteres carregando um banco"></canvas>
<div class="ui">
<header class="topbar">
<div class="brand-mark">CC</div>
<div>
<div class="brand-title">Coop Carry</div>
<div class="brand-sub">Laboratório de transporte colaborativo</div>
</div>
</header>
<section class="panel controls">
<div class="eyebrow">Estado da dupla</div>
<div class="status-row">
<div id="status">Validando rota</div>
<div id="statusDot" class="status-dot"></div>
</div>
<div id="phase">Teste geométrico da trajetória completa.</div>
<div class="button-row">
<button id="playButton" class="primary" type="button">Pausar</button>
<button id="resetButton" type="button">Reiniciar</button>
<button id="validateButton" type="button">Validar</button>
</div>
<div class="speed-row">
<span class="eyebrow">Velocidade</span>
<div class="speed-buttons">
<button type="button" data-speed="0.5">0,5×</button>
<button type="button" data-speed="1" class="active">1×</button>
<button type="button" data-speed="1.5">1,5×</button>
</div>
</div>
</section>
<section class="panel safety">
<div class="safe-banner">
<span class="check">✓</span>
<span id="validationTitle">Trajetória validada</span>
</div>
<div class="metric-grid">
<div class="metric">
<span>Posições inseguras</span>
<strong id="unsafeCount" class="good">0</strong>
</div>
<div class="metric">
<span>Safety Hold</span>
<strong id="holdCount" class="good">0</strong>
</div>
<div class="metric">
<span>Folga mínima</span>
<strong id="clearance">—</strong>
</div>
<div class="metric">
<span>Amostras testadas</span>
<strong id="sampleCount">—</strong>
</div>
</div>
<p class="validation-note" id="validationNote">
O banco é testado contra paredes, o bloco central e os invólucros corporais de A e B.
</p>
</section>
<section class="panel objective">
<div class="eyebrow">Objetivo de aprendizagem</div>
<p>
Sincronizar deslocamento e rotação, antecipar a folga dos obstáculos e concluir
a passagem entre A e B sem intersecções entre banco, paredes ou corpos.
</p>
</section>
<section class="panel timeline">
<div class="timeline-head">
<span>Travessia coordenada</span>
<span id="progressText">0%</span>
</div>
<div class="track"><div id="progressFill"></div></div>
<div class="phase-labels">
<span>Alinhar</span>
<span>Girar 90°</span>
<span>Contornar</span>
<span>Girar 90°</span>
<span>Saída A–B</span>
</div>
</section>
<div class="panel camera-tools" aria-label="Controles de câmera">
<button id="orbitLeft" type="button" aria-label="Girar câmera para a esquerda">↶</button>
<button id="overview" type="button">Visão geral</button>
<button id="orbitRight" type="button" aria-label="Girar câmera para a direita">↷</button>
</div>
<div id="success">
<strong>Travessia concluída!</strong>
<span>A e B passaram entre os marcos A–B sem posições inseguras.</span>
</div>
<div id="toast"></div>
</div>
<div id="loading">Preparando laboratório cooperativo…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.setClearColor(0xdce6df, 1);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xdce6df, 38, 58);
const camera = new THREE.OrthographicCamera(-16, 16, 9, -9, 0.1, 100);
const cameraRig = {
target: new THREE.Vector3(0.2, 0.4, -0.2),
yaw: 0.68,
pitch: 0.73,
radius: 32,
zoom: 1
};
scene.add(new THREE.HemisphereLight(0xf7fff4, 0x6f817b, 2.15));
const sun = new THREE.DirectionalLight(0xfff4dc, 3.1);
sun.position.set(9, 18, 12);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -19;
sun.shadow.camera.right = 19;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 50;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb8dcff, 0.8);
fill.position.set(-13, 8, -9);
scene.add(fill);
const materials = {
floor: new THREE.MeshStandardMaterial({ color: 0xd5ddd5, roughness: 0.95 }),
floorEdge: new THREE.MeshStandardMaterial({ color: 0xaab8ae, roughness: 0.95 }),
wall: new THREE.MeshStandardMaterial({ color: 0x7e9189, roughness: 0.88 }),
wallTop: new THREE.MeshStandardMaterial({ color: 0x9cada4, roughness: 0.9 }),
obstacle: new THREE.MeshStandardMaterial({ color: 0x8b8378, roughness: 0.9 }),
obstacleTop: new THREE.MeshStandardMaterial({ color: 0xa39a8b, roughness: 0.88 }),
route: new THREE.MeshStandardMaterial({ color: 0x4aa49d, roughness: 0.72, emissive: 0x123f3c, emissiveIntensity: 0.22 }),
wood: new THREE.MeshStandardMaterial({ color: 0xb9783f, roughness: 0.82 }),
woodLight: new THREE.MeshStandardMaterial({ color: 0xd39554, roughness: 0.8 }),
dark: new THREE.MeshStandardMaterial({ color: 0x273638, roughness: 0.82 }),
teal: new THREE.MeshStandardMaterial({ color: 0x1a8f87, roughness: 0.75 }),
coral: new THREE.MeshStandardMaterial({ color: 0xe27051, roughness: 0.75 }),
gold: new THREE.MeshStandardMaterial({ color: 0xe6b443, roughness: 0.76 }),
skinA: new THREE.MeshStandardMaterial({ color: 0xc98261, roughness: 0.86 }),
skinB: new THREE.MeshStandardMaterial({ color: 0x8f5d48, roughness: 0.86 }),
white: new THREE.MeshStandardMaterial({ color: 0xf6f5ea, roughness: 0.8 }),
eye: new THREE.MeshStandardMaterial({ color: 0x162326, roughness: 0.75 }),
start: new THREE.MeshStandardMaterial({ color: 0x86a995, roughness: 0.92 })
};
const edgeMaterial = new THREE.LineBasicMaterial({ color: 0x35494a, transparent: true, opacity: 0.26 });
function addBox(width, height, depth, x, y, z, material, edges = false, parent = scene) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth), material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
if (edges) {
const outline = new THREE.LineSegments(new THREE.EdgesGeometry(mesh.geometry), edgeMaterial);
mesh.add(outline);
}
return mesh;
}
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function makeLabel(text, background = "#172a2c", foreground = "#ffffff", width = 1.25, height = 0.58) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 112;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, 256, 112);
roundedRect(ctx, 8, 8, 240, 96, 22);
ctx.fillStyle = background;
ctx.fill();
ctx.fillStyle = foreground;
ctx.font = "800 52px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 128, 57);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
}));
sprite.scale.set(width, height, 1);
sprite.renderOrder = 20;
return sprite;
}
// Collision geometry and matching visible obstacles.
const obstacleRects = [
{ id: "parede oeste", x: -11.7, z: 0, w: 0.4, d: 15.8, kind: "wall" },
{ id: "parede norte", x: -0.1, z: -7.7, w: 23.6, d: 0.4, kind: "wall" },
{ id: "parede sul", x: -0.1, z: 7.7, w: 23.6, d: 0.4, kind: "wall" },
{ id: "parede leste inferior", x: 11.7, z: -6.4, w: 0.4, d: 3.2, kind: "wall" },
{ id: "parede leste superior", x: 11.7, z: 4, w: 0.4, d: 8, kind: "wall" },
{ id: "bloco central", x: 1.5, z: 0.1, w: 5, d: 2.6, kind: "obstacle" },
{ id: "marco A", x: 11.25, z: -4.15, w: 1, d: 0.9, kind: "gate" },
{ id: "marco B", x: 11.25, z: -0.65, w: 1, d: 0.9, kind: "gate" }
];
addBox(28, 0.22, 18, 1, -0.13, 0, materials.floor, true);
addBox(3.1, 0.24, 4.8, 13.1, -0.12, -2.4, materials.start, true);
const grid = new THREE.GridHelper(28, 28, 0x9baaa2, 0xb9c5bd);
grid.position.set(1, 0.006, 0);
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
for (const rect of obstacleRects) {
const mat = rect.kind === "gate"
? (rect.id.endsWith("A") ? materials.gold : materials.teal)
: rect.kind === "obstacle"
? materials.obstacle
: materials.wall;
addBox(rect.w, 1.55, rect.d, rect.x, 0.775, rect.z, mat, true);
addBox(rect.w, 0.13, rect.d, rect.x, 1.6, rect.z,
rect.kind === "gate" ? mat : materials.wallTop, false);
}
// Voxel details on the central island remain inside the collision footprint.
addBox(1.35, 0.55, 1.2, -0.05, 1.9, 0.1, materials.obstacleTop, true);
addBox(1.35, 0.55, 1.2, 1.65, 1.9, 0.1, materials.obstacleTop, true);
addBox(1.35, 0.55, 1.2, 3.35, 1.9, 0.1, materials.obstacleTop, true);
addBox(0.6, 0.35, 0.6, 0.8, 2.35, 0.1, materials.gold, true);
const centralLabel = makeLabel("BLOCO 01", "#5e5951", "#ffffff", 2.1, 0.68);
centralLabel.position.set(1.5, 2.85, 0.1);
scene.add(centralLabel);
const labelA = makeLabel("A", "#e6b443", "#243638", 0.72, 0.72);
labelA.position.set(11.25, 2.55, -4.15);
scene.add(labelA);
const labelB = makeLabel("B", "#1a8f87", "#ffffff", 0.72, 0.72);
labelB.position.set(11.25, 2.55, -0.65);
scene.add(labelB);
const exitLabel = makeLabel("SAÍDA A–B", "#172a2c", "#ffffff", 2.35, 0.72);
exitLabel.position.set(11.2, 3.25, -2.4);
scene.add(exitLabel);
const startLabel = makeLabel("ZONA DE CARGA", "#607b6b", "#ffffff", 2.25, 0.62);
startLabel.position.set(-8.2, 0.65, 6.35);
scene.add(startLabel);
const BENCH_LENGTH = 3.2;
const BENCH_WIDTH = 0.82;
const BODY_OFFSET = 0.68;
const segments = [
{ type: "move", from: { x: -8.3, z: 4 }, to: { x: -6, z: 4 }, angle: 0, duration: 2.4, phase: "Alinhamento e avanço inicial" },
{ type: "rotate", at: { x: -6, z: 4 }, fromAngle: 0, toAngle: -Math.PI / 2, duration: 2.2, phase: "Giro coordenado de 90° na praça de giro" },
{ type: "move", from: { x: -6, z: 4 }, to: { x: -6, z: -2.4 }, angle: -Math.PI / 2, duration: 3.4, phase: "Contorno do bloco central com offsets coordenados" },
{ type: "rotate", at: { x: -6, z: -2.4 }, fromAngle: -Math.PI / 2, toAngle: 0, duration: 2.2, phase: "Segundo giro de 90° antes do vão" },
{ type: "move", from: { x: -6, z: -2.4 }, to: { x: 10.4, z: -2.4 }, angle: 0, duration: 6.6, phase: "Travessia final pelo vão A–B" }
];
const totalDuration = segments.reduce((sum, segment) => sum + segment.duration, 0);
function smoothstep(t) {
return t * t * (3 - 2 * t);
}
function stateAt(time) {
let remaining = THREE.MathUtils.clamp(time, 0, totalDuration);
for (let index = 0; index < segments.length; index++) {
const segment = segments[index];
if (remaining <= segment.duration || index === segments.length - 1) {
const u = THREE.MathUtils.clamp(remaining / segment.duration, 0, 1);
if (segment.type === "move") {
return {
x: THREE.MathUtils.lerp(segment.from.x, segment.to.x, u),
z: THREE.MathUtils.lerp(segment.from.z, segment.to.z, u),
angle: segment.angle,
phaseIndex: index,
phase: segment.phase,
moving: true,
segment,
localU: u
};
}
const eased = smoothstep(u);
return {
x: segment.at.x,
z: segment.at.z,
angle: THREE.MathUtils.lerp(segment.fromAngle, segment.toAngle, eased),
phaseIndex: index,
phase: segment.phase,
moving: false,
segment,
localU: u
};
}
remaining -= segment.duration;
}
}
function addRouteDashes(from, to) {
const dx = to.x - from.x;
const dz = to.z - from.z;
const length = Math.hypot(dx, dz);
const count = Math.max(1, Math.floor(length / 0.72));
for (let i = 0; i < count; i++) {
const u = (i + 0.5) / count;
const dash = addBox(0.42, 0.045, 0.16,
THREE.MathUtils.lerp(from.x, to.x, u),
0.028,
THREE.MathUtils.lerp(from.z, to.z, u),
materials.route, false);
dash.rotation.y = -Math.atan2(dz, dx);
dash.castShadow = false;
}
}
addRouteDashes({ x: -8.3, z: 4 }, { x: -6, z: 4 });
addRouteDashes({ x: -6, z: 4 }, { x: -6, z: -2.4 });
addRouteDashes({ x: -6, z: -2.4 }, { x: 10.4, z: -2.4 });
function addArcDashes(center, radius, fromAngle, toAngle) {
const count = 12;
for (let i = 0; i < count; i++) {
const a = THREE.MathUtils.lerp(fromAngle, toAngle, (i + 0.5) / count);
const dash = addBox(0.16, 0.045, 0.16,
center.x + Math.cos(a) * radius,
0.03,
center.z + Math.sin(a) * radius,
materials.route, false);
dash.rotation.y = -a;
dash.castShadow = false;
}
}
addArcDashes({ x: -6, z: 4 }, 2.45, 0, -Math.PI / 2);
addArcDashes({ x: -6, z: -2.4 }, 2.45, -Math.PI / 2, 0);
const bench = new THREE.Group();
scene.add(bench);
addBox(BENCH_LENGTH, 0.18, 0.76, 0, 0, 0, materials.woodLight, true, bench);
addBox(BENCH_LENGTH, 0.42, 0.16, 0, 0.29, -0.32, materials.wood, true, bench);
addBox(0.18, 0.62, 0.68, -1.1, -0.33, 0, materials.dark, true, bench);
addBox(0.18, 0.62, 0.68, 1.1, -0.33, 0, materials.dark, true, bench);
addBox(0.17, 0.18, 0.95, -1.58, 0, 0, materials.gold, true, bench);
addBox(0.17, 0.18, 0.95, 1.58, 0, 0, materials.gold, true, bench);
function createCharacter(letter, shirtMaterial, skinMaterial) {
const root = new THREE.Group();
scene.add(root);
addBox(0.64, 0.25, 0.46, 0, 0.79, 0, materials.dark, true, root);
addBox(0.74, 0.62, 0.62, 0, 1.12, 0, shirtMaterial, true, root);
addBox(0.56, 0.53, 0.52, 0, 1.72, 0, skinMaterial, true, root);
addBox(0.6, 0.15, 0.56, 0, 2.02, 0, materials.dark, true, root);
addBox(0.1, 0.1, 0.035, -0.14, 1.76, 0.274, materials.eye, false, root);
addBox(0.1, 0.1, 0.035, 0.14, 1.76, 0.274, materials.eye, false, root);
const armLeft = addBox(0.18, 0.22, 0.54, -0.45, 1.22, 0.23, shirtMaterial, true, root);
const armRight = addBox(0.18, 0.22, 0.54, 0.45, 1.22, 0.23, shirtMaterial, true, root);
armLeft.rotation.x = -0.13;
armRight.rotation.x = -0.13;
addBox(0.2, 0.18, 0.2, -0.45, 1.23, 0.53, skinMaterial, true, root);
addBox(0.2, 0.18, 0.2, 0.45, 1.23, 0.53, skinMaterial, true, root);
const legPivots = [];
for (const side of [-1, 1]) {
const pivot = new THREE.Group();
pivot.position.set(side * 0.2, 0.75, 0);
root.add(pivot);
addBox(0.24, 0.58, 0.27, 0, -0.28, 0, materials.dark, true, pivot);
addBox(0.27, 0.18, 0.4, 0, -0.59, 0.06, materials.white, true, pivot);
legPivots.push(pivot);
}
const badge = makeLabel(letter, letter === "A" ? "#e6b443" : "#1a8f87",
letter === "A" ? "#243638" : "#ffffff", 0.58, 0.58);
badge.position.set(0, 2.48, 0);
root.add(badge);
return { root, legPivots, badge };
}
const characterA = createCharacter("A", materials.teal, materials.skinA);
const characterB = createCharacter("B", materials.coral, materials.skinB);
// Convex geometry helpers. All collision checks use the same dimensions as
// the visible bench, walls, island, gate markers and torso envelopes.
function rectPolygon(rect) {
const hx = rect.w / 2;
const hz = rect.d / 2;
return [
{ x: rect.x - hx, z: rect.z - hz },
{ x: rect.x + hx, z: rect.z - hz },
{ x: rect.x + hx, z: rect.z + hz },
{ x: rect.x - hx, z: rect.z + hz }
];
}
function obbPolygon(x, z, angle, halfX, halfZ) {
const ax = Math.cos(angle);
const az = Math.sin(angle);
const bx = -Math.sin(angle);
const bz = Math.cos(angle);
const corners = [
[-halfX, -halfZ],
[ halfX, -halfZ],
[ halfX, halfZ],
[-halfX, halfZ]
];
return corners.map(([u, v]) => ({
x: x + ax * u + bx * v,
z: z + az * u + bz * v
}));
}
function carrierData(state) {
const ax = Math.cos(state.angle);
const az = Math.sin(state.angle);
return [-1, 1].map((sign) => {
const outwardX = ax * sign;
const outwardZ = az * sign;
const distance = BENCH_LENGTH / 2 + BODY_OFFSET;
const x = state.x + outwardX * distance;
const z = state.z + outwardZ * distance;
const inwardX = -outwardX;
const inwardZ = -outwardZ;
const visualYaw = Math.atan2(inwardX, inwardZ);
const collisionAngle = -visualYaw;
return {
sign,
x,
z,
visualYaw,
polygon: obbPolygon(x, z, collisionAngle, 0.37, 0.32)
};
});
}
function projectPolygon(polygon, axis) {
let min = Infinity;
let max = -Infinity;
for (const point of polygon) {
const value = point.x * axis.x + point.z * axis.z;
min = Math.min(min, value);
max = Math.max(max, value);
}
return { min, max };
}
function polygonsOverlap(a, b) {
const axes = [];
for (const polygon of [a, b]) {
for (let i = 0; i < polygon.length; i++) {
const p = polygon[i];
const q = polygon[(i + 1) % polygon.length];
axes.push({ x: -(q.z - p.z), z: q.x - p.x });
}
}
for (const axis of axes) {
const pa = projectPolygon(a, axis);
const pb = projectPolygon(b, axis);
if (pa.max <= pb.min + 1e-8 || pb.max <= pa.min + 1e-8) return false;
}
return true;
}
function pointSegmentDistance(p, a, b) {
const dx = b.x - a.x;
const dz = b.z - a.z;
const lengthSquared = dx * dx + dz * dz;
if (lengthSquared === 0) return Math.hypot(p.x - a.x, p.z - a.z);
const t = THREE.MathUtils.clamp(((p.x - a.x) * dx + (p.z - a.z) * dz) / lengthSquared, 0, 1);
return Math.hypot(p.x - (a.x + t * dx), p.z - (a.z + t * dz));
}
function orientation(a, b, c) {
return (b.z - a.z) * (c.x - b.x) - (b.x - a.x) * (c.z - b.z);
}
function onSegment(a, b, p) {
return Math.min(a.x, b.x) - 1e-8 <= p.x && p.x <= Math.max(a.x, b.x) + 1e-8 &&
Math.min(a.z, b.z) - 1e-8 <= p.z && p.z <= Math.max(a.z, b.z) + 1e-8;
}
function segmentsIntersect(a, b, c, d) {
const o1 = orientation(a, b, c);
const o2 = orientation(a, b, d);
const o3 = orientation(c, d, a);
const o4 = orientation(c, d, b);
if (((o1 > 0 && o2 < 0) || (o1 < 0 && o2 > 0)) &&
((o3 > 0 && o4 < 0) || (o3 < 0 && o4 > 0))) return true;
if (Math.abs(o1) < 1e-9 && onSegment(a, b, c)) return true;
if (Math.abs(o2) < 1e-9 && onSegment(a, b, d)) return true;
if (Math.abs(o3) < 1e-9 && onSegment(c, d, a)) return true;
if (Math.abs(o4) < 1e-9 && onSegment(c, d, b)) return true;
return false;
}
function polygonDistance(a, b) {
if (polygonsOverlap(a, b)) return 0;
let minimum = Infinity;
for (let i = 0; i < a.length; i++) {
const a1 = a[i];
const a2 = a[(i + 1) % a.length];
for (let j = 0; j < b.length; j++) {
const b1 = b[j];
const b2 = b[(j + 1) % b.length];
if (segmentsIntersect(a1, a2, b1, b2)) return 0;
minimum = Math.min(minimum,
pointSegmentDistance(a1, b1, b2),
pointSegmentDistance(a2, b1, b2),
pointSegmentDistance(b1, a1, a2),
pointSegmentDistance(b2, a1, a2)
);
}
}
return minimum;
}
function inspectState(state) {
const benchPolygon = obbPolygon(state.x, state.z, state.angle, BENCH_LENGTH / 2, BENCH_WIDTH / 2);
const carriers = carrierData(state);
const hits = [];
let minimumClearance = Infinity;
for (const rect of obstacleRects) {
const rectPoly = rectPolygon(rect);
if (polygonsOverlap(benchPolygon, rectPoly)) hits.push(`banco/${rect.id}`);
minimumClearance = Math.min(minimumClearance, polygonDistance(benchPolygon, rectPoly));
for (let i = 0; i < carriers.length; i++) {
if (polygonsOverlap(carriers[i].polygon, rectPoly)) hits.push(`${i === 0 ? "A" : "B"}/${rect.id}`);
minimumClearance = Math.min(minimumClearance, polygonDistance(carriers[i].polygon, rectPoly));
}
}
for (const carrier of carriers) {
minimumClearance = Math.min(minimumClearance, polygonDistance(benchPolygon, carrier.polygon));
}
return {
safe: hits.length === 0,
hits,
clearance: minimumClearance
};
}
function validateRoute() {
const sampleCount = 1400;
let unsafe = 0;
let minimumClearance = Infinity;
const failures = [];
for (let i = 0; i < sampleCount; i++) {
const state = stateAt(totalDuration * i / (sampleCount - 1));
const result = inspectState(state);
minimumClearance = Math.min(minimumClearance, result.clearance);
if (!result.safe) {
unsafe++;
if (failures.length < 5) failures.push(`${i}: ${result.hits.join(", ")}`);
}
}
return { sampleCount, unsafe, minimumClearance, failures };
}
let validation = validateRoute();
let runtimeSamples = 0;
let runtimeUnsafe = 0;
let safetyHolds = 0;
let simulationTime = 0;
let playing = true;
let speed = 1;
let completed = false;
let lastUiUpdate = 0;
let toastTimer = 0;
const statusElement = document.getElementById("status");
const statusDot = document.getElementById("statusDot");
const phaseElement = document.getElementById("phase");
const unsafeElement = document.getElementById("unsafeCount");
const holdElement = document.getElementById("holdCount");
const clearanceElement = document.getElementById("clearance");
const sampleElement = document.getElementById("sampleCount");
const validationTitle = document.getElementById("validationTitle");
const validationNote = document.getElementById("validationNote");
const progressFill = document.getElementById("progressFill");
const progressText = document.getElementById("progressText");
const playButton = document.getElementById("playButton");
const success = document.getElementById("success");
const toast = document.getElementById("toast");
const numberFormat = new Intl.NumberFormat("pt-BR");
const decimalFormat = new Intl.NumberFormat("pt-BR", {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
function showToast(message) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2300);
}
function updateSafetyUI(result) {
const totalUnsafe = validation.unsafe + runtimeUnsafe;
unsafeElement.textContent = numberFormat.format(totalUnsafe);
holdElement.textContent = numberFormat.format(safetyHolds);
unsafeElement.className = totalUnsafe === 0 ? "good" : "alert";
holdElement.className = safetyHolds === 0 ? "good" : "alert";
clearanceElement.textContent = `${decimalFormat.format(result.clearance)} m`;
sampleElement.textContent = numberFormat.format(validation.sampleCount + runtimeSamples);
}
function updateStatus(state, result) {
const progress = THREE.MathUtils.clamp(simulationTime / totalDuration, 0, 1);
progressFill.style.width = `${progress * 100}%`;
progressText.textContent = `${Math.round(progress * 100)}%`;
phaseElement.textContent = state.phase;
if (!result.safe) {
statusElement.textContent = "Safety Hold";
statusDot.className = "status-dot";
phaseElement.textContent = "Colisão geométrica detectada; revisão da trajetória necessária.";
} else if (completed) {
statusElement.textContent = "Travessia concluída";
statusDot.className = "status-dot safe";
} else {
statusElement.textContent = playing ? "Travessia em curso" : "Pausa segura";
statusDot.className = "status-dot safe";
}
}
function applyValidationToUI() {
validationTitle.textContent = validation.unsafe === 0 ? "Trajetória validada" : "Trajetória requer revisão";
validationNote.textContent = validation.unsafe === 0
? `${numberFormat.format(validation.sampleCount)} estados testados: banco, corpos, paredes, bloco central e vão A–B. Nenhuma intersecção.`
: `${validation.unsafe} estados inseguros encontrados: ${validation.failures.join(" | ")}`;
}
function updateCharacters(state, time) {
const carriers = carrierData(state);
const gaitTime = time * 8.5;
const gaitAmplitude = state.moving ? 0.42 : 0;
const characters = [characterA, characterB];
for (let i = 0; i < carriers.length; i++) {
const carrier = carriers[i];
const character = characters[i];
const bob = state.moving ? Math.abs(Math.sin(gaitTime + i * Math.PI)) * 0.035 : 0;
character.root.position.set(carrier.x, bob, carrier.z);
character.root.rotation.y = carrier.visualYaw;
character.legPivots[0].rotation.x = Math.sin(gaitTime + i * Math.PI) * gaitAmplitude;
character.legPivots[1].rotation.x = -Math.sin(gaitTime + i * Math.PI) * gaitAmplitude;
}
bench.position.set(state.x, 1.17 + (state.moving ? Math.sin(time * 8.5) * 0.018 : 0), state.z);
bench.rotation.y = -state.angle;
}
function updateCamera() {
const aspect = Math.max(0.45, window.innerWidth / Math.max(1, window.innerHeight));
const halfHeight = Math.max(9.2, 14.2 / aspect) / cameraRig.zoom;
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
const cp = Math.cos(cameraRig.pitch);
camera.position.set(
cameraRig.target.x + Math.sin(cameraRig.yaw) * cp * cameraRig.radius,
cameraRig.target.y + Math.sin(cameraRig.pitch) * cameraRig.radius,
cameraRig.target.z + Math.cos(cameraRig.yaw) * cp * cameraRig.radius
);
camera.lookAt(cameraRig.target);
}
function resize() {
renderer.setSize(window.innerWidth, window.innerHeight, false);
updateCamera();
}
window.addEventListener("resize", resize);
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
canvas.classList.add("dragging");
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraRig.yaw -= dx * 0.006;
cameraRig.pitch = THREE.MathUtils.clamp(cameraRig.pitch + dy * 0.004, 0.38, 1.22);
});
function stopDragging() {
dragging = false;
canvas.classList.remove("dragging");
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraRig.zoom = THREE.MathUtils.clamp(cameraRig.zoom * (event.deltaY > 0 ? 0.92 : 1.08), 0.72, 1.65);
}, { passive: false });
document.getElementById("orbitLeft").addEventListener("click", () => {
cameraRig.yaw -= Math.PI / 8;
});
document.getElementById("orbitRight").addEventListener("click", () => {
cameraRig.yaw += Math.PI / 8;
});
document.getElementById("overview").addEventListener("click", () => {
cameraRig.target.set(0.2, 0.4, -0.2);
cameraRig.yaw = 0.68;
cameraRig.pitch = 0.73;
cameraRig.zoom = 1;
});
playButton.addEventListener("click", () => {
if (completed) {
simulationTime = 0;
completed = false;
success.classList.remove("show");
playing = true;
} else {
playing = !playing;
}
playButton.textContent = playing ? "Pausar" : "Continuar";
});
document.getElementById("resetButton").addEventListener("click", () => {
simulationTime = 0;
runtimeSamples = 0;
runtimeUnsafe = 0;
safetyHolds = 0;
completed = false;
playing = true;
success.classList.remove("show");
playButton.textContent = "Pausar";
showToast("Travessia reiniciada com a rota validada");
});
document.getElementById("validateButton").addEventListener("click", () => {
validation = validateRoute();
applyValidationToUI();
const state = stateAt(simulationTime);
updateSafetyUI(inspectState(state));
showToast(validation.unsafe === 0
? `${numberFormat.format(validation.sampleCount)} amostras · 0 posições inseguras`
: `${validation.unsafe} posições inseguras detectadas`);
});
document.querySelectorAll("[data-speed]").forEach((button) => {
button.addEventListener("click", () => {
speed = Number(button.dataset.speed);
document.querySelectorAll("[data-speed]").forEach((item) => item.classList.remove("active"));
button.classList.add("active");
});
});
applyValidationToUI();
resize();
const initialState = stateAt(0);
updateSafetyUI(inspectState(initialState));
updateStatus(initialState, inspectState(initialState));
let previousTime = performance.now();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (playing && !completed) {
simulationTime = Math.min(totalDuration, simulationTime + delta * speed);
if (simulationTime >= totalDuration) {
completed = true;
playing = false;
playButton.textContent = "Repetir";
success.classList.add("show");
}
}
const state = stateAt(simulationTime);
const result = inspectState(state);
if (!result.safe && runtimeUnsafe === 0) {
runtimeUnsafe++;
safetyHolds++;
playing = false;
playButton.textContent = "Continuar";
showToast("Safety Hold: trajetória interrompida por colisão");
}
runtimeSamples++;
updateCharacters(state, simulationTime);
if (now - lastUiUpdate > 100) {
updateSafetyUI(result);
updateStatus(state, result);
lastUiUpdate = now;
}
updateCamera();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
requestAnimationFrame(() => document.getElementById("loading").classList.add("hidden"));
</script>
</body>
</html>
```