Prompt specification
Build or customize the Three.js 3D scene "Move Supports to Close a Gap" 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: Move Supports to Close a Gap
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/move-supports-to-close-a-gap-x3442
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a tabletop bridge puzzle with fixed-length planks and movable piers. Validate geometric contact and continuous walking space rather than simulating full material failure. Voxel style.
Technical checks: When the solution is revealed, place all five 4 m segments on their supports. Measure contacts and usable width from the visible geometry in a consistent coordinate plane.
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 (move-supports-to-close-a-gap-x3442):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ponte de Voxel — Contato Geométrico X–Z</title>
<style>
:root {
--ink: #173438;
--muted: #587276;
--paper: rgba(248, 250, 245, 0.88);
--paper-strong: rgba(251, 252, 248, 0.96);
--line: rgba(31, 67, 68, 0.14);
--green: #238b65;
--green-soft: #d9f1e5;
--amber: #d8882f;
--amber-soft: #fff0d7;
--red: #c95348;
--red-soft: #ffe3df;
--shadow: 0 14px 40px rgba(29, 59, 60, 0.14);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce8e3;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, canvas { -webkit-tap-highlight-color: transparent; }
#app {
position: relative;
width: 100%;
height: 100%;
isolation: isolate;
}
#scene {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
outline: none;
touch-action: none;
}
.hud {
position: absolute;
inset: 0;
z-index: 5;
pointer-events: none;
}
.panel {
pointer-events: auto;
border: 1px solid rgba(255, 255, 255, 0.72);
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(16px) saturate(1.12);
-webkit-backdrop-filter: blur(16px) saturate(1.12);
}
.brand {
position: absolute;
top: 18px;
left: 18px;
width: min(348px, calc(100vw - 36px));
padding: 17px 18px 16px;
border-radius: 18px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
color: #41666a;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.mini-mark {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--amber);
box-shadow: 12px 0 0 #6d9290, 24px 0 0 #2b6668;
}
h1 {
margin: 8px 0 7px;
font-size: clamp(23px, 2.5vw, 31px);
line-height: 1.04;
letter-spacing: -0.035em;
}
.brand p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.48;
}
.axis-chip {
display: inline-flex;
align-items: center;
gap: 7px;
margin-top: 12px;
padding: 7px 9px;
border-radius: 8px;
color: #24585a;
background: #e1efea;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.axis-chip::before {
content: "";
width: 8px;
height: 8px;
border: 2px solid #3f7f7e;
border-radius: 50%;
}
.status {
position: absolute;
top: 18px;
right: 18px;
width: min(326px, calc(100vw - 36px));
padding: 15px;
border-radius: 18px;
transition: border-color 180ms ease, box-shadow 180ms ease;
}
.status[data-state="good"] {
border-color: rgba(58, 166, 119, 0.42);
box-shadow: 0 14px 40px rgba(37, 124, 91, 0.16);
}
.status[data-state="bad"] {
border-color: rgba(201, 83, 72, 0.32);
}
.status-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
}
.status-head strong {
font-size: 12px;
letter-spacing: 0.025em;
}
.status-head span:last-child {
color: #789093;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.14em;
}
.status-dot {
width: 9px;
height: 9px;
margin-right: 8px;
display: inline-block;
border-radius: 3px;
background: #9eaaa9;
box-shadow: 0 0 0 4px rgba(158, 170, 169, 0.15);
}
.status[data-state="good"] .status-dot {
background: var(--green);
box-shadow: 0 0 0 4px rgba(35, 139, 101, 0.14);
}
.status[data-state="bad"] .status-dot {
background: var(--red);
box-shadow: 0 0 0 4px rgba(201, 83, 72, 0.13);
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.metric {
min-width: 0;
padding: 10px 8px 9px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.52);
}
.metric small {
display: block;
margin-bottom: 4px;
color: #6d8587;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.12em;
}
.metric strong {
display: block;
overflow: hidden;
color: var(--ink);
font-size: 18px;
line-height: 1;
text-overflow: ellipsis;
white-space: nowrap;
}
.status[data-state="good"] .metric strong { color: var(--green); }
.status[data-state="bad"] .metric:first-child strong { color: var(--red); }
.progress-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-top: 11px;
}
.progress-label {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 6px;
color: #6c8183;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.pips { display: flex; gap: 5px; }
.pip {
width: 15px;
height: 6px;
border-radius: 3px;
background: #d9dfdc;
box-shadow: inset 0 0 0 1px rgba(32, 68, 69, 0.05);
transition: background 150ms ease, transform 150ms ease;
}
.pip.ok {
background: #45aa7d;
transform: translateY(-1px);
}
.validation-text {
min-height: 39px;
margin: 12px 1px 0;
color: #5e7476;
font-size: 11px;
line-height: 1.42;
}
.toolbar {
position: absolute;
right: 18px;
bottom: 18px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 7px;
max-width: min(650px, calc(100vw - 36px));
padding: 8px;
border-radius: 16px;
}
button {
min-height: 38px;
padding: 0 13px;
border: 1px solid rgba(27, 67, 68, 0.14);
border-radius: 10px;
color: #294d50;
background: rgba(255, 255, 255, 0.72);
font: inherit;
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition: transform 130ms ease, background 130ms ease, border-color 130ms ease;
}
button:hover {
transform: translateY(-1px);
border-color: rgba(27, 67, 68, 0.26);
background: #fff;
}
button:active { transform: translateY(0); }
button:focus-visible {
outline: 3px solid rgba(56, 130, 130, 0.28);
outline-offset: 2px;
}
button.primary {
color: #432b13;
border-color: #d89136;
background: #f2ae4e;
}
button.primary:hover { background: #f8b956; }
button.test {
color: #315e60;
background: #e4efeb;
}
.guide {
position: absolute;
left: 18px;
bottom: 18px;
width: min(348px, calc(100vw - 36px));
padding: 12px 14px;
border-radius: 14px;
color: #536e71;
font-size: 10px;
line-height: 1.45;
}
.guide strong {
display: block;
margin-bottom: 3px;
color: #284f52;
font-size: 11px;
}
#selectionText {
display: block;
margin-top: 6px;
color: #2c6564;
font-variant-numeric: tabular-nums;
font-weight: 750;
}
.test-panel {
position: absolute;
top: 226px;
left: 18px;
width: min(348px, calc(100vw - 36px));
padding: 14px 15px;
border-radius: 15px;
background: var(--paper-strong);
}
.test-panel h2 {
margin: 0 0 4px;
font-size: 13px;
}
.test-panel > p {
margin: 0 0 10px;
color: #6b7f81;
font-size: 10px;
line-height: 1.4;
}
.test-list {
display: grid;
gap: 6px;
margin: 0;
padding: 0;
list-style: none;
}
.test-item {
display: grid;
grid-template-columns: 9px 1fr auto;
gap: 7px;
align-items: center;
padding: 8px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.58);
}
.test-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--red);
}
.test-item.pass .test-dot { background: var(--green); }
.test-item span:nth-child(2) {
font-size: 10px;
font-weight: 800;
}
.test-item strong {
color: var(--green);
font-size: 9px;
letter-spacing: 0.06em;
}
.test-item.fail strong { color: var(--red); }
.test-detail {
grid-column: 2 / 4;
color: #718486;
font-size: 9px;
line-height: 1.3;
}
.toast {
position: absolute;
left: 50%;
bottom: 82px;
max-width: min(520px, calc(100vw - 32px));
padding: 11px 16px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 12px;
color: #fff;
background: rgba(27, 60, 62, 0.91);
box-shadow: 0 12px 30px rgba(20, 48, 49, 0.2);
font-size: 11px;
font-weight: 750;
text-align: center;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 12px);
transition: opacity 180ms ease, transform 180ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.toast.good { background: rgba(27, 112, 81, 0.94); }
.toast.bad { background: rgba(157, 68, 61, 0.94); }
[hidden] { display: none !important; }
@media (max-width: 760px) {
.brand {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px 14px;
}
.brand p { font-size: 11px; }
.axis-chip { margin-top: 8px; }
.status {
top: 154px;
left: 10px;
right: 10px;
width: auto;
padding: 11px;
}
.metric { padding: 8px 7px; }
.metric strong { font-size: 15px; }
.validation-text { min-height: 0; margin-top: 8px; font-size: 10px; }
.toolbar {
right: 10px;
bottom: 10px;
left: 10px;
justify-content: center;
max-width: none;
}
button {
min-height: 36px;
padding: 0 10px;
font-size: 10px;
}
.guide { display: none; }
.test-panel {
top: 300px;
left: 10px;
width: calc(100vw - 20px);
}
.toast { bottom: 72px; }
}
</style>
</head>
<body>
<main id="app">
<canvas id="scene" tabindex="0" aria-label="Puzzle tridimensional de ponte com pranchas e apoios móveis"></canvas>
<div class="hud">
<section class="brand panel">
<div class="eyebrow"><span class="mini-mark"></span> Laboratório geométrico · Voxel</div>
<h1>Ponte de 5 × 4 m</h1>
<p>
As pranchas mantêm 4 m. Arraste os quatro apoios no tabuleiro para sustentar
cada junta e formar uma faixa de passagem contínua.
</p>
<div class="axis-chip">Pegadas X–Z · Altura Y</div>
</section>
<section id="statusCard" class="status panel" data-state="idle" aria-live="polite">
<div class="status-head">
<strong><span class="status-dot"></span><span id="statusTitle">AGUARDANDO VERIFICAÇÃO</span></strong>
<span>GEOMETRIA</span>
</div>
<div class="metrics">
<div class="metric">
<small>CONTATOS</small>
<strong id="metricContacts">0/5</strong>
</div>
<div class="metric">
<small>LARGURA ÚTIL</small>
<strong id="metricWidth">0,00 m</strong>
</div>
<div class="metric">
<small>CAMINHO</small>
<strong id="metricPath">CONTÍNUO</strong>
</div>
</div>
<div class="progress-row">
<div>
<div class="progress-label"><span>Pranchas</span><span id="jointText">0/4 juntas</span></div>
<div id="contactPips" class="pips" aria-label="Estado das cinco pranchas">
<span class="pip"></span><span class="pip"></span><span class="pip"></span>
<span class="pip"></span><span class="pip"></span>
</div>
</div>
<div>
<div class="progress-label"><span>Juntas</span><span>X–Z</span></div>
<div id="jointPips" class="pips" aria-label="Estado das quatro juntas">
<span class="pip"></span><span class="pip"></span><span class="pip"></span><span class="pip"></span>
</div>
</div>
</div>
<p id="validationText" class="validation-text">
A área de contato é calculada pela interseção real dos polígonos no plano X–Z.
</p>
</section>
<section id="testPanel" class="test-panel panel" hidden>
<h2>Testes sobre a cena real</h2>
<p>Os testes reposicionam os apoios, recalculam a geometria visível e restauram o estado atual.</p>
<ul id="testList" class="test-list"></ul>
</section>
<aside class="guide panel">
<strong>Como jogar</strong>
Arraste um apoio para moverlo em X e Z. Use as setas para ajustes de 0,25 m
e Shift para passos de 0,50 m. Arraste o fundo para orbitar; use a roda para zoom.
<span id="selectionText">A1 selecionado</span>
</aside>
<nav class="toolbar panel" aria-label="Ações do puzzle">
<button id="checkBtn" type="button">Verificar</button>
<button id="solutionBtn" type="button" class="primary">Revelar solução</button>
<button id="resetBtn" type="button">Embaralhar</button>
<button id="viewBtn" type="button">Vista de topo</button>
<button id="testBtn" type="button" class="test">Testes XZ 0/0</button>
</nav>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
</div>
</main>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// Coordinate convention:
// Y is vertical. Every support/plank footprint polygon uses only [x, z].
// Contact and width are therefore never computed from an x/y polygon.
const canvas = document.getElementById("scene");
const statusCard = document.getElementById("statusCard");
const statusTitle = document.getElementById("statusTitle");
const metricContacts = document.getElementById("metricContacts");
const metricWidth = document.getElementById("metricWidth");
const metricPath = document.getElementById("metricPath");
const jointText = document.getElementById("jointText");
const validationText = document.getElementById("validationText");
const contactPips = [...document.getElementById("contactPips").children];
const jointPips = [...document.getElementById("jointPips").children];
const selectionText = document.getElementById("selectionText");
const toastElement = document.getElementById("toast");
const testPanel = document.getElementById("testPanel");
const testList = document.getElementById("testList");
const testButton = document.getElementById("testBtn");
const CFG = {
plankLength: 4,
plankDepth: 1.4,
plankThickness: 0.35,
deckBottom: 1.65,
deckTop: 2.0,
endpointDepth: 0.45,
contactTolerance: 0.025,
minBearing: 0.12,
minWidth: 0.35,
minArea: 0.10,
pathStepTolerance: 0.42
};
const INITIAL_PIERS = [
{ x: -7.75, z: 0.55 },
{ x: -3.25, z: -0.65 },
{ x: 2.75, z: 0.55 },
{ x: 7.25, z: -0.55 }
];
const state = {
planks: [],
piers: [],
banks: [],
routeSurfaces: [],
targetMarkers: [],
selectedPier: 0
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce8e3);
scene.fog = new THREE.Fog(0xdce8e3, 31, 60);
const camera = new THREE.PerspectiveCamera(42, innerWidth / innerHeight, 0.1, 130);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const cameraRig = {
target: new THREE.Vector3(0, 0.8, 0),
radius: 26,
azimuth: 0.58,
polar: 1.02
};
let cameraTouched = false;
let topView = false;
let toastTimer = 0;
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -CFG.deckBottom);
const dragOffset = new THREE.Vector2();
let dragMode = null;
let lastPointer = { x: 0, y: 0 };
let seed = 481516;
function random() {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
}
const materials = {
base: new THREE.MeshStandardMaterial({ color: 0x294c4d, roughness: 0.86 }),
baseRim: new THREE.MeshStandardMaterial({ color: 0x173638, roughness: 0.9 }),
riverBed: new THREE.MeshStandardMaterial({ color: 0x287c8b, roughness: 0.48 }),
water: new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.32,
metalness: 0.03,
vertexColors: true
}),
foam: new THREE.MeshStandardMaterial({ color: 0xc9f2ed, roughness: 0.7 }),
stone: new THREE.MeshStandardMaterial({ color: 0x657b7e, roughness: 0.95 }),
stoneDark: new THREE.MeshStandardMaterial({ color: 0x465e62, roughness: 0.98 }),
earth: new THREE.MeshStandardMaterial({ color: 0x8c7854, roughness: 1 }),
grass: new THREE.MeshStandardMaterial({ color: 0x739b67, roughness: 1 }),
path: new THREE.MeshStandardMaterial({ color: 0xc5b481, roughness: 0.95 }),
wood: [
new THREE.MeshStandardMaterial({ color: 0xb87843, roughness: 0.82 }),
new THREE.MeshStandardMaterial({ color: 0xc4874c, roughness: 0.84 }),
new THREE.MeshStandardMaterial({ color: 0xad6b3b, roughness: 0.86 }),
new THREE.MeshStandardMaterial({ color: 0xc58a50, roughness: 0.8 }),
new THREE.MeshStandardMaterial({ color: 0xb57440, roughness: 0.84 })
],
grain: new THREE.MeshStandardMaterial({ color: 0x85502f, roughness: 0.95 }),
metal: new THREE.MeshStandardMaterial({ color: 0x455b5e, roughness: 0.58, metalness: 0.42 }),
pierBody: new THREE.MeshStandardMaterial({ color: 0x62777e, roughness: 0.92 }),
pierDark: new THREE.MeshStandardMaterial({ color: 0x4d646b, roughness: 0.96 }),
cap: new THREE.MeshStandardMaterial({
color: 0xe0a34d,
roughness: 0.7,
emissive: 0x000000,
emissiveIntensity: 0.25
})
};
function box(parent, size, position, material, options = {}) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = options.cast !== false;
mesh.receiveShadow = options.receive !== false;
if (options.renderOrder !== undefined) mesh.renderOrder = options.renderOrder;
parent.add(mesh);
return mesh;
}
function roundedRectPath(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 = "#244c4e", foreground = "#fff8e9", scale = [1.1, 0.35]) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 160;
const ctx = labelCanvas.getContext("2d");
roundedRectPath(ctx, 8, 8, 496, 144, 28);
ctx.fillStyle = background;
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = "rgba(255,255,255,0.28)";
ctx.stroke();
ctx.fillStyle = foreground;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "800 62px system-ui, sans-serif";
ctx.fillText(text, 256, 83);
const texture = new THREE.CanvasTexture(labelCanvas);
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(scale[0], scale[1], 1);
sprite.renderOrder = 20;
sprite.frustumCulled = false;
return sprite;
}
function addLights() {
const hemisphere = new THREE.HemisphereLight(0xfff8e7, 0x42666a, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffedcb, 3.0);
sun.position.set(9, 17, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 48;
sun.shadow.bias = -0.00035;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xaad9e4, 0.8);
fill.position.set(-12, 8, -10);
scene.add(fill);
}
function buildWorld() {
const shadowGround = new THREE.Mesh(
new THREE.PlaneGeometry(180, 180),
new THREE.ShadowMaterial({ color: 0x345b5d, opacity: 0.13 })
);
shadowGround.rotation.x = -Math.PI / 2;
shadowGround.position.y = -1.51;
shadowGround.receiveShadow = true;
scene.add(shadowGround);
box(scene, [30.5, 0.16, 10.7], [0, -1.42, 0], materials.baseRim);
box(scene, [30, 0.65, 10.2], [0, -1.05, 0], materials.base);
box(scene, [20, 0.12, 8.2], [0, -0.65, 0], materials.riverBed);
const columns = 20;
const rows = 8;
const tileGeometry = new THREE.BoxGeometry(0.92, 0.08, 0.92);
const tiles = new THREE.InstancedMesh(tileGeometry, materials.water, columns * rows);
tiles.receiveShadow = true;
tiles.castShadow = false;
const dummy = new THREE.Object3D();
const color = new THREE.Color();
let instance = 0;
for (let x = 0; x < columns; x++) {
for (let z = 0; z < rows; z++) {
dummy.position.set(-9.5 + x, -0.54 + random() * 0.018, -3.5 + z);
dummy.updateMatrix();
tiles.setMatrixAt(instance, dummy.matrix);
color.setHSL(0.52 + random() * 0.025, 0.47, 0.47 + random() * 0.07);
tiles.setColorAt(instance, color);
instance++;
}
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
scene.add(tiles);
for (let i = 0; i < 18; i++) {
const side = i % 2 ? 1 : -1;
const foam = box(
scene,
[0.35 + random() * 0.55, 0.035, 0.10],
[-9 + random() * 18, -0.475, side * (3.72 + random() * 0.16)],
materials.foam,
{ cast: false }
);
foam.rotation.y = (random() - 0.5) * 0.35;
}
createBank(-12, -1);
createBank(12, 1);
}
function createBank(centerX, side) {
box(scene, [4, 1.15, 7.2], [centerX, -0.125, 0], materials.stoneDark);
box(scene, [4, 0.90, 7.2], [centerX, 0.90, 0], materials.earth);
const top = box(scene, [4, 0.65, 7.2], [centerX, 1.675, 0], materials.grass);
state.routeSurfaces.push(top);
box(scene, [4, 0.03, 2.2], [centerX, 2.015, 0], materials.path, { cast: false });
const abutmentX = side < 0 ? -10.35 : 10.35;
const abutment = box(
scene,
[1.3, 0.25, 1.4],
[abutmentX, 1.525, 0],
materials.stone
);
const indicatorMaterial = new THREE.MeshStandardMaterial({
color: 0x99a5a4,
roughness: 0.7,
emissive: 0x000000,
emissiveIntensity: 0.3
});
const indicator = box(
scene,
[0.28, 0.10, 0.05],
[abutmentX, 1.52, 0.72],
indicatorMaterial,
{ cast: false }
);
state.banks.push({
id: side < 0 ? "B1" : "B2",
kind: "bank",
mesh: abutment,
indicator
});
for (let i = 0; i < 9; i++) {
const z = (i % 2 ? 1 : -1) * (2.25 + random() * 0.45);
const x = centerX + (random() - 0.5) * 3.2;
const size = 0.25 + random() * 0.28;
box(scene, [size, 0.18 + random() * 0.12, size], [x, 2.08, z], materials.grass);
}
const shrubX = centerX + side * 1.1;
const shrubZ = side < 0 ? 2.65 : -2.65;
box(scene, [0.22, 0.42, 0.22], [shrubX, 2.20, shrubZ], materials.earth);
box(scene, [0.72, 0.45, 0.66], [shrubX, 2.55, shrubZ], materials.grass);
box(scene, [0.48, 0.32, 0.48], [shrubX + 0.12, 2.88, shrubZ - 0.08], materials.grass);
}
function buildBridge() {
const centers = [-8, -4, 0, 4, 8];
for (let i = 0; i < centers.length; i++) {
const group = new THREE.Group();
group.position.x = centers[i];
scene.add(group);
const mesh = box(
group,
[CFG.plankLength, CFG.plankThickness, CFG.plankDepth],
[0, 1.825, 0],
materials.wood[i]
);
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
new THREE.LineBasicMaterial({
color: 0x70462f,
transparent: true,
opacity: 0.55
})
);
outline.position.copy(mesh.position);
group.add(outline);
for (const x of [-1.94, 1.94]) {
box(group, [0.10, 0.37, 1.43], [x, 1.825, 0], materials.metal);
}
for (let j = 0; j < 3; j++) {
const patch = box(
group,
[0.45 + random() * 0.35, 0.018, 0.11],
[(random() - 0.5) * 2.9, 2.008, (random() - 0.5) * 0.9],
materials.grain,
{ cast: false }
);
patch.rotation.y = 0;
}
const label = makeLabel(`${i + 1} · 4 m`, "#6f452c", "#fff3dc", [1.18, 0.37]);
label.position.set(0, 2.37, 0);
group.add(label);
const leftPadMaterial = new THREE.MeshBasicMaterial({
color: 0xd95e53,
transparent: true,
opacity: 0.35,
depthWrite: false
});
const rightPadMaterial = leftPadMaterial.clone();
const leftPad = box(
group,
[CFG.endpointDepth, 0.018, CFG.plankDepth - 0.02],
[-CFG.plankLength / 2 + CFG.endpointDepth / 2, 1.635, 0],
leftPadMaterial,
{ cast: false, receive: false }
);
const rightPad = box(
group,
[CFG.endpointDepth, 0.018, CFG.plankDepth - 0.02],
[CFG.plankLength / 2 - CFG.endpointDepth / 2, 1.635, 0],
rightPadMaterial,
{ cast: false, receive: false }
);
state.planks.push({
id: `T${i + 1}`,
x: centers[i],
group,
mesh,
leftPad,
rightPad
});
state.routeSurfaces.push(mesh);
}
const ribbonMaterial = new THREE.MeshBasicMaterial({
color: 0xf1b348,
transparent: true,
opacity: 0.72,
depthWrite: false
});
const pathRibbon = new THREE.Group();
for (const x of centers) {
box(
pathRibbon,
[3.94, 0.022, 0.055],
[x, 2.023, 0.715],
ribbonMaterial,
{ cast: false, receive: false }
);
}
scene.add(pathRibbon);
state.pathRibbon = pathRibbon;
createTargetMarkers();
createPiers();
createDimensionGuide();
}
function createTargetMarkers() {
const targets = [-6, -2, 2, 6];
for (let i = 0; i < targets.length; i++) {
const group = new THREE.Group();
group.position.x = targets[i];
scene.add(group);
const padMaterial = new THREE.MeshBasicMaterial({
color: 0xf4b64e,
transparent: true,
opacity: 0.15,
side: THREE.DoubleSide,
depthWrite: false
});
const pad = new THREE.Mesh(new THREE.PlaneGeometry(1.55, 1.75), padMaterial);
pad.rotation.x = -Math.PI / 2;
pad.position.y = -0.47;
group.add(pad);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0xffc85f,
transparent: true,
opacity: 0.52
});
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1.2, 0.25, 1.4)),
edgeMaterial
);
edges.position.y = 1.525;
group.add(edges);
box(
group,
[0.12, 0.12, 0.12],
[0, 1.55, 0.82],
new THREE.MeshStandardMaterial({
color: 0xf5bb52,
emissive: 0x8a4a08,
emissiveIntensity: 0.35
}),
{ cast: false }
);
const label = makeLabel(`J${i + 1}`, "#765126", "#fff5dd", [0.48, 0.24]);
label.position.set(0, 0.16, -1.25);
group.add(label);
state.targetMarkers.push({ group, padMaterial, edgeMaterial });
}
}
function createPiers() {
const targets = [-6, -2, 2, 6];
for (let i = 0; i < targets.length; i++) {
const group = new THREE.Group();
scene.add(group);
box(group, [1.25, 0.45, 1.45], [0, -0.275, 0], materials.pierDark);
box(group, [1.05, 0.35, 1.25], [0, 0.125, 0], materials.pierBody);
box(group, [0.92, 0.45, 1.08], [0, 0.525, 0], materials.pierDark);
box(group, [0.82, 0.40, 0.98], [0, 0.95, 0], materials.pierBody);
box(group, [0.96, 0.30, 1.12], [0, 1.30, 0], materials.pierDark);
const capMaterial = materials.cap.clone();
const cap = box(group, [1.2, 0.25, 1.4], [0, 1.525, 0], capMaterial);
const indicatorMaterial = new THREE.MeshStandardMaterial({
color: 0x99a5a4,
roughness: 0.65,
emissive: 0x000000,
emissiveIntensity: 0.35
});
const indicator = box(
group,
[0.30, 0.10, 0.05],
[0, 1.52, 0.72],
indicatorMaterial,
{ cast: false }
);
const outlineMaterial = new THREE.LineBasicMaterial({
color: 0xffd16d,
transparent: true,
opacity: 0.9,
depthTest: false
});
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1.29, 0.29, 1.49)),
outlineMaterial
);
outline.position.y = 1.525;
outline.visible = false;
outline.renderOrder = 12;
group.add(outline);
const label = makeLabel(`A${i + 1}`, "#365e60", "#fff5df", [0.72, 0.31]);
label.position.set(0, 0.72, 0.78);
group.add(label);
cap.userData.pierIndex = i;
const pier = {
id: `A${i + 1}`,
kind: "pier",
targetX: targets[i],
x: INITIAL_PIERS[i].x,
z: INITIAL_PIERS[i].z,
group,
cap,
mesh: cap,
indicator,
outline
};
state.piers.push(pier);
setPierPosition(pier, pier.x, pier.z);
}
}
function createDimensionGuide() {
for (let i = 0; i < 20; i++) {
box(
scene,
[0.86, 0.035, 0.055],
[-9.5 + i, -0.31, 3.72],
materials.foam,
{ cast: false }
);
}
for (const x of [-10, -6, -2, 2, 6, 10]) {
box(scene, [0.055, 0.16, 0.55], [x, -0.27, 3.72], materials.foam, { cast: false });
}
const label = makeLabel("20 m · 5 × 4 m", "#285b5d", "#f8f0d8", [2.35, 0.55]);
label.position.set(0, -0.10, 4.10);
scene.add(label);
}
function setPierPosition(pier, x, z) {
pier.x = x;
pier.z = z;
pier.group.position.set(x, 0, z);
}
function updateAllPierTransforms() {
for (const pier of state.piers) setPierPosition(pier, pier.x, pier.z);
}
// ---------- Actual X/Z geometry helpers ----------
function worldBox(mesh) {
if (!mesh.geometry.boundingBox) mesh.geometry.computeBoundingBox();
return mesh.geometry.boundingBox.clone().applyMatrix4(mesh.matrixWorld);
}
function rectanglePolygon(minX, maxX, minZ, maxZ) {
return [
{ x: minX, z: minZ },
{ x: maxX, z: minZ },
{ x: maxX, z: maxZ },
{ x: minX, z: maxZ }
];
}
function footprintPolygonXZ(mesh) {
const bounds = worldBox(mesh);
return rectanglePolygon(bounds.min.x, bounds.max.x, bounds.min.z, bounds.max.z);
}
function signedAreaXZ(polygon) {
let area = 0;
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
area += a.x * b.z - b.x * a.z;
}
return area * 0.5;
}
function polygonAreaXZ(polygon) {
return polygon.length < 3 ? 0 : Math.abs(signedAreaXZ(polygon));
}
function orientCCW(polygon) {
const copy = polygon.map(p => ({ x: p.x, z: p.z }));
return signedAreaXZ(copy) < 0 ? copy.reverse() : copy;
}
function crossXZ(a, b, p) {
return (b.x - a.x) * (p.z - a.z) - (b.z - a.z) * (p.x - a.x);
}
function lineIntersectionXZ(a, b, c, d) {
const rx = b.x - a.x;
const rz = b.z - a.z;
const sx = d.x - c.x;
const sz = d.z - c.z;
const denominator = rx * sz - rz * sx;
if (Math.abs(denominator) < 1e-10) return { x: b.x, z: b.z };
const qx = c.x - a.x;
const qz = c.z - a.z;
const t = (qx * sz - qz * sx) / denominator;
return { x: a.x + t * rx, z: a.z + t * rz };
}
function deduplicatePolygon(polygon) {
const result = [];
for (const point of polygon) {
const previous = result[result.length - 1];
if (!previous || Math.hypot(point.x - previous.x, point.z - previous.z) > 1e-7) {
result.push({ x: point.x, z: point.z });
}
}
if (
result.length > 2 &&
Math.hypot(result[0].x - result[result.length - 1].x,
result[0].z - result[result.length - 1].z) < 1e-7
) {
result.pop();
}
return result;
}
function intersectPolygonsXZ(subject, clipper) {
let output = orientCCW(subject);
const clip = orientCCW(clipper);
for (let i = 0; i < clip.length && output.length; i++) {
const a = clip[i];
const b = clip[(i + 1) % clip.length];
const input = output;
output = [];
for (let j = 0; j < input.length; j++) {
const start = input[j];
const end = input[(j + 1) % input.length];
const startDistance = crossXZ(a, b, start);
const endDistance = crossXZ(a, b, end);
const startInside = startDistance >= -1e-9;
const endInside = endDistance >= -1e-9;
if (startInside !== endInside) {
output.push(lineIntersectionXZ(start, end, a, b));
}
if (endInside) output.push(end);
}
output = deduplicatePolygon(output);
}
return output;
}
function polygonBoundsXZ(polygon) {
if (!polygon.length) return null;
let minX = Infinity;
let maxX = -Infinity;
let minZ = Infinity;
let maxZ = -Infinity;
for (const point of polygon) {
minX = Math.min(minX, point.x);
maxX = Math.max(maxX, point.x);
minZ = Math.min(minZ, point.z);
maxZ = Math.max(maxZ, point.z);
}
return { minX, maxX, minZ, maxZ };
}
function endpointZone(plank, end) {
const bounds = worldBox(plank.mesh);
const depth = Math.min(CFG.endpointDepth, (bounds.max.x - bounds.min.x) * 0.2);
if (end === "left") {
return rectanglePolygon(
bounds.min.x,
bounds.min.x + depth,
bounds.min.z,
bounds.max.z
);
}
return rectanglePolygon(
bounds.max.x - depth,
bounds.max.x,
bounds.min.z,
bounds.max.z
);
}
function evaluateZoneAgainstSupport(zone, support, plankBottomY) {
const supportBounds = worldBox(support.mesh);
const verticalGap = Math.abs(supportBounds.max.y - plankBottomY);
if (verticalGap > CFG.contactTolerance) {
return { valid: false, area: 0, width: 0, bearing: 0, verticalGap };
}
const supportPolygon = footprintPolygonXZ(support.mesh);
const intersection = intersectPolygonsXZ(zone, supportPolygon);
const area = polygonAreaXZ(intersection);
const bounds = polygonBoundsXZ(intersection);
const width = bounds ? bounds.maxZ - bounds.minZ : 0;
const bearing = bounds ? bounds.maxX - bounds.minX : 0;
return {
valid:
area >= CFG.minArea &&
width >= CFG.minWidth &&
bearing >= CFG.minBearing,
area,
width,
bearing,
verticalGap,
support
};
}
function evaluateEndpoint(plank, end, supports) {
const zone = endpointZone(plank, end);
const bounds = worldBox(plank.mesh);
const candidates = supports.map(support =>
evaluateZoneAgainstSupport(zone, support, bounds.min.y)
);
const valid = candidates
.filter(candidate => candidate.valid)
.sort((a, b) => b.area - a.area);
return {
end,
valid: valid.length > 0,
best: valid[0] || null
};
}
function evaluateJoint(jointIndex) {
const left = state.planks[jointIndex];
const right = state.planks[jointIndex + 1];
const leftZone = endpointZone(left, "right");
const rightZone = endpointZone(right, "left");
const leftBottom = worldBox(left.mesh).min.y;
const rightBottom = worldBox(right.mesh).min.y;
for (const pier of state.piers) {
const leftContact = evaluateZoneAgainstSupport(leftZone, pier, leftBottom);
const rightContact = evaluateZoneAgainstSupport(rightZone, pier, rightBottom);
if (leftContact.valid && rightContact.valid) {
return { valid: true, support: pier };
}
}
return { valid: false, support: null };
}
function mergeIntervals(intervals) {
const sorted = intervals
.map(interval => ({ ...interval }))
.sort((a, b) => a.min - b.min);
const merged = [];
for (const interval of sorted) {
const last = merged[merged.length - 1];
if (!last || interval.min > last.max + 1e-8) {
merged.push({ ...interval });
} else {
last.max = Math.max(last.max, interval.max);
}
}
return merged;
}
function componentContainingZero(intervals) {
const merged = mergeIntervals(intervals);
return merged.find(interval => interval.min <= 0 && interval.max >= 0) || null;
}
function analyzeContinuousPath() {
const surfaces = state.routeSurfaces.map(mesh => ({
mesh,
bounds: worldBox(mesh)
}));
const boundaryValues = [];
for (const surface of surfaces) {
boundaryValues.push(surface.bounds.min.x, surface.bounds.max.x);
}
boundaryValues.sort((a, b) => a - b);
const boundaries = [];
for (const value of boundaryValues) {
if (!boundaries.length || Math.abs(value - boundaries[boundaries.length - 1]) > 1e-4) {
boundaries.push(value);
}
}
let minimumWidth = Infinity;
let gaps = 0;
for (let i = 0; i < boundaries.length - 1; i++) {
const midpoint = (boundaries[i] + boundaries[i + 1]) * 0.5;
const active = surfaces.filter(surface =>
surface.bounds.min.x <= midpoint + 1e-6 &&
surface.bounds.max.x >= midpoint - 1e-6
);
const component = componentContainingZero(active.map(surface => ({
min: surface.bounds.min.z,
max: surface.bounds.max.z
})));
if (!component) {
gaps++;
} else {
minimumWidth = Math.min(minimumWidth, component.max - component.min);
}
}
let disconnectedBoundaries = 0;
for (let i = 1; i < boundaries.length - 1; i++) {
const boundary = boundaries[i];
const leftSurfaces = surfaces.filter(surface =>
Math.abs(surface.bounds.max.x - boundary) < 2e-3
);
const rightSurfaces = surfaces.filter(surface =>
Math.abs(surface.bounds.min.x - boundary) < 2e-3
);
let connected = false;
for (const left of leftSurfaces) {
for (const right of rightSurfaces) {
const zOverlap = Math.min(left.bounds.max.z, right.bounds.max.z) -
Math.max(left.bounds.min.z, right.bounds.min.z);
const step = Math.abs(left.bounds.max.y - right.bounds.max.y);
if (zOverlap > 1e-4 && step <= CFG.pathStepTolerance) {
connected = true;
}
}
}
if (!connected) disconnectedBoundaries++;
}
return {
continuous: gaps === 0 && disconnectedBoundaries === 0,
width: Number.isFinite(minimumWidth) ? minimumWidth : 0,
gaps,
disconnectedBoundaries
};
}
function validateGeometry(options = {}) {
scene.updateMatrixWorld(true);
const supports = [...state.banks, ...state.piers];
const plankResults = state.planks.map(plank => {
const left = evaluateEndpoint(plank, "left", supports);
const right = evaluateEndpoint(plank, "right", supports);
return {
id: plank.id,
endpoints: { left, right },
secured: left.valid && right.valid
};
});
const contacts = plankResults.filter(result => result.secured).length;
const jointResults = state.planks.slice(0, -1).map((_, index) => evaluateJoint(index));
const joints = jointResults.filter(result => result.valid).length;
const path = analyzeContinuousPath();
const requiredWidths = [];
for (const result of plankResults) {
requiredWidths.push(result.endpoints.left.valid ? result.endpoints.left.best.width : 0);
requiredWidths.push(result.endpoints.right.valid ? result.endpoints.right.best.width : 0);
}
const minimumContactWidth = Math.min(...requiredWidths);
const structuralContactOK = contacts === state.planks.length && joints === state.planks.length - 1;
const usableWidth = structuralContactOK
? Math.min(minimumContactWidth, path.width)
: 0;
const result = {
contacts,
joints,
plankResults,
jointResults,
path,
minimumContactWidth,
usableWidth,
validStations: requiredWidths.filter(width => width > 0).length,
pass:
structuralContactOK &&
path.continuous &&
usableWidth > 0
};
if (!options.quiet) applyValidation(result);
return result;
}
function formatMeters(value) {
return value.toLocaleString("pt-BR", {
minimumFractionDigits: 2,
maximumFractionDigits: 2
}) + " m";
}
function applyValidation(result) {
metricContacts.textContent = `${result.contacts}/5`;
metricWidth.textContent = formatMeters(result.usableWidth);
metricPath.textContent = result.path.continuous ? "CONTÍNUO" : "INTERROMPIDO";
jointText.textContent = `${result.joints}/4 juntas`;
statusCard.dataset.state = result.pass ? "good" : "bad";
statusTitle.textContent = result.pass
? "PONTE GEOMETRICAMENTE VERIFICADA"
: "AJUSTE OS APOIOS";
for (let i = 0; i < contactPips.length; i++) {
contactPips[i].classList.toggle("ok", result.plankResults[i].secured);
}
for (let i = 0; i < jointPips.length; i++) {
jointPips[i].classList.toggle("ok", result.jointResults[i].valid);
}
for (const plank of state.planks) {
const plankResult = result.plankResults.find(item => item.id === plank.id);
for (const [end, pad] of [
["left", plank.leftPad],
["right", plank.rightPad]
]) {
const valid = plankResult.endpoints[end].valid;
pad.material.color.setHex(valid ? 0x35b77d : 0xe26356);
pad.material.opacity = valid ? 0.64 : 0.36;
}
}
const validSupportIds = new Set();
for (const plankResult of result.plankResults) {
for (const endpoint of Object.values(plankResult.endpoints)) {
if (endpoint.best) validSupportIds.add(endpoint.best.support.id);
}
}
for (const joint of result.jointResults) {
if (joint.support) validSupportIds.add(joint.support.id);
}
for (const support of [...state.banks, ...state.piers]) {
const valid = validSupportIds.has(support.id);
support.indicator.material.color.setHex(valid ? 0x43c58a : 0xe06457);
support.indicator.material.emissive.setHex(valid ? 0x0b4b31 : 0x4a100c);
support.indicator.material.emissiveIntensity = 0.42;
}
state.pathRibbon.visible = result.path.continuous;
state.pathRibbon.children.forEach(child => {
child.material.color.setHex(result.pass ? 0x32b77c : 0xf0ad3d);
});
if (result.pass) {
validationText.textContent =
"5 pranchas com contato nas duas pontas, 4 juntas apoiadas e corredor X–Z contínuo.";
} else {
const missing = 10 - result.validStations;
const missingJoints = 4 - result.joints;
validationText.textContent =
`${missing} zonas de apoio sem contato e ${missingJoints} juntas sem apoio duplo. ` +
"A validação usa interseção real X–Z, não x/y, e não simula ruptura.";
}
}
// ---------- Built-in tests against the actual meshes ----------
function runGeometryTests(announce = true) {
const saved = state.piers.map(pier => ({ x: pier.x, z: pier.z }));
const tests = [];
const setSolution = () => {
for (const pier of state.piers) setPierPosition(pier, pier.targetX, 0);
};
setSolution();
const solution = validateGeometry({ quiet: true });
tests.push({
name: "Solução revelada",
pass:
solution.contacts === 5 &&
solution.joints === 4 &&
solution.usableWidth >= 1.39 &&
solution.path.continuous,
detail:
`${solution.contacts}/5 contatos · ${formatMeters(solution.usableWidth)} · ` +
`${solution.path.continuous ? "caminho contínuo" : "caminho interrompido"}`
});
const actualPlankPolygon = footprintPolygonXZ(state.planks[0].mesh);
const actualSupportPolygon = footprintPolygonXZ(state.piers[0].cap);
const actualIntersection = intersectPolygonsXZ(actualPlankPolygon, actualSupportPolygon);
const actualBounds = polygonBoundsXZ(actualIntersection);
const actualArea = polygonAreaXZ(actualIntersection);
const actualWidth = actualBounds ? actualBounds.maxZ - actualBounds.minZ : 0;
const coordinatesAreXZ = actualIntersection.length >= 3 && actualIntersection.every(point =>
Number.isFinite(point.x) &&
Number.isFinite(point.z) &&
point.y === undefined
);
tests.push({
name: "Eixos X/Z da cena",
pass: coordinatesAreXZ && actualArea > 0.2 && actualWidth > 1.39,
detail:
`interseção real = ${actualArea.toFixed(2)} m² · ` +
`largura Z = ${formatMeters(actualWidth)}`
});
setSolution();
setPierPosition(state.piers[0], state.piers[0].targetX + 1.25, 0);
const displaced = validateGeometry({ quiet: true });
tests.push({
name: "Desalinhamento em X",
pass: displaced.contacts < 5,
detail: `${displaced.contacts}/5 contatos após mover A1 para fora da junta`
});
setSolution();
setPierPosition(state.piers[0], state.piers[0].targetX, 1.1);
const lateral = validateGeometry({ quiet: true });
tests.push({
name: "Desalinhamento em Z",
pass: lateral.contacts < 5 || lateral.usableWidth < 1.39,
detail: `${lateral.contacts}/5 contatos · largura útil ${formatMeters(lateral.usableWidth)}`
});
for (let i = 0; i < state.piers.length; i++) {
setPierPosition(state.piers[i], saved[i].x, saved[i].z);
}
validateGeometry();
renderTests(tests);
if (announce) {
const passed = tests.filter(test => test.pass).length;
toast(
passed === tests.length
? `${passed}/${tests.length} testes geométricos passaram sobre a cena real.`
: `${passed}/${tests.length} testes passaram; revise a geometria.`,
passed === tests.length ? "good" : "bad"
);
}
return tests;
}
function renderTests(tests) {
testList.replaceChildren();
let passed = 0;
for (const test of tests) {
if (test.pass) passed++;
const item = document.createElement("li");
item.className = `test-item ${test.pass ? "pass" : "fail"}`;
const dot = document.createElement("span");
dot.className = "test-dot";
const name = document.createElement("span");
name.textContent = test.name;
const verdict = document.createElement("strong");
verdict.textContent = test.pass ? "OK" : "FALHOU";
const detail = document.createElement("span");
detail.className = "test-detail";
detail.textContent = test.detail;
item.append(dot, name, verdict, detail);
testList.append(item);
}
testButton.textContent = `Testes XZ ${passed}/${tests.length}`;
testButton.setAttribute("aria-expanded", String(!testPanel.hidden));
}
// ---------- Interaction ----------
function toast(message, kind = "") {
clearTimeout(toastTimer);
toastElement.textContent = message;
toastElement.className = `toast show ${kind}`;
toastTimer = setTimeout(() => {
toastElement.className = "toast";
}, 2800);
}
function selectPier(index) {
state.selectedPier = index;
state.piers.forEach((pier, pierIndex) => {
pier.outline.visible = pierIndex === index;
});
updateSelectionReadout();
}
function updateSelectionReadout() {
const pier = state.piers[state.selectedPier];
const x = pier.x.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const z = pier.z.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
selectionText.textContent = `${pier.id} selecionado · X ${x} m · Z ${z} m`;
}
function snap(value, step = 0.25) {
return Math.round(value / step) * step;
}
function setPointerFromEvent(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function pickPier() {
const hits = raycaster.intersectObjects(state.piers.map(pier => pier.cap), false);
return hits.length ? hits[0].object.userData.pierIndex : null;
}
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
event.preventDefault();
setPointerFromEvent(event);
const pierIndex = pickPier();
lastPointer = { x: event.clientX, y: event.clientY };
if (pierIndex !== null) {
selectPier(pierIndex);
const point = new THREE.Vector3();
if (raycaster.ray.intersectPlane(dragPlane, point)) {
const pier = state.piers[pierIndex];
dragOffset.set(pier.x - point.x, pier.z - point.z);
dragMode = "pier";
canvas.style.cursor = "grabbing";
}
} else {
dragMode = "camera";
cameraTouched = true;
canvas.style.cursor = "grabbing";
}
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
setPointerFromEvent(event);
if (dragMode === "pier") {
const point = new THREE.Vector3();
if (raycaster.ray.intersectPlane(dragPlane, point)) {
const pier = state.piers[state.selectedPier];
const x = THREE.MathUtils.clamp(snap(point.x + dragOffset.x), -9, 9);
const z = THREE.MathUtils.clamp(snap(point.z + dragOffset.y), -1.75, 1.75);
setPierPosition(pier, x, z);
updateSelectionReadout();
validateGeometry();
}
} else if (dragMode === "camera") {
const dx = event.clientX - lastPointer.x;
const dy = event.clientY - lastPointer.y;
cameraRig.azimuth -= dx * 0.006;
cameraRig.polar = THREE.MathUtils.clamp(cameraRig.polar - dy * 0.005, 0.08, 1.38);
cameraTouched = true;
lastPointer = { x: event.clientX, y: event.clientY };
} else {
canvas.style.cursor = pickPier() !== null ? "grab" : "default";
}
});
function endPointer(event) {
if (dragMode === "pier") validateGeometry();
dragMode = null;
canvas.style.cursor = "default";
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraRig.radius = THREE.MathUtils.clamp(
cameraRig.radius * Math.exp(event.deltaY * 0.001),
12,
92
);
cameraTouched = true;
}, { passive: false });
window.addEventListener("keydown", event => {
if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return;
if (event.target instanceof HTMLButtonElement) return;
event.preventDefault();
const step = event.shiftKey ? 0.5 : 0.25;
const pier = state.piers[state.selectedPier];
let x = pier.x;
let z = pier.z;
if (event.key === "ArrowLeft") x -= step;
if (event.key === "ArrowRight") x += step;
if (event.key === "ArrowUp") z -= step;
if (event.key === "ArrowDown") z += step;
setPierPosition(
pier,
THREE.MathUtils.clamp(snap(x), -9, 9),
THREE.MathUtils.clamp(snap(z), -1.75, 1.75)
);
updateSelectionReadout();
validateGeometry();
});
document.getElementById("checkBtn").addEventListener("click", () => {
const result = validateGeometry();
toast(
result.pass
? `Validação aprovada: ${result.contacts}/5 contatos e ${formatMeters(result.usableWidth)}.`
: `Faltam apoios: ${result.contacts}/5 pranchas em contato.`,
result.pass ? "good" : "bad"
);
});
document.getElementById("solutionBtn").addEventListener("click", () => {
for (const pier of state.piers) setPierPosition(pier, pier.targetX, 0);
updateAllPierTransforms();
updateSelectionReadout();
// Tests and validation use the current, already revealed mesh positions.
runGeometryTests(false);
const result = validateGeometry();
toast(
result.pass
? `Solução revelada e validada: 5/5 contatos, ${formatMeters(result.usableWidth)}, caminho contínuo.`
: "A solução foi posicionada, mas a geometria precisa de revisão.",
result.pass ? "good" : "bad"
);
});
document.getElementById("resetBtn").addEventListener("click", () => {
state.piers.forEach((pier, index) => {
setPierPosition(pier, INITIAL_PIERS[index].x, INITIAL_PIERS[index].z);
});
updateSelectionReadout();
const result = validateGeometry();
toast(
`Apoios embaralhados. Estado atual: ${result.contacts}/5 contatos.`,
"bad"
);
});
document.getElementById("viewBtn").addEventListener("click", () => {
topView = !topView;
cameraTouched = true;
if (topView) {
cameraRig.azimuth = 0;
cameraRig.polar = 0.08;
cameraRig.radius = fitCameraDistance() * 1.03;
document.getElementById("viewBtn").textContent = "Vista em perspectiva";
} else {
cameraRig.azimuth = 0.58;
cameraRig.polar = 1.02;
cameraRig.radius = fitCameraDistance();
document.getElementById("viewBtn").textContent = "Vista de topo";
}
});
testButton.addEventListener("click", () => {
runGeometryTests(true);
testPanel.hidden = !testPanel.hidden;
testButton.setAttribute("aria-expanded", String(!testPanel.hidden));
});
// ---------- Camera and resize ----------
function fitCameraDistance() {
const aspect = innerWidth / innerHeight;
const halfVerticalFov = THREE.MathUtils.degToRad(camera.fov * 0.5);
return THREE.MathUtils.clamp(
31.5 / (2 * Math.tan(halfVerticalFov) * aspect) * 1.08,
24,
92
);
}
function updateCamera() {
const sinPolar = Math.sin(cameraRig.polar);
camera.position.set(
cameraRig.target.x + cameraRig.radius * sinPolar * Math.sin(cameraRig.azimuth),
cameraRig.target.y + cameraRig.radius * Math.cos(cameraRig.polar),
cameraRig.target.z + cameraRig.radius * sinPolar * Math.cos(cameraRig.azimuth)
);
camera.lookAt(cameraRig.target);
}
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight, false);
if (!cameraTouched) cameraRig.radius = fitCameraDistance();
updateCamera();
});
function animate(now) {
requestAnimationFrame(animate);
const pulse = 0.5 + 0.5 * Math.sin(now * 0.0032);
for (const marker of state.targetMarkers) {
marker.padMaterial.opacity = 0.12 + pulse * 0.09;
marker.edgeMaterial.opacity = 0.38 + pulse * 0.28;
}
for (const pier of state.piers) {
if (pier.outline.visible) {
pier.outline.material.opacity = 0.72 + pulse * 0.24;
}
}
updateCamera();
renderer.render(scene, camera);
}
addLights();
buildWorld();
buildBridge();
selectPier(0);
cameraRig.radius = fitCameraDistance();
updateCamera();
validateGeometry();
runGeometryTests(false);
requestAnimationFrame(animate);
</script>
</body>
</html>
```